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