]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/extends.rb
extends.rb: suppress warning
[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 #
8 # This file collects extensions to standard Ruby classes and to some core rbot
9 # classes to be used by the various plugins
10 #
11 # Please note that global symbols have to be prefixed by :: because this plugin
12 # will be read into an anonymous module
13
14 # Extensions to the Module class
15 #
16 class ::Module
17
18   # Many plugins define Struct objects to hold their data. On rescans, lots of
19   # warnings are echoed because of the redefinitions. Using this method solves
20   # the problem, by checking if the Struct already exists, and if it has the
21   # same attributes
22   #
23   def define_structure(name, *members)
24     sym = name.to_sym
25     if Struct.const_defined?(sym)
26       kl = Struct.const_get(sym)
27       if kl.new.members.map { |member| member.intern } == members.map
28         debug "Struct #{sym} previously defined, skipping"
29         const_set(sym, kl)
30         return
31       end
32     end
33     debug "Defining struct #{sym} with members #{members.inspect}"
34     const_set(sym, Struct.new(name.to_s, *members))
35   end
36 end
37
38
39 # DottedIndex mixin: extend a Hash or Array class with this module
40 # to achieve [] and []= methods that automatically split indices
41 # at dots (indices are automatically converted to symbols, too)
42 #
43 # You have to define the single_retrieve(_key_) and
44 # single_assign(_key_,_value_) methods (usually aliased at the
45 # original :[] and :[]= methods)
46 #
47 module ::DottedIndex
48   def rbot_index_split(*ar)
49     keys = ([] << ar).flatten
50     keys.map! { |k|
51       k.to_s.split('.').map { |kk| kk.to_sym rescue nil }.compact
52     }.flatten
53   end
54
55   def [](*ar)
56     keys = self.rbot_index_split(ar)
57     return self.single_retrieve(keys.first) if keys.length == 1
58     h = self
59     while keys.length > 1
60       k = keys.shift
61       h[k] ||= self.class.new
62       h = h[k]
63     end
64     h[keys.last]
65   end
66
67   def []=(*arr)
68     val = arr.last
69     ar = arr[0..-2]
70     keys = self.rbot_index_split(ar)
71     return self.single_assign(keys.first, val) if keys.length == 1
72     h = self
73     while keys.length > 1
74       k = keys.shift
75       h[k] ||= self.class.new
76       h = h[k]
77     end
78     h[keys.last] = val
79   end
80 end
81
82
83 # Extensions to the Array class
84 #
85 class ::Array
86
87   # This method returns a random element from the array, or nil if the array is
88   # empty
89   #
90   def pick_one
91     return nil if self.empty?
92     self[rand(self.length)]
93   end
94
95   # This method returns a given element from the array, deleting it from the
96   # array itself. The method returns nil if the element couldn't be found.
97   #
98   # If nil is specified, a random element is returned and deleted.
99   #
100   def delete_one(val=nil)
101     return nil if self.empty?
102     if val.nil?
103       index = rand(self.length)
104     else
105       index = self.index(val)
106       return nil unless index
107     end
108     self.delete_at(index)
109   end
110
111   # shuffle and shuffle! are defined in Ruby >= 1.8.7
112
113   # This method returns a new array with the same items as
114   # the receiver, but shuffled
115   unless method_defined? :shuffle
116     def shuffle
117       sort_by { rand }
118     end
119   end
120
121   # This method shuffles the items in the array
122   unless method_defined? :shuffle!
123     def shuffle!
124       replace shuffle
125     end
126   end
127
128 end
129
130 # Extensions to the Range class
131 #
132 class ::Range
133
134   # This method returns a random number between the lower and upper bound
135   #
136   def pick_one
137     len = self.last - self.first
138     len += 1 unless self.exclude_end?
139     self.first + Kernel::rand(len)
140   end
141   alias :rand :pick_one
142 end
143
144 # Extensions for the Numeric classes
145 #
146 class ::Numeric
147
148   # This method forces a real number to be not more than a given positive
149   # number or not less than a given positive number, or between two any given
150   # numbers
151   #
152   def clip(left,right=0)
153     raise ArgumentError unless left.kind_of?(Numeric) and right.kind_of?(Numeric)
154     l = [left,right].min
155     u = [left,right].max
156     return l if self < l
157     return u if self > u
158     return self
159   end
160 end
161
162 # Extensions to the String class
163 #
164 # TODO make riphtml() just call ircify_html() with stronger purify options.
165 #
166 class ::String
167
168   # This method will return a purified version of the receiver, with all HTML
169   # stripped off and some of it converted to IRC formatting
170   #
171   def ircify_html(opts={})
172     txt = self.dup
173
174     # remove scripts
175     txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
176
177     # remove styles
178     txt.gsub!(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
179
180     # bold and strong -> bold
181     txt.gsub!(/<\/?(?:b|strong)(?:\s+[^>]*)?>/im, "#{Bold}")
182
183     # italic, emphasis and underline -> underline
184     txt.gsub!(/<\/?(?:i|em|u)(?:\s+[^>]*)?>/im, "#{Underline}")
185
186     ## This would be a nice addition, but the results are horrible
187     ## Maybe make it configurable?
188     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
189     case val = opts[:a_href]
190     when Reverse, Bold, Underline
191       txt.gsub!(/<(?:\/a\s*|a (?:[^>]*\s+)?href\s*=\s*(?:[^>]*\s*)?)>/, val)
192     when :link_out
193       # Not good for nested links, but the best we can do without something like hpricot
194       txt.gsub!(/<a (?:[^>]*\s+)?href\s*=\s*(?:([^"'>][^\s>]*)\s+|"((?:[^"]|\\")*)"|'((?:[^']|\\')*)')(?:[^>]*\s+)?>(.*?)<\/a>/) { |match|
195         debug match
196         debug [$1, $2, $3, $4].inspect
197         link = $1 || $2 || $3
198         str = $4
199         str + ": " + link
200       }
201     else
202       warning "unknown :a_href option #{val} passed to ircify_html" if val
203     end
204
205     # Paragraph and br tags are converted to whitespace
206     txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/i, ' ')
207     txt.gsub!("\n", ' ')
208     txt.gsub!("\r", ' ')
209
210     # Superscripts and subscripts are turned into ^{...} and _{...}
211     # where the {} are omitted for single characters
212     txt.gsub!(/<sup>(.*?)<\/sup>/, '^{\1}')
213     txt.gsub!(/<sub>(.*?)<\/sub>/, '_{\1}')
214     txt.gsub!(/(^|_)\{(.)\}/, '\1\2')
215
216     # List items are converted to *). We don't have special support for
217     # nested or ordered lists.
218     txt.gsub!(/<li>/, ' *) ')
219
220     # All other tags are just removed
221     txt.gsub!(/<[^>]+>/, '')
222
223     # Convert HTML entities. We do it now to be able to handle stuff
224     # such as &nbsp;
225     txt = Utils.decode_html_entities(txt)
226
227     # Keep unbreakable spaces or conver them to plain spaces?
228     case val = opts[:nbsp]
229     when :space, ' '
230       txt.gsub!([160].pack('U'), ' ')
231     else
232       warning "unknown :nbsp option #{val} passed to ircify_html" if val
233     end
234
235     # Remove double formatting options, since they only waste bytes
236     txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
237     txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
238
239     # Simplify whitespace that appears on both sides of a formatting option
240     txt.gsub!(/\s+(#{Bold}|#{Underline})\s+/, ' \1')
241     txt.sub!(/\s+(#{Bold}|#{Underline})\z/, '\1')
242     txt.sub!(/\A(#{Bold}|#{Underline})\s+/, '\1')
243
244     # And finally whitespace is squeezed
245     txt.gsub!(/\s+/, ' ')
246     txt.strip!
247
248     if opts[:limit] && txt.size > opts[:limit]
249       txt = txt.slice(0, opts[:limit]) + "#{Reverse}...#{Reverse}"
250     end
251
252     # Decode entities and strip whitespace
253     return txt
254   end
255
256   # As above, but modify the receiver
257   #
258   def ircify_html!(opts={})
259     old_hash = self.hash
260     replace self.ircify_html(opts)
261     return self unless self.hash == old_hash
262   end
263
264   # This method will strip all HTML crud from the receiver
265   #
266   def riphtml
267     self.gsub(/<[^>]+>/, '').gsub(/&amp;/,'&').gsub(/&quot;/,'"').gsub(/&lt;/,'<').gsub(/&gt;/,'>').gsub(/&ellip;/,'...').gsub(/&apos;/, "'").gsub("\n",'')
268   end
269
270   # This method tries to find an HTML title in the string,
271   # and returns it if found
272   def get_html_title
273     if defined? ::Hpricot
274       Hpricot(self).at("title").inner_html
275     else
276       return unless Irc::Utils::TITLE_REGEX.match(self)
277       $1
278     end
279   end
280
281   # This method returns the IRC-formatted version of an
282   # HTML title found in the string
283   def ircify_html_title
284     self.get_html_title.ircify_html rescue nil
285   end
286 end
287
288
289 # Extensions to the Regexp class, with some common and/or complex regular
290 # expressions.
291 #
292 class ::Regexp
293
294   # A method to build a regexp that matches a list of something separated by
295   # optional commas and/or the word "and", an optionally repeated prefix,
296   # and whitespace.
297   def Regexp.new_list(reg, pfx = "")
298     if pfx.kind_of?(String) and pfx.empty?
299       return %r(#{reg}(?:,?(?:\s+and)?\s+#{reg})*)
300     else
301       return %r(#{reg}(?:,?(?:\s+and)?(?:\s+#{pfx})?\s+#{reg})*)
302     end
303   end
304
305   IN_ON = /in|on/
306
307   module Irc
308     # Match a list of channel anmes separated by optional commas, whitespace
309     # and optionally the word "and"
310     CHAN_LIST = Regexp.new_list(GEN_CHAN)
311
312     # Match "in #channel" or "on #channel" and/or "in private" (optionally
313     # shortened to "in pvt"), returning the channel name or the word 'private'
314     # or 'pvt' as capture
315     IN_CHAN = /#{IN_ON}\s+(#{GEN_CHAN})|(here)|/
316     IN_CHAN_PVT = /#{IN_CHAN}|in\s+(private|pvt)/
317
318     # As above, but with channel lists
319     IN_CHAN_LIST_SFX = Regexp.new_list(/#{GEN_CHAN}|here/, IN_ON)
320     IN_CHAN_LIST = /#{IN_ON}\s+#{IN_CHAN_LIST_SFX}|anywhere|everywhere/
321     IN_CHAN_LIST_PVT_SFX = Regexp.new_list(/#{GEN_CHAN}|here|private|pvt/, IN_ON)
322     IN_CHAN_LIST_PVT = /#{IN_ON}\s+#{IN_CHAN_LIST_PVT_SFX}|anywhere|everywhere/
323
324     # Match a list of nicknames separated by optional commas, whitespace and
325     # optionally the word "and"
326     NICK_LIST = Regexp.new_list(GEN_NICK)
327
328   end
329
330 end
331
332
333 module ::Irc
334
335
336   class BasicUserMessage
337
338     # We extend the BasicUserMessage class with a method that parses a string
339     # which is a channel list as matched by IN_CHAN(_LIST) and co. The method
340     # returns an array of channel names, where 'private' or 'pvt' is replaced
341     # by the Symbol :"?", 'here' is replaced by the channel of the message or
342     # by :"?" (depending on whether the message target is the bot or a
343     # Channel), and 'anywhere' and 'everywhere' are replaced by Symbol :*
344     #
345     def parse_channel_list(string)
346       return [:*] if [:anywhere, :everywhere].include? string.to_sym
347       string.scan(
348       /(?:^|,?(?:\s+and)?\s+)(?:in|on\s+)?(#{Regexp::Irc::GEN_CHAN}|here|private|pvt)/
349                  ).map { |chan_ar|
350         chan = chan_ar.first
351         case chan.to_sym
352         when :private, :pvt
353           :"?"
354         when :here
355           case self.target
356           when Channel
357             self.target.name
358           else
359             :"?"
360           end
361         else
362           chan
363         end
364       }.uniq
365     end
366
367     # The recurse depth of a message, for fake messages. 0 means an original
368     # message
369     def recurse_depth
370       unless defined? @recurse_depth
371         @recurse_depth = 0
372       end
373       @recurse_depth
374     end
375
376     # Set the recurse depth of a message, for fake messages. 0 should only
377     # be used by original messages
378     def recurse_depth=(val)
379       @recurse_depth = val
380     end
381   end
382
383   class Bot
384     module Plugins
385
386       # Maximum fake message recursion
387       MAX_RECURSE_DEPTH = 10
388
389       class RecurseTooDeep < RuntimeError
390       end
391
392       class BotModule
393         # Sometimes plugins need to create a new fake message based on an existing
394         # message: for example, this is done by alias, linkbot, reaction and remotectl.
395         #
396         # This method simplifies the message creation, including a recursion depth
397         # check.
398         #
399         # In the options you can specify the :bot, the :server, the :source,
400         # the :target, the message :class and whether or not to :delegate. To
401         # initialize these entries from an existing message, you can use :from
402         #
403         # Additionally, if :from is given, the reply method of created message
404         # is overriden to reply to :from instead. The #in_thread attribute
405         # for created mesage is also copied from :from
406         #
407         # If you don't specify a :from you should specify a :source.
408         #
409         def fake_message(string, opts={})
410           if from = opts[:from]
411             o = {
412               :bot => from.bot, :server => from.server, :source => from.source,
413               :target => from.target, :class => from.class, :delegate => true,
414               :depth => from.recurse_depth + 1
415             }.merge(opts)
416           else
417             o = {
418               :bot => @bot, :server => @bot.server, :target => @bot.myself,
419               :class => PrivMessage, :delegate => true, :depth => 1
420             }.merge(opts)
421           end
422           raise RecurseTooDeep if o[:depth] > MAX_RECURSE_DEPTH
423           new_m = o[:class].new(o[:bot], o[:server], o[:source], o[:target], string)
424           new_m.recurse_depth = o[:depth]
425           if from
426             # the created message will reply to the originating message
427             class << new_m
428               self
429             end.send(:define_method, :reply) do |*args|
430               debug "replying to '#{from.message}' with #{args.first}"
431               from.reply(*args)
432             end
433             # the created message will follow originating message's in_thread
434             new_m.in_thread = from.in_thread if from.respond_to?(:in_thread)
435           end
436           return new_m unless o[:delegate]
437           method = o[:class].to_s.gsub(/^Irc::|Message$/,'').downcase
438           method = 'privmsg' if method == 'priv'
439           o[:bot].plugins.irc_delegate(method, new_m)
440         end
441       end
442     end
443   end
444 end