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 # FIXME for the time being, we do it with a method that scans the server
8 # (if defined), so the method is slow and should not be used frequently.
9 # * Maybe ChannelList and UserList should be HashesOf instead of ArrayOf?
10 # See items marked as TODO Ho.
11 # The framework to do this is now in place, thanks to the new [] method
12 # for NetmaskList, which allows retrieval by Netmask or String
18 # This module defines the fundamental building blocks for IRC
20 # Author:: Giuseppe Bilotta (giuseppe.bilotta@gmail.com)
24 # We extend the Object class with a method that
25 # checks if the receiver is nil or empty
27 return true unless self
28 return true if self.respond_to? :empty? and self.empty?
32 # We alias the to_s method to __to_s__ to make
33 # it accessible in all classes
37 # The Irc module is used to keep all IRC-related classes
38 # in the same namespace
46 # This method checks if the receiver contains IRC glob characters
48 # IRC has a very primitive concept of globs: a <tt>*</tt> stands for "any
49 # number of arbitrary characters", a <tt>?</tt> stands for "one and exactly
50 # one arbitrary character". These characters can be escaped by prefixing them
51 # with a slash (<tt>\\</tt>).
53 # A known limitation of this glob syntax is that there is no way to escape
54 # the escape character itself, so it's not possible to build a glob pattern
55 # where the escape character precedes a glob.
58 self =~ /^[*?]|[^\\][*?]/
61 # This method is used to convert the receiver into a Regular Expression
62 # that matches according to the IRC glob syntax
65 regmask = Regexp.escape(self)
66 regmask.gsub!(/(\\\\)?\\[*?]/) { |m|
75 raise "Unexpected match #{m} when converting #{self}"
78 Regexp.new("^#{regmask}$")
83 # ArrayOf is a subclass of Array whose elements are supposed to be all
84 # of the same class. This is not intended to be used directly, but rather
85 # to be subclassed as needed (see for example Irc::UserList and Irc::NetmaskList)
87 # Presently, only very few selected methods from Array are overloaded to check
88 # if the new elements are the correct class. An orthodox? method is provided
89 # to check the entire ArrayOf against the appropriate class.
93 attr_reader :element_class
95 # Create a new ArrayOf whose elements are supposed to be all of type _kl_,
96 # optionally filling it with the elements from the Array argument.
98 def initialize(kl, ar=[])
99 raise TypeError, "#{kl.inspect} must be a class name" unless kl.kind_of?(Class)
106 raise TypeError, "#{self.class} can only be initialized from an Array"
111 self.__to_s__[0..-2].sub(/:[^:]+$/,"[#{@element_class}]\\0") + " #{super}>"
114 # Private method to check the validity of the elements passed to it
115 # and optionally raise an error
117 # TODO should it accept nils as valid?
119 def internal_will_accept?(raising, *els)
121 unless el.kind_of?(@element_class)
122 raise TypeError, "#{el.inspect} is not of class #{@element_class}" if raising
128 private :internal_will_accept?
130 # This method checks if the passed arguments are acceptable for our ArrayOf
132 def will_accept?(*els)
133 internal_will_accept?(false, *els)
136 # This method checks that all elements are of the appropriate class
142 # This method is similar to the above, except that it raises an exception
143 # if the receiver is not valid
146 raise TypeError unless valid?
149 # Overloaded from Array#<<, checks for appropriate class of argument
152 super(el) if internal_will_accept?(true, el)
155 # Overloaded from Array#&, checks for appropriate class of argument elements
159 ArrayOf.new(@element_class, r) if internal_will_accept?(true, *r)
162 # Overloaded from Array#+, checks for appropriate class of argument elements
165 ArrayOf.new(@element_class, super(ar)) if internal_will_accept?(true, *ar)
168 # Overloaded from Array#-, so that an ArrayOf is returned. There is no need
169 # to check the validity of the elements in the argument
172 ArrayOf.new(@element_class, super(ar)) # if internal_will_accept?(true, *ar)
175 # Overloaded from Array#|, checks for appropriate class of argument elements
178 ArrayOf.new(@element_class, super(ar)) if internal_will_accept?(true, *ar)
181 # Overloaded from Array#concat, checks for appropriate class of argument
185 super(ar) if internal_will_accept?(true, *ar)
188 # Overloaded from Array#insert, checks for appropriate class of argument
192 super(idx, *ar) if internal_will_accept?(true, *ar)
195 # Overloaded from Array#replace, checks for appropriate class of argument
199 super(ar) if (ar.kind_of?(ArrayOf) && ar.element_class <= @element_class) or internal_will_accept?(true, *ar)
202 # Overloaded from Array#push, checks for appropriate class of argument
206 super(*ar) if internal_will_accept?(true, *ar)
209 # Overloaded from Array#unshift, checks for appropriate class of argument(s)
213 super(el) if internal_will_accept?(true, *els)
217 # We introduce the 'downcase' method, which maps downcase() to all the Array
218 # elements, properly failing when the elements don't have a downcase method
221 self.map { |el| el.downcase }
224 # Modifying methods which we don't handle yet are made private
226 private :[]=, :collect!, :map!, :fill, :flatten!
231 # We extend the Regexp class with an Irc module which will contain some
232 # Irc-specific regexps
236 # We start with some general-purpose ones which will be used in the
237 # Irc module too, but are useful regardless
239 HEX_DIGIT = /[0-9A-Fa-f]/
240 HEX_DIGITS = /#{HEX_DIGIT}+/
241 HEX_OCTET = /#{HEX_DIGIT}#{HEX_DIGIT}?/
242 DEC_OCTET = /[01]?\d?\d|2[0-4]\d|25[0-5]/
243 DEC_IP_ADDR = /#{DEC_OCTET}\.#{DEC_OCTET}\.#{DEC_OCTET}\.#{DEC_OCTET}/
244 HEX_IP_ADDR = /#{HEX_OCTET}\.#{HEX_OCTET}\.#{HEX_OCTET}\.#{HEX_OCTET}/
245 IP_ADDR = /#{DEC_IP_ADDR}|#{HEX_IP_ADDR}/
247 # IPv6, from Resolv::IPv6, without the \A..\z anchors
248 HEX_16BIT = /#{HEX_DIGIT}{1,4}/
249 IP6_8Hex = /(?:#{HEX_16BIT}:){7}#{HEX_16BIT}/
250 IP6_CompressedHex = /((?:#{HEX_16BIT}(?::#{HEX_16BIT})*)?)::((?:#{HEX_16BIT}(?::#{HEX_16BIT})*)?)/
251 IP6_6Hex4Dec = /((?:#{HEX_16BIT}:){6,6})#{DEC_IP_ADDR}/
252 IP6_CompressedHex4Dec = /((?:#{HEX_16BIT}(?::#{HEX_16BIT})*)?)::((?:#{HEX_16BIT}:)*)#{DEC_IP_ADDR}/
253 IP6_ADDR = /(?:#{IP6_8Hex})|(?:#{IP6_CompressedHex})|(?:#{IP6_6Hex4Dec})|(?:#{IP6_CompressedHex4Dec})/
255 # We start with some IRC related regular expressions, used to match
256 # Irc::User nicks and users and Irc::Channel names
258 # For each of them we define two versions of the regular expression:
259 # * a generic one, which should match for any server but may turn out to
260 # match more than a specific server would accept
261 # * an RFC-compliant matcher
265 # Channel-name-matching regexps
267 CHAN_SAFE = /![A-Z0-9]{5}/
268 CHAN_ANY = /[^\x00\x07\x0A\x0D ,:]/
269 GEN_CHAN = /(?:#{CHAN_FIRST}|#{CHAN_SAFE})#{CHAN_ANY}+/
270 RFC_CHAN = /#{CHAN_FIRST}#{CHAN_ANY}{1,49}|#{CHAN_SAFE}#{CHAN_ANY}{1,44}/
272 # Nick-matching regexps
273 SPECIAL_CHAR = /[\x5b-\x60\x7b-\x7d]/
274 NICK_FIRST = /#{SPECIAL_CHAR}|[[:alpha:]]/
275 NICK_ANY = /#{SPECIAL_CHAR}|[[:alnum:]]|-/
276 GEN_NICK = /#{NICK_FIRST}#{NICK_ANY}+/
277 RFC_NICK = /#{NICK_FIRST}#{NICK_ANY}{0,8}/
279 USER_CHAR = /[^\x00\x0a\x0d @]/
280 GEN_USER = /#{USER_CHAR}+/
282 # Host-matching regexps
283 HOSTNAME_COMPONENT = /[[:alnum:]](?:[[:alnum:]]|-)*[[:alnum:]]*/
284 HOSTNAME = /#{HOSTNAME_COMPONENT}(?:\.#{HOSTNAME_COMPONENT})*/
285 HOSTADDR = /#{IP_ADDR}|#{IP6_ADDR}/
287 GEN_HOST = /#{HOSTNAME}|#{HOSTADDR}/
289 # # FreeNode network replaces the host of affiliated users with
291 # # FIXME we need the true syntax to match it properly ...
292 # PDPC_HOST_PART = /[0-9A-Za-z.-]+/
293 # PDPC_HOST = /#{PDPC_HOST_PART}(?:\/#{PDPC_HOST_PART})+/
295 # # NOTE: the final optional and non-greedy dot is needed because some
296 # # servers (e.g. FreeNode) send the hostname of the services as "services."
297 # # which is not RFC compliant, but sadly done.
298 # GEN_HOST_EXT = /#{PDPC_HOST}|#{GEN_HOST}\.??/
300 # Sadly, different networks have different, RFC-breaking ways of cloaking
301 # the actualy host address: see above for an example to handle FreeNode.
302 # Another example would be Azzurra, wich also inserts a "=" in the
303 # cloacked host. So let's just not care about this and go with the simplest
307 # User-matching Regexp
308 GEN_USER_ID = /(#{GEN_NICK})(?:(?:!(#{GEN_USER}))?@(#{GEN_HOST_EXT}))?/
310 # Things such has the BIP proxy send invalid nicks in a complete netmask,
311 # so we want to match this, rather: this matches either a compliant nick
312 # or a a string with a very generic nick, a very generic hostname after an
313 # @ sign, and an optional user after a !
314 BANG_AT = /#{GEN_NICK}|\S+?(?:!\S+?)?@\S+?/
316 # # For Netmask, we want to allow wildcards * and ? in the nick
317 # # (they are already allowed in the user and host part
318 # GEN_NICK_MASK = /(?:#{NICK_FIRST}|[?*])?(?:#{NICK_ANY}|[?*])+/
320 # # Netmask-matching Regexp
321 # GEN_MASK = /(#{GEN_NICK_MASK})(?:(?:!(#{GEN_USER}))?@(#{GEN_HOST_EXT}))?/
331 # A Netmask identifies each user by collecting its nick, username and
332 # hostname in the form <tt>nick!user@host</tt>
334 # Netmasks can also contain glob patterns in any of their components; in
335 # this form they are used to refer to more than a user or to a user
336 # appearing under different forms.
339 # * <tt>*!*@*</tt> refers to everybody
340 # * <tt>*!someuser@somehost</tt> refers to user +someuser+ on host +somehost+
341 # regardless of the nick used.
345 # Netmasks have an associated casemap unless they are bound to a server
347 include ServerOrCasemap
349 attr_reader :nick, :user, :host
352 # Create a new Netmask from string _str_, which must be in the form
353 # _nick_!_user_@_host_
355 # It is possible to specify a server or a casemap in the optional Hash:
356 # these are used to associate the Netmask with the given server and to set
357 # its casemap: if a server is specified and a casemap is not, the server's
358 # casemap is used. If both a server and a casemap are specified, the
359 # casemap must match the server's casemap or an exception will be raised.
361 # Empty +nick+, +user+ or +host+ are converted to the generic glob pattern
363 def initialize(str="", opts={})
364 # First of all, check for server/casemap option
366 init_server_or_casemap(opts)
368 # Now we can see if the given string _str_ is an actual Netmask
369 if str.respond_to?(:to_str)
371 # We match a pretty generic string, to work around non-compliant
373 when /^(?:(\S+?)(?:(?:!(\S+?))?@(\S+))?)?$/
374 # We do assignment using our internal methods
379 raise ArgumentError, "#{str.to_str.inspect} does not represent a valid #{self.class}"
382 raise TypeError, "#{str} cannot be converted to a #{self.class}"
386 # A Netmask is easily converted to a String for the usual representation.
387 # We skip the user or host parts if they are "*", unless we've been asked
392 ret << "!" << user unless user == "*"
393 ret << "@" << host unless host == "*"
398 "#{nick}!#{user}@#{host}"
401 alias :to_str :fullform
403 # This method downcases the fullform of the netmask. While this may not be
404 # significantly different from the #downcase() method provided by the
405 # ServerOrCasemap mixin, it's significantly different for Netmask
406 # subclasses such as User whose simple downcasing uses the nick only.
408 def full_irc_downcase(cmap=casemap)
409 self.fullform.irc_downcase(cmap)
412 # full_downcase() will return the fullform downcased according to the
416 self.full_irc_downcase
419 # This method returns a new Netmask which is the fully downcased version
422 return self.full_downcase.to_irc_netmask(server_and_casemap)
425 # Converts the receiver into a Netmask with the given (optional)
426 # server/casemap association. We return self unless a conversion
427 # is needed (different casemap/server)
429 # Subclasses of Netmask will return a new Netmask, using full_downcase
431 def to_irc_netmask(opts={})
432 if self.class == Netmask
433 return self if fits_with_server_and_casemap?(opts)
435 return self.full_downcase.to_irc_netmask(server_and_casemap.merge(opts))
438 # Converts the receiver into a User with the given (optional)
439 # server/casemap association. We return self unless a conversion
440 # is needed (different casemap/server)
442 def to_irc_user(opts={})
443 self.fullform.to_irc_user(server_and_casemap.merge(opts))
446 # Inspection of a Netmask reveals the server it's bound to (if there is
447 # one), its casemap and the nick, user and host part
450 str = self.__to_s__[0..-2]
451 str << " @server=#{@server}" if defined?(@server) and @server
452 str << " @nick=#{@nick.inspect} @user=#{@user.inspect}"
453 str << " @host=#{@host.inspect} casemap=#{casemap.inspect}"
457 # Equality: two Netmasks are equal if they downcase to the same thing
459 # TODO we may want it to try other.to_irc_netmask
462 return false unless other.kind_of?(self.class)
463 self.downcase == other.downcase
466 # This method changes the nick of the Netmask, defaulting to the generic
467 # glob pattern if the result is the null string.
471 @nick = "*" if @nick.empty?
474 # This method changes the user of the Netmask, defaulting to the generic
475 # glob pattern if the result is the null string.
479 @user = "*" if @user.empty?
483 # This method changes the hostname of the Netmask, defaulting to the generic
484 # glob pattern if the result is the null string.
488 @host = "*" if @host.empty?
491 # We can replace everything at once with data from another Netmask
499 @server = other.server
500 @casemap = other.casemap unless @server
502 replace(other.to_irc_netmask(server_and_casemap))
506 # This method checks if a Netmask is definite or not, by seeing if
507 # any of its components are defined by globs
510 return @nick.has_irc_glob? || @user.has_irc_glob? || @host.has_irc_glob?
515 unless u.has_irc_glob?
516 u.sub!(/^[in]=/, '=') or u.sub!(/^\W(\w+)/, '\1')
521 unless h.has_irc_glob?
523 h.sub!(/x-\w+$/, 'x-*')
525 h.match(/^[^\.]+\.[^\.]+$/) or
526 h.sub!(/azzurra[=-][0-9a-f]+/i, '*') or # hello, azzurra, you suck!
527 h.sub!(/^(\d+\.\d+\.\d+\.)\d+$/, '\1*') or
528 h.sub!(/^[^\.]+\./, '*.')
531 return Netmask.new("*!#{u}@#{h}", server_and_casemap)
534 # This method is used to match the current Netmask against another one
536 # The method returns true if each component of the receiver matches the
537 # corresponding component of the argument. By _matching_ here we mean
538 # that any netmask described by the receiver is also described by the
541 # In this sense, matching is rather simple to define in the case when the
542 # receiver has no globs: it is just necessary to check if the argument
543 # describes the receiver, which can be done by matching it against the
544 # argument converted into an IRC Regexp (see String#to_irc_regexp).
546 # The situation is also easy when the receiver has globs and the argument
547 # doesn't, since in this case the result is false.
549 # The more complex case in which both the receiver and the argument have
550 # globs is not handled yet.
553 cmp = arg.to_irc_netmask(:casemap => casemap)
554 debug "Matching #{self.fullform} against #{arg.inspect} (#{cmp.fullform})"
555 [:nick, :user, :host].each { |component|
556 us = self.send(component).irc_downcase(casemap)
557 them = cmp.send(component).irc_downcase(casemap)
558 if us.has_irc_glob? && them.has_irc_glob?
560 warn NotImplementedError
563 return false if us.has_irc_glob? && !them.has_irc_glob?
564 return false unless us =~ them.to_irc_regexp
569 # Case equality. Checks if arg matches self
572 arg.to_irc_netmask(:casemap => casemap).matches?(self)
575 # Sorting is done via the fullform
580 self.fullform.irc_downcase(casemap) <=> arg.fullform.irc_downcase(casemap)
582 self.downcase <=> arg.downcase
589 # A NetmaskList is an ArrayOf <code>Netmask</code>s
591 class NetmaskList < ArrayOf
593 # Create a new NetmaskList, optionally filling it with the elements from
594 # the Array argument fed to it.
596 def initialize(ar=[])
600 # We enhance the [] method by allowing it to pick an element that matches
601 # a given Netmask, a String or a Regexp
602 # TODO take into consideration the opportunity to use select() instead of
603 # find(), and/or a way to let the user choose which one to take (second
611 mask.matches?(args[0])
615 mask.matches?(args[0].to_irc_netmask(:casemap => mask.casemap))
619 mask.fullform =~ args[0]
636 # We keep extending String, this time adding a method that converts a
637 # String into an Irc::Netmask object
639 def to_irc_netmask(opts={})
640 Irc::Netmask.new(self, opts)
649 # An IRC User is identified by his/her Netmask (which must not have globs).
650 # In fact, User is just a subclass of Netmask.
652 # Ideally, the user and host information of an IRC User should never
653 # change, and it shouldn't contain glob patterns. However, IRC is somewhat
654 # idiosincratic and it may be possible to know the nick of a User much before
655 # its user and host are known. Moreover, some networks (namely Freenode) may
656 # change the hostname of a User when (s)he identifies with Nickserv.
658 # As a consequence, we must allow changes to a User host and user attributes.
659 # We impose a restriction, though: they may not contain glob patterns, except
660 # for the special case of an unknown user/host which is represented by a *.
662 # It is possible to create a totally unknown User (e.g. for initializations)
663 # by setting the nick to * too.
666 # * see if it's worth to add the other USER data
667 # * see if it's worth to add NICKSERV status
672 attr_accessor :real_name, :idle_since, :signon
674 # Create a new IRC User from a given Netmask (or anything that can be converted
675 # into a Netmask) provided that the given Netmask does not have globs.
677 def initialize(str="", opts={})
679 raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if nick.has_irc_glob? && nick != "*"
680 raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if user.has_irc_glob? && user != "*"
681 raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if host.has_irc_glob? && host != "*"
683 @real_name = String.new
688 # The nick of a User may be changed freely, but it must not contain glob patterns.
691 raise "Can't change the nick to #{newnick}" if defined?(@nick) and newnick.has_irc_glob?
695 # We have to allow changing the user of an Irc User due to some networks
696 # (e.g. Freenode) changing hostmasks on the fly. We still check if the new
697 # user data has glob patterns though.
700 raise "Can't change the username to #{newuser}" if defined?(@user) and newuser.has_irc_glob?
704 # We have to allow changing the host of an Irc User due to some networks
705 # (e.g. Freenode) changing hostmasks on the fly. We still check if the new
706 # host data has glob patterns though.
709 raise "Can't change the hostname to #{newhost}" if defined?(@host) and newhost.has_irc_glob?
713 # Checks if a User is well-known or not by looking at the hostname and user
716 return nick != "*" && user != "*" && host != "*"
725 # Set the away status of the user. Use away=(nil) or away=(false)
736 # Since to_irc_user runs the same checks on server and channel as
737 # to_irc_netmask, we just try that and return self if it works.
739 # Subclasses of User will return self if possible.
741 def to_irc_user(opts={})
742 return self if fits_with_server_and_casemap?(opts)
743 return self.full_downcase.to_irc_user(opts)
746 # We can replace everything at once with data from another User
751 self.nick = other.nick
752 self.user = other.user
753 self.host = other.host
754 @server = other.server
755 @casemap = other.casemap unless @server
758 self.replace(other.to_irc_user(server_and_casemap))
762 def modes_on(channel)
765 channel.modes_of(self)
767 return @server.channel(channel).modes_of(self) if @server
768 raise "Can't resolve channel #{channel}"
775 channel.has_op?(self)
777 return @server.channel(channel).has_op?(self) if @server
778 raise "Can't resolve channel #{channel}"
782 def is_voice?(channel)
785 channel.has_voice?(self)
787 return @server.channel(channel).has_voice?(self) if @server
788 raise "Can't resolve channel #{channel}"
794 @server.channels.select { |ch| ch.has_user?(self) }
802 # A UserList is an ArrayOf <code>User</code>s
803 # We derive it from NetmaskList, which allows us to inherit any special
806 class UserList < NetmaskList
808 # Create a new UserList, optionally filling it with the elements from
809 # the Array argument fed to it.
811 def initialize(ar=[])
813 @element_class = User
816 # Convenience method: convert the UserList to a list of nicks. The indices
820 self.map { |user| user.nick }
829 # We keep extending String, this time adding a method that converts a
830 # String into an Irc::User object
832 def to_irc_user(opts={})
833 Irc::User.new(self, opts)
840 # An IRC Channel is identified by its name, and it has a set of properties:
843 # * a set of Channel::Modes
845 # The Channel::Topic and Channel::Mode classes are defined within the
846 # Channel namespace because they only make sense there
861 # Hash of modes. Subclass of Hash that defines any? and all?
862 # to check if boolean modes (Type D) are set
863 class ModeHash < Hash
865 !!ar.find { |m| s = m.to_sym ; self[s] && self[s].set? }
868 !ar.find { |m| s = m.to_sym ; !(self[s] && self[s].set?) }
872 # Channel modes of type A manipulate lists
874 # Example: b (banlist)
876 class ModeTypeA < Mode
880 @list = NetmaskList.new
884 nm = @channel.server.new_netmask(val)
885 @list << nm unless @list.include?(nm)
889 nm = @channel.server.new_netmask(val)
896 # Channel modes of type B need an argument
900 class ModeTypeB < Mode
916 @arg = nil if @arg == val
922 # Channel modes that change the User prefixes are like
923 # Channel modes of type B, except that they manipulate
924 # lists of Users, so they are somewhat similar to channel
927 class UserMode < ModeTypeB
936 u = @channel.server.user(val)
937 @list << u unless @list.include?(u)
941 u = @channel.server.user(val)
948 # Channel modes of type C need an argument when set,
949 # but not when they get reset
953 class ModeTypeC < Mode
975 # Channel modes of type D are basically booleans
977 # Example: m (moderate)
979 class ModeTypeD < Mode
1000 # A Topic represents the topic of a channel. It consists of
1001 # the topic itself, who set it and when
1004 attr_accessor :text, :set_by, :set_on
1007 # Create a new Topic setting the text, the creator and
1010 def initialize(text="", set_by="", set_on=Time.new)
1012 @set_by = set_by.to_irc_netmask
1016 # Replace a Topic with another one
1019 raise TypeError, "#{topic.inspect} is not of class #{self.class}" unless topic.kind_of?(self.class)
1020 @text = topic.text.dup
1021 @set_by = topic.set_by.dup
1022 @set_on = topic.set_on.dup
1027 def to_irc_channel_topic
1040 # Returns an Irc::Channel::Topic with self as text
1042 def to_irc_channel_topic
1043 Irc::Channel::Topic.new(self)
1052 # Here we start with the actual Channel class
1056 include ServerOrCasemap
1057 attr_reader :name, :topic, :mode, :users
1059 attr_accessor :creation_time, :url
1062 str = self.__to_s__[0..-2]
1063 str << " on server #{server}" if server
1064 str << " @name=#{@name.inspect} @topic=#{@topic.text.inspect}"
1065 str << " @users=[#{user_nicks.sort.join(', ')}]"
1066 str << " (created on #{creation_time})" if creation_time
1067 str << " (URL #{url})" if url
1079 @users.map { |u| u.downcase }
1082 # Checks if the receiver already has a user with the given _nick_
1085 @users.index(nick.to_irc_user(server_and_casemap))
1088 # Returns the user with nick _nick_, if available
1091 idx = has_user?(nick)
1095 # Adds a user to the channel
1097 def add_user(user, opts={})
1098 silent = opts.fetch(:silent, false)
1100 warn "Trying to add user #{user} to channel #{self} again" unless silent
1102 @users << user.to_irc_user(server_and_casemap)
1106 # Creates a new channel with the given name, optionally setting the topic
1107 # and an initial users list.
1109 # No additional info is created here, because the channel flags and userlists
1110 # allowed depend on the server.
1112 def initialize(name, topic=nil, users=[], opts={})
1113 raise ArgumentError, "Channel name cannot be empty" if name.to_s.empty?
1114 warn "Unknown channel prefix #{name[0].chr}" if name !~ /^[&#+!]/
1115 raise ArgumentError, "Invalid character in #{name.inspect}" if name =~ /[ \x07,]/
1117 init_server_or_casemap(opts)
1121 @topic = topic ? topic.to_irc_channel_topic : Channel::Topic.new
1123 @users = UserList.new
1130 @mode = ModeHash.new
1132 # creation time, only on some networks
1133 @creation_time = nil
1135 # URL, only on some networks
1139 # Removes a user from the channel
1141 def delete_user(user)
1142 @mode.each { |sym, mode|
1143 mode.reset(user) if mode.kind_of?(UserMode)
1148 # The channel prefix
1154 # A channel is local to a server if it has the '&' prefix
1160 # A channel is modeless if it has the '+' prefix
1166 # A channel is safe if it has the '!' prefix
1172 # A channel is normal if it has the '#' prefix
1180 def create_mode(sym, kl)
1181 @mode[sym.to_sym] = kl.new(self)
1187 l << s if (m.class <= UserMode and m.list[user])
1193 @mode.has_key?(:o) and @mode[:o].list[user]
1196 def has_voice?(user)
1197 @mode.has_key?(:v) and @mode[:v].list[user]
1202 # A ChannelList is an ArrayOf <code>Channel</code>s
1204 class ChannelList < ArrayOf
1206 # Create a new ChannelList, optionally filling it with the elements from
1207 # the Array argument fed to it.
1209 def initialize(ar=[])
1213 # Convenience method: convert the ChannelList to a list of channel names.
1214 # The indices are preserved
1217 self.map { |chan| chan.name }
1227 # We keep extending String, this time adding a method that converts a
1228 # String into an Irc::Channel object
1230 def to_irc_channel(opts={})
1231 Irc::Channel.new(self, opts)
1240 # An IRC Server represents the Server the client is connected to.
1244 attr_reader :hostname, :version, :usermodes, :chanmodes
1245 alias :to_s :hostname
1246 attr_reader :supports, :capabilities
1248 attr_reader :channels, :users
1252 @channels.map { |ch| ch.downcase }
1257 @users.map { |u| u.downcase }
1261 chans, users = [@channels, @users].map {|d|
1263 a.downcase <=> b.downcase
1269 str = self.__to_s__[0..-2]
1270 str << " @hostname=#{hostname}"
1271 str << " @channels=#{chans}"
1272 str << " @users=#{users}"
1276 # Create a new Server, with all instance variables reset to nil (for
1277 # scalar variables), empty channel and user lists and @supports
1278 # initialized to the default values for all known supported features.
1281 @hostname = @version = @usermodes = @chanmodes = nil
1283 @channels = ChannelList.new
1285 @users = UserList.new
1290 # Resets the server capabilities
1292 def reset_capabilities
1294 :casemapping => 'rfc1459'.to_irc_casemap,
1297 :typea => nil, # Type A: address lists
1298 :typeb => nil, # Type B: needs a parameter
1299 :typec => nil, # Type C: needs a parameter when set
1300 :typed => nil # Type D: must not have a parameter
1303 :chantypes => "#&!+",
1314 :prefixes => [:"@", :+]
1325 # Convert a mode (o, v, h, ...) to the corresponding
1326 # prefix (@, +, %, ...). See also mode_for_prefix
1327 def prefix_for_mode(mode)
1328 return @supports[:prefix][:prefixes][
1329 @supports[:prefix][:modes].index(mode.to_sym)
1333 # Convert a prefix (@, +, %, ...) to the corresponding
1334 # mode (o, v, h, ...). See also prefix_for_mode
1335 def mode_for_prefix(pfx)
1336 return @supports[:prefix][:modes][
1337 @supports[:prefix][:prefixes].index(pfx.to_sym)
1341 # Resets the Channel and User list
1344 @users.reverse_each { |u|
1347 @channels.reverse_each { |u|
1357 @hostname = @version = @usermodes = @chanmodes = nil
1360 # This method is used to parse a 004 RPL_MY_INFO line
1362 def parse_my_info(line)
1363 ar = line.split(' ')
1370 def noval_warn(key, val, &block)
1372 yield if block_given?
1374 warn "No #{key.to_s.upcase} value"
1378 def val_warn(key, val, &block)
1379 if val == true or val == false or val.nil?
1380 yield if block_given?
1382 warn "No #{key.to_s.upcase} value must be specified, got #{val}"
1385 private :noval_warn, :val_warn
1387 # This method is used to parse a 005 RPL_ISUPPORT line
1389 # See the RPL_ISUPPORT draft[http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt]
1391 def parse_isupport(line)
1392 debug "Parsing ISUPPORT #{line.inspect}"
1393 ar = line.split(' ')
1396 prekey, val = en.split('=', 2)
1397 if prekey =~ /^-(.*)/
1398 key = $1.downcase.to_sym
1401 key = prekey.downcase.to_sym
1405 noval_warn(key, val) {
1406 @supports[key] = val.to_irc_casemap
1408 when :chanlimit, :idchan, :maxlist, :targmax
1409 noval_warn(key, val) {
1410 groups = val.split(',')
1413 @supports[key][k] = v.to_i || 0
1414 if @supports[key][k] == 0
1415 warn "Deleting #{key} limit of 0 for #{k}"
1416 @supports[key].delete(k)
1421 noval_warn(key, val) {
1422 groups = val.split(',')
1423 @supports[key][:typea] = groups[0].scan(/./).map { |x| x.to_sym}
1424 @supports[key][:typeb] = groups[1].scan(/./).map { |x| x.to_sym}
1425 @supports[key][:typec] = groups[2].scan(/./).map { |x| x.to_sym}
1426 @supports[key][:typed] = groups[3].scan(/./).map { |x| x.to_sym}
1428 when :channellen, :kicklen, :modes, :topiclen
1430 @supports[key] = val.to_i
1432 @supports[key] = nil
1435 @supports[key] = val # can also be nil
1438 @supports[key] = val
1441 @supports[key] = val
1443 noval_warn(key, val) {
1444 reparse += "CHANLIMIT=(chantypes):#{val} "
1447 noval_warn(key, val) {
1448 @supports[:targmax]['PRIVMSG'] = val.to_i
1449 @supports[:targmax]['NOTICE'] = val.to_i
1452 noval_warn(key, val) {
1453 @supports[key] = val
1456 noval_warn(key, val) {
1457 @supports[key] = val.to_i
1461 val.scan(/\((.*)\)(.*)/) { |m, p|
1462 @supports[key][:modes] = m.scan(/./).map { |x| x.to_sym}
1463 @supports[key][:prefixes] = p.scan(/./).map { |x| x.to_sym}
1466 @supports[key][:modes] = nil
1467 @supports[key][:prefixes] = nil
1470 val_warn(key, val) {
1471 @supports[key] = val.nil? ? true : val
1474 noval_warn(key, val) {
1475 @supports[key] = val.scan(/./)
1478 noval_warn(key, val) {
1479 @supports[key] = val.split(',')
1482 @supports[key] = val.nil? ? true : val
1485 reparse.gsub!("(chantypes)",@supports[:chantypes])
1486 parse_isupport(reparse) unless reparse.empty?
1489 # Returns the casemap of the server.
1492 @supports[:casemapping]
1495 # Returns User or Channel depending on what _name_ can be
1498 def user_or_channel?(name)
1499 if supports[:chantypes].include?(name[0])
1506 # Returns the actual User or Channel object matching _name_
1508 def user_or_channel(name)
1509 if supports[:chantypes].include?(name[0])
1510 return channel(name)
1516 # Checks if the receiver already has a channel with the given _name_
1518 def has_channel?(name)
1519 return false if name.nil_or_empty?
1520 channel_names.index(name.irc_downcase(casemap))
1522 alias :has_chan? :has_channel?
1524 # Returns the channel with name _name_, if available
1526 def get_channel(name)
1527 return nil if name.nil_or_empty?
1528 idx = has_channel?(name)
1529 channels[idx] if idx
1531 alias :get_chan :get_channel
1533 # Create a new Channel object bound to the receiver and add it to the
1534 # list of <code>Channel</code>s on the receiver, unless the channel was
1535 # present already. In this case, the default action is to raise an
1536 # exception, unless _fails_ is set to false. An exception can also be
1537 # raised if _str_ is nil or empty, again only if _fails_ is set to true;
1538 # otherwise, the method just returns nil
1540 def new_channel(name, topic=nil, users=[], fails=true)
1541 if name.nil_or_empty?
1542 raise "Tried to look for empty or nil channel name #{name.inspect}" if fails
1547 raise "Channel #{name} already exists on server #{self}" if fails
1551 prefix = name[0].chr
1553 # Give a warning if the new Channel goes over some server limits.
1555 # FIXME might need to raise an exception
1557 warn "#{self} doesn't support channel prefix #{prefix}" unless @supports[:chantypes].include?(prefix)
1558 warn "#{self} doesn't support channel names this long (#{name.length} > #{@supports[:channellen]})" unless name.length <= @supports[:channellen]
1560 # Next, we check if we hit the limit for channels of type +prefix+
1561 # if the server supports +chanlimit+
1563 @supports[:chanlimit].keys.each { |k|
1564 next unless k.include?(prefix)
1566 channel_names.each { |n|
1567 count += 1 if k.include?(n[0])
1569 # raise IndexError, "Already joined #{count} channels with prefix #{k}" if count == @supports[:chanlimit][k]
1570 warn "Already joined #{count}/#{@supports[:chanlimit][k]} channels with prefix #{k}, we may be going over server limits" if count >= @supports[:chanlimit][k]
1573 # So far, everything is fine. Now create the actual Channel
1575 chan = Channel.new(name, topic, users, :server => self)
1577 # We wade through +prefix+ and +chanmodes+ to create appropriate
1578 # lists and flags for this channel
1580 @supports[:prefix][:modes].each { |mode|
1581 chan.create_mode(mode, Channel::UserMode)
1582 } if @supports[:prefix][:modes]
1584 @supports[:chanmodes].each { |k, val|
1589 chan.create_mode(mode, Channel::ModeTypeA)
1593 chan.create_mode(mode, Channel::ModeTypeB)
1597 chan.create_mode(mode, Channel::ModeTypeC)
1601 chan.create_mode(mode, Channel::ModeTypeD)
1608 # debug "Created channel #{chan.inspect}"
1613 # Returns the Channel with the given _name_ on the server,
1614 # creating it if necessary. This is a short form for
1615 # new_channel(_str_, nil, [], +false+)
1618 new_channel(str,nil,[],false)
1621 # Remove Channel _name_ from the list of <code>Channel</code>s
1623 def delete_channel(name)
1624 idx = has_channel?(name)
1625 raise "Tried to remove unmanaged channel #{name}" unless idx
1626 @channels.delete_at(idx)
1629 # Checks if the receiver already has a user with the given _nick_
1632 return false if nick.nil_or_empty?
1633 user_nicks.index(nick.irc_downcase(casemap))
1636 # Returns the user with nick _nick_, if available
1639 idx = has_user?(nick)
1643 # Create a new User object bound to the receiver and add it to the list
1644 # of <code>User</code>s on the receiver, unless the User was present
1645 # already. In this case, the default action is to raise an exception,
1646 # unless _fails_ is set to false. An exception can also be raised
1647 # if _str_ is nil or empty, again only if _fails_ is set to true;
1648 # otherwise, the method just returns nil
1650 def new_user(str, fails=true)
1651 if str.nil_or_empty?
1652 raise "Tried to look for empty or nil user name #{str.inspect}" if fails
1655 tmp = str.to_irc_user(:server => self)
1656 old = get_user(tmp.nick)
1657 # debug "Tmp: #{tmp.inspect}"
1658 # debug "Old: #{old.inspect}"
1660 # debug "User already existed as #{old.inspect}"
1663 # debug "Both were known"
1664 # Do not raise an error: things like Freenode change the hostname after identification
1665 warning "User #{tmp.nick} has inconsistent Netmasks! #{self} knows #{old.inspect} but access was tried with #{tmp.inspect}" if old != tmp
1666 raise "User #{tmp} already exists on server #{self}" if fails
1668 if old.fullform.downcase != tmp.fullform.downcase
1670 # debug "Known user now #{old.inspect}"
1675 warn "#{self} doesn't support nicknames this long (#{tmp.nick.length} > #{@supports[:nicklen]})" unless tmp.nick.length <= @supports[:nicklen]
1681 # Returns the User with the given Netmask on the server,
1682 # creating it if necessary. This is a short form for
1683 # new_user(_str_, +false+)
1686 new_user(str, false)
1689 # Deletes User _user_ from Channel _channel_
1691 def delete_user_from_channel(user, channel)
1692 channel.delete_user(user)
1695 # Remove User _someuser_ from the list of <code>User</code>s.
1696 # _someuser_ must be specified with the full Netmask.
1698 def delete_user(someuser)
1699 idx = has_user?(someuser)
1700 raise "Tried to remove unmanaged user #{user}" unless idx
1701 have = self.user(someuser)
1702 @channels.each { |ch|
1703 delete_user_from_channel(have, ch)
1705 @users.delete_at(idx)
1708 # Create a new Netmask object with the appropriate casemap
1710 def new_netmask(str)
1711 str.to_irc_netmask(:server => self)
1714 # Finds all <code>User</code>s on server whose Netmask matches _mask_
1716 def find_users(mask)
1717 nm = new_netmask(mask)
1718 @users.inject(UserList.new) {
1720 if user.user == "*" or user.host == "*"
1721 list << user if user.nick.irc_downcase(casemap) =~ nm.nick.irc_downcase(casemap).to_irc_regexp
1723 list << user if user.matches?(nm)