]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/utils.rb
Licensing uniformity: dual-license rbot core under MIT+acknowledgement and GPLv2
[user/henk/code/ruby/rbot.git] / lib / rbot / core / utils / utils.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: rbot utilities provider
5 #
6 # Author:: Tom Gilbert <tom@linuxbrit.co.uk>
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
8 #
9 # TODO some of these Utils should be rewritten as extensions to the approriate
10 # standard Ruby classes and accordingly be moved to extends.rb
11
12 require 'tempfile'
13 require 'set'
14
15 # Try to load htmlentities, fall back to an HTML escape table.
16 begin
17   require 'htmlentities'
18 rescue LoadError
19   gems = nil
20   begin
21     gems = require 'rubygems'
22   rescue LoadError
23     gems = false
24   end
25   if gems
26     retry
27   else
28     module ::Irc
29       module Utils
30         UNESCAPE_TABLE = {
31     'laquo' => '«',
32     'raquo' => '»',
33     'quot' => '"',
34     'apos' => '\'',
35     'micro' => 'µ',
36     'copy' => '©',
37     'trade' => '™',
38     'reg' => '®',
39     'amp' => '&',
40     'lt' => '<',
41     'gt' => '>',
42     'hellip' => '…',
43     'nbsp' => ' ',
44     'Agrave' => 'À',
45     'Aacute' => 'Á',
46     'Acirc' => 'Â',
47     'Atilde' => 'Ã',
48     'Auml' => 'Ä',
49     'Aring' => 'Å',
50     'AElig' => 'Æ',
51     'OElig' => 'Œ',
52     'Ccedil' => 'Ç',
53     'Egrave' => 'È',
54     'Eacute' => 'É',
55     'Ecirc' => 'Ê',
56     'Euml' => 'Ë',
57     'Igrave' => 'Ì',
58     'Iacute' => 'Í',
59     'Icirc' => 'Î',
60     'Iuml' => 'Ï',
61     'ETH' => 'Ð',
62     'Ntilde' => 'Ñ',
63     'Ograve' => 'Ò',
64     'Oacute' => 'Ó',
65     'Ocirc' => 'Ô',
66     'Otilde' => 'Õ',
67     'Ouml' => 'Ö',
68     'Oslash' => 'Ø',
69     'Ugrave' => 'Ù',
70     'Uacute' => 'Ú',
71     'Ucirc' => 'Û',
72     'Uuml' => 'Ü',
73     'Yacute' => 'Ý',
74     'THORN' => 'Þ',
75     'szlig' => 'ß',
76     'agrave' => 'à',
77     'aacute' => 'á',
78     'acirc' => 'â',
79     'atilde' => 'ã',
80     'auml' => 'ä',
81     'aring' => 'å',
82     'aelig' => 'æ',
83     'oelig' => 'œ',
84     'ccedil' => 'ç',
85     'egrave' => 'è',
86     'eacute' => 'é',
87     'ecirc' => 'ê',
88     'euml' => 'ë',
89     'igrave' => 'ì',
90     'iacute' => 'í',
91     'icirc' => 'î',
92     'iuml' => 'ï',
93     'eth' => 'ð',
94     'ntilde' => 'ñ',
95     'ograve' => 'ò',
96     'oacute' => 'ó',
97     'ocirc' => 'ô',
98     'otilde' => 'õ',
99     'ouml' => 'ö',
100     'oslash' => 'ø',
101     'ugrave' => 'ù',
102     'uacute' => 'ú',
103     'ucirc' => 'û',
104     'uuml' => 'ü',
105     'yacute' => 'ý',
106     'thorn' => 'þ',
107     'yuml' => 'ÿ'
108         }
109       end
110     end
111   end
112 end
113
114 begin
115   require 'hpricot'
116   module ::Irc
117     module Utils
118       AFTER_PAR_PATH = /^(?:div|span)$/
119       AFTER_PAR_EX = /^(?:td|tr|tbody|table)$/
120       AFTER_PAR_CLASS = /body|message|text/i
121     end
122   end
123 rescue LoadError
124   gems = nil
125   begin
126     gems = require 'rubygems'
127   rescue LoadError
128     gems = false
129   end
130   if gems
131     retry
132   else
133     module ::Irc
134       module Utils
135         # Some regular expressions to manage HTML data
136
137         # Title
138         TITLE_REGEX = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
139
140         # H1, H2, etc
141         HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
142         # A paragraph
143         PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
144
145         # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
146         # to mark actual text
147         AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
148
149         # At worst, we can try stuff which is comprised between two <br>
150         AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
151       end
152     end
153   end
154 end
155
156 module ::Irc
157
158   # Miscellaneous useful functions
159   module Utils
160     @@bot = nil unless defined? @@bot
161     @@safe_save_dir = nil unless defined?(@@safe_save_dir)
162
163     # The bot instance
164     def Utils.bot
165       @@bot
166     end
167
168     # Set up some Utils routines which depend on the associated bot.
169     def Utils.bot=(b)
170       debug "initializing utils"
171       @@bot = b
172       @@safe_save_dir = "#{@@bot.botclass}/safe_save"
173     end
174
175
176     # Seconds per minute
177     SEC_PER_MIN = 60
178     # Seconds per hour
179     SEC_PER_HR = SEC_PER_MIN * 60
180     # Seconds per day
181     SEC_PER_DAY = SEC_PER_HR * 24
182     # Seconds per (30-day) month
183     SEC_PER_MNTH = SEC_PER_DAY * 30
184     # Second per (30*12 = 360 day) year
185     SEC_PER_YR = SEC_PER_MNTH * 12
186
187     # Auxiliary method needed by Utils.secs_to_string
188     def Utils.secs_to_string_case(array, var, string, plural)
189       case var
190       when 1
191         array << "1 #{string}"
192       else
193         array << "#{var} #{plural}"
194       end
195     end
196
197     # Turn a number of seconds into a human readable string, e.g
198     # 2 days, 3 hours, 18 minutes and 10 seconds
199     def Utils.secs_to_string(secs)
200       ret = []
201       years, secs = secs.divmod SEC_PER_YR
202       secs_to_string_case(ret, years, _("year"), _("years")) if years > 0
203       months, secs = secs.divmod SEC_PER_MNTH
204       secs_to_string_case(ret, months, _("month"), _("months")) if months > 0
205       days, secs = secs.divmod SEC_PER_DAY
206       secs_to_string_case(ret, days, _("day"), _("days")) if days > 0
207       hours, secs = secs.divmod SEC_PER_HR
208       secs_to_string_case(ret, hours, _("hour"), _("hours")) if hours > 0
209       mins, secs = secs.divmod SEC_PER_MIN
210       secs_to_string_case(ret, mins, _("minute"), _("minutes")) if mins > 0
211       secs = secs.to_i
212       secs_to_string_case(ret, secs, _("second"), _("seconds")) if secs > 0 or ret.empty?
213       case ret.length
214       when 0
215         raise "Empty ret array!"
216       when 1
217         return ret.to_s
218       else
219         return [ret[0, ret.length-1].join(", ") , ret[-1]].join(_(" and "))
220       end
221     end
222
223     # Turn a number of seconds into a hours:minutes:seconds e.g.
224     # 3:18:10 or 5'12" or 7s
225     #
226     def Utils.secs_to_short(seconds)
227       secs = seconds.to_i # make sure it's an integer
228       mins, secs = secs.divmod 60
229       hours, mins = mins.divmod 60
230       if hours > 0
231         return ("%s:%s:%s" % [hours, mins, secs])
232       elsif mins > 0
233         return ("%s'%s\"" % [mins, secs])
234       else
235         return ("%ss" % [secs])
236       end
237     end
238
239
240     # Execute an external program, returning a String obtained by redirecting
241     # the program's standards errors and output 
242     #
243     def Utils.safe_exec(command, *args)
244       IO.popen("-") { |p|
245         if p
246           return p.readlines.join("\n")
247         else
248           begin
249             $stderr.reopen($stdout)
250             exec(command, *args)
251           rescue Exception => e
252             puts "exec of #{command} led to exception: #{e.pretty_inspect}"
253             Kernel::exit! 0
254           end
255           puts "exec of #{command} failed"
256           Kernel::exit! 0
257         end
258       }
259     end
260
261
262     # Safely (atomically) save to _file_, by passing a tempfile to the block
263     # and then moving the tempfile to its final location when done.
264     #
265     # call-seq: Utils.safe_save(file, &block)
266     #
267     def Utils.safe_save(file)
268       raise 'No safe save directory defined!' if @@safe_save_dir.nil?
269       basename = File.basename(file)
270       temp = Tempfile.new(basename,@@safe_save_dir)
271       temp.binmode
272       yield temp if block_given?
273       temp.close
274       File.rename(temp.path, file)
275     end
276
277
278     # Decode HTML entities in the String _str_, using HTMLEntities if the
279     # package was found, or UNESCAPE_TABLE otherwise.
280     #
281     def Utils.decode_html_entities(str)
282       if defined? ::HTMLEntities
283         return HTMLEntities.decode_entities(str)
284       else
285         str.gsub(/(&(.+?);)/) {
286           symbol = $2
287           # remove the 0-paddng from unicode integers
288           if symbol =~ /^#(\d+)$/
289             symbol = $1.to_i.to_s
290           end
291
292           # output the symbol's irc-translated character, or a * if it's unknown
293           UNESCAPE_TABLE[symbol] || (symbol.match(/^\d+$/) ? [symbol.to_i].pack("U") : '*')
294         }
295       end
296     end
297
298     # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
299     # If possible, grab the one after the first heading
300     #
301     # It is possible to pass some options to determine how the stripping
302     # occurs. Currently supported options are
303     # strip:: Regex or String to strip at the beginning of the obtained
304     #         text
305     # min_spaces:: minimum number of spaces a paragraph should have
306     #
307     def Utils.ircify_first_html_par(xml_org, opts={})
308       if defined? ::Hpricot
309         Utils.ircify_first_html_par_wh(xml_org, opts)
310       else
311         Utils.ircify_first_html_par_woh(xml_org, opts)
312       end
313     end
314
315     # HTML first par grabber using hpricot
316     def Utils.ircify_first_html_par_wh(xml_org, opts={})
317       doc = Hpricot(xml_org)
318
319       # Strip styles and scripts
320       (doc/"style|script").remove
321
322       debug doc
323
324       strip = opts[:strip]
325       strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
326
327       min_spaces = opts[:min_spaces] || 8
328       min_spaces = 0 if min_spaces < 0
329
330       txt = String.new
331
332       pre_h = pars = by_span = nil
333
334       while true
335         debug "Minimum number of spaces: #{min_spaces}"
336
337         # Initial attempt: <p> that follows <h\d>
338         if pre_h.nil?
339           pre_h = Hpricot::Elements[]
340           found_h = false
341           doc.search("*") { |e|
342             next if e.bogusetag?
343             case e.pathname
344             when /^h\d/
345               found_h = true
346             when 'p'
347               pre_h << e if found_h
348             end
349           }
350           debug "Hx: found: #{pre_h.pretty_inspect}"
351         end
352
353         pre_h.each { |p|
354           debug p
355           txt = p.to_html.ircify_html
356           txt.sub!(strip, '') if strip
357           debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
358           break unless txt.empty? or txt.count(" ") < min_spaces
359         }
360
361         return txt unless txt.empty? or txt.count(" ") < min_spaces
362
363         # Second natural attempt: just get any <p>
364         pars = doc/"p" if pars.nil?
365         debug "par: found: #{pars.pretty_inspect}"
366         pars.each { |p|
367           debug p
368           txt = p.to_html.ircify_html
369           txt.sub!(strip, '') if strip
370           debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
371           break unless txt.empty? or txt.count(" ") < min_spaces
372         }
373
374         return txt unless txt.empty? or txt.count(" ") < min_spaces
375
376         # Nothing yet ... let's get drastic: we look for non-par elements too,
377         # but only for those that match something that we know is likely to
378         # contain text
379
380         # Some blogging and forum platforms use spans or divs with a 'body' or
381         # 'message' or 'text' in their class to mark actual text. Since we want
382         # the class match to be partial and case insensitive, we collect
383         # the common elements that may have this class and then filter out those
384         # we don't need. If no divs or spans are found, we'll accept additional
385         # elements too (td, tr, tbody, table).
386         if by_span.nil?
387           by_span = Hpricot::Elements[]
388           extra = Hpricot::Elements[]
389           doc.search("*") { |el|
390             next if el.bogusetag?
391             case el.pathname
392             when AFTER_PAR_PATH
393               by_span.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
394             when AFTER_PAR_EX
395               extra.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
396             end
397           }
398           if by_span.empty? and not extra.empty?
399             by_span.concat extra
400           end
401           debug "other \#1: found: #{by_span.pretty_inspect}"
402         end
403
404         by_span.each { |p|
405           debug p
406           txt = p.to_html.ircify_html
407           txt.sub!(strip, '') if strip
408           debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
409           break unless txt.empty? or txt.count(" ") < min_spaces
410         }
411
412         return txt unless txt.empty? or txt.count(" ") < min_spaces
413
414         # At worst, we can try stuff which is comprised between two <br>
415         # TODO
416
417         debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
418         return txt unless txt.count(" ") < min_spaces
419         break if min_spaces == 0
420         min_spaces /= 2
421       end
422     end
423
424     # HTML first par grabber without hpricot
425     def Utils.ircify_first_html_par_woh(xml_org, opts={})
426       xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
427
428       strip = opts[:strip]
429       strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
430
431       min_spaces = opts[:min_spaces] || 8
432       min_spaces = 0 if min_spaces < 0
433
434       txt = String.new
435
436       while true
437         debug "Minimum number of spaces: #{min_spaces}"
438         header_found = xml.match(HX_REGEX)
439         if header_found
440           header_found = $'
441           while txt.empty? or txt.count(" ") < min_spaces
442             candidate = header_found[PAR_REGEX]
443             break unless candidate
444             txt = candidate.ircify_html
445             header_found = $'
446             txt.sub!(strip, '') if strip
447             debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
448           end
449         end
450
451         return txt unless txt.empty? or txt.count(" ") < min_spaces
452
453         # If we haven't found a first par yet, try to get it from the whole
454         # document
455         header_found = xml
456         while txt.empty? or txt.count(" ") < min_spaces
457           candidate = header_found[PAR_REGEX]
458           break unless candidate
459           txt = candidate.ircify_html
460           header_found = $'
461           txt.sub!(strip, '') if strip
462           debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
463         end
464
465         return txt unless txt.empty? or txt.count(" ") < min_spaces
466
467         # Nothing yet ... let's get drastic: we look for non-par elements too,
468         # but only for those that match something that we know is likely to
469         # contain text
470
471         # Attempt #1
472         header_found = xml
473         while txt.empty? or txt.count(" ") < min_spaces
474           candidate = header_found[AFTER_PAR1_REGEX]
475           break unless candidate
476           txt = candidate.ircify_html
477           header_found = $'
478           txt.sub!(strip, '') if strip
479           debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
480         end
481
482         return txt unless txt.empty? or txt.count(" ") < min_spaces
483
484         # Attempt #2
485         header_found = xml
486         while txt.empty? or txt.count(" ") < min_spaces
487           candidate = header_found[AFTER_PAR2_REGEX]
488           break unless candidate
489           txt = candidate.ircify_html
490           header_found = $'
491           txt.sub!(strip, '') if strip
492           debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
493         end
494
495         debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
496         return txt unless txt.count(" ") < min_spaces
497         break if min_spaces == 0
498         min_spaces /= 2
499       end
500     end
501
502     # This method extracts title, content (first par) and extra
503     # information from the given document _doc_.
504     #
505     # _doc_ can be an URI, a Net::HTTPResponse or a String.
506     #
507     # If _doc_ is a String, only title and content information
508     # are retrieved (if possible), using standard methods.
509     #
510     # If _doc_ is an URI or a Net::HTTPResponse, additional
511     # information is retrieved, and special title/summary
512     # extraction routines are used if possible.
513     #
514     def Utils.get_html_info(doc, opts={})
515       case doc
516       when String
517         Utils.get_string_html_info(doc, opts)
518       when Net::HTTPResponse
519         Utils.get_resp_html_info(doc, opts)
520       when URI
521         ret = DataStream.new
522         @@bot.httputil.get_response(doc) { |resp|
523           ret.replace Utils.get_resp_html_info(resp, opts)
524         }
525         return ret
526       else
527         raise
528       end
529     end
530
531     class ::UrlLinkError < RuntimeError
532     end
533
534     # This method extracts title, content (first par) and extra
535     # information from the given Net::HTTPResponse _resp_.
536     #
537     # Currently, the only accepted options (in _opts_) are
538     # uri_fragment:: the URI fragment of the original request
539     # full_body::    get the whole body instead of
540     #                @@bot.config['http.info_bytes'] bytes only
541     #
542     # Returns a DataStream with the following keys:
543     # text:: the (partial) body
544     # title:: the title of the document (if any)
545     # content:: the first paragraph of the document (if any)
546     # headers::
547     #   the headers of the Net::HTTPResponse. The value is
548     #   a Hash whose keys are lowercase forms of the HTTP
549     #   header fields, and whose values are Arrays.
550     #
551     def Utils.get_resp_html_info(resp, opts={})
552       case resp
553       when Net::HTTPSuccess
554         loc = URI.parse(resp['x-rbot-location'] || resp['location']) rescue nil
555         if loc and loc.fragment and not loc.fragment.empty?
556           opts[:uri_fragment] ||= loc.fragment
557         end
558         ret = DataStream.new(opts.dup)
559         ret[:headers] = resp.to_hash
560         ret[:text] = partial = opts[:full_body] ? resp.body : resp.partial_body(@@bot.config['http.info_bytes'])
561
562         filtered = Utils.try_htmlinfo_filters(ret)
563
564         if filtered
565           return filtered
566         elsif resp['content-type'] =~ /^text\/|(?:x|ht)ml/
567           ret.merge!(Utils.get_string_html_info(partial, opts))
568         end
569         return ret
570       else
571         raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
572       end
573     end
574
575     # This method runs an appropriately-crafted DataStream _ds_ through the
576     # filters in the :htmlinfo filter group, in order. If one of the filters
577     # returns non-nil, its results are merged in _ds_ and returned. Otherwise
578     # nil is returned.
579     #
580     # The input DataStream shuold have the downloaded HTML as primary key
581     # (:text) and possibly a :headers key holding the resonse headers.
582     #
583     def Utils.try_htmlinfo_filters(ds)
584       filters = @@bot.filter_names(:htmlinfo)
585       return nil if filters.empty?
586       cur = nil
587       # TODO filter priority
588       filters.each { |n|
589         debug "testing filter #{n}"
590         cur = @@bot.filter(@@bot.global_filter_name(n, :htmlinfo), ds)
591         debug "returned #{cur.pretty_inspect}"
592         break if cur
593       }
594       return ds.merge(cur) if cur
595     end
596
597     # HTML info filters often need to check if the webpage location
598     # of a passed DataStream _ds_ matches a given Regexp.
599     def Utils.check_location(ds, rx)
600       debug ds[:headers]
601       if h = ds[:headers]
602         loc = [h['x-rbot-location'],h['location']].flatten.grep(rx)
603       end
604       loc ||= []
605       debug loc
606       return loc.empty? ? nil : loc
607     end
608
609     # This method extracts title and content (first par)
610     # from the given HTML or XML document _text_, using
611     # standard methods (String#ircify_html_title,
612     # Utils.ircify_first_html_par)
613     #
614     # Currently, the only accepted option (in _opts_) is
615     # uri_fragment:: the URI fragment of the original request
616     #
617     def Utils.get_string_html_info(text, opts={})
618       debug "getting string html info"
619       txt = text.dup
620       title = txt.ircify_html_title
621       debug opts
622       if frag = opts[:uri_fragment] and not frag.empty?
623         fragreg = /<a\s+(?:[^>]+\s+)?(?:name|id)=["']?#{frag}["']?[^>]*>/im
624         debug fragreg
625         debug txt
626         if txt.match(fragreg)
627           # grab the post-match
628           txt = $'
629         end
630         debug txt
631       end
632       c_opts = opts.dup
633       c_opts[:strip] ||= title
634       content = Utils.ircify_first_html_par(txt, c_opts)
635       content = nil if content.empty?
636       return {:title => title, :content => content}
637     end
638
639     # Get the first pars of the first _count_ _urls_.
640     # The pages are downloaded using the bot httputil service.
641     # Returns an array of the first paragraphs fetched.
642     # If (optional) _opts_ :message is specified, those paragraphs are
643     # echoed as replies to the IRC message passed as _opts_ :message
644     #
645     def Utils.get_first_pars(urls, count, opts={})
646       idx = 0
647       msg = opts[:message]
648       retval = Array.new
649       while count > 0 and urls.length > 0
650         url = urls.shift
651         idx += 1
652
653         begin
654           info = Utils.get_html_info(URI.parse(url), opts)
655
656           par = info[:content]
657           retval.push(par)
658
659           if par
660             msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
661             count -=1
662           end
663         rescue
664           debug "Unable to retrieve #{url}: #{$!}"
665           next
666         end
667       end
668       return retval
669     end
670
671   end
672 end
673
674 Irc::Utils.bot = Irc::Bot::Plugins.manager.bot