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