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