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