]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/irc.rb
Message mapper: we are ony interested in matching messages that fully agree with...
[user/henk/code/ruby/rbot.git] / lib / rbot / irc.rb
1 #-- vim:sw=2:et\r
2 # General TODO list\r
3 # * do we want to handle a Channel list for each User telling which\r
4 #   Channels is the User on (of those the client is on too)?\r
5 #   We may want this so that when a User leaves all Channels and he hasn't\r
6 #   sent us privmsgs, we know we can remove him from the Server @users list\r
7 # * Maybe ChannelList and UserList should be HashesOf instead of ArrayOf?\r
8 #   See items marked as TODO Ho.\r
9 #   The framework to do this is now in place, thanks to the new [] method\r
10 #   for NetmaskList, which allows retrieval by Netmask or String\r
11 #++\r
12 # :title: IRC module\r
13 #\r
14 # Basic IRC stuff\r
15 #\r
16 # This module defines the fundamental building blocks for IRC\r
17 #\r
18 # Author:: Giuseppe Bilotta (giuseppe.bilotta@gmail.com)\r
19 # Copyright:: Copyright (c) 2006 Giuseppe Bilotta\r
20 # License:: GPLv2\r
21 \r
22 require 'singleton'\r
23 \r
24 class Object\r
25 \r
26   # We extend the Object class with a method that\r
27   # checks if the receiver is nil or empty\r
28   def nil_or_empty?\r
29     return true unless self\r
30     return true if self.respond_to? :empty and self.empty?\r
31     return false\r
32   end\r
33 end\r
34 \r
35 # The Irc module is used to keep all IRC-related classes\r
36 # in the same namespace\r
37 #\r
38 module Irc\r
39 \r
40 \r
41   # Due to its Scandinavian origins, IRC has strange case mappings, which\r
42   # consider the characters <tt>{}|^</tt> as the uppercase\r
43   # equivalents of # <tt>[]\~</tt>.\r
44   #\r
45   # This is however not the same on all IRC servers: some use standard ASCII\r
46   # casemapping, other do not consider <tt>^</tt> as the uppercase of\r
47   # <tt>~</tt>\r
48   #\r
49   class Casemap\r
50     @@casemaps = {}\r
51 \r
52     # Create a new casemap with name _name_, uppercase characters _upper_ and\r
53     # lowercase characters _lower_\r
54     #\r
55     def initialize(name, upper, lower)\r
56       @key = name.to_sym\r
57       raise "Casemap #{name.inspect} already exists!" if @@casemaps.has_key?(@key)\r
58       @@casemaps[@key] = {\r
59         :upper => upper,\r
60         :lower => lower,\r
61         :casemap => self\r
62       }\r
63     end\r
64 \r
65     # Returns the Casemap with the given name\r
66     #\r
67     def Casemap.get(name)\r
68       @@casemaps[name.to_sym][:casemap]\r
69     end\r
70 \r
71     # Retrieve the 'uppercase characters' of this Casemap\r
72     #\r
73     def upper\r
74       @@casemaps[@key][:upper]\r
75     end\r
76 \r
77     # Retrieve the 'lowercase characters' of this Casemap\r
78     #\r
79     def lower\r
80       @@casemaps[@key][:lower]\r
81     end\r
82 \r
83     # Return a Casemap based on the receiver\r
84     #\r
85     def to_irc_casemap\r
86       self\r
87     end\r
88 \r
89     # A Casemap is represented by its lower/upper mappings\r
90     #\r
91     def inspect\r
92       "#<#{self.class}:#{'0x%x'% self.object_id}: #{upper.inspect} ~(#{self})~ #{lower.inspect}>"\r
93     end\r
94 \r
95     # As a String we return our name\r
96     #\r
97     def to_s\r
98       @key.to_s\r
99     end\r
100 \r
101     # Two Casemaps are equal if they have the same upper and lower ranges\r
102     #\r
103     def ==(arg)\r
104       other = arg.to_irc_casemap\r
105       return self.upper == other.upper && self.lower == other.lower\r
106     end\r
107 \r
108     # Raise an error if _arg_ and self are not the same Casemap\r
109     #\r
110     def must_be(arg)\r
111       other = arg.to_irc_casemap\r
112       raise "Casemap mismatch (#{self.inspect} != #{other.inspect})" unless self == other\r
113       return true\r
114     end\r
115 \r
116   end\r
117 \r
118   # The rfc1459 casemap\r
119   #\r
120   class RfcCasemap < Casemap\r
121     include Singleton\r
122 \r
123     def initialize\r
124       super('rfc1459', "\x41-\x5e", "\x61-\x7e")\r
125     end\r
126 \r
127   end\r
128   RfcCasemap.instance\r
129 \r
130   # The strict-rfc1459 Casemap\r
131   #\r
132   class StrictRfcCasemap < Casemap\r
133     include Singleton\r
134 \r
135     def initialize\r
136       super('strict-rfc1459', "\x41-\x5d", "\x61-\x7d")\r
137     end\r
138 \r
139   end\r
140   StrictRfcCasemap.instance\r
141 \r
142   # The ascii Casemap\r
143   #\r
144   class AsciiCasemap < Casemap\r
145     include Singleton\r
146 \r
147     def initialize\r
148       super('ascii', "\x41-\x5a", "\x61-\x7a")\r
149     end\r
150 \r
151   end\r
152   AsciiCasemap.instance\r
153 \r
154 \r
155   # This module is included by all classes that are either bound to a server\r
156   # or should have a casemap.\r
157   #\r
158   module ServerOrCasemap\r
159 \r
160     attr_reader :server\r
161 \r
162     # This method initializes the instance variables @server and @casemap\r
163     # according to the values of the hash keys :server and :casemap in _opts_\r
164     #\r
165     def init_server_or_casemap(opts={})\r
166       @server = opts.fetch(:server, nil)\r
167       raise TypeError, "#{@server} is not a valid Irc::Server" if @server and not @server.kind_of?(Server)\r
168 \r
169       @casemap = opts.fetch(:casemap, nil)\r
170       if @server\r
171         if @casemap\r
172           @server.casemap.must_be(@casemap)\r
173           @casemap = nil\r
174         end\r
175       else\r
176         @casemap = (@casemap || 'rfc1459').to_irc_casemap\r
177       end\r
178     end\r
179 \r
180     # This is an auxiliary method: it returns true if the receiver fits the\r
181     # server and casemap specified in _opts_, false otherwise.\r
182     #\r
183     def fits_with_server_and_casemap?(opts={})\r
184       srv = opts.fetch(:server, nil)\r
185       cmap = opts.fetch(:casemap, nil)\r
186       cmap = cmap.to_irc_casemap unless cmap.nil?\r
187 \r
188       if srv.nil?\r
189         return true if cmap.nil? or cmap == casemap\r
190       else\r
191         return true if srv == @server and (cmap.nil? or cmap == casemap)\r
192       end\r
193       return false\r
194     end\r
195 \r
196     # Returns the casemap of the receiver, by looking at the bound\r
197     # @server (if possible) or at the @casemap otherwise\r
198     #\r
199     def casemap\r
200       return @server.casemap if defined?(@server) and @server\r
201       return @casemap\r
202     end\r
203 \r
204     # Returns a hash with the current @server and @casemap as values of\r
205     # :server and :casemap\r
206     #\r
207     def server_and_casemap\r
208       h = {}\r
209       h[:server] = @server if defined?(@server) and @server\r
210       h[:casemap] = @casemap if defined?(@casemap) and @casemap\r
211       return h\r
212     end\r
213 \r
214     # We allow up/downcasing with a different casemap\r
215     #\r
216     def irc_downcase(cmap=casemap)\r
217       self.to_s.irc_downcase(cmap)\r
218     end\r
219 \r
220     # Up/downcasing something that includes this module returns its\r
221     # Up/downcased to_s form\r
222     #\r
223     def downcase\r
224       self.irc_downcase\r
225     end\r
226 \r
227     # We allow up/downcasing with a different casemap\r
228     #\r
229     def irc_upcase(cmap=casemap)\r
230       self.to_s.irc_upcase(cmap)\r
231     end\r
232 \r
233     # Up/downcasing something that includes this module returns its\r
234     # Up/downcased to_s form\r
235     #\r
236     def upcase\r
237       self.irc_upcase\r
238     end\r
239 \r
240   end\r
241 \r
242 end\r
243 \r
244 \r
245 # We start by extending the String class\r
246 # with some IRC-specific methods\r
247 #\r
248 class String\r
249 \r
250   # This method returns the Irc::Casemap whose name is the receiver\r
251   #\r
252   def to_irc_casemap\r
253     Irc::Casemap.get(self) rescue raise TypeError, "Unkown Irc::Casemap #{self.inspect}"\r
254   end\r
255 \r
256   # This method returns a string which is the downcased version of the\r
257   # receiver, according to the given _casemap_\r
258   #\r
259   #\r
260   def irc_downcase(casemap='rfc1459')\r
261     cmap = casemap.to_irc_casemap\r
262     self.tr(cmap.upper, cmap.lower)\r
263   end\r
264 \r
265   # This is the same as the above, except that the string is altered in place\r
266   #\r
267   # See also the discussion about irc_downcase\r
268   #\r
269   def irc_downcase!(casemap='rfc1459')\r
270     cmap = casemap.to_irc_casemap\r
271     self.tr!(cmap.upper, cmap.lower)\r
272   end\r
273 \r
274   # Upcasing functions are provided too\r
275   #\r
276   # See also the discussion about irc_downcase\r
277   #\r
278   def irc_upcase(casemap='rfc1459')\r
279     cmap = casemap.to_irc_casemap\r
280     self.tr(cmap.lower, cmap.upper)\r
281   end\r
282 \r
283   # In-place upcasing\r
284   #\r
285   # See also the discussion about irc_downcase\r
286   #\r
287   def irc_upcase!(casemap='rfc1459')\r
288     cmap = casemap.to_irc_casemap\r
289     self.tr!(cmap.lower, cmap.upper)\r
290   end\r
291 \r
292   # This method checks if the receiver contains IRC glob characters\r
293   #\r
294   # IRC has a very primitive concept of globs: a <tt>*</tt> stands for "any\r
295   # number of arbitrary characters", a <tt>?</tt> stands for "one and exactly\r
296   # one arbitrary character". These characters can be escaped by prefixing them\r
297   # with a slash (<tt>\\</tt>).\r
298   #\r
299   # A known limitation of this glob syntax is that there is no way to escape\r
300   # the escape character itself, so it's not possible to build a glob pattern\r
301   # where the escape character precedes a glob.\r
302   #\r
303   def has_irc_glob?\r
304     self =~ /^[*?]|[^\\][*?]/\r
305   end\r
306 \r
307   # This method is used to convert the receiver into a Regular Expression\r
308   # that matches according to the IRC glob syntax\r
309   #\r
310   def to_irc_regexp\r
311     regmask = Regexp.escape(self)\r
312     regmask.gsub!(/(\\\\)?\\[*?]/) { |m|\r
313       case m\r
314       when /\\(\\[*?])/\r
315         $1\r
316       when /\\\*/\r
317         '.*'\r
318       when /\\\?/\r
319         '.'\r
320       else\r
321         raise "Unexpected match #{m} when converting #{self}"\r
322       end\r
323     }\r
324     Regexp.new(regmask)\r
325   end\r
326 \r
327 end\r
328 \r
329 \r
330 # ArrayOf is a subclass of Array whose elements are supposed to be all\r
331 # of the same class. This is not intended to be used directly, but rather\r
332 # to be subclassed as needed (see for example Irc::UserList and Irc::NetmaskList)\r
333 #\r
334 # Presently, only very few selected methods from Array are overloaded to check\r
335 # if the new elements are the correct class. An orthodox? method is provided\r
336 # to check the entire ArrayOf against the appropriate class.\r
337 #\r
338 class ArrayOf < Array\r
339 \r
340   attr_reader :element_class\r
341 \r
342   # Create a new ArrayOf whose elements are supposed to be all of type _kl_,\r
343   # optionally filling it with the elements from the Array argument.\r
344   #\r
345   def initialize(kl, ar=[])\r
346     raise TypeError, "#{kl.inspect} must be a class name" unless kl.kind_of?(Class)\r
347     super()\r
348     @element_class = kl\r
349     case ar\r
350     when Array\r
351       insert(0, *ar)\r
352     else\r
353       raise TypeError, "#{self.class} can only be initialized from an Array"\r
354     end\r
355   end\r
356 \r
357   def inspect\r
358     "#<#{self.class}[#{@element_class}]:#{'0x%x' % self.object_id}: #{super}>"\r
359   end\r
360 \r
361   # Private method to check the validity of the elements passed to it\r
362   # and optionally raise an error\r
363   #\r
364   # TODO should it accept nils as valid?\r
365   #\r
366   def internal_will_accept?(raising, *els)\r
367     els.each { |el|\r
368       unless el.kind_of?(@element_class)\r
369         raise TypeError, "#{el.inspect} is not of class #{@element_class}" if raising\r
370         return false\r
371       end\r
372     }\r
373     return true\r
374   end\r
375   private :internal_will_accept?\r
376 \r
377   # This method checks if the passed arguments are acceptable for our ArrayOf\r
378   #\r
379   def will_accept?(*els)\r
380     internal_will_accept?(false, *els)\r
381   end\r
382 \r
383   # This method checks that all elements are of the appropriate class\r
384   #\r
385   def valid?\r
386     will_accept?(*self)\r
387   end\r
388 \r
389   # This method is similar to the above, except that it raises an exception\r
390   # if the receiver is not valid\r
391   #\r
392   def validate\r
393     raise TypeError unless valid?\r
394   end\r
395 \r
396   # Overloaded from Array#<<, checks for appropriate class of argument\r
397   #\r
398   def <<(el)\r
399     super(el) if internal_will_accept?(true, el)\r
400   end\r
401 \r
402   # Overloaded from Array#&, checks for appropriate class of argument elements\r
403   #\r
404   def &(ar)\r
405     r = super(ar)\r
406     ArrayOf.new(@element_class, r) if internal_will_accept?(true, *r)\r
407   end\r
408 \r
409   # Overloaded from Array#+, checks for appropriate class of argument elements\r
410   #\r
411   def +(ar)\r
412     ArrayOf.new(@element_class, super(ar)) if internal_will_accept?(true, *ar)\r
413   end\r
414 \r
415   # Overloaded from Array#-, so that an ArrayOf is returned. There is no need\r
416   # to check the validity of the elements in the argument\r
417   #\r
418   def -(ar)\r
419     ArrayOf.new(@element_class, super(ar)) # if internal_will_accept?(true, *ar)\r
420   end\r
421 \r
422   # Overloaded from Array#|, checks for appropriate class of argument elements\r
423   #\r
424   def |(ar)\r
425     ArrayOf.new(@element_class, super(ar)) if internal_will_accept?(true, *ar)\r
426   end\r
427 \r
428   # Overloaded from Array#concat, checks for appropriate class of argument\r
429   # elements\r
430   #\r
431   def concat(ar)\r
432     super(ar) if internal_will_accept?(true, *ar)\r
433   end\r
434 \r
435   # Overloaded from Array#insert, checks for appropriate class of argument\r
436   # elements\r
437   #\r
438   def insert(idx, *ar)\r
439     super(idx, *ar) if internal_will_accept?(true, *ar)\r
440   end\r
441 \r
442   # Overloaded from Array#replace, checks for appropriate class of argument\r
443   # elements\r
444   #\r
445   def replace(ar)\r
446     super(ar) if (ar.kind_of?(ArrayOf) && ar.element_class <= @element_class) or internal_will_accept?(true, *ar)\r
447   end\r
448 \r
449   # Overloaded from Array#push, checks for appropriate class of argument\r
450   # elements\r
451   #\r
452   def push(*ar)\r
453     super(*ar) if internal_will_accept?(true, *ar)\r
454   end\r
455 \r
456   # Overloaded from Array#unshift, checks for appropriate class of argument(s)\r
457   #\r
458   def unshift(*els)\r
459     els.each { |el|\r
460       super(el) if internal_will_accept?(true, *els)\r
461     }\r
462   end\r
463 \r
464   # We introduce the 'downcase' method, which maps downcase() to all the Array\r
465   # elements, properly failing when the elements don't have a downcase method\r
466   #\r
467   def downcase\r
468     self.map { |el| el.downcase }\r
469   end\r
470 \r
471   # Modifying methods which we don't handle yet are made private\r
472   #\r
473   private :[]=, :collect!, :map!, :fill, :flatten!\r
474 \r
475 end\r
476 \r
477 \r
478 module Irc\r
479 \r
480 \r
481   # A Netmask identifies each user by collecting its nick, username and\r
482   # hostname in the form <tt>nick!user@host</tt>\r
483   #\r
484   # Netmasks can also contain glob patterns in any of their components; in\r
485   # this form they are used to refer to more than a user or to a user\r
486   # appearing under different forms.\r
487   #\r
488   # Example:\r
489   # * <tt>*!*@*</tt> refers to everybody\r
490   # * <tt>*!someuser@somehost</tt> refers to user +someuser+ on host +somehost+\r
491   #   regardless of the nick used.\r
492   #\r
493   class Netmask\r
494 \r
495     # Netmasks have an associated casemap unless they are bound to a server\r
496     #\r
497     include ServerOrCasemap\r
498 \r
499     attr_reader :nick, :user, :host\r
500 \r
501     # Create a new Netmask from string _str_, which must be in the form\r
502     # _nick_!_user_@_host_\r
503     #\r
504     # It is possible to specify a server or a casemap in the optional Hash:\r
505     # these are used to associate the Netmask with the given server and to set\r
506     # its casemap: if a server is specified and a casemap is not, the server's\r
507     # casemap is used. If both a server and a casemap are specified, the\r
508     # casemap must match the server's casemap or an exception will be raised.\r
509     #\r
510     # Empty +nick+, +user+ or +host+ are converted to the generic glob pattern\r
511     #\r
512     def initialize(str="", opts={})\r
513       # First of all, check for server/casemap option\r
514       #\r
515       init_server_or_casemap(opts)\r
516 \r
517       # Now we can see if the given string _str_ is an actual Netmask\r
518       if str.respond_to?(:to_str)\r
519         case str.to_str\r
520         when /^(?:(\S+?)(?:!(\S+)@(?:(\S+))?)?)?$/\r
521           # We do assignment using our internal methods\r
522           self.nick = $1\r
523           self.user = $2\r
524           self.host = $3\r
525         else\r
526           raise ArgumentError, "#{str.to_str.inspect} does not represent a valid #{self.class}"\r
527         end\r
528       else\r
529         raise TypeError, "#{str} cannot be converted to a #{self.class}"\r
530       end\r
531     end\r
532 \r
533     # A Netmask is easily converted to a String for the usual representation\r
534     #\r
535     def fullform\r
536       "#{nick}!#{user}@#{host}"\r
537     end\r
538     alias :to_s :fullform\r
539 \r
540     # Converts the receiver into a Netmask with the given (optional)\r
541     # server/casemap association. We return self unless a conversion\r
542     # is needed (different casemap/server)\r
543     #\r
544     # Subclasses of Netmask will return a new Netmask\r
545     #\r
546     def to_irc_netmask(opts={})\r
547       if self.class == Netmask\r
548         return self if fits_with_server_and_casemap?(opts)\r
549       end\r
550       return self.fullform.to_irc_netmask(server_and_casemap.merge(opts))\r
551     end\r
552 \r
553     # Converts the receiver into a User with the given (optional)\r
554     # server/casemap association. We return self unless a conversion\r
555     # is needed (different casemap/server)\r
556     #\r
557     def to_irc_user(opts={})\r
558       self.fullform.to_irc_user(server_and_casemap.merge(opts))\r
559     end\r
560 \r
561     # Inspection of a Netmask reveals the server it's bound to (if there is\r
562     # one), its casemap and the nick, user and host part\r
563     #\r
564     def inspect\r
565       str = "<#{self.class}:#{'0x%x' % self.object_id}:"\r
566       str << " @server=#{@server}" if defined?(@server) and @server\r
567       str << " @nick=#{@nick.inspect} @user=#{@user.inspect}"\r
568       str << " @host=#{@host.inspect} casemap=#{casemap.inspect}"\r
569       str << ">"\r
570     end\r
571 \r
572     # Equality: two Netmasks are equal if they downcase to the same thing\r
573     #\r
574     # TODO we may want it to try other.to_irc_netmask\r
575     #\r
576     def ==(other)\r
577       return false unless other.kind_of?(self.class)\r
578       self.downcase == other.downcase\r
579     end\r
580 \r
581     # This method changes the nick of the Netmask, defaulting to the generic\r
582     # glob pattern if the result is the null string.\r
583     #\r
584     def nick=(newnick)\r
585       @nick = newnick.to_s\r
586       @nick = "*" if @nick.empty?\r
587     end\r
588 \r
589     # This method changes the user of the Netmask, defaulting to the generic\r
590     # glob pattern if the result is the null string.\r
591     #\r
592     def user=(newuser)\r
593       @user = newuser.to_s\r
594       @user = "*" if @user.empty?\r
595     end\r
596 \r
597     # This method changes the hostname of the Netmask, defaulting to the generic\r
598     # glob pattern if the result is the null string.\r
599     #\r
600     def host=(newhost)\r
601       @host = newhost.to_s\r
602       @host = "*" if @host.empty?\r
603     end\r
604 \r
605     # We can replace everything at once with data from another Netmask\r
606     #\r
607     def replace(other)\r
608       case other\r
609       when Netmask\r
610         nick = other.nick\r
611         user = other.user\r
612         host = other.host\r
613         @server = other.server\r
614         @casemap = other.casemap unless @server\r
615       else\r
616         replace(other.to_irc_netmask(server_and_casemap))\r
617       end\r
618     end\r
619 \r
620     # This method checks if a Netmask is definite or not, by seeing if\r
621     # any of its components are defined by globs\r
622     #\r
623     def has_irc_glob?\r
624       return @nick.has_irc_glob? || @user.has_irc_glob? || @host.has_irc_glob?\r
625     end\r
626 \r
627     # This method is used to match the current Netmask against another one\r
628     #\r
629     # The method returns true if each component of the receiver matches the\r
630     # corresponding component of the argument. By _matching_ here we mean\r
631     # that any netmask described by the receiver is also described by the\r
632     # argument.\r
633     #\r
634     # In this sense, matching is rather simple to define in the case when the\r
635     # receiver has no globs: it is just necessary to check if the argument\r
636     # describes the receiver, which can be done by matching it against the\r
637     # argument converted into an IRC Regexp (see String#to_irc_regexp).\r
638     #\r
639     # The situation is also easy when the receiver has globs and the argument\r
640     # doesn't, since in this case the result is false.\r
641     #\r
642     # The more complex case in which both the receiver and the argument have\r
643     # globs is not handled yet.\r
644     #\r
645     def matches?(arg)\r
646       cmp = arg.to_irc_netmask(:casemap => casemap)\r
647       debug "Matching #{self.fullform} against #{arg.fullform}"\r
648       [:nick, :user, :host].each { |component|\r
649         us = self.send(component).irc_downcase(casemap)\r
650         them = cmp.send(component).irc_downcase(casemap)\r
651         if us.has_irc_glob? && them.has_irc_glob?\r
652           next if us == them\r
653           warn NotImplementedError\r
654           return false\r
655         end\r
656         return false if us.has_irc_glob? && !them.has_irc_glob?\r
657         return false unless us =~ them.to_irc_regexp\r
658       }\r
659       return true\r
660     end\r
661 \r
662     # Case equality. Checks if arg matches self\r
663     #\r
664     def ===(arg)\r
665       arg.to_irc_netmask(:casemap => casemap).matches?(self)\r
666     end\r
667 \r
668     # Sorting is done via the fullform\r
669     #\r
670     def <=>(arg)\r
671       case arg\r
672       when Netmask\r
673         self.fullform.irc_downcase(casemap) <=> arg.fullform.irc_downcase(casemap)\r
674       else\r
675         self.downcase <=> arg.downcase\r
676       end\r
677     end\r
678 \r
679   end\r
680 \r
681 \r
682   # A NetmaskList is an ArrayOf <code>Netmask</code>s\r
683   #\r
684   class NetmaskList < ArrayOf\r
685 \r
686     # Create a new NetmaskList, optionally filling it with the elements from\r
687     # the Array argument fed to it.\r
688     #\r
689     def initialize(ar=[])\r
690       super(Netmask, ar)\r
691     end\r
692 \r
693     # We enhance the [] method by allowing it to pick an element that matches\r
694     # a given Netmask, a String or a Regexp\r
695     # TODO take into consideration the opportunity to use select() instead of\r
696     # find(), and/or a way to let the user choose which one to take (second\r
697     # argument?)\r
698     #\r
699     def [](*args)\r
700       if args.length == 1\r
701         case args[0]\r
702         when Netmask\r
703           self.find { |mask|\r
704             mask.matches?(args[0])\r
705           }\r
706         when String\r
707           self.find { |mask|\r
708             mask.matches?(args[0].to_irc_netmask(:casemap => mask.casemap))\r
709           }\r
710         when Regexp\r
711           self.find { |mask|\r
712             mask.fullform =~ args[0]\r
713           }\r
714         else\r
715           super(*args)\r
716         end\r
717       else\r
718         super(*args)\r
719       end\r
720     end\r
721 \r
722   end\r
723 \r
724 end\r
725 \r
726 \r
727 class String\r
728 \r
729   # We keep extending String, this time adding a method that converts a\r
730   # String into an Irc::Netmask object\r
731   #\r
732   def to_irc_netmask(opts={})\r
733     Irc::Netmask.new(self, opts)\r
734   end\r
735 \r
736 end\r
737 \r
738 \r
739 module Irc\r
740 \r
741 \r
742   # An IRC User is identified by his/her Netmask (which must not have globs).\r
743   # In fact, User is just a subclass of Netmask.\r
744   #\r
745   # Ideally, the user and host information of an IRC User should never\r
746   # change, and it shouldn't contain glob patterns. However, IRC is somewhat\r
747   # idiosincratic and it may be possible to know the nick of a User much before\r
748   # its user and host are known. Moreover, some networks (namely Freenode) may\r
749   # change the hostname of a User when (s)he identifies with Nickserv.\r
750   #\r
751   # As a consequence, we must allow changes to a User host and user attributes.\r
752   # We impose a restriction, though: they may not contain glob patterns, except\r
753   # for the special case of an unknown user/host which is represented by a *.\r
754   #\r
755   # It is possible to create a totally unknown User (e.g. for initializations)\r
756   # by setting the nick to * too.\r
757   #\r
758   # TODO list:\r
759   # * see if it's worth to add the other USER data\r
760   # * see if it's worth to add NICKSERV status\r
761   #\r
762   class User < Netmask\r
763     alias :to_s :nick\r
764 \r
765     # Create a new IRC User from a given Netmask (or anything that can be converted\r
766     # into a Netmask) provided that the given Netmask does not have globs.\r
767     #\r
768     def initialize(str="", opts={})\r
769       super\r
770       raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if nick.has_irc_glob? && nick != "*"\r
771       raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if user.has_irc_glob? && user != "*"\r
772       raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if host.has_irc_glob? && host != "*"\r
773       @away = false\r
774     end\r
775 \r
776     # The nick of a User may be changed freely, but it must not contain glob patterns.\r
777     #\r
778     def nick=(newnick)\r
779       raise "Can't change the nick to #{newnick}" if defined?(@nick) and newnick.has_irc_glob?\r
780       super\r
781     end\r
782 \r
783     # We have to allow changing the user of an Irc User due to some networks\r
784     # (e.g. Freenode) changing hostmasks on the fly. We still check if the new\r
785     # user data has glob patterns though.\r
786     #\r
787     def user=(newuser)\r
788       raise "Can't change the username to #{newuser}" if defined?(@user) and newuser.has_irc_glob?\r
789       super\r
790     end\r
791 \r
792     # We have to allow changing the host of an Irc User due to some networks\r
793     # (e.g. Freenode) changing hostmasks on the fly. We still check if the new\r
794     # host data has glob patterns though.\r
795     #\r
796     def host=(newhost)\r
797       raise "Can't change the hostname to #{newhost}" if defined?(@host) and newhost.has_irc_glob?\r
798       super\r
799     end\r
800 \r
801     # Checks if a User is well-known or not by looking at the hostname and user\r
802     #\r
803     def known?\r
804       return nick!= "*" && user!="*" && host!="*"\r
805     end\r
806 \r
807     # Is the user away?\r
808     #\r
809     def away?\r
810       return @away\r
811     end\r
812 \r
813     # Set the away status of the user. Use away=(nil) or away=(false)\r
814     # to unset away\r
815     #\r
816     def away=(msg="")\r
817       if msg\r
818         @away = msg\r
819       else\r
820         @away = false\r
821       end\r
822     end\r
823 \r
824     # Since to_irc_user runs the same checks on server and channel as\r
825     # to_irc_netmask, we just try that and return self if it works.\r
826     #\r
827     # Subclasses of User will return self if possible.\r
828     #\r
829     def to_irc_user(opts={})\r
830       return self if fits_with_server_and_casemap?(opts)\r
831       return self.fullform.to_irc_user(server_and_casemap(opts))\r
832     end\r
833 \r
834     # We can replace everything at once with data from another User\r
835     #\r
836     def replace(other)\r
837       case other\r
838       when User\r
839         self.nick = other.nick\r
840         self.user = other.user\r
841         self.host = other.host\r
842         @server = other.server\r
843         @casemap = other.casemap unless @server\r
844         @away = other.away?\r
845       else\r
846         self.replace(other.to_irc_user(server_and_casemap))\r
847       end\r
848     end\r
849 \r
850   end\r
851 \r
852 \r
853   # A UserList is an ArrayOf <code>User</code>s\r
854   # We derive it from NetmaskList, which allows us to inherit any special\r
855   # NetmaskList method\r
856   #\r
857   class UserList < NetmaskList\r
858 \r
859     # Create a new UserList, optionally filling it with the elements from\r
860     # the Array argument fed to it.\r
861     #\r
862     def initialize(ar=[])\r
863       super(ar)\r
864       @element_class = User\r
865     end\r
866 \r
867     # Convenience method: convert the UserList to a list of nicks. The indices\r
868     # are preserved\r
869     #\r
870     def nicks\r
871       self.map { |user| user.nick }\r
872     end\r
873 \r
874   end\r
875 \r
876 end\r
877 \r
878 class String\r
879 \r
880   # We keep extending String, this time adding a method that converts a\r
881   # String into an Irc::User object\r
882   #\r
883   def to_irc_user(opts={})\r
884     Irc::User.new(self, opts)\r
885   end\r
886 \r
887 end\r
888 \r
889 module Irc\r
890 \r
891   # An IRC Channel is identified by its name, and it has a set of properties:\r
892   # * a Channel::Topic\r
893   # * a UserList\r
894   # * a set of Channel::Modes\r
895   #\r
896   # The Channel::Topic and Channel::Mode classes are defined within the\r
897   # Channel namespace because they only make sense there\r
898   #\r
899   class Channel\r
900 \r
901 \r
902     # Mode on a Channel\r
903     #\r
904     class Mode\r
905       attr_reader :channel\r
906       def initialize(ch)\r
907         @channel = ch\r
908       end\r
909 \r
910     end\r
911 \r
912 \r
913     # Channel modes of type A manipulate lists\r
914     #\r
915     # Example: b (banlist)\r
916     #\r
917     class ModeTypeA < Mode\r
918       attr_reader :list\r
919       def initialize(ch)\r
920         super\r
921         @list = NetmaskList.new\r
922       end\r
923 \r
924       def set(val)\r
925         nm = @channel.server.new_netmask(val)\r
926         @list << nm unless @list.include?(nm)\r
927       end\r
928 \r
929       def reset(val)\r
930         nm = @channel.server.new_netmask(val)\r
931         @list.delete(nm)\r
932       end\r
933 \r
934     end\r
935 \r
936 \r
937     # Channel modes of type B need an argument\r
938     #\r
939     # Example: k (key)\r
940     #\r
941     class ModeTypeB < Mode\r
942       def initialize(ch)\r
943         super\r
944         @arg = nil\r
945       end\r
946 \r
947       def status\r
948         @arg\r
949       end\r
950       alias :value :status\r
951 \r
952       def set(val)\r
953         @arg = val\r
954       end\r
955 \r
956       def reset(val)\r
957         @arg = nil if @arg == val\r
958       end\r
959 \r
960     end\r
961 \r
962 \r
963     # Channel modes that change the User prefixes are like\r
964     # Channel modes of type B, except that they manipulate\r
965     # lists of Users, so they are somewhat similar to channel\r
966     # modes of type A\r
967     #\r
968     class UserMode < ModeTypeB\r
969       attr_reader :list\r
970       alias :users :list\r
971       def initialize(ch)\r
972         super\r
973         @list = UserList.new\r
974       end\r
975 \r
976       def set(val)\r
977         u = @channel.server.user(val)\r
978         @list << u unless @list.include?(u)\r
979       end\r
980 \r
981       def reset(val)\r
982         u = @channel.server.user(val)\r
983         @list.delete(u)\r
984       end\r
985 \r
986     end\r
987 \r
988 \r
989     # Channel modes of type C need an argument when set,\r
990     # but not when they get reset\r
991     #\r
992     # Example: l (limit)\r
993     #\r
994     class ModeTypeC < Mode\r
995       def initialize(ch)\r
996         super\r
997         @arg = nil\r
998       end\r
999 \r
1000       def status\r
1001         @arg\r
1002       end\r
1003       alias :value :status\r
1004 \r
1005       def set(val)\r
1006         @arg = val\r
1007       end\r
1008 \r
1009       def reset\r
1010         @arg = nil\r
1011       end\r
1012 \r
1013     end\r
1014 \r
1015 \r
1016     # Channel modes of type D are basically booleans\r
1017     #\r
1018     # Example: m (moderate)\r
1019     #\r
1020     class ModeTypeD < Mode\r
1021       def initialize(ch)\r
1022         super\r
1023         @set = false\r
1024       end\r
1025 \r
1026       def set?\r
1027         return @set\r
1028       end\r
1029 \r
1030       def set\r
1031         @set = true\r
1032       end\r
1033 \r
1034       def reset\r
1035         @set = false\r
1036       end\r
1037 \r
1038     end\r
1039 \r
1040 \r
1041     # A Topic represents the topic of a channel. It consists of\r
1042     # the topic itself, who set it and when\r
1043     #\r
1044     class Topic\r
1045       attr_accessor :text, :set_by, :set_on\r
1046       alias :to_s :text\r
1047 \r
1048       # Create a new Topic setting the text, the creator and\r
1049       # the creation time\r
1050       #\r
1051       def initialize(text="", set_by="", set_on=Time.new)\r
1052         @text = text\r
1053         @set_by = set_by.to_irc_user\r
1054         @set_on = set_on\r
1055       end\r
1056 \r
1057       # Replace a Topic with another one\r
1058       #\r
1059       def replace(topic)\r
1060         raise TypeError, "#{topic.inspect} is not of class #{self.class}" unless topic.kind_of?(self.class)\r
1061         @text = topic.text.dup\r
1062         @set_by = topic.set_by.dup\r
1063         @set_on = topic.set_on.dup\r
1064       end\r
1065 \r
1066       # Returns self\r
1067       #\r
1068       def to_irc_channel_topic\r
1069         self\r
1070       end\r
1071 \r
1072     end\r
1073 \r
1074   end\r
1075 \r
1076 end\r
1077 \r
1078 \r
1079 class String\r
1080 \r
1081   # Returns an Irc::Channel::Topic with self as text\r
1082   #\r
1083   def to_irc_channel_topic\r
1084     Irc::Channel::Topic.new(self)\r
1085   end\r
1086 \r
1087 end\r
1088 \r
1089 \r
1090 module Irc\r
1091 \r
1092 \r
1093   # Here we start with the actual Channel class\r
1094   #\r
1095   class Channel\r
1096 \r
1097     include ServerOrCasemap\r
1098     attr_reader :name, :topic, :mode, :users\r
1099     alias :to_s :name\r
1100 \r
1101     def inspect\r
1102       str = "<#{self.class}:#{'0x%x' % self.object_id}:"\r
1103       str << " on server #{server}" if server\r
1104       str << " @name=#{@name.inspect} @topic=#{@topic.text.inspect}"\r
1105       str << " @users=[#{user_nicks.sort.join(', ')}]"\r
1106       str << ">"\r
1107     end\r
1108 \r
1109     # Returns self\r
1110     #\r
1111     def to_irc_channel\r
1112       self\r
1113     end\r
1114 \r
1115     # TODO Ho\r
1116     def user_nicks\r
1117       @users.map { |u| u.downcase }\r
1118     end\r
1119 \r
1120     # Checks if the receiver already has a user with the given _nick_\r
1121     #\r
1122     def has_user?(nick)\r
1123       user_nicks.index(nick.irc_downcase(casemap))\r
1124     end\r
1125 \r
1126     # Returns the user with nick _nick_, if available\r
1127     #\r
1128     def get_user(nick)\r
1129       idx = has_user?(nick)\r
1130       @users[idx] if idx\r
1131     end\r
1132 \r
1133     # Adds a user to the channel\r
1134     #\r
1135     def add_user(user, opts={})\r
1136       silent = opts.fetch(:silent, false) \r
1137       if has_user?(user) && !silent\r
1138         warn "Trying to add user #{user} to channel #{self} again"\r
1139       else\r
1140         @users << user.to_irc_user(server_and_casemap)\r
1141       end\r
1142     end\r
1143 \r
1144     # Creates a new channel with the given name, optionally setting the topic\r
1145     # and an initial users list.\r
1146     #\r
1147     # No additional info is created here, because the channel flags and userlists\r
1148     # allowed depend on the server.\r
1149     #\r
1150     def initialize(name, topic=nil, users=[], opts={})\r
1151       raise ArgumentError, "Channel name cannot be empty" if name.to_s.empty?\r
1152       warn "Unknown channel prefix #{name[0].chr}" if name !~ /^[&#+!]/\r
1153       raise ArgumentError, "Invalid character in #{name.inspect}" if name =~ /[ \x07,]/\r
1154 \r
1155       init_server_or_casemap(opts)\r
1156 \r
1157       @name = name\r
1158 \r
1159       @topic = (topic.to_irc_channel_topic rescue Channel::Topic.new)\r
1160 \r
1161       @users = UserList.new\r
1162 \r
1163       users.each { |u|\r
1164         add_user(u)\r
1165       }\r
1166 \r
1167       # Flags\r
1168       @mode = {}\r
1169     end\r
1170 \r
1171     # Removes a user from the channel\r
1172     #\r
1173     def delete_user(user)\r
1174       @mode.each { |sym, mode|\r
1175         mode.reset(user) if mode.kind_of?(UserMode)\r
1176       }\r
1177       @users.delete(user)\r
1178     end\r
1179 \r
1180     # The channel prefix\r
1181     #\r
1182     def prefix\r
1183       name[0].chr\r
1184     end\r
1185 \r
1186     # A channel is local to a server if it has the '&' prefix\r
1187     #\r
1188     def local?\r
1189       name[0] == 0x26\r
1190     end\r
1191 \r
1192     # A channel is modeless if it has the '+' prefix\r
1193     #\r
1194     def modeless?\r
1195       name[0] == 0x2b\r
1196     end\r
1197 \r
1198     # A channel is safe if it has the '!' prefix\r
1199     #\r
1200     def safe?\r
1201       name[0] == 0x21\r
1202     end\r
1203 \r
1204     # A channel is normal if it has the '#' prefix\r
1205     #\r
1206     def normal?\r
1207       name[0] == 0x23\r
1208     end\r
1209 \r
1210     # Create a new mode\r
1211     #\r
1212     def create_mode(sym, kl)\r
1213       @mode[sym.to_sym] = kl.new(self)\r
1214     end\r
1215 \r
1216   end\r
1217 \r
1218 \r
1219   # A ChannelList is an ArrayOf <code>Channel</code>s\r
1220   #\r
1221   class ChannelList < ArrayOf\r
1222 \r
1223     # Create a new ChannelList, optionally filling it with the elements from\r
1224     # the Array argument fed to it.\r
1225     #\r
1226     def initialize(ar=[])\r
1227       super(Channel, ar)\r
1228     end\r
1229 \r
1230     # Convenience method: convert the ChannelList to a list of channel names.\r
1231     # The indices are preserved\r
1232     #\r
1233     def names\r
1234       self.map { |chan| chan.name }\r
1235     end\r
1236 \r
1237   end\r
1238 \r
1239 end\r
1240 \r
1241 \r
1242 class String\r
1243 \r
1244   # We keep extending String, this time adding a method that converts a\r
1245   # String into an Irc::Channel object\r
1246   #\r
1247   def to_irc_channel(opts={})\r
1248     Irc::Channel.new(self, opts)\r
1249   end\r
1250 \r
1251 end\r
1252 \r
1253 \r
1254 module Irc\r
1255 \r
1256 \r
1257   # An IRC Server represents the Server the client is connected to.\r
1258   #\r
1259   class Server\r
1260 \r
1261     attr_reader :hostname, :version, :usermodes, :chanmodes\r
1262     alias :to_s :hostname\r
1263     attr_reader :supports, :capabilities\r
1264 \r
1265     attr_reader :channels, :users\r
1266 \r
1267     # TODO Ho\r
1268     def channel_names\r
1269       @channels.map { |ch| ch.downcase }\r
1270     end\r
1271 \r
1272     # TODO Ho\r
1273     def user_nicks\r
1274       @users.map { |u| u.downcase }\r
1275     end\r
1276 \r
1277     def inspect\r
1278       chans, users = [@channels, @users].map {|d|\r
1279         d.sort { |a, b|\r
1280           a.downcase <=> b.downcase\r
1281         }.map { |x|\r
1282           x.inspect\r
1283         }\r
1284       }\r
1285 \r
1286       str = "<#{self.class}:#{'0x%x' % self.object_id}:"\r
1287       str << " @hostname=#{hostname}"\r
1288       str << " @channels=#{chans}"\r
1289       str << " @users=#{users}"\r
1290       str << ">"\r
1291     end\r
1292 \r
1293     # Create a new Server, with all instance variables reset to nil (for\r
1294     # scalar variables), empty channel and user lists and @supports\r
1295     # initialized to the default values for all known supported features.\r
1296     #\r
1297     def initialize\r
1298       @hostname = @version = @usermodes = @chanmodes = nil\r
1299 \r
1300       @channels = ChannelList.new\r
1301 \r
1302       @users = UserList.new\r
1303 \r
1304       reset_capabilities\r
1305     end\r
1306 \r
1307     # Resets the server capabilities\r
1308     #\r
1309     def reset_capabilities\r
1310       @supports = {\r
1311         :casemapping => 'rfc1459'.to_irc_casemap,\r
1312         :chanlimit => {},\r
1313         :chanmodes => {\r
1314           :typea => nil, # Type A: address lists\r
1315           :typeb => nil, # Type B: needs a parameter\r
1316           :typec => nil, # Type C: needs a parameter when set\r
1317           :typed => nil  # Type D: must not have a parameter\r
1318         },\r
1319         :channellen => 200,\r
1320         :chantypes => "#&",\r
1321         :excepts => nil,\r
1322         :idchan => {},\r
1323         :invex => nil,\r
1324         :kicklen => nil,\r
1325         :maxlist => {},\r
1326         :modes => 3,\r
1327         :network => nil,\r
1328         :nicklen => 9,\r
1329         :prefix => {\r
1330           :modes => 'ov'.scan(/./),\r
1331           :prefixes => '@+'.scan(/./)\r
1332         },\r
1333         :safelist => nil,\r
1334         :statusmsg => nil,\r
1335         :std => nil,\r
1336         :targmax => {},\r
1337         :topiclen => nil\r
1338       }\r
1339       @capabilities = {}\r
1340     end\r
1341 \r
1342     # Resets the Channel and User list\r
1343     #\r
1344     def reset_lists\r
1345       @users.each { |u|\r
1346         delete_user(u)\r
1347       }\r
1348       @channels.each { |u|\r
1349         delete_channel(u)\r
1350       }\r
1351     end\r
1352 \r
1353     # Clears the server\r
1354     #\r
1355     def clear\r
1356       reset_lists\r
1357       reset_capabilities\r
1358     end\r
1359 \r
1360     # This method is used to parse a 004 RPL_MY_INFO line\r
1361     #\r
1362     def parse_my_info(line)\r
1363       ar = line.split(' ')\r
1364       @hostname = ar[0]\r
1365       @version = ar[1]\r
1366       @usermodes = ar[2]\r
1367       @chanmodes = ar[3]\r
1368     end\r
1369 \r
1370     def noval_warn(key, val, &block)\r
1371       if val\r
1372         yield if block_given?\r
1373       else\r
1374         warn "No #{key.to_s.upcase} value"\r
1375       end\r
1376     end\r
1377 \r
1378     def val_warn(key, val, &block)\r
1379       if val == true or val == false or val.nil?\r
1380         yield if block_given?\r
1381       else\r
1382         warn "No #{key.to_s.upcase} value must be specified, got #{val}"\r
1383       end\r
1384     end\r
1385     private :noval_warn, :val_warn\r
1386 \r
1387     # This method is used to parse a 005 RPL_ISUPPORT line\r
1388     #\r
1389     # See the RPL_ISUPPORT draft[http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt]\r
1390     #\r
1391     def parse_isupport(line)\r
1392       debug "Parsing ISUPPORT #{line.inspect}"\r
1393       ar = line.split(' ')\r
1394       reparse = ""\r
1395       ar.each { |en|\r
1396         prekey, val = en.split('=', 2)\r
1397         if prekey =~ /^-(.*)/\r
1398           key = $1.downcase.to_sym\r
1399           val = false\r
1400         else\r
1401           key = prekey.downcase.to_sym\r
1402         end\r
1403         case key\r
1404         when :casemapping\r
1405           noval_warn(key, val) {\r
1406             @supports[key] = val.to_irc_casemap\r
1407           }\r
1408         when :chanlimit, :idchan, :maxlist, :targmax\r
1409           noval_warn(key, val) {\r
1410             groups = val.split(',')\r
1411             groups.each { |g|\r
1412               k, v = g.split(':')\r
1413               @supports[key][k] = v.to_i || 0\r
1414             }\r
1415           }\r
1416         when :chanmodes\r
1417           noval_warn(key, val) {\r
1418             groups = val.split(',')\r
1419             @supports[key][:typea] = groups[0].scan(/./).map { |x| x.to_sym}\r
1420             @supports[key][:typeb] = groups[1].scan(/./).map { |x| x.to_sym}\r
1421             @supports[key][:typec] = groups[2].scan(/./).map { |x| x.to_sym}\r
1422             @supports[key][:typed] = groups[3].scan(/./).map { |x| x.to_sym}\r
1423           }\r
1424         when :channellen, :kicklen, :modes, :topiclen\r
1425           if val\r
1426             @supports[key] = val.to_i\r
1427           else\r
1428             @supports[key] = nil\r
1429           end\r
1430         when :chantypes\r
1431           @supports[key] = val # can also be nil\r
1432         when :excepts\r
1433           val ||= 'e'\r
1434           @supports[key] = val\r
1435         when :invex\r
1436           val ||= 'I'\r
1437           @supports[key] = val\r
1438         when :maxchannels\r
1439           noval_warn(key, val) {\r
1440             reparse += "CHANLIMIT=(chantypes):#{val} "\r
1441           }\r
1442         when :maxtargets\r
1443           noval_warn(key, val) {\r
1444             @supports[:targmax]['PRIVMSG'] = val.to_i\r
1445             @supports[:targmax]['NOTICE'] = val.to_i\r
1446           }\r
1447         when :network\r
1448           noval_warn(key, val) {\r
1449             @supports[key] = val\r
1450           }\r
1451         when :nicklen\r
1452           noval_warn(key, val) {\r
1453             @supports[key] = val.to_i\r
1454           }\r
1455         when :prefix\r
1456           if val\r
1457             val.scan(/\((.*)\)(.*)/) { |m, p|\r
1458               @supports[key][:modes] = m.scan(/./).map { |x| x.to_sym}\r
1459               @supports[key][:prefixes] = p.scan(/./).map { |x| x.to_sym}\r
1460             }\r
1461           else\r
1462             @supports[key][:modes] = nil\r
1463             @supports[key][:prefixes] = nil\r
1464           end\r
1465         when :safelist\r
1466           val_warn(key, val) {\r
1467             @supports[key] = val.nil? ? true : val\r
1468           }\r
1469         when :statusmsg\r
1470           noval_warn(key, val) {\r
1471             @supports[key] = val.scan(/./)\r
1472           }\r
1473         when :std\r
1474           noval_warn(key, val) {\r
1475             @supports[key] = val.split(',')\r
1476           }\r
1477         else\r
1478           @supports[key] =  val.nil? ? true : val\r
1479         end\r
1480       }\r
1481       reparse.gsub!("(chantypes)",@supports[:chantypes])\r
1482       parse_isupport(reparse) unless reparse.empty?\r
1483     end\r
1484 \r
1485     # Returns the casemap of the server.\r
1486     #\r
1487     def casemap\r
1488       @supports[:casemapping]\r
1489     end\r
1490 \r
1491     # Returns User or Channel depending on what _name_ can be\r
1492     # a name of\r
1493     #\r
1494     def user_or_channel?(name)\r
1495       if supports[:chantypes].include?(name[0])\r
1496         return Channel\r
1497       else\r
1498         return User\r
1499       end\r
1500     end\r
1501 \r
1502     # Returns the actual User or Channel object matching _name_\r
1503     #\r
1504     def user_or_channel(name)\r
1505       if supports[:chantypes].include?(name[0])\r
1506         return channel(name)\r
1507       else\r
1508         return user(name)\r
1509       end\r
1510     end\r
1511 \r
1512     # Checks if the receiver already has a channel with the given _name_\r
1513     #\r
1514     def has_channel?(name)\r
1515       return false if name.nil_or_empty?\r
1516       channel_names.index(name.irc_downcase(casemap))\r
1517     end\r
1518     alias :has_chan? :has_channel?\r
1519 \r
1520     # Returns the channel with name _name_, if available\r
1521     #\r
1522     def get_channel(name)\r
1523       return nil if name.nil_or_empty?\r
1524       idx = has_channel?(name)\r
1525       channels[idx] if idx\r
1526     end\r
1527     alias :get_chan :get_channel\r
1528 \r
1529     # Create a new Channel object bound to the receiver and add it to the\r
1530     # list of <code>Channel</code>s on the receiver, unless the channel was\r
1531     # present already. In this case, the default action is to raise an\r
1532     # exception, unless _fails_ is set to false.  An exception can also be\r
1533     # raised if _str_ is nil or empty, again only if _fails_ is set to true;\r
1534     # otherwise, the method just returns nil\r
1535     #\r
1536     def new_channel(name, topic=nil, users=[], fails=true)\r
1537       if name.nil_or_empty?\r
1538         raise "Tried to look for empty or nil channel name #{name.inspect}" if fails\r
1539         return nil\r
1540       end\r
1541       ex = get_chan(name)\r
1542       if ex\r
1543         raise "Channel #{name} already exists on server #{self}" if fails\r
1544         return ex\r
1545       else\r
1546 \r
1547         prefix = name[0].chr\r
1548 \r
1549         # Give a warning if the new Channel goes over some server limits.\r
1550         #\r
1551         # FIXME might need to raise an exception\r
1552         #\r
1553         warn "#{self} doesn't support channel prefix #{prefix}" unless @supports[:chantypes].include?(prefix)\r
1554         warn "#{self} doesn't support channel names this long (#{name.length} > #{@supports[:channellen]})" unless name.length <= @supports[:channellen]\r
1555 \r
1556         # Next, we check if we hit the limit for channels of type +prefix+\r
1557         # if the server supports +chanlimit+\r
1558         #\r
1559         @supports[:chanlimit].keys.each { |k|\r
1560           next unless k.include?(prefix)\r
1561           count = 0\r
1562           channel_names.each { |n|\r
1563             count += 1 if k.include?(n[0])\r
1564           }\r
1565           raise IndexError, "Already joined #{count} channels with prefix #{k}" if count == @supports[:chanlimit][k]\r
1566         }\r
1567 \r
1568         # So far, everything is fine. Now create the actual Channel\r
1569         #\r
1570         chan = Channel.new(name, topic, users, :server => self)\r
1571 \r
1572         # We wade through +prefix+ and +chanmodes+ to create appropriate\r
1573         # lists and flags for this channel\r
1574 \r
1575         @supports[:prefix][:modes].each { |mode|\r
1576           chan.create_mode(mode, Channel::UserMode)\r
1577         } if @supports[:prefix][:modes]\r
1578 \r
1579         @supports[:chanmodes].each { |k, val|\r
1580           if val\r
1581             case k\r
1582             when :typea\r
1583               val.each { |mode|\r
1584                 chan.create_mode(mode, Channel::ModeTypeA)\r
1585               }\r
1586             when :typeb\r
1587               val.each { |mode|\r
1588                 chan.create_mode(mode, Channel::ModeTypeB)\r
1589               }\r
1590             when :typec\r
1591               val.each { |mode|\r
1592                 chan.create_mode(mode, Channel::ModeTypeC)\r
1593               }\r
1594             when :typed\r
1595               val.each { |mode|\r
1596                 chan.create_mode(mode, Channel::ModeTypeD)\r
1597               }\r
1598             end\r
1599           end\r
1600         }\r
1601 \r
1602         @channels << chan\r
1603         # debug "Created channel #{chan.inspect}"\r
1604         return chan\r
1605       end\r
1606     end\r
1607 \r
1608     # Returns the Channel with the given _name_ on the server,\r
1609     # creating it if necessary. This is a short form for\r
1610     # new_channel(_str_, nil, [], +false+)\r
1611     #\r
1612     def channel(str)\r
1613       new_channel(str,nil,[],false)\r
1614     end\r
1615 \r
1616     # Remove Channel _name_ from the list of <code>Channel</code>s\r
1617     #\r
1618     def delete_channel(name)\r
1619       idx = has_channel?(name)\r
1620       raise "Tried to remove unmanaged channel #{name}" unless idx\r
1621       @channels.delete_at(idx)\r
1622     end\r
1623 \r
1624     # Checks if the receiver already has a user with the given _nick_\r
1625     #\r
1626     def has_user?(nick)\r
1627       return false if nick.nil_or_empty?\r
1628       user_nicks.index(nick.irc_downcase(casemap))\r
1629     end\r
1630 \r
1631     # Returns the user with nick _nick_, if available\r
1632     #\r
1633     def get_user(nick)\r
1634       idx = has_user?(nick)\r
1635       @users[idx] if idx\r
1636     end\r
1637 \r
1638     # Create a new User object bound to the receiver and add it to the list\r
1639     # of <code>User</code>s on the receiver, unless the User was present\r
1640     # already. In this case, the default action is to raise an exception,\r
1641     # unless _fails_ is set to false. An exception can also be raised\r
1642     # if _str_ is nil or empty, again only if _fails_ is set to true;\r
1643     # otherwise, the method just returns nil\r
1644     #\r
1645     def new_user(str, fails=true)\r
1646       if str.nil_or_empty?\r
1647         raise "Tried to look for empty or nil user name #{str.inspect}" if fails\r
1648         return nil\r
1649       end\r
1650       tmp = str.to_irc_user(:server => self)\r
1651       old = get_user(tmp.nick)\r
1652       # debug "Tmp: #{tmp.inspect}"\r
1653       # debug "Old: #{old.inspect}"\r
1654       if old\r
1655         # debug "User already existed as #{old.inspect}"\r
1656         if tmp.known?\r
1657           if old.known?\r
1658             # debug "Both were known"\r
1659             # Do not raise an error: things like Freenode change the hostname after identification\r
1660             warning "User #{tmp.nick} has inconsistent Netmasks! #{self} knows #{old.inspect} but access was tried with #{tmp.inspect}" if old != tmp\r
1661             raise "User #{tmp} already exists on server #{self}" if fails\r
1662           end\r
1663           if old.fullform.downcase != tmp.fullform.downcase\r
1664             old.replace(tmp)\r
1665             # debug "Known user now #{old.inspect}"\r
1666           end\r
1667         end\r
1668         return old\r
1669       else\r
1670         warn "#{self} doesn't support nicknames this long (#{tmp.nick.length} > #{@supports[:nicklen]})" unless tmp.nick.length <= @supports[:nicklen]\r
1671         @users << tmp\r
1672         return @users.last\r
1673       end\r
1674     end\r
1675 \r
1676     # Returns the User with the given Netmask on the server,\r
1677     # creating it if necessary. This is a short form for\r
1678     # new_user(_str_, +false+)\r
1679     #\r
1680     def user(str)\r
1681       new_user(str, false)\r
1682     end\r
1683 \r
1684     # Deletes User _user_ from Channel _channel_\r
1685     #\r
1686     def delete_user_from_channel(user, channel)\r
1687       channel.delete_user(user)\r
1688     end\r
1689 \r
1690     # Remove User _someuser_ from the list of <code>User</code>s.\r
1691     # _someuser_ must be specified with the full Netmask.\r
1692     #\r
1693     def delete_user(someuser)\r
1694       idx = has_user?(someuser)\r
1695       raise "Tried to remove unmanaged user #{user}" unless idx\r
1696       have = self.user(someuser)\r
1697       @channels.each { |ch|\r
1698         delete_user_from_channel(have, ch)\r
1699       }\r
1700       @users.delete_at(idx)\r
1701     end\r
1702 \r
1703     # Create a new Netmask object with the appropriate casemap\r
1704     #\r
1705     def new_netmask(str)\r
1706       str.to_irc_netmask(:server => self)\r
1707     end\r
1708 \r
1709     # Finds all <code>User</code>s on server whose Netmask matches _mask_\r
1710     #\r
1711     def find_users(mask)\r
1712       nm = new_netmask(mask)\r
1713       @users.inject(UserList.new) {\r
1714         |list, user|\r
1715         if user.user == "*" or user.host == "*"\r
1716           list << user if user.nick.irc_downcase(casemap) =~ nm.nick.irc_downcase(casemap).to_irc_regexp\r
1717         else\r
1718           list << user if user.matches?(nm)\r
1719         end\r
1720         list\r
1721       }\r
1722     end\r
1723 \r
1724   end\r
1725 \r
1726 end\r
1727 \r