def beg(params, user_info):
     if user_info['data']['id'] == params['be_focused_user_id']:
         return Utils.formatError(CONST['CODE']['BAD_REQUEST']['value'],
                                  '无法添加自己为新朋友')
     addressBookdata = AddressBook.getAdddressBookByFocusedUserId(
         user_info['data']['id'], params['be_focused_user_id'])
     if addressBookdata != None:
         return Utils.formatError(CONST['CODE']['BAD_REQUEST']['value'],
                                  '已添加')
     msg_uuid = Utils.unique_id()
     userData = Users().getOne({Users.id == user_info['data']['id']})
     data = {
         'data': userData,
         'action': 'beg_add',
         'msg_uuid': msg_uuid,
         'be_focused_user_id': params['be_focused_user_id'],
         'focused_user_id': user_info['data']['id']
     }
     socketio.emit('beg',
                   Utils.formatBody(data),
                   namespace='/api',
                   room='@broadcast.' +
                   str(params['be_focused_user_id']))  #,callback=success)
     #只缓存最新的一条
     cache.set('@broadcast.beg' + str(params['be_focused_user_id']), data)
     return Utils.formatBody({}, msg='发送成功')
Beispiel #2
0
 def add(params,user_info):
     ''' 添加通讯录 '''
     if params['focused_user_id'] == user_info['data']['id']:
         return Utils.formatError(Code.BAD_REQUEST,msg='无法添加自己为新朋友')
     filters = {
         AddressBook.focused_user_id == params['focused_user_id'],
         AddressBook.be_focused_user_id == user_info['data']['id']
     }
     addressBookData = AddressBook().getOne(filters)
     if(addressBookData == None):
         # 加入房间号
         room_uuid = Utils.unique_id()
         # 建立通讯录关系
         status = AddressBook.addRoomAndAddressBook(
             room_uuid, params['focused_user_id'], user_info['data']['id'])
         if status == False:
             return Utils.formatError(Code.BAD_REQUEST,msg='添加失败')
     
         #回复被添加用户
         socketio.emit('beg', Utils.formatBody({
             'action':'beg_add_success',
             'focused_user_id' : user_info['data']['id']
         }), namespace='/room', room='@broadcast.'+str(params['focused_user_id']))
         #添加后同步房间
         addressBookData = AddressBook.get(room_uuid)
         for item in addressBookData:
             roomList = AddressBook.getRoomList(item.be_focused_user_id)['data']
             socketio.emit('room',Utils.formatBody(roomList), namespace="/room",room='@broadcast.'+str(item.be_focused_user_id))   
         return Utils.formatBody({},msg='添加成功')
     return Utils.formatError(Code.BAD_REQUEST,msg='已添加')
Beispiel #3
0
 def begCache(params, user_info):
     """ 获取添加好友缓存 """
     data = cache.get('@broadcast.beg'+str(user_info['data']['id']))
     if data is None:
         return Utils.formatBody()
     else:
         cache.delete('@broadcast.beg'+str(user_info['data']['id']))
         return Utils.formatBody(data)
Beispiel #4
0
 def create(params, user_info):
     # 加入房间号
     data = ChatService().groupChatCreate(params, user_info)
     if data:
         #添加后同步房间
         user_room_relation_data = Utils.db_l_to_d(UserRoomRelation.get(data['room_uuid']))
         for item in user_room_relation_data:
             roomList = UserRoomRelation.getRoomList(item['user_id'])
             socketio.emit('groupRoom', Utils.formatBody(roomList), namespace='/api', room='@broadcast.'+str(item['user_id']))
         return Utils.formatBody(data, msg='创建成功')
     return Utils.formatError(CONST['CODE']['BAD_REQUEST']['value'],msg='创建失败')
Beispiel #5
0
 def create(user_info, params):
     # 加入房间号
     data = ChatService().groupChatCreate(user_info, params)
     if data:
         #添加后同步房间
         user_room_relation_data = Utils.db_l_to_d(UserRoomRelation.get(data['room_uuid']))
         for item in user_room_relation_data:
             roomList = UserRoomRelation.getRoomList(item['user_id'])['data']
             socketio.emit('groupRoom', Utils.formatBody(roomList), namespace='/room', room='@broadcast.'+str(item['user_id']))
         return Utils.formatBody(data, msg='创建成功')
     return Utils.formatError(Code.BAD_REQUEST,msg='创建失败')
Beispiel #6
0
 def input(params, user_info):
     filters = {
         AddressBook.focused_user_id == user_info['data']['id'],
         AddressBook.room_uuid == params['room_uuid']
     }
     AddressBook().edit({'is_input': 1}, filters)
     # 发送消息
     data = AddressBook().getOne(filters)
     data['even'] = params['even']
     emit('input',  Utils.formatBody(data),
          room='@broadcast.'+str(data['be_focused_user_id']))
     return Utils.formatBody({'action': "input", "data": data})
Beispiel #7
0
 def updateAlert(params, user_info):
     """ 更新对否提醒 """
     filters = {
         Room.room_uuid == params['room_uuid']
     }
     roomData = Room().getOne(filters)
     if roomData['type'] == 0:
         filters = {
             AddressBook.room_uuid == params['room_uuid'],
             AddressBook.be_focused_user_id == user_info['data']['id']
         }
         data = {
             'is_alert': params['is_alert']
         }
         status = AddressBook().edit(data, filters)
     else:
         filters = {
             UserRoomRelation.room_uuid == params['room_uuid'],
             UserRoomRelation.user_id == user_info['data']['id']
         }
         data = {
             'is_alert': params['is_alert']
         }
         status = UserRoomRelation().edit(data, filters)
     if status:
         return Utils.formatBody()
Beispiel #8
0
 def updateSaveAction(params, user_info):
     """ 更新是否云端保存 """
     filters = {
         Room.room_uuid == params['room_uuid']
     }
     roomData = Room().getOne(filters)
     if roomData['type'] == CONST['ROOM']['ALONE']['value']:
         filters = {
             AddressBook.room_uuid == params['room_uuid'],
             AddressBook.be_focused_user_id == user_info['data']['id']
         }
         data = {
             'save_action': params['save_action']
         }
         status = AddressBook().edit(data, filters)
     else:
         filters = {
             UserRoomRelation.room_uuid == params['room_uuid'],
             UserRoomRelation.user_id == user_info['data']['id']
         }
         data = {
             'save_action': params['save_action']
         }
         status = UserRoomRelation().edit(data, filters)
     if status:
         return Utils.formatBody()
Beispiel #9
0
 def get(params, user_info):
     """ 获取通讯录列表 """
     filters = {
         UserRoomRelation.user_id == user_info['data']['id']
     }
     data = UserRoomRelation().getAll(filters, 'updated_at desc')
     return Utils.formatBody(data)
Beispiel #10
0
 def getByRoomUuid(params, user_info):
     """ 获取群组或单聊信息 """
     filters = {
         Room.room_uuid == params['room_uuid']
     }
     roomData = Room().getOne(filters)
     if roomData['type'] == 0:
         filters = {
             AddressBook.room_uuid == params['room_uuid']
         }
         data = AddressBook().getList( filters, AddressBook.updated_at.desc())
         filters.add(
             AddressBook.be_focused_user_id == user_info['data']['id']
         )
         data['room'] = AddressBook().getOne( filters)
     else:
         filters = {
             UserRoomRelation.room_uuid == params['room_uuid']
         }
         data = UserRoomRelation().getList( filters, UserRoomRelation.updated_at.desc())
         filters.add(
             UserRoomRelation.user_id == user_info['data']['id']
         )
         data['room'] = UserRoomRelation().getOne( filters)
     return Utils.formatBody(data)
 def login(self, data):
     name = data['name']
     #生成一个md5对象
     m1 = hashlib.md5()
     #使用md5对象里的update方法md5转换
     m1.update(data['pwd'].encode("utf-8"))
     pwd = m1.hexdigest()
     #用户名/邮箱/手机登录
     filters = {
         Admin.name == name, Admin.pwd == pwd, Admin.delete_time == 0
     }
     admin = Admin().getOne(filters, 'add_time desc')
     if admin == None:
         filters = {
             Admin.email == name, Admin.pwd == pwd, Admin.delete_time == 0
         }
         admin = Admin().getOne(filters, 'add_time desc')
         if admin == None:
             filters = {
                 Admin.mobile == name, Admin.pwd == pwd,
                 Admin.delete_time == 0
             }
             admin = Admin().getOne(filters, 'add_time desc')
     if admin != None:
         #更新登录时间
         filters = {Admin.id == admin['id']}
         update_time = int(time.time())
         Admin().edit({Admin.update_time: update_time}, filters)
         token = UsersAuthJWT.encode_auth_token(admin['id'], update_time)
         return Utils.formatBody({'token': token, 'user': admin})
     return Utils.formatError(CONST['CODE']['ERROR']['value'])
Beispiel #12
0
 def authenticate(email, password):
     """
     用户登录,登录成功返回token,写将登录时间写入数据库;登录失败返回失败原因
     :param password:
     :return: json
     """
     userInfo = Users().getOne(
         {Users.email == email}, 'id desc',
         ('email', 'password', 'id', 'nick_name', 'head_img'))
     if (userInfo is None):
         return Utils.formatError(Code.BAD_REQUEST, '找不到用户')
     else:
         if (Users.check_password(userInfo['password'], password)):
             updated_at = int(time.time())
             Users().edit({'updated_at': updated_at},
                          {Users.email == email})
             token = UsersAuthJWT.encode_auth_token(userInfo['id'],
                                                    updated_at)
             userInfo.pop('password')  #删除密码
             return Utils.formatBody(
                 {
                     'token': token.decode(),
                     'user': userInfo
                 }, '登陆成功')
         else:
             return Utils.formatError(Code.BAD_REQUEST, '密码不正确')
 def add(self, data=[]):
     #添加
     if 'update_time' in data.keys():
         data['update_time'] = int(time.time())
     #判断用户名
     if 'name' in data.keys():
         filters = {Admin.delete_time == 0, Admin.name == data['name']}
         adminData = Admin().getOne(filters, 'add_time desc')
         if adminData != None:
             return Utils.formatError(CONST['CODE']['ERROR']['value'],
                                      '用户名已经存在')
     #判断手机号码
     if 'mobile' in data.keys():
         filters = {Admin.delete_time == 0, Admin.mobile == data['mobile']}
         admin = Admin().getOne(filters, 'add_time desc')
         if admin:
             return Utils.formatError(CONST['CODE']['ERROR']['value'],
                                      '手机号码已经存在')
     #判断邮箱
     if 'email' in data.keys():
         filters = {Admin.delete_time == 0, Admin.email == data['email']}
         admin = Admin().getOne(filters, Admin.add_time.desc())
         if admin:
             return Utils.formatError(CONST['CODE']['ERROR']['value'],
                                      '邮箱已经存在')
     #生成一个md5对象
     m1 = hashlib.md5()
     #使用md5对象里的update方法md5转换
     m1.update(data['pwd'].encode("utf-8"))
     data['pwd'] = m1.hexdigest()
     res = Admin().add(data)
     if res:
         return Utils.formatBody(msg='添加成功')
     return Utils.formatError(CONST['CODE']['ERROR']['value'], '添加失败')
 def search(params):
     filters = {
         Users.nick_name.like('%' + params['keywords'] + '%')
         | Users.email.like('%' + params['keywords'] + '%')
     }
     userList = Users().getAll(filters)
     data = {"userList": userList}
     return Utils.formatBody(data)
Beispiel #15
0
 def delete(params, user_info):
     filters = {Room.room_uuid == params['room_uuid']}
     roomData = Room().getOne(filters)
     if roomData['type'] == 0:
         address_book_data = Utils.db_l_to_d(
             AddressBook.get(params['room_uuid']))
         filters = {AddressBook.room_uuid == params['room_uuid']}
         AddressBook().delete(filters)
         filters = {Room.room_uuid == params['room_uuid']}
         Room().delete(filters)
         for item in address_book_data:
             roomList = AddressBook.getRoomList(
                 item['be_focused_user_id'])['data']
             socketio.emit('room',
                           Utils.formatBody(roomList),
                           namespace="/room",
                           room='@broadcast.' +
                           str(item['be_focused_user_id']))
             roomList = AddressBook.getRoomList(
                 item['focused_user_id'])['data']
             socketio.emit('room',
                           Utils.formatBody(roomList),
                           namespace="/room",
                           room='@broadcast.' +
                           str(item['focused_user_id']))
     else:
         user_room_relation_data = Utils.db_l_to_d(
             UserRoomRelation.get(params['room_uuid']))
         filters = {
             UserRoomRelation.room_uuid == params['room_uuid'],
             UserRoomRelation.user_id == user_info['data']['id']
         }
         data = UserRoomRelation().delete(filters)
         filters = {Room.room_uuid == params['room_uuid']}
         Room().delete(filters)
         filters = {UserRoomRelation.room_uuid == params['room_uuid']}
         UserRoomRelation().delete(filters)
         for item in user_room_relation_data:
             roomList = UserRoomRelation.getRoomList(
                 item['user_id'])['data']
             socketio.emit('groupRoom',
                           Utils.formatBody(roomList),
                           namespace='/room',
                           room='@broadcast.' + str(item['user_id']))
     return Utils.formatBody()
Beispiel #16
0
 def delMsg(params, user_info):
     """ 删除聊天数据
         :param dict user_info
         :param dict params
         :return dict
     """
     filters = {
         Msg.room_uuid == params['room_uuid'],
         Msg.user_id == user_info['data']['id']
     }
     Msg().delete(filters)
     return Utils.formatBody()
Beispiel #17
0
def join(message, user_info):
    if message['type'] == 0:
        room_uuid = message['room_uuid']
        join_room(room_uuid)
    elif message['type'] == 1:
        room_uuid = message['room_uuid']
        join_room(room_uuid)
    elif message['type'] == 2:
        join_room('@broadcast.'+str(user_info['data']['id']))
    elif message['type'] == 3:#这个暂时用会话id表示,不需要token
        join_room('@api.'+str(request.sid))
    return  Utils.formatBody({'action':"join"})
Beispiel #18
0
    def edit(self, data, filters = {}):
    
        if 'update_time' in data.keys():
            data['update_time'] = time.time()
        adminData = Admin().getOne(filters, 'add_time desc')
        if adminData == None:
            return Utils.formatError(Code.ERROR, '用户不存在')
        #判断用户名
        if 'name' in data.keys():
            filters = {
                Admin.delete_time == 0,
                Admin.name        == data['name'],
                Admin.id          != adminData['id']
            }
            admin = Admin().getOne(filters, 'add_time desc')
            if admin != None:
                return Utils.formatError(Code.ERROR, '用户名已经存在')


        
        #判断手机号码
        if 'mobile' in data.keys():
            filters = {
                Admin.delete_time == 0,
                Admin.mobile      == data['mobile'],
                Admin.id          != adminData['id']
            }
            admin = Admin().getOne(filters, 'add_time desc')
            if admin != None:
                return Utils.formatError(Code.ERROR, '手机号码已经存在')
        
        #判断邮箱
        if 'email' in data.keys():
            filters = {
                Admin.delete_time == 0,
                Admin.email       == data['email'],
                Admin.id          != adminData['id']
            }
            admin = Admin().getOne(filters, Admin.add_time.desc())
            if admin != None:
                return Utils.formatError(Code.ERROR, '邮箱已经存在')
        
        if 'pwd' in data.keys():
            #生成一个md5对象
            m1 = hashlib.md5()
            #使用md5对象里的update方法md5转换
            m1.update(data['pwd'].encode("utf-8"))
            data['pwd'] = m1.hexdigest()      
        res = Admin().edit(data, filters)
        if res==True:
            return Utils.formatBody(msg='编辑成功')
        return Utils.formatError(Code.ERROR, '编辑失败', 0)
Beispiel #19
0
def join(message, user_info):
    if message['type'] == CONST['ROOM']['ALONE']['value']:
        room_uuid = message['room_uuid']
        join_room(room_uuid)
    elif message['type'] == CONST['ROOM']['GROUP']['value']:
        room_uuid = message['room_uuid']
        join_room(room_uuid)
    elif message['type'] == CONST['ROOM']['ADMIN']['value']:
        room_uuid = message['room_uuid']
        join_room(room_uuid)
    elif message['type'] == CONST['ROOM']['NOTIFY']['value']:
        join_room('@broadcast.'+str(user_info['data']['id']))
    return Utils.formatBody({'action': "join"})
Beispiel #20
0
 def updateMsg(params, user_info):
     """ 
         更新聊天数据
         :param dict user_info
         :param dict params
         :return dict
     """
     filters = {
         Msg.room_uuid == params['room_uuid'],
         Msg.created_at == params['created_at'],
         Msg.user_id == user_info['data']['id']
     }
     Msg().edit({'send_status': params['send_status']}, filters)
     return Utils.formatBody()
Beispiel #21
0
 def uploadBase64(params):
     userImg = params['imgDatas'].split(',')[1]
     typeImg = params['imgDatas'].split(',')[0]
     if 'png' in typeImg:
         typeImg = 'png'
     elif 'gif' in typeImg:
         typeImg = 'gif'
     elif 'jpeg' in typeImg:
         typeImg = 'jpeg'
     imgdata = base64.b64decode(userImg)
     path = UPLOAD_FOLDER + Utils.unique_id() + '.' + typeImg
     file = open(os.getcwd() + path, 'wb')
     file.write(imgdata)
     file.close()
     return Utils.formatBody({'path': path}, '上传成功')
Beispiel #22
0
def addressBookBeg(params):
    if params['focused_user_id'] == params['be_focused_user_id']:
        return BaseController().error(msg='无法添加自己为新朋友')
    addressBookdata = AddressBook.getAdddressBookByFocusedUserId(params['focused_user_id'], params['be_focused_user_id'])
    if addressBookdata != None:
        return BaseController().error(msg='已添加')
    msg_uuid = Utils.unique_id()
    userData = Users().getOne({Users.id == params['focused_user_id']})
    socketio.emit('beg', Utils.formatBody({
        'data':userData, 
        'action':'beg_add', 
        'msg_uuid': msg_uuid, 
        'be_focused_user_id': params['be_focused_user_id']
    }), namespace='/room', room='@broadcast.'+str(params['be_focused_user_id']), callback=success)
    return BaseController().successData(msg='发送成功')
Beispiel #23
0
 def adminCreateRoom(message):
     admin_user_info = UsersAuthJWT().adminIdentify(
         message['Authorization'])
     if isinstance(admin_user_info, str):
         return Utils.formatError(CONST['CODE']['ERROR_AUTH_CHECK_TOKEN_FAIL']['value'], admin_user_info)
     filters = {
         Admin.id == admin_user_info['data']['id'],
     }
     admin_user_info = Admin().getOne(filters)
     filters = {
         AddressBook.be_focused_user_id == message['user_id'],
         AddressBook.focused_user_id == admin_user_info['id'],
         AddressBook.type == 1
     }
     addressBookInfo = AddressBook().getOne(filters)
     if addressBookInfo == None:
         room_uuid = Utils.unique_id()
         # 建立通讯录关系
         status = AddressBook.adminAddRoomAndAddressBook(
             room_uuid, admin_user_info, message['user_id'])
         if status == False:
             return Utils.formatError(CONST['CODE']['BAD_REQUEST']['value'], msg='添加失败')
         # 添加后同步房间
         addressBookData = AddressBook.get(room_uuid)
         for item in addressBookData:
             roomList = AddressBook.getRoomList(
                 item.be_focused_user_id)['list']
             if item['type'] == CONST['ADDRESSBOOK']['ADMIN']['value']:
                 socketio.emit('room', Utils.formatBody(
                     roomList), namespace="/api", room='@broadcast.'+str(item.be_focused_user_id))
             else:
                 socketio.emit('room', Utils.formatBody(
                     roomList), namespace="/api", room='@broadcast.'+str(item.be_focused_user_id))
     else:
         room_uuid = addressBookInfo['room_uuid']
     return Utils.formatBody({'room_uuid': room_uuid})
def groupChatCreate(user_info, params):
    # 加入房间号
    data = ChatService().groupChatCreate(user_info, params)
    if data:
        #添加后同步房间
        user_room_relation_data = Utils.db_l_to_d(
            UserRoomRelation.get(data['room_uuid']))
        for item in user_room_relation_data:
            roomList = UserRoomRelation.getRoomList(item['user_id'])
            socketio.emit('groupRoom',
                          Utils.formatBody(roomList),
                          namespace='/api',
                          room='@broadcast.' + str(item['user_id']))
        return BaseController().successData(data, msg='创建成功')
    return BaseController().error(msg='创建失败')
Beispiel #25
0
 def getMsg(params, user_info):
     """
     查询聊天数据
     :param dict user_info
     :param dict params
     :return dict
     """
     filters = {Msg.room_uuid == params['room_uuid']}
     data = Msg().getList(filters, Msg.created_at.desc(), (),
                          params['page_no'], params['per_page'])
     """ def format(x):
         x['msg'] = json.loads(x['msg'])
         return x
     data['list'] = list(map(format, data['list'])) """
     return Utils.formatBody(data)
Beispiel #26
0
 def addMsg(params, user_info):
     """ bug
         添加聊天数据
         :param dict user_info
         :param dict params
         :return dict 
     """
     res = Msg().getOne({
         Msg.room_uuid == params['room_uuid'],
         Msg.created_at == params['created_at'],
         Msg.user_id == params['user_id']
     })
     if res == None:
         params['msg'] = json.dumps(params['msg'])
         Msg().add(params)
     return Utils.formatBody()
Beispiel #27
0
 def upload(params):
     filename = secure_filename(params['name'])
     base64Data = params['dataUrl'].split(',')[1]
     if (base64Data and Utils.allowed_file(filename)):
         file_suffix = params['name'].split('.')[1]
         path = UPLOAD_FOLDER + Utils.unique_id() + '.' + file_suffix
         full_path = os.getcwd() + path
         f = open(full_path, 'wb')
         data = base64.b64decode(base64Data)
         f.write(data)
         #f.write(params['arrayBuffer'])
         f.close
         return Utils.formatBody({
             'path': path,
             'name': filename
         },
                                 msg='上传成功')
     return Utils.formatError(Code.BAD_REQUEST, '文件类型不允许')
Beispiel #28
0
def background_thread():
    """启动一个后台线程来处理所有的延时任务
    """
    while True:
        socketio.sleep(2)
        # 延迟推送
        d_list = delayQueue.consumer()
        for item in d_list:
            if item["action"] == 'invite':
                socketio.emit('beg', Utils.formatBody(
                    item), namespace='/api', room='@broadcast.'+str(item["id"]))
        # 查询用户是否在线
        onlineUsers = delayQueue.client.zrange(
            'onlineUsers', 0, -1, withscores=True)
        for onlineUser in onlineUsers:
            nowTime = int(time.time())
            onlineTime = int(onlineUser[1])+10
            if onlineTime < nowTime:
                UsersService.edit({'online': 0}, {Users.id == onlineUser[0]})
                delayQueue.client.zrem('onlineUsers', onlineUser[0])
            else:
                UsersService.edit({'online': 1}, {Users.id == onlineUser[0]})
Beispiel #29
0
def addressBookAdd(params):
    if params['focused_user_id'] == params['be_focused_user_id']:
        return BaseController().error(msg='无法添加自己为新朋友')
    filters = {
        AddressBook.focused_user_id == params['focused_user_id'],
        AddressBook.be_focused_user_id == params['be_focused_user_id']
    }
    addressBookData = AddressBook().getOne(filters)
    if(addressBookData == None):
        # 加入房间号
        room_uuid = Utils.unique_id()
        # 建立通讯录关系
        status = AddressBook.addRoomAndAddressBook(
            room_uuid, params['focused_user_id'], params['be_focused_user_id'])
        if status == False:
            return BaseController().error(msg='添加失败')
      
        #回复被添加用户
        socketio.emit('beg', Utils.formatBody({
            'action':'beg_add_success'
        }), namespace='/room', room='@broadcast.'+str(params['focused_user_id']))
        return BaseController().successData(msg='添加成功')
    return BaseController().error(msg='已添加')
Beispiel #30
0
def success(data):
    socketio.emit('beg', Utils.formatBody({
        'data':{}, 
        'action':'beg_success'})
    , namespace='/room', room='@broadcast.'+str(data['data']['id']))