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