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
183 SEC_PER_WK = SEC_PER_DAY * 7
184 # Seconds per (30-day) month
185 SEC_PER_MNTH = SEC_PER_DAY * 30
186 # Second per (non-leap) year
187 SEC_PER_YR = SEC_PER_DAY * 365
189 # Auxiliary method needed by Utils.secs_to_string
190 def Utils.secs_to_string_case(array, var, string, plural)
193 array << "1 #{string}"
195 array << "#{var} #{plural}"
199 # Turn a number of seconds into a human readable string, e.g
200 # 2 days, 3 hours, 18 minutes and 10 seconds
201 def Utils.secs_to_string(secs)
203 years, secs = secs.divmod SEC_PER_YR
204 secs_to_string_case(ret, years, _("year"), _("years")) if years > 0
205 months, secs = secs.divmod SEC_PER_MNTH
206 secs_to_string_case(ret, months, _("month"), _("months")) if months > 0
207 days, secs = secs.divmod SEC_PER_DAY
208 secs_to_string_case(ret, days, _("day"), _("days")) if days > 0
209 hours, secs = secs.divmod SEC_PER_HR
210 secs_to_string_case(ret, hours, _("hour"), _("hours")) if hours > 0
211 mins, secs = secs.divmod SEC_PER_MIN
212 secs_to_string_case(ret, mins, _("minute"), _("minutes")) if mins > 0
214 secs_to_string_case(ret, secs, _("second"), _("seconds")) if secs > 0 or ret.empty?
217 raise "Empty ret array!"
221 return [ret[0, ret.length-1].join(", ") , ret[-1]].join(_(" and "))
225 # Turn a number of seconds into a hours:minutes:seconds e.g.
226 # 3:18:10 or 5'12" or 7s
228 def Utils.secs_to_short(seconds)
229 secs = seconds.to_i # make sure it's an integer
230 mins, secs = secs.divmod 60
231 hours, mins = mins.divmod 60
233 return ("%s:%s:%s" % [hours, mins, secs])
235 return ("%s'%s\"" % [mins, secs])
237 return ("%ss" % [secs])
241 # Returns human readable time.
245 # :start_date, sets the time to measure against, defaults to now
246 # :date_format, used with <tt>to_formatted_s<tt>, default to :default
247 def Utils.timeago(time, options = {})
248 start_date = options.delete(:start_date) || Time.new
249 date_format = options.delete(:date_format) || "%x"
250 delta = (start_date - time).round
254 distance = Utils.age_string(delta)
256 _("%{d} from now") % {:d => distance}
258 _("%{d} ago") % {:d => distance}
263 # Converts age in seconds to "nn units". Inspired by previous attempts
264 # but also gitweb's age_string() sub
265 def Utils.age_string(secs)
268 Utils.age_string(-secs)
269 when secs > 2*SEC_PER_YR
270 _("%{m} years") % { :m => secs/SEC_PER_YR }
271 when secs > 2*SEC_PER_MNTH
272 _("%{m} months") % { :m => secs/SEC_PER_MNTH }
273 when secs > 2*SEC_PER_WK
274 _("%{m} weeks") % { :m => secs/SEC_PER_WK }
275 when secs > 2*SEC_PER_DAY
276 _("%{m} days") % { :m => secs/SEC_PER_DAY }
277 when secs > 2*SEC_PER_HR
278 _("%{m} hours") % { :m => secs/SEC_PER_HR }
279 when (20*SEC_PER_MIN..40*SEC_PER_MIN).include?(secs)
281 when (50*SEC_PER_MIN..70*SEC_PER_MIN).include?(secs)
282 # _("about one hour")
284 when (80*SEC_PER_MIN..100*SEC_PER_MIN).include?(secs)
285 _("an hour and a half")
286 when secs > 2*SEC_PER_MIN
287 _("%{m} minutes") % { :m => secs/SEC_PER_MIN }
289 _("%{m} seconds") % { :m => secs }
295 # Execute an external program, returning a String obtained by redirecting
296 # the program's standards errors and output
298 def Utils.safe_exec(command, *args)
301 return p.readlines.join("\n")
304 $stderr.reopen($stdout)
306 rescue Exception => e
307 puts "exec of #{command} led to exception: #{e.pretty_inspect}"
310 puts "exec of #{command} failed"
317 # Safely (atomically) save to _file_, by passing a tempfile to the block
318 # and then moving the tempfile to its final location when done.
320 # call-seq: Utils.safe_save(file, &block)
322 def Utils.safe_save(file)
323 raise 'No safe save directory defined!' if @@safe_save_dir.nil?
324 basename = File.basename(file)
325 temp = Tempfile.new(basename,@@safe_save_dir)
327 yield temp if block_given?
329 File.rename(temp.path, file)
333 # Decode HTML entities in the String _str_, using HTMLEntities if the
334 # package was found, or UNESCAPE_TABLE otherwise.
336 def Utils.decode_html_entities(str)
337 if defined? ::HTMLEntities
338 return HTMLEntities.decode_entities(str)
340 str.gsub(/(&(.+?);)/) {
342 # remove the 0-paddng from unicode integers
343 if symbol =~ /^#(\d+)$/
344 symbol = $1.to_i.to_s
347 # output the symbol's irc-translated character, or a * if it's unknown
348 UNESCAPE_TABLE[symbol] || (symbol.match(/^\d+$/) ? [symbol.to_i].pack("U") : '*')
353 # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
354 # If possible, grab the one after the first heading
356 # It is possible to pass some options to determine how the stripping
357 # occurs. Currently supported options are
358 # strip:: Regex or String to strip at the beginning of the obtained
360 # min_spaces:: minimum number of spaces a paragraph should have
362 def Utils.ircify_first_html_par(xml_org, opts={})
363 if defined? ::Hpricot
364 Utils.ircify_first_html_par_wh(xml_org, opts)
366 Utils.ircify_first_html_par_woh(xml_org, opts)
370 # HTML first par grabber using hpricot
371 def Utils.ircify_first_html_par_wh(xml_org, opts={})
372 doc = Hpricot(xml_org)
374 # Strip styles and scripts
375 (doc/"style|script").remove
380 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
382 min_spaces = opts[:min_spaces] || 8
383 min_spaces = 0 if min_spaces < 0
387 pre_h = pars = by_span = nil
390 debug "Minimum number of spaces: #{min_spaces}"
392 # Initial attempt: <p> that follows <h\d>
394 pre_h = Hpricot::Elements[]
396 doc.search("*") { |e|
402 pre_h << e if found_h
405 debug "Hx: found: #{pre_h.pretty_inspect}"
410 txt = p.to_html.ircify_html
411 txt.sub!(strip, '') if strip
412 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
413 break unless txt.empty? or txt.count(" ") < min_spaces
416 return txt unless txt.empty? or txt.count(" ") < min_spaces
418 # Second natural attempt: just get any <p>
419 pars = doc/"p" if pars.nil?
420 debug "par: found: #{pars.pretty_inspect}"
423 txt = p.to_html.ircify_html
424 txt.sub!(strip, '') if strip
425 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
426 break unless txt.empty? or txt.count(" ") < min_spaces
429 return txt unless txt.empty? or txt.count(" ") < min_spaces
431 # Nothing yet ... let's get drastic: we look for non-par elements too,
432 # but only for those that match something that we know is likely to
435 # Some blogging and forum platforms use spans or divs with a 'body' or
436 # 'message' or 'text' in their class to mark actual text. Since we want
437 # the class match to be partial and case insensitive, we collect
438 # the common elements that may have this class and then filter out those
439 # we don't need. If no divs or spans are found, we'll accept additional
440 # elements too (td, tr, tbody, table).
442 by_span = Hpricot::Elements[]
443 extra = Hpricot::Elements[]
444 doc.search("*") { |el|
445 next if el.bogusetag?
448 by_span.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
450 extra.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
453 if by_span.empty? and not extra.empty?
456 debug "other \#1: found: #{by_span.pretty_inspect}"
461 txt = p.to_html.ircify_html
462 txt.sub!(strip, '') if strip
463 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
464 break unless txt.empty? or txt.count(" ") < min_spaces
467 return txt unless txt.empty? or txt.count(" ") < min_spaces
469 # At worst, we can try stuff which is comprised between two <br>
472 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
473 return txt unless txt.count(" ") < min_spaces
474 break if min_spaces == 0
479 # HTML first par grabber without hpricot
480 def Utils.ircify_first_html_par_woh(xml_org, opts={})
481 xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
484 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
486 min_spaces = opts[:min_spaces] || 8
487 min_spaces = 0 if min_spaces < 0
492 debug "Minimum number of spaces: #{min_spaces}"
493 header_found = xml.match(HX_REGEX)
496 while txt.empty? or txt.count(" ") < min_spaces
497 candidate = header_found[PAR_REGEX]
498 break unless candidate
499 txt = candidate.ircify_html
501 txt.sub!(strip, '') if strip
502 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
506 return txt unless txt.empty? or txt.count(" ") < min_spaces
508 # If we haven't found a first par yet, try to get it from the whole
511 while txt.empty? or txt.count(" ") < min_spaces
512 candidate = header_found[PAR_REGEX]
513 break unless candidate
514 txt = candidate.ircify_html
516 txt.sub!(strip, '') if strip
517 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
520 return txt unless txt.empty? or txt.count(" ") < min_spaces
522 # Nothing yet ... let's get drastic: we look for non-par elements too,
523 # but only for those that match something that we know is likely to
528 while txt.empty? or txt.count(" ") < min_spaces
529 candidate = header_found[AFTER_PAR1_REGEX]
530 break unless candidate
531 txt = candidate.ircify_html
533 txt.sub!(strip, '') if strip
534 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
537 return txt unless txt.empty? or txt.count(" ") < min_spaces
541 while txt.empty? or txt.count(" ") < min_spaces
542 candidate = header_found[AFTER_PAR2_REGEX]
543 break unless candidate
544 txt = candidate.ircify_html
546 txt.sub!(strip, '') if strip
547 debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
550 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
551 return txt unless txt.count(" ") < min_spaces
552 break if min_spaces == 0
557 # This method extracts title, content (first par) and extra
558 # information from the given document _doc_.
560 # _doc_ can be an URI, a Net::HTTPResponse or a String.
562 # If _doc_ is a String, only title and content information
563 # are retrieved (if possible), using standard methods.
565 # If _doc_ is an URI or a Net::HTTPResponse, additional
566 # information is retrieved, and special title/summary
567 # extraction routines are used if possible.
569 def Utils.get_html_info(doc, opts={})
572 Utils.get_string_html_info(doc, opts)
573 when Net::HTTPResponse
574 Utils.get_resp_html_info(doc, opts)
577 @@bot.httputil.get_response(doc) { |resp|
578 ret.replace Utils.get_resp_html_info(resp, opts)
586 class ::UrlLinkError < RuntimeError
589 # This method extracts title, content (first par) and extra
590 # information from the given Net::HTTPResponse _resp_.
592 # Currently, the only accepted options (in _opts_) are
593 # uri_fragment:: the URI fragment of the original request
594 # full_body:: get the whole body instead of
595 # @@bot.config['http.info_bytes'] bytes only
597 # Returns a DataStream with the following keys:
598 # text:: the (partial) body
599 # title:: the title of the document (if any)
600 # content:: the first paragraph of the document (if any)
602 # the headers of the Net::HTTPResponse. The value is
603 # a Hash whose keys are lowercase forms of the HTTP
604 # header fields, and whose values are Arrays.
606 def Utils.get_resp_html_info(resp, opts={})
608 when Net::HTTPSuccess
609 loc = URI.parse(resp['x-rbot-location'] || resp['location']) rescue nil
610 if loc and loc.fragment and not loc.fragment.empty?
611 opts[:uri_fragment] ||= loc.fragment
613 ret = DataStream.new(opts.dup)
614 ret[:headers] = resp.to_hash
615 ret[:text] = partial = opts[:full_body] ? resp.body : resp.partial_body(@@bot.config['http.info_bytes'])
617 filtered = Utils.try_htmlinfo_filters(ret)
621 elsif resp['content-type'] =~ /^text\/|(?:x|ht)ml/
622 ret.merge!(Utils.get_string_html_info(partial, opts))
626 raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
630 # This method runs an appropriately-crafted DataStream _ds_ through the
631 # filters in the :htmlinfo filter group, in order. If one of the filters
632 # returns non-nil, its results are merged in _ds_ and returned. Otherwise
635 # The input DataStream should have the downloaded HTML as primary key
636 # (:text) and possibly a :headers key holding the resonse headers.
638 def Utils.try_htmlinfo_filters(ds)
639 filters = @@bot.filter_names(:htmlinfo)
640 return nil if filters.empty?
642 # TODO filter priority
644 debug "testing htmlinfo filter #{n}"
645 cur = @@bot.filter(@@bot.global_filter_name(n, :htmlinfo), ds)
646 debug "returned #{cur.pretty_inspect}"
649 return ds.merge(cur) if cur
652 # HTML info filters often need to check if the webpage location
653 # of a passed DataStream _ds_ matches a given Regexp.
654 def Utils.check_location(ds, rx)
657 loc = [h['x-rbot-location'],h['location']].flatten.grep(rx)
661 return loc.empty? ? nil : loc
664 # This method extracts title and content (first par)
665 # from the given HTML or XML document _text_, using
666 # standard methods (String#ircify_html_title,
667 # Utils.ircify_first_html_par)
669 # Currently, the only accepted option (in _opts_) is
670 # uri_fragment:: the URI fragment of the original request
672 def Utils.get_string_html_info(text, opts={})
673 debug "getting string html info"
675 title = txt.ircify_html_title
677 if frag = opts[:uri_fragment] and not frag.empty?
678 fragreg = /<a\s+(?:[^>]+\s+)?(?:name|id)=["']?#{frag}["']?[^>]*>/im
681 if txt.match(fragreg)
682 # grab the post-match
688 c_opts[:strip] ||= title
689 content = Utils.ircify_first_html_par(txt, c_opts)
690 content = nil if content.empty?
691 return {:title => title, :content => content}
694 # Get the first pars of the first _count_ _urls_.
695 # The pages are downloaded using the bot httputil service.
696 # Returns an array of the first paragraphs fetched.
697 # If (optional) _opts_ :message is specified, those paragraphs are
698 # echoed as replies to the IRC message passed as _opts_ :message
700 def Utils.get_first_pars(urls, count, opts={})
704 while count > 0 and urls.length > 0
709 info = Utils.get_html_info(URI.parse(url), opts)
715 msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
719 debug "Unable to retrieve #{url}: #{$!}"
729 Irc::Utils.bot = Irc::Bot::Plugins.manager.bot