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
20 require 'htmlentities'
21 $we_have_html_entities_decoder = true
25 gems = require 'rubygems'
32 $we_have_html_entities_decoder = false
55 # extras codes, for future use...
69 'otimes' => '⊗',
78 'Epsilon' => 'Ε',
82 'Upsilon' => 'Υ',
84 'there4' => '∴',
89 'rsaquo' => '›',
101 'lceil' => '⌈',
103 'rdquo' => '”',
111 'lfloor' => '⌊',
118 'clubs' => '♣',
119 'diams' => '♦',
126 'Scaron' => 'Š',
132 'sbquo' => '‚',
145 'infin' => '∞',
150 'thinsp' => ' ',
152 'bdquo' => '„',
159 'mdash' => '—',
161 'permil' => '‰',
166 'forall' => '∀',
168 'rceil' => '⌉',
171 'lambda' => 'λ',
175 'dagger' => '†',
178 'image' => 'ℑ',
179 'alefsym' => 'ℵ',
185 'frasl' => '⁄',
187 'lowast' => '∗',
198 'oline' => '‾',
205 'empty' => '∅',
212 'weierp' => '℘',
217 'omicron' => 'ο',
218 'upsilon' => 'υ',
220 'Lambda' => 'Λ',
227 'scaron' => 'š',
228 'lsquo' => '‘',
236 'hellip' => '…',
240 'rfloor' => '⌋',
242 'crarr' => '↵',
244 'notin' => '∉',
245 'exist' => '∃',
248 'Dagger' => '‡',
249 'oplus' => '⊕',
255 'lsaquo' => '‹',
257 'Omicron' => 'Ο',
272 'sigmaf' => 'ς',
274 'minus' => '−',
277 'epsilon' => 'ε',
288 'spades' => '♠',
289 'rsquo' => '’',
293 'thetasym' => 'ϑ',
297 'ldquo' => '“',
298 'hearts' => '♥',
311 # miscellaneous useful functions
313 @@bot = nil unless defined? @@bot
314 @@safe_save_dir = nil unless defined?(@@safe_save_dir)
321 debug "initializing utils"
323 @@safe_save_dir = "#{@@bot.botclass}/safe_save"
328 SEC_PER_HR = SEC_PER_MIN * 60
329 SEC_PER_DAY = SEC_PER_HR * 24
330 SEC_PER_MNTH = SEC_PER_DAY * 30
331 SEC_PER_YR = SEC_PER_MNTH * 12
333 def Utils.secs_to_string_case(array, var, string, plural)
336 array << "1 #{string}"
338 array << "#{var} #{plural}"
342 # turn a number of seconds into a human readable string, e.g
343 # 2 days, 3 hours, 18 minutes, 10 seconds
344 def Utils.secs_to_string(secs)
346 years, secs = secs.divmod SEC_PER_YR
347 secs_to_string_case(ret, years, "year", "years") if years > 0
348 months, secs = secs.divmod SEC_PER_MNTH
349 secs_to_string_case(ret, months, "month", "months") if months > 0
350 days, secs = secs.divmod SEC_PER_DAY
351 secs_to_string_case(ret, days, "day", "days") if days > 0
352 hours, secs = secs.divmod SEC_PER_HR
353 secs_to_string_case(ret, hours, "hour", "hours") if hours > 0
354 mins, secs = secs.divmod SEC_PER_MIN
355 secs_to_string_case(ret, mins, "minute", "minutes") if mins > 0
357 secs_to_string_case(ret, secs, "second", "seconds") if secs > 0 or ret.empty?
360 raise "Empty ret array!"
364 return [ret[0, ret.length-1].join(", ") , ret[-1]].join(" and ")
369 def Utils.safe_exec(command, *args)
372 return p.readlines.join("\n")
377 rescue Exception => e
378 puts "exec of #{command} led to exception: #{e.inspect}"
381 puts "exec of #{command} failed"
388 def Utils.safe_save(file)
389 raise 'No safe save directory defined!' if @@safe_save_dir.nil?
390 basename = File.basename(file)
391 temp = Tempfile.new(basename,@@safe_save_dir)
393 yield temp if block_given?
395 File.rename(temp.path, file)
399 def Utils.decode_html_entities(str)
400 if $we_have_html_entities_decoder
401 return HTMLEntities.decode_entities(str)
403 str.gsub(/(&(.+?);)/) {
405 # remove the 0-paddng from unicode integers
407 symbol = "##{$1.to_i.to_s}"
410 # output the symbol's irc-translated character, or a * if it's unknown
411 UNESCAPE_TABLE[symbol] || [symbol[/\d+/].to_i].pack("U") rescue '*'
416 HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
417 PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
419 # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
420 # to mark actual text
421 AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
423 # At worst, we can try stuff which is comprised between two <br>
424 AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
426 # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
427 # If possible, grab the one after the first heading
429 # It is possible to pass some options to determine how the stripping
430 # occurs. Currently supported options are
431 # * :strip => Regex or String to strip at the beginning of the obtained
433 # * :min_spaces => Minimum number of spaces a paragraph should have
435 def Utils.ircify_first_html_par(xml_org, opts={})
436 xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
439 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
441 min_spaces = opts[:min_spaces] || 8
442 min_spaces = 0 if min_spaces < 0
447 debug "Minimum number of spaces: #{min_spaces}"
448 header_found = xml.match(HX_REGEX)
451 while txt.empty? or txt.count(" ") < min_spaces
452 candidate = header_found[PAR_REGEX]
453 break unless candidate
454 txt = candidate.ircify_html
456 txt.sub!(strip, '') if strip
457 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
461 return txt unless txt.empty? or txt.count(" ") < min_spaces
463 # If we haven't found a first par yet, try to get it from the whole
466 while txt.empty? or txt.count(" ") < min_spaces
467 candidate = header_found[PAR_REGEX]
468 break unless candidate
469 txt = candidate.ircify_html
471 txt.sub!(strip, '') if strip
472 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
475 return txt unless txt.empty? or txt.count(" ") < min_spaces
477 # Nothing yet ... let's get drastic: we look for non-par elements too,
478 # but only for those that match something that we know is likely to
483 while txt.empty? or txt.count(" ") < min_spaces
484 candidate = header_found[AFTER_PAR1_REGEX]
485 break unless candidate
486 txt = candidate.ircify_html
488 txt.sub!(strip, '') if strip
489 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
492 return txt unless txt.empty? or txt.count(" ") < min_spaces
496 while txt.empty? or txt.count(" ") < min_spaces
497 candidate = header_found[AFTER_PAR2_REGEX]
498 break unless candidate
499 txt = candidate.ircify_html
501 txt.sub!(strip, '') if strip
502 debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
505 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
506 return txt unless txt.count(" ") < min_spaces
511 # Get the first pars of the first _count_ _urls_.
512 # The pages are downloaded using the bot httputil service.
513 # Returns an array of the first paragraphs fetched.
514 # If (optional) _opts_ :message is specified, those paragraphs are
515 # echoed as replies to the IRC message passed as _opts_ :message
517 def Utils.get_first_pars(urls, count, opts={})
521 while count > 0 and urls.length > 0
525 # FIXME what happens if some big file is returned? We should share
526 # code with the url plugin to only retrieve partial file content!
527 xml = self.bot.httputil.get(url)
529 debug "Unable to retrieve #{url}"
532 par = Utils.ircify_first_html_par(xml, opts)
534 debug "No first par found\n#{xml}"
535 # FIXME only do this if the 'url' plugin is loaded
536 # TODO even better, put the code here
537 # par = @bot.plugins['url'].get_title_from_html(xml)
543 msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
554 Irc::Utils.bot = Irc::Plugins.manager.bot