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])
240 # Execute an external program, returning a String obtained by redirecting
241 # the program's standards errors and output
243 def Utils.safe_exec(command, *args)
246 return p.readlines.join("\n")
249 $stderr.reopen($stdout)
251 rescue Exception => e
252 puts "exec of #{command} led to exception: #{e.pretty_inspect}"
255 puts "exec of #{command} failed"
262 # Safely (atomically) save to _file_, by passing a tempfile to the block
263 # and then moving the tempfile to its final location when done.
265 # call-seq: Utils.safe_save(file, &block)
267 def Utils.safe_save(file)
268 raise 'No safe save directory defined!' if @@safe_save_dir.nil?
269 basename = File.basename(file)
270 temp = Tempfile.new(basename,@@safe_save_dir)
272 yield temp if block_given?
274 File.rename(temp.path, file)
278 # Decode HTML entities in the String _str_, using HTMLEntities if the
279 # package was found, or UNESCAPE_TABLE otherwise.
281 def Utils.decode_html_entities(str)
282 if defined? ::HTMLEntities
283 return HTMLEntities.decode_entities(str)
285 str.gsub(/(&(.+?);)/) {
287 # remove the 0-paddng from unicode integers
288 if symbol =~ /^#(\d+)$/
289 symbol = $1.to_i.to_s
292 # output the symbol's irc-translated character, or a * if it's unknown
293 UNESCAPE_TABLE[symbol] || (symbol.match(/^\d+$/) ? [symbol.to_i].pack("U") : '*')
298 # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
299 # If possible, grab the one after the first heading
301 # It is possible to pass some options to determine how the stripping
302 # occurs. Currently supported options are
303 # strip:: Regex or String to strip at the beginning of the obtained
305 # min_spaces:: minimum number of spaces a paragraph should have
307 def Utils.ircify_first_html_par(xml_org, opts={})
308 if defined? ::Hpricot
309 Utils.ircify_first_html_par_wh(xml_org, opts)
311 Utils.ircify_first_html_par_woh(xml_org, opts)
315 # HTML first par grabber using hpricot
316 def Utils.ircify_first_html_par_wh(xml_org, opts={})
317 doc = Hpricot(xml_org)
319 # Strip styles and scripts
320 (doc/"style|script").remove
325 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
327 min_spaces = opts[:min_spaces] || 8
328 min_spaces = 0 if min_spaces < 0
332 pre_h = pars = by_span = nil
335 debug "Minimum number of spaces: #{min_spaces}"
337 # Initial attempt: <p> that follows <h\d>
339 pre_h = Hpricot::Elements[]
341 doc.search("*") { |e|
347 pre_h << e if found_h
350 debug "Hx: found: #{pre_h.pretty_inspect}"
355 txt = p.to_html.ircify_html
356 txt.sub!(strip, '') if strip
357 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
358 break unless txt.empty? or txt.count(" ") < min_spaces
361 return txt unless txt.empty? or txt.count(" ") < min_spaces
363 # Second natural attempt: just get any <p>
364 pars = doc/"p" if pars.nil?
365 debug "par: found: #{pars.pretty_inspect}"
368 txt = p.to_html.ircify_html
369 txt.sub!(strip, '') if strip
370 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
371 break unless txt.empty? or txt.count(" ") < min_spaces
374 return txt unless txt.empty? or txt.count(" ") < min_spaces
376 # Nothing yet ... let's get drastic: we look for non-par elements too,
377 # but only for those that match something that we know is likely to
380 # Some blogging and forum platforms use spans or divs with a 'body' or
381 # 'message' or 'text' in their class to mark actual text. Since we want
382 # the class match to be partial and case insensitive, we collect
383 # the common elements that may have this class and then filter out those
384 # we don't need. If no divs or spans are found, we'll accept additional
385 # elements too (td, tr, tbody, table).
387 by_span = Hpricot::Elements[]
388 extra = Hpricot::Elements[]
389 doc.search("*") { |el|
390 next if el.bogusetag?
393 by_span.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
395 extra.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
398 if by_span.empty? and not extra.empty?
401 debug "other \#1: found: #{by_span.pretty_inspect}"
406 txt = p.to_html.ircify_html
407 txt.sub!(strip, '') if strip
408 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
409 break unless txt.empty? or txt.count(" ") < min_spaces
412 return txt unless txt.empty? or txt.count(" ") < min_spaces
414 # At worst, we can try stuff which is comprised between two <br>
417 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
418 return txt unless txt.count(" ") < min_spaces
419 break if min_spaces == 0
424 # HTML first par grabber without hpricot
425 def Utils.ircify_first_html_par_woh(xml_org, opts={})
426 xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
429 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
431 min_spaces = opts[:min_spaces] || 8
432 min_spaces = 0 if min_spaces < 0
437 debug "Minimum number of spaces: #{min_spaces}"
438 header_found = xml.match(HX_REGEX)
441 while txt.empty? or txt.count(" ") < min_spaces
442 candidate = header_found[PAR_REGEX]
443 break unless candidate
444 txt = candidate.ircify_html
446 txt.sub!(strip, '') if strip
447 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
451 return txt unless txt.empty? or txt.count(" ") < min_spaces
453 # If we haven't found a first par yet, try to get it from the whole
456 while txt.empty? or txt.count(" ") < min_spaces
457 candidate = header_found[PAR_REGEX]
458 break unless candidate
459 txt = candidate.ircify_html
461 txt.sub!(strip, '') if strip
462 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
465 return txt unless txt.empty? or txt.count(" ") < min_spaces
467 # Nothing yet ... let's get drastic: we look for non-par elements too,
468 # but only for those that match something that we know is likely to
473 while txt.empty? or txt.count(" ") < min_spaces
474 candidate = header_found[AFTER_PAR1_REGEX]
475 break unless candidate
476 txt = candidate.ircify_html
478 txt.sub!(strip, '') if strip
479 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
482 return txt unless txt.empty? or txt.count(" ") < min_spaces
486 while txt.empty? or txt.count(" ") < min_spaces
487 candidate = header_found[AFTER_PAR2_REGEX]
488 break unless candidate
489 txt = candidate.ircify_html
491 txt.sub!(strip, '') if strip
492 debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
495 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
496 return txt unless txt.count(" ") < min_spaces
497 break if min_spaces == 0
502 # This method extracts title, content (first par) and extra
503 # information from the given document _doc_.
505 # _doc_ can be an URI, a Net::HTTPResponse or a String.
507 # If _doc_ is a String, only title and content information
508 # are retrieved (if possible), using standard methods.
510 # If _doc_ is an URI or a Net::HTTPResponse, additional
511 # information is retrieved, and special title/summary
512 # extraction routines are used if possible.
514 def Utils.get_html_info(doc, opts={})
517 Utils.get_string_html_info(doc, opts)
518 when Net::HTTPResponse
519 Utils.get_resp_html_info(doc, opts)
522 @@bot.httputil.get_response(doc) { |resp|
523 ret.replace Utils.get_resp_html_info(resp, opts)
531 class ::UrlLinkError < RuntimeError
534 # This method extracts title, content (first par) and extra
535 # information from the given Net::HTTPResponse _resp_.
537 # Currently, the only accepted options (in _opts_) are
538 # uri_fragment:: the URI fragment of the original request
539 # full_body:: get the whole body instead of
540 # @@bot.config['http.info_bytes'] bytes only
542 # Returns a DataStream with the following keys:
543 # text:: the (partial) body
544 # title:: the title of the document (if any)
545 # content:: the first paragraph of the document (if any)
547 # the headers of the Net::HTTPResponse. The value is
548 # a Hash whose keys are lowercase forms of the HTTP
549 # header fields, and whose values are Arrays.
551 def Utils.get_resp_html_info(resp, opts={})
553 when Net::HTTPSuccess
554 loc = URI.parse(resp['x-rbot-location'] || resp['location']) rescue nil
555 if loc and loc.fragment and not loc.fragment.empty?
556 opts[:uri_fragment] ||= loc.fragment
558 ret = DataStream.new(opts.dup)
559 ret[:headers] = resp.to_hash
560 ret[:text] = partial = opts[:full_body] ? resp.body : resp.partial_body(@@bot.config['http.info_bytes'])
562 filtered = Utils.try_htmlinfo_filters(ret)
566 elsif resp['content-type'] =~ /^text\/|(?:x|ht)ml/
567 ret.merge!(Utils.get_string_html_info(partial, opts))
571 raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
575 # This method runs an appropriately-crafted DataStream _ds_ through the
576 # filters in the :htmlinfo filter group, in order. If one of the filters
577 # returns non-nil, its results are merged in _ds_ and returned. Otherwise
580 # The input DataStream shuold have the downloaded HTML as primary key
581 # (:text) and possibly a :headers key holding the resonse headers.
583 def Utils.try_htmlinfo_filters(ds)
584 filters = @@bot.filter_names(:htmlinfo)
585 return nil if filters.empty?
587 # TODO filter priority
589 debug "testing filter #{n}"
590 cur = @@bot.filter(@@bot.global_filter_name(n, :htmlinfo), ds)
591 debug "returned #{cur.pretty_inspect}"
594 return ds.merge(cur) if cur
597 # HTML info filters often need to check if the webpage location
598 # of a passed DataStream _ds_ matches a given Regexp.
599 def Utils.check_location(ds, rx)
602 loc = [h['x-rbot-location'],h['location']].flatten.grep(rx)
606 return loc.empty? ? nil : loc
609 # This method extracts title and content (first par)
610 # from the given HTML or XML document _text_, using
611 # standard methods (String#ircify_html_title,
612 # Utils.ircify_first_html_par)
614 # Currently, the only accepted option (in _opts_) is
615 # uri_fragment:: the URI fragment of the original request
617 def Utils.get_string_html_info(text, opts={})
618 debug "getting string html info"
620 title = txt.ircify_html_title
622 if frag = opts[:uri_fragment] and not frag.empty?
623 fragreg = /<a\s+(?:[^>]+\s+)?(?:name|id)=["']?#{frag}["']?[^>]*>/im
626 if txt.match(fragreg)
627 # grab the post-match
633 c_opts[:strip] ||= title
634 content = Utils.ircify_first_html_par(txt, c_opts)
635 content = nil if content.empty?
636 return {:title => title, :content => content}
639 # Get the first pars of the first _count_ _urls_.
640 # The pages are downloaded using the bot httputil service.
641 # Returns an array of the first paragraphs fetched.
642 # If (optional) _opts_ :message is specified, those paragraphs are
643 # echoed as replies to the IRC message passed as _opts_ :message
645 def Utils.get_first_pars(urls, count, opts={})
649 while count > 0 and urls.length > 0
654 info = Utils.get_html_info(URI.parse(url), opts)
660 msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
664 debug "Unable to retrieve #{url}: #{$!}"
674 Irc::Utils.bot = Irc::Bot::Plugins.manager.bot