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