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 # Define some regular expressions to be used by first_html_par
323 HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
325 PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
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
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
340 # Miscellaneous useful functions
342 @@bot = nil unless defined? @@bot
343 @@safe_save_dir = nil unless defined?(@@safe_save_dir)
350 # Set up some Utils routines which depend on the associated bot.
352 debug "initializing utils"
354 @@safe_save_dir = "#{@@bot.botclass}/safe_save"
361 SEC_PER_HR = SEC_PER_MIN * 60
363 SEC_PER_DAY = SEC_PER_HR * 24
364 # Seconds per (30-day) month
365 SEC_PER_MNTH = SEC_PER_DAY * 30
366 # Second per (30*12 = 360 day) year
367 SEC_PER_YR = SEC_PER_MNTH * 12
369 # Auxiliary method needed by Utils.secs_to_string
370 def Utils.secs_to_string_case(array, var, string, plural)
373 array << "1 #{string}"
375 array << "#{var} #{plural}"
379 # Turn a number of seconds into a human readable string, e.g
380 # 2 days, 3 hours, 18 minutes and 10 seconds
381 def Utils.secs_to_string(secs)
383 years, secs = secs.divmod SEC_PER_YR
384 secs_to_string_case(ret, years, _("year"), _("years")) if years > 0
385 months, secs = secs.divmod SEC_PER_MNTH
386 secs_to_string_case(ret, months, _("month"), _("months")) if months > 0
387 days, secs = secs.divmod SEC_PER_DAY
388 secs_to_string_case(ret, days, _("day"), _("days")) if days > 0
389 hours, secs = secs.divmod SEC_PER_HR
390 secs_to_string_case(ret, hours, _("hour"), _("hours")) if hours > 0
391 mins, secs = secs.divmod SEC_PER_MIN
392 secs_to_string_case(ret, mins, _("minute"), _("minutes")) if mins > 0
394 secs_to_string_case(ret, secs, _("second"), _("seconds")) if secs > 0 or ret.empty?
397 raise "Empty ret array!"
401 return [ret[0, ret.length-1].join(", ") , ret[-1]].join(_(" and "))
406 # Execute an external program, returning a String obtained by redirecting
407 # the program's standards errors and output
409 def Utils.safe_exec(command, *args)
412 return p.readlines.join("\n")
415 $stderr.reopen($stdout)
417 rescue Exception => e
418 puts "exec of #{command} led to exception: #{e.pretty_inspect}"
421 puts "exec of #{command} failed"
428 # Safely (atomically) save to _file_, by passing a tempfile to the block
429 # and then moving the tempfile to its final location when done.
431 # call-seq: Utils.safe_save(file, &block)
433 def Utils.safe_save(file)
434 raise 'No safe save directory defined!' if @@safe_save_dir.nil?
435 basename = File.basename(file)
436 temp = Tempfile.new(basename,@@safe_save_dir)
438 yield temp if block_given?
440 File.rename(temp.path, file)
444 # Decode HTML entities in the String _str_, using HTMLEntities if the
445 # package was found, or UNESCAPE_TABLE otherwise.
447 def Utils.decode_html_entities(str)
448 if defined? ::HTMLEntities
449 return HTMLEntities.decode_entities(str)
451 str.gsub(/(&(.+?);)/) {
453 # remove the 0-paddng from unicode integers
455 symbol = "##{$1.to_i.to_s}"
458 # output the symbol's irc-translated character, or a * if it's unknown
459 UNESCAPE_TABLE[symbol] || [symbol[/\d+/].to_i].pack("U") rescue '*'
464 # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
465 # If possible, grab the one after the first heading
467 # It is possible to pass some options to determine how the stripping
468 # occurs. Currently supported options are
469 # strip:: Regex or String to strip at the beginning of the obtained
471 # min_spaces:: minimum number of spaces a paragraph should have
473 def Utils.ircify_first_html_par(xml_org, opts={})
474 if defined? ::Hpricot
475 Utils.ircify_first_html_par_wh(xml_org, opts)
477 Utils.ircify_first_html_par_woh(xml_org, opts)
481 # HTML first par grabber using hpricot
482 def Utils.ircify_first_html_par_wh(xml_org, opts={})
483 doc = Hpricot(xml_org)
485 # Strip styles and scripts
486 (doc/"style|script").remove
491 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
493 min_spaces = opts[:min_spaces] || 8
494 min_spaces = 0 if min_spaces < 0
498 h = %w{h1 h2 h3 h4 h5 h6}
506 h_p_css = ar.join("|")
507 debug "css search: #{h_p_css}"
509 pre_h = pars = by_span = nil
512 debug "Minimum number of spaces: #{min_spaces}"
514 # Initial attempt: <p> that follows <h\d>
515 pre_h = doc/h_p_css if pre_h.nil?
516 debug "Hx: found: #{pre_h.pretty_inspect}"
519 txt = p.to_html.ircify_html
520 txt.sub!(strip, '') if strip
521 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
522 break unless txt.empty? or txt.count(" ") < min_spaces
525 return txt unless txt.empty? or txt.count(" ") < min_spaces
527 # Second natural attempt: just get any <p>
528 pars = doc/"p" if pars.nil?
529 debug "par: found: #{pars.pretty_inspect}"
532 txt = p.to_html.ircify_html
533 txt.sub!(strip, '') if strip
534 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
535 break unless txt.empty? or txt.count(" ") < min_spaces
538 return txt unless txt.empty? or txt.count(" ") < min_spaces
540 # Nothing yet ... let's get drastic: we look for non-par elements too,
541 # but only for those that match something that we know is likely to
544 # Some blogging and forum platforms use spans or divs with a 'body' or
545 # 'message' or 'text' in their class to mark actual text. Since we want
546 # the class match to be partial and case insensitive, we collect
547 # the common elements that may have this class and then filter out those
550 by_span = Hpricot::Elements[]
551 pre_pars = doc/"div|span|td|tr|tbody|table"
553 by_span.push el if el.class =~ /body|message|text/i
555 debug "other \#1: found: #{by_span.pretty_inspect}"
560 txt = p.to_html.ircify_html
561 txt.sub!(strip, '') if strip
562 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
563 break unless txt.empty? or txt.count(" ") < min_spaces
566 return txt unless txt.empty? or txt.count(" ") < min_spaces
568 # At worst, we can try stuff which is comprised between two <br>
571 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
572 return txt unless txt.count(" ") < min_spaces
573 break if min_spaces == 0
578 # HTML first par grabber without hpricot
579 def Utils.ircify_first_html_par_woh(xml_org, opts={})
580 xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
583 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
585 min_spaces = opts[:min_spaces] || 8
586 min_spaces = 0 if min_spaces < 0
591 debug "Minimum number of spaces: #{min_spaces}"
592 header_found = xml.match(HX_REGEX)
595 while txt.empty? or txt.count(" ") < min_spaces
596 candidate = header_found[PAR_REGEX]
597 break unless candidate
598 txt = candidate.ircify_html
600 txt.sub!(strip, '') if strip
601 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
605 return txt unless txt.empty? or txt.count(" ") < min_spaces
607 # If we haven't found a first par yet, try to get it from the whole
610 while txt.empty? or txt.count(" ") < min_spaces
611 candidate = header_found[PAR_REGEX]
612 break unless candidate
613 txt = candidate.ircify_html
615 txt.sub!(strip, '') if strip
616 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
619 return txt unless txt.empty? or txt.count(" ") < min_spaces
621 # Nothing yet ... let's get drastic: we look for non-par elements too,
622 # but only for those that match something that we know is likely to
627 while txt.empty? or txt.count(" ") < min_spaces
628 candidate = header_found[AFTER_PAR1_REGEX]
629 break unless candidate
630 txt = candidate.ircify_html
632 txt.sub!(strip, '') if strip
633 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
636 return txt unless txt.empty? or txt.count(" ") < min_spaces
640 while txt.empty? or txt.count(" ") < min_spaces
641 candidate = header_found[AFTER_PAR2_REGEX]
642 break unless candidate
643 txt = candidate.ircify_html
645 txt.sub!(strip, '') if strip
646 debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
649 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
650 return txt unless txt.count(" ") < min_spaces
651 break if min_spaces == 0
656 # Get the first pars of the first _count_ _urls_.
657 # The pages are downloaded using the bot httputil service.
658 # Returns an array of the first paragraphs fetched.
659 # If (optional) _opts_ :message is specified, those paragraphs are
660 # echoed as replies to the IRC message passed as _opts_ :message
662 def Utils.get_first_pars(urls, count, opts={})
666 while count > 0 and urls.length > 0
670 # FIXME what happens if some big file is returned? We should share
671 # code with the url plugin to only retrieve partial file content!
672 xml = self.bot.httputil.get(url)
674 debug "Unable to retrieve #{url}"
677 par = Utils.ircify_first_html_par(xml, opts)
679 debug "No first par found\n#{xml}"
680 # FIXME only do this if the 'url' plugin is loaded
681 # TODO even better, put the code here
682 # par = @bot.plugins['url'].get_title_from_html(xml)
688 msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
698 Irc::Utils.bot = Irc::Bot::Plugins.manager.bot