]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/extends.rb
Stringlib/rbot/core/utils/extends.rbutfy_xml() method that tries to transcode a webpa...
[user/henk/code/ruby/rbot.git] / lib / rbot / core / utils / extends.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Standard classes extensions
5 #
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2006,2007 Giuseppe Bilotta
8 # License:: GPL v2
9 #
10 # This file collects extensions to standard Ruby classes and to some core rbot
11 # classes to be used by the various plugins
12 #
13 # Please note that global symbols have to be prefixed by :: because this plugin
14 # will be read into an anonymous module
15
16
17 # Extensions to the Array class
18 #
19 class ::Array
20
21   # This method returns a random element from the array, or nil if the array is
22   # empty
23   #
24   def pick_one
25     return nil if self.empty?
26     self[rand(self.length)]
27   end
28 end
29
30 begin
31   require 'iconv'
32   $we_have_iconv = true
33 rescue LoadError
34   $we_have_iconv = false
35 end
36
37 # Extensions to the String class
38 #
39 # TODO make ircify_html() accept an Hash of options, and make riphtml() just
40 # call ircify_html() with stronger purify options.
41 #
42 class ::String
43
44   # This method will try to transcode a String supposed to hold an XML or HTML
45   # document from the original charset to UTF-8.
46   #
47   # To find the original encoding, it will first see if the String responds to
48   # #http_headers(), and if it does it will assume that the charset indicated
49   # there is the correct one. Otherwise, it will try to detect the charset from
50   # some typical XML and HTML headers
51   def utfy_xml
52     return self unless $we_have_iconv
53
54     charset = nil
55
56     if self.respond_to?(:http_headers) and headers = self.http_headers
57       if headers['content-type'].first.match(/charset="?(\S+?)"?\s*;?/i)
58         charset = $1
59       end
60     end
61
62     if not charset
63       case self
64       when /<\?xml.*encoding="(\S+)".*\?>/i
65         charset = $1
66       when /<meta\s+http-equiv\s*=\s*"Content-Type".*charset\s*=\s*"?(\S+?)"?\s*;?/i
67         charset = $1
68       end
69     end
70
71     if charset
72       debug "charset: #{charset}"
73       return Iconv.iconv('utf-8', charset, self).join rescue self
74     else
75       debug "Couldn't find charset for #{self.inspect}"
76       return self
77     end
78
79   end
80
81   # This method will return a purified version of the receiver, with all HTML
82   # stripped off and some of it converted to IRC formatting
83   #
84   def ircify_html
85     txt = self
86
87     # remove scripts
88     txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
89
90     # remove styles
91     txt.gsub!(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
92
93     # bold and strong -> bold
94     txt.gsub!(/<\/?(?:b|strong)(?:\s+[^>]*)?>/im, "#{Bold}")
95
96     # italic, emphasis and underline -> underline
97     txt.gsub!(/<\/?(?:i|em|u)(?:\s+[^>]*)?>/im, "#{Underline}")
98
99     ## This would be a nice addition, but the results are horrible
100     ## Maybe make it configurable?
101     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
102
103     # Paragraph and br tags are converted to whitespace
104     txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/, ' ')
105     txt.gsub!("\n", ' ')
106     txt.gsub!("\r", ' ')
107
108     # All other tags are just removed
109     txt.gsub!(/<[^>]+>/, '')
110
111     # Convert HTML entities. We do it now to be able to handle stuff
112     # such as &nbsp;
113     txt = Utils.decode_html_entities(txt)
114
115     # Remove double formatting options, since they only waste bytes
116     txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
117     txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
118
119     # Simplify whitespace that appears on both sides of a formatting option
120     txt.gsub!(/\s+(#{Bold}|#{Underline})\s+/, ' \1')
121     txt.sub!(/\s+(#{Bold}|#{Underline})\z/, '\1')
122     txt.sub!(/\A(#{Bold}|#{Underline})\s+/, '\1')
123
124     # And finally whitespace is squeezed
125     txt.gsub!(/\s+/, ' ')
126
127     # Decode entities and strip whitespace
128     return txt.strip
129   end
130
131   # This method will strip all HTML crud from the receiver
132   #
133   def riphtml
134     self.gsub(/<[^>]+>/, '').gsub(/&amp;/,'&').gsub(/&quot;/,'"').gsub(/&lt;/,'<').gsub(/&gt;/,'>').gsub(/&ellip;/,'...').gsub(/&apos;/, "'").gsub("\n",'')
135   end
136 end
137
138
139 # Extensions to the Regexp class, with some common and/or complex regular
140 # expressions.
141 #
142 class ::Regexp
143
144   # A method to build a regexp that matches a list of something separated by
145   # optional commas and/or the word "and", an optionally repeated prefix,
146   # and whitespace.
147   def Regexp.new_list(reg, pfx = "")
148     if pfx.kind_of?(String) and pfx.empty?
149       return %r(#{reg}(?:,?(?:\s+and)?\s+#{reg})*)
150     else
151       return %r(#{reg}(?:,?(?:\s+and)?(?:\s+#{pfx})?\s+#{reg})*)
152     end
153   end
154
155   IN_ON = /in|on/
156
157   module Irc
158     # Match a list of channel anmes separated by optional commas, whitespace
159     # and optionally the word "and"
160     CHAN_LIST = Regexp.new_list(GEN_CHAN)
161
162     # Match "in #channel" or "on #channel" and/or "in private" (optionally
163     # shortened to "in pvt"), returning the channel name or the word 'private'
164     # or 'pvt' as capture
165     IN_CHAN = /#{IN_ON}\s+(#{GEN_CHAN})|(here)|/
166     IN_CHAN_PVT = /#{IN_CHAN}|in\s+(private|pvt)/
167
168     # As above, but with channel lists
169     IN_CHAN_LIST_SFX = Regexp.new_list(/#{GEN_CHAN}|here/, IN_ON)
170     IN_CHAN_LIST = /#{IN_ON}\s+#{IN_CHAN_LIST_SFX}|anywhere|everywhere/
171     IN_CHAN_LIST_PVT_SFX = Regexp.new_list(/#{GEN_CHAN}|here|private|pvt/, IN_ON)
172     IN_CHAN_LIST_PVT = /#{IN_ON}\s+#{IN_CHAN_LIST_PVT_SFX}|anywhere|everywhere/
173
174     # Match a list of nicknames separated by optional commas, whitespace and
175     # optionally the word "and"
176     NICK_LIST = Regexp.new_list(GEN_NICK)
177
178   end
179
180 end
181
182
183 module ::Irc
184
185
186   class BasicUserMessage
187
188     # We extend the BasicUserMessage class with a method that parses a string
189     # which is a channel list as matched by IN_CHAN(_LIST) and co. The method
190     # returns an array of channel names, where 'private' or 'pvt' is replaced
191     # by the Symbol :"?", 'here' is replaced by the channel of the message or
192     # by :"?" (depending on whether the message target is the bot or a
193     # Channel), and 'anywhere' and 'everywhere' are replaced by Symbol :*
194     #
195     def parse_channel_list(string)
196       return [:*] if [:anywhere, :everywhere].include? string.to_sym
197       string.scan(
198       /(?:^|,?(?:\s+and)?\s+)(?:in|on\s+)?(#{Regexp::Irc::GEN_CHAN}|here|private|pvt)/
199                  ).map { |chan_ar|
200         chan = chan_ar.first
201         case chan.to_sym
202         when :private, :pvt
203           :"?"
204         when :here
205           case self.target
206           when Channel
207             self.target.name
208           else
209             :"?"
210           end
211         else
212           chan
213         end
214       }.uniq
215     end
216   end
217 end