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
12 # :title: IRC module
\r
16 # This module defines the fundamental building blocks for IRC
\r
18 # Author:: Giuseppe Bilotta (giuseppe.bilotta@gmail.com)
\r
19 # Copyright:: Copyright (c) 2006 Giuseppe Bilotta
\r
26 # We extend the Object class with a method that
\r
27 # checks if the receiver is nil or empty
\r
29 return true unless self
\r
30 return true if self.respond_to? :empty and self.empty?
\r
35 # The Irc module is used to keep all IRC-related classes
\r
36 # in the same namespace
\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
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
52 # Create a new casemap with name _name_, uppercase characters _upper_ and
\r
53 # lowercase characters _lower_
\r
55 def initialize(name, upper, lower)
\r
57 raise "Casemap #{name.inspect} already exists!" if @@casemaps.has_key?(@key)
\r
58 @@casemaps[@key] = {
\r
65 # Returns the Casemap with the given name
\r
67 def Casemap.get(name)
\r
68 @@casemaps[name.to_sym][:casemap]
\r
71 # Retrieve the 'uppercase characters' of this Casemap
\r
74 @@casemaps[@key][:upper]
\r
77 # Retrieve the 'lowercase characters' of this Casemap
\r
80 @@casemaps[@key][:lower]
\r
83 # Return a Casemap based on the receiver
\r
89 # A Casemap is represented by its lower/upper mappings
\r
92 "#<#{self.class}:#{'0x%x'% self.object_id}: #{upper.inspect} ~(#{self})~ #{lower.inspect}>"
\r
95 # As a String we return our name
\r
101 # Two Casemaps are equal if they have the same upper and lower ranges
\r
104 other = arg.to_irc_casemap
\r
105 return self.upper == other.upper && self.lower == other.lower
\r
108 # Raise an error if _arg_ and self are not the same Casemap
\r
111 other = arg.to_irc_casemap
\r
112 raise "Casemap mismatch (#{self.inspect} != #{other.inspect})" unless self == other
\r
118 # The rfc1459 casemap
\r
120 class RfcCasemap < Casemap
\r
124 super('rfc1459', "\x41-\x5e", "\x61-\x7e")
\r
128 RfcCasemap.instance
\r
130 # The strict-rfc1459 Casemap
\r
132 class StrictRfcCasemap < Casemap
\r
136 super('strict-rfc1459', "\x41-\x5d", "\x61-\x7d")
\r
140 StrictRfcCasemap.instance
\r
142 # The ascii Casemap
\r
144 class AsciiCasemap < Casemap
\r
148 super('ascii', "\x41-\x5a", "\x61-\x7a")
\r
152 AsciiCasemap.instance
\r
155 # This module is included by all classes that are either bound to a server
\r
156 # or should have a casemap.
\r
158 module ServerOrCasemap
\r
160 attr_reader :server
\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
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
169 @casemap = opts.fetch(:casemap, nil)
\r
172 @server.casemap.must_be(@casemap)
\r
176 @casemap = (@casemap || 'rfc1459').to_irc_casemap
\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
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
189 return true if cmap.nil? or cmap == casemap
\r
191 return true if srv == @server and (cmap.nil? or cmap == casemap)
\r
196 # Returns the casemap of the receiver, by looking at the bound
\r
197 # @server (if possible) or at the @casemap otherwise
\r
200 return @server.casemap if defined?(@server) and @server
\r
204 # Returns a hash with the current @server and @casemap as values of
\r
205 # :server and :casemap
\r
207 def server_and_casemap
\r
209 h[:server] = @server if defined?(@server) and @server
\r
210 h[:casemap] = @casemap if defined?(@casemap) and @casemap
\r
214 # We allow up/downcasing with a different casemap
\r
216 def irc_downcase(cmap=casemap)
\r
217 self.to_s.irc_downcase(cmap)
\r
220 # Up/downcasing something that includes this module returns its
\r
221 # Up/downcased to_s form
\r
227 # We allow up/downcasing with a different casemap
\r
229 def irc_upcase(cmap=casemap)
\r
230 self.to_s.irc_upcase(cmap)
\r
233 # Up/downcasing something that includes this module returns its
\r
234 # Up/downcased to_s form
\r
245 # We start by extending the String class
\r
246 # with some IRC-specific methods
\r
250 # This method returns the Irc::Casemap whose name is the receiver
\r
253 Irc::Casemap.get(self) rescue raise TypeError, "Unkown Irc::Casemap #{self.inspect}"
\r
256 # This method returns a string which is the downcased version of the
\r
257 # receiver, according to the given _casemap_
\r
260 def irc_downcase(casemap='rfc1459')
\r
261 cmap = casemap.to_irc_casemap
\r
262 self.tr(cmap.upper, cmap.lower)
\r
265 # This is the same as the above, except that the string is altered in place
\r
267 # See also the discussion about irc_downcase
\r
269 def irc_downcase!(casemap='rfc1459')
\r
270 cmap = casemap.to_irc_casemap
\r
271 self.tr!(cmap.upper, cmap.lower)
\r
274 # Upcasing functions are provided too
\r
276 # See also the discussion about irc_downcase
\r
278 def irc_upcase(casemap='rfc1459')
\r
279 cmap = casemap.to_irc_casemap
\r
280 self.tr(cmap.lower, cmap.upper)
\r
283 # In-place upcasing
\r
285 # See also the discussion about irc_downcase
\r
287 def irc_upcase!(casemap='rfc1459')
\r
288 cmap = casemap.to_irc_casemap
\r
289 self.tr!(cmap.lower, cmap.upper)
\r
292 # This method checks if the receiver contains IRC glob characters
\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
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
304 self =~ /^[*?]|[^\\][*?]/
\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
311 regmask = Regexp.escape(self)
\r
312 regmask.gsub!(/(\\\\)?\\[*?]/) { |m|
\r
321 raise "Unexpected match #{m} when converting #{self}"
\r
324 Regexp.new(regmask)
\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
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
338 class ArrayOf < Array
\r
340 attr_reader :element_class
\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
345 def initialize(kl, ar=[])
\r
346 raise TypeError, "#{kl.inspect} must be a class name" unless kl.kind_of?(Class)
\r
348 @element_class = kl
\r
353 raise TypeError, "#{self.class} can only be initialized from an Array"
\r
358 "#<#{self.class}[#{@element_class}]:#{'0x%x' % self.object_id}: #{super}>"
\r
361 # Private method to check the validity of the elements passed to it
\r
362 # and optionally raise an error
\r
364 # TODO should it accept nils as valid?
\r
366 def internal_will_accept?(raising, *els)
\r
368 unless el.kind_of?(@element_class)
\r
369 raise TypeError, "#{el.inspect} is not of class #{@element_class}" if raising
\r
375 private :internal_will_accept?
\r
377 # This method checks if the passed arguments are acceptable for our ArrayOf
\r
379 def will_accept?(*els)
\r
380 internal_will_accept?(false, *els)
\r
383 # This method checks that all elements are of the appropriate class
\r
386 will_accept?(*self)
\r
389 # This method is similar to the above, except that it raises an exception
\r
390 # if the receiver is not valid
\r
393 raise TypeError unless valid?
\r
396 # Overloaded from Array#<<, checks for appropriate class of argument
\r
399 super(el) if internal_will_accept?(true, el)
\r
402 # Overloaded from Array#&, checks for appropriate class of argument elements
\r
406 ArrayOf.new(@element_class, r) if internal_will_accept?(true, *r)
\r
409 # Overloaded from Array#+, checks for appropriate class of argument elements
\r
412 ArrayOf.new(@element_class, super(ar)) if internal_will_accept?(true, *ar)
\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
419 ArrayOf.new(@element_class, super(ar)) # if internal_will_accept?(true, *ar)
\r
422 # Overloaded from Array#|, checks for appropriate class of argument elements
\r
425 ArrayOf.new(@element_class, super(ar)) if internal_will_accept?(true, *ar)
\r
428 # Overloaded from Array#concat, checks for appropriate class of argument
\r
432 super(ar) if internal_will_accept?(true, *ar)
\r
435 # Overloaded from Array#insert, checks for appropriate class of argument
\r
438 def insert(idx, *ar)
\r
439 super(idx, *ar) if internal_will_accept?(true, *ar)
\r
442 # Overloaded from Array#replace, checks for appropriate class of argument
\r
446 super(ar) if (ar.kind_of?(ArrayOf) && ar.element_class <= @element_class) or internal_will_accept?(true, *ar)
\r
449 # Overloaded from Array#push, checks for appropriate class of argument
\r
453 super(*ar) if internal_will_accept?(true, *ar)
\r
456 # Overloaded from Array#unshift, checks for appropriate class of argument(s)
\r
460 super(el) if internal_will_accept?(true, *els)
\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
468 self.map { |el| el.downcase }
\r
471 # Modifying methods which we don't handle yet are made private
\r
473 private :[]=, :collect!, :map!, :fill, :flatten!
\r
478 # We extend the Regexp class with an Irc module which will contain some
\r
479 # Irc-specific regexps
\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
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
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
502 # We start with some IRC related regular expressions, used to match
\r
503 # Irc::User nicks and users and Irc::Channel names
\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
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
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
526 USER_CHAR = /[^\x00\x0a\x0d @]/
\r
527 GEN_USER = /#{USER_CHAR}+/
\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
534 GEN_HOST = /#{HOSTNAME}|#{HOSTADDR}/
\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
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
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
552 GEN_HOST_EXT = /\S+/
\r
554 # User-matching Regexp
\r
555 GEN_USER_ID = /(#{GEN_NICK})(?:(?:!(#{GEN_USER}))?@(#{GEN_HOST_EXT}))?/
\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
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
567 # # Netmask-matching Regexp
\r
568 # GEN_MASK = /(#{GEN_NICK_MASK})(?:(?:!(#{GEN_USER}))?@(#{GEN_HOST_EXT}))?/
\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
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
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
592 # Netmasks have an associated casemap unless they are bound to a server
\r
594 include ServerOrCasemap
\r
596 attr_reader :nick, :user, :host
\r
598 # Create a new Netmask from string _str_, which must be in the form
\r
599 # _nick_!_user_@_host_
\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
607 # Empty +nick+, +user+ or +host+ are converted to the generic glob pattern
\r
609 def initialize(str="", opts={})
\r
610 # First of all, check for server/casemap option
\r
612 init_server_or_casemap(opts)
\r
614 # Now we can see if the given string _str_ is an actual Netmask
\r
615 if str.respond_to?(:to_str)
\r
617 # We match a pretty generic string, to work around non-compliant
\r
619 when /^(?:(\S+?)(?:(?:!(\S+?))?@(\S+))?)?$/
\r
620 # We do assignment using our internal methods
\r
625 raise ArgumentError, "#{str.to_str.inspect} does not represent a valid #{self.class}"
\r
628 raise TypeError, "#{str} cannot be converted to a #{self.class}"
\r
632 # A Netmask is easily converted to a String for the usual representation.
\r
633 # We skip the user or host parts if they are "*", unless we've been asked
\r
634 # for the full form
\r
638 ret << "!" << user unless user == "*"
\r
639 ret << "@" << host unless host == "*"
\r
643 "#{nick}!#{user}@#{host}"
\r
646 # Converts the receiver into a Netmask with the given (optional)
\r
647 # server/casemap association. We return self unless a conversion
\r
648 # is needed (different casemap/server)
\r
650 # Subclasses of Netmask will return a new Netmask
\r
652 def to_irc_netmask(opts={})
\r
653 if self.class == Netmask
\r
654 return self if fits_with_server_and_casemap?(opts)
\r
656 return self.downcase.to_irc_netmask(opts)
\r
659 # Converts the receiver into a User with the given (optional)
\r
660 # server/casemap association. We return self unless a conversion
\r
661 # is needed (different casemap/server)
\r
663 def to_irc_user(opts={})
\r
664 self.fullform.to_irc_user(server_and_casemap.merge(opts))
\r
667 # Inspection of a Netmask reveals the server it's bound to (if there is
\r
668 # one), its casemap and the nick, user and host part
\r
671 str = "<#{self.class}:#{'0x%x' % self.object_id}:"
\r
672 str << " @server=#{@server}" if defined?(@server) and @server
\r
673 str << " @nick=#{@nick.inspect} @user=#{@user.inspect}"
\r
674 str << " @host=#{@host.inspect} casemap=#{casemap.inspect}"
\r
678 # Equality: two Netmasks are equal if they downcase to the same thing
\r
680 # TODO we may want it to try other.to_irc_netmask
\r
683 return false unless other.kind_of?(self.class)
\r
684 self.downcase == other.downcase
\r
687 # This method changes the nick of the Netmask, defaulting to the generic
\r
688 # glob pattern if the result is the null string.
\r
691 @nick = newnick.to_s
\r
692 @nick = "*" if @nick.empty?
\r
695 # This method changes the user of the Netmask, defaulting to the generic
\r
696 # glob pattern if the result is the null string.
\r
699 @user = newuser.to_s
\r
700 @user = "*" if @user.empty?
\r
703 # This method changes the hostname of the Netmask, defaulting to the generic
\r
704 # glob pattern if the result is the null string.
\r
707 @host = newhost.to_s
\r
708 @host = "*" if @host.empty?
\r
711 # We can replace everything at once with data from another Netmask
\r
719 @server = other.server
\r
720 @casemap = other.casemap unless @server
\r
722 replace(other.to_irc_netmask(server_and_casemap))
\r
726 # This method checks if a Netmask is definite or not, by seeing if
\r
727 # any of its components are defined by globs
\r
730 return @nick.has_irc_glob? || @user.has_irc_glob? || @host.has_irc_glob?
\r
733 # This method is used to match the current Netmask against another one
\r
735 # The method returns true if each component of the receiver matches the
\r
736 # corresponding component of the argument. By _matching_ here we mean
\r
737 # that any netmask described by the receiver is also described by the
\r
740 # In this sense, matching is rather simple to define in the case when the
\r
741 # receiver has no globs: it is just necessary to check if the argument
\r
742 # describes the receiver, which can be done by matching it against the
\r
743 # argument converted into an IRC Regexp (see String#to_irc_regexp).
\r
745 # The situation is also easy when the receiver has globs and the argument
\r
746 # doesn't, since in this case the result is false.
\r
748 # The more complex case in which both the receiver and the argument have
\r
749 # globs is not handled yet.
\r
752 cmp = arg.to_irc_netmask(:casemap => casemap)
\r
753 debug "Matching #{self.fullform} against #{arg.inspect} (#{cmp.fullform})"
\r
754 [:nick, :user, :host].each { |component|
\r
755 us = self.send(component).irc_downcase(casemap)
\r
756 them = cmp.send(component).irc_downcase(casemap)
\r
757 if us.has_irc_glob? && them.has_irc_glob?
\r
759 warn NotImplementedError
\r
762 return false if us.has_irc_glob? && !them.has_irc_glob?
\r
763 return false unless us =~ them.to_irc_regexp
\r
768 # Case equality. Checks if arg matches self
\r
771 arg.to_irc_netmask(:casemap => casemap).matches?(self)
\r
774 # Sorting is done via the fullform
\r
779 self.fullform.irc_downcase(casemap) <=> arg.fullform.irc_downcase(casemap)
\r
781 self.downcase <=> arg.downcase
\r
788 # A NetmaskList is an ArrayOf <code>Netmask</code>s
\r
790 class NetmaskList < ArrayOf
\r
792 # Create a new NetmaskList, optionally filling it with the elements from
\r
793 # the Array argument fed to it.
\r
795 def initialize(ar=[])
\r
799 # We enhance the [] method by allowing it to pick an element that matches
\r
800 # a given Netmask, a String or a Regexp
\r
801 # TODO take into consideration the opportunity to use select() instead of
\r
802 # find(), and/or a way to let the user choose which one to take (second
\r
806 if args.length == 1
\r
810 mask.matches?(args[0])
\r
814 mask.matches?(args[0].to_irc_netmask(:casemap => mask.casemap))
\r
818 mask.fullform =~ args[0]
\r
835 # We keep extending String, this time adding a method that converts a
\r
836 # String into an Irc::Netmask object
\r
838 def to_irc_netmask(opts={})
\r
839 Irc::Netmask.new(self, opts)
\r
848 # An IRC User is identified by his/her Netmask (which must not have globs).
\r
849 # In fact, User is just a subclass of Netmask.
\r
851 # Ideally, the user and host information of an IRC User should never
\r
852 # change, and it shouldn't contain glob patterns. However, IRC is somewhat
\r
853 # idiosincratic and it may be possible to know the nick of a User much before
\r
854 # its user and host are known. Moreover, some networks (namely Freenode) may
\r
855 # change the hostname of a User when (s)he identifies with Nickserv.
\r
857 # As a consequence, we must allow changes to a User host and user attributes.
\r
858 # We impose a restriction, though: they may not contain glob patterns, except
\r
859 # for the special case of an unknown user/host which is represented by a *.
\r
861 # It is possible to create a totally unknown User (e.g. for initializations)
\r
862 # by setting the nick to * too.
\r
865 # * see if it's worth to add the other USER data
\r
866 # * see if it's worth to add NICKSERV status
\r
868 class User < Netmask
\r
871 # Create a new IRC User from a given Netmask (or anything that can be converted
\r
872 # into a Netmask) provided that the given Netmask does not have globs.
\r
874 def initialize(str="", opts={})
\r
876 raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if nick.has_irc_glob? && nick != "*"
\r
877 raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if user.has_irc_glob? && user != "*"
\r
878 raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if host.has_irc_glob? && host != "*"
\r
882 # The nick of a User may be changed freely, but it must not contain glob patterns.
\r
885 raise "Can't change the nick to #{newnick}" if defined?(@nick) and newnick.has_irc_glob?
\r
889 # We have to allow changing the user of an Irc User due to some networks
\r
890 # (e.g. Freenode) changing hostmasks on the fly. We still check if the new
\r
891 # user data has glob patterns though.
\r
894 raise "Can't change the username to #{newuser}" if defined?(@user) and newuser.has_irc_glob?
\r
898 # We have to allow changing the host of an Irc User due to some networks
\r
899 # (e.g. Freenode) changing hostmasks on the fly. We still check if the new
\r
900 # host data has glob patterns though.
\r
903 raise "Can't change the hostname to #{newhost}" if defined?(@host) and newhost.has_irc_glob?
\r
907 # Checks if a User is well-known or not by looking at the hostname and user
\r
910 return nick != "*" && user != "*" && host != "*"
\r
913 # Is the user away?
\r
919 # Set the away status of the user. Use away=(nil) or away=(false)
\r
930 # Users can be either simply downcased (their nick only)
\r
931 # or fully downcased: this will return the fullform downcased
\r
932 # according to the given casemap.
\r
934 def full_irc_downcase(cmap=casemap)
\r
935 self.fullform.irc_downcase(cmap)
\r
938 # full_downcase() will return the fullform downcased according to the
\r
939 # User's own casemap
\r
942 self.full_irc_downcase
\r
945 # Since to_irc_user runs the same checks on server and channel as
\r
946 # to_irc_netmask, we just try that and return self if it works.
\r
948 # Subclasses of User will return self if possible.
\r
950 def to_irc_user(opts={})
\r
951 return self if fits_with_server_and_casemap?(opts)
\r
952 return self.full_downcase.to_irc_user(opts)
\r
955 # We can replace everything at once with data from another User
\r
960 self.nick = other.nick
\r
961 self.user = other.user
\r
962 self.host = other.host
\r
963 @server = other.server
\r
964 @casemap = other.casemap unless @server
\r
965 @away = other.away?
\r
967 self.replace(other.to_irc_user(server_and_casemap))
\r
974 # A UserList is an ArrayOf <code>User</code>s
\r
975 # We derive it from NetmaskList, which allows us to inherit any special
\r
976 # NetmaskList method
\r
978 class UserList < NetmaskList
\r
980 # Create a new UserList, optionally filling it with the elements from
\r
981 # the Array argument fed to it.
\r
983 def initialize(ar=[])
\r
985 @element_class = User
\r
988 # Convenience method: convert the UserList to a list of nicks. The indices
\r
992 self.map { |user| user.nick }
\r
1001 # We keep extending String, this time adding a method that converts a
\r
1002 # String into an Irc::User object
\r
1004 def to_irc_user(opts={})
\r
1005 Irc::User.new(self, opts)
\r
1012 # An IRC Channel is identified by its name, and it has a set of properties:
\r
1013 # * a Channel::Topic
\r
1015 # * a set of Channel::Modes
\r
1017 # The Channel::Topic and Channel::Mode classes are defined within the
\r
1018 # Channel namespace because they only make sense there
\r
1023 # Mode on a Channel
\r
1026 attr_reader :channel
\r
1027 def initialize(ch)
\r
1034 # Channel modes of type A manipulate lists
\r
1036 # Example: b (banlist)
\r
1038 class ModeTypeA < Mode
\r
1040 def initialize(ch)
\r
1042 @list = NetmaskList.new
\r
1046 nm = @channel.server.new_netmask(val)
\r
1047 @list << nm unless @list.include?(nm)
\r
1051 nm = @channel.server.new_netmask(val)
\r
1058 # Channel modes of type B need an argument
\r
1060 # Example: k (key)
\r
1062 class ModeTypeB < Mode
\r
1063 def initialize(ch)
\r
1071 alias :value :status
\r
1078 @arg = nil if @arg == val
\r
1084 # Channel modes that change the User prefixes are like
\r
1085 # Channel modes of type B, except that they manipulate
\r
1086 # lists of Users, so they are somewhat similar to channel
\r
1089 class UserMode < ModeTypeB
\r
1091 alias :users :list
\r
1092 def initialize(ch)
\r
1094 @list = UserList.new
\r
1098 u = @channel.server.user(val)
\r
1099 @list << u unless @list.include?(u)
\r
1103 u = @channel.server.user(val)
\r
1110 # Channel modes of type C need an argument when set,
\r
1111 # but not when they get reset
\r
1113 # Example: l (limit)
\r
1115 class ModeTypeC < Mode
\r
1116 def initialize(ch)
\r
1124 alias :value :status
\r
1137 # Channel modes of type D are basically booleans
\r
1139 # Example: m (moderate)
\r
1141 class ModeTypeD < Mode
\r
1142 def initialize(ch)
\r
1162 # A Topic represents the topic of a channel. It consists of
\r
1163 # the topic itself, who set it and when
\r
1166 attr_accessor :text, :set_by, :set_on
\r
1169 # Create a new Topic setting the text, the creator and
\r
1170 # the creation time
\r
1172 def initialize(text="", set_by="", set_on=Time.new)
\r
1174 @set_by = set_by.to_irc_netmask
\r
1178 # Replace a Topic with another one
\r
1180 def replace(topic)
\r
1181 raise TypeError, "#{topic.inspect} is not of class #{self.class}" unless topic.kind_of?(self.class)
\r
1182 @text = topic.text.dup
\r
1183 @set_by = topic.set_by.dup
\r
1184 @set_on = topic.set_on.dup
\r
1189 def to_irc_channel_topic
\r
1202 # Returns an Irc::Channel::Topic with self as text
\r
1204 def to_irc_channel_topic
\r
1205 Irc::Channel::Topic.new(self)
\r
1214 # Here we start with the actual Channel class
\r
1218 include ServerOrCasemap
\r
1219 attr_reader :name, :topic, :mode, :users
\r
1223 str = "<#{self.class}:#{'0x%x' % self.object_id}:"
\r
1224 str << " on server #{server}" if server
\r
1225 str << " @name=#{@name.inspect} @topic=#{@topic.text.inspect}"
\r
1226 str << " @users=[#{user_nicks.sort.join(', ')}]"
\r
1232 def to_irc_channel
\r
1238 @users.map { |u| u.downcase }
\r
1241 # Checks if the receiver already has a user with the given _nick_
\r
1243 def has_user?(nick)
\r
1244 user_nicks.index(nick.irc_downcase(casemap))
\r
1247 # Returns the user with nick _nick_, if available
\r
1249 def get_user(nick)
\r
1250 idx = has_user?(nick)
\r
1251 @users[idx] if idx
\r
1254 # Adds a user to the channel
\r
1256 def add_user(user, opts={})
\r
1257 silent = opts.fetch(:silent, false)
\r
1258 if has_user?(user) && !silent
\r
1259 warn "Trying to add user #{user} to channel #{self} again"
\r
1261 @users << user.to_irc_user(server_and_casemap)
\r
1265 # Creates a new channel with the given name, optionally setting the topic
\r
1266 # and an initial users list.
\r
1268 # No additional info is created here, because the channel flags and userlists
\r
1269 # allowed depend on the server.
\r
1271 def initialize(name, topic=nil, users=[], opts={})
\r
1272 raise ArgumentError, "Channel name cannot be empty" if name.to_s.empty?
\r
1273 warn "Unknown channel prefix #{name[0].chr}" if name !~ /^[&#+!]/
\r
1274 raise ArgumentError, "Invalid character in #{name.inspect}" if name =~ /[ \x07,]/
\r
1276 init_server_or_casemap(opts)
\r
1280 @topic = (topic.to_irc_channel_topic rescue Channel::Topic.new)
\r
1282 @users = UserList.new
\r
1292 # Removes a user from the channel
\r
1294 def delete_user(user)
\r
1295 @mode.each { |sym, mode|
\r
1296 mode.reset(user) if mode.kind_of?(UserMode)
\r
1298 @users.delete(user)
\r
1301 # The channel prefix
\r
1307 # A channel is local to a server if it has the '&' prefix
\r
1313 # A channel is modeless if it has the '+' prefix
\r
1319 # A channel is safe if it has the '!' prefix
\r
1325 # A channel is normal if it has the '#' prefix
\r
1331 # Create a new mode
\r
1333 def create_mode(sym, kl)
\r
1334 @mode[sym.to_sym] = kl.new(self)
\r
1340 # A ChannelList is an ArrayOf <code>Channel</code>s
\r
1342 class ChannelList < ArrayOf
\r
1344 # Create a new ChannelList, optionally filling it with the elements from
\r
1345 # the Array argument fed to it.
\r
1347 def initialize(ar=[])
\r
1348 super(Channel, ar)
\r
1351 # Convenience method: convert the ChannelList to a list of channel names.
\r
1352 # The indices are preserved
\r
1355 self.map { |chan| chan.name }
\r
1365 # We keep extending String, this time adding a method that converts a
\r
1366 # String into an Irc::Channel object
\r
1368 def to_irc_channel(opts={})
\r
1369 Irc::Channel.new(self, opts)
\r
1378 # An IRC Server represents the Server the client is connected to.
\r
1382 attr_reader :hostname, :version, :usermodes, :chanmodes
\r
1383 alias :to_s :hostname
\r
1384 attr_reader :supports, :capabilities
\r
1386 attr_reader :channels, :users
\r
1390 @channels.map { |ch| ch.downcase }
\r
1395 @users.map { |u| u.downcase }
\r
1399 chans, users = [@channels, @users].map {|d|
\r
1401 a.downcase <=> b.downcase
\r
1407 str = "<#{self.class}:#{'0x%x' % self.object_id}:"
\r
1408 str << " @hostname=#{hostname}"
\r
1409 str << " @channels=#{chans}"
\r
1410 str << " @users=#{users}"
\r
1414 # Create a new Server, with all instance variables reset to nil (for
\r
1415 # scalar variables), empty channel and user lists and @supports
\r
1416 # initialized to the default values for all known supported features.
\r
1419 @hostname = @version = @usermodes = @chanmodes = nil
\r
1421 @channels = ChannelList.new
\r
1423 @users = UserList.new
\r
1425 reset_capabilities
\r
1428 # Resets the server capabilities
\r
1430 def reset_capabilities
\r
1432 :casemapping => 'rfc1459'.to_irc_casemap,
\r
1435 :typea => nil, # Type A: address lists
\r
1436 :typeb => nil, # Type B: needs a parameter
\r
1437 :typec => nil, # Type C: needs a parameter when set
\r
1438 :typed => nil # Type D: must not have a parameter
\r
1440 :channellen => 50,
\r
1441 :chantypes => "#&!+",
\r
1451 :modes => [:o, :v],
\r
1452 :prefixes => [:"@", :+]
\r
1455 :statusmsg => nil,
\r
1460 @capabilities = {}
\r
1463 # Resets the Channel and User list
\r
1466 @users.reverse_each { |u|
\r
1469 @channels.reverse_each { |u|
\r
1474 # Clears the server
\r
1478 reset_capabilities
\r
1479 @hostname = @version = @usermodes = @chanmodes = nil
\r
1482 # This method is used to parse a 004 RPL_MY_INFO line
\r
1484 def parse_my_info(line)
\r
1485 ar = line.split(' ')
\r
1488 @usermodes = ar[2]
\r
1489 @chanmodes = ar[3]
\r
1492 def noval_warn(key, val, &block)
\r
1494 yield if block_given?
\r
1496 warn "No #{key.to_s.upcase} value"
\r
1500 def val_warn(key, val, &block)
\r
1501 if val == true or val == false or val.nil?
\r
1502 yield if block_given?
\r
1504 warn "No #{key.to_s.upcase} value must be specified, got #{val}"
\r
1507 private :noval_warn, :val_warn
\r
1509 # This method is used to parse a 005 RPL_ISUPPORT line
\r
1511 # See the RPL_ISUPPORT draft[http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt]
\r
1513 def parse_isupport(line)
\r
1514 debug "Parsing ISUPPORT #{line.inspect}"
\r
1515 ar = line.split(' ')
\r
1518 prekey, val = en.split('=', 2)
\r
1519 if prekey =~ /^-(.*)/
\r
1520 key = $1.downcase.to_sym
\r
1523 key = prekey.downcase.to_sym
\r
1527 noval_warn(key, val) {
\r
1528 @supports[key] = val.to_irc_casemap
\r
1530 when :chanlimit, :idchan, :maxlist, :targmax
\r
1531 noval_warn(key, val) {
\r
1532 groups = val.split(',')
\r
1534 k, v = g.split(':')
\r
1535 @supports[key][k] = v.to_i || 0
\r
1536 if @supports[key][k] == 0
\r
1537 warn "Deleting #{key} limit of 0 for #{k}"
\r
1538 @supports[key].delete(k)
\r
1543 noval_warn(key, val) {
\r
1544 groups = val.split(',')
\r
1545 @supports[key][:typea] = groups[0].scan(/./).map { |x| x.to_sym}
\r
1546 @supports[key][:typeb] = groups[1].scan(/./).map { |x| x.to_sym}
\r
1547 @supports[key][:typec] = groups[2].scan(/./).map { |x| x.to_sym}
\r
1548 @supports[key][:typed] = groups[3].scan(/./).map { |x| x.to_sym}
\r
1550 when :channellen, :kicklen, :modes, :topiclen
\r
1552 @supports[key] = val.to_i
\r
1554 @supports[key] = nil
\r
1557 @supports[key] = val # can also be nil
\r
1560 @supports[key] = val
\r
1563 @supports[key] = val
\r
1565 noval_warn(key, val) {
\r
1566 reparse += "CHANLIMIT=(chantypes):#{val} "
\r
1569 noval_warn(key, val) {
\r
1570 @supports[:targmax]['PRIVMSG'] = val.to_i
\r
1571 @supports[:targmax]['NOTICE'] = val.to_i
\r
1574 noval_warn(key, val) {
\r
1575 @supports[key] = val
\r
1578 noval_warn(key, val) {
\r
1579 @supports[key] = val.to_i
\r
1583 val.scan(/\((.*)\)(.*)/) { |m, p|
\r
1584 @supports[key][:modes] = m.scan(/./).map { |x| x.to_sym}
\r
1585 @supports[key][:prefixes] = p.scan(/./).map { |x| x.to_sym}
\r
1588 @supports[key][:modes] = nil
\r
1589 @supports[key][:prefixes] = nil
\r
1592 val_warn(key, val) {
\r
1593 @supports[key] = val.nil? ? true : val
\r
1596 noval_warn(key, val) {
\r
1597 @supports[key] = val.scan(/./)
\r
1600 noval_warn(key, val) {
\r
1601 @supports[key] = val.split(',')
\r
1604 @supports[key] = val.nil? ? true : val
\r
1607 reparse.gsub!("(chantypes)",@supports[:chantypes])
\r
1608 parse_isupport(reparse) unless reparse.empty?
\r
1611 # Returns the casemap of the server.
\r
1614 @supports[:casemapping]
\r
1617 # Returns User or Channel depending on what _name_ can be
\r
1620 def user_or_channel?(name)
\r
1621 if supports[:chantypes].include?(name[0])
\r
1628 # Returns the actual User or Channel object matching _name_
\r
1630 def user_or_channel(name)
\r
1631 if supports[:chantypes].include?(name[0])
\r
1632 return channel(name)
\r
1638 # Checks if the receiver already has a channel with the given _name_
\r
1640 def has_channel?(name)
\r
1641 return false if name.nil_or_empty?
\r
1642 channel_names.index(name.irc_downcase(casemap))
\r
1644 alias :has_chan? :has_channel?
\r
1646 # Returns the channel with name _name_, if available
\r
1648 def get_channel(name)
\r
1649 return nil if name.nil_or_empty?
\r
1650 idx = has_channel?(name)
\r
1651 channels[idx] if idx
\r
1653 alias :get_chan :get_channel
\r
1655 # Create a new Channel object bound to the receiver and add it to the
\r
1656 # list of <code>Channel</code>s on the receiver, unless the channel was
\r
1657 # present already. In this case, the default action is to raise an
\r
1658 # exception, unless _fails_ is set to false. An exception can also be
\r
1659 # raised if _str_ is nil or empty, again only if _fails_ is set to true;
\r
1660 # otherwise, the method just returns nil
\r
1662 def new_channel(name, topic=nil, users=[], fails=true)
\r
1663 if name.nil_or_empty?
\r
1664 raise "Tried to look for empty or nil channel name #{name.inspect}" if fails
\r
1667 ex = get_chan(name)
\r
1669 raise "Channel #{name} already exists on server #{self}" if fails
\r
1673 prefix = name[0].chr
\r
1675 # Give a warning if the new Channel goes over some server limits.
\r
1677 # FIXME might need to raise an exception
\r
1679 warn "#{self} doesn't support channel prefix #{prefix}" unless @supports[:chantypes].include?(prefix)
\r
1680 warn "#{self} doesn't support channel names this long (#{name.length} > #{@supports[:channellen]})" unless name.length <= @supports[:channellen]
\r
1682 # Next, we check if we hit the limit for channels of type +prefix+
\r
1683 # if the server supports +chanlimit+
\r
1685 @supports[:chanlimit].keys.each { |k|
\r
1686 next unless k.include?(prefix)
\r
1688 channel_names.each { |n|
\r
1689 count += 1 if k.include?(n[0])
\r
1691 # raise IndexError, "Already joined #{count} channels with prefix #{k}" if count == @supports[:chanlimit][k]
\r
1692 warn "Already joined #{count}/#{@supports[:chanlimit][k]} channels with prefix #{k}, we may be going over server limits" if count >= @supports[:chanlimit][k]
\r
1695 # So far, everything is fine. Now create the actual Channel
\r
1697 chan = Channel.new(name, topic, users, :server => self)
\r
1699 # We wade through +prefix+ and +chanmodes+ to create appropriate
\r
1700 # lists and flags for this channel
\r
1702 @supports[:prefix][:modes].each { |mode|
\r
1703 chan.create_mode(mode, Channel::UserMode)
\r
1704 } if @supports[:prefix][:modes]
\r
1706 @supports[:chanmodes].each { |k, val|
\r
1711 chan.create_mode(mode, Channel::ModeTypeA)
\r
1715 chan.create_mode(mode, Channel::ModeTypeB)
\r
1719 chan.create_mode(mode, Channel::ModeTypeC)
\r
1723 chan.create_mode(mode, Channel::ModeTypeD)
\r
1730 # debug "Created channel #{chan.inspect}"
\r
1735 # Returns the Channel with the given _name_ on the server,
\r
1736 # creating it if necessary. This is a short form for
\r
1737 # new_channel(_str_, nil, [], +false+)
\r
1740 new_channel(str,nil,[],false)
\r
1743 # Remove Channel _name_ from the list of <code>Channel</code>s
\r
1745 def delete_channel(name)
\r
1746 idx = has_channel?(name)
\r
1747 raise "Tried to remove unmanaged channel #{name}" unless idx
\r
1748 @channels.delete_at(idx)
\r
1751 # Checks if the receiver already has a user with the given _nick_
\r
1753 def has_user?(nick)
\r
1754 return false if nick.nil_or_empty?
\r
1755 user_nicks.index(nick.irc_downcase(casemap))
\r
1758 # Returns the user with nick _nick_, if available
\r
1760 def get_user(nick)
\r
1761 idx = has_user?(nick)
\r
1762 @users[idx] if idx
\r
1765 # Create a new User object bound to the receiver and add it to the list
\r
1766 # of <code>User</code>s on the receiver, unless the User was present
\r
1767 # already. In this case, the default action is to raise an exception,
\r
1768 # unless _fails_ is set to false. An exception can also be raised
\r
1769 # if _str_ is nil or empty, again only if _fails_ is set to true;
\r
1770 # otherwise, the method just returns nil
\r
1772 def new_user(str, fails=true)
\r
1773 if str.nil_or_empty?
\r
1774 raise "Tried to look for empty or nil user name #{str.inspect}" if fails
\r
1777 tmp = str.to_irc_user(:server => self)
\r
1778 old = get_user(tmp.nick)
\r
1779 # debug "Tmp: #{tmp.inspect}"
\r
1780 # debug "Old: #{old.inspect}"
\r
1782 # debug "User already existed as #{old.inspect}"
\r
1785 # debug "Both were known"
\r
1786 # Do not raise an error: things like Freenode change the hostname after identification
\r
1787 warning "User #{tmp.nick} has inconsistent Netmasks! #{self} knows #{old.inspect} but access was tried with #{tmp.inspect}" if old != tmp
\r
1788 raise "User #{tmp} already exists on server #{self}" if fails
\r
1790 if old.fullform.downcase != tmp.fullform.downcase
\r
1792 # debug "Known user now #{old.inspect}"
\r
1797 warn "#{self} doesn't support nicknames this long (#{tmp.nick.length} > #{@supports[:nicklen]})" unless tmp.nick.length <= @supports[:nicklen]
\r
1799 return @users.last
\r
1803 # Returns the User with the given Netmask on the server,
\r
1804 # creating it if necessary. This is a short form for
\r
1805 # new_user(_str_, +false+)
\r
1808 new_user(str, false)
\r
1811 # Deletes User _user_ from Channel _channel_
\r
1813 def delete_user_from_channel(user, channel)
\r
1814 channel.delete_user(user)
\r
1817 # Remove User _someuser_ from the list of <code>User</code>s.
\r
1818 # _someuser_ must be specified with the full Netmask.
\r
1820 def delete_user(someuser)
\r
1821 idx = has_user?(someuser)
\r
1822 raise "Tried to remove unmanaged user #{user}" unless idx
\r
1823 have = self.user(someuser)
\r
1824 @channels.each { |ch|
\r
1825 delete_user_from_channel(have, ch)
\r
1827 @users.delete_at(idx)
\r
1830 # Create a new Netmask object with the appropriate casemap
\r
1832 def new_netmask(str)
\r
1833 str.to_irc_netmask(:server => self)
\r
1836 # Finds all <code>User</code>s on server whose Netmask matches _mask_
\r
1838 def find_users(mask)
\r
1839 nm = new_netmask(mask)
\r
1840 @users.inject(UserList.new) {
\r
1842 if user.user == "*" or user.host == "*"
\r
1843 list << user if user.nick.irc_downcase(casemap) =~ nm.nick.irc_downcase(casemap).to_irc_regexp
\r
1845 list << user if user.matches?(nm)
\r