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
18 # Try to load htmlentities, fall back to an HTML escape table.
20 require 'htmlentities'
24 gems = require 'rubygems'
121 AFTER_PAR_PATH = /^(?:div|span)$/
122 AFTER_PAR_EX = /^(?:td|tr|tbody|table)$/
123 AFTER_PAR_CLASS = /body|message|text/i
129 gems = require 'rubygems'
138 # Some regular expressions to manage HTML data
141 TITLE_REGEX = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
144 HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
146 PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
148 # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
149 # to mark actual text
150 AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
152 # At worst, we can try stuff which is comprised between two <br>
153 AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
161 # Miscellaneous useful functions
163 @@bot = nil unless defined? @@bot
164 @@safe_save_dir = nil unless defined?(@@safe_save_dir)
171 # Set up some Utils routines which depend on the associated bot.
173 debug "initializing utils"
175 @@safe_save_dir = "#{@@bot.botclass}/safe_save"
182 SEC_PER_HR = SEC_PER_MIN * 60
184 SEC_PER_DAY = SEC_PER_HR * 24
185 # Seconds per (30-day) month
186 SEC_PER_MNTH = SEC_PER_DAY * 30
187 # Second per (30*12 = 360 day) year
188 SEC_PER_YR = SEC_PER_MNTH * 12
190 # Auxiliary method needed by Utils.secs_to_string
191 def Utils.secs_to_string_case(array, var, string, plural)
194 array << "1 #{string}"
196 array << "#{var} #{plural}"
200 # Turn a number of seconds into a human readable string, e.g
201 # 2 days, 3 hours, 18 minutes and 10 seconds
202 def Utils.secs_to_string(secs)
204 years, secs = secs.divmod SEC_PER_YR
205 secs_to_string_case(ret, years, _("year"), _("years")) if years > 0
206 months, secs = secs.divmod SEC_PER_MNTH
207 secs_to_string_case(ret, months, _("month"), _("months")) if months > 0
208 days, secs = secs.divmod SEC_PER_DAY
209 secs_to_string_case(ret, days, _("day"), _("days")) if days > 0
210 hours, secs = secs.divmod SEC_PER_HR
211 secs_to_string_case(ret, hours, _("hour"), _("hours")) if hours > 0
212 mins, secs = secs.divmod SEC_PER_MIN
213 secs_to_string_case(ret, mins, _("minute"), _("minutes")) if mins > 0
215 secs_to_string_case(ret, secs, _("second"), _("seconds")) if secs > 0 or ret.empty?
218 raise "Empty ret array!"
222 return [ret[0, ret.length-1].join(", ") , ret[-1]].join(_(" and "))
226 # Turn a number of seconds into a hours:minutes:seconds e.g.
227 # 3:18:10 or 5'12" or 7s
229 def Utils.secs_to_short(seconds)
230 secs = seconds.to_i # make sure it's an integer
231 mins, secs = secs.divmod 60
232 hours, mins = mins.divmod 60
234 return ("%s:%s:%s" % [hours, mins, secs])
236 return ("%s'%s\"" % [mins, secs])
238 return ("%ss" % [secs])
243 # Execute an external program, returning a String obtained by redirecting
244 # the program's standards errors and output
246 def Utils.safe_exec(command, *args)
249 return p.readlines.join("\n")
252 $stderr.reopen($stdout)
254 rescue Exception => e
255 puts "exec of #{command} led to exception: #{e.pretty_inspect}"
258 puts "exec of #{command} failed"
265 # Safely (atomically) save to _file_, by passing a tempfile to the block
266 # and then moving the tempfile to its final location when done.
268 # call-seq: Utils.safe_save(file, &block)
270 def Utils.safe_save(file)
271 raise 'No safe save directory defined!' if @@safe_save_dir.nil?
272 basename = File.basename(file)
273 temp = Tempfile.new(basename,@@safe_save_dir)
275 yield temp if block_given?
277 File.rename(temp.path, file)
281 # Decode HTML entities in the String _str_, using HTMLEntities if the
282 # package was found, or UNESCAPE_TABLE otherwise.
284 def Utils.decode_html_entities(str)
285 if defined? ::HTMLEntities
286 return HTMLEntities.decode_entities(str)
288 str.gsub(/(&(.+?);)/) {
290 # remove the 0-paddng from unicode integers
291 if symbol =~ /^#(\d+)$/
292 symbol = $1.to_i.to_s
295 # output the symbol's irc-translated character, or a * if it's unknown
296 UNESCAPE_TABLE[symbol] || (symbol.match(/^\d+$/) ? [symbol.to_i].pack("U") : '*')
301 # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
302 # If possible, grab the one after the first heading
304 # It is possible to pass some options to determine how the stripping
305 # occurs. Currently supported options are
306 # strip:: Regex or String to strip at the beginning of the obtained
308 # min_spaces:: minimum number of spaces a paragraph should have
310 def Utils.ircify_first_html_par(xml_org, opts={})
311 if defined? ::Hpricot
312 Utils.ircify_first_html_par_wh(xml_org, opts)
314 Utils.ircify_first_html_par_woh(xml_org, opts)
318 # HTML first par grabber using hpricot
319 def Utils.ircify_first_html_par_wh(xml_org, opts={})
320 doc = Hpricot(xml_org)
322 # Strip styles and scripts
323 (doc/"style|script").remove
328 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
330 min_spaces = opts[:min_spaces] || 8
331 min_spaces = 0 if min_spaces < 0
335 pre_h = pars = by_span = nil
338 debug "Minimum number of spaces: #{min_spaces}"
340 # Initial attempt: <p> that follows <h\d>
342 pre_h = Hpricot::Elements[]
344 doc.search("*") { |e|
350 pre_h << e if found_h
353 debug "Hx: found: #{pre_h.pretty_inspect}"
358 txt = p.to_html.ircify_html
359 txt.sub!(strip, '') if strip
360 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
361 break unless txt.empty? or txt.count(" ") < min_spaces
364 return txt unless txt.empty? or txt.count(" ") < min_spaces
366 # Second natural attempt: just get any <p>
367 pars = doc/"p" if pars.nil?
368 debug "par: found: #{pars.pretty_inspect}"
371 txt = p.to_html.ircify_html
372 txt.sub!(strip, '') if strip
373 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
374 break unless txt.empty? or txt.count(" ") < min_spaces
377 return txt unless txt.empty? or txt.count(" ") < min_spaces
379 # Nothing yet ... let's get drastic: we look for non-par elements too,
380 # but only for those that match something that we know is likely to
383 # Some blogging and forum platforms use spans or divs with a 'body' or
384 # 'message' or 'text' in their class to mark actual text. Since we want
385 # the class match to be partial and case insensitive, we collect
386 # the common elements that may have this class and then filter out those
387 # we don't need. If no divs or spans are found, we'll accept additional
388 # elements too (td, tr, tbody, table).
390 by_span = Hpricot::Elements[]
391 extra = Hpricot::Elements[]
392 doc.search("*") { |el|
393 next if el.bogusetag?
396 by_span.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
398 extra.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
401 if by_span.empty? and not extra.empty?
404 debug "other \#1: found: #{by_span.pretty_inspect}"
409 txt = p.to_html.ircify_html
410 txt.sub!(strip, '') if strip
411 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
412 break unless txt.empty? or txt.count(" ") < min_spaces
415 return txt unless txt.empty? or txt.count(" ") < min_spaces
417 # At worst, we can try stuff which is comprised between two <br>
420 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
421 return txt unless txt.count(" ") < min_spaces
422 break if min_spaces == 0
427 # HTML first par grabber without hpricot
428 def Utils.ircify_first_html_par_woh(xml_org, opts={})
429 xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
432 strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
434 min_spaces = opts[:min_spaces] || 8
435 min_spaces = 0 if min_spaces < 0
440 debug "Minimum number of spaces: #{min_spaces}"
441 header_found = xml.match(HX_REGEX)
444 while txt.empty? or txt.count(" ") < min_spaces
445 candidate = header_found[PAR_REGEX]
446 break unless candidate
447 txt = candidate.ircify_html
449 txt.sub!(strip, '') if strip
450 debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
454 return txt unless txt.empty? or txt.count(" ") < min_spaces
456 # If we haven't found a first par yet, try to get it from the whole
459 while txt.empty? or txt.count(" ") < min_spaces
460 candidate = header_found[PAR_REGEX]
461 break unless candidate
462 txt = candidate.ircify_html
464 txt.sub!(strip, '') if strip
465 debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
468 return txt unless txt.empty? or txt.count(" ") < min_spaces
470 # Nothing yet ... let's get drastic: we look for non-par elements too,
471 # but only for those that match something that we know is likely to
476 while txt.empty? or txt.count(" ") < min_spaces
477 candidate = header_found[AFTER_PAR1_REGEX]
478 break unless candidate
479 txt = candidate.ircify_html
481 txt.sub!(strip, '') if strip
482 debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
485 return txt unless txt.empty? or txt.count(" ") < min_spaces
489 while txt.empty? or txt.count(" ") < min_spaces
490 candidate = header_found[AFTER_PAR2_REGEX]
491 break unless candidate
492 txt = candidate.ircify_html
494 txt.sub!(strip, '') if strip
495 debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
498 debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
499 return txt unless txt.count(" ") < min_spaces
500 break if min_spaces == 0
505 # This method extracts title, content (first par) and extra
506 # information from the given document _doc_.
508 # _doc_ can be an URI, a Net::HTTPResponse or a String.
510 # If _doc_ is a String, only title and content information
511 # are retrieved (if possible), using standard methods.
513 # If _doc_ is an URI or a Net::HTTPResponse, additional
514 # information is retrieved, and special title/summary
515 # extraction routines are used if possible.
517 def Utils.get_html_info(doc, opts={})
520 Utils.get_string_html_info(doc, opts)
521 when Net::HTTPResponse
522 Utils.get_resp_html_info(doc, opts)
525 @@bot.httputil.get_response(doc) { |resp|
526 ret.replace Utils.get_resp_html_info(resp, opts)
534 class ::UrlLinkError < RuntimeError
537 # This method extracts title, content (first par) and extra
538 # information from the given Net::HTTPResponse _resp_.
540 # Currently, the only accepted options (in _opts_) are
541 # uri_fragment:: the URI fragment of the original request
542 # full_body:: get the whole body instead of
543 # @@bot.config['http.info_bytes'] bytes only
545 # Returns a DataStream with the following keys:
546 # text:: the (partial) body
547 # title:: the title of the document (if any)
548 # content:: the first paragraph of the document (if any)
550 # the headers of the Net::HTTPResponse. The value is
551 # a Hash whose keys are lowercase forms of the HTTP
552 # header fields, and whose values are Arrays.
554 def Utils.get_resp_html_info(resp, opts={})
556 when Net::HTTPSuccess
557 loc = URI.parse(resp['x-rbot-location'] || resp['location']) rescue nil
558 if loc and loc.fragment and not loc.fragment.empty?
559 opts[:uri_fragment] ||= loc.fragment
561 ret = DataStream.new(opts.dup)
562 ret[:headers] = resp.to_hash
563 ret[:text] = partial = opts[:full_body] ? resp.body : resp.partial_body(@@bot.config['http.info_bytes'])
565 filtered = Utils.try_htmlinfo_filters(ret)
569 elsif resp['content-type'] =~ /^text\/|(?:x|ht)ml/
570 ret.merge!(Utils.get_string_html_info(partial, opts))
574 raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
578 # This method runs an appropriately-crafted DataStream _ds_ through the
579 # filters in the :htmlinfo filter group, in order. If one of the filters
580 # returns non-nil, its results are merged in _ds_ and returned. Otherwise
583 # The input DataStream shuold have the downloaded HTML as primary key
584 # (:text) and possibly a :headers key holding the resonse headers.
586 def Utils.try_htmlinfo_filters(ds)
587 filters = @@bot.filter_names(:htmlinfo)
588 return nil if filters.empty?
590 # TODO filter priority
592 debug "testing filter #{n}"
593 cur = @@bot.filter(@@bot.global_filter_name(n, :htmlinfo), ds)
594 debug "returned #{cur.pretty_inspect}"
597 return ds.merge(cur) if cur
600 # HTML info filters often need to check if the webpage location
601 # of a passed DataStream _ds_ matches a given Regexp.
602 def Utils.check_location(ds, rx)
605 loc = [h['x-rbot-location'],h['location']].flatten.grep(rx)
609 return loc.empty? ? nil : loc
612 # This method extracts title and content (first par)
613 # from the given HTML or XML document _text_, using
614 # standard methods (String#ircify_html_title,
615 # Utils.ircify_first_html_par)
617 # Currently, the only accepted option (in _opts_) is
618 # uri_fragment:: the URI fragment of the original request
620 def Utils.get_string_html_info(text, opts={})
621 debug "getting string html info"
623 title = txt.ircify_html_title
625 if frag = opts[:uri_fragment] and not frag.empty?
626 fragreg = /<a\s+(?:[^>]+\s+)?(?:name|id)=["']?#{frag}["']?[^>]*>/im
629 if txt.match(fragreg)
630 # grab the post-match
636 c_opts[:strip] ||= title
637 content = Utils.ircify_first_html_par(txt, c_opts)
638 content = nil if content.empty?
639 return {:title => title, :content => content}
642 # Get the first pars of the first _count_ _urls_.
643 # The pages are downloaded using the bot httputil service.
644 # Returns an array of the first paragraphs fetched.
645 # If (optional) _opts_ :message is specified, those paragraphs are
646 # echoed as replies to the IRC message passed as _opts_ :message
648 def Utils.get_first_pars(urls, count, opts={})
652 while count > 0 and urls.length > 0
657 info = Utils.get_html_info(URI.parse(url), opts)
663 msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
667 debug "Unable to retrieve #{url}: #{$!}"
677 Irc::Utils.bot = Irc::Bot::Plugins.manager.bot