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' => '♥',
310 AFTER_PAR_PATH = /^(?:div|span)$/
311 AFTER_PAR_EX = /^(?:td|tr|tbody|table)$/
312 AFTER_PAR_CLASS = /body|message|text/i
318 gems = require 'rubygems'
327 # Some regular expressions to manage HTML data
330 TITLE_REGEX = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
333 HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
335 PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
337 # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
338 # to mark actual text
339 AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
341 # At worst, we can try stuff which is comprised between two <br>
342 AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
350 # Miscellaneous useful functions
352 @@bot = nil unless defined? @@bot
353 @@safe_save_dir = nil unless defined?(@@safe_save_dir)
360 # Set up some Utils routines which depend on the associated bot.
362 debug "initializing utils"
364 @@safe_save_dir = "#{@@bot.botclass}/safe_save"
371 SEC_PER_HR = SEC_PER_MIN * 60
373 SEC_PER_DAY = SEC_PER_HR * 24
374 # Seconds per (30-day) month
375 SEC_PER_MNTH = SEC_PER_DAY * 30
376 # Second per (30*12 = 360 day) year
377 SEC_PER_YR = SEC_PER_MNTH * 12
379 # Auxiliary method needed by Utils.secs_to_string
380 def Utils.secs_to_string_case(array, var, string, plural)
383 array << "1 #{string}"
385 array << "#{var} #{plural}"
389 # Turn a number of seconds into a human readable string, e.g
390 # 2 days, 3 hours, 18 minutes and 10 seconds
391 def Utils.secs_to_string(secs)
393 years, secs = secs.divmod SEC_PER_YR
394 secs_to_string_case(ret, years, _("year"), _("years")) if years > 0
395 months, secs = secs.divmod SEC_PER_MNTH
396 secs_to_string_case(ret, months, _("month"), _("months")) if months > 0
397 days, secs = secs.divmod SEC_PER_DAY
398 secs_to_string_case(ret, days, _("day"), _("days")) if days > 0
399 hours, secs = secs.divmod SEC_PER_HR
400 secs_to_string_case(ret, hours, _("hour"), _("hours")) if hours > 0
401 mins, secs = secs.divmod SEC_PER_MIN
402 secs_to_string_case(ret, mins, _("minute"), _("minutes")) if mins > 0
404 secs_to_string_case(ret, secs, _("second"), _("seconds")) if secs > 0 or ret.empty?
407 raise "Empty ret array!"
411 return [ret[0, ret.length-1].join(", ") , ret[-1]].join(_(" and "))
416 # Execute an external program, returning a String obtained by redirecting
417 # the program's standards errors and output
419 def Utils.safe_exec(command, *args)
422 return p.readlines.join("\n")
425 $stderr.reopen($stdout)
427 rescue Exception => e
428 puts "exec of #{command} led to exception: #{e.pretty_inspect}"
431 puts "exec of #{command} failed"
438 # Safely (atomically) save to _file_, by passing a tempfile to the block
439 # and then moving the tempfile to its final location when done.
441 # call-seq: Utils.safe_save(file, &block)
443 def Utils.safe_save(file)
444 raise 'No safe save directory defined!' if @@safe_save_dir.nil?
445 basename = File.basename(file)
446 temp = Tempfile.new(basename,@@safe_save_dir)
448 yield temp if block_given?
450 File.rename(temp.path, file)
454 # Decode HTML entities in the String _str_, using HTMLEntities if the
455 # package was found, or UNESCAPE_TABLE otherwise.
457 def Utils.decode_html_entities(str)
458 if defined? ::HTMLEntities
459 return HTMLEntities.decode_entities(str)
461 str.gsub(/(&(.+?);)/) {
463 # remove the 0-paddng from unicode integers
465 symbol = "##{$1.to_i.to_s}"
468 # output the symbol's irc-translated character, or a * if it's unknown
469 UNESCAPE_TABLE[symbol] || (symbol.match(/^\d+$/) ? [$0.to_i].pack("U") : '*')
474 # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
475 # If possible, grab the one after the first heading
477 # It is possible to pass some options to determine how the stripping
478 # occurs. Currently supported options are
479 # strip:: Regex or String to strip at the beginning of the obtained
481 # min_spaces:: minimum number of spaces a paragraph should have
483 def Utils.ircify_first_html_par(xml_org, opts={})
484 if defined? ::Hpricot
485 Utils.ircify_first_html_par_wh(xml_org, opts)
487 Utils.ircify_first_html_par_woh(xml_org, opts)
491 # HTML first par grabber using hpricot
492 def Utils.ircify_first_html_par_wh(xml_org, opts={})
493 doc = Hpricot(xml_org)
495 # Strip styles and scripts
496 (doc/"style|script").remove
501 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
503 min_spaces = opts[:min_spaces] || 8
504 min_spaces = 0 if min_spaces < 0
508 pre_h = pars = by_span = nil
511 debug "Minimum number of spaces: #{min_spaces}"
513 # Initial attempt: <p> that follows <h\d>
515 pre_h = Hpricot::Elements[]
517 doc.search("*") { |e|
523 pre_h << e if found_h
526 debug "Hx: found: #{pre_h.pretty_inspect}"
531 txt = p.to_html.ircify_html
532 txt.sub!(strip, '') if strip
533 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
534 break unless txt.empty? or txt.count(" ") < min_spaces
537 return txt unless txt.empty? or txt.count(" ") < min_spaces
539 # Second natural attempt: just get any <p>
540 pars = doc/"p" if pars.nil?
541 debug "par: found: #{pars.pretty_inspect}"
544 txt = p.to_html.ircify_html
545 txt.sub!(strip, '') if strip
546 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
547 break unless txt.empty? or txt.count(" ") < min_spaces
550 return txt unless txt.empty? or txt.count(" ") < min_spaces
552 # Nothing yet ... let's get drastic: we look for non-par elements too,
553 # but only for those that match something that we know is likely to
556 # Some blogging and forum platforms use spans or divs with a 'body' or
557 # 'message' or 'text' in their class to mark actual text. Since we want
558 # the class match to be partial and case insensitive, we collect
559 # the common elements that may have this class and then filter out those
560 # we don't need. If no divs or spans are found, we'll accept additional
561 # elements too (td, tr, tbody, table).
563 by_span = Hpricot::Elements[]
564 extra = Hpricot::Elements[]
565 doc.search("*") { |el|
566 next if el.bogusetag?
569 by_span.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
571 extra.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
574 if by_span.empty? and not extra.empty?
577 debug "other \#1: found: #{by_span.pretty_inspect}"
582 txt = p.to_html.ircify_html
583 txt.sub!(strip, '') if strip
584 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
585 break unless txt.empty? or txt.count(" ") < min_spaces
588 return txt unless txt.empty? or txt.count(" ") < min_spaces
590 # At worst, we can try stuff which is comprised between two <br>
593 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
594 return txt unless txt.count(" ") < min_spaces
595 break if min_spaces == 0
600 # HTML first par grabber without hpricot
601 def Utils.ircify_first_html_par_woh(xml_org, opts={})
602 xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
605 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
607 min_spaces = opts[:min_spaces] || 8
608 min_spaces = 0 if min_spaces < 0
613 debug "Minimum number of spaces: #{min_spaces}"
614 header_found = xml.match(HX_REGEX)
617 while txt.empty? or txt.count(" ") < min_spaces
618 candidate = header_found[PAR_REGEX]
619 break unless candidate
620 txt = candidate.ircify_html
622 txt.sub!(strip, '') if strip
623 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
627 return txt unless txt.empty? or txt.count(" ") < min_spaces
629 # If we haven't found a first par yet, try to get it from the whole
632 while txt.empty? or txt.count(" ") < min_spaces
633 candidate = header_found[PAR_REGEX]
634 break unless candidate
635 txt = candidate.ircify_html
637 txt.sub!(strip, '') if strip
638 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
641 return txt unless txt.empty? or txt.count(" ") < min_spaces
643 # Nothing yet ... let's get drastic: we look for non-par elements too,
644 # but only for those that match something that we know is likely to
649 while txt.empty? or txt.count(" ") < min_spaces
650 candidate = header_found[AFTER_PAR1_REGEX]
651 break unless candidate
652 txt = candidate.ircify_html
654 txt.sub!(strip, '') if strip
655 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
658 return txt unless txt.empty? or txt.count(" ") < min_spaces
662 while txt.empty? or txt.count(" ") < min_spaces
663 candidate = header_found[AFTER_PAR2_REGEX]
664 break unless candidate
665 txt = candidate.ircify_html
667 txt.sub!(strip, '') if strip
668 debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
671 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
672 return txt unless txt.count(" ") < min_spaces
673 break if min_spaces == 0
678 # This method extracts title, content (first par) and extra
679 # information from the given document _doc_.
681 # _doc_ can be an URI, a Net::HTTPResponse or a String.
683 # If _doc_ is a String, only title and content information
684 # are retrieved (if possible), using standard methods.
686 # If _doc_ is an URI or a Net::HTTPResponse, additional
687 # information is retrieved, and special title/summary
688 # extraction routines are used if possible.
690 def Utils.get_html_info(doc, opts={})
693 Utils.get_string_html_info(doc, opts)
694 when Net::HTTPResponse
695 Utils.get_resp_html_info(doc, opts)
697 if doc.fragment and not doc.fragment.empty?
698 opts[:uri_fragment] ||= doc.fragment
701 @@bot.httputil.get_response(doc) { |resp|
702 ret = Utils.get_resp_html_info(resp, opts)
710 class ::UrlLinkError < RuntimeError
713 # This method extracts title, content (first par) and extra
714 # information from the given Net::HTTPResponse _resp_.
716 # Currently, the only accepted option (in _opts_) is
717 # uri_fragment:: the URI fragment of the original request
719 # Returns a Hash with the following keys:
720 # title:: the title of the document (if any)
721 # content:: the first paragraph of the document (if any)
723 # the headers of the Net::HTTPResponse. The value is
724 # a Hash whose keys are lowercase forms of the HTTP
725 # header fields, and whose values are Arrays.
727 def Utils.get_resp_html_info(resp, opts={})
730 when Net::HTTPSuccess
731 ret[:headers] = resp.to_hash
733 if resp['content-type'] =~ /^text\/|(?:x|ht)ml/
734 partial = resp.partial_body(@@bot.config['http.info_bytes'])
735 ret.merge!(Utils.get_string_html_info(partial, opts))
739 raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
743 # This method extracts title and content (first par)
744 # from the given HTML or XML document _text_, using
745 # standard methods (String#ircify_html_title,
746 # Utils.ircify_first_html_par)
748 # Currently, the only accepted option (in _opts_) is
749 # uri_fragment:: the URI fragment of the original request
751 def Utils.get_string_html_info(text, opts={})
753 title = txt.ircify_html_title
754 if frag = opts[:uri_fragment] and not frag.empty?
755 fragreg = /.*?<a\s+[^>]*name=["']?#{frag}["']?.*?>/im
759 c_opts[:strip] ||= title
760 content = Utils.ircify_first_html_par(txt, c_opts)
761 content = nil if content.empty?
762 return {:title => title, :content => content}
765 # Get the first pars of the first _count_ _urls_.
766 # The pages are downloaded using the bot httputil service.
767 # Returns an array of the first paragraphs fetched.
768 # If (optional) _opts_ :message is specified, those paragraphs are
769 # echoed as replies to the IRC message passed as _opts_ :message
771 def Utils.get_first_pars(urls, count, opts={})
775 while count > 0 and urls.length > 0
780 info = Utils.get_html_info(URI.parse(url), opts)
786 msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
790 debug "Unable to retrieve #{url}: #{$!}"
800 Irc::Utils.bot = Irc::Bot::Plugins.manager.bot