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