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