示例#1
0
    def read_loop(self):
        try:
            try:
                while self.connected:

                    header = yield from self.reader.readexactly(6)
                    message_type, length = struct.unpack(Protocol.PREFIX_FORMAT,
                                                         header)
                    if message_type not in Protocol.MESSAGE_ID.values():
                        critical("Unknown ID, exiting.")
                        self.die()
                    raw_message = (yield from self.reader.readexactly(length))
                    message = Protocol.ID_MESSAGE[message_type]()
                    message.ParseFromString(raw_message)
                    yield from self.mumble_received(message)
            except asyncio.IncompleteReadError:
                critical("Disconnected. Reconnecting...")
            except GeneratorExit:
                self.connected = False
        finally:
            self.pinger.cancel()
            self.writer.close()
            if not self.connected:
                self.bots.remove(self)
            if not self.bots:
                l = asyncio.get_event_loop()
                l.stop()
            if self.connected:
                yield from self.reconnect()
示例#2
0
 def handle_text_message(self, message):
     try:
         actor = self.users.by_session(message.actor)
         info("Message from {0}: {1}", actor,
              message.message)
         m = {}
     except KeyError:
         critical("Unknown actor in handle_text_message")
         return
     m['origin'] = actor
     m['private'] = False
     if len(message.session) > 0:  # It's directed as a private message
         info("Received private")
         m['destination'] = self.own_user
         m['private'] = True
     elif message.channel_id:
         info("Received channel message")
         m['destination'] = self.channel_manager.get(message.channel_id[0])
     else:
         info("Received tree message")
         m['destination'] = None
         return m
     m['message'] = message.message
     try:
         x = yield from self.command_manager.handle_message(m)
     except NewBot as e:
         self.create_bot(*e.args[0])
         yield from self.send_text_message("Creating new bot.", m['origin'])
         return
     if isinstance(x, str):
         if m['destination'] == self.get_channel(self.channel):
             s = m['destination']
         else:
             s = m['origin']
         yield from self.send_text_message(x, s)
示例#3
0
    def mumble_received(self, message):
        if isinstance(message, Mumble_pb2.Version):
            pass

        elif isinstance(message, Mumble_pb2.Reject):
            critical("Rejected")
            self.die()


        elif isinstance(message, Mumble_pb2.CodecVersion):
            pass
        elif isinstance(message, Mumble_pb2.CryptSetup):
            pass
        elif isinstance(message, Mumble_pb2.ChannelState):
            self.channel_manager.add_from_message(message)
        elif isinstance(message, Mumble_pb2.PermissionQuery):
            pass
        elif isinstance(message, Mumble_pb2.UserState):
            if self.own_user is None:
                self.own_user = self.users.from_message(message)
                u = self.own_user
                print(u)
            elif message.session and message.session == self.own_user.session:
                self.own_user.update_from_message(message)
                u = self.own_user
            else:
                try:
                    u = self.users.from_message(message)
                except NameError:
                    u = None
            if u and u is not self.own_user:
                if u.channel_id == self.own_user.channel_id:
                    yield from self.user_joined_channel(u)
        elif isinstance(message, Mumble_pb2.ServerSync):
            pass
        elif isinstance(message, Mumble_pb2.ServerConfig):
            if self.connection_lock.locked():
                self.connection_lock.release()  # We're as connected as possible.
            if self.home_server:
                asyncio.Task(self.group_manager.new_group(server=self.home_server))
        elif isinstance(message, Mumble_pb2.Ping):
            pass
        elif isinstance(message, Mumble_pb2.UserRemove):
            pass
        elif isinstance(message, Mumble_pb2.TextMessage):
            yield from self.handle_text_message(message)
        elif isinstance(message, Mumble_pb2.ChannelRemove):
            self.channel_manager.del_channel(message.channel_id)
        else:
            warning("Received unknown message type")
            info(message)
示例#4
0
 def leave(self):
     try:
         yield from self.socket.close()
         yield from self.socket.close_connection()
         self.socket = None
         self.group_loop.cancel()
         self.group_loop = None
     except Exception as e:
         critical(e)
     x = yield from aiohttp.request("GET",
                                    "http://tagpro-%s.koalabeast.com/groups/leave/" % self.server,
                                    cookies=self.cookies,
                                    headers=self.headers,
                                    allow_redirects=False)  # cookies={"tagpro": self.cookie}, headers=headers)
     x.close()
示例#5
0
 def del_perm(self, source, target, *args):
     '''Deletes a permission by name.'''
     name = " ".join(args[:-1])
     perm = args[-1].lower()
     try:
         p = self.get_perm(perm)
         u = self.um.by_name(name)
         if u.del_permission(p):
             yield from self.protocol.send_text_message(
                 "Your {} permissions have been revoked by {}.".format(
                     p.name, source.name), u)
             return "Removed permission {} from user {}.".format(p.name, u.name)
         else:
             return "User {} didn't have permission {}".format(u.name,
                                                               p.name)
     except KeyError as e:
         critical(e)
         return str(e)
示例#6
0
 def test_global_functions(self):
     handler = logbook.TestHandler()
     with handler:
         logbook.debug('a debug message')
         logbook.info('an info message')
         logbook.warn('warning part 1')
         logbook.warning('warning part 2')
         logbook.notice('notice')
         logbook.error('an error')
         logbook.critical('pretty critical')
         logbook.log(logbook.CRITICAL, 'critical too')
     self.assert_(handler.has_debug('a debug message'))
     self.assert_(handler.has_info('an info message'))
     self.assert_(handler.has_warning('warning part 1'))
     self.assert_(handler.has_warning('warning part 2'))
     self.assert_(handler.has_notice('notice'))
     self.assert_(handler.has_error('an error'))
     self.assert_(handler.has_critical('pretty critical'))
     self.assert_(handler.has_critical('critical too'))
     self.assertEqual(handler.records[0].logger_name, 'generic')
     self.assertEqual(handler.records[0].channel, None)
示例#7
0
    def add_perm(self, source, target, *args):
        """Adds a permission by name."""
        name = " ".join(args[:-1])
        perm = args[-1].lower()
        try:
            p = self.get_perm(perm)
            print(p)
            print(p.subpermissions)
            u = self.um.by_name(name)
            if u.add_permission(p):
                yield from self.protocol.send_text_message("You've been given {} permissions by {}." 
				"Use them wisely.".format(p.name, source.name), u)
                return "Added permission {} to user {}.".format(p.name, u.name)
            else:
                return "User {} already had permission {}".format(u.name,
                                                                  p.name)


        except KeyError as e:
            critical(e)
            return str(e)
示例#8
0
 def test_global_functions(self):
     handler = logbook.TestHandler()
     with handler:
         logbook.debug('a debug message')
         logbook.info('an info message')
         logbook.warn('warning part 1')
         logbook.warning('warning part 2')
         logbook.notice('notice')
         logbook.error('an error')
         logbook.critical('pretty critical')
         logbook.log(logbook.CRITICAL, 'critical too')
     self.assert_(handler.has_debug('a debug message'))
     self.assert_(handler.has_info('an info message'))
     self.assert_(handler.has_warning('warning part 1'))
     self.assert_(handler.has_warning('warning part 2'))
     self.assert_(handler.has_notice('notice'))
     self.assert_(handler.has_error('an error'))
     self.assert_(handler.has_critical('pretty critical'))
     self.assert_(handler.has_critical('critical too'))
     self.assertEqual(handler.records[0].channel, 'Generic')
     self.assertEqual(handler.records[0].dispatcher, None)
示例#9
0
def test_global_functions(activation_strategy):
    with activation_strategy(logbook.TestHandler()) as handler:
        logbook.debug('a debug message')
        logbook.info('an info message')
        logbook.warn('warning part 1')
        logbook.warning('warning part 2')
        logbook.notice('notice')
        logbook.error('an error')
        logbook.critical('pretty critical')
        logbook.log(logbook.CRITICAL, 'critical too')

    assert handler.has_debug('a debug message')
    assert handler.has_info('an info message')
    assert handler.has_warning('warning part 1')
    assert handler.has_warning('warning part 2')
    assert handler.has_notice('notice')
    assert handler.has_error('an error')
    assert handler.has_critical('pretty critical')
    assert handler.has_critical('critical too')
    assert handler.records[0].channel == 'Generic'
    assert handler.records[0].dispatcher is None
示例#10
0
def run_with_restart(fn, max_restart=0, args=(), kwargs={}):
    restartCounter = 0
    while True:
        try:
            return apply(fn, args, kwargs)
        except AssertionError:
            raise
        except Exception as e:
            logbook.error("Unhandled exception of type {exctype}: {exception}",
                          exctype=type(e),
                          exception=str(e))

            restartCounter += 1
            if max_restart and restartCounter > max_restart:
                logbook.critical("Alreadying restarted {nth} times. Exiting.",
                                 nth=restartCounter)
            else:
                # Sleep longer each time we restart, but no more than 5 minutes
                delay = min(restartCounter * 15, 300)
                logbook.error("Restarting for {nth} time in {sec} seconds.",
                              nth=restartCounter,
                              sec=delay)
                time.sleep(delay)
示例#11
0
def run_with_restart(fn, max_restart=0, args=(), kwargs={}):
    restartCounter = 0
    while True:
        try:
            return apply(fn, args, kwargs)
        except AssertionError:
            raise
        except Exception as e:
            logbook.error("Unhandled exception of type {exctype}: {exception}",
                          exctype=type(e),
                          exception=str(e))

            restartCounter += 1
            if max_restart and restartCounter > max_restart:
                logbook.critical("Alreadying restarted {nth} times. Exiting.",
                                 nth=restartCounter)
            else:
                # Sleep longer each time we restart, but no more than 5 minutes
                delay = min(restartCounter * 15, 300)
                logbook.error("Restarting for {nth} time in {sec} seconds.",
                              nth=restartCounter,
                              sec=delay)
                time.sleep(delay)
示例#12
0
 def test_global_functions(self):
     handler = logbook.TestHandler()
     handler.push_thread()
     try:
         logbook.debug('a debug message')
         logbook.info('an info message')
         logbook.warn('warning part 1')
         logbook.warning('warning part 2')
         logbook.notice('notice')
         logbook.error('an error')
         logbook.critical('pretty critical')
         logbook.log(logbook.CRITICAL, 'critical too')
     finally:
         handler.pop_thread()
     self.assert_(handler.has_debug('a debug message'))
     self.assert_(handler.has_info('an info message'))
     self.assert_(handler.has_warning('warning part 1'))
     self.assert_(handler.has_warning('warning part 2'))
     self.assert_(handler.has_notice('notice'))
     self.assert_(handler.has_error('an error'))
     self.assert_(handler.has_critical('pretty critical'))
     self.assert_(handler.has_critical('critical too'))
     self.assertEqual(handler.records[0].channel, 'Generic')
     self.assertEqual(handler.records[0].dispatcher, None)