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
314 SEC_PER_HR = SEC_PER_MIN * 60
315 SEC_PER_DAY = SEC_PER_HR * 24
316 SEC_PER_MNTH = SEC_PER_DAY * 30
317 SEC_PER_YR = SEC_PER_MNTH * 12
319 @@bot = nil unless defined? @@bot
320 @@safe_save_dir = nil unless defined?(@@safe_save_dir)
328 @@safe_save_dir = "#{@@bot.botclass}/safe_save"
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")
375 rescue Exception => e
376 puts "exec of #{command} led to exception: #{e.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)
396 def Utils.decode_html_entities(str)
397 if $we_have_html_entities_decoder
398 return HTMLEntities.decode_entities(str)
400 str.gsub(/(&(.+?);)/) {
402 # remove the 0-paddng from unicode integers
404 symbol = "##{$1.to_i.to_s}"
407 # output the symbol's irc-translated character, or a * if it's unknown
408 UNESCAPE_TABLE[symbol] || [symbol[/\d+/].to_i].pack("U") rescue '*'
413 HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
414 PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
416 # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
417 # to mark actual text
418 AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
420 # At worst, we can try stuff which is comprised between two <br>
421 AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
423 # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
424 # If possible, grab the one after the first heading
426 # It is possible to pass some options to determine how the stripping
427 # occurs. Currently supported options are
428 # * :strip => Regex or String to strip at the beginning of the obtained
430 # * :min_spaces => Minimum number of spaces a paragraph should have
432 def Utils.ircify_first_html_par(xml_org, opts={})
433 xml = xml_org.gsub(/<!--.*?-->/, '')
436 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
438 min_spaces = opts[:min_spaces] || 8
439 min_spaces = 0 if min_spaces < 0
444 debug "Minimum number of spaces: #{min_spaces}"
445 header_found = xml.match(HX_REGEX)
448 while txt.empty? or txt.count(" ") < min_spaces
449 candidate = header_found[PAR_REGEX]
450 break unless candidate
451 txt = candidate.ircify_html
453 txt.sub!(strip, '') if strip
454 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
458 return txt unless txt.empty? or txt.count(" ") < min_spaces
460 # If we haven't found a first par yet, try to get it from the whole
463 while txt.empty? or txt.count(" ") < min_spaces
464 candidate = header_found[PAR_REGEX]
465 break unless candidate
466 txt = candidate.ircify_html
468 txt.sub!(strip, '') if strip
469 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
472 return txt unless txt.empty? or txt.count(" ") < min_spaces
474 # Nothing yet ... let's get drastic: we look for non-par elements too,
475 # but only for those that match something that we know is likely to
480 while txt.empty? or txt.count(" ") < min_spaces
481 candidate = header_found[AFTER_PAR1_REGEX]
482 break unless candidate
483 txt = candidate.ircify_html
485 txt.sub!(strip, '') if strip
486 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
489 return txt unless txt.empty? or txt.count(" ") < min_spaces
493 while txt.empty? or txt.count(" ") < min_spaces
494 candidate = header_found[AFTER_PAR2_REGEX]
495 break unless candidate
496 txt = candidate.ircify_html
498 txt.sub!(strip, '') if strip
499 debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
502 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
503 return txt unless txt.count(" ") < min_spaces
508 # Get the first pars of the first _count_ _urls_.
509 # The pages are downloaded using the bot httputil service.
510 # Returns an array of the first paragraphs fetched.
511 # If (optional) _opts_ :message is specified, those paragraphs are
512 # echoed as replies to the IRC message passed as _opts_ :message
514 def Utils.get_first_pars(urls, count, opts={})
518 while count > 0 and urls.length > 0
522 # FIXME what happens if some big file is returned? We should share
523 # code with the url plugin to only retrieve partial file content!
524 xml = self.bot.httputil.get_cached(url)
526 debug "Unable to retrieve #{url}"
529 par = Utils.ircify_first_html_par(xml, opts)
531 debug "No first par found\n#{xml}"
532 # FIXME only do this if the 'url' plugin is loaded
533 # TODO even better, put the code here
534 # par = @bot.plugins['url'].get_title_from_html(xml)
537 msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg