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