4 # :title: rbot utilities provider
6 # Author:: Tom Gilbert <tom@linuxbrit.co.uk>
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
9 # Copyright:: (C) 2002-2006 Tom Gilbert
10 # Copyright:: (C) 2007 Giuseppe Bilotta
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
18 # Try to load htmlentities, fall back to an HTML escape table.
20 require 'htmlentities'
24 gems = require 'rubygems'
53 # extras codes, for future use...
67 'otimes' => '⊗',
76 'Epsilon' => 'Ε',
80 'Upsilon' => 'Υ',
82 'there4' => '∴',
87 'rsaquo' => '›',
101 'rdquo' => '”',
109 'lfloor' => '⌊',
116 'clubs' => '♣',
117 'diams' => '♦',
124 'Scaron' => 'Š',
130 'sbquo' => '‚',
143 'infin' => '∞',
148 'thinsp' => ' ',
150 'bdquo' => '„',
157 'mdash' => '—',
159 'permil' => '‰',
164 'forall' => '∀',
166 'rceil' => '⌉',
169 'lambda' => 'λ',
173 'dagger' => '†',
176 'image' => 'ℑ',
177 'alefsym' => 'ℵ',
183 'frasl' => '⁄',
185 'lowast' => '∗',
196 'oline' => '‾',
203 'empty' => '∅',
210 'weierp' => '℘',
215 'omicron' => 'ο',
216 'upsilon' => 'υ',
218 'Lambda' => 'Λ',
225 'scaron' => 'š',
226 'lsquo' => '‘',
234 'hellip' => '…',
238 'rfloor' => '⌋',
240 'crarr' => '↵',
242 'notin' => '∉',
243 'exist' => '∃',
246 'Dagger' => '‡',
247 'oplus' => '⊕',
253 'lsaquo' => '‹',
255 'Omicron' => 'Ο',
270 'sigmaf' => 'ς',
272 'minus' => '−',
275 'epsilon' => 'ε',
286 'spades' => '♠',
287 'rsquo' => '’',
291 'thetasym' => 'ϑ',
295 'ldquo' => '“',
296 'hearts' => '♥',
307 require 'htmlentities'
311 gems = require 'rubygems'
320 # Some regular expressions to manage HTML data
323 TITLE_REGEX = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
326 HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
328 PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
330 # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
331 # to mark actual text
332 AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
334 # At worst, we can try stuff which is comprised between two <br>
335 AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
343 # Miscellaneous useful functions
345 @@bot = nil unless defined? @@bot
346 @@safe_save_dir = nil unless defined?(@@safe_save_dir)
353 # Set up some Utils routines which depend on the associated bot.
355 debug "initializing utils"
357 @@safe_save_dir = "#{@@bot.botclass}/safe_save"
364 SEC_PER_HR = SEC_PER_MIN * 60
366 SEC_PER_DAY = SEC_PER_HR * 24
367 # Seconds per (30-day) month
368 SEC_PER_MNTH = SEC_PER_DAY * 30
369 # Second per (30*12 = 360 day) year
370 SEC_PER_YR = SEC_PER_MNTH * 12
372 # Auxiliary method needed by Utils.secs_to_string
373 def Utils.secs_to_string_case(array, var, string, plural)
376 array << "1 #{string}"
378 array << "#{var} #{plural}"
382 # Turn a number of seconds into a human readable string, e.g
383 # 2 days, 3 hours, 18 minutes and 10 seconds
384 def Utils.secs_to_string(secs)
386 years, secs = secs.divmod SEC_PER_YR
387 secs_to_string_case(ret, years, _("year"), _("years")) if years > 0
388 months, secs = secs.divmod SEC_PER_MNTH
389 secs_to_string_case(ret, months, _("month"), _("months")) if months > 0
390 days, secs = secs.divmod SEC_PER_DAY
391 secs_to_string_case(ret, days, _("day"), _("days")) if days > 0
392 hours, secs = secs.divmod SEC_PER_HR
393 secs_to_string_case(ret, hours, _("hour"), _("hours")) if hours > 0
394 mins, secs = secs.divmod SEC_PER_MIN
395 secs_to_string_case(ret, mins, _("minute"), _("minutes")) if mins > 0
397 secs_to_string_case(ret, secs, _("second"), _("seconds")) if secs > 0 or ret.empty?
400 raise "Empty ret array!"
404 return [ret[0, ret.length-1].join(", ") , ret[-1]].join(_(" and "))
409 # Execute an external program, returning a String obtained by redirecting
410 # the program's standards errors and output
412 def Utils.safe_exec(command, *args)
415 return p.readlines.join("\n")
418 $stderr.reopen($stdout)
420 rescue Exception => e
421 puts "exec of #{command} led to exception: #{e.pretty_inspect}"
424 puts "exec of #{command} failed"
431 # Safely (atomically) save to _file_, by passing a tempfile to the block
432 # and then moving the tempfile to its final location when done.
434 # call-seq: Utils.safe_save(file, &block)
436 def Utils.safe_save(file)
437 raise 'No safe save directory defined!' if @@safe_save_dir.nil?
438 basename = File.basename(file)
439 temp = Tempfile.new(basename,@@safe_save_dir)
441 yield temp if block_given?
443 File.rename(temp.path, file)
447 # Decode HTML entities in the String _str_, using HTMLEntities if the
448 # package was found, or UNESCAPE_TABLE otherwise.
450 def Utils.decode_html_entities(str)
451 if defined? ::HTMLEntities
452 return HTMLEntities.decode_entities(str)
454 str.gsub(/(&(.+?);)/) {
456 # remove the 0-paddng from unicode integers
458 symbol = "##{$1.to_i.to_s}"
461 # output the symbol's irc-translated character, or a * if it's unknown
462 UNESCAPE_TABLE[symbol] || [symbol[/\d+/].to_i].pack("U") rescue '*'
467 # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
468 # If possible, grab the one after the first heading
470 # It is possible to pass some options to determine how the stripping
471 # occurs. Currently supported options are
472 # strip:: Regex or String to strip at the beginning of the obtained
474 # min_spaces:: minimum number of spaces a paragraph should have
476 def Utils.ircify_first_html_par(xml_org, opts={})
477 if defined? ::Hpricot
478 Utils.ircify_first_html_par_wh(xml_org, opts)
480 Utils.ircify_first_html_par_woh(xml_org, opts)
484 # HTML first par grabber using hpricot
485 def Utils.ircify_first_html_par_wh(xml_org, opts={})
486 doc = Hpricot(xml_org)
488 # Strip styles and scripts
489 (doc/"style|script").remove
494 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
496 min_spaces = opts[:min_spaces] || 8
497 min_spaces = 0 if min_spaces < 0
501 h = %w{h1 h2 h3 h4 h5 h6}
509 h_p_css = ar.join("|")
510 debug "css search: #{h_p_css}"
512 pre_h = pars = by_span = nil
515 debug "Minimum number of spaces: #{min_spaces}"
517 # Initial attempt: <p> that follows <h\d>
518 pre_h = doc/h_p_css if pre_h.nil?
519 debug "Hx: found: #{pre_h.pretty_inspect}"
522 txt = p.to_html.ircify_html
523 txt.sub!(strip, '') if strip
524 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
525 break unless txt.empty? or txt.count(" ") < min_spaces
528 return txt unless txt.empty? or txt.count(" ") < min_spaces
530 # Second natural attempt: just get any <p>
531 pars = doc/"p" if pars.nil?
532 debug "par: found: #{pars.pretty_inspect}"
535 txt = p.to_html.ircify_html
536 txt.sub!(strip, '') if strip
537 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
538 break unless txt.empty? or txt.count(" ") < min_spaces
541 return txt unless txt.empty? or txt.count(" ") < min_spaces
543 # Nothing yet ... let's get drastic: we look for non-par elements too,
544 # but only for those that match something that we know is likely to
547 # Some blogging and forum platforms use spans or divs with a 'body' or
548 # 'message' or 'text' in their class to mark actual text. Since we want
549 # the class match to be partial and case insensitive, we collect
550 # the common elements that may have this class and then filter out those
553 by_span = Hpricot::Elements[]
554 pre_pars = doc/"div|span|td|tr|tbody|table"
556 by_span.push el if el[:class] =~ /body|message|text/i
558 debug "other \#1: found: #{by_span.pretty_inspect}"
563 txt = p.to_html.ircify_html
564 txt.sub!(strip, '') if strip
565 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
566 break unless txt.empty? or txt.count(" ") < min_spaces
569 return txt unless txt.empty? or txt.count(" ") < min_spaces
571 # At worst, we can try stuff which is comprised between two <br>
574 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
575 return txt unless txt.count(" ") < min_spaces
576 break if min_spaces == 0
581 # HTML first par grabber without hpricot
582 def Utils.ircify_first_html_par_woh(xml_org, opts={})
583 xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
586 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
588 min_spaces = opts[:min_spaces] || 8
589 min_spaces = 0 if min_spaces < 0
594 debug "Minimum number of spaces: #{min_spaces}"
595 header_found = xml.match(HX_REGEX)
598 while txt.empty? or txt.count(" ") < min_spaces
599 candidate = header_found[PAR_REGEX]
600 break unless candidate
601 txt = candidate.ircify_html
603 txt.sub!(strip, '') if strip
604 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
608 return txt unless txt.empty? or txt.count(" ") < min_spaces
610 # If we haven't found a first par yet, try to get it from the whole
613 while txt.empty? or txt.count(" ") < min_spaces
614 candidate = header_found[PAR_REGEX]
615 break unless candidate
616 txt = candidate.ircify_html
618 txt.sub!(strip, '') if strip
619 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
622 return txt unless txt.empty? or txt.count(" ") < min_spaces
624 # Nothing yet ... let's get drastic: we look for non-par elements too,
625 # but only for those that match something that we know is likely to
630 while txt.empty? or txt.count(" ") < min_spaces
631 candidate = header_found[AFTER_PAR1_REGEX]
632 break unless candidate
633 txt = candidate.ircify_html
635 txt.sub!(strip, '') if strip
636 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
639 return txt unless txt.empty? or txt.count(" ") < min_spaces
643 while txt.empty? or txt.count(" ") < min_spaces
644 candidate = header_found[AFTER_PAR2_REGEX]
645 break unless candidate
646 txt = candidate.ircify_html
648 txt.sub!(strip, '') if strip
649 debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
652 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
653 return txt unless txt.count(" ") < min_spaces
654 break if min_spaces == 0
659 # This method extracts title, content (first par) and extra
660 # information from the given document _doc_.
662 # _doc_ can be an URI, a Net::HTTPResponse or a String.
664 # If _doc_ is a String, only title and content information
665 # are retrieved (if possible), using standard methods.
667 # If _doc_ is an URI or a Net::HTTPResponse, additional
668 # information is retrieved, and special title/summary
669 # extraction routines are used if possible.
671 def Utils.get_html_info(doc, opts={})
674 Utils.get_string_html_info(doc, opts)
675 when Net::HTTPResponse
676 Utils.get_resp_html_info(doc, opts)
678 if doc.fragment and not doc.fragment.empty?
679 opts[:uri_fragment] ||= doc.fragment
682 @@bot.httputil.get_response(doc) { |resp|
683 ret = Utils.get_resp_html_info(resp, opts)
691 class ::UrlLinkError < RuntimeError
694 # This method extracts title, content (first par) and extra
695 # information from the given Net::HTTPResponse _resp_.
697 # Currently, the only accepted option (in _opts_) is
698 # uri_fragment:: the URI fragment of the original request
700 # Returns a Hash with the following keys:
701 # title:: the title of the document (if any)
702 # content:: the first paragraph of the document (if any)
704 # the headers of the Net::HTTPResponse. The value is
705 # a Hash whose keys are lowercase forms of the HTTP
706 # header fields, and whose values are Arrays.
708 def Utils.get_resp_html_info(resp, opts={})
711 when Net::HTTPSuccess
712 ret[:headers] = resp.to_hash
714 if resp['content-type'] =~ /^text\/|(?:x|ht)ml/
715 partial = resp.partial_body(@@bot.config['http.info_bytes'])
716 ret.merge!(Utils.get_string_html_info(partial, opts))
720 raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
724 # This method extracts title and content (first par)
725 # from the given HTML or XML document _text_, using
726 # standard methods (String#ircify_html_title,
727 # Utils.ircify_first_html_par)
729 # Currently, the only accepted option (in _opts_) is
730 # uri_fragment:: the URI fragment of the original request
732 def Utils.get_string_html_info(text, opts={})
734 title = txt.ircify_html_title
735 if frag = opts[:uri_fragment] and not frag.empty?
736 fragreg = /.*?<a\s+[^>]*name=["']?#{frag}["']?.*?>/im
740 c_opts[:strip] ||= title
741 content = Utils.ircify_first_html_par(txt, c_opts)
742 content = nil if content.empty?
743 return {:title => title, :content => content}
746 # Get the first pars of the first _count_ _urls_.
747 # The pages are downloaded using the bot httputil service.
748 # Returns an array of the first paragraphs fetched.
749 # If (optional) _opts_ :message is specified, those paragraphs are
750 # echoed as replies to the IRC message passed as _opts_ :message
752 def Utils.get_first_pars(urls, count, opts={})
756 while count > 0 and urls.length > 0
761 info = Utils.get_html_info(URI.parse(url), opts)
767 msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
771 debug "Unable to retrieve #{url}: #{$!}"
781 Irc::Utils.bot = Irc::Bot::Plugins.manager.bot