]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/utils.rb
namespaces: move rbot-specific classes and modules from Irc::* to Irc::Bot::*
[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' => 'u',
39     'copy' => '(c)',
40     'trade' => '(tm)',
41     'reg' => '(R)',
42     '#174' => '(R)',
43     '#8220' => '"',
44     '#8221' => '"',
45     '#8212' => '--',
46     '#39' => '\'',
47     'amp' => '&',
48     'lt' => '<',
49     'gt' => '>',
50     'hellip' => '...',
51     'nbsp' => ' ',
52 =begin
53     # extras codes, for future use...
54     'zwnj' => '&#8204;',
55     'aring' => '\xe5',
56     'gt' => '>',
57     'yen' => '\xa5',
58     'ograve' => '\xf2',
59     'Chi' => '&#935;',
60     'bull' => '&#8226;',
61     'Egrave' => '\xc8',
62     'Ntilde' => '\xd1',
63     'upsih' => '&#978;',
64     'Yacute' => '\xdd',
65     'asymp' => '&#8776;',
66     'radic' => '&#8730;',
67     'otimes' => '&#8855;',
68     'nabla' => '&#8711;',
69     'aelig' => '\xe6',
70     'oelig' => '&#339;',
71     'equiv' => '&#8801;',
72     'Psi' => '&#936;',
73     'auml' => '\xe4',
74     'circ' => '&#710;',
75     'Acirc' => '\xc2',
76     'Epsilon' => '&#917;',
77     'Yuml' => '&#376;',
78     'Eta' => '&#919;',
79     'Icirc' => '\xce',
80     'Upsilon' => '&#933;',
81     'ndash' => '&#8211;',
82     'there4' => '&#8756;',
83     'Prime' => '&#8243;',
84     'prime' => '&#8242;',
85     'psi' => '&#968;',
86     'Kappa' => '&#922;',
87     'rsaquo' => '&#8250;',
88     'Tau' => '&#932;',
89     'darr' => '&#8595;',
90     'ocirc' => '\xf4',
91     'lrm' => '&#8206;',
92     'zwj' => '&#8205;',
93     'cedil' => '\xb8',
94     'Ecirc' => '\xca',
95     'not' => '\xac',
96     'AElig' => '\xc6',
97     'oslash' => '\xf8',
98     'acute' => '\xb4',
99     'lceil' => '&#8968;',
100     'shy' => '\xad',
101     'rdquo' => '&#8221;',
102     'ge' => '&#8805;',
103     'Igrave' => '\xcc',
104     'Ograve' => '\xd2',
105     'euro' => '&#8364;',
106     'dArr' => '&#8659;',
107     'sdot' => '&#8901;',
108     'nbsp' => '\xa0',
109     'lfloor' => '&#8970;',
110     'lArr' => '&#8656;',
111     'Auml' => '\xc4',
112     'larr' => '&#8592;',
113     'Atilde' => '\xc3',
114     'Otilde' => '\xd5',
115     'szlig' => '\xdf',
116     'clubs' => '&#9827;',
117     'diams' => '&#9830;',
118     'agrave' => '\xe0',
119     'Ocirc' => '\xd4',
120     'Iota' => '&#921;',
121     'Theta' => '&#920;',
122     'Pi' => '&#928;',
123     'OElig' => '&#338;',
124     'Scaron' => '&#352;',
125     'frac14' => '\xbc',
126     'egrave' => '\xe8',
127     'sub' => '&#8834;',
128     'iexcl' => '\xa1',
129     'frac12' => '\xbd',
130     'sbquo' => '&#8218;',
131     'ordf' => '\xaa',
132     'sum' => '&#8721;',
133     'prop' => '&#8733;',
134     'Uuml' => '\xdc',
135     'ntilde' => '\xf1',
136     'sup' => '&#8835;',
137     'theta' => '&#952;',
138     'prod' => '&#8719;',
139     'nsub' => '&#8836;',
140     'hArr' => '&#8660;',
141     'rlm' => '&#8207;',
142     'THORN' => '\xde',
143     'infin' => '&#8734;',
144     'yuml' => '\xff',
145     'Mu' => '&#924;',
146     'le' => '&#8804;',
147     'Eacute' => '\xc9',
148     'thinsp' => '&#8201;',
149     'ecirc' => '\xea',
150     'bdquo' => '&#8222;',
151     'Sigma' => '&#931;',
152     'fnof' => '&#402;',
153     'Aring' => '\xc5',
154     'tilde' => '&#732;',
155     'frac34' => '\xbe',
156     'emsp' => '&#8195;',
157     'mdash' => '&#8212;',
158     'uarr' => '&#8593;',
159     'permil' => '&#8240;',
160     'Ugrave' => '\xd9',
161     'rarr' => '&#8594;',
162     'Agrave' => '\xc0',
163     'chi' => '&#967;',
164     'forall' => '&#8704;',
165     'eth' => '\xf0',
166     'rceil' => '&#8969;',
167     'iuml' => '\xef',
168     'gamma' => '&#947;',
169     'lambda' => '&#955;',
170     'harr' => '&#8596;',
171     'rang' => '&#9002;',
172     'xi' => '&#958;',
173     'dagger' => '&#8224;',
174     'divide' => '\xf7',
175     'Ouml' => '\xd6',
176     'image' => '&#8465;',
177     'alefsym' => '&#8501;',
178     'igrave' => '\xec',
179     'otilde' => '\xf5',
180     'Oacute' => '\xd3',
181     'sube' => '&#8838;',
182     'alpha' => '&#945;',
183     'frasl' => '&#8260;',
184     'ETH' => '\xd0',
185     'lowast' => '&#8727;',
186     'Nu' => '&#925;',
187     'plusmn' => '\xb1',
188     'Euml' => '\xcb',
189     'real' => '&#8476;',
190     'sup1' => '\xb9',
191     'sup2' => '\xb2',
192     'sup3' => '\xb3',
193     'Oslash' => '\xd8',
194     'Aacute' => '\xc1',
195     'cent' => '\xa2',
196     'oline' => '&#8254;',
197     'Beta' => '&#914;',
198     'perp' => '&#8869;',
199     'Delta' => '&#916;',
200     'loz' => '&#9674;',
201     'pi' => '&#960;',
202     'iota' => '&#953;',
203     'empty' => '&#8709;',
204     'euml' => '\xeb',
205     'brvbar' => '\xa6',
206     'iacute' => '\xed',
207     'para' => '\xb6',
208     'micro' => '\xb5',
209     'cup' => '&#8746;',
210     'weierp' => '&#8472;',
211     'uuml' => '\xfc',
212     'part' => '&#8706;',
213     'icirc' => '\xee',
214     'delta' => '&#948;',
215     'omicron' => '&#959;',
216     'upsilon' => '&#965;',
217     'Iuml' => '\xcf',
218     'Lambda' => '&#923;',
219     'Xi' => '&#926;',
220     'kappa' => '&#954;',
221     'ccedil' => '\xe7',
222     'Ucirc' => '\xdb',
223     'cap' => '&#8745;',
224     'mu' => '&#956;',
225     'scaron' => '&#353;',
226     'lsquo' => '&#8216;',
227     'isin' => '&#8712;',
228     'Zeta' => '&#918;',
229     'supe' => '&#8839;',
230     'deg' => '\xb0',
231     'and' => '&#8743;',
232     'tau' => '&#964;',
233     'pound' => '\xa3',
234     'hellip' => '&#8230;',
235     'curren' => '\xa4',
236     'int' => '&#8747;',
237     'ucirc' => '\xfb',
238     'rfloor' => '&#8971;',
239     'ensp' => '&#8194;',
240     'crarr' => '&#8629;',
241     'ugrave' => '\xf9',
242     'notin' => '&#8713;',
243     'exist' => '&#8707;',
244     'uArr' => '&#8657;',
245     'cong' => '&#8773;',
246     'Dagger' => '&#8225;',
247     'oplus' => '&#8853;',
248     'times' => '\xd7',
249     'atilde' => '\xe3',
250     'piv' => '&#982;',
251     'ni' => '&#8715;',
252     'Phi' => '&#934;',
253     'lsaquo' => '&#8249;',
254     'Uacute' => '\xda',
255     'Omicron' => '&#927;',
256     'ang' => '&#8736;',
257     'ne' => '&#8800;',
258     'iquest' => '\xbf',
259     'eta' => '&#951;',
260     'yacute' => '\xfd',
261     'Rho' => '&#929;',
262     'uacute' => '\xfa',
263     'Alpha' => '&#913;',
264     'zeta' => '&#950;',
265     'Omega' => '&#937;',
266     'nu' => '&#957;',
267     'sim' => '&#8764;',
268     'sect' => '\xa7',
269     'phi' => '&#966;',
270     'sigmaf' => '&#962;',
271     'macr' => '\xaf',
272     'minus' => '&#8722;',
273     'Ccedil' => '\xc7',
274     'ordm' => '\xba',
275     'epsilon' => '&#949;',
276     'beta' => '&#946;',
277     'rArr' => '&#8658;',
278     'rho' => '&#961;',
279     'aacute' => '\xe1',
280     'eacute' => '\xe9',
281     'omega' => '&#969;',
282     'middot' => '\xb7',
283     'Gamma' => '&#915;',
284     'Iacute' => '\xcd',
285     'lang' => '&#9001;',
286     'spades' => '&#9824;',
287     'rsquo' => '&#8217;',
288     'uml' => '\xa8',
289     'thorn' => '\xfe',
290     'ouml' => '\xf6',
291     'thetasym' => '&#977;',
292     'or' => '&#8744;',
293     'raquo' => '\xbb',
294     'acirc' => '\xe2',
295     'ldquo' => '&#8220;',
296     'hearts' => '&#9829;',
297     'sigma' => '&#963;',
298     'oacute' => '\xf3',
299 =end
300         }
301       end
302     end
303   end
304 end
305
306 begin
307   require 'htmlentities'
308 rescue LoadError
309   gems = nil
310   begin
311     gems = require 'rubygems'
312   rescue LoadError
313     gems = false
314   end
315   if gems
316     retry
317   else
318     module ::Irc
319       module Utils
320         # define some regular expressions to be used for first_html_par
321
322         # H1, H2, etc
323         HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
324         # A paragraph
325         PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
326
327         # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
328         # to mark actual text
329         AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
330
331         # At worst, we can try stuff which is comprised between two <br>
332         AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
333       end
334     end
335   end
336 end
337
338 module ::Irc
339
340   # miscellaneous useful functions
341   module Utils
342     @@bot = nil unless defined? @@bot
343     @@safe_save_dir = nil unless defined?(@@safe_save_dir)
344
345     def Utils.bot
346       @@bot
347     end
348
349     def Utils.bot=(b)
350       debug "initializing utils"
351       @@bot = b
352       @@safe_save_dir = "#{@@bot.botclass}/safe_save"
353     end
354
355
356     SEC_PER_MIN = 60
357     SEC_PER_HR = SEC_PER_MIN * 60
358     SEC_PER_DAY = SEC_PER_HR * 24
359     SEC_PER_MNTH = SEC_PER_DAY * 30
360     SEC_PER_YR = SEC_PER_MNTH * 12
361
362     def Utils.secs_to_string_case(array, var, string, plural)
363       case var
364       when 1
365         array << "1 #{string}"
366       else
367         array << "#{var} #{plural}"
368       end
369     end
370
371     # turn a number of seconds into a human readable string, e.g
372     # 2 days, 3 hours, 18 minutes, 10 seconds
373     def Utils.secs_to_string(secs)
374       ret = []
375       years, secs = secs.divmod SEC_PER_YR
376       secs_to_string_case(ret, years, _("year"), _("years")) if years > 0
377       months, secs = secs.divmod SEC_PER_MNTH
378       secs_to_string_case(ret, months, _("month"), _("months")) if months > 0
379       days, secs = secs.divmod SEC_PER_DAY
380       secs_to_string_case(ret, days, _("day"), _("days")) if days > 0
381       hours, secs = secs.divmod SEC_PER_HR
382       secs_to_string_case(ret, hours, _("hour"), _("hours")) if hours > 0
383       mins, secs = secs.divmod SEC_PER_MIN
384       secs_to_string_case(ret, mins, _("minute"), _("minutes")) if mins > 0
385       secs = secs.to_i
386       secs_to_string_case(ret, secs, _("second"), _("seconds")) if secs > 0 or ret.empty?
387       case ret.length
388       when 0
389         raise "Empty ret array!"
390       when 1
391         return ret.to_s
392       else
393         return [ret[0, ret.length-1].join(", ") , ret[-1]].join(_(" and "))
394       end
395     end
396
397
398     def Utils.safe_exec(command, *args)
399       IO.popen("-") {|p|
400         if(p)
401           return p.readlines.join("\n")
402         else
403           begin
404             $stderr.reopen($stdout)
405             exec(command, *args)
406           rescue Exception => e
407             puts "exec of #{command} led to exception: #{e.pretty_inspect}"
408             Kernel::exit! 0
409           end
410           puts "exec of #{command} failed"
411           Kernel::exit! 0
412         end
413       }
414     end
415
416
417     def Utils.safe_save(file)
418       raise 'No safe save directory defined!' if @@safe_save_dir.nil?
419       basename = File.basename(file)
420       temp = Tempfile.new(basename,@@safe_save_dir)
421       temp.binmode
422       yield temp if block_given?
423       temp.close
424       File.rename(temp.path, file)
425     end
426
427
428     def Utils.decode_html_entities(str)
429       if defined? ::HTMLEntities
430         return HTMLEntities.decode_entities(str)
431       else
432         str.gsub(/(&(.+?);)/) {
433           symbol = $2
434           # remove the 0-paddng from unicode integers
435           if symbol =~ /#(.+)/
436             symbol = "##{$1.to_i.to_s}"
437           end
438
439           # output the symbol's irc-translated character, or a * if it's unknown
440           UNESCAPE_TABLE[symbol] || [symbol[/\d+/].to_i].pack("U") rescue '*'
441         }
442       end
443     end
444
445     # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
446     # If possible, grab the one after the first heading
447     #
448     # It is possible to pass some options to determine how the stripping
449     # occurs. Currently supported options are
450     #   * :strip => Regex or String to strip at the beginning of the obtained
451     #               text
452     #   * :min_spaces => Minimum number of spaces a paragraph should have
453     #
454     def Utils.ircify_first_html_par(xml_org, opts={})
455       if defined? ::Hpricot
456         Utils.ircify_first_html_par_wh(xml_org, opts)
457       else
458         Utils.ircify_first_html_par_woh(xml_org, opts)
459       end
460     end
461
462     # with hpricot
463     def Utils.ircify_first_html_par_wh(xml_org, opts={})
464       doc = Hpricot(xml_org)
465
466       # Strip styles and scripts
467       (doc/"style|script").remove
468
469       debug doc.inspect
470
471       strip = opts[:strip]
472       strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
473
474       min_spaces = opts[:min_spaces] || 8
475       min_spaces = 0 if min_spaces < 0
476
477       txt = String.new
478
479       h = %w{h1 h2 h3 h4 h5 h6}
480       p = %w{p}
481       ar = []
482       h.each { |hx|
483         p.each { |px|
484           ar << "#{hx}~#{px}"
485         }
486       }
487       h_p_css = ar.join("|")
488       debug "css search: #{h_p_css}"
489
490       pre_h = pars = by_span = nil
491
492       while true
493         debug "Minimum number of spaces: #{min_spaces}"
494
495         # Initial attempt: <p> that follows <h\d>
496         pre_h = doc/h_p_css if pre_h.nil?
497         debug "Hx: found: #{pre_h.pretty_inspect}"
498         pre_h.each { |p|
499           debug p
500           txt = p.to_html.ircify_html
501           txt.sub!(strip, '') if strip
502           debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
503           break unless txt.empty? or txt.count(" ") < min_spaces
504         }
505
506         return txt unless txt.empty? or txt.count(" ") < min_spaces
507
508         # Second natural attempt: just get any <p>
509         pars = doc/"p" if pars.nil?
510         debug "par: found: #{pars.pretty_inspect}"
511         pars.each { |p|
512           debug p
513           txt = p.to_html.ircify_html
514           txt.sub!(strip, '') if strip
515           debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
516           break unless txt.empty? or txt.count(" ") < min_spaces
517         }
518
519         return txt unless txt.empty? or txt.count(" ") < min_spaces
520
521         # Nothing yet ... let's get drastic: we look for non-par elements too,
522         # but only for those that match something that we know is likely to
523         # contain text
524
525         # Some blogging and forum platforms use spans or divs with a 'body' or
526         # 'message' or 'text' in their class to mark actual text. Since we want
527         # the class match to be partial and case insensitive, we collect
528         # the common elements that may have this class and then filter out those
529         # we don't need
530         if by_span.nil?
531           by_span = Hpricot::Elements[]
532           pre_pars = doc/"div|span|td|tr|tbody|table"
533           pre_pars.each { |el|
534             by_span.push el if el.class =~ /body|message|text/i
535           }
536           debug "other \#1: found: #{by_span.pretty_inspect}"
537         end
538
539         by_span.each { |p|
540           debug p
541           txt = p.to_html.ircify_html
542           txt.sub!(strip, '') if strip
543           debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
544           break unless txt.empty? or txt.count(" ") < min_spaces
545         }
546
547         return txt unless txt.empty? or txt.count(" ") < min_spaces
548
549         # At worst, we can try stuff which is comprised between two <br>
550         # TODO
551
552         debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
553         return txt unless txt.count(" ") < min_spaces
554         break if min_spaces == 0
555         min_spaces /= 2
556       end
557     end
558
559     # without hpricot
560     def Utils.ircify_first_html_par_woh(xml_org, opts={})
561       xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
562
563       strip = opts[:strip]
564       strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
565
566       min_spaces = opts[:min_spaces] || 8
567       min_spaces = 0 if min_spaces < 0
568
569       txt = String.new
570
571       while true
572         debug "Minimum number of spaces: #{min_spaces}"
573         header_found = xml.match(HX_REGEX)
574         if header_found
575           header_found = $'
576           while txt.empty? or txt.count(" ") < min_spaces
577             candidate = header_found[PAR_REGEX]
578             break unless candidate
579             txt = candidate.ircify_html
580             header_found = $'
581             txt.sub!(strip, '') if strip
582             debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
583           end
584         end
585
586         return txt unless txt.empty? or txt.count(" ") < min_spaces
587
588         # If we haven't found a first par yet, try to get it from the whole
589         # document
590         header_found = xml
591         while txt.empty? or txt.count(" ") < min_spaces
592           candidate = header_found[PAR_REGEX]
593           break unless candidate
594           txt = candidate.ircify_html
595           header_found = $'
596           txt.sub!(strip, '') if strip
597           debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
598         end
599
600         return txt unless txt.empty? or txt.count(" ") < min_spaces
601
602         # Nothing yet ... let's get drastic: we look for non-par elements too,
603         # but only for those that match something that we know is likely to
604         # contain text
605
606         # Attempt #1
607         header_found = xml
608         while txt.empty? or txt.count(" ") < min_spaces
609           candidate = header_found[AFTER_PAR1_REGEX]
610           break unless candidate
611           txt = candidate.ircify_html
612           header_found = $'
613           txt.sub!(strip, '') if strip
614           debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
615         end
616
617         return txt unless txt.empty? or txt.count(" ") < min_spaces
618
619         # Attempt #2
620         header_found = xml
621         while txt.empty? or txt.count(" ") < min_spaces
622           candidate = header_found[AFTER_PAR2_REGEX]
623           break unless candidate
624           txt = candidate.ircify_html
625           header_found = $'
626           txt.sub!(strip, '') if strip
627           debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
628         end
629
630         debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
631         return txt unless txt.count(" ") < min_spaces
632         break if min_spaces == 0
633         min_spaces /= 2
634       end
635     end
636
637     # Get the first pars of the first _count_ _urls_.
638     # The pages are downloaded using the bot httputil service.
639     # Returns an array of the first paragraphs fetched.
640     # If (optional) _opts_ :message is specified, those paragraphs are
641     # echoed as replies to the IRC message passed as _opts_ :message
642     #
643     def Utils.get_first_pars(urls, count, opts={})
644       idx = 0
645       msg = opts[:message]
646       retval = Array.new
647       while count > 0 and urls.length > 0
648         url = urls.shift
649         idx += 1
650
651         # FIXME what happens if some big file is returned? We should share
652         # code with the url plugin to only retrieve partial file content!
653         xml = self.bot.httputil.get(url)
654         if xml.nil?
655           debug "Unable to retrieve #{url}"
656           next
657         end
658         par = Utils.ircify_first_html_par(xml, opts)
659         if par.empty?
660           debug "No first par found\n#{xml}"
661           # FIXME only do this if the 'url' plugin is loaded
662           # TODO even better, put the code here
663           # par = @bot.plugins['url'].get_title_from_html(xml)
664           if par.empty?
665             retval.push(nil)
666             next
667           end
668         end
669         msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
670         count -=1
671         retval.push(par)
672       end
673       return retval
674     end
675
676   end
677 end
678
679 Irc::Utils.bot = Irc::Bot::Plugins.manager.bot