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 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
10 # :title: IRC module
\r
14 # This module defines the fundamental building blocks for IRC
\r
16 # Author:: Giuseppe Bilotta (giuseppe.bilotta@gmail.com)
\r
17 # Copyright:: Copyright (c) 2006 Giuseppe Bilotta
\r
24 # We extend the Object class with a method that
\r
25 # checks if the receiver is nil or empty
\r
27 return true unless self
\r
28 return true if self.respond_to? :empty and self.empty?
\r
33 # The Irc module is used to keep all IRC-related classes
\r
34 # in the same namespace
\r
39 # Due to its Scandinavian origins, IRC has strange case mappings, which
\r
40 # consider the characters <tt>{}|^</tt> as the uppercase
\r
41 # equivalents of # <tt>[]\~</tt>.
\r
43 # This is however not the same on all IRC servers: some use standard ASCII
\r
44 # casemapping, other do not consider <tt>^</tt> as the uppercase of
\r
50 # Create a new casemap with name _name_, uppercase characters _upper_ and
\r
51 # lowercase characters _lower_
\r
53 def initialize(name, upper, lower)
\r
55 raise "Casemap #{name.inspect} already exists!" if @@casemaps.has_key?(@key)
\r
56 @@casemaps[@key] = {
\r
63 # Returns the Casemap with the given name
\r
65 def Casemap.get(name)
\r
66 @@casemaps[name.to_sym][:casemap]
\r
69 # Retrieve the 'uppercase characters' of this Casemap
\r
72 @@casemaps[@key][:upper]
\r
75 # Retrieve the 'lowercase characters' of this Casemap
\r
78 @@casemaps[@key][:lower]
\r
81 # Return a Casemap based on the receiver
\r
87 # A Casemap is represented by its lower/upper mappings
\r
90 "#<#{self.class}:#{'0x%x'% self.object_id}: #{upper.inspect} ~(#{self})~ #{lower.inspect}>"
\r
93 # As a String we return our name
\r
99 # Two Casemaps are equal if they have the same upper and lower ranges
\r
102 other = arg.to_irc_casemap
\r
103 return self.upper == other.upper && self.lower == other.lower
\r
106 # Raise an error if _arg_ and self are not the same Casemap
\r
109 other = arg.to_irc_casemap
\r
110 raise "Casemap mismatch (#{self.inspect} != #{other.inspect})" unless self == other
\r
116 # The rfc1459 casemap
\r
118 class RfcCasemap < Casemap
\r
122 super('rfc1459', "\x41-\x5e", "\x61-\x7e")
\r
126 RfcCasemap.instance
\r
128 # The strict-rfc1459 Casemap
\r
130 class StrictRfcCasemap < Casemap
\r
134 super('strict-rfc1459', "\x41-\x5d", "\x61-\x7d")
\r
138 StrictRfcCasemap.instance
\r
140 # The ascii Casemap
\r
142 class AsciiCasemap < Casemap
\r
146 super('ascii', "\x41-\x5a", "\x61-\x7a")
\r
150 AsciiCasemap.instance
\r
153 # This module is included by all classes that are either bound to a server
\r
154 # or should have a casemap.
\r
156 module ServerOrCasemap
\r
158 attr_reader :server
\r
160 # This method initializes the instance variables @server and @casemap
\r
161 # according to the values of the hash keys :server and :casemap in _opts_
\r
163 def init_server_or_casemap(opts={})
\r
164 @server = opts.fetch(:server, nil)
\r
165 raise TypeError, "#{@server} is not a valid Irc::Server" if @server and not @server.kind_of?(Server)
\r
167 @casemap = opts.fetch(:casemap, nil)
\r
170 @server.casemap.must_be(@casemap)
\r
174 @casemap = (@casemap || 'rfc1459').to_irc_casemap
\r
178 # This is an auxiliary method: it returns true if the receiver fits the
\r
179 # server and casemap specified in _opts_, false otherwise.
\r
181 def fits_with_server_and_casemap?(opts={})
\r
182 srv = opts.fetch(:server, nil)
\r
183 cmap = opts.fetch(:casemap, nil)
\r
184 cmap = cmap.to_irc_casemap unless cmap.nil?
\r
187 return true if cmap.nil? or cmap == casemap
\r
189 return true if srv == @server and (cmap.nil? or cmap == casemap)
\r
194 # Returns the casemap of the receiver, by looking at the bound
\r
195 # @server (if possible) or at the @casemap otherwise
\r
198 return @server.casemap if defined?(@server) and @server
\r
202 # Returns a hash with the current @server and @casemap as values of
\r
203 # :server and :casemap
\r
205 def server_and_casemap
\r
207 h[:server] = @server if defined?(@server) and @server
\r
208 h[:casemap] = @casemap if defined?(@casemap) and @casemap
\r
212 # We allow up/downcasing with a different casemap
\r
214 def irc_downcase(cmap=casemap)
\r
215 self.to_s.irc_downcase(cmap)
\r
218 # Up/downcasing something that includes this module returns its
\r
219 # Up/downcased to_s form
\r
225 # We allow up/downcasing with a different casemap
\r
227 def irc_upcase(cmap=casemap)
\r
228 self.to_s.irc_upcase(cmap)
\r
231 # Up/downcasing something that includes this module returns its
\r
232 # Up/downcased to_s form
\r
243 # We start by extending the String class
\r
244 # with some IRC-specific methods
\r
248 # This method returns the Irc::Casemap whose name is the receiver
\r
251 Irc::Casemap.get(self) rescue raise TypeError, "Unkown Irc::Casemap #{self.inspect}"
\r
254 # This method returns a string which is the downcased version of the
\r
255 # receiver, according to the given _casemap_
\r
258 def irc_downcase(casemap='rfc1459')
\r
259 cmap = casemap.to_irc_casemap
\r
260 self.tr(cmap.upper, cmap.lower)
\r
263 # This is the same as the above, except that the string is altered in place
\r
265 # See also the discussion about irc_downcase
\r
267 def irc_downcase!(casemap='rfc1459')
\r
268 cmap = casemap.to_irc_casemap
\r
269 self.tr!(cmap.upper, cmap.lower)
\r
272 # Upcasing functions are provided too
\r
274 # See also the discussion about irc_downcase
\r
276 def irc_upcase(casemap='rfc1459')
\r
277 cmap = casemap.to_irc_casemap
\r
278 self.tr(cmap.lower, cmap.upper)
\r
281 # In-place upcasing
\r
283 # See also the discussion about irc_downcase
\r
285 def irc_upcase!(casemap='rfc1459')
\r
286 cmap = casemap.to_irc_casemap
\r
287 self.tr!(cmap.lower, cmap.upper)
\r
290 # This method checks if the receiver contains IRC glob characters
\r
292 # IRC has a very primitive concept of globs: a <tt>*</tt> stands for "any
\r
293 # number of arbitrary characters", a <tt>?</tt> stands for "one and exactly
\r
294 # one arbitrary character". These characters can be escaped by prefixing them
\r
295 # with a slash (<tt>\\</tt>).
\r
297 # A known limitation of this glob syntax is that there is no way to escape
\r
298 # the escape character itself, so it's not possible to build a glob pattern
\r
299 # where the escape character precedes a glob.
\r
302 self =~ /^[*?]|[^\\][*?]/
\r
305 # This method is used to convert the receiver into a Regular Expression
\r
306 # that matches according to the IRC glob syntax
\r
309 regmask = Regexp.escape(self)
\r
310 regmask.gsub!(/(\\\\)?\\[*?]/) { |m|
\r
319 raise "Unexpected match #{m} when converting #{self}"
\r
322 Regexp.new(regmask)
\r
328 # ArrayOf is a subclass of Array whose elements are supposed to be all
\r
329 # of the same class. This is not intended to be used directly, but rather
\r
330 # to be subclassed as needed (see for example Irc::UserList and Irc::NetmaskList)
\r
332 # Presently, only very few selected methods from Array are overloaded to check
\r
333 # if the new elements are the correct class. An orthodox? method is provided
\r
334 # to check the entire ArrayOf against the appropriate class.
\r
336 class ArrayOf < Array
\r
338 attr_reader :element_class
\r
340 # Create a new ArrayOf whose elements are supposed to be all of type _kl_,
\r
341 # optionally filling it with the elements from the Array argument.
\r
343 def initialize(kl, ar=[])
\r
344 raise TypeError, "#{kl.inspect} must be a class name" unless kl.kind_of?(Class)
\r
346 @element_class = kl
\r
351 raise TypeError, "#{self.class} can only be initialized from an Array"
\r
356 "#<#{self.class}[#{@element_class}]:#{'0x%x' % self.object_id}: #{super}>"
\r
359 # Private method to check the validity of the elements passed to it
\r
360 # and optionally raise an error
\r
362 # TODO should it accept nils as valid?
\r
364 def internal_will_accept?(raising, *els)
\r
366 unless el.kind_of?(@element_class)
\r
367 raise TypeError, "#{el.inspect} is not of class #{@element_class}" if raising
\r
373 private :internal_will_accept?
\r
375 # This method checks if the passed arguments are acceptable for our ArrayOf
\r
377 def will_accept?(*els)
\r
378 internal_will_accept?(false, *els)
\r
381 # This method checks that all elements are of the appropriate class
\r
384 will_accept?(*self)
\r
387 # This method is similar to the above, except that it raises an exception
\r
388 # if the receiver is not valid
\r
391 raise TypeError unless valid?
\r
394 # Overloaded from Array#<<, checks for appropriate class of argument
\r
397 super(el) if internal_will_accept?(true, el)
\r
400 # Overloaded from Array#&, checks for appropriate class of argument elements
\r
404 ArrayOf.new(@element_class, r) if internal_will_accept?(true, *r)
\r
407 # Overloaded from Array#+, checks for appropriate class of argument elements
\r
410 ArrayOf.new(@element_class, super(ar)) if internal_will_accept?(true, *ar)
\r
413 # Overloaded from Array#-, so that an ArrayOf is returned. There is no need
\r
414 # to check the validity of the elements in the argument
\r
417 ArrayOf.new(@element_class, super(ar)) # if internal_will_accept?(true, *ar)
\r
420 # Overloaded from Array#|, checks for appropriate class of argument elements
\r
423 ArrayOf.new(@element_class, super(ar)) if internal_will_accept?(true, *ar)
\r
426 # Overloaded from Array#concat, checks for appropriate class of argument
\r
430 super(ar) if internal_will_accept?(true, *ar)
\r
433 # Overloaded from Array#insert, checks for appropriate class of argument
\r
436 def insert(idx, *ar)
\r
437 super(idx, *ar) if internal_will_accept?(true, *ar)
\r
440 # Overloaded from Array#replace, checks for appropriate class of argument
\r
444 super(ar) if (ar.kind_of?(ArrayOf) && ar.element_class <= @element_class) or internal_will_accept?(true, *ar)
\r
447 # Overloaded from Array#push, checks for appropriate class of argument
\r
451 super(*ar) if internal_will_accept?(true, *ar)
\r
454 # Overloaded from Array#unshift, checks for appropriate class of argument(s)
\r
458 super(el) if internal_will_accept?(true, *els)
\r
462 # Modifying methods which we don't handle yet are made private
\r
464 private :[]=, :collect!, :map!, :fill, :flatten!
\r
472 # A Netmask identifies each user by collecting its nick, username and
\r
473 # hostname in the form <tt>nick!user@host</tt>
\r
475 # Netmasks can also contain glob patterns in any of their components; in
\r
476 # this form they are used to refer to more than a user or to a user
\r
477 # appearing under different forms.
\r
480 # * <tt>*!*@*</tt> refers to everybody
\r
481 # * <tt>*!someuser@somehost</tt> refers to user +someuser+ on host +somehost+
\r
482 # regardless of the nick used.
\r
486 # Netmasks have an associated casemap unless they are bound to a server
\r
488 include ServerOrCasemap
\r
490 attr_reader :nick, :user, :host
\r
492 # Create a new Netmask from string _str_, which must be in the form
\r
493 # _nick_!_user_@_host_
\r
495 # It is possible to specify a server or a casemap in the optional Hash:
\r
496 # these are used to associate the Netmask with the given server and to set
\r
497 # its casemap: if a server is specified and a casemap is not, the server's
\r
498 # casemap is used. If both a server and a casemap are specified, the
\r
499 # casemap must match the server's casemap or an exception will be raised.
\r
501 # Empty +nick+, +user+ or +host+ are converted to the generic glob pattern
\r
503 def initialize(str="", opts={})
\r
504 # First of all, check for server/casemap option
\r
506 init_server_or_casemap(opts)
\r
508 # Now we can see if the given string _str_ is an actual Netmask
\r
509 if str.respond_to?(:to_str)
\r
511 when /^(?:(\S+?)(?:!(\S+)@(?:(\S+))?)?)?$/
\r
512 # We do assignment using our internal methods
\r
517 raise ArgumentError, "#{str.to_str.inspect} does not represent a valid #{self.class}"
\r
520 raise TypeError, "#{str} cannot be converted to a #{self.class}"
\r
524 # A Netmask is easily converted to a String for the usual representation
\r
527 "#{nick}!#{user}@#{host}"
\r
529 alias :to_s :fullform
\r
531 # Converts the receiver into a Netmask with the given (optional)
\r
532 # server/casemap association. We return self unless a conversion
\r
533 # is needed (different casemap/server)
\r
535 # Subclasses of Netmask will return a new Netmask
\r
537 def to_irc_netmask(opts={})
\r
538 if self.class == Netmask
\r
539 return self if fits_with_server_and_casemap?(opts)
\r
541 return self.fullform.to_irc_netmask(server_and_casemap.merge(opts))
\r
544 # Converts the receiver into a User with the given (optional)
\r
545 # server/casemap association. We return self unless a conversion
\r
546 # is needed (different casemap/server)
\r
548 def to_irc_user(opts={})
\r
549 self.fullform.to_irc_user(server_and_casemap.merge(opts))
\r
552 # Inspection of a Netmask reveals the server it's bound to (if there is
\r
553 # one), its casemap and the nick, user and host part
\r
556 str = "<#{self.class}:#{'0x%x' % self.object_id}:"
\r
557 str << " @server=#{@server}" if defined?(@server) and @server
\r
558 str << " @nick=#{@nick.inspect} @user=#{@user.inspect}"
\r
559 str << " @host=#{@host.inspect} casemap=#{casemap.inspect}"
\r
563 # Equality: two Netmasks are equal if they downcase to the same thing
\r
565 # TODO we may want it to try other.to_irc_netmask
\r
568 return false unless other.kind_of?(self.class)
\r
569 self.downcase == other.downcase
\r
572 # This method changes the nick of the Netmask, defaulting to the generic
\r
573 # glob pattern if the result is the null string.
\r
576 @nick = newnick.to_s
\r
577 @nick = "*" if @nick.empty?
\r
580 # This method changes the user of the Netmask, defaulting to the generic
\r
581 # glob pattern if the result is the null string.
\r
584 @user = newuser.to_s
\r
585 @user = "*" if @user.empty?
\r
588 # This method changes the hostname of the Netmask, defaulting to the generic
\r
589 # glob pattern if the result is the null string.
\r
592 @host = newhost.to_s
\r
593 @host = "*" if @host.empty?
\r
596 # We can replace everything at once with data from another Netmask
\r
604 @server = other.server
\r
605 @casemap = other.casemap unless @server
\r
607 replace(other.to_irc_netmask(server_and_casemap))
\r
611 # This method checks if a Netmask is definite or not, by seeing if
\r
612 # any of its components are defined by globs
\r
615 return @nick.has_irc_glob? || @user.has_irc_glob? || @host.has_irc_glob?
\r
618 # This method is used to match the current Netmask against another one
\r
620 # The method returns true if each component of the receiver matches the
\r
621 # corresponding component of the argument. By _matching_ here we mean
\r
622 # that any netmask described by the receiver is also described by the
\r
625 # In this sense, matching is rather simple to define in the case when the
\r
626 # receiver has no globs: it is just necessary to check if the argument
\r
627 # describes the receiver, which can be done by matching it against the
\r
628 # argument converted into an IRC Regexp (see String#to_irc_regexp).
\r
630 # The situation is also easy when the receiver has globs and the argument
\r
631 # doesn't, since in this case the result is false.
\r
633 # The more complex case in which both the receiver and the argument have
\r
634 # globs is not handled yet.
\r
637 cmp = arg.to_irc_netmask(:casemap => casemap)
\r
638 debug "Matching #{self.fullform} against #{arg.fullform}"
\r
639 [:nick, :user, :host].each { |component|
\r
640 us = self.send(component).irc_downcase(casemap)
\r
641 them = cmp.send(component).irc_downcase(casemap)
\r
642 if us.has_irc_glob? && them.has_irc_glob?
\r
644 warn NotImplementedError
\r
647 return false if us.has_irc_glob? && !them.has_irc_glob?
\r
648 return false unless us =~ them.to_irc_regexp
\r
653 # Case equality. Checks if arg matches self
\r
656 arg.to_irc_netmask(:casemap => casemap).matches?(self)
\r
659 # Sorting is done via the fullform
\r
664 self.fullform.irc_downcase(casemap) <=> arg.fullform.irc_downcase(casemap)
\r
666 self.downcase <=> arg.downcase
\r
673 # A NetmaskList is an ArrayOf <code>Netmask</code>s
\r
675 class NetmaskList < ArrayOf
\r
677 # Create a new NetmaskList, optionally filling it with the elements from
\r
678 # the Array argument fed to it.
\r
680 def initialize(ar=[])
\r
691 # We keep extending String, this time adding a method that converts a
\r
692 # String into an Irc::Netmask object
\r
694 def to_irc_netmask(opts={})
\r
695 Irc::Netmask.new(self, opts)
\r
704 # An IRC User is identified by his/her Netmask (which must not have globs).
\r
705 # In fact, User is just a subclass of Netmask.
\r
707 # Ideally, the user and host information of an IRC User should never
\r
708 # change, and it shouldn't contain glob patterns. However, IRC is somewhat
\r
709 # idiosincratic and it may be possible to know the nick of a User much before
\r
710 # its user and host are known. Moreover, some networks (namely Freenode) may
\r
711 # change the hostname of a User when (s)he identifies with Nickserv.
\r
713 # As a consequence, we must allow changes to a User host and user attributes.
\r
714 # We impose a restriction, though: they may not contain glob patterns, except
\r
715 # for the special case of an unknown user/host which is represented by a *.
\r
717 # It is possible to create a totally unknown User (e.g. for initializations)
\r
718 # by setting the nick to * too.
\r
721 # * see if it's worth to add the other USER data
\r
722 # * see if it's worth to add NICKSERV status
\r
724 class User < Netmask
\r
727 # Create a new IRC User from a given Netmask (or anything that can be converted
\r
728 # into a Netmask) provided that the given Netmask does not have globs.
\r
730 def initialize(str="", opts={})
\r
732 raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if nick.has_irc_glob? && nick != "*"
\r
733 raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if user.has_irc_glob? && user != "*"
\r
734 raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if host.has_irc_glob? && host != "*"
\r
738 # The nick of a User may be changed freely, but it must not contain glob patterns.
\r
741 raise "Can't change the nick to #{newnick}" if defined?(@nick) and newnick.has_irc_glob?
\r
745 # We have to allow changing the user of an Irc User due to some networks
\r
746 # (e.g. Freenode) changing hostmasks on the fly. We still check if the new
\r
747 # user data has glob patterns though.
\r
750 raise "Can't change the username to #{newuser}" if defined?(@user) and newuser.has_irc_glob?
\r
754 # We have to allow changing the host of an Irc User due to some networks
\r
755 # (e.g. Freenode) changing hostmasks on the fly. We still check if the new
\r
756 # host data has glob patterns though.
\r
759 raise "Can't change the hostname to #{newhost}" if defined?(@host) and newhost.has_irc_glob?
\r
763 # Checks if a User is well-known or not by looking at the hostname and user
\r
766 return nick!= "*" && user!="*" && host!="*"
\r
769 # Is the user away?
\r
775 # Set the away status of the user. Use away=(nil) or away=(false)
\r
786 # Since to_irc_user runs the same checks on server and channel as
\r
787 # to_irc_netmask, we just try that and return self if it works.
\r
789 # Subclasses of User will return self if possible.
\r
791 def to_irc_user(opts={})
\r
792 return self if fits_with_server_and_casemap?(opts)
\r
793 return self.fullform.to_irc_user(server_and_casemap(opts))
\r
796 # We can replace everything at once with data from another User
\r
801 self.nick = other.nick
\r
802 self.user = other.user
\r
803 self.host = other.host
\r
804 @server = other.server
\r
805 @casemap = other.casemap unless @server
\r
806 @away = other.away?
\r
808 self.replace(other.to_irc_user(server_and_casemap))
\r
815 # A UserList is an ArrayOf <code>User</code>s
\r
817 class UserList < ArrayOf
\r
819 # Create a new UserList, optionally filling it with the elements from
\r
820 # the Array argument fed to it.
\r
822 def initialize(ar=[])
\r
832 # We keep extending String, this time adding a method that converts a
\r
833 # String into an Irc::User object
\r
835 def to_irc_user(opts={})
\r
836 Irc::User.new(self, opts)
\r
843 # An IRC Channel is identified by its name, and it has a set of properties:
\r
844 # * a Channel::Topic
\r
846 # * a set of Channel::Modes
\r
848 # The Channel::Topic and Channel::Mode classes are defined within the
\r
849 # Channel namespace because they only make sense there
\r
854 # Mode on a Channel
\r
864 # Channel modes of type A manipulate lists
\r
866 # Example: b (banlist)
\r
868 class ModeTypeA < Mode
\r
871 @list = NetmaskList.new
\r
875 nm = @channel.server.new_netmask(val)
\r
876 @list << nm unless @list.include?(nm)
\r
880 nm = @channel.server.new_netmask(val)
\r
887 # Channel modes of type B need an argument
\r
891 class ModeTypeB < Mode
\r
902 @arg = nil if @arg == val
\r
908 # Channel modes that change the User prefixes are like
\r
909 # Channel modes of type B, except that they manipulate
\r
910 # lists of Users, so they are somewhat similar to channel
\r
913 class UserMode < ModeTypeB
\r
916 @list = UserList.new
\r
920 u = @channel.server.user(val)
\r
921 @list << u unless @list.include?(u)
\r
925 u = @channel.server.user(val)
\r
932 # Channel modes of type C need an argument when set,
\r
933 # but not when they get reset
\r
935 # Example: l (limit)
\r
937 class ModeTypeC < Mode
\r
958 # Channel modes of type D are basically booleans
\r
960 # Example: m (moderate)
\r
962 class ModeTypeD < Mode
\r
983 # A Topic represents the topic of a channel. It consists of
\r
984 # the topic itself, who set it and when
\r
987 attr_accessor :text, :set_by, :set_on
\r
990 # Create a new Topic setting the text, the creator and
\r
991 # the creation time
\r
993 def initialize(text="", set_by="", set_on=Time.new)
\r
995 @set_by = set_by.to_irc_user
\r
999 # Replace a Topic with another one
\r
1001 def replace(topic)
\r
1002 raise TypeError, "#{topic.inspect} is not of class #{self.class}" unless topic.kind_of?(self.class)
\r
1003 @text = topic.text.dup
\r
1004 @set_by = topic.set_by.dup
\r
1005 @set_on = topic.set_on.dup
\r
1010 def to_irc_channel_topic
\r
1023 # Returns an Irc::Channel::Topic with self as text
\r
1025 def to_irc_channel_topic
\r
1026 Irc::Channel::Topic.new(self)
\r
1035 # Here we start with the actual Channel class
\r
1039 include ServerOrCasemap
\r
1040 attr_reader :name, :topic, :mode, :users
\r
1044 str = "<#{self.class}:#{'0x%x' % self.object_id}:"
\r
1045 str << " on server #{server}" if server
\r
1046 str << " @name=#{@name.inspect} @topic=#{@topic.text.inspect}"
\r
1047 str << " @users=[#{user_nicks.sort.join(', ')}]"
\r
1053 def to_irc_channel
\r
1059 @users.map { |u| u.downcase }
\r
1062 # Checks if the receiver already has a user with the given _nick_
\r
1064 def has_user?(nick)
\r
1065 user_nicks.index(nick.irc_downcase(casemap))
\r
1068 # Returns the user with nick _nick_, if available
\r
1070 def get_user(nick)
\r
1071 idx = has_user?(nick)
\r
1072 @users[idx] if idx
\r
1075 # Adds a user to the channel
\r
1077 def add_user(user, opts={})
\r
1078 silent = opts.fetch(:silent, false)
\r
1079 if has_user?(user) && !silent
\r
1080 warn "Trying to add user #{user} to channel #{self} again"
\r
1082 @users << user.to_irc_user(server_and_casemap)
\r
1086 # Creates a new channel with the given name, optionally setting the topic
\r
1087 # and an initial users list.
\r
1089 # No additional info is created here, because the channel flags and userlists
\r
1090 # allowed depend on the server.
\r
1092 def initialize(name, topic=nil, users=[], opts={})
\r
1093 raise ArgumentError, "Channel name cannot be empty" if name.to_s.empty?
\r
1094 warn "Unknown channel prefix #{name[0].chr}" if name !~ /^[&#+!]/
\r
1095 raise ArgumentError, "Invalid character in #{name.inspect}" if name =~ /[ \x07,]/
\r
1097 init_server_or_casemap(opts)
\r
1101 @topic = (topic.to_irc_channel_topic rescue Channel::Topic.new)
\r
1103 @users = UserList.new
\r
1113 # Removes a user from the channel
\r
1115 def delete_user(user)
\r
1116 @mode.each { |sym, mode|
\r
1117 mode.reset(user) if mode.kind_of?(UserMode)
\r
1119 @users.delete(user)
\r
1122 # The channel prefix
\r
1128 # A channel is local to a server if it has the '&' prefix
\r
1134 # A channel is modeless if it has the '+' prefix
\r
1140 # A channel is safe if it has the '!' prefix
\r
1146 # A channel is normal if it has the '#' prefix
\r
1152 # Create a new mode
\r
1154 def create_mode(sym, kl)
\r
1155 @mode[sym.to_sym] = kl.new(self)
\r
1161 # A ChannelList is an ArrayOf <code>Channel</code>s
\r
1163 class ChannelList < ArrayOf
\r
1165 # Create a new ChannelList, optionally filling it with the elements from
\r
1166 # the Array argument fed to it.
\r
1168 def initialize(ar=[])
\r
1169 super(Channel, ar)
\r
1179 # We keep extending String, this time adding a method that converts a
\r
1180 # String into an Irc::Channel object
\r
1182 def to_irc_channel(opts={})
\r
1183 Irc::Channel.new(self, opts)
\r
1192 # An IRC Server represents the Server the client is connected to.
\r
1196 attr_reader :hostname, :version, :usermodes, :chanmodes
\r
1197 alias :to_s :hostname
\r
1198 attr_reader :supports, :capabilities
\r
1200 attr_reader :channels, :users
\r
1204 @channels.map { |ch| ch.downcase }
\r
1209 @users.map { |u| u.downcase }
\r
1213 chans, users = [@channels, @users].map {|d|
\r
1215 a.downcase <=> b.downcase
\r
1221 str = "<#{self.class}:#{'0x%x' % self.object_id}:"
\r
1222 str << " @hostname=#{hostname}"
\r
1223 str << " @channels=#{chans}"
\r
1224 str << " @users=#{users}"
\r
1228 # Create a new Server, with all instance variables reset to nil (for
\r
1229 # scalar variables), empty channel and user lists and @supports
\r
1230 # initialized to the default values for all known supported features.
\r
1233 @hostname = @version = @usermodes = @chanmodes = nil
\r
1235 @channels = ChannelList.new
\r
1237 @users = UserList.new
\r
1239 reset_capabilities
\r
1242 # Resets the server capabilities
\r
1244 def reset_capabilities
\r
1246 :casemapping => 'rfc1459'.to_irc_casemap,
\r
1249 :typea => nil, # Type A: address lists
\r
1250 :typeb => nil, # Type B: needs a parameter
\r
1251 :typec => nil, # Type C: needs a parameter when set
\r
1252 :typed => nil # Type D: must not have a parameter
\r
1254 :channellen => 200,
\r
1255 :chantypes => "#&",
\r
1265 :modes => 'ov'.scan(/./),
\r
1266 :prefixes => '@+'.scan(/./)
\r
1269 :statusmsg => nil,
\r
1274 @capabilities = {}
\r
1277 # Resets the Channel and User list
\r
1283 @channels.each { |u|
\r
1288 # Clears the server
\r
1292 reset_capabilities
\r
1295 # This method is used to parse a 004 RPL_MY_INFO line
\r
1297 def parse_my_info(line)
\r
1298 ar = line.split(' ')
\r
1301 @usermodes = ar[2]
\r
1302 @chanmodes = ar[3]
\r
1305 def noval_warn(key, val, &block)
\r
1307 yield if block_given?
\r
1309 warn "No #{key.to_s.upcase} value"
\r
1313 def val_warn(key, val, &block)
\r
1314 if val == true or val == false or val.nil?
\r
1315 yield if block_given?
\r
1317 warn "No #{key.to_s.upcase} value must be specified, got #{val}"
\r
1320 private :noval_warn, :val_warn
\r
1322 # This method is used to parse a 005 RPL_ISUPPORT line
\r
1324 # See the RPL_ISUPPORT draft[http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt]
\r
1326 def parse_isupport(line)
\r
1327 debug "Parsing ISUPPORT #{line.inspect}"
\r
1328 ar = line.split(' ')
\r
1331 prekey, val = en.split('=', 2)
\r
1332 if prekey =~ /^-(.*)/
\r
1333 key = $1.downcase.to_sym
\r
1336 key = prekey.downcase.to_sym
\r
1340 noval_warn(key, val) {
\r
1341 @supports[key] = val.to_irc_casemap
\r
1343 when :chanlimit, :idchan, :maxlist, :targmax
\r
1344 noval_warn(key, val) {
\r
1345 groups = val.split(',')
\r
1347 k, v = g.split(':')
\r
1348 @supports[key][k] = v.to_i || 0
\r
1352 noval_warn(key, val) {
\r
1353 groups = val.split(',')
\r
1354 @supports[key][:typea] = groups[0].scan(/./).map { |x| x.to_sym}
\r
1355 @supports[key][:typeb] = groups[1].scan(/./).map { |x| x.to_sym}
\r
1356 @supports[key][:typec] = groups[2].scan(/./).map { |x| x.to_sym}
\r
1357 @supports[key][:typed] = groups[3].scan(/./).map { |x| x.to_sym}
\r
1359 when :channellen, :kicklen, :modes, :topiclen
\r
1361 @supports[key] = val.to_i
\r
1363 @supports[key] = nil
\r
1366 @supports[key] = val # can also be nil
\r
1369 @supports[key] = val
\r
1372 @supports[key] = val
\r
1374 noval_warn(key, val) {
\r
1375 reparse += "CHANLIMIT=(chantypes):#{val} "
\r
1378 noval_warn(key, val) {
\r
1379 @supports[:targmax]['PRIVMSG'] = val.to_i
\r
1380 @supports[:targmax]['NOTICE'] = val.to_i
\r
1383 noval_warn(key, val) {
\r
1384 @supports[key] = val
\r
1387 noval_warn(key, val) {
\r
1388 @supports[key] = val.to_i
\r
1392 val.scan(/\((.*)\)(.*)/) { |m, p|
\r
1393 @supports[key][:modes] = m.scan(/./).map { |x| x.to_sym}
\r
1394 @supports[key][:prefixes] = p.scan(/./).map { |x| x.to_sym}
\r
1397 @supports[key][:modes] = nil
\r
1398 @supports[key][:prefixes] = nil
\r
1401 val_warn(key, val) {
\r
1402 @supports[key] = val.nil? ? true : val
\r
1405 noval_warn(key, val) {
\r
1406 @supports[key] = val.scan(/./)
\r
1409 noval_warn(key, val) {
\r
1410 @supports[key] = val.split(',')
\r
1413 @supports[key] = val.nil? ? true : val
\r
1416 reparse.gsub!("(chantypes)",@supports[:chantypes])
\r
1417 parse_isupport(reparse) unless reparse.empty?
\r
1420 # Returns the casemap of the server.
\r
1423 @supports[:casemapping]
\r
1426 # Returns User or Channel depending on what _name_ can be
\r
1429 def user_or_channel?(name)
\r
1430 if supports[:chantypes].include?(name[0])
\r
1437 # Returns the actual User or Channel object matching _name_
\r
1439 def user_or_channel(name)
\r
1440 if supports[:chantypes].include?(name[0])
\r
1441 return channel(name)
\r
1447 # Checks if the receiver already has a channel with the given _name_
\r
1449 def has_channel?(name)
\r
1450 return false if name.nil_or_empty?
\r
1451 channel_names.index(name.irc_downcase(casemap))
\r
1453 alias :has_chan? :has_channel?
\r
1455 # Returns the channel with name _name_, if available
\r
1457 def get_channel(name)
\r
1458 return nil if name.nil_or_empty?
\r
1459 idx = has_channel?(name)
\r
1460 channels[idx] if idx
\r
1462 alias :get_chan :get_channel
\r
1464 # Create a new Channel object bound to the receiver and add it to the
\r
1465 # list of <code>Channel</code>s on the receiver, unless the channel was
\r
1466 # present already. In this case, the default action is to raise an
\r
1467 # exception, unless _fails_ is set to false. An exception can also be
\r
1468 # raised if _str_ is nil or empty, again only if _fails_ is set to true;
\r
1469 # otherwise, the method just returns nil
\r
1471 def new_channel(name, topic=nil, users=[], fails=true)
\r
1472 if name.nil_or_empty?
\r
1473 raise "Tried to look for empty or nil channel name #{name.inspect}" if fails
\r
1476 ex = get_chan(name)
\r
1478 raise "Channel #{name} already exists on server #{self}" if fails
\r
1482 prefix = name[0].chr
\r
1484 # Give a warning if the new Channel goes over some server limits.
\r
1486 # FIXME might need to raise an exception
\r
1488 warn "#{self} doesn't support channel prefix #{prefix}" unless @supports[:chantypes].include?(prefix)
\r
1489 warn "#{self} doesn't support channel names this long (#{name.length} > #{@supports[:channellen]})" unless name.length <= @supports[:channellen]
\r
1491 # Next, we check if we hit the limit for channels of type +prefix+
\r
1492 # if the server supports +chanlimit+
\r
1494 @supports[:chanlimit].keys.each { |k|
\r
1495 next unless k.include?(prefix)
\r
1497 channel_names.each { |n|
\r
1498 count += 1 if k.include?(n[0])
\r
1500 raise IndexError, "Already joined #{count} channels with prefix #{k}" if count == @supports[:chanlimit][k]
\r
1503 # So far, everything is fine. Now create the actual Channel
\r
1505 chan = Channel.new(name, topic, users, :server => self)
\r
1507 # We wade through +prefix+ and +chanmodes+ to create appropriate
\r
1508 # lists and flags for this channel
\r
1510 @supports[:prefix][:modes].each { |mode|
\r
1511 chan.create_mode(mode, Channel::UserMode)
\r
1512 } if @supports[:prefix][:modes]
\r
1514 @supports[:chanmodes].each { |k, val|
\r
1519 chan.create_mode(mode, Channel::ModeTypeA)
\r
1523 chan.create_mode(mode, Channel::ModeTypeB)
\r
1527 chan.create_mode(mode, Channel::ModeTypeC)
\r
1531 chan.create_mode(mode, Channel::ModeTypeD)
\r
1538 # debug "Created channel #{chan.inspect}"
\r
1543 # Returns the Channel with the given _name_ on the server,
\r
1544 # creating it if necessary. This is a short form for
\r
1545 # new_channel(_str_, nil, [], +false+)
\r
1548 new_channel(str,nil,[],false)
\r
1551 # Remove Channel _name_ from the list of <code>Channel</code>s
\r
1553 def delete_channel(name)
\r
1554 idx = has_channel?(name)
\r
1555 raise "Tried to remove unmanaged channel #{name}" unless idx
\r
1556 @channels.delete_at(idx)
\r
1559 # Checks if the receiver already has a user with the given _nick_
\r
1561 def has_user?(nick)
\r
1562 return false if nick.nil_or_empty?
\r
1563 user_nicks.index(nick.irc_downcase(casemap))
\r
1566 # Returns the user with nick _nick_, if available
\r
1568 def get_user(nick)
\r
1569 idx = has_user?(nick)
\r
1570 @users[idx] if idx
\r
1573 # Create a new User object bound to the receiver and add it to the list
\r
1574 # of <code>User</code>s on the receiver, unless the User was present
\r
1575 # already. In this case, the default action is to raise an exception,
\r
1576 # unless _fails_ is set to false. An exception can also be raised
\r
1577 # if _str_ is nil or empty, again only if _fails_ is set to true;
\r
1578 # otherwise, the method just returns nil
\r
1580 def new_user(str, fails=true)
\r
1581 if str.nil_or_empty?
\r
1582 raise "Tried to look for empty or nil user name #{str.inspect}" if fails
\r
1585 tmp = str.to_irc_user(:server => self)
\r
1586 old = get_user(tmp.nick)
\r
1587 # debug "Tmp: #{tmp.inspect}"
\r
1588 # debug "Old: #{old.inspect}"
\r
1590 # debug "User already existed as #{old.inspect}"
\r
1593 # debug "Both were known"
\r
1594 # Do not raise an error: things like Freenode change the hostname after identification
\r
1595 warning "User #{tmp.nick} has inconsistent Netmasks! #{self} knows #{old.inspect} but access was tried with #{tmp.inspect}" if old != tmp
\r
1596 raise "User #{tmp} already exists on server #{self}" if fails
\r
1598 if old.fullform.downcase != tmp.fullform.downcase
\r
1600 # debug "Known user now #{old.inspect}"
\r
1605 warn "#{self} doesn't support nicknames this long (#{tmp.nick.length} > #{@supports[:nicklen]})" unless tmp.nick.length <= @supports[:nicklen]
\r
1607 return @users.last
\r
1611 # Returns the User with the given Netmask on the server,
\r
1612 # creating it if necessary. This is a short form for
\r
1613 # new_user(_str_, +false+)
\r
1616 new_user(str, false)
\r
1619 # Deletes User _user_ from Channel _channel_
\r
1621 def delete_user_from_channel(user, channel)
\r
1622 channel.delete_user(user)
\r
1625 # Remove User _someuser_ from the list of <code>User</code>s.
\r
1626 # _someuser_ must be specified with the full Netmask.
\r
1628 def delete_user(someuser)
\r
1629 idx = has_user?(someuser)
\r
1630 raise "Tried to remove unmanaged user #{user}" unless idx
\r
1631 have = self.user(someuser)
\r
1632 @channels.each { |ch|
\r
1633 delete_user_from_channel(have, ch)
\r
1635 @users.delete_at(idx)
\r
1638 # Create a new Netmask object with the appropriate casemap
\r
1640 def new_netmask(str)
\r
1641 str.to_irc_netmask(:server => self)
\r
1644 # Finds all <code>User</code>s on server whose Netmask matches _mask_
\r
1646 def find_users(mask)
\r
1647 nm = new_netmask(mask)
\r
1648 @users.inject(UserList.new) {
\r
1650 if user.user == "*" or user.host == "*"
\r
1651 list << user if user.nick.irc_downcase(casemap) =~ nm.nick.irc_downcase(casemap).to_irc_regexp
\r
1653 list << user if user.matches?(nm)
\r