def _create_or_update(self, data, username, network=None): if network: network_data = network.to_dict() network_data.update(data) form = NetworkForm(formdata=MultiDict(network_data)) else: form = NetworkForm(formdata=MultiDict(data)) form.validate() if form.errors: return web.Response( body=json.dumps(form.errors).encode(), status=400, content_type='application/json') cleaned_data = form.data cleaned_data['user'] = username if network: network = yield from NetworkStore.update( dict( filter=('id', network.id), update=cleaned_data ) ) else: network = yield from NetworkStore.create(**cleaned_data) return web.Response(body=self.serialize(network).encode(), content_type='application/json')
def get(self): username = yield from get_auth(self.request) user = yield from UserStore.get(dict(query=('username', username))) networks = yield from NetworkStore.get( dict(query={'user_id': user.id})) or [] return web.Response(body=self.serialize(networks).encode(), content_type='application/json')
def load_data(f): with open(f, 'r') as f: config = yaml.load(f) if validate_yaml(config): for user in config.keys(): user_data = config[user] yield from UserStore.create( dict( username=user, email=user_data['email'], password=user_data['password'] ) ) networks = user_data['networks'] for net in networks.keys(): net_data = networks[net] network = yield from NetworkStore.create( dict( user_username=user, name=net, nickname=net_data["nick"], hostname=net_data["host"], port=net_data["port"], realname=net_data["realname"], username=net_data["username"], network_password=net_data["password"], usermode=net_data["usermode"], ) )
def ls(page=1): networks = yield from NetworkStore.get({'query': {}}) headers = ['Id', 'User', 'Name', 'Nick', 'Server'] table = [[ network.id, network.user_id, network.name, network.nickname, '{}/{}'.format(network.hostname, network.port) ] for network in networks] print(tabulate(table, headers, tablefmt='grid'))
def get(self): username = yield from get_auth(self.request) user = yield from UserStore.get( dict(query=('username', username))) networks = yield from NetworkStore.get( dict(query={'user_id': user.id})) or [] return web.Response(body=self.serialize(networks).encode(), content_type='application/json')
def put(self): network_id = self.request.match_info['id'] action = self.request.match_info['action'] if action not in ('connect', 'disconnect'): raise web.HTTPNotFound() username = yield from get_auth(self.request) user = yield from UserStore.get( dict(query=('username', username))) networks = yield from NetworkStore.get( dict(query={'user_id': user.id, 'id': network_id}) ) if not networks: raise web.HTTPNotFound() network = networks[0] network = yield from NetworkStore.update( dict(filter=('id', network.id), update={'status': '0' if action == 'connect' else '2'}) ) return web.Response(body=self.serialize(network).encode(), content_type='application/json')
def put(self): network_id = self.request.match_info['id'] action = self.request.match_info['action'] if action not in ('connect', 'disconnect'): raise web.HTTPNotFound() username = yield from get_auth(self.request) user = yield from UserStore.get(dict(query=('username', username))) networks = yield from NetworkStore.get( dict(query={ 'user_id': user.id, 'id': network_id })) if not networks: raise web.HTTPNotFound() network = networks[0] network = yield from NetworkStore.update( dict(filter=('id', network.id), update={'status': '0' if action == 'connect' else '2'})) return web.Response(body=self.serialize(network).encode(), content_type='application/json')
def get(self): username = yield from get_auth(self.request) user = yield from UserStore.get( dict(query=('username', username))) network_id = self.request.match_info['id'] networks = yield from NetworkStore.get( dict(query={'user_id': user.id, 'id': int(network_id)})) network = (networks and networks[0]) or None if network is None: raise web.HTTPNotFound() return web.Response(body=self.serialize(network).encode(), content_type='application/json')
def _create_or_update(self, data, username, network=None): if network: network_data = network.to_dict() network_data.update(data) form = NetworkForm(formdata=MultiDict(network_data)) else: form = NetworkForm(formdata=MultiDict(data)) form.validate() if form.errors: return web.Response(body=json.dumps(form.errors).encode(), status=400, content_type='application/json') cleaned_data = form.data cleaned_data['user'] = username if network: network = yield from NetworkStore.update( dict(filter=('id', network.id), update=cleaned_data)) else: network = yield from NetworkStore.create(**cleaned_data) return web.Response(body=self.serialize(network).encode(), content_type='application/json')
def put(self): network_id = self.request.match_info['id'] username = yield from get_auth(self.request) data = yield from self.request.post() user = yield from UserStore.get( dict(query=('username', username))) networks = yield from NetworkStore.get( dict(query={'user_id': user.id, 'id': network_id}) ) if not networks: raise web.HTTPNotFound() resp = yield from self._create_or_update(data, username, networks[0]) return resp
def get(self): username = yield from get_auth(self.request) user = yield from UserStore.get(dict(query=('username', username))) network_id = self.request.match_info['id'] networks = yield from NetworkStore.get( dict(query={ 'user_id': user.id, 'id': int(network_id) })) network = (networks and networks[0]) or None if network is None: raise web.HTTPNotFound() return web.Response(body=self.serialize(network).encode(), content_type='application/json')
def put(self): network_id = self.request.match_info['id'] username = yield from get_auth(self.request) data = yield from self.request.post() user = yield from UserStore.get(dict(query=('username', username))) networks = yield from NetworkStore.get( dict(query={ 'user_id': user.id, 'id': network_id })) if not networks: raise web.HTTPNotFound() resp = yield from self._create_or_update(data, username, networks[0]) return resp
def handle_received_data(self, data): logger.debug('RECV: {}'.format(data)) lport, rport = [_.strip() for _ in data.split(',')] networks = yield from NetworkStore.get({ 'query': {'lport': lport, 'rport': rport} }) network = networks[0] user = yield from UserStore.get({ 'query': network.user_id }) rpl_msg = '{lport}, {rport} : USERID : UNIX : {username}'.format( lport=lport, rport=rport, username=user.username) logger.debug('RPL: {}'.format(rpl_msg)) self.send(rpl_mgs)
def handle_connection_lost(self): logger.debug('Network disconnected: %s, %s, %s', self.factory.config.userinfo, self.factory.config.name, self.factory.config.nick) yield from NetworkStore.update( dict( filter=('id', self.factory.config.id), update={ 'status': '3', 'lhost': None, 'lport': None, 'rhost': None, 'rport': None } ) )
def create(user, network_name, host, port, nick, realname, username, password, usermode, ssl, ssl_verify): """Create a network for a user""" network = yield from NetworkStore.create( dict(user_username=user, name=network_name, nickname=nick, hostname=host, port=port, realname=realname, network_username=username, password=password, usermode=usermode, ssl=ssl, ssl_verify=ssl_verify)) print(network.access_token)
def get_bot_handle(self, network, client): try: key = network.id bot = self.bots.get(key) self.register_client(key, client) connected_channels = yield from ChannelStore.get({ 'filter': dict( network_id=key, status='1' ) }) if bot is None: yield from NetworkStore.update( dict( filter=('id', network.id), update={ 'status': '0' }) ) return logger.debug('Reusing existing bot: {}'.format(bot)) # Wait for bot.config.lock to be release when connection is # made to remote IRC server if bot.config.lock: yield from bot.config.lock bot.config.lock = None joining_messages_list = [ ':* 001 {nick} :You are now connected to {network}'.format( nick=bot.nick, network=network.name), ':* 251 {nick} : '.format(nick=bot.nick) ] for channel in connected_channels: joining_messages_list.append( ':{nick}!* JOIN {channel}'.format( nick=bot.nick, channel=channel.name) ) bot.raw('NAMES %s' % channel.name) client.send(*['\r\n'.join(joining_messages_list)]) return bot except Exception as e: logger.error('get_bot_handle error: {}'.format(e), exc_info=True)
def create(user, network_name, host, port, nick, realname, username, password, usermode, ssl, ssl_verify): """Create a network for a user""" network = yield from NetworkStore.create( dict( user=user, name=network_name, nickname=nick, hostname=host, port=port, realname=realname, username=username, password=password, usermode=usermode, ssl=ssl, ssl_verify=ssl_verify, ) ) print(network.access_token)
def handle_connection_made(self, transport): logger.debug('Network connected: %s, %s, %s', self.factory.config.user, self.factory.config.name, self.factory.config.nick) socket = transport.get_extra_info('socket') lhost, lport = socket.getsockname() rhost, rport = socket.getpeername() yield from NetworkStore.update( dict( filter=('id', self.factory.config.id), update={ 'status': '1', 'lhost': lhost, 'lport': lport, 'rhost': rhost, 'rport': rport } ) )
def __init__(self, loop=None): self.loop = loop or asyncio.get_event_loop() self.bots = {} self.clients = defaultdict(set) NetworkStore.on('create', self.on_network_create) NetworkStore.on('update', self.on_network_update)
def fetch(self): results = yield from NetworkStore.get( {'query': { 'user_id': self.user_id }}, raw=True) return results
def get_bot_handle(self, network, client): try: key = network.id bot = self.bots.get(key) self.register_client(key, client) connected_channels = yield from ChannelStore.get( {'query': dict(network_id=key, status='1')}) if bot is None: user = yield from UserStore.get({'query': network.user_id}) logger.debug('Creating new bot: {}-{}'.format( user.username, network.name)) yield from NetworkStore.update( dict(filter=('id', network.id), update={'status': '0'})) config = dict( id=network.id, name=network.name, userinfo=network.username, password=network.password, nick=network.nickname, realname=network.realname, host=network.hostname, port=network.port, ssl=network.ssl, ssl_verify=network.ssl_verify.code, lock=asyncio.Lock(), autojoins=[channel.name for channel in connected_channels]) # Acquire lock for connecting to IRC server, so that # other clients connecting to the same bot can wait on this # lock before trying to send messages to the bot yield from config['lock'].acquire() bot = IrcbBot(**config) bot.run_in_loop() self.register_bot(key, bot) else: logger.debug('Reusing existing bot: {}'.format(bot)) # Wait for bot.config.lock to be release when connection is # made to remote IRC server if bot.config.lock: yield from bot.config.lock bot.config.lock = None joining_messages_list = [ ':* 001 {nick} :You are now connected to {network}'.format( nick=bot.nick, network=network.name), ':* 251 {nick} : '.format(nick=bot.nick) ] for channel in connected_channels: joining_messages_list.append( ':{nick}!* JOIN {channel}'.format( nick=bot.nick, channel=channel.name)) bot.raw('NAMES %s' % channel.name) client.send(*['\r\n'.join(joining_messages_list)]) def forward(line): bot = self.bots.get(key) if bot: logger.debug('Forwarding {}\t {}'.format(bot, line)) bot.raw(line) return forward except Exception as e: logger.error('get_bot_handle error: {}'.format(e), exc_info=True)
def get_network(self, access_token): result = yield from NetworkStore.get( {'query': ('access_token', access_token)}) return result
def get_bot_handle(self, network, client): try: key = network.id bot = self.bots.get(key) self.register_client(key, client) connected_channels = yield from ChannelStore.get({ 'query': dict( network_id=key, status='1' ) }) if bot is None: user = yield from UserStore.get({'query': network.user_id}) logger.debug( 'Creating new bot: {}-{}'.format( user.username, network.name) ) yield from NetworkStore.update( dict( filter=('id', network.id), update={ 'status': '0' }) ) config = dict( id=network.id, name=network.name, userinfo=network.username, password=network.password, nick=network.nickname, realname=network.realname, host=network.hostname, port=network.port, ssl=network.ssl, ssl_verify=network.ssl_verify.code, lock=asyncio.Lock(), autojoins=[channel.name for channel in connected_channels] ) # Acquire lock for connecting to IRC server, so that # other clients connecting to the same bot can wait on this # lock before trying to send messages to the bot yield from config['lock'].acquire() bot = IrcbBot(**config) bot.run_in_loop() self.register_bot(key, bot) else: logger.debug('Reusing existing bot: {}'.format(bot)) # Wait for bot.config.lock to be release when connection is # made to remote IRC server if bot.config.lock: yield from bot.config.lock bot.config.lock = None joining_messages_list = [ ':* 001 {nick} :You are now connected to {network}'.format( nick=bot.nick, network=network.name), ':* 251 {nick} : '.format(nick=bot.nick) ] for channel in connected_channels: joining_messages_list.append( ':{nick}!* JOIN {channel}'.format( nick=bot.nick, channel=channel.name) ) bot.raw('NAMES %s' % channel.name) client.send(*['\r\n'.join(joining_messages_list)]) def forward(line): bot = self.bots.get(key) if bot: logger.debug( 'Forwarding {}\t {}'.format(bot, line)) bot.raw(line) return forward except Exception as e: logger.error('get_bot_handle error: {}'.format(e), exc_info=True)
def disconnect(id): network = yield from NetworkStore.update( dict(filter=('id', id), update={'status': '2'}))