3 # * do we want to handle a Channel list for each User telling which
4 # Channels is the User on (of those the client is on too)?
5 # We may want this so that when a User leaves all Channels and he hasn't
6 # sent us privmsgs, we know we can remove him from the Server @users list
7 # * Maybe ChannelList and UserList should be HashesOf instead of ArrayOf?
8 # See items marked as TODO Ho.
9 # The framework to do this is now in place, thanks to the new [] method
10 # for NetmaskList, which allows retrieval by Netmask or String
16 # This module defines the fundamental building blocks for IRC
18 # Author:: Giuseppe Bilotta (giuseppe.bilotta@gmail.com)
19 # Copyright:: Copyright (c) 2006 Giuseppe Bilotta
26 # We extend the Object class with a method that
27 # checks if the receiver is nil or empty
29 return true unless self
30 return true if self.respond_to? :empty? and self.empty?
34 # We alias the to_s method to __to_s__ to make
35 # it accessible in all classes
39 # The Irc module is used to keep all IRC-related classes
40 # in the same namespace
45 # Due to its Scandinavian origins, IRC has strange case mappings, which
46 # consider the characters <tt>{}|^</tt> as the uppercase
47 # equivalents of # <tt>[]\~</tt>.
49 # This is however not the same on all IRC servers: some use standard ASCII
50 # casemapping, other do not consider <tt>^</tt> as the uppercase of
56 # Create a new casemap with name _name_, uppercase characters _upper_ and
57 # lowercase characters _lower_
59 def initialize(name, upper, lower)
61 raise "Casemap #{name.inspect} already exists!" if @@casemaps.has_key?(@key)
69 # Returns the Casemap with the given name
72 @@casemaps[name.to_sym][:casemap]
75 # Retrieve the 'uppercase characters' of this Casemap
78 @@casemaps[@key][:upper]
81 # Retrieve the 'lowercase characters' of this Casemap
84 @@casemaps[@key][:lower]
87 # Return a Casemap based on the receiver
93 # A Casemap is represented by its lower/upper mappings
96 self.__to_s__[0..-2] + " #{upper.inspect} ~(#{self})~ #{lower.inspect}>"
99 # As a String we return our name
105 # Two Casemaps are equal if they have the same upper and lower ranges
108 other = arg.to_irc_casemap
109 return self.upper == other.upper && self.lower == other.lower
112 # Give a warning if _arg_ and self are not the same Casemap
115 other = arg.to_irc_casemap
119 warn "Casemap mismatch (#{self.inspect} != #{other.inspect})"
126 # The rfc1459 casemap
128 class RfcCasemap < Casemap
132 super('rfc1459', "\x41-\x5e", "\x61-\x7e")
138 # The strict-rfc1459 Casemap
140 class StrictRfcCasemap < Casemap
144 super('strict-rfc1459', "\x41-\x5d", "\x61-\x7d")
148 StrictRfcCasemap.instance
152 class AsciiCasemap < Casemap
156 super('ascii', "\x41-\x5a", "\x61-\x7a")
160 AsciiCasemap.instance
163 # This module is included by all classes that are either bound to a server
164 # or should have a casemap.
166 module ServerOrCasemap
170 # This method initializes the instance variables @server and @casemap
171 # according to the values of the hash keys :server and :casemap in _opts_
173 def init_server_or_casemap(opts={})
174 @server = opts.fetch(:server, nil)
175 raise TypeError, "#{@server} is not a valid Irc::Server" if @server and not @server.kind_of?(Server)
177 @casemap = opts.fetch(:casemap, nil)
180 @server.casemap.must_be(@casemap)
184 @casemap = (@casemap || 'rfc1459').to_irc_casemap
188 # This is an auxiliary method: it returns true if the receiver fits the
189 # server and casemap specified in _opts_, false otherwise.
191 def fits_with_server_and_casemap?(opts={})
192 srv = opts.fetch(:server, nil)
193 cmap = opts.fetch(:casemap, nil)
194 cmap = cmap.to_irc_casemap unless cmap.nil?
197 return true if cmap.nil? or cmap == casemap
199 return true if srv == @server and (cmap.nil? or cmap == casemap)
204 # Returns the casemap of the receiver, by looking at the bound
205 # @server (if possible) or at the @casemap otherwise
208 return @server.casemap if defined?(@server) and @server
212 # Returns a hash with the current @server and @casemap as values of
213 # :server and :casemap
215 def server_and_casemap
217 h[:server] = @server if defined?(@server) and @server
218 h[:casemap] = @casemap if defined?(@casemap) and @casemap
222 # We allow up/downcasing with a different casemap
224 def irc_downcase(cmap=casemap)
225 self.to_s.irc_downcase(cmap)
228 # Up/downcasing something that includes this module returns its
229 # Up/downcased to_s form
235 # We allow up/downcasing with a different casemap
237 def irc_upcase(cmap=casemap)
238 self.to_s.irc_upcase(cmap)
241 # Up/downcasing something that includes this module returns its
242 # Up/downcased to_s form
253 # We start by extending the String class
254 # with some IRC-specific methods
258 # This method returns the Irc::Casemap whose name is the receiver
261 Irc::Casemap.get(self) rescue raise TypeError, "Unkown Irc::Casemap #{self.inspect}"
264 # This method returns a string which is the downcased version of the
265 # receiver, according to the given _casemap_
268 def irc_downcase(casemap='rfc1459')
269 cmap = casemap.to_irc_casemap
270 self.tr(cmap.upper, cmap.lower)
273 # This is the same as the above, except that the string is altered in place
275 # See also the discussion about irc_downcase
277 def irc_downcase!(casemap='rfc1459')
278 cmap = casemap.to_irc_casemap
279 self.tr!(cmap.upper, cmap.lower)
282 # Upcasing functions are provided too
284 # See also the discussion about irc_downcase
286 def irc_upcase(casemap='rfc1459')
287 cmap = casemap.to_irc_casemap
288 self.tr(cmap.lower, cmap.upper)
293 # See also the discussion about irc_downcase
295 def irc_upcase!(casemap='rfc1459')
296 cmap = casemap.to_irc_casemap
297 self.tr!(cmap.lower, cmap.upper)
300 # This method checks if the receiver contains IRC glob characters
302 # IRC has a very primitive concept of globs: a <tt>*</tt> stands for "any
303 # number of arbitrary characters", a <tt>?</tt> stands for "one and exactly
304 # one arbitrary character". These characters can be escaped by prefixing them
305 # with a slash (<tt>\\</tt>).
307 # A known limitation of this glob syntax is that there is no way to escape
308 # the escape character itself, so it's not possible to build a glob pattern
309 # where the escape character precedes a glob.
312 self =~ /^[*?]|[^\\][*?]/
315 # This method is used to convert the receiver into a Regular Expression
316 # that matches according to the IRC glob syntax
319 regmask = Regexp.escape(self)
320 regmask.gsub!(/(\\\\)?\\[*?]/) { |m|
329 raise "Unexpected match #{m} when converting #{self}"
332 Regexp.new("^#{regmask}$")
338 # ArrayOf is a subclass of Array whose elements are supposed to be all
339 # of the same class. This is not intended to be used directly, but rather
340 # to be subclassed as needed (see for example Irc::UserList and Irc::NetmaskList)
342 # Presently, only very few selected methods from Array are overloaded to check
343 # if the new elements are the correct class. An orthodox? method is provided
344 # to check the entire ArrayOf against the appropriate class.
346 class ArrayOf < Array
348 attr_reader :element_class
350 # Create a new ArrayOf whose elements are supposed to be all of type _kl_,
351 # optionally filling it with the elements from the Array argument.
353 def initialize(kl, ar=[])
354 raise TypeError, "#{kl.inspect} must be a class name" unless kl.kind_of?(Class)
361 raise TypeError, "#{self.class} can only be initialized from an Array"
366 self.__to_s__[0..-2].sub(/:[^:]+$/,"[#{@element_class}]\\0") + " #{super}>"
369 # Private method to check the validity of the elements passed to it
370 # and optionally raise an error
372 # TODO should it accept nils as valid?
374 def internal_will_accept?(raising, *els)
376 unless el.kind_of?(@element_class)
377 raise TypeError, "#{el.inspect} is not of class #{@element_class}" if raising
383 private :internal_will_accept?
385 # This method checks if the passed arguments are acceptable for our ArrayOf
387 def will_accept?(*els)
388 internal_will_accept?(false, *els)
391 # This method checks that all elements are of the appropriate class
397 # This method is similar to the above, except that it raises an exception
398 # if the receiver is not valid
401 raise TypeError unless valid?
404 # Overloaded from Array#<<, checks for appropriate class of argument
407 super(el) if internal_will_accept?(true, el)
410 # Overloaded from Array#&, checks for appropriate class of argument elements
414 ArrayOf.new(@element_class, r) if internal_will_accept?(true, *r)
417 # Overloaded from Array#+, checks for appropriate class of argument elements
420 ArrayOf.new(@element_class, super(ar)) if internal_will_accept?(true, *ar)
423 # Overloaded from Array#-, so that an ArrayOf is returned. There is no need
424 # to check the validity of the elements in the argument
427 ArrayOf.new(@element_class, super(ar)) # if internal_will_accept?(true, *ar)
430 # Overloaded from Array#|, checks for appropriate class of argument elements
433 ArrayOf.new(@element_class, super(ar)) if internal_will_accept?(true, *ar)
436 # Overloaded from Array#concat, checks for appropriate class of argument
440 super(ar) if internal_will_accept?(true, *ar)
443 # Overloaded from Array#insert, checks for appropriate class of argument
447 super(idx, *ar) if internal_will_accept?(true, *ar)
450 # Overloaded from Array#replace, checks for appropriate class of argument
454 super(ar) if (ar.kind_of?(ArrayOf) && ar.element_class <= @element_class) or internal_will_accept?(true, *ar)
457 # Overloaded from Array#push, checks for appropriate class of argument
461 super(*ar) if internal_will_accept?(true, *ar)
464 # Overloaded from Array#unshift, checks for appropriate class of argument(s)
468 super(el) if internal_will_accept?(true, *els)
472 # We introduce the 'downcase' method, which maps downcase() to all the Array
473 # elements, properly failing when the elements don't have a downcase method
476 self.map { |el| el.downcase }
479 # Modifying methods which we don't handle yet are made private
481 private :[]=, :collect!, :map!, :fill, :flatten!
486 # We extend the Regexp class with an Irc module which will contain some
487 # Irc-specific regexps
491 # We start with some general-purpose ones which will be used in the
492 # Irc module too, but are useful regardless
494 HEX_DIGIT = /[0-9A-Fa-f]/
495 HEX_DIGITS = /#{HEX_DIGIT}+/
496 HEX_OCTET = /#{HEX_DIGIT}#{HEX_DIGIT}?/
497 DEC_OCTET = /[01]?\d?\d|2[0-4]\d|25[0-5]/
498 DEC_IP_ADDR = /#{DEC_OCTET}.#{DEC_OCTET}.#{DEC_OCTET}.#{DEC_OCTET}/
499 HEX_IP_ADDR = /#{HEX_OCTET}.#{HEX_OCTET}.#{HEX_OCTET}.#{HEX_OCTET}/
500 IP_ADDR = /#{DEC_IP_ADDR}|#{HEX_IP_ADDR}/
502 # IPv6, from Resolv::IPv6, without the \A..\z anchors
503 HEX_16BIT = /#{HEX_DIGIT}{1,4}/
504 IP6_8Hex = /(?:#{HEX_16BIT}:){7}#{HEX_16BIT}/
505 IP6_CompressedHex = /((?:#{HEX_16BIT}(?::#{HEX_16BIT})*)?)::((?:#{HEX_16BIT}(?::#{HEX_16BIT})*)?)/
506 IP6_6Hex4Dec = /((?:#{HEX_16BIT}:){6,6})#{DEC_IP_ADDR}/
507 IP6_CompressedHex4Dec = /((?:#{HEX_16BIT}(?::#{HEX_16BIT})*)?)::((?:#{HEX_16BIT}:)*)#{DEC_IP_ADDR}/
508 IP6_ADDR = /(?:#{IP6_8Hex})|(?:#{IP6_CompressedHex})|(?:#{IP6_6Hex4Dec})|(?:#{IP6_CompressedHex4Dec})/
510 # We start with some IRC related regular expressions, used to match
511 # Irc::User nicks and users and Irc::Channel names
513 # For each of them we define two versions of the regular expression:
514 # * a generic one, which should match for any server but may turn out to
515 # match more than a specific server would accept
516 # * an RFC-compliant matcher
520 # Channel-name-matching regexps
522 CHAN_SAFE = /![A-Z0-9]{5}/
523 CHAN_ANY = /[^\x00\x07\x0A\x0D ,:]/
524 GEN_CHAN = /(?:#{CHAN_FIRST}|#{CHAN_SAFE})#{CHAN_ANY}+/
525 RFC_CHAN = /#{CHAN_FIRST}#{CHAN_ANY}{1,49}|#{CHAN_SAFE}#{CHAN_ANY}{1,44}/
527 # Nick-matching regexps
528 SPECIAL_CHAR = /[\x5b-\x60\x7b-\x7d]/
529 NICK_FIRST = /#{SPECIAL_CHAR}|[[:alpha:]]/
530 NICK_ANY = /#{SPECIAL_CHAR}|[[:alnum:]]|-/
531 GEN_NICK = /#{NICK_FIRST}#{NICK_ANY}+/
532 RFC_NICK = /#{NICK_FIRST}#{NICK_ANY}{0,8}/
534 USER_CHAR = /[^\x00\x0a\x0d @]/
535 GEN_USER = /#{USER_CHAR}+/
537 # Host-matching regexps
538 HOSTNAME_COMPONENT = /[[:alnum:]](?:[[:alnum:]]|-)*[[:alnum:]]*/
539 HOSTNAME = /#{HOSTNAME_COMPONENT}(?:\.#{HOSTNAME_COMPONENT})*/
540 HOSTADDR = /#{IP_ADDR}|#{IP6_ADDR}/
542 GEN_HOST = /#{HOSTNAME}|#{HOSTADDR}/
544 # # FreeNode network replaces the host of affiliated users with
546 # # FIXME we need the true syntax to match it properly ...
547 # PDPC_HOST_PART = /[0-9A-Za-z.-]+/
548 # PDPC_HOST = /#{PDPC_HOST_PART}(?:\/#{PDPC_HOST_PART})+/
550 # # NOTE: the final optional and non-greedy dot is needed because some
551 # # servers (e.g. FreeNode) send the hostname of the services as "services."
552 # # which is not RFC compliant, but sadly done.
553 # GEN_HOST_EXT = /#{PDPC_HOST}|#{GEN_HOST}\.??/
555 # Sadly, different networks have different, RFC-breaking ways of cloaking
556 # the actualy host address: see above for an example to handle FreeNode.
557 # Another example would be Azzurra, wich also inserts a "=" in the
558 # cloacked host. So let's just not care about this and go with the simplest
562 # User-matching Regexp
563 GEN_USER_ID = /(#{GEN_NICK})(?:(?:!(#{GEN_USER}))?@(#{GEN_HOST_EXT}))?/
565 # Things such has the BIP proxy send invalid nicks in a complete netmask,
566 # so we want to match this, rather: this matches either a compliant nick
567 # or a a string with a very generic nick, a very generic hostname after an
568 # @ sign, and an optional user after a !
569 BANG_AT = /#{GEN_NICK}|\S+?(?:!\S+?)?@\S+?/
571 # # For Netmask, we want to allow wildcards * and ? in the nick
572 # # (they are already allowed in the user and host part
573 # GEN_NICK_MASK = /(?:#{NICK_FIRST}|[?*])?(?:#{NICK_ANY}|[?*])+/
575 # # Netmask-matching Regexp
576 # GEN_MASK = /(#{GEN_NICK_MASK})(?:(?:!(#{GEN_USER}))?@(#{GEN_HOST_EXT}))?/
586 # A Netmask identifies each user by collecting its nick, username and
587 # hostname in the form <tt>nick!user@host</tt>
589 # Netmasks can also contain glob patterns in any of their components; in
590 # this form they are used to refer to more than a user or to a user
591 # appearing under different forms.
594 # * <tt>*!*@*</tt> refers to everybody
595 # * <tt>*!someuser@somehost</tt> refers to user +someuser+ on host +somehost+
596 # regardless of the nick used.
600 # Netmasks have an associated casemap unless they are bound to a server
602 include ServerOrCasemap
604 attr_reader :nick, :user, :host
607 # Create a new Netmask from string _str_, which must be in the form
608 # _nick_!_user_@_host_
610 # It is possible to specify a server or a casemap in the optional Hash:
611 # these are used to associate the Netmask with the given server and to set
612 # its casemap: if a server is specified and a casemap is not, the server's
613 # casemap is used. If both a server and a casemap are specified, the
614 # casemap must match the server's casemap or an exception will be raised.
616 # Empty +nick+, +user+ or +host+ are converted to the generic glob pattern
618 def initialize(str="", opts={})
619 # First of all, check for server/casemap option
621 init_server_or_casemap(opts)
623 # Now we can see if the given string _str_ is an actual Netmask
624 if str.respond_to?(:to_str)
626 # We match a pretty generic string, to work around non-compliant
628 when /^(?:(\S+?)(?:(?:!(\S+?))?@(\S+))?)?$/
629 # We do assignment using our internal methods
634 raise ArgumentError, "#{str.to_str.inspect} does not represent a valid #{self.class}"
637 raise TypeError, "#{str} cannot be converted to a #{self.class}"
641 # A Netmask is easily converted to a String for the usual representation.
642 # We skip the user or host parts if they are "*", unless we've been asked
647 ret << "!" << user unless user == "*"
648 ret << "@" << host unless host == "*"
653 "#{nick}!#{user}@#{host}"
656 alias :to_str :fullform
658 # This method downcases the fullform of the netmask. While this may not be
659 # significantly different from the #downcase() method provided by the
660 # ServerOrCasemap mixin, it's significantly different for Netmask
661 # subclasses such as User whose simple downcasing uses the nick only.
663 def full_irc_downcase(cmap=casemap)
664 self.fullform.irc_downcase(cmap)
667 # full_downcase() will return the fullform downcased according to the
671 self.full_irc_downcase
674 # This method returns a new Netmask which is the fully downcased version
677 return self.full_downcase.to_irc_netmask(server_and_casemap)
680 # Converts the receiver into a Netmask with the given (optional)
681 # server/casemap association. We return self unless a conversion
682 # is needed (different casemap/server)
684 # Subclasses of Netmask will return a new Netmask, using full_downcase
686 def to_irc_netmask(opts={})
687 if self.class == Netmask
688 return self if fits_with_server_and_casemap?(opts)
690 return self.full_downcase.to_irc_netmask(server_and_casemap.merge(opts))
693 # Converts the receiver into a User with the given (optional)
694 # server/casemap association. We return self unless a conversion
695 # is needed (different casemap/server)
697 def to_irc_user(opts={})
698 self.fullform.to_irc_user(server_and_casemap.merge(opts))
701 # Inspection of a Netmask reveals the server it's bound to (if there is
702 # one), its casemap and the nick, user and host part
705 str = self.__to_s__[0..-2]
706 str << " @server=#{@server}" if defined?(@server) and @server
707 str << " @nick=#{@nick.inspect} @user=#{@user.inspect}"
708 str << " @host=#{@host.inspect} casemap=#{casemap.inspect}"
712 # Equality: two Netmasks are equal if they downcase to the same thing
714 # TODO we may want it to try other.to_irc_netmask
717 return false unless other.kind_of?(self.class)
718 self.downcase == other.downcase
721 # This method changes the nick of the Netmask, defaulting to the generic
722 # glob pattern if the result is the null string.
726 @nick = "*" if @nick.empty?
729 # This method changes the user of the Netmask, defaulting to the generic
730 # glob pattern if the result is the null string.
734 @user = "*" if @user.empty?
738 # This method changes the hostname of the Netmask, defaulting to the generic
739 # glob pattern if the result is the null string.
743 @host = "*" if @host.empty?
746 # We can replace everything at once with data from another Netmask
754 @server = other.server
755 @casemap = other.casemap unless @server
757 replace(other.to_irc_netmask(server_and_casemap))
761 # This method checks if a Netmask is definite or not, by seeing if
762 # any of its components are defined by globs
765 return @nick.has_irc_glob? || @user.has_irc_glob? || @host.has_irc_glob?
770 unless u.has_irc_glob?
771 u.sub!(/^[in]=/, '=') or u.sub!(/^\W(\w+)/, '\1')
776 unless h.has_irc_glob?
778 h.sub!(/x-\w+$/, 'x-*')
780 h.match(/^[^\.]+\.[^\.]+$/) or
781 h.sub!(/azzurra[=-][0-9a-f]+/i, '*') or # hello, azzurra, you suck!
782 h.sub!(/^(\d+\.\d+\.\d+\.)\d+$/, '\1*') or
783 h.sub!(/^[^\.]+\./, '*.')
786 return Netmask.new("*!#{u}@#{h}", server_and_casemap)
789 # This method is used to match the current Netmask against another one
791 # The method returns true if each component of the receiver matches the
792 # corresponding component of the argument. By _matching_ here we mean
793 # that any netmask described by the receiver is also described by the
796 # In this sense, matching is rather simple to define in the case when the
797 # receiver has no globs: it is just necessary to check if the argument
798 # describes the receiver, which can be done by matching it against the
799 # argument converted into an IRC Regexp (see String#to_irc_regexp).
801 # The situation is also easy when the receiver has globs and the argument
802 # doesn't, since in this case the result is false.
804 # The more complex case in which both the receiver and the argument have
805 # globs is not handled yet.
808 cmp = arg.to_irc_netmask(:casemap => casemap)
809 debug "Matching #{self.fullform} against #{arg.inspect} (#{cmp.fullform})"
810 [:nick, :user, :host].each { |component|
811 us = self.send(component).irc_downcase(casemap)
812 them = cmp.send(component).irc_downcase(casemap)
813 if us.has_irc_glob? && them.has_irc_glob?
815 warn NotImplementedError
818 return false if us.has_irc_glob? && !them.has_irc_glob?
819 return false unless us =~ them.to_irc_regexp
824 # Case equality. Checks if arg matches self
827 arg.to_irc_netmask(:casemap => casemap).matches?(self)
830 # Sorting is done via the fullform
835 self.fullform.irc_downcase(casemap) <=> arg.fullform.irc_downcase(casemap)
837 self.downcase <=> arg.downcase
844 # A NetmaskList is an ArrayOf <code>Netmask</code>s
846 class NetmaskList < ArrayOf
848 # Create a new NetmaskList, optionally filling it with the elements from
849 # the Array argument fed to it.
851 def initialize(ar=[])
855 # We enhance the [] method by allowing it to pick an element that matches
856 # a given Netmask, a String or a Regexp
857 # TODO take into consideration the opportunity to use select() instead of
858 # find(), and/or a way to let the user choose which one to take (second
866 mask.matches?(args[0])
870 mask.matches?(args[0].to_irc_netmask(:casemap => mask.casemap))
874 mask.fullform =~ args[0]
891 # We keep extending String, this time adding a method that converts a
892 # String into an Irc::Netmask object
894 def to_irc_netmask(opts={})
895 Irc::Netmask.new(self, opts)
904 # An IRC User is identified by his/her Netmask (which must not have globs).
905 # In fact, User is just a subclass of Netmask.
907 # Ideally, the user and host information of an IRC User should never
908 # change, and it shouldn't contain glob patterns. However, IRC is somewhat
909 # idiosincratic and it may be possible to know the nick of a User much before
910 # its user and host are known. Moreover, some networks (namely Freenode) may
911 # change the hostname of a User when (s)he identifies with Nickserv.
913 # As a consequence, we must allow changes to a User host and user attributes.
914 # We impose a restriction, though: they may not contain glob patterns, except
915 # for the special case of an unknown user/host which is represented by a *.
917 # It is possible to create a totally unknown User (e.g. for initializations)
918 # by setting the nick to * too.
921 # * see if it's worth to add the other USER data
922 # * see if it's worth to add NICKSERV status
927 attr_accessor :real_name
929 # Create a new IRC User from a given Netmask (or anything that can be converted
930 # into a Netmask) provided that the given Netmask does not have globs.
932 def initialize(str="", opts={})
934 raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if nick.has_irc_glob? && nick != "*"
935 raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if user.has_irc_glob? && user != "*"
936 raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if host.has_irc_glob? && host != "*"
938 @real_name = String.new
941 # The nick of a User may be changed freely, but it must not contain glob patterns.
944 raise "Can't change the nick to #{newnick}" if defined?(@nick) and newnick.has_irc_glob?
948 # We have to allow changing the user of an Irc User due to some networks
949 # (e.g. Freenode) changing hostmasks on the fly. We still check if the new
950 # user data has glob patterns though.
953 raise "Can't change the username to #{newuser}" if defined?(@user) and newuser.has_irc_glob?
957 # We have to allow changing the host of an Irc User due to some networks
958 # (e.g. Freenode) changing hostmasks on the fly. We still check if the new
959 # host data has glob patterns though.
962 raise "Can't change the hostname to #{newhost}" if defined?(@host) and newhost.has_irc_glob?
966 # Checks if a User is well-known or not by looking at the hostname and user
969 return nick != "*" && user != "*" && host != "*"
978 # Set the away status of the user. Use away=(nil) or away=(false)
989 # Since to_irc_user runs the same checks on server and channel as
990 # to_irc_netmask, we just try that and return self if it works.
992 # Subclasses of User will return self if possible.
994 def to_irc_user(opts={})
995 return self if fits_with_server_and_casemap?(opts)
996 return self.full_downcase.to_irc_user(opts)
999 # We can replace everything at once with data from another User
1004 self.nick = other.nick
1005 self.user = other.user
1006 self.host = other.host
1007 @server = other.server
1008 @casemap = other.casemap unless @server
1011 self.replace(other.to_irc_user(server_and_casemap))
1015 def modes_on(channel)
1018 channel.modes_of(self)
1020 return @server.channel(channel).modes_of(self) if @server
1021 raise "Can't resolve channel #{channel}"
1028 channel.has_op?(self)
1030 return @server.channel(channel).has_op?(self) if @server
1031 raise "Can't resolve channel #{channel}"
1035 def is_voice?(channel)
1038 channel.has_voice?(self)
1040 return @server.channel(channel).has_voice?(self) if @server
1041 raise "Can't resolve channel #{channel}"
1047 # A UserList is an ArrayOf <code>User</code>s
1048 # We derive it from NetmaskList, which allows us to inherit any special
1049 # NetmaskList method
1051 class UserList < NetmaskList
1053 # Create a new UserList, optionally filling it with the elements from
1054 # the Array argument fed to it.
1056 def initialize(ar=[])
1058 @element_class = User
1061 # Convenience method: convert the UserList to a list of nicks. The indices
1065 self.map { |user| user.nick }
1074 # We keep extending String, this time adding a method that converts a
1075 # String into an Irc::User object
1077 def to_irc_user(opts={})
1078 Irc::User.new(self, opts)
1085 # An IRC Channel is identified by its name, and it has a set of properties:
1086 # * a Channel::Topic
1088 # * a set of Channel::Modes
1090 # The Channel::Topic and Channel::Mode classes are defined within the
1091 # Channel namespace because they only make sense there
1099 attr_reader :channel
1107 # Channel modes of type A manipulate lists
1109 # Example: b (banlist)
1111 class ModeTypeA < Mode
1115 @list = NetmaskList.new
1119 nm = @channel.server.new_netmask(val)
1120 @list << nm unless @list.include?(nm)
1124 nm = @channel.server.new_netmask(val)
1131 # Channel modes of type B need an argument
1135 class ModeTypeB < Mode
1144 alias :value :status
1151 @arg = nil if @arg == val
1157 # Channel modes that change the User prefixes are like
1158 # Channel modes of type B, except that they manipulate
1159 # lists of Users, so they are somewhat similar to channel
1162 class UserMode < ModeTypeB
1167 @list = UserList.new
1171 u = @channel.server.user(val)
1172 @list << u unless @list.include?(u)
1176 u = @channel.server.user(val)
1183 # Channel modes of type C need an argument when set,
1184 # but not when they get reset
1186 # Example: l (limit)
1188 class ModeTypeC < Mode
1197 alias :value :status
1210 # Channel modes of type D are basically booleans
1212 # Example: m (moderate)
1214 class ModeTypeD < Mode
1235 # A Topic represents the topic of a channel. It consists of
1236 # the topic itself, who set it and when
1239 attr_accessor :text, :set_by, :set_on
1242 # Create a new Topic setting the text, the creator and
1245 def initialize(text="", set_by="", set_on=Time.new)
1247 @set_by = set_by.to_irc_netmask
1251 # Replace a Topic with another one
1254 raise TypeError, "#{topic.inspect} is not of class #{self.class}" unless topic.kind_of?(self.class)
1255 @text = topic.text.dup
1256 @set_by = topic.set_by.dup
1257 @set_on = topic.set_on.dup
1262 def to_irc_channel_topic
1275 # Returns an Irc::Channel::Topic with self as text
1277 def to_irc_channel_topic
1278 Irc::Channel::Topic.new(self)
1287 # Here we start with the actual Channel class
1291 include ServerOrCasemap
1292 attr_reader :name, :topic, :mode, :users
1296 str = self.__to_s__[0..-2]
1297 str << " on server #{server}" if server
1298 str << " @name=#{@name.inspect} @topic=#{@topic.text.inspect}"
1299 str << " @users=[#{user_nicks.sort.join(', ')}]"
1311 @users.map { |u| u.downcase }
1314 # Checks if the receiver already has a user with the given _nick_
1317 @users.index(nick.to_irc_user(server_and_casemap))
1320 # Returns the user with nick _nick_, if available
1323 idx = has_user?(nick)
1327 # Adds a user to the channel
1329 def add_user(user, opts={})
1330 silent = opts.fetch(:silent, false)
1332 warn "Trying to add user #{user} to channel #{self} again" unless silent
1334 @users << user.to_irc_user(server_and_casemap)
1338 # Creates a new channel with the given name, optionally setting the topic
1339 # and an initial users list.
1341 # No additional info is created here, because the channel flags and userlists
1342 # allowed depend on the server.
1344 def initialize(name, topic=nil, users=[], opts={})
1345 raise ArgumentError, "Channel name cannot be empty" if name.to_s.empty?
1346 warn "Unknown channel prefix #{name[0].chr}" if name !~ /^[&#+!]/
1347 raise ArgumentError, "Invalid character in #{name.inspect}" if name =~ /[ \x07,]/
1349 init_server_or_casemap(opts)
1353 @topic = topic ? topic.to_irc_channel_topic : Channel::Topic.new
1355 @users = UserList.new
1365 # Removes a user from the channel
1367 def delete_user(user)
1368 @mode.each { |sym, mode|
1369 mode.reset(user) if mode.kind_of?(UserMode)
1374 # The channel prefix
1380 # A channel is local to a server if it has the '&' prefix
1386 # A channel is modeless if it has the '+' prefix
1392 # A channel is safe if it has the '!' prefix
1398 # A channel is normal if it has the '#' prefix
1406 def create_mode(sym, kl)
1407 @mode[sym.to_sym] = kl.new(self)
1413 l << s if (m.class <= UserMode and m.list[user])
1419 @mode.has_key?(:o) and @mode[:o].list[user]
1422 def has_voice?(user)
1423 @mode.has_key?(:v) and @mode[:v].list[user]
1428 # A ChannelList is an ArrayOf <code>Channel</code>s
1430 class ChannelList < ArrayOf
1432 # Create a new ChannelList, optionally filling it with the elements from
1433 # the Array argument fed to it.
1435 def initialize(ar=[])
1439 # Convenience method: convert the ChannelList to a list of channel names.
1440 # The indices are preserved
1443 self.map { |chan| chan.name }
1453 # We keep extending String, this time adding a method that converts a
1454 # String into an Irc::Channel object
1456 def to_irc_channel(opts={})
1457 Irc::Channel.new(self, opts)
1466 # An IRC Server represents the Server the client is connected to.
1470 attr_reader :hostname, :version, :usermodes, :chanmodes
1471 alias :to_s :hostname
1472 attr_reader :supports, :capabilities
1474 attr_reader :channels, :users
1478 @channels.map { |ch| ch.downcase }
1483 @users.map { |u| u.downcase }
1487 chans, users = [@channels, @users].map {|d|
1489 a.downcase <=> b.downcase
1495 str = self.__to_s__[0..-2]
1496 str << " @hostname=#{hostname}"
1497 str << " @channels=#{chans}"
1498 str << " @users=#{users}"
1502 # Create a new Server, with all instance variables reset to nil (for
1503 # scalar variables), empty channel and user lists and @supports
1504 # initialized to the default values for all known supported features.
1507 @hostname = @version = @usermodes = @chanmodes = nil
1509 @channels = ChannelList.new
1511 @users = UserList.new
1516 # Resets the server capabilities
1518 def reset_capabilities
1520 :casemapping => 'rfc1459'.to_irc_casemap,
1523 :typea => nil, # Type A: address lists
1524 :typeb => nil, # Type B: needs a parameter
1525 :typec => nil, # Type C: needs a parameter when set
1526 :typed => nil # Type D: must not have a parameter
1529 :chantypes => "#&!+",
1540 :prefixes => [:"@", :+]
1551 # Convert a mode (o, v, h, ...) to the corresponding
1552 # prefix (@, +, %, ...). See also mode_for_prefix
1553 def prefix_for_mode(mode)
1554 return @supports[:prefix][:prefixes][
1555 @supports[:prefix][:modes].index(mode.to_sym)
1559 # Convert a prefix (@, +, %, ...) to the corresponding
1560 # mode (o, v, h, ...). See also prefix_for_mode
1561 def mode_for_prefix(pfx)
1562 return @supports[:prefix][:modes][
1563 @supports[:prefix][:prefixes].index(pfx.to_sym)
1567 # Resets the Channel and User list
1570 @users.reverse_each { |u|
1573 @channels.reverse_each { |u|
1583 @hostname = @version = @usermodes = @chanmodes = nil
1586 # This method is used to parse a 004 RPL_MY_INFO line
1588 def parse_my_info(line)
1589 ar = line.split(' ')
1596 def noval_warn(key, val, &block)
1598 yield if block_given?
1600 warn "No #{key.to_s.upcase} value"
1604 def val_warn(key, val, &block)
1605 if val == true or val == false or val.nil?
1606 yield if block_given?
1608 warn "No #{key.to_s.upcase} value must be specified, got #{val}"
1611 private :noval_warn, :val_warn
1613 # This method is used to parse a 005 RPL_ISUPPORT line
1615 # See the RPL_ISUPPORT draft[http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt]
1617 def parse_isupport(line)
1618 debug "Parsing ISUPPORT #{line.inspect}"
1619 ar = line.split(' ')
1622 prekey, val = en.split('=', 2)
1623 if prekey =~ /^-(.*)/
1624 key = $1.downcase.to_sym
1627 key = prekey.downcase.to_sym
1631 noval_warn(key, val) {
1632 @supports[key] = val.to_irc_casemap
1634 when :chanlimit, :idchan, :maxlist, :targmax
1635 noval_warn(key, val) {
1636 groups = val.split(',')
1639 @supports[key][k] = v.to_i || 0
1640 if @supports[key][k] == 0
1641 warn "Deleting #{key} limit of 0 for #{k}"
1642 @supports[key].delete(k)
1647 noval_warn(key, val) {
1648 groups = val.split(',')
1649 @supports[key][:typea] = groups[0].scan(/./).map { |x| x.to_sym}
1650 @supports[key][:typeb] = groups[1].scan(/./).map { |x| x.to_sym}
1651 @supports[key][:typec] = groups[2].scan(/./).map { |x| x.to_sym}
1652 @supports[key][:typed] = groups[3].scan(/./).map { |x| x.to_sym}
1654 when :channellen, :kicklen, :modes, :topiclen
1656 @supports[key] = val.to_i
1658 @supports[key] = nil
1661 @supports[key] = val # can also be nil
1664 @supports[key] = val
1667 @supports[key] = val
1669 noval_warn(key, val) {
1670 reparse += "CHANLIMIT=(chantypes):#{val} "
1673 noval_warn(key, val) {
1674 @supports[:targmax]['PRIVMSG'] = val.to_i
1675 @supports[:targmax]['NOTICE'] = val.to_i
1678 noval_warn(key, val) {
1679 @supports[key] = val
1682 noval_warn(key, val) {
1683 @supports[key] = val.to_i
1687 val.scan(/\((.*)\)(.*)/) { |m, p|
1688 @supports[key][:modes] = m.scan(/./).map { |x| x.to_sym}
1689 @supports[key][:prefixes] = p.scan(/./).map { |x| x.to_sym}
1692 @supports[key][:modes] = nil
1693 @supports[key][:prefixes] = nil
1696 val_warn(key, val) {
1697 @supports[key] = val.nil? ? true : val
1700 noval_warn(key, val) {
1701 @supports[key] = val.scan(/./)
1704 noval_warn(key, val) {
1705 @supports[key] = val.split(',')
1708 @supports[key] = val.nil? ? true : val
1711 reparse.gsub!("(chantypes)",@supports[:chantypes])
1712 parse_isupport(reparse) unless reparse.empty?
1715 # Returns the casemap of the server.
1718 @supports[:casemapping]
1721 # Returns User or Channel depending on what _name_ can be
1724 def user_or_channel?(name)
1725 if supports[:chantypes].include?(name[0])
1732 # Returns the actual User or Channel object matching _name_
1734 def user_or_channel(name)
1735 if supports[:chantypes].include?(name[0])
1736 return channel(name)
1742 # Checks if the receiver already has a channel with the given _name_
1744 def has_channel?(name)
1745 return false if name.nil_or_empty?
1746 channel_names.index(name.irc_downcase(casemap))
1748 alias :has_chan? :has_channel?
1750 # Returns the channel with name _name_, if available
1752 def get_channel(name)
1753 return nil if name.nil_or_empty?
1754 idx = has_channel?(name)
1755 channels[idx] if idx
1757 alias :get_chan :get_channel
1759 # Create a new Channel object bound to the receiver and add it to the
1760 # list of <code>Channel</code>s on the receiver, unless the channel was
1761 # present already. In this case, the default action is to raise an
1762 # exception, unless _fails_ is set to false. An exception can also be
1763 # raised if _str_ is nil or empty, again only if _fails_ is set to true;
1764 # otherwise, the method just returns nil
1766 def new_channel(name, topic=nil, users=[], fails=true)
1767 if name.nil_or_empty?
1768 raise "Tried to look for empty or nil channel name #{name.inspect}" if fails
1773 raise "Channel #{name} already exists on server #{self}" if fails
1777 prefix = name[0].chr
1779 # Give a warning if the new Channel goes over some server limits.
1781 # FIXME might need to raise an exception
1783 warn "#{self} doesn't support channel prefix #{prefix}" unless @supports[:chantypes].include?(prefix)
1784 warn "#{self} doesn't support channel names this long (#{name.length} > #{@supports[:channellen]})" unless name.length <= @supports[:channellen]
1786 # Next, we check if we hit the limit for channels of type +prefix+
1787 # if the server supports +chanlimit+
1789 @supports[:chanlimit].keys.each { |k|
1790 next unless k.include?(prefix)
1792 channel_names.each { |n|
1793 count += 1 if k.include?(n[0])
1795 # raise IndexError, "Already joined #{count} channels with prefix #{k}" if count == @supports[:chanlimit][k]
1796 warn "Already joined #{count}/#{@supports[:chanlimit][k]} channels with prefix #{k}, we may be going over server limits" if count >= @supports[:chanlimit][k]
1799 # So far, everything is fine. Now create the actual Channel
1801 chan = Channel.new(name, topic, users, :server => self)
1803 # We wade through +prefix+ and +chanmodes+ to create appropriate
1804 # lists and flags for this channel
1806 @supports[:prefix][:modes].each { |mode|
1807 chan.create_mode(mode, Channel::UserMode)
1808 } if @supports[:prefix][:modes]
1810 @supports[:chanmodes].each { |k, val|
1815 chan.create_mode(mode, Channel::ModeTypeA)
1819 chan.create_mode(mode, Channel::ModeTypeB)
1823 chan.create_mode(mode, Channel::ModeTypeC)
1827 chan.create_mode(mode, Channel::ModeTypeD)
1834 # debug "Created channel #{chan.inspect}"
1839 # Returns the Channel with the given _name_ on the server,
1840 # creating it if necessary. This is a short form for
1841 # new_channel(_str_, nil, [], +false+)
1844 new_channel(str,nil,[],false)
1847 # Remove Channel _name_ from the list of <code>Channel</code>s
1849 def delete_channel(name)
1850 idx = has_channel?(name)
1851 raise "Tried to remove unmanaged channel #{name}" unless idx
1852 @channels.delete_at(idx)
1855 # Checks if the receiver already has a user with the given _nick_
1858 return false if nick.nil_or_empty?
1859 user_nicks.index(nick.irc_downcase(casemap))
1862 # Returns the user with nick _nick_, if available
1865 idx = has_user?(nick)
1869 # Create a new User object bound to the receiver and add it to the list
1870 # of <code>User</code>s on the receiver, unless the User was present
1871 # already. In this case, the default action is to raise an exception,
1872 # unless _fails_ is set to false. An exception can also be raised
1873 # if _str_ is nil or empty, again only if _fails_ is set to true;
1874 # otherwise, the method just returns nil
1876 def new_user(str, fails=true)
1877 if str.nil_or_empty?
1878 raise "Tried to look for empty or nil user name #{str.inspect}" if fails
1881 tmp = str.to_irc_user(:server => self)
1882 old = get_user(tmp.nick)
1883 # debug "Tmp: #{tmp.inspect}"
1884 # debug "Old: #{old.inspect}"
1886 # debug "User already existed as #{old.inspect}"
1889 # debug "Both were known"
1890 # Do not raise an error: things like Freenode change the hostname after identification
1891 warning "User #{tmp.nick} has inconsistent Netmasks! #{self} knows #{old.inspect} but access was tried with #{tmp.inspect}" if old != tmp
1892 raise "User #{tmp} already exists on server #{self}" if fails
1894 if old.fullform.downcase != tmp.fullform.downcase
1896 # debug "Known user now #{old.inspect}"
1901 warn "#{self} doesn't support nicknames this long (#{tmp.nick.length} > #{@supports[:nicklen]})" unless tmp.nick.length <= @supports[:nicklen]
1907 # Returns the User with the given Netmask on the server,
1908 # creating it if necessary. This is a short form for
1909 # new_user(_str_, +false+)
1912 new_user(str, false)
1915 # Deletes User _user_ from Channel _channel_
1917 def delete_user_from_channel(user, channel)
1918 channel.delete_user(user)
1921 # Remove User _someuser_ from the list of <code>User</code>s.
1922 # _someuser_ must be specified with the full Netmask.
1924 def delete_user(someuser)
1925 idx = has_user?(someuser)
1926 raise "Tried to remove unmanaged user #{user}" unless idx
1927 have = self.user(someuser)
1928 @channels.each { |ch|
1929 delete_user_from_channel(have, ch)
1931 @users.delete_at(idx)
1934 # Create a new Netmask object with the appropriate casemap
1936 def new_netmask(str)
1937 str.to_irc_netmask(:server => self)
1940 # Finds all <code>User</code>s on server whose Netmask matches _mask_
1942 def find_users(mask)
1943 nm = new_netmask(mask)
1944 @users.inject(UserList.new) {
1946 if user.user == "*" or user.host == "*"
1947 list << user if user.nick.irc_downcase(casemap) =~ nm.nick.irc_downcase(casemap).to_irc_regexp
1949 list << user if user.matches?(nm)