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