]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/utils.rb
0582cd4bc89749e616eb5d92542037ae1a542b28
[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 'hpricot'
308   module ::Irc
309     module Utils
310       AFTER_PAR_PATH = /^(?:div|span|td|tr|tbody|table)$/
311       AFTER_PAR_CLASS = /body|message|text/i
312     end
313   end
314 rescue LoadError
315   gems = nil
316   begin
317     gems = require 'rubygems'
318   rescue LoadError
319     gems = false
320   end
321   if gems
322     retry
323   else
324     module ::Irc
325       module Utils
326         # Some regular expressions to manage HTML data
327
328         # Title
329         TITLE_REGEX = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
330
331         # H1, H2, etc
332         HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
333         # A paragraph
334         PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
335
336         # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
337         # to mark actual text
338         AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
339
340         # At worst, we can try stuff which is comprised between two <br>
341         AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
342       end
343     end
344   end
345 end
346
347 module ::Irc
348
349   # Miscellaneous useful functions
350   module Utils
351     @@bot = nil unless defined? @@bot
352     @@safe_save_dir = nil unless defined?(@@safe_save_dir)
353
354     # The bot instance
355     def Utils.bot
356       @@bot
357     end
358
359     # Set up some Utils routines which depend on the associated bot.
360     def Utils.bot=(b)
361       debug "initializing utils"
362       @@bot = b
363       @@safe_save_dir = "#{@@bot.botclass}/safe_save"
364     end
365
366
367     # Seconds per minute
368     SEC_PER_MIN = 60
369     # Seconds per hour
370     SEC_PER_HR = SEC_PER_MIN * 60
371     # Seconds per day
372     SEC_PER_DAY = SEC_PER_HR * 24
373     # Seconds per (30-day) month
374     SEC_PER_MNTH = SEC_PER_DAY * 30
375     # Second per (30*12 = 360 day) year
376     SEC_PER_YR = SEC_PER_MNTH * 12
377
378     # Auxiliary method needed by Utils.secs_to_string
379     def Utils.secs_to_string_case(array, var, string, plural)
380       case var
381       when 1
382         array << "1 #{string}"
383       else
384         array << "#{var} #{plural}"
385       end
386     end
387
388     # Turn a number of seconds into a human readable string, e.g
389     # 2 days, 3 hours, 18 minutes and 10 seconds
390     def Utils.secs_to_string(secs)
391       ret = []
392       years, secs = secs.divmod SEC_PER_YR
393       secs_to_string_case(ret, years, _("year"), _("years")) if years > 0
394       months, secs = secs.divmod SEC_PER_MNTH
395       secs_to_string_case(ret, months, _("month"), _("months")) if months > 0
396       days, secs = secs.divmod SEC_PER_DAY
397       secs_to_string_case(ret, days, _("day"), _("days")) if days > 0
398       hours, secs = secs.divmod SEC_PER_HR
399       secs_to_string_case(ret, hours, _("hour"), _("hours")) if hours > 0
400       mins, secs = secs.divmod SEC_PER_MIN
401       secs_to_string_case(ret, mins, _("minute"), _("minutes")) if mins > 0
402       secs = secs.to_i
403       secs_to_string_case(ret, secs, _("second"), _("seconds")) if secs > 0 or ret.empty?
404       case ret.length
405       when 0
406         raise "Empty ret array!"
407       when 1
408         return ret.to_s
409       else
410         return [ret[0, ret.length-1].join(", ") , ret[-1]].join(_(" and "))
411       end
412     end
413
414
415     # Execute an external program, returning a String obtained by redirecting
416     # the program's standards errors and output 
417     #
418     def Utils.safe_exec(command, *args)
419       IO.popen("-") { |p|
420         if p
421           return p.readlines.join("\n")
422         else
423           begin
424             $stderr.reopen($stdout)
425             exec(command, *args)
426           rescue Exception => e
427             puts "exec of #{command} led to exception: #{e.pretty_inspect}"
428             Kernel::exit! 0
429           end
430           puts "exec of #{command} failed"
431           Kernel::exit! 0
432         end
433       }
434     end
435
436
437     # Safely (atomically) save to _file_, by passing a tempfile to the block
438     # and then moving the tempfile to its final location when done.
439     #
440     # call-seq: Utils.safe_save(file, &block)
441     #
442     def Utils.safe_save(file)
443       raise 'No safe save directory defined!' if @@safe_save_dir.nil?
444       basename = File.basename(file)
445       temp = Tempfile.new(basename,@@safe_save_dir)
446       temp.binmode
447       yield temp if block_given?
448       temp.close
449       File.rename(temp.path, file)
450     end
451
452
453     # Decode HTML entities in the String _str_, using HTMLEntities if the
454     # package was found, or UNESCAPE_TABLE otherwise.
455     #
456     def Utils.decode_html_entities(str)
457       if defined? ::HTMLEntities
458         return HTMLEntities.decode_entities(str)
459       else
460         str.gsub(/(&(.+?);)/) {
461           symbol = $2
462           # remove the 0-paddng from unicode integers
463           if symbol =~ /#(.+)/
464             symbol = "##{$1.to_i.to_s}"
465           end
466
467           # output the symbol's irc-translated character, or a * if it's unknown
468           UNESCAPE_TABLE[symbol] || [symbol[/\d+/].to_i].pack("U") rescue '*'
469         }
470       end
471     end
472
473     # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
474     # If possible, grab the one after the first heading
475     #
476     # It is possible to pass some options to determine how the stripping
477     # occurs. Currently supported options are
478     # strip:: Regex or String to strip at the beginning of the obtained
479     #         text
480     # min_spaces:: minimum number of spaces a paragraph should have
481     #
482     def Utils.ircify_first_html_par(xml_org, opts={})
483       if defined? ::Hpricot
484         Utils.ircify_first_html_par_wh(xml_org, opts)
485       else
486         Utils.ircify_first_html_par_woh(xml_org, opts)
487       end
488     end
489
490     # HTML first par grabber using hpricot
491     def Utils.ircify_first_html_par_wh(xml_org, opts={})
492       doc = Hpricot(xml_org)
493
494       # Strip styles and scripts
495       (doc/"style|script").remove
496
497       debug doc
498
499       strip = opts[:strip]
500       strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
501
502       min_spaces = opts[:min_spaces] || 8
503       min_spaces = 0 if min_spaces < 0
504
505       txt = String.new
506
507       pre_h = pars = by_span = nil
508
509       while true
510         debug "Minimum number of spaces: #{min_spaces}"
511
512         # Initial attempt: <p> that follows <h\d>
513         if pre_h.nil?
514           pre_h = Hpricot::Elements[]
515           found_h = false
516           doc.search("*") { |e|
517             next if e.bogusetag?
518             case e.pathname
519             when /^h\d/
520               found_h = true
521             when 'p'
522               pre_h << e if found_h
523             end
524           }
525           debug "Hx: found: #{pre_h.pretty_inspect}"
526         end
527
528         pre_h.each { |p|
529           debug p
530           txt = p.to_html.ircify_html
531           txt.sub!(strip, '') if strip
532           debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
533           break unless txt.empty? or txt.count(" ") < min_spaces
534         }
535
536         return txt unless txt.empty? or txt.count(" ") < min_spaces
537
538         # Second natural attempt: just get any <p>
539         pars = doc/"p" if pars.nil?
540         debug "par: found: #{pars.pretty_inspect}"
541         pars.each { |p|
542           debug p
543           txt = p.to_html.ircify_html
544           txt.sub!(strip, '') if strip
545           debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
546           break unless txt.empty? or txt.count(" ") < min_spaces
547         }
548
549         return txt unless txt.empty? or txt.count(" ") < min_spaces
550
551         # Nothing yet ... let's get drastic: we look for non-par elements too,
552         # but only for those that match something that we know is likely to
553         # contain text
554
555         # Some blogging and forum platforms use spans or divs with a 'body' or
556         # 'message' or 'text' in their class to mark actual text. Since we want
557         # the class match to be partial and case insensitive, we collect
558         # the common elements that may have this class and then filter out those
559         # we don't need
560         if by_span.nil?
561           by_span = Hpricot::Elements[]
562           doc.search("*") { |el|
563             next if el.bogusetag?
564             by_span.push el if el.pathname =~ AFTER_PAR_PATH and (el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS)
565           }
566           debug "other \#1: found: #{by_span.pretty_inspect}"
567         end
568
569         by_span.each { |p|
570           debug p
571           txt = p.to_html.ircify_html
572           txt.sub!(strip, '') if strip
573           debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
574           break unless txt.empty? or txt.count(" ") < min_spaces
575         }
576
577         return txt unless txt.empty? or txt.count(" ") < min_spaces
578
579         # At worst, we can try stuff which is comprised between two <br>
580         # TODO
581
582         debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
583         return txt unless txt.count(" ") < min_spaces
584         break if min_spaces == 0
585         min_spaces /= 2
586       end
587     end
588
589     # HTML first par grabber without hpricot
590     def Utils.ircify_first_html_par_woh(xml_org, opts={})
591       xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
592
593       strip = opts[:strip]
594       strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
595
596       min_spaces = opts[:min_spaces] || 8
597       min_spaces = 0 if min_spaces < 0
598
599       txt = String.new
600
601       while true
602         debug "Minimum number of spaces: #{min_spaces}"
603         header_found = xml.match(HX_REGEX)
604         if header_found
605           header_found = $'
606           while txt.empty? or txt.count(" ") < min_spaces
607             candidate = header_found[PAR_REGEX]
608             break unless candidate
609             txt = candidate.ircify_html
610             header_found = $'
611             txt.sub!(strip, '') if strip
612             debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
613           end
614         end
615
616         return txt unless txt.empty? or txt.count(" ") < min_spaces
617
618         # If we haven't found a first par yet, try to get it from the whole
619         # document
620         header_found = xml
621         while txt.empty? or txt.count(" ") < min_spaces
622           candidate = header_found[PAR_REGEX]
623           break unless candidate
624           txt = candidate.ircify_html
625           header_found = $'
626           txt.sub!(strip, '') if strip
627           debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
628         end
629
630         return txt unless txt.empty? or txt.count(" ") < min_spaces
631
632         # Nothing yet ... let's get drastic: we look for non-par elements too,
633         # but only for those that match something that we know is likely to
634         # contain text
635
636         # Attempt #1
637         header_found = xml
638         while txt.empty? or txt.count(" ") < min_spaces
639           candidate = header_found[AFTER_PAR1_REGEX]
640           break unless candidate
641           txt = candidate.ircify_html
642           header_found = $'
643           txt.sub!(strip, '') if strip
644           debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
645         end
646
647         return txt unless txt.empty? or txt.count(" ") < min_spaces
648
649         # Attempt #2
650         header_found = xml
651         while txt.empty? or txt.count(" ") < min_spaces
652           candidate = header_found[AFTER_PAR2_REGEX]
653           break unless candidate
654           txt = candidate.ircify_html
655           header_found = $'
656           txt.sub!(strip, '') if strip
657           debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
658         end
659
660         debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
661         return txt unless txt.count(" ") < min_spaces
662         break if min_spaces == 0
663         min_spaces /= 2
664       end
665     end
666
667     # This method extracts title, content (first par) and extra
668     # information from the given document _doc_.
669     #
670     # _doc_ can be an URI, a Net::HTTPResponse or a String.
671     #
672     # If _doc_ is a String, only title and content information
673     # are retrieved (if possible), using standard methods.
674     #
675     # If _doc_ is an URI or a Net::HTTPResponse, additional
676     # information is retrieved, and special title/summary
677     # extraction routines are used if possible.
678     #
679     def Utils.get_html_info(doc, opts={})
680       case doc
681       when String
682         Utils.get_string_html_info(doc, opts)
683       when Net::HTTPResponse
684         Utils.get_resp_html_info(doc, opts)
685       when URI
686         if doc.fragment and not doc.fragment.empty?
687           opts[:uri_fragment] ||= doc.fragment
688         end
689         ret = Hash.new
690         @@bot.httputil.get_response(doc) { |resp|
691           ret = Utils.get_resp_html_info(resp, opts)
692         }
693         return ret
694       else
695         raise
696       end
697     end
698
699     class ::UrlLinkError < RuntimeError
700     end
701
702     # This method extracts title, content (first par) and extra
703     # information from the given Net::HTTPResponse _resp_.
704     #
705     # Currently, the only accepted option (in _opts_) is
706     # uri_fragment:: the URI fragment of the original request
707     #
708     # Returns a Hash with the following keys:
709     # title:: the title of the document (if any)
710     # content:: the first paragraph of the document (if any)
711     # headers::
712     #   the headers of the Net::HTTPResponse. The value is
713     #   a Hash whose keys are lowercase forms of the HTTP
714     #   header fields, and whose values are Arrays.
715     #
716     def Utils.get_resp_html_info(resp, opts={})
717       ret = Hash.new
718       case resp
719       when Net::HTTPSuccess
720         ret[:headers] = resp.to_hash
721
722         if resp['content-type'] =~ /^text\/|(?:x|ht)ml/
723           partial = resp.partial_body(@@bot.config['http.info_bytes'])
724           ret.merge!(Utils.get_string_html_info(partial, opts))
725         end
726         return ret
727       else
728         raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
729       end
730     end
731
732     # This method extracts title and content (first par)
733     # from the given HTML or XML document _text_, using
734     # standard methods (String#ircify_html_title,
735     # Utils.ircify_first_html_par)
736     #
737     # Currently, the only accepted option (in _opts_) is
738     # uri_fragment:: the URI fragment of the original request
739     #
740     def Utils.get_string_html_info(text, opts={})
741       txt = text.dup
742       title = txt.ircify_html_title
743       if frag = opts[:uri_fragment] and not frag.empty?
744         fragreg = /.*?<a\s+[^>]*name=["']?#{frag}["']?.*?>/im
745         txt.sub!(fragreg,'')
746       end
747       c_opts = opts.dup
748       c_opts[:strip] ||= title
749       content = Utils.ircify_first_html_par(txt, c_opts)
750       content = nil if content.empty?
751       return {:title => title, :content => content}
752     end
753
754     # Get the first pars of the first _count_ _urls_.
755     # The pages are downloaded using the bot httputil service.
756     # Returns an array of the first paragraphs fetched.
757     # If (optional) _opts_ :message is specified, those paragraphs are
758     # echoed as replies to the IRC message passed as _opts_ :message
759     #
760     def Utils.get_first_pars(urls, count, opts={})
761       idx = 0
762       msg = opts[:message]
763       retval = Array.new
764       while count > 0 and urls.length > 0
765         url = urls.shift
766         idx += 1
767
768         begin
769           info = Utils.get_html_info(URI.parse(url), opts)
770
771           par = info[:content]
772           retval.push(par)
773
774           if par
775             msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
776             count -=1
777           end
778         rescue
779           debug "Unable to retrieve #{url}: #{$!}"
780           next
781         end
782       end
783       return retval
784     end
785
786   end
787 end
788
789 Irc::Utils.bot = Irc::Bot::Plugins.manager.bot