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
21 require 'htmlentities'
22 $we_have_html_entities_decoder = true
26 gems = require 'rubygems'
33 $we_have_html_entities_decoder = false
56 # extras codes, for future use...
70 'otimes' => '⊗',
79 'Epsilon' => 'Ε',
83 'Upsilon' => 'Υ',
85 'there4' => '∴',
90 'rsaquo' => '›',
102 'lceil' => '⌈',
104 'rdquo' => '”',
112 'lfloor' => '⌊',
119 'clubs' => '♣',
120 'diams' => '♦',
127 'Scaron' => 'Š',
133 'sbquo' => '‚',
146 'infin' => '∞',
151 'thinsp' => ' ',
153 'bdquo' => '„',
160 'mdash' => '—',
162 'permil' => '‰',
167 'forall' => '∀',
169 'rceil' => '⌉',
172 'lambda' => 'λ',
176 'dagger' => '†',
179 'image' => 'ℑ',
180 'alefsym' => 'ℵ',
186 'frasl' => '⁄',
188 'lowast' => '∗',
199 'oline' => '‾',
206 'empty' => '∅',
213 'weierp' => '℘',
218 'omicron' => 'ο',
219 'upsilon' => 'υ',
221 'Lambda' => 'Λ',
228 'scaron' => 'š',
229 'lsquo' => '‘',
237 'hellip' => '…',
241 'rfloor' => '⌋',
243 'crarr' => '↵',
245 'notin' => '∉',
246 'exist' => '∃',
249 'Dagger' => '‡',
250 'oplus' => '⊕',
256 'lsaquo' => '‹',
258 'Omicron' => 'Ο',
273 'sigmaf' => 'ς',
275 'minus' => '−',
278 'epsilon' => 'ε',
289 'spades' => '♠',
290 'rsquo' => '’',
294 'thetasym' => 'ϑ',
298 'ldquo' => '“',
299 'hearts' => '♥',
312 # miscellaneous useful functions
314 @@bot = nil unless defined? @@bot
315 @@safe_save_dir = nil unless defined?(@@safe_save_dir)
322 debug "initializing utils"
324 @@safe_save_dir = "#{@@bot.botclass}/safe_save"
329 SEC_PER_HR = SEC_PER_MIN * 60
330 SEC_PER_DAY = SEC_PER_HR * 24
331 SEC_PER_MNTH = SEC_PER_DAY * 30
332 SEC_PER_YR = SEC_PER_MNTH * 12
334 def Utils.secs_to_string_case(array, var, string, plural)
337 array << "1 #{string}"
339 array << "#{var} #{plural}"
343 # turn a number of seconds into a human readable string, e.g
344 # 2 days, 3 hours, 18 minutes, 10 seconds
345 def Utils.secs_to_string(secs)
347 years, secs = secs.divmod SEC_PER_YR
348 secs_to_string_case(ret, years, "year", "years") if years > 0
349 months, secs = secs.divmod SEC_PER_MNTH
350 secs_to_string_case(ret, months, "month", "months") if months > 0
351 days, secs = secs.divmod SEC_PER_DAY
352 secs_to_string_case(ret, days, "day", "days") if days > 0
353 hours, secs = secs.divmod SEC_PER_HR
354 secs_to_string_case(ret, hours, "hour", "hours") if hours > 0
355 mins, secs = secs.divmod SEC_PER_MIN
356 secs_to_string_case(ret, mins, "minute", "minutes") if mins > 0
358 secs_to_string_case(ret, secs, "second", "seconds") if secs > 0 or ret.empty?
361 raise "Empty ret array!"
365 return [ret[0, ret.length-1].join(", ") , ret[-1]].join(" and ")
370 def Utils.safe_exec(command, *args)
373 return p.readlines.join("\n")
376 $stderr.reopen($stdout)
378 rescue Exception => e
379 puts "exec of #{command} led to exception: #{e.inspect}"
382 puts "exec of #{command} failed"
389 def Utils.safe_save(file)
390 raise 'No safe save directory defined!' if @@safe_save_dir.nil?
391 basename = File.basename(file)
392 temp = Tempfile.new(basename,@@safe_save_dir)
394 yield temp if block_given?
396 File.rename(temp.path, file)
400 def Utils.decode_html_entities(str)
401 if $we_have_html_entities_decoder
402 return HTMLEntities.decode_entities(str)
404 str.gsub(/(&(.+?);)/) {
406 # remove the 0-paddng from unicode integers
408 symbol = "##{$1.to_i.to_s}"
411 # output the symbol's irc-translated character, or a * if it's unknown
412 UNESCAPE_TABLE[symbol] || [symbol[/\d+/].to_i].pack("U") rescue '*'
417 HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
418 PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
420 # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
421 # to mark actual text
422 AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
424 # At worst, we can try stuff which is comprised between two <br>
425 AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
427 # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
428 # If possible, grab the one after the first heading
430 # It is possible to pass some options to determine how the stripping
431 # occurs. Currently supported options are
432 # * :strip => Regex or String to strip at the beginning of the obtained
434 # * :min_spaces => Minimum number of spaces a paragraph should have
436 def Utils.ircify_first_html_par(xml_org, opts={})
437 xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
440 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
442 min_spaces = opts[:min_spaces] || 8
443 min_spaces = 0 if min_spaces < 0
448 debug "Minimum number of spaces: #{min_spaces}"
449 header_found = xml.match(HX_REGEX)
452 while txt.empty? or txt.count(" ") < min_spaces
453 candidate = header_found[PAR_REGEX]
454 break unless candidate
455 txt = candidate.ircify_html
457 txt.sub!(strip, '') if strip
458 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
462 return txt unless txt.empty? or txt.count(" ") < min_spaces
464 # If we haven't found a first par yet, try to get it from the whole
467 while txt.empty? or txt.count(" ") < min_spaces
468 candidate = header_found[PAR_REGEX]
469 break unless candidate
470 txt = candidate.ircify_html
472 txt.sub!(strip, '') if strip
473 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
476 return txt unless txt.empty? or txt.count(" ") < min_spaces
478 # Nothing yet ... let's get drastic: we look for non-par elements too,
479 # but only for those that match something that we know is likely to
484 while txt.empty? or txt.count(" ") < min_spaces
485 candidate = header_found[AFTER_PAR1_REGEX]
486 break unless candidate
487 txt = candidate.ircify_html
489 txt.sub!(strip, '') if strip
490 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
493 return txt unless txt.empty? or txt.count(" ") < min_spaces
497 while txt.empty? or txt.count(" ") < min_spaces
498 candidate = header_found[AFTER_PAR2_REGEX]
499 break unless candidate
500 txt = candidate.ircify_html
502 txt.sub!(strip, '') if strip
503 debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
506 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
507 return txt unless txt.count(" ") < min_spaces
512 # Get the first pars of the first _count_ _urls_.
513 # The pages are downloaded using the bot httputil service.
514 # Returns an array of the first paragraphs fetched.
515 # If (optional) _opts_ :message is specified, those paragraphs are
516 # echoed as replies to the IRC message passed as _opts_ :message
518 def Utils.get_first_pars(urls, count, opts={})
522 while count > 0 and urls.length > 0
526 # FIXME what happens if some big file is returned? We should share
527 # code with the url plugin to only retrieve partial file content!
528 xml = self.bot.httputil.get(url)
530 debug "Unable to retrieve #{url}"
533 par = Utils.ircify_first_html_par(xml, opts)
535 debug "No first par found\n#{xml}"
536 # FIXME only do this if the 'url' plugin is loaded
537 # TODO even better, put the code here
538 # par = @bot.plugins['url'].get_title_from_html(xml)
544 msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
555 Irc::Utils.bot = Irc::Plugins.manager.bot