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'
108 require 'nokogiri/hpricot'
109 ::Hpricot = Nokogiri::Hpricot
113 AFTER_PAR_PATH = /^(?:div|span)$/
114 AFTER_PAR_EX = /^(?:td|tr|tbody|table)$/
115 AFTER_PAR_CLASS = /body|message|text/i
121 # Some regular expressions to manage HTML data
124 TITLE_REGEX = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
127 HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
129 PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
131 # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
132 # to mark actual text
133 AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
135 # At worst, we can try stuff which is comprised between two <br>
136 AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
143 # Miscellaneous useful functions
145 @@bot = nil unless defined? @@bot
146 @@safe_save_dir = nil unless defined?(@@safe_save_dir)
153 # Set up some Utils routines which depend on the associated bot.
155 debug "initializing utils"
157 @@safe_save_dir = @@bot.path('safe_save')
164 SEC_PER_HR = SEC_PER_MIN * 60
166 SEC_PER_DAY = SEC_PER_HR * 24
168 SEC_PER_WK = SEC_PER_DAY * 7
169 # Seconds per (30-day) month
170 SEC_PER_MNTH = SEC_PER_DAY * 30
171 # Second per (non-leap) year
172 SEC_PER_YR = SEC_PER_DAY * 365
174 # Auxiliary method needed by Utils.secs_to_string
175 def Utils.secs_to_string_case(array, var, string, plural)
178 array << "1 #{string}"
180 array << "#{var} #{plural}"
184 # Turn a number of seconds into a human readable string, e.g
185 # 2 days, 3 hours, 18 minutes and 10 seconds
186 def Utils.secs_to_string(secs)
188 years, secs = secs.divmod SEC_PER_YR
189 secs_to_string_case(ret, years, _("year"), _("years")) if years > 0
190 months, secs = secs.divmod SEC_PER_MNTH
191 secs_to_string_case(ret, months, _("month"), _("months")) if months > 0
192 days, secs = secs.divmod SEC_PER_DAY
193 secs_to_string_case(ret, days, _("day"), _("days")) if days > 0
194 hours, secs = secs.divmod SEC_PER_HR
195 secs_to_string_case(ret, hours, _("hour"), _("hours")) if hours > 0
196 mins, secs = secs.divmod SEC_PER_MIN
197 secs_to_string_case(ret, mins, _("minute"), _("minutes")) if mins > 0
199 secs_to_string_case(ret, secs, _("second"), _("seconds")) if secs > 0 or ret.empty?
202 raise "Empty ret array!"
206 return [ret[0, ret.length-1].join(", ") , ret[-1]].join(_(" and "))
210 # Turn a number of seconds into a hours:minutes:seconds e.g.
211 # 3:18:10 or 5'12" or 7s
213 def Utils.secs_to_short(seconds)
214 secs = seconds.to_i # make sure it's an integer
215 mins, secs = secs.divmod 60
216 hours, mins = mins.divmod 60
218 return ("%s:%s:%s" % [hours, mins, secs])
220 return ("%s'%s\"" % [mins, secs])
222 return ("%ss" % [secs])
226 # Returns human readable time.
230 # :start_date, sets the time to measure against, defaults to now
231 # :date_format, used with <tt>to_formatted_s<tt>, default to :default
232 def Utils.timeago(time, options = {})
233 start_date = options.delete(:start_date) || Time.new
234 date_format = options.delete(:date_format) || "%x"
235 delta = (start_date - time).round
239 distance = Utils.age_string(delta)
241 _("%{d} from now") % {:d => distance}
243 _("%{d} ago") % {:d => distance}
248 # Converts age in seconds to "nn units". Inspired by previous attempts
249 # but also gitweb's age_string() sub
250 def Utils.age_string(secs)
253 Utils.age_string(-secs)
254 when secs > 2*SEC_PER_YR
255 _("%{m} years") % { :m => secs/SEC_PER_YR }
256 when secs > 2*SEC_PER_MNTH
257 _("%{m} months") % { :m => secs/SEC_PER_MNTH }
258 when secs > 2*SEC_PER_WK
259 _("%{m} weeks") % { :m => secs/SEC_PER_WK }
260 when secs > 2*SEC_PER_DAY
261 _("%{m} days") % { :m => secs/SEC_PER_DAY }
262 when secs > 2*SEC_PER_HR
263 _("%{m} hours") % { :m => secs/SEC_PER_HR }
264 when (20*SEC_PER_MIN..40*SEC_PER_MIN).include?(secs)
266 when (50*SEC_PER_MIN..70*SEC_PER_MIN).include?(secs)
267 # _("about one hour")
269 when (80*SEC_PER_MIN..100*SEC_PER_MIN).include?(secs)
270 _("an hour and a half")
271 when secs > 2*SEC_PER_MIN
272 _("%{m} minutes") % { :m => secs/SEC_PER_MIN }
274 _("%{m} seconds") % { :m => secs }
280 # Execute an external program, returning a String obtained by redirecting
281 # the program's standards errors and output
283 def Utils.safe_exec(command, *args)
286 return p.readlines.join("\n")
289 $stderr.reopen($stdout)
291 rescue Exception => e
292 puts "exception #{e.pretty_inspect} trying to run #{command}"
295 puts "exec of #{command} failed"
301 # Try executing an external program, returning true if the run was successful
302 # and false otherwise
303 def Utils.try_exec(command, *args)
307 $stderr.reopen($stdout)
309 rescue Exception => e
321 # Safely (atomically) save to _file_, by passing a tempfile to the block
322 # and then moving the tempfile to its final location when done.
324 # call-seq: Utils.safe_save(file, &block)
326 def Utils.safe_save(file)
327 raise 'No safe save directory defined!' if @@safe_save_dir.nil?
328 basename = File.basename(file)
329 temp = Tempfile.new(basename,@@safe_save_dir)
331 yield temp if block_given?
333 File.rename(temp.path, file)
337 # Decode HTML entities in the String _str_, using HTMLEntities if the
338 # package was found, or UNESCAPE_TABLE otherwise.
340 def Utils.decode_html_entities(str)
341 if defined? ::HTMLEntities
342 return HTMLEntities.decode_entities(str)
344 str.gsub(/(&(.+?);)/) {
346 # remove the 0-paddng from unicode integers
347 if symbol =~ /^#(\d+)$/
348 symbol = $1.to_i.to_s
351 # output the symbol's irc-translated character, or a * if it's unknown
352 UNESCAPE_TABLE[symbol] || (symbol.match(/^\d+$/) ? [symbol.to_i].pack("U") : '*')
357 # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
358 # If possible, grab the one after the first heading
360 # It is possible to pass some options to determine how the stripping
361 # occurs. Currently supported options are
362 # strip:: Regex or String to strip at the beginning of the obtained
364 # min_spaces:: minimum number of spaces a paragraph should have
366 def Utils.ircify_first_html_par(xml_org, opts={})
367 if defined? ::Hpricot
368 Utils.ircify_first_html_par_wh(xml_org, opts)
370 Utils.ircify_first_html_par_woh(xml_org, opts)
374 # HTML first par grabber using hpricot
375 def Utils.ircify_first_html_par_wh(xml_org, opts={})
376 doc = Hpricot(xml_org)
378 # Strip styles and scripts
379 (doc/"style|script").remove
384 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
386 min_spaces = opts[:min_spaces] || 8
387 min_spaces = 0 if min_spaces < 0
391 pre_h = pars = by_span = nil
394 debug "Minimum number of spaces: #{min_spaces}"
396 # Initial attempt: <p> that follows <h\d>
398 pre_h = Hpricot::Elements[]
400 doc.search("*") { |e|
406 pre_h << e if found_h
409 debug "Hx: found: #{pre_h.pretty_inspect}"
414 txt = p.to_html.ircify_html
415 txt.sub!(strip, '') if strip
416 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
417 break unless txt.empty? or txt.count(" ") < min_spaces
420 return txt unless txt.empty? or txt.count(" ") < min_spaces
422 # Second natural attempt: just get any <p>
423 pars = doc/"p" if pars.nil?
424 debug "par: found: #{pars.pretty_inspect}"
427 txt = p.to_html.ircify_html
428 txt.sub!(strip, '') if strip
429 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
430 break unless txt.empty? or txt.count(" ") < min_spaces
433 return txt unless txt.empty? or txt.count(" ") < min_spaces
435 # Nothing yet ... let's get drastic: we look for non-par elements too,
436 # but only for those that match something that we know is likely to
439 # Some blogging and forum platforms use spans or divs with a 'body' or
440 # 'message' or 'text' in their class to mark actual text. Since we want
441 # the class match to be partial and case insensitive, we collect
442 # the common elements that may have this class and then filter out those
443 # we don't need. If no divs or spans are found, we'll accept additional
444 # elements too (td, tr, tbody, table).
446 by_span = Hpricot::Elements[]
447 extra = Hpricot::Elements[]
448 doc.search("*") { |el|
449 next if el.bogusetag?
452 by_span.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
454 extra.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
457 if by_span.empty? and not extra.empty?
460 debug "other \#1: found: #{by_span.pretty_inspect}"
465 txt = p.to_html.ircify_html
466 txt.sub!(strip, '') if strip
467 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
468 break unless txt.empty? or txt.count(" ") < min_spaces
471 return txt unless txt.empty? or txt.count(" ") < min_spaces
473 # At worst, we can try stuff which is comprised between two <br>
476 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
477 return txt unless txt.count(" ") < min_spaces
478 break if min_spaces == 0
483 # HTML first par grabber without hpricot
484 def Utils.ircify_first_html_par_woh(xml_org, opts={})
485 xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
488 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
490 min_spaces = opts[:min_spaces] || 8
491 min_spaces = 0 if min_spaces < 0
496 debug "Minimum number of spaces: #{min_spaces}"
497 header_found = xml.match(HX_REGEX)
500 while txt.empty? or txt.count(" ") < min_spaces
501 candidate = header_found[PAR_REGEX]
502 break unless candidate
503 txt = candidate.ircify_html
505 txt.sub!(strip, '') if strip
506 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
510 return txt unless txt.empty? or txt.count(" ") < min_spaces
512 # If we haven't found a first par yet, try to get it from the whole
515 while txt.empty? or txt.count(" ") < min_spaces
516 candidate = header_found[PAR_REGEX]
517 break unless candidate
518 txt = candidate.ircify_html
520 txt.sub!(strip, '') if strip
521 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
524 return txt unless txt.empty? or txt.count(" ") < min_spaces
526 # Nothing yet ... let's get drastic: we look for non-par elements too,
527 # but only for those that match something that we know is likely to
532 while txt.empty? or txt.count(" ") < min_spaces
533 candidate = header_found[AFTER_PAR1_REGEX]
534 break unless candidate
535 txt = candidate.ircify_html
537 txt.sub!(strip, '') if strip
538 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
541 return txt unless txt.empty? or txt.count(" ") < min_spaces
545 while txt.empty? or txt.count(" ") < min_spaces
546 candidate = header_found[AFTER_PAR2_REGEX]
547 break unless candidate
548 txt = candidate.ircify_html
550 txt.sub!(strip, '') if strip
551 debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
554 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
555 return txt unless txt.count(" ") < min_spaces
556 break if min_spaces == 0
561 # This method extracts title, content (first par) and extra
562 # information from the given document _doc_.
564 # _doc_ can be an URI, a Net::HTTPResponse or a String.
566 # If _doc_ is a String, only title and content information
567 # are retrieved (if possible), using standard methods.
569 # If _doc_ is an URI or a Net::HTTPResponse, additional
570 # information is retrieved, and special title/summary
571 # extraction routines are used if possible.
573 def Utils.get_html_info(doc, opts={})
576 Utils.get_string_html_info(doc, opts)
577 when Net::HTTPResponse
578 Utils.get_resp_html_info(doc, opts)
581 @@bot.httputil.get_response(doc) { |resp|
582 ret.replace Utils.get_resp_html_info(resp, opts)
590 class ::UrlLinkError < RuntimeError
593 # This method extracts title, content (first par) and extra
594 # information from the given Net::HTTPResponse _resp_.
596 # Currently, the only accepted options (in _opts_) are
597 # uri_fragment:: the URI fragment of the original request
598 # full_body:: get the whole body instead of
599 # @@bot.config['http.info_bytes'] bytes only
601 # Returns a DataStream with the following keys:
602 # text:: the (partial) body
603 # title:: the title of the document (if any)
604 # content:: the first paragraph of the document (if any)
606 # the headers of the Net::HTTPResponse. The value is
607 # a Hash whose keys are lowercase forms of the HTTP
608 # header fields, and whose values are Arrays.
610 def Utils.get_resp_html_info(resp, opts={})
612 when Net::HTTPSuccess
613 loc = URI.parse(resp['x-rbot-location'] || resp['location']) rescue nil
614 if loc and loc.fragment and not loc.fragment.empty?
615 opts[:uri_fragment] ||= loc.fragment
617 ret = DataStream.new(opts.dup)
618 ret[:headers] = resp.to_hash
619 ret[:text] = partial = opts[:full_body] ? resp.body : resp.partial_body(@@bot.config['http.info_bytes'])
621 filtered = Utils.try_htmlinfo_filters(ret)
625 elsif resp['content-type'] =~ /^text\/|(?:x|ht)ml/
626 ret.merge!(Utils.get_string_html_info(partial, opts))
630 raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
634 # This method runs an appropriately-crafted DataStream _ds_ through the
635 # filters in the :htmlinfo filter group, in order. If one of the filters
636 # returns non-nil, its results are merged in _ds_ and returned. Otherwise
639 # The input DataStream should have the downloaded HTML as primary key
640 # (:text) and possibly a :headers key holding the resonse headers.
642 def Utils.try_htmlinfo_filters(ds)
643 filters = @@bot.filter_names(:htmlinfo)
644 return nil if filters.empty?
646 # TODO filter priority
648 debug "testing htmlinfo filter #{n}"
649 cur = @@bot.filter(@@bot.global_filter_name(n, :htmlinfo), ds)
650 debug "returned #{cur.pretty_inspect}"
653 return ds.merge(cur) if cur
656 # HTML info filters often need to check if the webpage location
657 # of a passed DataStream _ds_ matches a given Regexp.
658 def Utils.check_location(ds, rx)
661 loc = [h['x-rbot-location'],h['location']].flatten.grep(rx)
665 return loc.empty? ? nil : loc
668 # This method extracts title and content (first par)
669 # from the given HTML or XML document _text_, using
670 # standard methods (String#ircify_html_title,
671 # Utils.ircify_first_html_par)
673 # Currently, the only accepted option (in _opts_) is
674 # uri_fragment:: the URI fragment of the original request
676 def Utils.get_string_html_info(text, opts={})
677 debug "getting string html info"
679 title = txt.ircify_html_title
681 if frag = opts[:uri_fragment] and not frag.empty?
682 fragreg = /<a\s+(?:[^>]+\s+)?(?:name|id)=["']?#{frag}["']?[^>]*>/im
685 if txt.match(fragreg)
686 # grab the post-match
692 c_opts[:strip] ||= title
693 content = Utils.ircify_first_html_par(txt, c_opts)
694 content = nil if content.empty?
695 return {:title => title, :content => content}
698 # Get the first pars of the first _count_ _urls_.
699 # The pages are downloaded using the bot httputil service.
700 # Returns an array of the first paragraphs fetched.
701 # If (optional) _opts_ :message is specified, those paragraphs are
702 # echoed as replies to the IRC message passed as _opts_ :message
704 def Utils.get_first_pars(urls, count, opts={})
708 while count > 0 and urls.length > 0
713 info = Utils.get_html_info(URI.parse(url), opts)
719 msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
723 debug "Unable to retrieve #{url}: #{$!}"
730 # Returns a comma separated list except for the last element
731 # which is joined in with specified conjunction
733 def Utils.comma_list(words, options={})
734 defaults = { :join_with => ", ", :join_last_with => _(" and ") }
735 opts = defaults.merge(options)
740 [words[0..-2].join(opts[:join_with]), words.last].join(opts[:join_last_with])
747 Irc::Utils.bot = Irc::Bot::Plugins.manager.bot