4 # :title: rbot utilities provider
6 # Author:: Tom Gilbert <tom@linuxbrit.co.uk>
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
9 # TODO some of these Utils should be rewritten as extensions to the approriate
10 # standard Ruby classes and accordingly be moved to extends.rb
15 # Try to load htmlentities, fall back to an HTML escape table.
17 require 'htmlentities'
21 gems = require 'rubygems'
118 AFTER_PAR_PATH = /^(?:div|span)$/
119 AFTER_PAR_EX = /^(?:td|tr|tbody|table)$/
120 AFTER_PAR_CLASS = /body|message|text/i
126 gems = require 'rubygems'
135 # Some regular expressions to manage HTML data
138 TITLE_REGEX = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
141 HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
143 PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
145 # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
146 # to mark actual text
147 AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
149 # At worst, we can try stuff which is comprised between two <br>
150 AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
158 # Miscellaneous useful functions
160 @@bot = nil unless defined? @@bot
161 @@safe_save_dir = nil unless defined?(@@safe_save_dir)
168 # Set up some Utils routines which depend on the associated bot.
170 debug "initializing utils"
172 @@safe_save_dir = "#{@@bot.botclass}/safe_save"
179 SEC_PER_HR = SEC_PER_MIN * 60
181 SEC_PER_DAY = SEC_PER_HR * 24
182 # Seconds per (30-day) month
183 SEC_PER_MNTH = SEC_PER_DAY * 30
184 # Second per (30*12 = 360 day) year
185 SEC_PER_YR = SEC_PER_MNTH * 12
187 # Auxiliary method needed by Utils.secs_to_string
188 def Utils.secs_to_string_case(array, var, string, plural)
191 array << "1 #{string}"
193 array << "#{var} #{plural}"
197 # Turn a number of seconds into a human readable string, e.g
198 # 2 days, 3 hours, 18 minutes and 10 seconds
199 def Utils.secs_to_string(secs)
201 years, secs = secs.divmod SEC_PER_YR
202 secs_to_string_case(ret, years, _("year"), _("years")) if years > 0
203 months, secs = secs.divmod SEC_PER_MNTH
204 secs_to_string_case(ret, months, _("month"), _("months")) if months > 0
205 days, secs = secs.divmod SEC_PER_DAY
206 secs_to_string_case(ret, days, _("day"), _("days")) if days > 0
207 hours, secs = secs.divmod SEC_PER_HR
208 secs_to_string_case(ret, hours, _("hour"), _("hours")) if hours > 0
209 mins, secs = secs.divmod SEC_PER_MIN
210 secs_to_string_case(ret, mins, _("minute"), _("minutes")) if mins > 0
212 secs_to_string_case(ret, secs, _("second"), _("seconds")) if secs > 0 or ret.empty?
215 raise "Empty ret array!"
219 return [ret[0, ret.length-1].join(", ") , ret[-1]].join(_(" and "))
223 # Turn a number of seconds into a hours:minutes:seconds e.g.
224 # 3:18:10 or 5'12" or 7s
226 def Utils.secs_to_short(seconds)
227 secs = seconds.to_i # make sure it's an integer
228 mins, secs = secs.divmod 60
229 hours, mins = mins.divmod 60
231 return ("%s:%s:%s" % [hours, mins, secs])
233 return ("%s'%s\"" % [mins, secs])
235 return ("%ss" % [secs])
239 # Returns human readable time.
243 # :start_date, sets the time to measure against, defaults to now
244 # :date_format, used with <tt>to_formatted_s<tt>, default to :default
245 def Utils.timeago(time, options = {})
246 start_date = options.delete(:start_date) || Time.new
247 date_format = options.delete(:date_format) || "%x"
248 delta_minutes = (start_date.to_i - time.to_i).floor / 60
249 if delta_minutes.abs <= (8724*60) # eight weeks? I'm lazy to count days for longer than that
250 distance = Utils.distance_of_time_in_words(delta_minutes);
252 _("%{d} from now") % {:d => distance}
254 _("%{d} ago") % {:d => distance}
257 return _("on %{date}") % {:date => time.strftime(date_format)}
260 # Translates a number of minutes into verbal distances.
261 # e.g. 0.5 => less than a minute
262 # 70 => about one hour
263 def Utils.distance_of_time_in_words(minutes)
266 Utils.distance_of_time_in_words(-minutes)
268 _("less than a minute")
270 _("%{m} minutes") % {:m => minutes}
274 _("%{m} hours") % {:m => (minutes / 60).round}
280 _("%{m} days") % {:m => (minutes / 1440).round}
285 # Execute an external program, returning a String obtained by redirecting
286 # the program's standards errors and output
288 def Utils.safe_exec(command, *args)
291 return p.readlines.join("\n")
294 $stderr.reopen($stdout)
296 rescue Exception => e
297 puts "exec of #{command} led to exception: #{e.pretty_inspect}"
300 puts "exec of #{command} failed"
307 # Safely (atomically) save to _file_, by passing a tempfile to the block
308 # and then moving the tempfile to its final location when done.
310 # call-seq: Utils.safe_save(file, &block)
312 def Utils.safe_save(file)
313 raise 'No safe save directory defined!' if @@safe_save_dir.nil?
314 basename = File.basename(file)
315 temp = Tempfile.new(basename,@@safe_save_dir)
317 yield temp if block_given?
319 File.rename(temp.path, file)
323 # Decode HTML entities in the String _str_, using HTMLEntities if the
324 # package was found, or UNESCAPE_TABLE otherwise.
326 def Utils.decode_html_entities(str)
327 if defined? ::HTMLEntities
328 return HTMLEntities.decode_entities(str)
330 str.gsub(/(&(.+?);)/) {
332 # remove the 0-paddng from unicode integers
333 if symbol =~ /^#(\d+)$/
334 symbol = $1.to_i.to_s
337 # output the symbol's irc-translated character, or a * if it's unknown
338 UNESCAPE_TABLE[symbol] || (symbol.match(/^\d+$/) ? [symbol.to_i].pack("U") : '*')
343 # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
344 # If possible, grab the one after the first heading
346 # It is possible to pass some options to determine how the stripping
347 # occurs. Currently supported options are
348 # strip:: Regex or String to strip at the beginning of the obtained
350 # min_spaces:: minimum number of spaces a paragraph should have
352 def Utils.ircify_first_html_par(xml_org, opts={})
353 if defined? ::Hpricot
354 Utils.ircify_first_html_par_wh(xml_org, opts)
356 Utils.ircify_first_html_par_woh(xml_org, opts)
360 # HTML first par grabber using hpricot
361 def Utils.ircify_first_html_par_wh(xml_org, opts={})
362 doc = Hpricot(xml_org)
364 # Strip styles and scripts
365 (doc/"style|script").remove
370 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
372 min_spaces = opts[:min_spaces] || 8
373 min_spaces = 0 if min_spaces < 0
377 pre_h = pars = by_span = nil
380 debug "Minimum number of spaces: #{min_spaces}"
382 # Initial attempt: <p> that follows <h\d>
384 pre_h = Hpricot::Elements[]
386 doc.search("*") { |e|
392 pre_h << e if found_h
395 debug "Hx: found: #{pre_h.pretty_inspect}"
400 txt = p.to_html.ircify_html
401 txt.sub!(strip, '') if strip
402 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
403 break unless txt.empty? or txt.count(" ") < min_spaces
406 return txt unless txt.empty? or txt.count(" ") < min_spaces
408 # Second natural attempt: just get any <p>
409 pars = doc/"p" if pars.nil?
410 debug "par: found: #{pars.pretty_inspect}"
413 txt = p.to_html.ircify_html
414 txt.sub!(strip, '') if strip
415 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
416 break unless txt.empty? or txt.count(" ") < min_spaces
419 return txt unless txt.empty? or txt.count(" ") < min_spaces
421 # Nothing yet ... let's get drastic: we look for non-par elements too,
422 # but only for those that match something that we know is likely to
425 # Some blogging and forum platforms use spans or divs with a 'body' or
426 # 'message' or 'text' in their class to mark actual text. Since we want
427 # the class match to be partial and case insensitive, we collect
428 # the common elements that may have this class and then filter out those
429 # we don't need. If no divs or spans are found, we'll accept additional
430 # elements too (td, tr, tbody, table).
432 by_span = Hpricot::Elements[]
433 extra = Hpricot::Elements[]
434 doc.search("*") { |el|
435 next if el.bogusetag?
438 by_span.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
440 extra.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
443 if by_span.empty? and not extra.empty?
446 debug "other \#1: found: #{by_span.pretty_inspect}"
451 txt = p.to_html.ircify_html
452 txt.sub!(strip, '') if strip
453 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
454 break unless txt.empty? or txt.count(" ") < min_spaces
457 return txt unless txt.empty? or txt.count(" ") < min_spaces
459 # At worst, we can try stuff which is comprised between two <br>
462 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
463 return txt unless txt.count(" ") < min_spaces
464 break if min_spaces == 0
469 # HTML first par grabber without hpricot
470 def Utils.ircify_first_html_par_woh(xml_org, opts={})
471 xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
474 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
476 min_spaces = opts[:min_spaces] || 8
477 min_spaces = 0 if min_spaces < 0
482 debug "Minimum number of spaces: #{min_spaces}"
483 header_found = xml.match(HX_REGEX)
486 while txt.empty? or txt.count(" ") < min_spaces
487 candidate = header_found[PAR_REGEX]
488 break unless candidate
489 txt = candidate.ircify_html
491 txt.sub!(strip, '') if strip
492 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
496 return txt unless txt.empty? or txt.count(" ") < min_spaces
498 # If we haven't found a first par yet, try to get it from the whole
501 while txt.empty? or txt.count(" ") < min_spaces
502 candidate = header_found[PAR_REGEX]
503 break unless candidate
504 txt = candidate.ircify_html
506 txt.sub!(strip, '') if strip
507 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
510 return txt unless txt.empty? or txt.count(" ") < min_spaces
512 # Nothing yet ... let's get drastic: we look for non-par elements too,
513 # but only for those that match something that we know is likely to
518 while txt.empty? or txt.count(" ") < min_spaces
519 candidate = header_found[AFTER_PAR1_REGEX]
520 break unless candidate
521 txt = candidate.ircify_html
523 txt.sub!(strip, '') if strip
524 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
527 return txt unless txt.empty? or txt.count(" ") < min_spaces
531 while txt.empty? or txt.count(" ") < min_spaces
532 candidate = header_found[AFTER_PAR2_REGEX]
533 break unless candidate
534 txt = candidate.ircify_html
536 txt.sub!(strip, '') if strip
537 debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
540 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
541 return txt unless txt.count(" ") < min_spaces
542 break if min_spaces == 0
547 # This method extracts title, content (first par) and extra
548 # information from the given document _doc_.
550 # _doc_ can be an URI, a Net::HTTPResponse or a String.
552 # If _doc_ is a String, only title and content information
553 # are retrieved (if possible), using standard methods.
555 # If _doc_ is an URI or a Net::HTTPResponse, additional
556 # information is retrieved, and special title/summary
557 # extraction routines are used if possible.
559 def Utils.get_html_info(doc, opts={})
562 Utils.get_string_html_info(doc, opts)
563 when Net::HTTPResponse
564 Utils.get_resp_html_info(doc, opts)
567 @@bot.httputil.get_response(doc) { |resp|
568 ret.replace Utils.get_resp_html_info(resp, opts)
576 class ::UrlLinkError < RuntimeError
579 # This method extracts title, content (first par) and extra
580 # information from the given Net::HTTPResponse _resp_.
582 # Currently, the only accepted options (in _opts_) are
583 # uri_fragment:: the URI fragment of the original request
584 # full_body:: get the whole body instead of
585 # @@bot.config['http.info_bytes'] bytes only
587 # Returns a DataStream with the following keys:
588 # text:: the (partial) body
589 # title:: the title of the document (if any)
590 # content:: the first paragraph of the document (if any)
592 # the headers of the Net::HTTPResponse. The value is
593 # a Hash whose keys are lowercase forms of the HTTP
594 # header fields, and whose values are Arrays.
596 def Utils.get_resp_html_info(resp, opts={})
598 when Net::HTTPSuccess
599 loc = URI.parse(resp['x-rbot-location'] || resp['location']) rescue nil
600 if loc and loc.fragment and not loc.fragment.empty?
601 opts[:uri_fragment] ||= loc.fragment
603 ret = DataStream.new(opts.dup)
604 ret[:headers] = resp.to_hash
605 ret[:text] = partial = opts[:full_body] ? resp.body : resp.partial_body(@@bot.config['http.info_bytes'])
607 filtered = Utils.try_htmlinfo_filters(ret)
611 elsif resp['content-type'] =~ /^text\/|(?:x|ht)ml/
612 ret.merge!(Utils.get_string_html_info(partial, opts))
616 raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
620 # This method runs an appropriately-crafted DataStream _ds_ through the
621 # filters in the :htmlinfo filter group, in order. If one of the filters
622 # returns non-nil, its results are merged in _ds_ and returned. Otherwise
625 # The input DataStream shuold have the downloaded HTML as primary key
626 # (:text) and possibly a :headers key holding the resonse headers.
628 def Utils.try_htmlinfo_filters(ds)
629 filters = @@bot.filter_names(:htmlinfo)
630 return nil if filters.empty?
632 # TODO filter priority
634 debug "testing filter #{n}"
635 cur = @@bot.filter(@@bot.global_filter_name(n, :htmlinfo), ds)
636 debug "returned #{cur.pretty_inspect}"
639 return ds.merge(cur) if cur
642 # HTML info filters often need to check if the webpage location
643 # of a passed DataStream _ds_ matches a given Regexp.
644 def Utils.check_location(ds, rx)
647 loc = [h['x-rbot-location'],h['location']].flatten.grep(rx)
651 return loc.empty? ? nil : loc
654 # This method extracts title and content (first par)
655 # from the given HTML or XML document _text_, using
656 # standard methods (String#ircify_html_title,
657 # Utils.ircify_first_html_par)
659 # Currently, the only accepted option (in _opts_) is
660 # uri_fragment:: the URI fragment of the original request
662 def Utils.get_string_html_info(text, opts={})
663 debug "getting string html info"
665 title = txt.ircify_html_title
667 if frag = opts[:uri_fragment] and not frag.empty?
668 fragreg = /<a\s+(?:[^>]+\s+)?(?:name|id)=["']?#{frag}["']?[^>]*>/im
671 if txt.match(fragreg)
672 # grab the post-match
678 c_opts[:strip] ||= title
679 content = Utils.ircify_first_html_par(txt, c_opts)
680 content = nil if content.empty?
681 return {:title => title, :content => content}
684 # Get the first pars of the first _count_ _urls_.
685 # The pages are downloaded using the bot httputil service.
686 # Returns an array of the first paragraphs fetched.
687 # If (optional) _opts_ :message is specified, those paragraphs are
688 # echoed as replies to the IRC message passed as _opts_ :message
690 def Utils.get_first_pars(urls, count, opts={})
694 while count > 0 and urls.length > 0
699 info = Utils.get_html_info(URI.parse(url), opts)
705 msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
709 debug "Unable to retrieve #{url}: #{$!}"
719 Irc::Utils.bot = Irc::Bot::Plugins.manager.bot