]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blobdiff - lib/rbot/core/utils/extends.rb
httputil: try to guess content-type from extension if it's not defined
[user/henk/code/ruby/rbot.git] / lib / rbot / core / utils / extends.rb
index fa2dff9515c3291e099453e579f58043c507d553..7b733994b74d323b010db0bc2ee6d66dad1f598d 100644 (file)
 # Please note that global symbols have to be prefixed by :: because this plugin
 # will be read into an anonymous module
 
+# Extensions to the Module class
+#
+class ::Module
+
+  # Many plugins define Struct objects to hold their data. On rescans, lots of
+  # warnings are echoed because of the redefinitions. Using this method solves
+  # the problem, by checking if the Struct already exists, and if it has the
+  # same attributes
+  #
+  def define_structure(name, *members)
+    sym = name.to_sym
+    if Struct.const_defined?(sym)
+      kl = Struct.const_get(sym)
+      if kl.new.members.map { |member| member.intern } == members.map
+        debug "Struct #{sym} previously defined, skipping"
+        const_set(sym, kl)
+        return
+      end
+    end
+    debug "Defining struct #{sym} with members #{members.inspect}"
+    const_set(sym, Struct.new(name.to_s, *members))
+  end
+end
+
 
 # Extensions to the Array class
 #
@@ -27,63 +51,49 @@ class ::Array
   end
 end
 
-begin
-  require 'iconv'
-  $we_have_iconv = true
-rescue LoadError
-  $we_have_iconv = false
-end
-
-# Extensions to the String class
-#
-# TODO make ircify_html() accept an Hash of options, and make riphtml() just
-# call ircify_html() with stronger purify options.
+# Extensions to the Range class
 #
-class ::String
+class ::Range
 
-  # This method will try to transcode a String supposed to hold an XML or HTML
-  # document from the original charset to UTF-8.
+  # This method returns a random number between the lower and upper bound
   #
-  # To find the original encoding, it will first see if the String responds to
-  # #http_headers(), and if it does it will assume that the charset indicated
-  # there is the correct one. Otherwise, it will try to detect the charset from
-  # some typical XML and HTML headers
-  def utfy_xml
-    return self unless $we_have_iconv
-
-    charset = nil
-
-    if self.respond_to?(:http_headers) and headers = self.http_headers
-      if headers['content-type'].first.match(/charset=(\S+?)\s*(?:;|\Z)/i)
-        debug "charset #{charset} set from header"
-        charset = $1
-      end
-    end
-
-    if not charset
-      case self
-      when /<\?xml.*encoding="(\S+)".*\?>/i
-        charset = $1
-      when /<meta\s+http-equiv\s*=\s*["']?Content-Type["']?.*charset\s*=\s*(\S+?)(?:;|["']|\s).*>/i
-        charset = $1
-      end
-      debug "charset #{charset} set from string"
-    end
+  def pick_one
+    len = self.last - self.first
+    len += 1 unless self.exclude_end?
+    self.first + Kernel::rand(len)
+  end
+  alias :rand :pick_one
+end
 
-    if charset
-      return Iconv.iconv('utf-8', charset, self).join rescue self
-    else
-      debug "Couldn't find charset for #{self.inspect}"
-      return self
-    end
+# Extensions for the Numeric classes
+#
+class ::Numeric
 
+  # This method forces a real number to be not more than a given positive
+  # number or not less than a given positive number, or between two any given
+  # numbers
+  #
+  def clip(left,right=0)
+    raise ArgumentError unless left.kind_of?(Numeric) and right.kind_of?(Numeric)
+    l = [left,right].min
+    u = [left,right].max
+    return l if self < l
+    return u if self > u
+    return self
   end
+end
+
+# Extensions to the String class
+#
+# TODO make riphtml() just call ircify_html() with stronger purify options.
+#
+class ::String
 
   # This method will return a purified version of the receiver, with all HTML
   # stripped off and some of it converted to IRC formatting
   #
-  def ircify_html
-    txt = self
+  def ircify_html(opts={})
+    txt = self.dup
 
     # remove scripts
     txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
@@ -100,12 +110,37 @@ class ::String
     ## This would be a nice addition, but the results are horrible
     ## Maybe make it configurable?
     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
+    case val = opts[:a_href]
+    when Reverse, Bold, Underline
+      txt.gsub!(/<(?:\/a\s*|a (?:[^>]*\s+)?href\s*=\s*(?:[^>]*\s*)?)>/, val)
+    when :link_out
+      # Not good for nested links, but the best we can do without something like hpricot
+      txt.gsub!(/<a (?:[^>]*\s+)?href\s*=\s*(?:([^"'>][^\s>]*)\s+|"((?:[^"]|\\")*)"|'((?:[^']|\\')*)')(?:[^>]*\s+)?>(.*?)<\/a>/) { |match|
+        debug match
+        debug [$1, $2, $3, $4].inspect
+        link = $1 || $2 || $3
+        str = $4
+        str + ": " + link
+      }
+    else
+      warning "unknown :a_href option #{val} passed to ircify_html" if val
+    end
 
     # Paragraph and br tags are converted to whitespace
-    txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/, ' ')
+    txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/i, ' ')
     txt.gsub!("\n", ' ')
     txt.gsub!("\r", ' ')
 
+    # Superscripts and subscripts are turned into ^{...} and _{...}
+    # where the {} are omitted for single characters
+    txt.gsub!(/<sup>(.*?)<\/sup>/, '^{\1}')
+    txt.gsub!(/<sub>(.*?)<\/sub>/, '_{\1}')
+    txt.gsub!(/(^|_)\{(.)\}/, '\1\2')
+
+    # List items are converted to *). We don't have special support for
+    # nested or ordered lists.
+    txt.gsub!(/<li>/, ' *) ')
+
     # All other tags are just removed
     txt.gsub!(/<[^>]+>/, '')
 
@@ -113,6 +148,14 @@ class ::String
     # such as &nbsp;
     txt = Utils.decode_html_entities(txt)
 
+    # Keep unbreakable spaces or conver them to plain spaces?
+    case val = opts[:nbsp]
+    when :space, ' '
+      txt.gsub!([160].pack('U'), ' ')
+    else
+      warning "unknown :nbsp option #{val} passed to ircify_html" if val
+    end
+
     # Remove double formatting options, since they only waste bytes
     txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
     txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
@@ -124,9 +167,22 @@ class ::String
 
     # And finally whitespace is squeezed
     txt.gsub!(/\s+/, ' ')
+    txt.strip!
+
+    if opts[:limit] && txt.size > opts[:limit]
+      txt = txt.slice(0, opts[:limit]) + "#{Reverse}...#{Reverse}"
+    end
 
     # Decode entities and strip whitespace
-    return txt.strip
+    return txt
+  end
+
+  # As above, but modify the receiver
+  #
+  def ircify_html!(opts={})
+    old_hash = self.hash
+    replace self.ircify_html(opts)
+    return self unless self.hash == old_hash
   end
 
   # This method will strip all HTML crud from the receiver
@@ -134,6 +190,23 @@ class ::String
   def riphtml
     self.gsub(/<[^>]+>/, '').gsub(/&amp;/,'&').gsub(/&quot;/,'"').gsub(/&lt;/,'<').gsub(/&gt;/,'>').gsub(/&ellip;/,'...').gsub(/&apos;/, "'").gsub("\n",'')
   end
+
+  # This method tries to find an HTML title in the string,
+  # and returns it if found
+  def get_html_title
+    if defined? ::Hpricot
+      Hpricot(self).at("title").inner_html
+    else
+      return unless Irc::Utils::TITLE_REGEX.match(self)
+      $1
+    end
+  end
+
+  # This method returns the IRC-formatted version of an
+  # HTML title found in the string
+  def ircify_html_title
+    self.get_html_title.ircify_html rescue nil
+  end
 end