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' => '♥',
309 # miscellaneous useful functions
311 @@bot = nil unless defined? @@bot
312 @@safe_save_dir = nil unless defined?(@@safe_save_dir)
319 debug "initializing utils"
321 @@safe_save_dir = "#{@@bot.botclass}/safe_save"
326 SEC_PER_HR = SEC_PER_MIN * 60
327 SEC_PER_DAY = SEC_PER_HR * 24
328 SEC_PER_MNTH = SEC_PER_DAY * 30
329 SEC_PER_YR = SEC_PER_MNTH * 12
331 def Utils.secs_to_string_case(array, var, string, plural)
334 array << "1 #{string}"
336 array << "#{var} #{plural}"
340 # turn a number of seconds into a human readable string, e.g
341 # 2 days, 3 hours, 18 minutes, 10 seconds
342 def Utils.secs_to_string(secs)
344 years, secs = secs.divmod SEC_PER_YR
345 secs_to_string_case(ret, years, _("year"), _("years")) if years > 0
346 months, secs = secs.divmod SEC_PER_MNTH
347 secs_to_string_case(ret, months, _("month"), _("months")) if months > 0
348 days, secs = secs.divmod SEC_PER_DAY
349 secs_to_string_case(ret, days, _("day"), _("days")) if days > 0
350 hours, secs = secs.divmod SEC_PER_HR
351 secs_to_string_case(ret, hours, _("hour"), _("hours")) if hours > 0
352 mins, secs = secs.divmod SEC_PER_MIN
353 secs_to_string_case(ret, mins, _("minute"), _("minutes")) if mins > 0
355 secs_to_string_case(ret, secs, _("second"), _("seconds")) if secs > 0 or ret.empty?
358 raise "Empty ret array!"
362 return [ret[0, ret.length-1].join(", ") , ret[-1]].join(_(" and "))
367 def Utils.safe_exec(command, *args)
370 return p.readlines.join("\n")
373 $stderr.reopen($stdout)
375 rescue Exception => e
376 puts "exec of #{command} led to exception: #{e.pretty_inspect}"
379 puts "exec of #{command} failed"
386 def Utils.safe_save(file)
387 raise 'No safe save directory defined!' if @@safe_save_dir.nil?
388 basename = File.basename(file)
389 temp = Tempfile.new(basename,@@safe_save_dir)
391 yield temp if block_given?
393 File.rename(temp.path, file)
397 def Utils.decode_html_entities(str)
398 if defined? ::HTMLEntities
399 return HTMLEntities.decode_entities(str)
401 str.gsub(/(&(.+?);)/) {
403 # remove the 0-paddng from unicode integers
405 symbol = "##{$1.to_i.to_s}"
408 # output the symbol's irc-translated character, or a * if it's unknown
409 UNESCAPE_TABLE[symbol] || [symbol[/\d+/].to_i].pack("U") rescue '*'
414 HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
415 PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
417 # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
418 # to mark actual text
419 AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
421 # At worst, we can try stuff which is comprised between two <br>
422 AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
424 # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
425 # If possible, grab the one after the first heading
427 # It is possible to pass some options to determine how the stripping
428 # occurs. Currently supported options are
429 # * :strip => Regex or String to strip at the beginning of the obtained
431 # * :min_spaces => Minimum number of spaces a paragraph should have
433 def Utils.ircify_first_html_par(xml_org, opts={})
434 xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
437 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
439 min_spaces = opts[:min_spaces] || 8
440 min_spaces = 0 if min_spaces < 0
445 debug "Minimum number of spaces: #{min_spaces}"
446 header_found = xml.match(HX_REGEX)
449 while txt.empty? or txt.count(" ") < min_spaces
450 candidate = header_found[PAR_REGEX]
451 break unless candidate
452 txt = candidate.ircify_html
454 txt.sub!(strip, '') if strip
455 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
459 return txt unless txt.empty? or txt.count(" ") < min_spaces
461 # If we haven't found a first par yet, try to get it from the whole
464 while txt.empty? or txt.count(" ") < min_spaces
465 candidate = header_found[PAR_REGEX]
466 break unless candidate
467 txt = candidate.ircify_html
469 txt.sub!(strip, '') if strip
470 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
473 return txt unless txt.empty? or txt.count(" ") < min_spaces
475 # Nothing yet ... let's get drastic: we look for non-par elements too,
476 # but only for those that match something that we know is likely to
481 while txt.empty? or txt.count(" ") < min_spaces
482 candidate = header_found[AFTER_PAR1_REGEX]
483 break unless candidate
484 txt = candidate.ircify_html
486 txt.sub!(strip, '') if strip
487 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
490 return txt unless txt.empty? or txt.count(" ") < min_spaces
494 while txt.empty? or txt.count(" ") < min_spaces
495 candidate = header_found[AFTER_PAR2_REGEX]
496 break unless candidate
497 txt = candidate.ircify_html
499 txt.sub!(strip, '') if strip
500 debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
503 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
504 return txt unless txt.count(" ") < min_spaces
509 # Get the first pars of the first _count_ _urls_.
510 # The pages are downloaded using the bot httputil service.
511 # Returns an array of the first paragraphs fetched.
512 # If (optional) _opts_ :message is specified, those paragraphs are
513 # echoed as replies to the IRC message passed as _opts_ :message
515 def Utils.get_first_pars(urls, count, opts={})
519 while count > 0 and urls.length > 0
523 # FIXME what happens if some big file is returned? We should share
524 # code with the url plugin to only retrieve partial file content!
525 xml = self.bot.httputil.get(url)
527 debug "Unable to retrieve #{url}"
530 par = Utils.ircify_first_html_par(xml, opts)
532 debug "No first par found\n#{xml}"
533 # FIXME only do this if the 'url' plugin is loaded
534 # TODO even better, put the code here
535 # par = @bot.plugins['url'].get_title_from_html(xml)
541 msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
551 Irc::Utils.bot = Irc::Plugins.manager.bot