]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/rss.rb
plugins: raise a descriptive LoadError when the db is corrupt on load
[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(:headlines, @outkey) { |s|
318       line1 = (s[:handle].empty? ? "%{date}" : "%{handle}") << "%{title}"
319       make_stream(line1, nil, s)
320     }
321     @bot.register_filter(:blog, @outkey) { |s|
322       author = s[:author] ? (s[:author] + " ") : ""
323       abt = s[:category] ? "about #{s[:category]} " : ""
324       line1 = "%{handle}%{date}%{author}blogged %{abt}at %{link}"
325       line2 = "%{handle}%{title} - %{desc}"
326       make_stream(line1, line2, s, :author => author, :abt => abt)
327     }
328     @bot.register_filter(:photoblog, @outkey) { |s|
329       author = s[:author] ? (s[:author] + " ") : ""
330       abt = s[:category] ? "under #{s[:category]} " : ""
331       line1 = "%{handle}%{date}%{author}added an image %{abt}at %{link}"
332       line2 = "%{handle}%{title} - %{desc}"
333       make_stream(line1, line2, s, :author => author, :abt => abt)
334     }
335     @bot.register_filter(:news, @outkey) { |s|
336       line1 = "%{handle}%{date}%{title}%{at}%{link}" % s
337       line2 = "%{handle}%{date}%{desc}" % s
338       make_stream(line1, line2, s)
339     }
340     @bot.register_filter(:git, @outkey) { |s|
341       author = s[:author] ? (s[:author] + " ") : ""
342       line1 = "%{handle}%{date}%{author}committed %{title}%{at}%{link}"
343       make_stream(line1, nil, s, :author => author)
344     }
345     @bot.register_filter(:forum, @outkey) { |s|
346       line1 = "%{handle}%{date}%{title}%{at}%{link}"
347       make_stream(line1, nil, s)
348     }
349     @bot.register_filter(:wiki, @outkey) { |s|
350       line1 = "%{handle}%{date}%{title}%{at}%{link}"
351       line1 << "has been edited by %{author}. %{desc}"
352       make_stream(line1, nil, s)
353     }
354     @bot.register_filter(:gmane, @outkey) { |s|
355       line1 = "%{handle}%{date}Message %{title} sent by %{author}. %{desc}"
356       make_stream(line1, nil, s)
357     }
358     @bot.register_filter(:trac, @outkey) { |s|
359       author = s[:author].sub(/@\S+?\s*>/, "@...>") + ": " if s[:author]
360       line1 = "%{handle}%{date}%{author}%{title}%{at}%{link}"
361       line2 = nil
362       unless s[:item].title =~ /^(?:Changeset \[(?:[\da-f]+)\]|\(git commit\))/
363         line2 = "%{handle}%{date}%{desc}"
364       end
365       make_stream(line1, line2, s, :author => author)
366     }
367     @bot.register_filter(:"/.", @outkey) { |s|
368       dept = "(from the #{s[:item].slash_department} dept) " rescue nil
369       sec = " in section #{s[:item].slash_section}" rescue nil
370       line1 = "%{handle}%{date}%{dept}%{title}%{at}%{link} "
371       line1 << "(posted by %{author}%{sec})"
372       make_stream(line1, nil, s, :dept => dept, :sec => sec)
373     }
374     @bot.register_filter(:default, @outkey) { |s|
375       line1 = "%{handle}%{date}%{title}%{at}%{link}"
376       line1 << " (by %{author})" if s[:author]
377       make_stream(line1, nil, s)
378     }
379
380     # Define an HTML info filter too
381     @bot.register_filter(:rss, :htmlinfo) { |s| htmlinfo_filter(s) }
382
383     # This is the output format used by the input filter
384     @bot.register_filter(:htmlinfo, @outkey) { |s|
385       line1 = "%{title}%{at}%{link}"
386       make_stream(line1, nil, s)
387     }
388   end
389
390   FEED_NS = %r{xmlns.*http://(purl\.org/rss|www.w3c.org/1999/02/22-rdf)}
391   def htmlinfo_filter(s)
392     return nil unless s[:headers] and s[:headers]['x-rbot-location']
393     return nil unless s[:headers]['content-type'].first.match(/xml|rss|atom|rdf/i) or
394       (s[:text].include?("<rdf:RDF") and s[:text].include?("<channel")) or
395       s[:text].include?("<rss") or s[:text].include?("<feed") or
396       s[:text].match(FEED_NS)
397     blob = RssBlob.new(s[:headers]['x-rbot-location'],"", :htmlinfo)
398     unless (fetchRss(blob, nil) and parseRss(blob, nil) rescue nil)
399       debug "#{s.pretty_inspect} is not an RSS feed, despite the appearances"
400       return nil
401     end
402     output = []
403     blob.items.each { |it|
404       output << printFormattedRss(blob, it)[:text]
405     }
406     return {:title => blob.title, :content => output.join(" | ")}
407   end
408
409   # Display the known rss types
410   def rss_types(m, params)
411     ar = @bot.filter_names(@outkey)
412     ar.delete(:default)
413     m.reply ar.map { |k| k.to_s }.sort!.join(", ")
414   end
415
416   attr_reader :feeds
417
418   def initialize
419     super
420
421     define_filters
422
423     if @registry.has_key?(:feeds)
424       # When migrating from Ruby 1.8.5 to 1.8.6, dumped Mutexes may render the
425       # data unrestorable. If this happens, we patch the data, thus allowing
426       # the restore to work.
427       #
428       # This is actually pretty safe for a number of reasons:
429       # * the code is only called if standard marshalling fails
430       # * the string we look for is quite unlikely to appear randomly
431       # * if the string appears somewhere and the patched string isn't recoverable
432       #   either, we'll get another (unrecoverable) error, which makes the rss
433       #   plugin unsable, just like it was if no recovery was attempted
434       # * if the string appears somewhere and the patched string is recoverable,
435       #   we may get a b0rked feed, which is eventually overwritten by a clean
436       #   one, so the worst thing that can happen is that a feed update spams
437       #   the watchers once
438       @registry.recovery = Proc.new { |val|
439         patched = val.sub(":\v@mutexo:\nMutex", ":\v@mutexo:\vObject")
440         ret = Marshal.restore(patched)
441         ret.each_value { |blob|
442           blob.mutex = nil
443           blob
444         }
445       }
446
447       @feeds = @registry[:feeds]
448       raise LoadError, "corrupted feed database" unless @feeds
449
450       @registry.recovery = nil
451
452       @feeds.keys.grep(/[A-Z]/) { |k|
453         @feeds[k.downcase] = @feeds[k]
454         @feeds.delete(k)
455       }
456       @feeds.each { |k, f|
457         f.mutex = Mutex.new
458         f.sanitize_watchers
459         parseRss(f) if f.xml
460       }
461     else
462       @feeds = Hash.new
463     end
464     @watch = Hash.new
465     rewatch_rss
466   end
467
468   def name
469     "rss"
470   end
471
472   def watchlist
473     @feeds.select { |h, f| f.watched? }
474   end
475
476   def cleanup
477     stop_watches
478     super
479   end
480
481   def save
482     unparsed = Hash.new()
483     @feeds.each { |k, f|
484       unparsed[k] = f.dup
485       # we don't want to save the mutex
486       unparsed[k].mutex = nil
487     }
488     @registry[:feeds] = unparsed
489   end
490
491   def stop_watch(handle)
492     if @watch.has_key?(handle)
493       begin
494         debug "Stopping watch #{handle}"
495         @bot.timer.remove(@watch[handle])
496         @watch.delete(handle)
497       rescue Exception => e
498         report_problem("Failed to stop watch for #{handle}", e, nil)
499       end
500     end
501   end
502
503   def stop_watches
504     @watch.each_key { |k|
505       stop_watch(k)
506     }
507   end
508
509   def help(plugin,topic="")
510     case topic
511     when "show"
512       "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"
513     when "list"
514       "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
515     when "watched"
516       "rss watched [#{Bold}handle#{Bold}] [in #{Bold}chan#{Bold}]: list all watched rss feeds (matching #{Bold}handle#{Bold}) (in channel #{Bold}chan#{Bold})"
517     when "who", "watches", "who watches"
518       "rss who watches [#{Bold}handle#{Bold}]]: list all watchers for rss feeds (matching #{Bold}handle#{Bold})"
519     when "add"
520       "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})"
521     when "change"
522       "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}"
523     when /^(del(ete)?|rm)$/
524       "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
525     when "replace"
526       "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"
527     when "forcereplace"
528       "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})"
529     when "watch"
530       "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"
531     when /(un|rm)watch/
532       "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes"
533     when  /who(?: watche?s?)?/
534       "rss who watches #{Bold}handle#{Bold}: lists watches for rss #{Bold}handle#{Bold}"
535     when "rewatch"
536       "rss rewatch : restart threads that watch for changes in watched rss"
537     when "types"
538       "rss types : show the rss types for which an output format existi (all other types will use the default one)"
539     else
540       "manage RSS feeds: rss types|show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch|who watches"
541     end
542   end
543
544   def report_problem(report, e=nil, m=nil)
545     if m && m.respond_to?(:reply)
546       m.reply report
547     else
548       warning report
549     end
550     if e
551       debug e.inspect
552       debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
553     end
554   end
555
556   def show_rss(m, params)
557     handle = params[:handle]
558     lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
559     debug lims.to_a.inspect
560     if lims[2]
561       ll = [[lims[1].to_i-1,lims[2].to_i-1].min,  0].max
562       ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
563       rev = lims[1].to_i > lims[2].to_i
564     else
565       ll = 0
566       ul = [[lims[1].to_i-1, 0].max, 14].min
567       rev = false
568     end
569
570     feed = @feeds.fetch(handle.downcase, nil)
571     unless feed
572       m.reply "I don't know any feeds named #{handle}"
573       return
574     end
575
576     m.reply "lemme fetch it..."
577     title = items = nil
578     we_were_watching = false
579
580     if @watch.key?(feed.handle)
581       # If a feed is being watched, we run the watcher thread
582       # so that all watchers can be informed of changes to
583       # the feed. Before we do that, though, we remove the
584       # show requester from the watchlist, if present, lest
585       # he gets the update twice.
586       if feed.watched_by?(m.replyto)
587         we_were_watching = true
588         feed.rm_watch(m.replyto)
589       end
590       @bot.timer.reschedule(@watch[feed.handle], 0)
591       if we_were_watching
592         feed.add_watch(m.replyto)
593       end
594     else
595       fetched = fetchRss(feed, m, false)
596     end
597     return unless fetched or feed.xml
598     if fetched or not feed.items
599       parsed = parseRss(feed, m)
600     end
601     return unless feed.items
602     m.reply "using old data" unless fetched and parsed
603
604     title = feed.title
605     items = feed.items
606
607     # We sort the feeds in freshness order (newer ones first)
608     items = freshness_sort(items)
609     disp = items[ll..ul]
610     disp.reverse! if rev
611
612     m.reply "Channel : #{title}"
613     disp.each do |item|
614       printFormattedRss(feed, item, {:places=>[m.replyto],:handle=>nil,:date=>true})
615     end
616   end
617
618   def itemDate(item,ex=nil)
619     return item.pubDate if item.respond_to?(:pubDate) and item.pubDate
620     return item.date if item.respond_to?(:date) and item.date
621     return ex
622   end
623
624   def freshness_sort(items)
625     notime = Time.at(0)
626     items.sort { |a, b|
627       itemDate(b, notime) <=> itemDate(a, notime)
628     }
629   end
630
631   def list_rss(m, params)
632     wanted = params[:handle]
633     reply = String.new
634     @feeds.each { |handle, feed|
635       next if wanted and !handle.match(/#{wanted}/i)
636       reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
637       (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
638       (reply << " (watched)") if feed.watched_by?(m.replyto)
639       reply << "\n"
640     }
641     if reply.empty?
642       reply = "no feeds found"
643       reply << " matching #{wanted}" if wanted
644     end
645     m.reply reply, :max_lines => reply.length
646   end
647
648   def watched_rss(m, params)
649     wanted = params[:handle]
650     chan = params[:chan] || m.replyto
651     reply = String.new
652     watchlist.each { |handle, feed|
653       next if wanted and !handle.match(/#{wanted}/i)
654       next unless feed.watched_by?(chan)
655       reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
656       (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
657       reply << "\n"
658     }
659     if reply.empty?
660       reply = "no watched feeds"
661       reply << " matching #{wanted}" if wanted
662     end
663     m.reply reply
664   end
665
666   def who_watches(m, params)
667     wanted = params[:handle]
668     reply = String.new
669     watchlist.each { |handle, feed|
670       next if wanted and !handle.match(/#{wanted}/i)
671       reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
672       (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
673       reply << ": watched by #{feed.watchers.join(', ')}"
674       reply << "\n"
675     }
676     if reply.empty?
677       reply = "no watched feeds"
678       reply << " matching #{wanted}" if wanted
679     end
680     m.reply reply
681   end
682
683   def add_rss(m, params, force=false)
684     handle = params[:handle]
685     url = params[:url]
686     unless url.match(/https?/)
687       m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
688       return
689     end
690     type = params[:type]
691     if @feeds.fetch(handle.downcase, nil) && !force
692       m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"
693       return
694     end
695     unless url
696       m.reply "You must specify both a handle and an url to add an RSS feed"
697       return
698     end
699     @feeds[handle.downcase] = RssBlob.new(url,handle,type)
700     reply = "Added RSS #{url} named #{handle}"
701     if type
702       reply << " (format: #{type})"
703     end
704     m.reply reply
705     return handle
706   end
707
708   def change_rss(m, params)
709     handle = params[:handle].downcase
710     feed = @feeds.fetch(handle, nil)
711     unless feed
712       m.reply "No such feed with handle #{handle}"
713       return
714     end
715     case params[:what].intern
716     when :handle
717       new = params[:new].downcase
718       if @feeds.key?(new) and @feeds[new]
719         m.reply "There already is a feed with handle #{new}"
720         return
721       else
722         feed.mutex.synchronize do
723           @feeds[new] = feed
724           @feeds.delete(handle)
725           feed.handle = new
726         end
727         handle = new
728       end
729     when :url
730       new = params[:new]
731       feed.mutex.synchronize do
732         feed.url = new
733       end
734     when :format, :type
735       new = params[:new]
736       new = nil if new == 'default'
737       feed.mutex.synchronize do
738         feed.type = new
739       end
740     when :refresh
741       new = params[:new].to_i
742       new = nil if new == 0
743       feed.mutex.synchronize do
744         feed.refresh_rate = new
745       end
746     else
747       m.reply "Don't know how to change #{params[:what]} for feeds"
748       return
749     end
750     m.reply "Feed changed:"
751     list_rss(m, {:handle => handle})
752   end
753
754   def del_rss(m, params, pass=false)
755     feed = unwatch_rss(m, params, true)
756     return unless feed
757     if feed.watched?
758       m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
759       return
760     end
761     @feeds.delete(feed.handle.downcase)
762     m.okay unless pass
763     return
764   end
765
766   def replace_rss(m, params)
767     handle = params[:handle]
768     if @feeds.key?(handle.downcase)
769       del_rss(m, {:handle => handle}, true)
770     end
771     if @feeds.key?(handle.downcase)
772       m.reply "can't replace #{feed.handle}"
773     else
774       add_rss(m, params, true)
775     end
776   end
777
778   def forcereplace_rss(m, params)
779     add_rss(m, params, true)
780   end
781
782   def watch_rss(m, params)
783     handle = params[:handle]
784     chan = params[:chan] || m.replyto
785     url = params[:url]
786     type = params[:type]
787     if url
788       add_rss(m, params)
789     end
790     feed = @feeds.fetch(handle.downcase, nil)
791     if feed
792       if feed.add_watch(chan)
793         watchRss(feed, m)
794         m.okay
795       else
796         m.reply "Already watching #{feed.handle} in #{chan}"
797       end
798     else
799       m.reply "Couldn't watch feed #{handle} (no such feed found)"
800     end
801   end
802
803   def unwatch_rss(m, params, pass=false)
804     handle = params[:handle].downcase
805     chan = params[:chan] || m.replyto
806     unless @feeds.has_key?(handle)
807       m.reply("dunno that feed")
808       return
809     end
810     feed = @feeds[handle]
811     if feed.rm_watch(chan)
812       m.reply "#{chan} has been removed from the watchlist for #{feed.handle}"
813     else
814       m.reply("#{chan} wasn't watching #{feed.handle}") unless pass
815     end
816     if !feed.watched?
817       stop_watch(handle)
818     end
819     return feed
820   end
821
822   def rewatch_rss(m=nil, params=nil)
823     if params and handle = params[:handle]
824       feed = @feeds.fetch(handle.downcase, nil)
825       if feed
826         @bot.timer.reschedule(@watch[feed.handle], (params[:delay] || 0).to_f)
827         m.okay if m
828       else
829         m.reply _("no such feed %{handle}") % { :handle => handle } if m
830       end
831     else
832       stop_watches
833
834       # Read watches from list.
835       watchlist.each{ |handle, feed|
836         watchRss(feed, m)
837       }
838       m.okay if m
839     end
840   end
841
842   private
843   def watchRss(feed, m=nil)
844     if @watch.has_key?(feed.handle)
845       report_problem("watcher thread for #{feed.handle} is already running", nil, m)
846       return
847     end
848     status = Hash.new
849     status[:failures] = 0
850     tmout = 0
851     if feed.last_fetched
852       tmout = feed.last_fetched + calculate_timeout(feed) - Time.now
853       tmout = 0 if tmout < 0
854     end
855     debug "scheduling a watcher for #{feed} in #{tmout} seconds"
856     @watch[feed.handle] = @bot.timer.add(tmout) {
857       debug "watcher for #{feed} wakes up"
858       failures = status[:failures]
859       begin
860         debug "fetching #{feed}"
861         first_run = !feed.last_fetched
862         oldxml = feed.xml ? feed.xml.dup : nil
863         unless fetchRss(feed)
864           failures += 1
865         else
866           if first_run
867             debug "first run for #{feed}, getting items"
868             parseRss(feed)
869           elsif oldxml and oldxml == feed.xml
870             debug "xml for #{feed} didn't change"
871             failures -= 1 if failures > 0
872           else
873             if not feed.items
874               debug "no previous items in feed #{feed}"
875               parseRss(feed)
876               failures -= 1 if failures > 0
877             else
878               # This one is used for debugging
879               otxt = []
880
881               # These are used for checking new items vs old ones
882               oids = Set.new feed.items.map { |item|
883                 uid = make_uid item
884                 otxt << item.to_s
885                 debug [uid, item].inspect
886                 debug [uid, otxt.last].inspect
887                 uid
888               }
889
890               unless parseRss(feed)
891                 debug "no items in feed #{feed}"
892                 failures += 1
893               else
894                 debug "Checking if new items are available for #{feed}"
895                 failures -= 1 if failures > 0
896                 # debug "Old:"
897                 # debug oldxml
898                 # debug "New:"
899                 # debug feed.xml
900
901                 dispItems = feed.items.reject { |item|
902                   uid = make_uid item
903                   txt = item.to_s
904                   if oids.include?(uid)
905                     debug "rejecting old #{uid} #{item.inspect}"
906                     debug [uid, txt].inspect
907                     true
908                   else
909                     debug "accepting new #{uid} #{item.inspect}"
910                     debug [uid, txt].inspect
911                     warning "same text! #{txt}" if otxt.include?(txt)
912                     false
913                   end
914                 }
915
916                 if dispItems.length > 0
917                   debug "Found #{dispItems.length} new items in #{feed}"
918                   # When displaying watched feeds, publish them from older to newer
919                   dispItems.reverse.each { |item|
920                     printFormattedRss(feed, item)
921                   }
922                 else
923                   debug "No new items found in #{feed}"
924                 end
925               end
926             end
927           end
928         end
929       rescue Exception => e
930         error "Error watching #{feed}: #{e.inspect}"
931         debug e.backtrace.join("\n")
932         failures += 1
933       end
934
935       status[:failures] = failures
936
937       seconds = calculate_timeout(feed, failures)
938       debug "watcher for #{feed} going to sleep #{seconds} seconds.."
939       begin
940         @bot.timer.reschedule(@watch[feed.handle], seconds)
941       rescue
942         warning "watcher for #{feed} failed to reschedule: #{$!.inspect}"
943       end
944     }
945     debug "watcher for #{feed} added"
946   end
947
948   def calculate_timeout(feed, failures = 0)
949       seconds = @bot.config['rss.thread_sleep']
950       feed.mutex.synchronize do
951         seconds = feed.refresh_rate if feed.refresh_rate
952       end
953       seconds *= failures + 1
954       seconds += seconds * (rand(100)-50)/100
955       return seconds
956   end
957
958   def select_nonempty(*ar)
959     # debug ar
960     ar.each { |i| return i unless i.nil_or_empty? }
961     return nil
962   end
963
964   def printFormattedRss(feed, item, opts=nil)
965     # debug item
966     places = feed.watchers
967     handle = feed.handle.empty? ? "" : "::#{feed.handle}:: "
968     date = String.new
969     if opts
970       places = opts[:places] if opts.key?(:places)
971       handle = opts[:handle].to_s if opts.key?(:handle)
972       if opts.key?(:date) && opts[:date]
973         if item.respond_to?(:updated)
974           if item.updated.content.class <= Time
975             date = item.updated.content.strftime("%Y/%m/%d %H:%M")
976           else
977             date = item.updated.content.to_s
978           end
979         elsif item.respond_to?(:source) and item.source.respond_to?(:updated)
980           if item.source.updated.content.class <= Time
981             date = item.source.updated.content.strftime("%Y/%m/%d %H:%M")
982           else
983             date = item.source.updated.content.to_s
984           end
985         elsif item.respond_to?(:pubDate) 
986           if item.pubDate.class <= Time
987             date = item.pubDate.strftime("%Y/%m/%d %H:%M")
988           else
989             date = item.pubDate.to_s
990           end
991         elsif item.respond_to?(:date)
992           if item.date.class <= Time
993             date = item.date.strftime("%Y/%m/%d %H:%M")
994           else
995             date = item.date.to_s
996           end
997         else
998           date = "(no date)"
999         end
1000         date += " :: "
1001       end
1002     end
1003
1004     tit_opt = {}
1005     # Twitters don't need a cap on the title length since they have a hard
1006     # limit to 160 characters, and most of them are under 140 characters
1007     tit_opt[:limit] = @bot.config['rss.head_max'] unless feed.type == 'twitter'
1008
1009     if item.title
1010       base_title = item.title.to_s.dup
1011       # git changesets are SHA1 hashes (40 hex digits), way too long, get rid of them, as they are
1012       # visible in the URL anyway
1013       # TODO make this optional?
1014       base_title.sub!(/^Changeset \[([\da-f]{40})\]:/) { |c| "(git commit)"} if feed.type == 'trac'
1015       title = "#{Bold}#{base_title.ircify_html(tit_opt)}#{Bold}"
1016     end
1017
1018     desc_opt = {}
1019     desc_opt[:limit] = @bot.config['rss.text_max']
1020     desc_opt[:a_href] = :link_out if @bot.config['rss.show_links']
1021
1022     # We prefer content_encoded here as it tends to provide more html formatting 
1023     # for use with ircify_html.
1024     if item.respond_to?(:content_encoded) && item.content_encoded
1025       desc = item.content_encoded.ircify_html(desc_opt)
1026     elsif item.respond_to?(:description) && item.description
1027       desc = item.description.ircify_html(desc_opt)
1028     elsif item.respond_to?(:content) && item.content
1029       if item.content.type == "html"
1030         desc = item.content.content.ircify_html(desc_opt)
1031       else
1032         desc = item.content.content
1033         if desc.size > desc_opt[:limit]
1034           desc = desc.slice(0, desc_opt[:limit]) + "#{Reverse}...#{Reverse}"
1035         end
1036       end
1037     else
1038       desc = "(?)"
1039     end
1040
1041     link = item.link.href rescue item.link rescue nil
1042     link.strip! if link
1043
1044     category = select_nonempty((item.category.content rescue nil), (item.dc_subject rescue nil))
1045     category.strip! if category
1046     author = select_nonempty((item.author.name.content rescue nil), (item.dc_creator rescue nil), (item.author rescue nil))
1047     author.strip! if author
1048
1049     line1 = nil
1050     line2 = nil
1051
1052     at = ((item.title && item.link) ? ' @ ' : '')
1053
1054     key = @bot.global_filter_name(feed.type, @outkey)
1055     key = @bot.global_filter_name(:default, @outkey) unless @bot.has_filter?(key)
1056
1057     output = @bot.filter(key, :item => item, :handle => handle, :date => date,
1058                          :title => title, :desc => desc, :link => link,
1059                          :category => category, :author => author, :at => at)
1060
1061     return output if places.empty?
1062
1063     places.each { |loc|
1064       output.to_s.each_line { |line|
1065         @bot.say loc, line, :overlong => :truncate
1066       }
1067     }
1068   end
1069
1070   def fetchRss(feed, m=nil, cache=true)
1071     feed.last_fetched = Time.now
1072     begin
1073       # Use 60 sec timeout, cause the default is too low
1074       xml = @bot.httputil.get(feed.url,
1075                               :read_timeout => 60,
1076                               :open_timeout => 60,
1077                               :cache => cache)
1078     rescue URI::InvalidURIError, URI::BadURIError => e
1079       report_problem("invalid rss feed #{feed.url}", e, m)
1080       return nil
1081     rescue => e
1082       report_problem("error getting #{feed.url}", e, m)
1083       return nil
1084     end
1085     debug "fetched #{feed}"
1086     unless xml
1087       report_problem("reading feed #{feed} failed", nil, m)
1088       return nil
1089     end
1090     # Ok, 0.9 feeds are not supported, maybe because
1091     # Netscape happily removed the DTD. So what we do is just to
1092     # reassign the 0.9 RDFs to 1.0, and hope it goes right.
1093     xml.gsub!("xmlns=\"http://my.netscape.com/rdf/simple/0.9/\"",
1094               "xmlns=\"http://purl.org/rss/1.0/\"")
1095     # make sure the parser doesn't double-convert in case the feed is not UTF-8
1096     xml.sub!(/<\?xml (.*?)\?>/) do |match|
1097       if /\bencoding=(['"])(.*?)\1/.match(match)
1098         match.sub!(/\bencoding=(['"])(?:.*?)\1/,'encoding="UTF-8"')
1099       end
1100       match
1101     end
1102     feed.mutex.synchronize do
1103       feed.xml = xml
1104     end
1105     return true
1106   end
1107
1108   def parseRss(feed, m=nil)
1109     return nil unless feed.xml
1110     feed.mutex.synchronize do
1111       xml = feed.xml
1112       begin
1113         ## do validate parse
1114         rss = RSS::Parser.parse(xml)
1115         debug "parsed and validated #{feed}"
1116       rescue RSS::InvalidRSSError
1117         ## do non validate parse for invalid RSS 1.0
1118         begin
1119           rss = RSS::Parser.parse(xml, false)
1120           debug "parsed but not validated #{feed}"
1121         rescue RSS::Error => e
1122           report_problem("parsing rss stream failed, whoops =(", e, m)
1123           return nil
1124         end
1125       rescue RSS::Error => e
1126         report_problem("parsing rss stream failed, oioi", e, m)
1127         return nil
1128       rescue => e
1129         report_problem("processing error occured, sorry =(", e, m)
1130         return nil
1131       end
1132       items = []
1133       if rss.nil?
1134         if xml.match(/xmlns\s*=\s*(['"])http:\/\/www.w3.org\/2005\/Atom\1/) and not defined?(RSS::Atom)
1135           report_problem("#{feed.handle} @ #{feed.url} looks like an Atom feed, but your Ruby/RSS library doesn't seem to support it. Consider getting the latest version from http://raa.ruby-lang.org/project/rss/", nil, m)
1136         else
1137           report_problem("#{feed.handle} @ #{feed.url} doesn't seem to contain an RSS or Atom feed I can read", nil, m)
1138         end
1139         return nil
1140       else
1141         begin
1142           rss.output_encoding = 'UTF-8'
1143         rescue RSS::UnknownConvertMethod => e
1144           report_problem("bah! something went wrong =(", e, m)
1145           return nil
1146         end
1147         if rss.respond_to? :channel
1148           rss.channel.title ||= "(?)"
1149           title = rss.channel.title
1150         else
1151           title = rss.title.content
1152         end
1153         rss.items.each do |item|
1154           item.title ||= "(?)"
1155           items << item
1156         end
1157       end
1158
1159       if items.empty?
1160         report_problem("no items found in the feed, maybe try weed?", e, m)
1161         return nil
1162       end
1163       feed.title = title.strip
1164       feed.items = items
1165       return true
1166     end
1167   end
1168 end
1169
1170 plugin = RSSFeedsPlugin.new
1171
1172 plugin.default_auth( 'edit', false )
1173 plugin.default_auth( 'edit:add', true)
1174
1175 plugin.map 'rss show :handle :limit',
1176   :action => 'show_rss',
1177   :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
1178   :defaults => {:limit => 5}
1179 plugin.map 'rss list :handle',
1180   :action => 'list_rss',
1181   :defaults => {:handle => nil}
1182 plugin.map 'rss watched :handle [in :chan]',
1183   :action => 'watched_rss',
1184   :defaults => {:handle => nil}
1185 plugin.map 'rss who watches :handle',
1186   :action => 'who_watches',
1187   :defaults => {:handle => nil}
1188 plugin.map 'rss add :handle :url :type',
1189   :action => 'add_rss',
1190   :auth_path => 'edit',
1191   :defaults => {:type => nil}
1192 plugin.map 'rss change :what of :handle to :new',
1193   :action => 'change_rss',
1194   :auth_path => 'edit',
1195   :requirements => { :what => /handle|url|format|type|refresh/ }
1196 plugin.map 'rss change :what for :handle to :new',
1197   :action => 'change_rss',
1198   :auth_path => 'edit',
1199   :requirements => { :what => /handle|url|format|type|refesh/ }
1200 plugin.map 'rss del :handle',
1201   :auth_path => 'edit:rm!',
1202   :action => 'del_rss'
1203 plugin.map 'rss delete :handle',
1204   :auth_path => 'edit:rm!',
1205   :action => 'del_rss'
1206 plugin.map 'rss rm :handle',
1207   :auth_path => 'edit:rm!',
1208   :action => 'del_rss'
1209 plugin.map 'rss replace :handle :url :type',
1210   :auth_path => 'edit',
1211   :action => 'replace_rss',
1212   :defaults => {:type => nil}
1213 plugin.map 'rss forcereplace :handle :url :type',
1214   :auth_path => 'edit',
1215   :action => 'forcereplace_rss',
1216   :defaults => {:type => nil}
1217 plugin.map 'rss watch :handle [in :chan]',
1218   :action => 'watch_rss',
1219   :defaults => {:url => nil, :type => nil}
1220 plugin.map 'rss watch :handle :url :type [in :chan]',
1221   :action => 'watch_rss',
1222   :defaults => {:url => nil, :type => nil}
1223 plugin.map 'rss unwatch :handle [in :chan]',
1224   :action => 'unwatch_rss'
1225 plugin.map 'rss rmwatch :handle [in :chan]',
1226   :action => 'unwatch_rss'
1227 plugin.map 'rss rewatch [:handle] [:delay]',
1228   :action => 'rewatch_rss'
1229 plugin.map 'rss types',
1230   :action => 'rss_types'