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