]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/rss.rb
* (plugins/rss) more item uid calculation fixes
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / rss.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: RSS feed plugin for rbot
5 #
6 # Author:: Stanislav Karchebny <berkus@madfire.net>
7 # Author:: Ian Monroe <ian@monroe.nu>
8 # Author:: Mark Kretschmann <markey@web.de>
9 # Author:: Giuseppe Bilotta <giuseppe.bilotta@gmail.com>
10 #
11 # Copyright:: (C) 2004 Stanislav Karchebny
12 # Copyright:: (C) 2005 Ian Monroe, Mark Kretschmann
13 # Copyright:: (C) 2006-2007 Giuseppe Bilotta
14 #
15 # License:: MIT license
16
17 require 'rss'
18
19 # Try to load rss/content/2.0 so we can access the data in <content:encoded> 
20 # tags.
21 begin
22   require 'rss/content/2.0'
23 rescue LoadError
24 end
25
26 module ::RSS
27
28   # Add support for Slashdot namespace in RDF. The code is just an adaptation
29   # of the DublinCore code.
30   unless defined?(SLASH_PREFIX)
31     SLASH_PREFIX = 'slash'
32     SLASH_URI = "http://purl.org/rss/1.0/modules/slash/"
33
34     RDF.install_ns(SLASH_PREFIX, SLASH_URI)
35
36     module BaseSlashModel
37       def append_features(klass)
38         super
39
40         return if klass.instance_of?(Module)
41         SlashModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
42           plural = plural_name || "#{name}s"
43           full_name = "#{SLASH_PREFIX}_#{name}"
44           full_plural_name = "#{SLASH_PREFIX}_#{plural}"
45           klass_name = "Slash#{Utils.to_class_name(name)}"
46
47           # This will fail with older version of the Ruby RSS module
48           begin
49             klass.install_have_children_element(name, SLASH_URI, "*",
50                                                 full_name, full_plural_name)
51             klass.install_must_call_validator(SLASH_PREFIX, SLASH_URI)
52           rescue ArgumentError
53             klass.module_eval("install_have_children_element(#{full_name.dump}, #{full_plural_name.dump})")
54           end
55
56           klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0))
57           remove_method :#{full_name}     if method_defined? :#{full_name}
58           remove_method :#{full_name}=    if method_defined? :#{full_name}=
59           remove_method :set_#{full_name} if method_defined? :set_#{full_name}
60
61           def #{full_name}
62             @#{full_name}.first and @#{full_name}.first.value
63           end
64
65           def #{full_name}=(new_value)
66             @#{full_name}[0] = Utils.new_with_value_if_need(#{klass_name}, new_value)
67           end
68           alias set_#{full_name} #{full_name}=
69         EOC
70         end
71       end
72     end
73
74     module SlashModel
75       extend BaseModel
76       extend BaseSlashModel
77
78       TEXT_ELEMENTS = {
79       "department" => nil,
80       "section" => nil,
81       "comments" =>  nil,
82       "hit_parade" => nil
83       }
84
85       ELEMENT_NAME_INFOS = SlashModel::TEXT_ELEMENTS.to_a
86
87       ELEMENTS = TEXT_ELEMENTS.keys
88
89       ELEMENTS.each do |name, plural_name|
90         module_eval(<<-EOC, *get_file_and_line_from_caller(0))
91         class Slash#{Utils.to_class_name(name)} < Element
92           include RSS10
93
94           content_setup
95
96           class << self
97             def required_prefix
98               SLASH_PREFIX
99             end
100
101             def required_uri
102               SLASH_URI
103             end
104           end
105
106           @tag_name = #{name.dump}
107
108           alias_method(:value, :content)
109           alias_method(:value=, :content=)
110
111           def initialize(*args)
112             begin
113               if Utils.element_initialize_arguments?(args)
114                 super
115               else
116                 super()
117                 self.content = args[0]
118               end
119             # Older Ruby RSS module
120             rescue NoMethodError
121               super()
122               self.content = args[0]
123             end
124           end
125
126           def full_name
127             tag_name_with_prefix(SLASH_PREFIX)
128           end
129
130           def maker_target(target)
131             target.new_#{name}
132           end
133
134           def setup_maker_attributes(#{name})
135             #{name}.content = content
136           end
137         end
138       EOC
139       end
140     end
141
142     class RDF
143       class Item; include SlashModel; end
144     end
145
146     SlashModel::ELEMENTS.each do |name|
147       class_name = Utils.to_class_name(name)
148       BaseListener.install_class_name(SLASH_URI, name, "Slash#{class_name}")
149     end
150
151     SlashModel::ELEMENTS.collect! {|name| "#{SLASH_PREFIX}_#{name}"}
152   end
153 end
154
155
156 class ::RssBlob
157   attr_accessor :url, :handle, :type, :refresh_rate, :xml, :title, :items,
158     :mutex, :watchers, :last_fetched
159
160   def initialize(url,handle=nil,type=nil,watchers=[], xml=nil, lf = nil)
161     @url = url
162     if handle
163       @handle = handle
164     else
165       @handle = url
166     end
167     @type = type
168     @watchers=[]
169     @refresh_rate = nil
170     @xml = xml
171     @title = nil
172     @items = nil
173     @mutex = Mutex.new
174     @last_fetched = lf
175     sanitize_watchers(watchers)
176   end
177
178   def dup
179     @mutex.synchronize do
180       self.class.new(@url,
181                      @handle,
182                      @type ? @type.dup : nil,
183                      @watchers.dup,
184                      @xml ? @xml.dup : nil,
185                      @last_fetched)
186     end
187   end
188
189   # Downcase all watchers, possibly turning them into Strings if they weren't
190   def sanitize_watchers(list=@watchers)
191     ls = list.dup
192     @watchers.clear
193     ls.each { |w|
194       add_watch(w)
195     }
196   end
197
198   def watched?
199     !@watchers.empty?
200   end
201
202   def watched_by?(who)
203     @watchers.include?(who.downcase)
204   end
205
206   def add_watch(who)
207     if watched_by?(who)
208       return nil
209     end
210     @mutex.synchronize do
211       @watchers << who.downcase
212     end
213     return who
214   end
215
216   def rm_watch(who)
217     @mutex.synchronize do
218       @watchers.delete(who.downcase)
219     end
220   end
221
222   def to_a
223     [@handle,@url,@type,@refresh_rate,@watchers]
224   end
225
226   def to_s(watchers=false)
227     if watchers
228       a = self.to_a.flatten
229     else
230       a = self.to_a[0,3]
231     end
232     a.compact.join(" | ")
233   end
234 end
235
236 class RSSFeedsPlugin < Plugin
237   Config.register Config::IntegerValue.new('rss.head_max',
238     :default => 100, :validate => Proc.new{|v| v > 0 && v < 200},
239     :desc => "How many characters to use of a RSS item header")
240
241   Config.register Config::IntegerValue.new('rss.text_max',
242     :default => 200, :validate => Proc.new{|v| v > 0 && v < 400},
243     :desc => "How many characters to use of a RSS item text")
244
245   Config.register Config::IntegerValue.new('rss.thread_sleep',
246     :default => 300, :validate => Proc.new{|v| v > 30},
247     :desc => "How many seconds to sleep before checking RSS feeds again")
248
249   Config.register Config::BooleanValue.new('rss.show_updated',
250     :default => true,
251     :desc => "Whether feed items for which the description was changed should be shown as new")
252
253   Config.register Config::BooleanValue.new('rss.show_links',
254     :default => true,
255     :desc => "Whether to display links from the text of a feed item.")
256
257   # Make an  'unique' ID for a given item, based on appropriate bot options
258   # Currently only suppored is bot.config['rss.show_updated']: when false,
259   # only the guid/link is accounted for.
260   
261   def block_rescue(df = nil, &block)
262     v = block.call rescue nil
263     (String === v && '' != v) ? v : nil
264   end
265
266   def make_uid(item)
267     uid = [
268       (block_rescue do item.guid.content end ||
269        block_rescue do item.guid end ||
270        block_rescue do item.link.href end ||
271        block_rescue do item.link end
272       )
273     ]
274     if @bot.config['rss.show_updated']
275       uid.push(
276         block_rescue do item.content.content end ||
277         block_rescue do item.description end
278       )
279       uid.unshift(
280         block_rescue do item.title.content end ||
281         block_rescue do item.title end
282       )
283     end
284     # debug "taking hash of #{uid.inspect}"
285     uid.hash
286   end
287
288
289   # We used to save the Mutex with the RssBlob, which was idiotic. And
290   # since Mutexes dumped in one version might not be resotrable in another,
291   # we need a few tricks to be able to restore data from other versions of Ruby
292   #
293   # When migrating 1.8.6 => 1.8.5, all we need to do is define an empty
294   # #marshal_load() method for Mutex. For 1.8.5 => 1.8.6 we need something
295   # dirtier, as seen later on in the initialization code.
296   unless Mutex.new.respond_to?(:marshal_load)
297     class ::Mutex
298       def marshal_load(str)
299         return
300       end
301     end
302   end
303
304   # Auxiliary method used to collect two lines for rss output filters,
305   # running substitutions against DataStream _s_ optionally joined
306   # with hash _h_
307   def make_stream(line1, line2, s, h={})
308     ss = s.merge(h)
309     DataStream.new([line1, line2].compact.join("\n") % ss, ss)
310   end
311
312   # Define default RSS filters
313   #
314   # TODO: load personal ones
315   def define_filters
316     @outkey = :"rss.out"
317     @bot.register_filter(:blog, @outkey) { |s|
318       author = s[:author] ? (s[:author] + " ") : ""
319       abt = s[:category] ? "about #{s[:category]} " : ""
320       line1 = "%{handle}%{date}%{author}blogged %{abt}at %{link}"
321       line2 = "%{handle}%{title} - %{desc}"
322       make_stream(line1, line2, s, :author => author, :abt => abt)
323     }
324     @bot.register_filter(:photoblog, @outkey) { |s|
325       author = s[:author] ? (s[:author] + " ") : ""
326       abt = s[:category] ? "under #{s[:category]} " : ""
327       line1 = "%{handle}%{date}%{author}added an image %{abt}at %{link}"
328       line2 = "%{handle}%{title} - %{desc}"
329       make_stream(line1, line2, s, :author => author, :abt => abt)
330     }
331     @bot.register_filter(:news, @outkey) { |s|
332       line1 = "%{handle}%{date}%{title} @ %{link}" % s
333       line2 = "%{handle}%{date}%{desc}" % s
334       make_stream(line1, line2, s)
335     }
336     @bot.register_filter(:git, @outkey) { |s|
337       author = s[:author] ? (s[:author] + " ") : ""
338       line1 = "%{handle}%{date}%{author}committed %{title} @ %{link}"
339       make_stream(line1, nil, s, :author => author)
340     }
341     @bot.register_filter(:forum, @outkey) { |s|
342       line1 = "%{handle}%{date}%{title}%{at}%{link}"
343       make_stream(line1, nil, s)
344     }
345     @bot.register_filter(:wiki, @outkey) { |s|
346       line1 = "%{handle}%{date}%{title}%{at}%{link}"
347       line1 << "has been edited by %{author}. %{desc}"
348       make_stream(line1, nil, s)
349     }
350     @bot.register_filter(:gmane, @outkey) { |s|
351       line1 = "%{handle}%{date}Message %{title} sent by %{author}. %{desc}"
352       make_stream(line1, nil, s)
353     }
354     @bot.register_filter(:trac, @outkey) { |s|
355       author = s[:author].sub(/@\S+?\s*>/, "@...>") + ": " if s[:author]
356       line1 = "%{handle}%{date}%{author}%{title} @ %{link}"
357       line2 = nil
358       unless s[:item].title =~ /^(?:Changeset \[(?:[\da-f]+)\]|\(git commit\))/
359         line2 = "%{handle}%{date}%{desc}"
360       end
361       make_stream(line1, line2, s, :author => author)
362     }
363     @bot.register_filter(:"/.", @outkey) { |s|
364       dept = "(from the #{s[:item].slash_department} dept) " rescue nil
365       sec = " in section #{s[:item].slash_section}" rescue nil
366       line1 = "%{handle}%{date}%{dept}%{title}%{at}%{link} "
367       line1 << "(posted by %{author}%{sec})"
368       make_stream(line1, nil, s, :dept => dept, :sec => sec)
369     }
370     @bot.register_filter(:default, @outkey) { |s|
371       line1 = "%{handle}%{date}%{title}%{at}%{link}"
372       line1 << " (by %{author})" if s[:author]
373       make_stream(line1, nil, s)
374     }
375
376     # Define an HTML info filter too
377     @bot.register_filter(:rss, :htmlinfo) { |s| htmlinfo_filter(s) }
378
379     # This is the output format used by the input filter
380     @bot.register_filter(:htmlinfo, @outkey) { |s|
381       line1 = "%{title}%{at}%{link}"
382       make_stream(line1, nil, s)
383     }
384   end
385
386   FEED_NS = %r{xmlns.*http://(purl\.org/rss|www.w3c.org/1999/02/22-rdf)}
387   def htmlinfo_filter(s)
388     return nil unless s[:headers] and s[:headers]['x-rbot-location']
389     return nil unless s[:headers]['content-type'].first.match(/xml|rss|atom|rdf/i) or
390       (s[:text].include?("<rdf:RDF") and s[:text].include?("<channel")) or
391       s[:text].include?("<rss") or s[:text].include?("<feed") or
392       s[:text].match(FEED_NS)
393     blob = RssBlob.new(s[:headers]['x-rbot-location'],"", :htmlinfo)
394     unless (fetchRss(blob, nil) and parseRss(blob, nil) rescue nil)
395       debug "#{s.pretty_inspect} is not an RSS feed, despite the appearances"
396       return nil
397     end
398     output = []
399     blob.items.each { |it|
400       output << printFormattedRss(blob, it)[:text]
401     }
402     return {:title => blob.title, :content => output.join(" | ")}
403   end
404
405   # Display the known rss types
406   def rss_types(m, params)
407     ar = @bot.filter_names(@outkey)
408     ar.delete(:default)
409     m.reply ar.map { |k| k.to_s }.sort!.join(", ")
410   end
411
412   attr_reader :feeds
413
414   def initialize
415     super
416
417     define_filters
418
419     if @registry.has_key?(:feeds)
420       # When migrating from Ruby 1.8.5 to 1.8.6, dumped Mutexes may render the
421       # data unrestorable. If this happens, we patch the data, thus allowing
422       # the restore to work.
423       #
424       # This is actually pretty safe for a number of reasons:
425       # * the code is only called if standard marshalling fails
426       # * the string we look for is quite unlikely to appear randomly
427       # * if the string appears somewhere and the patched string isn't recoverable
428       #   either, we'll get another (unrecoverable) error, which makes the rss
429       #   plugin unsable, just like it was if no recovery was attempted
430       # * if the string appears somewhere and the patched string is recoverable,
431       #   we may get a b0rked feed, which is eventually overwritten by a clean
432       #   one, so the worst thing that can happen is that a feed update spams
433       #   the watchers once
434       @registry.recovery = Proc.new { |val|
435         patched = val.sub(":\v@mutexo:\nMutex", ":\v@mutexo:\vObject")
436         ret = Marshal.restore(patched)
437         ret.each_value { |blob|
438           blob.mutex = nil
439           blob
440         }
441       }
442
443       @feeds = @registry[:feeds]
444       raise unless @feeds
445
446       @registry.recovery = nil
447
448       @feeds.keys.grep(/[A-Z]/) { |k|
449         @feeds[k.downcase] = @feeds[k]
450         @feeds.delete(k)
451       }
452       @feeds.each { |k, f|
453         f.mutex = Mutex.new
454         f.sanitize_watchers
455         parseRss(f) if f.xml
456       }
457     else
458       @feeds = Hash.new
459     end
460     @watch = Hash.new
461     rewatch_rss
462   end
463
464   def name
465     "rss"
466   end
467
468   def watchlist
469     @feeds.select { |h, f| f.watched? }
470   end
471
472   def cleanup
473     stop_watches
474     super
475   end
476
477   def save
478     unparsed = Hash.new()
479     @feeds.each { |k, f|
480       unparsed[k] = f.dup
481       # we don't want to save the mutex
482       unparsed[k].mutex = nil
483     }
484     @registry[:feeds] = unparsed
485   end
486
487   def stop_watch(handle)
488     if @watch.has_key?(handle)
489       begin
490         debug "Stopping watch #{handle}"
491         @bot.timer.remove(@watch[handle])
492         @watch.delete(handle)
493       rescue Exception => e
494         report_problem("Failed to stop watch for #{handle}", e, nil)
495       end
496     end
497   end
498
499   def stop_watches
500     @watch.each_key { |k|
501       stop_watch(k)
502     }
503   end
504
505   def help(plugin,topic="")
506     case topic
507     when "show"
508       "rss show #{Bold}handle#{Bold} [#{Bold}limit#{Bold}] : show #{Bold}limit#{Bold} (default: 5, max: 15) entries from rss #{Bold}handle#{Bold}; #{Bold}limit#{Bold} can also be in the form a..b, to display a specific range of items"
509     when "list"
510       "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
511     when "watched"
512       "rss watched [#{Bold}handle#{Bold}] [in #{Bold}chan#{Bold}]: list all watched rss feeds (matching #{Bold}handle#{Bold}) (in channel #{Bold}chan#{Bold})"
513     when "who", "watches", "who watches"
514       "rss who watches [#{Bold}handle#{Bold}]]: list all watchers for rss feeds (matching #{Bold}handle#{Bold})"
515     when "add"
516       "rss add #{Bold}handle#{Bold} #{Bold}url#{Bold} [#{Bold}type#{Bold}] : add a new rss called #{Bold}handle#{Bold} from url #{Bold}url#{Bold} (of type #{Bold}type#{Bold})"
517     when "change"
518       "rss change #{Bold}what#{Bold} of #{Bold}handle#{Bold} to #{Bold}new#{Bold} : change the #{Underline}handle#{Underline}, #{Underline}url#{Underline}, #{Underline}type#{Underline} or #{Underline}refresh#{Underline} rate of rss called #{Bold}handle#{Bold} to value #{Bold}new#{Bold}"
519     when /^(del(ete)?|rm)$/
520       "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
521     when "replace"
522       "rss replace #{Bold}handle#{Bold} #{Bold}url#{Bold} [#{Bold}type#{Bold}] : try to replace the url of rss called #{Bold}handle#{Bold} with #{Bold}url#{Bold} (of type #{Bold}type#{Bold}); only works if nobody else is watching it"
523     when "forcereplace"
524       "rss forcereplace #{Bold}handle#{Bold} #{Bold}url#{Bold} [#{Bold}type#{Bold}] : replace the url of rss called #{Bold}handle#{Bold} with #{Bold}url#{Bold} (of type #{Bold}type#{Bold})"
525     when "watch"
526       "rss watch #{Bold}handle#{Bold} [#{Bold}url#{Bold} [#{Bold}type#{Bold}]]  [in #{Bold}chan#{Bold}]: watch rss #{Bold}handle#{Bold} for changes (in channel #{Bold}chan#{Bold}); when the other parameters are present, the feed will be created if it doesn't exist yet"
527     when /(un|rm)watch/
528       "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes"
529     when  /who(?: watche?s?)?/
530       "rss who watches #{Bold}handle#{Bold}: lists watches for rss #{Bold}handle#{Bold}"
531     when "rewatch"
532       "rss rewatch : restart threads that watch for changes in watched rss"
533     when "types"
534       "rss types : show the rss types for which an output format existi (all other types will use the default one)"
535     else
536       "manage RSS feeds: rss types|show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch|who watches"
537     end
538   end
539
540   def report_problem(report, e=nil, m=nil)
541     if m && m.respond_to?(:reply)
542       m.reply report
543     else
544       warning report
545     end
546     if e
547       debug e.inspect
548       debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
549     end
550   end
551
552   def show_rss(m, params)
553     handle = params[:handle]
554     lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
555     debug lims.to_a.inspect
556     if lims[2]
557       ll = [[lims[1].to_i-1,lims[2].to_i-1].min,  0].max
558       ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
559       rev = lims[1].to_i > lims[2].to_i
560     else
561       ll = 0
562       ul = [[lims[1].to_i-1, 0].max, 14].min
563       rev = false
564     end
565
566     feed = @feeds.fetch(handle.downcase, nil)
567     unless feed
568       m.reply "I don't know any feeds named #{handle}"
569       return
570     end
571
572     m.reply "lemme fetch it..."
573     title = items = nil
574     we_were_watching = false
575
576     if @watch.key?(feed.handle)
577       # If a feed is being watched, we run the watcher thread
578       # so that all watchers can be informed of changes to
579       # the feed. Before we do that, though, we remove the
580       # show requester from the watchlist, if present, lest
581       # he gets the update twice.
582       if feed.watched_by?(m.replyto)
583         we_were_watching = true
584         feed.rm_watch(m.replyto)
585       end
586       @bot.timer.reschedule(@watch[feed.handle], 0)
587       if we_were_watching
588         feed.add_watch(m.replyto)
589       end
590     else
591       fetched = fetchRss(feed, m, false)
592     end
593     return unless fetched or feed.xml
594     if not fetched and feed.items
595       m.reply "using old data"
596     else
597       parsed = parseRss(feed, m)
598       m.reply "using old data" unless parsed
599     end
600     return unless feed.items
601     title = feed.title
602     items = feed.items
603
604     # We sort the feeds in freshness order (newer ones first)
605     items = freshness_sort(items)
606     disp = items[ll..ul]
607     disp.reverse! if rev
608
609     m.reply "Channel : #{title}"
610     disp.each do |item|
611       printFormattedRss(feed, item, {:places=>[m.replyto],:handle=>nil,:date=>true})
612     end
613   end
614
615   def itemDate(item,ex=nil)
616     return item.pubDate if item.respond_to?(:pubDate) and item.pubDate
617     return item.date if item.respond_to?(:date) and item.date
618     return ex
619   end
620
621   def freshness_sort(items)
622     notime = Time.at(0)
623     items.sort { |a, b|
624       itemDate(b, notime) <=> itemDate(a, notime)
625     }
626   end
627
628   def list_rss(m, params)
629     wanted = params[:handle]
630     reply = String.new
631     @feeds.each { |handle, feed|
632       next if wanted and !handle.match(/#{wanted}/i)
633       reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
634       (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
635       (reply << " (watched)") if feed.watched_by?(m.replyto)
636       reply << "\n"
637     }
638     if reply.empty?
639       reply = "no feeds found"
640       reply << " matching #{wanted}" if wanted
641     end
642     m.reply reply, :max_lines => reply.length
643   end
644
645   def watched_rss(m, params)
646     wanted = params[:handle]
647     chan = params[:chan] || m.replyto
648     reply = String.new
649     watchlist.each { |handle, feed|
650       next if wanted and !handle.match(/#{wanted}/i)
651       next unless feed.watched_by?(chan)
652       reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
653       (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
654       reply << "\n"
655     }
656     if reply.empty?
657       reply = "no watched feeds"
658       reply << " matching #{wanted}" if wanted
659     end
660     m.reply reply
661   end
662
663   def who_watches(m, params)
664     wanted = params[:handle]
665     reply = String.new
666     watchlist.each { |handle, feed|
667       next if wanted and !handle.match(/#{wanted}/i)
668       reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
669       (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
670       reply << ": watched by #{feed.watchers.join(', ')}"
671       reply << "\n"
672     }
673     if reply.empty?
674       reply = "no watched feeds"
675       reply << " matching #{wanted}" if wanted
676     end
677     m.reply reply
678   end
679
680   def add_rss(m, params, force=false)
681     handle = params[:handle]
682     url = params[:url]
683     unless url.match(/https?/)
684       m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
685       return
686     end
687     type = params[:type]
688     if @feeds.fetch(handle.downcase, nil) && !force
689       m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"
690       return
691     end
692     unless url
693       m.reply "You must specify both a handle and an url to add an RSS feed"
694       return
695     end
696     @feeds[handle.downcase] = RssBlob.new(url,handle,type)
697     reply = "Added RSS #{url} named #{handle}"
698     if type
699       reply << " (format: #{type})"
700     end
701     m.reply reply
702     return handle
703   end
704
705   def change_rss(m, params)
706     handle = params[:handle].downcase
707     feed = @feeds.fetch(handle, nil)
708     unless feed
709       m.reply "No such feed with handle #{handle}"
710       return
711     end
712     case params[:what].intern
713     when :handle
714       new = params[:new].downcase
715       if @feeds.key?(new) and @feeds[new]
716         m.reply "There already is a feed with handle #{new}"
717         return
718       else
719         feed.mutex.synchronize do
720           @feeds[new] = feed
721           @feeds.delete(handle)
722           feed.handle = new
723         end
724         handle = new
725       end
726     when :url
727       new = params[:new]
728       feed.mutex.synchronize do
729         feed.url = new
730       end
731     when :format, :type
732       new = params[:new]
733       new = nil if new == 'default'
734       feed.mutex.synchronize do
735         feed.type = new
736       end
737     when :refresh
738       new = params[:new].to_i
739       new = nil if new == 0
740       feed.mutex.synchronize do
741         feed.refresh_rate = new
742       end
743     else
744       m.reply "Don't know how to change #{params[:what]} for feeds"
745       return
746     end
747     m.reply "Feed changed:"
748     list_rss(m, {:handle => handle})
749   end
750
751   def del_rss(m, params, pass=false)
752     feed = unwatch_rss(m, params, true)
753     return unless feed
754     if feed.watched?
755       m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
756       return
757     end
758     @feeds.delete(feed.handle.downcase)
759     m.okay unless pass
760     return
761   end
762
763   def replace_rss(m, params)
764     handle = params[:handle]
765     if @feeds.key?(handle.downcase)
766       del_rss(m, {:handle => handle}, true)
767     end
768     if @feeds.key?(handle.downcase)
769       m.reply "can't replace #{feed.handle}"
770     else
771       add_rss(m, params, true)
772     end
773   end
774
775   def forcereplace_rss(m, params)
776     add_rss(m, params, true)
777   end
778
779   def watch_rss(m, params)
780     handle = params[:handle]
781     chan = params[:chan] || m.replyto
782     url = params[:url]
783     type = params[:type]
784     if url
785       add_rss(m, params)
786     end
787     feed = @feeds.fetch(handle.downcase, nil)
788     if feed
789       if feed.add_watch(chan)
790         watchRss(feed, m)
791         m.okay
792       else
793         m.reply "Already watching #{feed.handle} in #{chan}"
794       end
795     else
796       m.reply "Couldn't watch feed #{handle} (no such feed found)"
797     end
798   end
799
800   def unwatch_rss(m, params, pass=false)
801     handle = params[:handle].downcase
802     chan = params[:chan] || m.replyto
803     unless @feeds.has_key?(handle)
804       m.reply("dunno that feed")
805       return
806     end
807     feed = @feeds[handle]
808     if feed.rm_watch(chan)
809       m.reply "#{chan} has been removed from the watchlist for #{feed.handle}"
810     else
811       m.reply("#{chan} wasn't watching #{feed.handle}") unless pass
812     end
813     if !feed.watched?
814       stop_watch(handle)
815     end
816     return feed
817   end
818
819   def rewatch_rss(m=nil, params=nil)
820     if params and handle = params[:handle]
821       feed = @feeds.fetch(handle.downcase, nil)
822       if feed
823         @bot.timer.reschedule(@watch[feed.handle], (params[:delay] || 0).to_f)
824         m.okay if m
825       else
826         m.reply _("no such feed %{handle}") % { :handle => handle } if m
827       end
828     else
829       stop_watches
830
831       # Read watches from list.
832       watchlist.each{ |handle, feed|
833         watchRss(feed, m)
834       }
835       m.okay if m
836     end
837   end
838
839   private
840   def watchRss(feed, m=nil)
841     if @watch.has_key?(feed.handle)
842       report_problem("watcher thread for #{feed.handle} is already running", nil, m)
843       return
844     end
845     status = Hash.new
846     status[:failures] = 0
847     tmout = 0
848     if feed.last_fetched
849       tmout = feed.last_fetched + calculate_timeout(feed) - Time.now
850       tmout = 0 if tmout < 0
851     end
852     debug "scheduling a watcher for #{feed} in #{tmout} seconds"
853     @watch[feed.handle] = @bot.timer.add(tmout) {
854       debug "watcher for #{feed} wakes up"
855       failures = status[:failures]
856       begin
857         debug "fetching #{feed}"
858         first_run = !feed.last_fetched
859         oldxml = feed.xml ? feed.xml.dup : nil
860         unless fetchRss(feed)
861           failures += 1
862         else
863           if first_run
864             debug "first run for #{feed}, getting items"
865             parseRss(feed)
866           elsif oldxml and oldxml == feed.xml
867             debug "xml for #{feed} didn't change"
868             failures -= 1 if failures > 0
869           else
870             if not feed.items
871               debug "no previous items in feed #{feed}"
872               parseRss(feed)
873               failures -= 1 if failures > 0
874             else
875               # This one is used for debugging
876               otxt = []
877
878               # These are used for checking new items vs old ones
879               oids = Set.new feed.items.map { |item|
880                 uid = make_uid item
881                 otxt << item.to_s
882                 debug [uid, item].inspect
883                 debug [uid, otxt.last].inspect
884                 uid
885               }
886
887               unless parseRss(feed)
888                 debug "no items in feed #{feed}"
889                 failures += 1
890               else
891                 debug "Checking if new items are available for #{feed}"
892                 failures -= 1 if failures > 0
893                 # debug "Old:"
894                 # debug oldxml
895                 # debug "New:"
896                 # debug feed.xml
897
898                 dispItems = feed.items.reject { |item|
899                   uid = make_uid item
900                   txt = item.to_s
901                   if oids.include?(uid)
902                     debug "rejecting old #{uid} #{item.inspect}"
903                     debug [uid, txt].inspect
904                     true
905                   else
906                     debug "accepting new #{uid} #{item.inspect}"
907                     debug [uid, txt].inspect
908                     warning "same text! #{txt}" if otxt.include?(txt)
909                     false
910                   end
911                 }
912
913                 if dispItems.length > 0
914                   debug "Found #{dispItems.length} new items in #{feed}"
915                   # When displaying watched feeds, publish them from older to newer
916                   dispItems.reverse.each { |item|
917                     printFormattedRss(feed, item)
918                   }
919                 else
920                   debug "No new items found in #{feed}"
921                 end
922               end
923             end
924           end
925         end
926       rescue Exception => e
927         error "Error watching #{feed}: #{e.inspect}"
928         debug e.backtrace.join("\n")
929         failures += 1
930       end
931
932       status[:failures] = failures
933
934       seconds = calculate_timeout(feed, failures)
935       debug "watcher for #{feed} going to sleep #{seconds} seconds.."
936       begin
937         @bot.timer.reschedule(@watch[feed.handle], seconds)
938       rescue
939         warning "watcher for #{feed} failed to reschedule: #{$!.inspect}"
940       end
941     }
942     debug "watcher for #{feed} added"
943   end
944
945   def calculate_timeout(feed, failures = 0)
946       seconds = @bot.config['rss.thread_sleep']
947       feed.mutex.synchronize do
948         seconds = feed.refresh_rate if feed.refresh_rate
949       end
950       seconds *= failures + 1
951       seconds += seconds * (rand(100)-50)/100
952       return seconds
953   end
954
955   def select_nonempty(*ar)
956     # debug ar
957     ar.each { |i| return i unless i.nil_or_empty? }
958     return nil
959   end
960
961   def printFormattedRss(feed, item, opts=nil)
962     # debug item
963     places = feed.watchers
964     handle = feed.handle.empty? ? "" : "::#{feed.handle}:: "
965     date = String.new
966     if opts
967       places = opts[:places] if opts.key?(:places)
968       handle = opts[:handle].to_s if opts.key?(:handle)
969       if opts.key?(:date) && opts[:date]
970         if item.respond_to?(:updated)
971           if item.updated.content.class <= Time
972             date = item.updated.content.strftime("%Y/%m/%d %H:%M")
973           else
974             date = item.updated.content.to_s
975           end
976         elsif item.respond_to?(:source) and item.source.respond_to?(:updated)
977           if item.source.updated.content.class <= Time
978             date = item.source.updated.content.strftime("%Y/%m/%d %H:%M")
979           else
980             date = item.source.updated.content.to_s
981           end
982         elsif item.respond_to?(:pubDate) 
983           if item.pubDate.class <= Time
984             date = item.pubDate.strftime("%Y/%m/%d %H:%M")
985           else
986             date = item.pubDate.to_s
987           end
988         elsif item.respond_to?(:date)
989           if item.date.class <= Time
990             date = item.date.strftime("%Y/%m/%d %H:%M")
991           else
992             date = item.date.to_s
993           end
994         else
995           date = "(no date)"
996         end
997         date += " :: "
998       end
999     end
1000
1001     tit_opt = {}
1002     # Twitters don't need a cap on the title length since they have a hard
1003     # limit to 160 characters, and most of them are under 140 characters
1004     tit_opt[:limit] = @bot.config['rss.head_max'] unless feed.type == 'twitter'
1005
1006     if item.title
1007       base_title = item.title.to_s.dup
1008       # git changesets are SHA1 hashes (40 hex digits), way too long, get rid of them, as they are
1009       # visible in the URL anyway
1010       # TODO make this optional?
1011       base_title.sub!(/^Changeset \[([\da-f]{40})\]:/) { |c| "(git commit)"} if feed.type == 'trac'
1012       title = "#{Bold}#{base_title.ircify_html(tit_opt)}#{Bold}"
1013     end
1014
1015     desc_opt = {}
1016     desc_opt[:limit] = @bot.config['rss.text_max']
1017     desc_opt[:a_href] = :link_out if @bot.config['rss.show_links']
1018
1019     # We prefer content_encoded here as it tends to provide more html formatting 
1020     # for use with ircify_html.
1021     if item.respond_to?(:content_encoded) && item.content_encoded
1022       desc = item.content_encoded.ircify_html(desc_opt)
1023     elsif item.respond_to?(:description) && item.description
1024       desc = item.description.ircify_html(desc_opt)
1025     elsif item.respond_to?(:content) && item.content
1026       if item.content.type == "html"
1027         desc = item.content.content.ircify_html(desc_opt)
1028       else
1029         desc = item.content.content
1030         if desc.size > desc_opt[:limit]
1031           desc = desc.slice(0, desc_opt[:limit]) + "#{Reverse}...#{Reverse}"
1032         end
1033       end
1034     else
1035       desc = "(?)"
1036     end
1037
1038     link = item.link.href rescue item.link.chomp rescue nil
1039
1040     category = select_nonempty((item.category.content rescue nil), (item.dc_subject rescue nil))
1041     author = select_nonempty((item.author.name.content rescue nil), (item.dc_creator rescue nil), (item.author rescue nil))
1042
1043     line1 = nil
1044     line2 = nil
1045
1046     at = ((item.title && item.link) ? ' @ ' : '')
1047
1048     key = @bot.global_filter_name(feed.type, @outkey)
1049     key = @bot.global_filter_name(:default, @outkey) unless @bot.has_filter?(key)
1050
1051     output = @bot.filter(key, :item => item, :handle => handle, :date => date,
1052                          :title => title, :desc => desc, :link => link,
1053                          :category => category, :author => author, :at => at)
1054
1055     return output if places.empty?
1056
1057     places.each { |loc|
1058       output.to_s.each_line { |line|
1059         @bot.say loc, line, :overlong => :truncate
1060       }
1061     }
1062   end
1063
1064   def fetchRss(feed, m=nil, cache=true)
1065     feed.last_fetched = Time.now
1066     begin
1067       # Use 60 sec timeout, cause the default is too low
1068       xml = @bot.httputil.get(feed.url,
1069                               :read_timeout => 60,
1070                               :open_timeout => 60,
1071                               :cache => cache)
1072     rescue URI::InvalidURIError, URI::BadURIError => e
1073       report_problem("invalid rss feed #{feed.url}", e, m)
1074       return nil
1075     rescue => e
1076       report_problem("error getting #{feed.url}", e, m)
1077       return nil
1078     end
1079     debug "fetched #{feed}"
1080     unless xml
1081       report_problem("reading feed #{feed} failed", nil, m)
1082       return nil
1083     end
1084     # Ok, 0.9 feeds are not supported, maybe because
1085     # Netscape happily removed the DTD. So what we do is just to
1086     # reassign the 0.9 RDFs to 1.0, and hope it goes right.
1087     xml.gsub!("xmlns=\"http://my.netscape.com/rdf/simple/0.9/\"",
1088               "xmlns=\"http://purl.org/rss/1.0/\"")
1089     feed.mutex.synchronize do
1090       feed.xml = xml
1091     end
1092     return true
1093   end
1094
1095   def parseRss(feed, m=nil)
1096     return nil unless feed.xml
1097     feed.mutex.synchronize do
1098       xml = feed.xml
1099       begin
1100         ## do validate parse
1101         rss = RSS::Parser.parse(xml)
1102         debug "parsed and validated #{feed}"
1103       rescue RSS::InvalidRSSError
1104         ## do non validate parse for invalid RSS 1.0
1105         begin
1106           rss = RSS::Parser.parse(xml, false)
1107           debug "parsed but not validated #{feed}"
1108         rescue RSS::Error => e
1109           report_problem("parsing rss stream failed, whoops =(", e, m)
1110           return nil
1111         end
1112       rescue RSS::Error => e
1113         report_problem("parsing rss stream failed, oioi", e, m)
1114         return nil
1115       rescue => e
1116         report_problem("processing error occured, sorry =(", e, m)
1117         return nil
1118       end
1119       items = []
1120       if rss.nil?
1121         report_problem("#{feed} does not include RSS 1.0 or 0.9x/2.0", nil, m)
1122       else
1123         begin
1124           rss.output_encoding = 'UTF-8'
1125         rescue RSS::UnknownConvertMethod => e
1126           report_problem("bah! something went wrong =(", e, m)
1127           return nil
1128         end
1129         if rss.respond_to? :channel
1130           rss.channel.title ||= "(?)"
1131           title = rss.channel.title
1132         else
1133           title = rss.title.content
1134         end
1135         rss.items.each do |item|
1136           item.title ||= "(?)"
1137           items << item
1138         end
1139       end
1140
1141       if items.empty?
1142         report_problem("no items found in the feed, maybe try weed?", e, m)
1143         return nil
1144       end
1145       feed.title = title
1146       feed.items = items
1147       return true
1148     end
1149   end
1150 end
1151
1152 plugin = RSSFeedsPlugin.new
1153
1154 plugin.default_auth( 'edit', false )
1155 plugin.default_auth( 'edit:add', true)
1156
1157 plugin.map 'rss show :handle :limit',
1158   :action => 'show_rss',
1159   :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
1160   :defaults => {:limit => 5}
1161 plugin.map 'rss list :handle',
1162   :action => 'list_rss',
1163   :defaults => {:handle => nil}
1164 plugin.map 'rss watched :handle [in :chan]',
1165   :action => 'watched_rss',
1166   :defaults => {:handle => nil}
1167 plugin.map 'rss who watches :handle',
1168   :action => 'who_watches',
1169   :defaults => {:handle => nil}
1170 plugin.map 'rss add :handle :url :type',
1171   :action => 'add_rss',
1172   :auth_path => 'edit',
1173   :defaults => {:type => nil}
1174 plugin.map 'rss change :what of :handle to :new',
1175   :action => 'change_rss',
1176   :auth_path => 'edit',
1177   :requirements => { :what => /handle|url|format|type|refresh/ }
1178 plugin.map 'rss change :what for :handle to :new',
1179   :action => 'change_rss',
1180   :auth_path => 'edit',
1181   :requirements => { :what => /handle|url|format|type|refesh/ }
1182 plugin.map 'rss del :handle',
1183   :auth_path => 'edit:rm!',
1184   :action => 'del_rss'
1185 plugin.map 'rss delete :handle',
1186   :auth_path => 'edit:rm!',
1187   :action => 'del_rss'
1188 plugin.map 'rss rm :handle',
1189   :auth_path => 'edit:rm!',
1190   :action => 'del_rss'
1191 plugin.map 'rss replace :handle :url :type',
1192   :auth_path => 'edit',
1193   :action => 'replace_rss',
1194   :defaults => {:type => nil}
1195 plugin.map 'rss forcereplace :handle :url :type',
1196   :auth_path => 'edit',
1197   :action => 'forcereplace_rss',
1198   :defaults => {:type => nil}
1199 plugin.map 'rss watch :handle [in :chan]',
1200   :action => 'watch_rss',
1201   :defaults => {:url => nil, :type => nil}
1202 plugin.map 'rss watch :handle :url :type [in :chan]',
1203   :action => 'watch_rss',
1204   :defaults => {:url => nil, :type => nil}
1205 plugin.map 'rss unwatch :handle [in :chan]',
1206   :action => 'unwatch_rss'
1207 plugin.map 'rss rmwatch :handle [in :chan]',
1208   :action => 'unwatch_rss'
1209 plugin.map 'rss rewatch [:handle] [:delay]',
1210   :action => 'rewatch_rss'
1211 plugin.map 'rss types',
1212   :action => 'rss_types'