<commit_before>#!/usr/bin/env python

###
# Copyright (c) 2002, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

"""
Handles relaying between networks.
"""

__revision__ = "$Id$"
__author__ = '<NAME> (jemfinch) <<EMAIL>>'

import supybot.plugins as plugins

import re
import sys
import copy
import time
from itertools import imap, ifilter

import supybot.conf as conf
import supybot.utils as utils
import supybot.world as world
import supybot.irclib as irclib
import supybot.drivers as drivers
import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils
import supybot.privmsgs as privmsgs
import supybot.registry as registry
import supybot.callbacks as callbacks

def configure(advanced):
    from supybot.questions import output, expect, anything, something, yn
    conf.registerPlugin('Relay', True)
    if yn('Would you like to relay between any channels?'):
        channels = anything('What channels?  Separated them by spaces.')
        conf.supybot.plugins.Relay.channels.set(channels)
    if yn('Would you like to use color to distinguish between nicks?'):
        conf.supybot.plugins.Relay.color.setValue(True)
    output("""Right now there's no way to configure the actual connection to
    the server.  What you'll need to do when the bot finishes starting up is
    use the 'start' command followed by the 'connect' command.  Use the 'help'
    command to see how these two commands should be used.""")

class Networks(registry.SpaceSeparatedListOf):
    List = ircutils.IrcSet
    Value = registry.String

conf.registerPlugin('Relay')
conf.registerChannelValue(conf.supybot.plugins.Relay, 'color',
    registry.Boolean(False, """Determines whether the bot will color relayed
    PRIVMSGs so as to make the messages easier to read."""))
conf.registerChannelValue(conf.supybot.plugins.Relay, 'topicSync',
    registry.Boolean(True, """Determines whether the bot will synchronize
    topics between networks in the channels it relays."""))
conf.registerChannelValue(conf.supybot.plugins.Relay, 'hostmasks',
    registry.Boolean(False, """Determines whether the bot will relay the
    hostmask of the person joining or parting the channel when he or she joins
    or parts."""))
conf.registerChannelValue(conf.supybot.plugins.Relay, 'includeNetwork',
    registry.Boolean(True, """Determines whether the bot will include the
    network in relayed PRIVMSGs; if you're only relaying between two networks,
    it's somewhat redundant, and you may wish to save the space."""))
conf.registerGlobalValue(conf.supybot.plugins.Relay, 'channels',
    conf.SpaceSeparatedSetOfChannels([], """Determines which channels the bot
    will relay in."""))
conf.registerGlobalValue(conf.supybot.plugins.Relay, 'networks',
    Networks('', """Determines what networks the bot will join in order to relay
    between."""))

class Relay(callbacks.Privmsg):
    noIgnore = True
    priority = sys.maxint
    def __init__(self):
        callbacks.Privmsg.__init__(self)
        self._whois = {}
        self.ircs = []
        self.relayedMsgs = {}
        self.lastmsg = {}
        self.ircstates = {}

    def __call__(self, irc, msg):
        try:
            irc = self._getRealIrc(irc)
            if irc not in self.ircs:
                self._addIrc(irc)
            self.ircstates[irc].addMsg(irc, self.lastmsg[irc])
        finally:
            self.lastmsg[irc] = msg
        callbacks.Privmsg.__call__(self, irc, msg)

    def do376(self, irc, msg):
        if not self.ircs:
            name = self._getIrcName(irc)
            self.log.info('Registering initial Irc as %s.', name)
            self._connect(name, irc, serverPort=None, makeNew=False)
        L = []
        for channel in self.registryValue('channels'):
            if channel not in irc.state.channels:
                L.append(channel)
        if L:
            irc.queueMsg(ircmsgs.joins(L))
        for network in self.registryValue('networks'):
            ircNames = map(self._getIrcName, self.ircs)
            if network not in ircNames:
                self.log.info('Starting relay connection to %s.', network)
                self._connect(network, irc)
    do377 = do422 = do376

    def _getRealIrc(self, irc):
        if isinstance(irc, irclib.Irc):
            return irc
        else:
            return irc.getRealIrc()

    def _getIrc(self, name):
        for irc in self.ircs:
            if self._getIrcName(irc) == name:
                return irc
        raise KeyError, name

    def _getIrcName(self, irc):
        # We should allow abbreviations at some point.
        return irc.network

    def connect(self, irc, msg, args):
        """<network> [<host:port>] (port defaults to 6667)

        Connects to another network at <host:port>.  The network name is used
        when relaying messages from that network to other networks.
        """
        realIrc = self._getRealIrc(irc)
        (network, server) = privmsgs.getArgs(args, optional=1)
        if server:
            if ':' in server:
                (server, port) = server.split(':')
                port = int(port)
            else:
                port = 6667
            serverPort = (server, port)
        else:
            serverPort = None
        self._connect(network, realIrc, serverPort=serverPort)
        irc.replySuccess()
    connect = privmsgs.checkCapability(connect, 'owner')

    def _addIrc(self, irc):
        # Let's just be extra-special-careful here.
        if irc not in self.ircs:
            self.ircs.append(irc)
        if irc not in self.ircstates:
            self.ircstates[irc] = irclib.IrcState()
        if irc not in self.lastmsg:
            self.lastmsg[irc] = ircmsgs.ping('this is just a fake message')

    def _connect(self, network, realIrc, serverPort=None, makeNew=True):
        try:
            group = conf.supybot.networks.get(network)
            (server, port) = group.servers()[0]
        except (registry.NonExistentRegistryEntry, IndexError):
            if serverPort is None:
                raise callbacks.Error, '_connect requires a (server, port) ' \
                                       'if the network is not registered.'
            conf.registerNetwork(network, servers=('%s:%s' % serverPort,))
        if makeNew:
            self.log.info('Creating new Irc for relaying to %s.', network)
            newIrc = irclib.Irc(network)
            newIrc.state.history = realIrc.state.history
            newIrc.callbacks = realIrc.callbacks
            driver = drivers.newDriver(newIrc)
        else:
            newIrc = realIrc
        self._addIrc(newIrc)
        networks = self.registryValue('networks')
        networks.add(network)

    def disconnect(self, irc, msg, args):
        """<network>

        Disconnects and ceases to relay to and from the network represented by
        the network <network>.
        """
        network = privmsgs.getArgs(args)
        otherIrc = self._getIrc(network)
        otherIrc.driver.die()
        world.ircs.remove(otherIrc)
        self.ircs.remove(otherIrc) # Should we abstract this?
        irc.replySuccess()
    disconnect = privmsgs.checkCapability(disconnect, 'owner')

    def join(self, irc, msg, args):
        """<channel>

        Starts relaying between the channel <channel> on all networks.  If on a
        network the bot isn't in <channel>, he'll join.  This commands is
        required even if the bot is in the channel on both networks; he won't
        relay between those channels unless he's told to join both
        channels.
        """
        channel = privmsgs.getArgs(args)
        if not ircutils.isChannel(channel):
            irc.error('%r is not a valid channel.' % channel)
            return
        self.registryValue('channels').add(channel)
        for otherIrc in self.ircs: # Should we abstract this?
            if channel not in otherIrc.state.channels:
                otherIrc.queueMsg(ircmsgs.join(channel))
        irc.replySuccess()
    join = privmsgs.checkCapability(join, 'owner')

    def part(self, irc, msg, args):
        """<channel>

        Ceases relaying between the channel <channel> on all networks.  The bot
        will part from the channel on all networks in which it is on the
        channel.
        """
        channel = privmsgs.getArgs(args)
        if not ircutils.isChannel(channel):
            irc.error('%r is not a valid channel.' % channel)
            return
        self.registryValue('channels').remove(channel)
        for otherIrc in self.ircs:
            if channel in otherIrc.state.channels:
                otherIrc.queueMsg(ircmsgs.part(channel))
        irc.replySuccess()
    part = privmsgs.checkCapability(part, 'owner')

    def command(self, irc, msg, args):
        """<network> <command> [<arg> ...]

        Gives the bot <command> (with its associated <arg>s) on <network>.
        """
        if len(args) < 2:
            raise callbacks.ArgumentError
        network = args.pop(0)
        try:
            otherIrc = self._getIrc(network)
        except KeyError:
            irc.error('I\'m not currently on the network %r.' % network)
            return
        Owner = irc.getCallback('Owner')
        Owner.disambiguate(irc, args)
        self.Proxy(otherIrc, msg, args)
    command = privmsgs.checkCapability(command, 'admin')

    def nicks(self, irc, msg, args):
        """[<channel>] (only if not sent in the channel itself.)

        The <channel> argument is only necessary if the message isn't sent on
        the channel itself.  Returns the nicks of the people in the channel on
        the various networks the bot is connected to.
        """
        realIrc = self._getRealIrc(irc)
        channel = privmsgs.getChannel(msg, args)
        if channel not in self.registryValue('channels'):
            irc.error('I\'m not relaying in %s.' % channel)
            return
        users = []
        for otherIrc in self.ircs:
            network = self._getIrcName(otherIrc)
            ops = []
            halfops = []
            voices = []
            usersS = []
            if network != self._getIrcName(realIrc):
                try:
                    Channel = otherIrc.state.channels[channel]
                except KeyError:
                    s = 'Somehow I\'m not in %s on %s.'% (channel, network)
                    irc.error(s)<commit_msg>Added networks command.<commit_after>#!/usr/bin/env python

###
# Copyright (c) 2002, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

"""
Handles relaying between networks.
"""

__revision__ = "$Id$"
__author__ = '<NAME> (jemfinch) <<EMAIL>>'

import supybot.plugins as plugins

import re
import sys
import copy
import time
from itertools import imap, ifilter

import supybot.conf as conf
import supybot.utils as utils
import supybot.world as world
import supybot.irclib as irclib
import supybot.drivers as drivers
import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils
import supybot.privmsgs as privmsgs
import supybot.registry as registry
import supybot.callbacks as callbacks

def configure(advanced):
    from supybot.questions import output, expect, anything, something, yn
    conf.registerPlugin('Relay', True)
    if yn('Would you like to relay between any channels?'):
        channels = anything('What channels?  Separated them by spaces.')
        conf.supybot.plugins.Relay.channels.set(channels)
    if yn('Would you like to use color to distinguish between nicks?'):
        conf.supybot.plugins.Relay.color.setValue(True)
    output("""Right now there's no way to configure the actual connection to
    the server.  What you'll need to do when the bot finishes starting up is
    use the 'start' command followed by the 'connect' command.  Use the 'help'
    command to see how these two commands should be used.""")

class Networks(registry.SpaceSeparatedListOf):
    List = ircutils.IrcSet
    Value = registry.String

conf.registerPlugin('Relay')
conf.registerChannelValue(conf.supybot.plugins.Relay, 'color',
    registry.Boolean(False, """Determines whether the bot will color relayed
    PRIVMSGs so as to make the messages easier to read."""))
conf.registerChannelValue(conf.supybot.plugins.Relay, 'topicSync',
    registry.Boolean(True, """Determines whether the bot will synchronize
    topics between networks in the channels it relays."""))
conf.registerChannelValue(conf.supybot.plugins.Relay, 'hostmasks',
    registry.Boolean(False, """Determines whether the bot will relay the
    hostmask of the person joining or parting the channel when he or she joins
    or parts."""))
conf.registerChannelValue(conf.supybot.plugins.Relay, 'includeNetwork',
    registry.Boolean(True, """Determines whether the bot will include the
    network in relayed PRIVMSGs; if you're only relaying between two networks,
    it's somewhat redundant, and you may wish to save the space."""))
conf.registerGlobalValue(conf.supybot.plugins.Relay, 'channels',
    conf.SpaceSeparatedSetOfChannels([], """Determines which channels the bot
    will relay in."""))
conf.registerGlobalValue(conf.supybot.plugins.Relay, 'networks',
    Networks('', """Determines what networks the bot will join in order to relay
    between."""))

class Relay(callbacks.Privmsg):
    noIgnore = True
    priority = sys.maxint
    def __init__(self):
        callbacks.Privmsg.__init__(self)
        self._whois = {}
        self.ircs = []
        self.relayedMsgs = {}
        self.lastmsg = {}
        self.ircstates = {}

    def __call__(self, irc, msg):
        try:
            irc = self._getRealIrc(irc)
            if irc not in self.ircs:
                self._addIrc(irc)
            self.ircstates[irc].addMsg(irc, self.lastmsg[irc])
        finally:
            self.lastmsg[irc] = msg
        callbacks.Privmsg.__call__(self, irc, msg)

    def do376(self, irc, msg):
        if not self.ircs:
            name = self._getIrcName(irc)
            self.log.info('Registering initial Irc as %s.', name)
            self._connect(name, irc, serverPort=None, makeNew=False)
        L = []
        for channel in self.registryValue('channels'):
            if channel not in irc.state.channels:
                L.append(channel)
        if L:
            irc.queueMsg(ircmsgs.joins(L))
        for network in self.registryValue('networks'):
            ircNames = map(self._getIrcName, self.ircs)
            if network not in ircNames:
                self.log.info('Starting relay connection to %s.', network)
                self._connect(network, irc)
    do377 = do422 = do376

    def _getRealIrc(self, irc):
        if isinstance(irc, irclib.Irc):
            return irc
        else:
            return irc.getRealIrc()

    def _getIrc(self, name):
        for irc in self.ircs:
            if self._getIrcName(irc) == name:
                return irc
        raise KeyError, name

    def _getIrcName(self, irc):
        # We should allow abbreviations at some point.
        return irc.network

    def connect(self, irc, msg, args):
        """<network> [<host:port>] (port defaults to 6667)

        Connects to another network at <host:port>.  The network name is used
        when relaying messages from that network to other networks.
        """
        realIrc = self._getRealIrc(irc)
        (network, server) = privmsgs.getArgs(args, optional=1)
        if server:
            if ':' in server:
                (server, port) = server.split(':')
                port = int(port)
            else:
                port = 6667
            serverPort = (server, port)
        else:
            serverPort = None
        self._connect(network, realIrc, serverPort=serverPort)
        irc.replySuccess()
    connect = privmsgs.checkCapability(connect, 'owner')

    def _addIrc(self, irc):
        # Let's just be extra-special-careful here.
        if irc not in self.ircs:
            self.ircs.append(irc)
        if irc not in self.ircstates:
            self.ircstates[irc] = irclib.IrcState()
        if irc not in self.lastmsg:
            self.lastmsg[irc] = ircmsgs.ping('this is just a fake message')

    def _connect(self, network, realIrc, serverPort=None, makeNew=True):
        try:
            group = conf.supybot.networks.get(network)
            (server, port) = group.servers()[0]
        except (registry.NonExistentRegistryEntry, IndexError):
            if serverPort is None:
                raise callbacks.Error, '_connect requires a (server, port) ' \
                                       'if the network is not registered.'
            conf.registerNetwork(network, servers=('%s:%s' % serverPort,))
        if makeNew:
            self.log.info('Creating new Irc for relaying to %s.', network)
            newIrc = irclib.Irc(network)
            newIrc.state.history = realIrc.state.history
            newIrc.callbacks = realIrc.callbacks
            driver = drivers.newDriver(newIrc)
        else:
            newIrc = realIrc
        self._addIrc(newIrc)
        networks = self.registryValue('networks')
        networks.add(network)

    def disconnect(self, irc, msg, args):
        """<network>

        Disconnects and ceases to relay to and from the network represented by
        the network <network>.
        """
        network = privmsgs.getArgs(args)
        otherIrc = self._getIrc(network)
        otherIrc.driver.die()
        world.ircs.remove(otherIrc)
        self.ircs.remove(otherIrc) # Should we abstract this?
        irc.replySuccess()
    disconnect = privmsgs.checkCapability(disconnect, 'owner')

    def join(self, irc, msg, args):
        """<channel>

        Starts relaying between the channel <channel> on all networks.  If on a
        network the bot isn't in <channel>, he'll join.  This commands is
        required even if the bot is in the channel on both networks; he won't
        relay between those channels unless he's told to join both
        channels.
        """
        channel = privmsgs.getArgs(args)
        if not ircutils.isChannel(channel):
            irc.error('%r is not a valid channel.' % channel)
            return
        self.registryValue('channels').add(channel)
        for otherIrc in self.ircs: # Should we abstract this?
            if channel not in otherIrc.state.channels:
                otherIrc.queueMsg(ircmsgs.join(channel))
        irc.replySuccess()
    join = privmsgs.checkCapability(join, 'owner')

    def part(self, irc, msg, args):
        """<channel>

        Ceases relaying between the channel <channel> on all networks.  The bot
        will part from the channel on all networks in which it is on the
        channel.
        """
        channel = privmsgs.getArgs(args)
        if not ircutils.isChannel(channel):
            irc.error('%r is not a valid channel.' % channel)
            return
        self.registryValue('channels').remove(channel)
        for otherIrc in self.ircs:
            if channel in otherIrc.state.channels:
                otherIrc.queueMsg(ircmsgs.part(channel))
        irc.replySuccess()
    part = privmsgs.checkCapability(part, 'owner')

    def command(self, irc, msg, args):
        """<network> <command> [<arg> ...]

        Gives the bot <command> (with its associated <arg>s) on <network>.
        """
        if len(args) < 2:
            raise callbacks.ArgumentError
        network = args.pop(0)
        try:
            otherIrc = self._getIrc(network)
        except KeyError:
            irc.error('I\'m not currently on the network %r.' % network)
            return
        Owner = irc.getCallback('Owner')
        Owner.disambiguate(irc, args)
        self.Proxy(otherIrc, msg, args)
    command = privmsgs.checkCapability(command, 'admin')

    def networks(self, irc, msg, args):
        """takes no arguments

        Returns the networks to which the bot is currently connected.
        """
        L = ['%s: %s' % (irc.network, irc.server) for irc in self.ircs]
        utils.sortBy(str.lower, L)
        irc.reply(utils.commaAndify(L))
        
    def nicks(self, irc, msg, args):
        """[<channel>]

        Returns the nicks of the people in the channel on the various networks
        the bot is connected to.  <channel> is only necessary if the message
        isn't sent on the channel itself.
        """
        realIrc = self._getRealIrc(irc)
        channel = privmsgs.getChannel(msg, args)
        if channel not in self.registryValue('channels'):
            irc.error('I\'m not relaying in %s.' % channel)
            return
        users = []
        for otherIrc in self.ircs:
            network = self._getIrcName(otherIrc)
            ops = []
            halfops = []
            voices = []
            usersS = []
            if network != self._getIrcName(realIrc):
                try:
                    Channel = otherIrc.state.channels[channel]
                except KeyError:
                    s = 'Somehow I\'m not in %s on %s.'% (channel, network)
                    irc.error(s)
{'fraction_non_alphanumeric': 0.09244433324993745, 'fraction_numerical': 0.002335084646818447, 'mean_word_length': 2.4899592549476135, 'pattern_counts': {'":': 0, '<': 49, '<?xml version=': 0, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6295999', 'n_tokens_mistral': 7014, 'n_tokens_neox': 6670, 'n_words': 2257}