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