]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/extends.rb
core/utils/extends.rb: add #conjoin for Array
[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   # This method is an advanced version of #join
129   # allowing fine control of separators:
130   #
131   #   [1,2,3].conjoin(', ', ' and ')
132   #   => "1, 2 and 3
133   #
134   #   [1,2,3,4].conjoin{ |i, a, b| i % 2 == 0 ? '.' : '-' }
135   #   => "1.2-3.4"
136   #
137   # Code lifted from the ruby facets project:
138   # <http://facets.rubyforge.org>
139   # git-rev: c8b7395255b977d3c7de268ff563e3c5bc7f1441
140   # file: lib/core/facets/array/conjoin.rb
141   def conjoin(*args, &block)
142     return first.to_s if size < 2
143
144     sep = []
145
146     if block_given?
147       (size - 1).times do |i|
148         sep << yield(i, *slice(i, 2))
149       end
150     else
151       options = (Hash === args.last) ? args.pop : {}
152       separator = args.shift || ""
153       options[-1] = args.shift unless args.empty?
154
155       sep = [separator] * (size - 1)
156
157       if options.key?(:last)
158         options[-1] = options.delete(:last)
159       end
160       options[-1] ||= _(" and ")
161
162       options.each{ |i, s| sep[i] = s }
163     end
164
165     zip(sep).join
166   end
167 end
168
169 # Extensions to the Range class
170 #
171 class ::Range
172
173   # This method returns a random number between the lower and upper bound
174   #
175   def pick_one
176     len = self.last - self.first
177     len += 1 unless self.exclude_end?
178     self.first + Kernel::rand(len)
179   end
180   alias :rand :pick_one
181 end
182
183 # Extensions for the Numeric classes
184 #
185 class ::Numeric
186
187   # This method forces a real number to be not more than a given positive
188   # number or not less than a given positive number, or between two any given
189   # numbers
190   #
191   def clip(left,right=0)
192     raise ArgumentError unless left.kind_of?(Numeric) and right.kind_of?(Numeric)
193     l = [left,right].min
194     u = [left,right].max
195     return l if self < l
196     return u if self > u
197     return self
198   end
199 end
200
201 # Extensions to the String class
202 #
203 # TODO make riphtml() just call ircify_html() with stronger purify options.
204 #
205 class ::String
206
207   # This method will return a purified version of the receiver, with all HTML
208   # stripped off and some of it converted to IRC formatting
209   #
210   def ircify_html(opts={})
211     txt = self.dup
212
213     # remove scripts
214     txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
215
216     # remove styles
217     txt.gsub!(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
218
219     # bold and strong -> bold
220     txt.gsub!(/<\/?(?:b|strong)(?:\s+[^>]*)?>/im, "#{Bold}")
221
222     # italic, emphasis and underline -> underline
223     txt.gsub!(/<\/?(?:i|em|u)(?:\s+[^>]*)?>/im, "#{Underline}")
224
225     ## This would be a nice addition, but the results are horrible
226     ## Maybe make it configurable?
227     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
228     case val = opts[:a_href]
229     when Reverse, Bold, Underline
230       txt.gsub!(/<(?:\/a\s*|a (?:[^>]*\s+)?href\s*=\s*(?:[^>]*\s*)?)>/, val)
231     when :link_out
232       # Not good for nested links, but the best we can do without something like hpricot
233       txt.gsub!(/<a (?:[^>]*\s+)?href\s*=\s*(?:([^"'>][^\s>]*)\s+|"((?:[^"]|\\")*)"|'((?:[^']|\\')*)')(?:[^>]*\s+)?>(.*?)<\/a>/) { |match|
234         debug match
235         debug [$1, $2, $3, $4].inspect
236         link = $1 || $2 || $3
237         str = $4
238         str + ": " + link
239       }
240     else
241       warning "unknown :a_href option #{val} passed to ircify_html" if val
242     end
243
244     # Paragraph and br tags are converted to whitespace
245     txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/i, ' ')
246     txt.gsub!("\n", ' ')
247     txt.gsub!("\r", ' ')
248
249     # Superscripts and subscripts are turned into ^{...} and _{...}
250     # where the {} are omitted for single characters
251     txt.gsub!(/<sup>(.*?)<\/sup>/, '^{\1}')
252     txt.gsub!(/<sub>(.*?)<\/sub>/, '_{\1}')
253     txt.gsub!(/(^|_)\{(.)\}/, '\1\2')
254
255     # List items are converted to *). We don't have special support for
256     # nested or ordered lists.
257     txt.gsub!(/<li>/, ' *) ')
258
259     # All other tags are just removed
260     txt.gsub!(/<[^>]+>/, '')
261
262     # Convert HTML entities. We do it now to be able to handle stuff
263     # such as &nbsp;
264     txt = Utils.decode_html_entities(txt)
265
266     # Keep unbreakable spaces or conver them to plain spaces?
267     case val = opts[:nbsp]
268     when :space, ' '
269       txt.gsub!([160].pack('U'), ' ')
270     else
271       warning "unknown :nbsp option #{val} passed to ircify_html" if val
272     end
273
274     # Remove double formatting options, since they only waste bytes
275     txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
276     txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
277
278     # Simplify whitespace that appears on both sides of a formatting option
279     txt.gsub!(/\s+(#{Bold}|#{Underline})\s+/, ' \1')
280     txt.sub!(/\s+(#{Bold}|#{Underline})\z/, '\1')
281     txt.sub!(/\A(#{Bold}|#{Underline})\s+/, '\1')
282
283     # And finally whitespace is squeezed
284     txt.gsub!(/\s+/, ' ')
285     txt.strip!
286
287     if opts[:limit] && txt.size > opts[:limit]
288       txt = txt.slice(0, opts[:limit]) + "#{Reverse}...#{Reverse}"
289     end
290
291     # Decode entities and strip whitespace
292     return txt
293   end
294
295   # As above, but modify the receiver
296   #
297   def ircify_html!(opts={})
298     old_hash = self.hash
299     replace self.ircify_html(opts)
300     return self unless self.hash == old_hash
301   end
302
303   # This method will strip all HTML crud from the receiver
304   #
305   def riphtml
306     self.gsub(/<[^>]+>/, '').gsub(/&amp;/,'&').gsub(/&quot;/,'"').gsub(/&lt;/,'<').gsub(/&gt;/,'>').gsub(/&ellip;/,'...').gsub(/&apos;/, "'").gsub("\n",'')
307   end
308
309   # This method tries to find an HTML title in the string,
310   # and returns it if found
311   def get_html_title
312     if defined? ::Hpricot
313       Hpricot(self).at("title").inner_html
314     else
315       return unless Irc::Utils::TITLE_REGEX.match(self)
316       $1
317     end
318   end
319
320   # This method returns the IRC-formatted version of an
321   # HTML title found in the string
322   def ircify_html_title
323     self.get_html_title.ircify_html rescue nil
324   end
325
326   # This method is used to wrap a nonempty String by adding
327   # the prefix and postfix
328   def wrap_nonempty(pre, post, opts={})
329     if self.empty?
330       String.new
331     else
332       "#{pre}#{self}#{post}"
333     end
334   end
335 end
336
337
338 # Extensions to the Regexp class, with some common and/or complex regular
339 # expressions.
340 #
341 class ::Regexp
342
343   # A method to build a regexp that matches a list of something separated by
344   # optional commas and/or the word "and", an optionally repeated prefix,
345   # and whitespace.
346   def Regexp.new_list(reg, pfx = "")
347     if pfx.kind_of?(String) and pfx.empty?
348       return %r(#{reg}(?:,?(?:\s+and)?\s+#{reg})*)
349     else
350       return %r(#{reg}(?:,?(?:\s+and)?(?:\s+#{pfx})?\s+#{reg})*)
351     end
352   end
353
354   IN_ON = /in|on/
355
356   module Irc
357     # Match a list of channel anmes separated by optional commas, whitespace
358     # and optionally the word "and"
359     CHAN_LIST = Regexp.new_list(GEN_CHAN)
360
361     # Match "in #channel" or "on #channel" and/or "in private" (optionally
362     # shortened to "in pvt"), returning the channel name or the word 'private'
363     # or 'pvt' as capture
364     IN_CHAN = /#{IN_ON}\s+(#{GEN_CHAN})|(here)|/
365     IN_CHAN_PVT = /#{IN_CHAN}|in\s+(private|pvt)/
366
367     # As above, but with channel lists
368     IN_CHAN_LIST_SFX = Regexp.new_list(/#{GEN_CHAN}|here/, IN_ON)
369     IN_CHAN_LIST = /#{IN_ON}\s+#{IN_CHAN_LIST_SFX}|anywhere|everywhere/
370     IN_CHAN_LIST_PVT_SFX = Regexp.new_list(/#{GEN_CHAN}|here|private|pvt/, IN_ON)
371     IN_CHAN_LIST_PVT = /#{IN_ON}\s+#{IN_CHAN_LIST_PVT_SFX}|anywhere|everywhere/
372
373     # Match a list of nicknames separated by optional commas, whitespace and
374     # optionally the word "and"
375     NICK_LIST = Regexp.new_list(GEN_NICK)
376
377   end
378
379 end
380
381
382 module ::Irc
383
384
385   class BasicUserMessage
386
387     # We extend the BasicUserMessage class with a method that parses a string
388     # which is a channel list as matched by IN_CHAN(_LIST) and co. The method
389     # returns an array of channel names, where 'private' or 'pvt' is replaced
390     # by the Symbol :"?", 'here' is replaced by the channel of the message or
391     # by :"?" (depending on whether the message target is the bot or a
392     # Channel), and 'anywhere' and 'everywhere' are replaced by Symbol :*
393     #
394     def parse_channel_list(string)
395       return [:*] if [:anywhere, :everywhere].include? string.to_sym
396       string.scan(
397       /(?:^|,?(?:\s+and)?\s+)(?:in|on\s+)?(#{Regexp::Irc::GEN_CHAN}|here|private|pvt)/
398                  ).map { |chan_ar|
399         chan = chan_ar.first
400         case chan.to_sym
401         when :private, :pvt
402           :"?"
403         when :here
404           case self.target
405           when Channel
406             self.target.name
407           else
408             :"?"
409           end
410         else
411           chan
412         end
413       }.uniq
414     end
415
416     # The recurse depth of a message, for fake messages. 0 means an original
417     # message
418     def recurse_depth
419       unless defined? @recurse_depth
420         @recurse_depth = 0
421       end
422       @recurse_depth
423     end
424
425     # Set the recurse depth of a message, for fake messages. 0 should only
426     # be used by original messages
427     def recurse_depth=(val)
428       @recurse_depth = val
429     end
430   end
431
432   class Bot
433     module Plugins
434
435       # Maximum fake message recursion
436       MAX_RECURSE_DEPTH = 10
437
438       class RecurseTooDeep < RuntimeError
439       end
440
441       class BotModule
442         # Sometimes plugins need to create a new fake message based on an existing
443         # message: for example, this is done by alias, linkbot, reaction and remotectl.
444         #
445         # This method simplifies the message creation, including a recursion depth
446         # check.
447         #
448         # In the options you can specify the :bot, the :server, the :source,
449         # the :target, the message :class and whether or not to :delegate. To
450         # initialize these entries from an existing message, you can use :from
451         #
452         # Additionally, if :from is given, the reply method of created message
453         # is overriden to reply to :from instead. The #in_thread attribute
454         # for created mesage is also copied from :from
455         #
456         # If you don't specify a :from you should specify a :source.
457         #
458         def fake_message(string, opts={})
459           if from = opts[:from]
460             o = {
461               :bot => from.bot, :server => from.server, :source => from.source,
462               :target => from.target, :class => from.class, :delegate => true,
463               :depth => from.recurse_depth + 1
464             }.merge(opts)
465           else
466             o = {
467               :bot => @bot, :server => @bot.server, :target => @bot.myself,
468               :class => PrivMessage, :delegate => true, :depth => 1
469             }.merge(opts)
470           end
471           raise RecurseTooDeep if o[:depth] > MAX_RECURSE_DEPTH
472           new_m = o[:class].new(o[:bot], o[:server], o[:source], o[:target], string)
473           new_m.recurse_depth = o[:depth]
474           if from
475             # the created message will reply to the originating message
476             class << new_m
477               self
478             end.send(:define_method, :reply) do |*args|
479               debug "replying to '#{from.message}' with #{args.first}"
480               from.reply(*args)
481             end
482             # the created message will follow originating message's in_thread
483             new_m.in_thread = from.in_thread if from.respond_to?(:in_thread)
484           end
485           return new_m unless o[:delegate]
486           method = o[:class].to_s.gsub(/^Irc::|Message$/,'').downcase
487           method = 'privmsg' if method == 'priv'
488           o[:bot].plugins.irc_delegate(method, new_m)
489         end
490       end
491     end
492   end
493 end