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