New IRC Framework: NetmaskList now have an enhanced [] that allows retrieval by Netma...
[rbot] / 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   # Modifying methods which we don't handle yet are made private\r
465   #\r
466   private :[]=, :collect!, :map!, :fill, :flatten!\r
467 \r
468 end\r
469 \r
470 \r
471 module Irc\r
472 \r
473 \r
474   # A Netmask identifies each user by collecting its nick, username and\r
475   # hostname in the form <tt>nick!user@host</tt>\r
476   #\r
477   # Netmasks can also contain glob patterns in any of their components; in\r
478   # this form they are used to refer to more than a user or to a user\r
479   # appearing under different forms.\r
480   #\r
481   # Example:\r
482   # * <tt>*!*@*</tt> refers to everybody\r
483   # * <tt>*!someuser@somehost</tt> refers to user +someuser+ on host +somehost+\r
484   #   regardless of the nick used.\r
485   #\r
486   class Netmask\r
487 \r
488     # Netmasks have an associated casemap unless they are bound to a server\r
489     #\r
490     include ServerOrCasemap\r
491 \r
492     attr_reader :nick, :user, :host\r
493 \r
494     # Create a new Netmask from string _str_, which must be in the form\r
495     # _nick_!_user_@_host_\r
496     #\r
497     # It is possible to specify a server or a casemap in the optional Hash:\r
498     # these are used to associate the Netmask with the given server and to set\r
499     # its casemap: if a server is specified and a casemap is not, the server's\r
500     # casemap is used. If both a server and a casemap are specified, the\r
501     # casemap must match the server's casemap or an exception will be raised.\r
502     #\r
503     # Empty +nick+, +user+ or +host+ are converted to the generic glob pattern\r
504     #\r
505     def initialize(str="", opts={})\r
506       # First of all, check for server/casemap option\r
507       #\r
508       init_server_or_casemap(opts)\r
509 \r
510       # Now we can see if the given string _str_ is an actual Netmask\r
511       if str.respond_to?(:to_str)\r
512         case str.to_str\r
513         when /^(?:(\S+?)(?:!(\S+)@(?:(\S+))?)?)?$/\r
514           # We do assignment using our internal methods\r
515           self.nick = $1\r
516           self.user = $2\r
517           self.host = $3\r
518         else\r
519           raise ArgumentError, "#{str.to_str.inspect} does not represent a valid #{self.class}"\r
520         end\r
521       else\r
522         raise TypeError, "#{str} cannot be converted to a #{self.class}"\r
523       end\r
524     end\r
525 \r
526     # A Netmask is easily converted to a String for the usual representation\r
527     #\r
528     def fullform\r
529       "#{nick}!#{user}@#{host}"\r
530     end\r
531     alias :to_s :fullform\r
532 \r
533     # Converts the receiver into a Netmask with the given (optional)\r
534     # server/casemap association. We return self unless a conversion\r
535     # is needed (different casemap/server)\r
536     #\r
537     # Subclasses of Netmask will return a new Netmask\r
538     #\r
539     def to_irc_netmask(opts={})\r
540       if self.class == Netmask\r
541         return self if fits_with_server_and_casemap?(opts)\r
542       end\r
543       return self.fullform.to_irc_netmask(server_and_casemap.merge(opts))\r
544     end\r
545 \r
546     # Converts the receiver into a User with the given (optional)\r
547     # server/casemap association. We return self unless a conversion\r
548     # is needed (different casemap/server)\r
549     #\r
550     def to_irc_user(opts={})\r
551       self.fullform.to_irc_user(server_and_casemap.merge(opts))\r
552     end\r
553 \r
554     # Inspection of a Netmask reveals the server it's bound to (if there is\r
555     # one), its casemap and the nick, user and host part\r
556     #\r
557     def inspect\r
558       str = "<#{self.class}:#{'0x%x' % self.object_id}:"\r
559       str << " @server=#{@server}" if defined?(@server) and @server\r
560       str << " @nick=#{@nick.inspect} @user=#{@user.inspect}"\r
561       str << " @host=#{@host.inspect} casemap=#{casemap.inspect}"\r
562       str << ">"\r
563     end\r
564 \r
565     # Equality: two Netmasks are equal if they downcase to the same thing\r
566     #\r
567     # TODO we may want it to try other.to_irc_netmask\r
568     #\r
569     def ==(other)\r
570       return false unless other.kind_of?(self.class)\r
571       self.downcase == other.downcase\r
572     end\r
573 \r
574     # This method changes the nick of the Netmask, defaulting to the generic\r
575     # glob pattern if the result is the null string.\r
576     #\r
577     def nick=(newnick)\r
578       @nick = newnick.to_s\r
579       @nick = "*" if @nick.empty?\r
580     end\r
581 \r
582     # This method changes the user of the Netmask, defaulting to the generic\r
583     # glob pattern if the result is the null string.\r
584     #\r
585     def user=(newuser)\r
586       @user = newuser.to_s\r
587       @user = "*" if @user.empty?\r
588     end\r
589 \r
590     # This method changes the hostname of the Netmask, defaulting to the generic\r
591     # glob pattern if the result is the null string.\r
592     #\r
593     def host=(newhost)\r
594       @host = newhost.to_s\r
595       @host = "*" if @host.empty?\r
596     end\r
597 \r
598     # We can replace everything at once with data from another Netmask\r
599     #\r
600     def replace(other)\r
601       case other\r
602       when Netmask\r
603         nick = other.nick\r
604         user = other.user\r
605         host = other.host\r
606         @server = other.server\r
607         @casemap = other.casemap unless @server\r
608       else\r
609         replace(other.to_irc_netmask(server_and_casemap))\r
610       end\r
611     end\r
612 \r
613     # This method checks if a Netmask is definite or not, by seeing if\r
614     # any of its components are defined by globs\r
615     #\r
616     def has_irc_glob?\r
617       return @nick.has_irc_glob? || @user.has_irc_glob? || @host.has_irc_glob?\r
618     end\r
619 \r
620     # This method is used to match the current Netmask against another one\r
621     #\r
622     # The method returns true if each component of the receiver matches the\r
623     # corresponding component of the argument. By _matching_ here we mean\r
624     # that any netmask described by the receiver is also described by the\r
625     # argument.\r
626     #\r
627     # In this sense, matching is rather simple to define in the case when the\r
628     # receiver has no globs: it is just necessary to check if the argument\r
629     # describes the receiver, which can be done by matching it against the\r
630     # argument converted into an IRC Regexp (see String#to_irc_regexp).\r
631     #\r
632     # The situation is also easy when the receiver has globs and the argument\r
633     # doesn't, since in this case the result is false.\r
634     #\r
635     # The more complex case in which both the receiver and the argument have\r
636     # globs is not handled yet.\r
637     #\r
638     def matches?(arg)\r
639       cmp = arg.to_irc_netmask(:casemap => casemap)\r
640       debug "Matching #{self.fullform} against #{arg.fullform}"\r
641       [:nick, :user, :host].each { |component|\r
642         us = self.send(component).irc_downcase(casemap)\r
643         them = cmp.send(component).irc_downcase(casemap)\r
644         if us.has_irc_glob? && them.has_irc_glob?\r
645           next if us == them\r
646           warn NotImplementedError\r
647           return false\r
648         end\r
649         return false if us.has_irc_glob? && !them.has_irc_glob?\r
650         return false unless us =~ them.to_irc_regexp\r
651       }\r
652       return true\r
653     end\r
654 \r
655     # Case equality. Checks if arg matches self\r
656     #\r
657     def ===(arg)\r
658       arg.to_irc_netmask(:casemap => casemap).matches?(self)\r
659     end\r
660 \r
661     # Sorting is done via the fullform\r
662     #\r
663     def <=>(arg)\r
664       case arg\r
665       when Netmask\r
666         self.fullform.irc_downcase(casemap) <=> arg.fullform.irc_downcase(casemap)\r
667       else\r
668         self.downcase <=> arg.downcase\r
669       end\r
670     end\r
671 \r
672   end\r
673 \r
674 \r
675   # A NetmaskList is an ArrayOf <code>Netmask</code>s\r
676   #\r
677   class NetmaskList < ArrayOf\r
678 \r
679     # Create a new NetmaskList, optionally filling it with the elements from\r
680     # the Array argument fed to it.\r
681     #\r
682     def initialize(ar=[])\r
683       super(Netmask, ar)\r
684     end\r
685 \r
686     # We enhance the [] method by allowing it to pick an element that matches\r
687     # a given Netmask or String\r
688     #\r
689     def [](*args)\r
690       if args.length == 1\r
691         case args[0]\r
692         when Netmask\r
693           self.find { |mask|\r
694             mask.matches?(args[0])\r
695           }\r
696         when String\r
697           self.find { |mask|\r
698             mask.matches?(args[0].to_irc_netmask(:casemap => mask.casemap))\r
699           }\r
700         else\r
701           super(*args)\r
702         end\r
703       else\r
704         super(*args)\r
705       end\r
706     end\r
707 \r
708   end\r
709 \r
710 end\r
711 \r
712 \r
713 class String\r
714 \r
715   # We keep extending String, this time adding a method that converts a\r
716   # String into an Irc::Netmask object\r
717   #\r
718   def to_irc_netmask(opts={})\r
719     Irc::Netmask.new(self, opts)\r
720   end\r
721 \r
722 end\r
723 \r
724 \r
725 module Irc\r
726 \r
727 \r
728   # An IRC User is identified by his/her Netmask (which must not have globs).\r
729   # In fact, User is just a subclass of Netmask.\r
730   #\r
731   # Ideally, the user and host information of an IRC User should never\r
732   # change, and it shouldn't contain glob patterns. However, IRC is somewhat\r
733   # idiosincratic and it may be possible to know the nick of a User much before\r
734   # its user and host are known. Moreover, some networks (namely Freenode) may\r
735   # change the hostname of a User when (s)he identifies with Nickserv.\r
736   #\r
737   # As a consequence, we must allow changes to a User host and user attributes.\r
738   # We impose a restriction, though: they may not contain glob patterns, except\r
739   # for the special case of an unknown user/host which is represented by a *.\r
740   #\r
741   # It is possible to create a totally unknown User (e.g. for initializations)\r
742   # by setting the nick to * too.\r
743   #\r
744   # TODO list:\r
745   # * see if it's worth to add the other USER data\r
746   # * see if it's worth to add NICKSERV status\r
747   #\r
748   class User < Netmask\r
749     alias :to_s :nick\r
750 \r
751     # Create a new IRC User from a given Netmask (or anything that can be converted\r
752     # into a Netmask) provided that the given Netmask does not have globs.\r
753     #\r
754     def initialize(str="", opts={})\r
755       super\r
756       raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if nick.has_irc_glob? && nick != "*"\r
757       raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if user.has_irc_glob? && user != "*"\r
758       raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if host.has_irc_glob? && host != "*"\r
759       @away = false\r
760     end\r
761 \r
762     # The nick of a User may be changed freely, but it must not contain glob patterns.\r
763     #\r
764     def nick=(newnick)\r
765       raise "Can't change the nick to #{newnick}" if defined?(@nick) and newnick.has_irc_glob?\r
766       super\r
767     end\r
768 \r
769     # We have to allow changing the user of an Irc User due to some networks\r
770     # (e.g. Freenode) changing hostmasks on the fly. We still check if the new\r
771     # user data has glob patterns though.\r
772     #\r
773     def user=(newuser)\r
774       raise "Can't change the username to #{newuser}" if defined?(@user) and newuser.has_irc_glob?\r
775       super\r
776     end\r
777 \r
778     # We have to allow changing the host of an Irc User due to some networks\r
779     # (e.g. Freenode) changing hostmasks on the fly. We still check if the new\r
780     # host data has glob patterns though.\r
781     #\r
782     def host=(newhost)\r
783       raise "Can't change the hostname to #{newhost}" if defined?(@host) and newhost.has_irc_glob?\r
784       super\r
785     end\r
786 \r
787     # Checks if a User is well-known or not by looking at the hostname and user\r
788     #\r
789     def known?\r
790       return nick!= "*" && user!="*" && host!="*"\r
791     end\r
792 \r
793     # Is the user away?\r
794     #\r
795     def away?\r
796       return @away\r
797     end\r
798 \r
799     # Set the away status of the user. Use away=(nil) or away=(false)\r
800     # to unset away\r
801     #\r
802     def away=(msg="")\r
803       if msg\r
804         @away = msg\r
805       else\r
806         @away = false\r
807       end\r
808     end\r
809 \r
810     # Since to_irc_user runs the same checks on server and channel as\r
811     # to_irc_netmask, we just try that and return self if it works.\r
812     #\r
813     # Subclasses of User will return self if possible.\r
814     #\r
815     def to_irc_user(opts={})\r
816       return self if fits_with_server_and_casemap?(opts)\r
817       return self.fullform.to_irc_user(server_and_casemap(opts))\r
818     end\r
819 \r
820     # We can replace everything at once with data from another User\r
821     #\r
822     def replace(other)\r
823       case other\r
824       when User\r
825         self.nick = other.nick\r
826         self.user = other.user\r
827         self.host = other.host\r
828         @server = other.server\r
829         @casemap = other.casemap unless @server\r
830         @away = other.away?\r
831       else\r
832         self.replace(other.to_irc_user(server_and_casemap))\r
833       end\r
834     end\r
835 \r
836   end\r
837 \r
838 \r
839   # A UserList is an ArrayOf <code>User</code>s\r
840   # We derive it from NetmaskList, which allows us to inherit any special\r
841   # NetmaskList method\r
842   #\r
843   class UserList < NetmaskList\r
844 \r
845     # Create a new UserList, optionally filling it with the elements from\r
846     # the Array argument fed to it.\r
847     #\r
848     def initialize(ar=[])\r
849       super(ar)\r
850       @element_class = User\r
851     end\r
852 \r
853   end\r
854 \r
855 end\r
856 \r
857 class String\r
858 \r
859   # We keep extending String, this time adding a method that converts a\r
860   # String into an Irc::User object\r
861   #\r
862   def to_irc_user(opts={})\r
863     Irc::User.new(self, opts)\r
864   end\r
865 \r
866 end\r
867 \r
868 module Irc\r
869 \r
870   # An IRC Channel is identified by its name, and it has a set of properties:\r
871   # * a Channel::Topic\r
872   # * a UserList\r
873   # * a set of Channel::Modes\r
874   #\r
875   # The Channel::Topic and Channel::Mode classes are defined within the\r
876   # Channel namespace because they only make sense there\r
877   #\r
878   class Channel\r
879 \r
880 \r
881     # Mode on a Channel\r
882     #\r
883     class Mode\r
884       attr_reader :channel\r
885       def initialize(ch)\r
886         @channel = ch\r
887       end\r
888 \r
889     end\r
890 \r
891 \r
892     # Channel modes of type A manipulate lists\r
893     #\r
894     # Example: b (banlist)\r
895     #\r
896     class ModeTypeA < Mode\r
897       attr_reader :list\r
898       def initialize(ch)\r
899         super\r
900         @list = NetmaskList.new\r
901       end\r
902 \r
903       def set(val)\r
904         nm = @channel.server.new_netmask(val)\r
905         @list << nm unless @list.include?(nm)\r
906       end\r
907 \r
908       def reset(val)\r
909         nm = @channel.server.new_netmask(val)\r
910         @list.delete(nm)\r
911       end\r
912 \r
913     end\r
914 \r
915 \r
916     # Channel modes of type B need an argument\r
917     #\r
918     # Example: k (key)\r
919     #\r
920     class ModeTypeB < Mode\r
921       def initialize(ch)\r
922         super\r
923         @arg = nil\r
924       end\r
925 \r
926       def status\r
927         @arg\r
928       end\r
929       alias :value :status\r
930 \r
931       def set(val)\r
932         @arg = val\r
933       end\r
934 \r
935       def reset(val)\r
936         @arg = nil if @arg == val\r
937       end\r
938 \r
939     end\r
940 \r
941 \r
942     # Channel modes that change the User prefixes are like\r
943     # Channel modes of type B, except that they manipulate\r
944     # lists of Users, so they are somewhat similar to channel\r
945     # modes of type A\r
946     #\r
947     class UserMode < ModeTypeB\r
948       attr_reader :list\r
949       alias :users :list\r
950       def initialize(ch)\r
951         super\r
952         @list = UserList.new\r
953       end\r
954 \r
955       def set(val)\r
956         u = @channel.server.user(val)\r
957         @list << u unless @list.include?(u)\r
958       end\r
959 \r
960       def reset(val)\r
961         u = @channel.server.user(val)\r
962         @list.delete(u)\r
963       end\r
964 \r
965     end\r
966 \r
967 \r
968     # Channel modes of type C need an argument when set,\r
969     # but not when they get reset\r
970     #\r
971     # Example: l (limit)\r
972     #\r
973     class ModeTypeC < Mode\r
974       def initialize(ch)\r
975         super\r
976         @arg = nil\r
977       end\r
978 \r
979       def status\r
980         @arg\r
981       end\r
982       alias :value :status\r
983 \r
984       def set(val)\r
985         @arg = val\r
986       end\r
987 \r
988       def reset\r
989         @arg = nil\r
990       end\r
991 \r
992     end\r
993 \r
994 \r
995     # Channel modes of type D are basically booleans\r
996     #\r
997     # Example: m (moderate)\r
998     #\r
999     class ModeTypeD < Mode\r
1000       def initialize(ch)\r
1001         super\r
1002         @set = false\r
1003       end\r
1004 \r
1005       def set?\r
1006         return @set\r
1007       end\r
1008 \r
1009       def set\r
1010         @set = true\r
1011       end\r
1012 \r
1013       def reset\r
1014         @set = false\r
1015       end\r
1016 \r
1017     end\r
1018 \r
1019 \r
1020     # A Topic represents the topic of a channel. It consists of\r
1021     # the topic itself, who set it and when\r
1022     #\r
1023     class Topic\r
1024       attr_accessor :text, :set_by, :set_on\r
1025       alias :to_s :text\r
1026 \r
1027       # Create a new Topic setting the text, the creator and\r
1028       # the creation time\r
1029       #\r
1030       def initialize(text="", set_by="", set_on=Time.new)\r
1031         @text = text\r
1032         @set_by = set_by.to_irc_user\r
1033         @set_on = set_on\r
1034       end\r
1035 \r
1036       # Replace a Topic with another one\r
1037       #\r
1038       def replace(topic)\r
1039         raise TypeError, "#{topic.inspect} is not of class #{self.class}" unless topic.kind_of?(self.class)\r
1040         @text = topic.text.dup\r
1041         @set_by = topic.set_by.dup\r
1042         @set_on = topic.set_on.dup\r
1043       end\r
1044 \r
1045       # Returns self\r
1046       #\r
1047       def to_irc_channel_topic\r
1048         self\r
1049       end\r
1050 \r
1051     end\r
1052 \r
1053   end\r
1054 \r
1055 end\r
1056 \r
1057 \r
1058 class String\r
1059 \r
1060   # Returns an Irc::Channel::Topic with self as text\r
1061   #\r
1062   def to_irc_channel_topic\r
1063     Irc::Channel::Topic.new(self)\r
1064   end\r
1065 \r
1066 end\r
1067 \r
1068 \r
1069 module Irc\r
1070 \r
1071 \r
1072   # Here we start with the actual Channel class\r
1073   #\r
1074   class Channel\r
1075 \r
1076     include ServerOrCasemap\r
1077     attr_reader :name, :topic, :mode, :users\r
1078     alias :to_s :name\r
1079 \r
1080     def inspect\r
1081       str = "<#{self.class}:#{'0x%x' % self.object_id}:"\r
1082       str << " on server #{server}" if server\r
1083       str << " @name=#{@name.inspect} @topic=#{@topic.text.inspect}"\r
1084       str << " @users=[#{user_nicks.sort.join(', ')}]"\r
1085       str << ">"\r
1086     end\r
1087 \r
1088     # Returns self\r
1089     #\r
1090     def to_irc_channel\r
1091       self\r
1092     end\r
1093 \r
1094     # TODO Ho\r
1095     def user_nicks\r
1096       @users.map { |u| u.downcase }\r
1097     end\r
1098 \r
1099     # Checks if the receiver already has a user with the given _nick_\r
1100     #\r
1101     def has_user?(nick)\r
1102       user_nicks.index(nick.irc_downcase(casemap))\r
1103     end\r
1104 \r
1105     # Returns the user with nick _nick_, if available\r
1106     #\r
1107     def get_user(nick)\r
1108       idx = has_user?(nick)\r
1109       @users[idx] if idx\r
1110     end\r
1111 \r
1112     # Adds a user to the channel\r
1113     #\r
1114     def add_user(user, opts={})\r
1115       silent = opts.fetch(:silent, false) \r
1116       if has_user?(user) && !silent\r
1117         warn "Trying to add user #{user} to channel #{self} again"\r
1118       else\r
1119         @users << user.to_irc_user(server_and_casemap)\r
1120       end\r
1121     end\r
1122 \r
1123     # Creates a new channel with the given name, optionally setting the topic\r
1124     # and an initial users list.\r
1125     #\r
1126     # No additional info is created here, because the channel flags and userlists\r
1127     # allowed depend on the server.\r
1128     #\r
1129     def initialize(name, topic=nil, users=[], opts={})\r
1130       raise ArgumentError, "Channel name cannot be empty" if name.to_s.empty?\r
1131       warn "Unknown channel prefix #{name[0].chr}" if name !~ /^[&#+!]/\r
1132       raise ArgumentError, "Invalid character in #{name.inspect}" if name =~ /[ \x07,]/\r
1133 \r
1134       init_server_or_casemap(opts)\r
1135 \r
1136       @name = name\r
1137 \r
1138       @topic = (topic.to_irc_channel_topic rescue Channel::Topic.new)\r
1139 \r
1140       @users = UserList.new\r
1141 \r
1142       users.each { |u|\r
1143         add_user(u)\r
1144       }\r
1145 \r
1146       # Flags\r
1147       @mode = {}\r
1148     end\r
1149 \r
1150     # Removes a user from the channel\r
1151     #\r
1152     def delete_user(user)\r
1153       @mode.each { |sym, mode|\r
1154         mode.reset(user) if mode.kind_of?(UserMode)\r
1155       }\r
1156       @users.delete(user)\r
1157     end\r
1158 \r
1159     # The channel prefix\r
1160     #\r
1161     def prefix\r
1162       name[0].chr\r
1163     end\r
1164 \r
1165     # A channel is local to a server if it has the '&' prefix\r
1166     #\r
1167     def local?\r
1168       name[0] == 0x26\r
1169     end\r
1170 \r
1171     # A channel is modeless if it has the '+' prefix\r
1172     #\r
1173     def modeless?\r
1174       name[0] == 0x2b\r
1175     end\r
1176 \r
1177     # A channel is safe if it has the '!' prefix\r
1178     #\r
1179     def safe?\r
1180       name[0] == 0x21\r
1181     end\r
1182 \r
1183     # A channel is normal if it has the '#' prefix\r
1184     #\r
1185     def normal?\r
1186       name[0] == 0x23\r
1187     end\r
1188 \r
1189     # Create a new mode\r
1190     #\r
1191     def create_mode(sym, kl)\r
1192       @mode[sym.to_sym] = kl.new(self)\r
1193     end\r
1194 \r
1195   end\r
1196 \r
1197 \r
1198   # A ChannelList is an ArrayOf <code>Channel</code>s\r
1199   #\r
1200   class ChannelList < ArrayOf\r
1201 \r
1202     # Create a new ChannelList, optionally filling it with the elements from\r
1203     # the Array argument fed to it.\r
1204     #\r
1205     def initialize(ar=[])\r
1206       super(Channel, ar)\r
1207     end\r
1208 \r
1209   end\r
1210 \r
1211 end\r
1212 \r
1213 \r
1214 class String\r
1215 \r
1216   # We keep extending String, this time adding a method that converts a\r
1217   # String into an Irc::Channel object\r
1218   #\r
1219   def to_irc_channel(opts={})\r
1220     Irc::Channel.new(self, opts)\r
1221   end\r
1222 \r
1223 end\r
1224 \r
1225 \r
1226 module Irc\r
1227 \r
1228 \r
1229   # An IRC Server represents the Server the client is connected to.\r
1230   #\r
1231   class Server\r
1232 \r
1233     attr_reader :hostname, :version, :usermodes, :chanmodes\r
1234     alias :to_s :hostname\r
1235     attr_reader :supports, :capabilities\r
1236 \r
1237     attr_reader :channels, :users\r
1238 \r
1239     # TODO Ho\r
1240     def channel_names\r
1241       @channels.map { |ch| ch.downcase }\r
1242     end\r
1243 \r
1244     # TODO Ho\r
1245     def user_nicks\r
1246       @users.map { |u| u.downcase }\r
1247     end\r
1248 \r
1249     def inspect\r
1250       chans, users = [@channels, @users].map {|d|\r
1251         d.sort { |a, b|\r
1252           a.downcase <=> b.downcase\r
1253         }.map { |x|\r
1254           x.inspect\r
1255         }\r
1256       }\r
1257 \r
1258       str = "<#{self.class}:#{'0x%x' % self.object_id}:"\r
1259       str << " @hostname=#{hostname}"\r
1260       str << " @channels=#{chans}"\r
1261       str << " @users=#{users}"\r
1262       str << ">"\r
1263     end\r
1264 \r
1265     # Create a new Server, with all instance variables reset to nil (for\r
1266     # scalar variables), empty channel and user lists and @supports\r
1267     # initialized to the default values for all known supported features.\r
1268     #\r
1269     def initialize\r
1270       @hostname = @version = @usermodes = @chanmodes = nil\r
1271 \r
1272       @channels = ChannelList.new\r
1273 \r
1274       @users = UserList.new\r
1275 \r
1276       reset_capabilities\r
1277     end\r
1278 \r
1279     # Resets the server capabilities\r
1280     #\r
1281     def reset_capabilities\r
1282       @supports = {\r
1283         :casemapping => 'rfc1459'.to_irc_casemap,\r
1284         :chanlimit => {},\r
1285         :chanmodes => {\r
1286           :typea => nil, # Type A: address lists\r
1287           :typeb => nil, # Type B: needs a parameter\r
1288           :typec => nil, # Type C: needs a parameter when set\r
1289           :typed => nil  # Type D: must not have a parameter\r
1290         },\r
1291         :channellen => 200,\r
1292         :chantypes => "#&",\r
1293         :excepts => nil,\r
1294         :idchan => {},\r
1295         :invex => nil,\r
1296         :kicklen => nil,\r
1297         :maxlist => {},\r
1298         :modes => 3,\r
1299         :network => nil,\r
1300         :nicklen => 9,\r
1301         :prefix => {\r
1302           :modes => 'ov'.scan(/./),\r
1303           :prefixes => '@+'.scan(/./)\r
1304         },\r
1305         :safelist => nil,\r
1306         :statusmsg => nil,\r
1307         :std => nil,\r
1308         :targmax => {},\r
1309         :topiclen => nil\r
1310       }\r
1311       @capabilities = {}\r
1312     end\r
1313 \r
1314     # Resets the Channel and User list\r
1315     #\r
1316     def reset_lists\r
1317       @users.each { |u|\r
1318         delete_user(u)\r
1319       }\r
1320       @channels.each { |u|\r
1321         delete_channel(u)\r
1322       }\r
1323     end\r
1324 \r
1325     # Clears the server\r
1326     #\r
1327     def clear\r
1328       reset_lists\r
1329       reset_capabilities\r
1330     end\r
1331 \r
1332     # This method is used to parse a 004 RPL_MY_INFO line\r
1333     #\r
1334     def parse_my_info(line)\r
1335       ar = line.split(' ')\r
1336       @hostname = ar[0]\r
1337       @version = ar[1]\r
1338       @usermodes = ar[2]\r
1339       @chanmodes = ar[3]\r
1340     end\r
1341 \r
1342     def noval_warn(key, val, &block)\r
1343       if val\r
1344         yield if block_given?\r
1345       else\r
1346         warn "No #{key.to_s.upcase} value"\r
1347       end\r
1348     end\r
1349 \r
1350     def val_warn(key, val, &block)\r
1351       if val == true or val == false or val.nil?\r
1352         yield if block_given?\r
1353       else\r
1354         warn "No #{key.to_s.upcase} value must be specified, got #{val}"\r
1355       end\r
1356     end\r
1357     private :noval_warn, :val_warn\r
1358 \r
1359     # This method is used to parse a 005 RPL_ISUPPORT line\r
1360     #\r
1361     # See the RPL_ISUPPORT draft[http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt]\r
1362     #\r
1363     def parse_isupport(line)\r
1364       debug "Parsing ISUPPORT #{line.inspect}"\r
1365       ar = line.split(' ')\r
1366       reparse = ""\r
1367       ar.each { |en|\r
1368         prekey, val = en.split('=', 2)\r
1369         if prekey =~ /^-(.*)/\r
1370           key = $1.downcase.to_sym\r
1371           val = false\r
1372         else\r
1373           key = prekey.downcase.to_sym\r
1374         end\r
1375         case key\r
1376         when :casemapping\r
1377           noval_warn(key, val) {\r
1378             @supports[key] = val.to_irc_casemap\r
1379           }\r
1380         when :chanlimit, :idchan, :maxlist, :targmax\r
1381           noval_warn(key, val) {\r
1382             groups = val.split(',')\r
1383             groups.each { |g|\r
1384               k, v = g.split(':')\r
1385               @supports[key][k] = v.to_i || 0\r
1386             }\r
1387           }\r
1388         when :chanmodes\r
1389           noval_warn(key, val) {\r
1390             groups = val.split(',')\r
1391             @supports[key][:typea] = groups[0].scan(/./).map { |x| x.to_sym}\r
1392             @supports[key][:typeb] = groups[1].scan(/./).map { |x| x.to_sym}\r
1393             @supports[key][:typec] = groups[2].scan(/./).map { |x| x.to_sym}\r
1394             @supports[key][:typed] = groups[3].scan(/./).map { |x| x.to_sym}\r
1395           }\r
1396         when :channellen, :kicklen, :modes, :topiclen\r
1397           if val\r
1398             @supports[key] = val.to_i\r
1399           else\r
1400             @supports[key] = nil\r
1401           end\r
1402         when :chantypes\r
1403           @supports[key] = val # can also be nil\r
1404         when :excepts\r
1405           val ||= 'e'\r
1406           @supports[key] = val\r
1407         when :invex\r
1408           val ||= 'I'\r
1409           @supports[key] = val\r
1410         when :maxchannels\r
1411           noval_warn(key, val) {\r
1412             reparse += "CHANLIMIT=(chantypes):#{val} "\r
1413           }\r
1414         when :maxtargets\r
1415           noval_warn(key, val) {\r
1416             @supports[:targmax]['PRIVMSG'] = val.to_i\r
1417             @supports[:targmax]['NOTICE'] = val.to_i\r
1418           }\r
1419         when :network\r
1420           noval_warn(key, val) {\r
1421             @supports[key] = val\r
1422           }\r
1423         when :nicklen\r
1424           noval_warn(key, val) {\r
1425             @supports[key] = val.to_i\r
1426           }\r
1427         when :prefix\r
1428           if val\r
1429             val.scan(/\((.*)\)(.*)/) { |m, p|\r
1430               @supports[key][:modes] = m.scan(/./).map { |x| x.to_sym}\r
1431               @supports[key][:prefixes] = p.scan(/./).map { |x| x.to_sym}\r
1432             }\r
1433           else\r
1434             @supports[key][:modes] = nil\r
1435             @supports[key][:prefixes] = nil\r
1436           end\r
1437         when :safelist\r
1438           val_warn(key, val) {\r
1439             @supports[key] = val.nil? ? true : val\r
1440           }\r
1441         when :statusmsg\r
1442           noval_warn(key, val) {\r
1443             @supports[key] = val.scan(/./)\r
1444           }\r
1445         when :std\r
1446           noval_warn(key, val) {\r
1447             @supports[key] = val.split(',')\r
1448           }\r
1449         else\r
1450           @supports[key] =  val.nil? ? true : val\r
1451         end\r
1452       }\r
1453       reparse.gsub!("(chantypes)",@supports[:chantypes])\r
1454       parse_isupport(reparse) unless reparse.empty?\r
1455     end\r
1456 \r
1457     # Returns the casemap of the server.\r
1458     #\r
1459     def casemap\r
1460       @supports[:casemapping]\r
1461     end\r
1462 \r
1463     # Returns User or Channel depending on what _name_ can be\r
1464     # a name of\r
1465     #\r
1466     def user_or_channel?(name)\r
1467       if supports[:chantypes].include?(name[0])\r
1468         return Channel\r
1469       else\r
1470         return User\r
1471       end\r
1472     end\r
1473 \r
1474     # Returns the actual User or Channel object matching _name_\r
1475     #\r
1476     def user_or_channel(name)\r
1477       if supports[:chantypes].include?(name[0])\r
1478         return channel(name)\r
1479       else\r
1480         return user(name)\r
1481       end\r
1482     end\r
1483 \r
1484     # Checks if the receiver already has a channel with the given _name_\r
1485     #\r
1486     def has_channel?(name)\r
1487       return false if name.nil_or_empty?\r
1488       channel_names.index(name.irc_downcase(casemap))\r
1489     end\r
1490     alias :has_chan? :has_channel?\r
1491 \r
1492     # Returns the channel with name _name_, if available\r
1493     #\r
1494     def get_channel(name)\r
1495       return nil if name.nil_or_empty?\r
1496       idx = has_channel?(name)\r
1497       channels[idx] if idx\r
1498     end\r
1499     alias :get_chan :get_channel\r
1500 \r
1501     # Create a new Channel object bound to the receiver and add it to the\r
1502     # list of <code>Channel</code>s on the receiver, unless the channel was\r
1503     # present already. In this case, the default action is to raise an\r
1504     # exception, unless _fails_ is set to false.  An exception can also be\r
1505     # raised if _str_ is nil or empty, again only if _fails_ is set to true;\r
1506     # otherwise, the method just returns nil\r
1507     #\r
1508     def new_channel(name, topic=nil, users=[], fails=true)\r
1509       if name.nil_or_empty?\r
1510         raise "Tried to look for empty or nil channel name #{name.inspect}" if fails\r
1511         return nil\r
1512       end\r
1513       ex = get_chan(name)\r
1514       if ex\r
1515         raise "Channel #{name} already exists on server #{self}" if fails\r
1516         return ex\r
1517       else\r
1518 \r
1519         prefix = name[0].chr\r
1520 \r
1521         # Give a warning if the new Channel goes over some server limits.\r
1522         #\r
1523         # FIXME might need to raise an exception\r
1524         #\r
1525         warn "#{self} doesn't support channel prefix #{prefix}" unless @supports[:chantypes].include?(prefix)\r
1526         warn "#{self} doesn't support channel names this long (#{name.length} > #{@supports[:channellen]})" unless name.length <= @supports[:channellen]\r
1527 \r
1528         # Next, we check if we hit the limit for channels of type +prefix+\r
1529         # if the server supports +chanlimit+\r
1530         #\r
1531         @supports[:chanlimit].keys.each { |k|\r
1532           next unless k.include?(prefix)\r
1533           count = 0\r
1534           channel_names.each { |n|\r
1535             count += 1 if k.include?(n[0])\r
1536           }\r
1537           raise IndexError, "Already joined #{count} channels with prefix #{k}" if count == @supports[:chanlimit][k]\r
1538         }\r
1539 \r
1540         # So far, everything is fine. Now create the actual Channel\r
1541         #\r
1542         chan = Channel.new(name, topic, users, :server => self)\r
1543 \r
1544         # We wade through +prefix+ and +chanmodes+ to create appropriate\r
1545         # lists and flags for this channel\r
1546 \r
1547         @supports[:prefix][:modes].each { |mode|\r
1548           chan.create_mode(mode, Channel::UserMode)\r
1549         } if @supports[:prefix][:modes]\r
1550 \r
1551         @supports[:chanmodes].each { |k, val|\r
1552           if val\r
1553             case k\r
1554             when :typea\r
1555               val.each { |mode|\r
1556                 chan.create_mode(mode, Channel::ModeTypeA)\r
1557               }\r
1558             when :typeb\r
1559               val.each { |mode|\r
1560                 chan.create_mode(mode, Channel::ModeTypeB)\r
1561               }\r
1562             when :typec\r
1563               val.each { |mode|\r
1564                 chan.create_mode(mode, Channel::ModeTypeC)\r
1565               }\r
1566             when :typed\r
1567               val.each { |mode|\r
1568                 chan.create_mode(mode, Channel::ModeTypeD)\r
1569               }\r
1570             end\r
1571           end\r
1572         }\r
1573 \r
1574         @channels << chan\r
1575         # debug "Created channel #{chan.inspect}"\r
1576         return chan\r
1577       end\r
1578     end\r
1579 \r
1580     # Returns the Channel with the given _name_ on the server,\r
1581     # creating it if necessary. This is a short form for\r
1582     # new_channel(_str_, nil, [], +false+)\r
1583     #\r
1584     def channel(str)\r
1585       new_channel(str,nil,[],false)\r
1586     end\r
1587 \r
1588     # Remove Channel _name_ from the list of <code>Channel</code>s\r
1589     #\r
1590     def delete_channel(name)\r
1591       idx = has_channel?(name)\r
1592       raise "Tried to remove unmanaged channel #{name}" unless idx\r
1593       @channels.delete_at(idx)\r
1594     end\r
1595 \r
1596     # Checks if the receiver already has a user with the given _nick_\r
1597     #\r
1598     def has_user?(nick)\r
1599       return false if nick.nil_or_empty?\r
1600       user_nicks.index(nick.irc_downcase(casemap))\r
1601     end\r
1602 \r
1603     # Returns the user with nick _nick_, if available\r
1604     #\r
1605     def get_user(nick)\r
1606       idx = has_user?(nick)\r
1607       @users[idx] if idx\r
1608     end\r
1609 \r
1610     # Create a new User object bound to the receiver and add it to the list\r
1611     # of <code>User</code>s on the receiver, unless the User was present\r
1612     # already. In this case, the default action is to raise an exception,\r
1613     # unless _fails_ is set to false. An exception can also be raised\r
1614     # if _str_ is nil or empty, again only if _fails_ is set to true;\r
1615     # otherwise, the method just returns nil\r
1616     #\r
1617     def new_user(str, fails=true)\r
1618       if str.nil_or_empty?\r
1619         raise "Tried to look for empty or nil user name #{str.inspect}" if fails\r
1620         return nil\r
1621       end\r
1622       tmp = str.to_irc_user(:server => self)\r
1623       old = get_user(tmp.nick)\r
1624       # debug "Tmp: #{tmp.inspect}"\r
1625       # debug "Old: #{old.inspect}"\r
1626       if old\r
1627         # debug "User already existed as #{old.inspect}"\r
1628         if tmp.known?\r
1629           if old.known?\r
1630             # debug "Both were known"\r
1631             # Do not raise an error: things like Freenode change the hostname after identification\r
1632             warning "User #{tmp.nick} has inconsistent Netmasks! #{self} knows #{old.inspect} but access was tried with #{tmp.inspect}" if old != tmp\r
1633             raise "User #{tmp} already exists on server #{self}" if fails\r
1634           end\r
1635           if old.fullform.downcase != tmp.fullform.downcase\r
1636             old.replace(tmp)\r
1637             # debug "Known user now #{old.inspect}"\r
1638           end\r
1639         end\r
1640         return old\r
1641       else\r
1642         warn "#{self} doesn't support nicknames this long (#{tmp.nick.length} > #{@supports[:nicklen]})" unless tmp.nick.length <= @supports[:nicklen]\r
1643         @users << tmp\r
1644         return @users.last\r
1645       end\r
1646     end\r
1647 \r
1648     # Returns the User with the given Netmask on the server,\r
1649     # creating it if necessary. This is a short form for\r
1650     # new_user(_str_, +false+)\r
1651     #\r
1652     def user(str)\r
1653       new_user(str, false)\r
1654     end\r
1655 \r
1656     # Deletes User _user_ from Channel _channel_\r
1657     #\r
1658     def delete_user_from_channel(user, channel)\r
1659       channel.delete_user(user)\r
1660     end\r
1661 \r
1662     # Remove User _someuser_ from the list of <code>User</code>s.\r
1663     # _someuser_ must be specified with the full Netmask.\r
1664     #\r
1665     def delete_user(someuser)\r
1666       idx = has_user?(someuser)\r
1667       raise "Tried to remove unmanaged user #{user}" unless idx\r
1668       have = self.user(someuser)\r
1669       @channels.each { |ch|\r
1670         delete_user_from_channel(have, ch)\r
1671       }\r
1672       @users.delete_at(idx)\r
1673     end\r
1674 \r
1675     # Create a new Netmask object with the appropriate casemap\r
1676     #\r
1677     def new_netmask(str)\r
1678       str.to_irc_netmask(:server => self)\r
1679     end\r
1680 \r
1681     # Finds all <code>User</code>s on server whose Netmask matches _mask_\r
1682     #\r
1683     def find_users(mask)\r
1684       nm = new_netmask(mask)\r
1685       @users.inject(UserList.new) {\r
1686         |list, user|\r
1687         if user.user == "*" or user.host == "*"\r
1688           list << user if user.nick.irc_downcase(casemap) =~ nm.nick.irc_downcase(casemap).to_irc_regexp\r
1689         else\r
1690           list << user if user.matches?(nm)\r
1691         end\r
1692         list\r
1693       }\r
1694     end\r
1695 \r
1696   end\r
1697 \r
1698 end\r
1699 \r