Exemple #1
0
async def whisper(chatino=None,
                  unit: Unit = None,
                  ws: websockets.server.WebSocketServerProtocol = None,
                  args: dict = None,
                  cmd: str = None) -> dict:
    logger.debug('Command Whisper started!')
    logger.debug('cmd:' + cmd)
    logger.debug('args:' + str(args))
    room = args['room']
    text = args['text']
    target = args['target']

    # 注意这些可选参数
    message: Message = Message(
        room,
        unit.username,
        text,
        time.time(),
        type_=args.get('type', MessageType.text),
        # visibility=args.get('visibility', Visibility.public),
        # status=args.get('status', Status.available),
        direction=target)
    try:
        await chatino.push_message(message)
    except ChatinoException.BaseException as e:
        return utils.make_result(1, message=str(e))
    return utils.make_result(0)
Exemple #2
0
 async def parser(self, ws, unit: config.Unit):
     while True:
         # 还是有可能接收失败
         try:
             try:
                 resp = await ws.recv()
             except (websockets.exceptions.ConnectionClosedError,
                     websockets.exceptions.ConnectionClosedOK) as e:
                 logger.warning('Connection error: ' + str(e))
                 break
             try:
                 data = json.loads(str(resp))
             except json.decoder.JSONDecodeError:
                 # 数据错误
                 await ws.send(utils.dump(utils.make_result(2)))
                 continue
             # 找找有没有对应命令
             cmd = data['cmd']
             args = data['args']
             if cmd not in Commands.commands_table:
                 # 命令错误
                 await ws.send(utils.dump(utils.make_result(4)))
                 continue
             # 检查参数合理性
             reasonable = True
             for arg in Commands.commands_table[cmd]['args']:
                 if arg not in args and Commands.commands_table[cmd][
                         'args'][arg]['necessary']:
                     reasonable = False
                     break
                 if Commands.commands_table[cmd]['args'][arg]['type'] is not None and \
                         type(args[arg]) is not Commands.commands_table[cmd]['args'][arg]['type']:
                     reasonable = False
                     break
             if not reasonable:
                 # 参数不合理
                 await ws.send(utils.dump(utils.make_result(5)))
                 continue
             logger.debug('Recv: ' + str(resp))
             # username = unit.username
             function = Commands.commands_table[cmd]['function']
             result = await function(chatino=self,
                                     unit=unit,
                                     ws=ws,
                                     cmd=cmd,
                                     args=args)
             await ws.send(utils.dump(result))
         except (websockets.exceptions.ConnectionClosedError,
                 websockets.exceptions.ConnectionClosedOK) as e:
             logger.warning('Connection error: ' + str(e))
             break
Exemple #3
0
async def exit_(chatino=None,
                unit: Unit = None,
                ws: websockets.server.WebSocketServerProtocol = None,
                args: dict = None,
                cmd: str = None) -> dict:
    logger.debug('Command Exit started!')
    logger.debug('cmd:' + cmd)
    logger.debug('args:' + str(args))
    room = args['room']
    try:
        await chatino.exit_room(unit.username, room)
    except ChatinoException.BaseException as e:
        return utils.make_result(1, message=str(e))
    return utils.make_result(0)
Exemple #4
0
async def start(ws):
    while True:
        try:
            raw = await ws.recv()
            # print('raw', raw)
            data = json.loads(raw)
        except Exception as e:
            print('except:', utils.make_error_result(e))
            await ws.send(utils.dump(utils.make_error_result(e)))
            continue
        # print(data)
        if data is None:
            # 数据无效
            await ws.send(utils.dump(utils.make_result(2)))
            continue
        # 处理数据
        if not utils.verify(data) or data['cmd'] != 'start' or 'password' not in data['args']:
            # 命令无效
            await ws.send(utils.dump(utils.make_result(3)))
            continue
Exemple #5
0
    async def ws_start(self, ws) -> config.Unit:
        while True:
            try:
                try:
                    raw = await ws.recv()
                    # print('raw', raw)
                    data = json.loads(raw)
                except Exception as e:
                    print('except:', utils.make_error_result(e))
                    await ws.send(utils.dump(utils.make_error_result(e)))
                    continue
                # print(data)
                if data is None:
                    # 数据无效
                    await ws.send(utils.dump(utils.make_result(2)))
                    continue
                # 处理数据
                if not utils.verify(data) or data['cmd'] != 'start':
                    # 命令无效
                    await ws.send(utils.dump(utils.make_result(2)))
                    continue
                args = data['args']
                if ('username' not in args
                        and 'token' not in args) or ('username' in args
                                                     and 'token' in args):
                    # 命令无效(token和username必须有且只有一个)
                    await ws.send(utils.dump(utils.make_result(2)))
                    continue

                # 一下几个选项必须生成token
                token = ''
                unit = None
                if 'username' in args and 'password' not in args:
                    # 匿名模式
                    # 先创建token
                    username = args['username']
                    unit = self.db.token_create(username)
                    token = unit.token
                if 'username' in args and 'password' in args:
                    # 登录模式
                    # 登录校验
                    username, password = args['username'], args['password']
                    if not self.db.user_verify(username, password=password):
                        # 登录失败
                        await ws.send(utils.dump(utils.make_result(3)))
                        continue
                    unit = self.db.token_create(username)
                    token = unit.token
                if 'token' in args:
                    token = args['token']

                username = self.db.token_to_username(token)
                if username is None:
                    # 认证失败
                    await ws.send(utils.dump(utils.make_result(3)))
                    continue
                user = None
                try:
                    user = self.db.user_find(username)
                except ChatinoException.UsernameNotFound:
                    # 找不到user的情况下,user在unit中是None
                    pass
                # for i in user:
                #     unit['user'][i] = user[i]
                # unit = self.unit_create(username, token, ws, user=user)
                # 只提供了token的情况
                if unit is None:
                    unit = config.Unit(username, token, ws, user=user)
                # ws的补充
                if unit.ws is None:
                    unit.ws = ws
                if unit.user is None:
                    unit.user = user
                    # 补充了user之后也可能是None

                # 最后加入online_users,当做登录
                # global config.online_users
                # 注意这里的username变量已经变成None了
                config.online_users[unit.username] = unit
                # 返回成功的值
                await ws.send(
                    utils.dump(utils.make_result(0, data=unit.to_dict())))
                # break
                return unit
            except (websockets.exceptions.ConnectionClosedOK,
                    websockets.exceptions.ConnectionClosedError) as e2:
                logger.warning('Connection error: ' + str(e2))
                break