def createUserInviteCode(self): cursor = ClassHelper('User').find({}) if cursor: i = 0 for u in cursor: code = ClassHelper('InviteCode').find_one({'from': u['_id'], 'status': 0}) n = 0 if not code: while (True): try: invite_code = MeObject('InviteCode') invite_code['code'] = InviteCodeUtil.create_code() invite_code['status'] = 0 invite_code['from'] = u['_id'] invite_code.save() n = n + 1 logger.debug('create invite code success') self.notify_new_code(u['_id']) # logger.debug('create invite code finish %d', i) if n >= 1: break except Exception, e: logger.error(e) else: logger.debug('user already has a code') i = i + 1 logger.debug('finish %d', i) logger.debug('all finish')
def saveCid(self): try: cid = self.jsonBody['cid'] platform = self.jsonBody['platform'] logger.debug('cid: %s, platform: %s', cid, platform) userid = self.user['_id'] # userid = '5a016819ca71430a9d0fe108' logger.debug('userid: %s', userid) push_cid_obj = ClassHelper('PushCid').find_one({'userid': userid}) print push_cid_obj push_cid = MeObject('PushCid', obj=push_cid_obj) print type(push_cid) push_cid['userid'] = userid push_cid['platform'] = platform push_cid['cid'] = cid push_cid['logout'] = False push_cid.save() self.write(ERR_SUCCESS.message) r = ClassHelper('PushCid').db.update_many('PushCid', { 'cid': cid, 'userid': { '$ne': userid }, 'logout': False }, {'$set': { 'logout': True }}) logger.debug('r:%s', r) except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def unreadListByFromId(self): try: # test msg_id # ObjectId("59dc380051159a123fe8a230") # msg_id = self.get_argument('id') # logger.debug("id: %s", msg_id) print self.user['_id'] # to_id = "59ca0b46ca714306705996dc" to_id = self.user['_id'] from_id = self.get_argument('from_id') m_id = self.get_argument('m_id') logger.debug('from_id: %s, m_id: %s', from_id, m_id) # if msg_id: # query = {"to_id": to_id, "status": 0, # "_id": {"$lt": ObjectId(msg_id)}} # else: # query = {"to_id": to_id, "status": 0} query = { "to_id": to_id, "status": 0, "from_id": from_id, "msg_type": 2, "m_id": m_id } print query helper = ClassHelper('Message') cursor = helper.find(query) unread_list = [] if cursor: for data in cursor: logger.debug('data:%s', data) unread_list.append(data) logger.debug(unread_list) # print unread_list.__len__() if unread_list: for unread_msg in unread_list: unread_msg['id'] = unread_msg['_id'] unread_msg['create_at'] = long( unread_msg['createAt'].strftime('%s')) * 1000 del unread_msg['_id'] if unread_msg.get('acl', None) is not None: del unread_msg['acl'] del unread_msg['createAt'] del unread_msg['updateAt'] result = {} result['errCode'] = 0 result['unread_list'] = unread_list r = json.dumps(result, ensure_ascii=False) self.write(str(r)) # , cls=CJsonEncoder #格式化时间 except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def notify_new_code(self, userid): # 长链接通知 title = '恭喜获得了一枚新的黑蜜邀请码' content = '快分享给朋友一起来玩吧' uri = 'honey://newInviteCode' message_dict = {'t': 'notify'} message_dict['title'] = title message_dict['subtitle'] = content message_dict['avatar'] = None message_dict['to_id'] = userid message_dict['uri'] = uri message_json = json.dumps(message_dict, ensure_ascii=False) logger.debug('publish_message:%s', message_json) rc = RedisDb.get_connection() publish_result = rc.publish(Constants.REDIS_CHANNEL_FOR_PUSH, message_json) logger.debug('publish_result: %s', publish_result) push_cid_obj = ClassHelper('PushCid').find_one({'userid': userid}) logger.debug('push_cid_obj: %s', push_cid_obj) if (push_cid_obj is None) or push_cid_obj['logout'] is True: # 没有找到对应的push_cid self.write(ERR_PARA.message) return push_cid = MeObject('PushCid', obj=push_cid_obj) result = MyGtUtil.pushMessageToSingle(push_cid['cid'], title.decode("utf-8"), content.decode("utf-8"), data=uri) logger.debug('push result:%s', result)
def saveCid(self): try: cid = self.jsonBody['cid'] platform = self.jsonBody['platform'] logger.debug('cid: %s, type: %s', cid, type) userid = self.user['_id'] logger.debug('userid: %s', userid) push_cid_obj = ClassHelper('PushCid').find_one({'userid': userid}) print push_cid_obj push_cid = MeObject('PushCid', obj=push_cid_obj) # if push_cid is None: # push_cid = MeObject('PushCid') # else: # push_cid = Me print type(push_cid) push_cid['userid'] = userid push_cid['platform'] = platform push_cid['cid'] = cid push_cid.save() self.write(ERR_SUCCESS.message) except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def searchUser(self): try: logger.debug(self.jsonBody) obj = self.jsonBody content = obj.get('content') logger.debug('search content:%s', content) scroll_id = obj.get('scrollId', None) page_size = obj.get('pageSize', None) if not page_size: page_size = 10 if page_size is None or page_size <= 0 or page_size > EsClient.USER_PAGE_SIZE: page_size = EsClient.USER_PAGE_SIZE # logger.debug('scroll_id: %s', scroll_id) # logger.debug('page_size: %d', page_size) if not content and not scroll_id: self.write(ERR_PARA.message) else: # print content.replace(' ', '') # es 搜索 (去空格) searched = EsClient.searchUser(content.replace(' ', ''), scroll_id, pageSize=page_size) users = [] for item in searched['hits']['hits']: source = item['_source'] del source['pinyin'] del source['pinyinsmall'] users.append(source) # print users logger.debug('find num: %d', users.__len__()) result = {} result['scrollId'] = searched['_scroll_id'] result['users'] = users if users.__len__() > 0: followerHelper = ClassHelper('Followee') for user in result['users']: r = CountHelper.get_specific_count(user['user']) logger.debug('r:%s', r) logger.debug('nickName: %s,user: %s', user['nickName'], user['user']) user['fansCount'] = r['followers'] user['followers'] = r['followers'] # TODO 计算来自XX人贡献了xx照片 user['assigners'] = r['assigners'] user['contributeCount'] = r['assigners'] user['imageCount'] = r['medias'] user['medias'] = r['medias'] user['isUser'] = 1 del user['id'] # logger.debug('final result:' + json.dumps(result, ensure_ascii=False)) result['errCode'] = 0 # 执行成功code=0 self.write(result) except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def owned(self): # '5a0a7f88ca714378820c022f' invite_code = ClassHelper('InviteCode').find_one({'from': self.user['_id'], 'status': 0}) result = deepcopy(ERR_SUCCESS.message) code = None if invite_code: code = invite_code['code'] result['code'] = code self.write(result)
def push(self): try: userid = self.jsonBody['userid'] otherid = self.jsonBody['otherid'] action = self.jsonBody.get('action') logger.debug('userid: %s, otherid: %s, action: %s', userid, otherid, action) if userid is None or action is None or otherid is None: self.write(ERR_PARA.message) return uri = action_uri_dict.get(action, None) if uri is None: self.write(ERR_PARA.message) return uri = 'honey://' + uri logger.debug('uri: %s', uri) if action == 'claimed': uri = uri + '/' + otherid notify_content = self.getNotifyContent(action, otherid) logger.debug('notify_content: %s', notify_content) if notify_content is None: self.write(ERR_PARA.message) return # 长链接通知 message_dict = {'t': 'notify'} message_dict['title1'] = notify_content['title'] # message_dict['title2'] = notify_content['title2'] message_dict['title2'] = notify_content['content'] message_dict['to_id'] = userid message_dict['uri'] = uri message_json = json.dumps(message_dict, ensure_ascii=False) logger.debug(message_json) rc = RedisDb.get_connection() publish_result = rc.publish(Constants.REDIS_CHANNEL_FOR_PUSH, message_json) logger.debug('public_result: %s', publish_result) push_cid_obj = ClassHelper('PushCid').find_one({'userid': userid}) logger.debug('push_cid_obj: %s', push_cid_obj) if push_cid_obj is None: # 没有找到对应的push_cid self.write(ERR_PARA.message) return push_cid = MeObject('PushCid', obj=push_cid_obj) result = MyGtUtil.pushMessageToSingle( push_cid['cid'], notify_content['title'].decode("utf-8"), notify_content['content'].decode("utf-8"), data=uri) logger.debug('result:%s', result) # result = PushUtil.pushMessageToSingle() self.write(result) except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def getFace(self, media, userid1, userid2): faces = media.get('faces', []) logger.debug('faces:%s', faces) if not faces: return {} face_helper = ClassHelper('Face') face = {} for faceId in faces: face = face_helper.get(faceId) logger.debug('face:%s', face) if not face: face = {} continue assign = face.get('assign', None) if not assign: continue if (assign.get('user', None) == userid1 or assign.get( 'user', None) == userid2) and assign.get('status') == 1: return face return face
def check(self): # code = self.jsonBody.get('code') device = self.jsonBody.get('device') logger.debug('active check, device:%s', device) active_device = ClassHelper('ActiveDevice').find_one({'device': device}) if active_device: logger.debug('device:%s active true', device) r = {'errCode': 0, 'active': True} else: logger.debug('device:%s active false', device) r = {'errCode': 0, 'active': False} self.write(r)
def flow(self): id = self.get_argument('id', None) size = int(self.get_argument('size', 10)) userid = self.user['_id'] # userid = '59dc3decca7143413c03a62f' if id: query = {'user': userid, "_id": {"$lt": ObjectId(id)}} else: query = {'user': userid} cursor = ClassHelper('IncomeFlow').find(query, limit=size) data_list = [] if cursor: for data in cursor: data['id'] = data['_id'] del data['_id'] # logger.debug('new time:%s', datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S.%f%Z')) # new_date = datetime.strptime(data['createAt'], '%Y-%m-%d %H:%M:%S.%f%Z') create_at = data['createAt'].strftime('%Y-%m-%d %H:%M:%S') logger.debug('create_at:%s', create_at) data['create_at'] = create_at data['mosaic'] = 1 del data['_sid'] del data['updateAt'] del data['createAt'] del data['user'] data_list.append(data) logger.debug('data_list size:%d', data_list.__len__()) result = {} result['code'] = 0 result['errCode'] = 0 result['flows'] = data_list self.write(result) # 新收益计数清空 ClassHelper('StatCount').updateOne({'name': 'newIncome_' + userid}, {"$set": { 'count': 0 }}, upsert=True)
def createCommentSession(self): cursor = ClassHelper('Message').find({'msg_type': 2}) if cursor: i = 1 for d in cursor: m = MeObject('Message', obj=d) logger.debug('message id :%s', m['_id']) logger.debug('fromid:%s toid:%s', m['from_id'], m['to_id']) session = SessionUtil.create(m['from_id'], m['to_id']) logger.debug('session:%s', session) m['session'] = session m.save() logger.debug('%d finish', i) i = i + 1 # break logger.debug('all finish')
def index(self): try: userid = self.user['_id'] # userid = '5a1aea98ca714333dda69c5c' cursor = ClassHelper('StatCount').find({'name': { '$in': ['unreadMsg_' + userid, 'newFans_' + userid, 'toClaim_' + userid, 'newIncome_' + userid]}}) unread_msg = 0 fans = 0 unclaimed = 0 earnings = 0 if cursor: for data in cursor: if data['name'] == 'unreadMsg_' + userid: unread_msg = data['count'] elif data['name'] == 'newFans_' + userid: fans = data['count'] elif data['name'] == 'toClaim_' + userid: unclaimed = data['count'] elif data['name'] == 'newIncome_' + userid: earnings = data['count'] result = {} result['code'] = 0 result['errCode'] = 0 result['fans'] = fans # result['unread_msg'] = unread_msg result['unread_msg'] = ClassHelper('Message').query_count({'to_id': userid, 'status': 0}) result['earnings'] = earnings result['unclaimed'] = unclaimed result['feedCount'] = int(RedisDb.get('user_unread_feed_count_%s' % userid) or 0) faceHelper = ClassHelper( 'FaceRecommend' ) sid = RedisDb.hget( "recommendSLatestOid", userid) if sid: query={'_sid': {"$lte": sid},'user': userid, 'read': {'$exists': False},'backupUser': {'$exists': False}} result['similarCount'] = faceHelper.query_count(query) else: result['similarCount'] = 0 recommendHelper = ClassHelper('UserRecommend') result['possibleCount'] = recommendHelper.query_count({'user': userid}) self.write(result) except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def post(self, action=None): try: logger.debug('Cookie: %s', self.request.headers['Cookie']) cookie = self.request.headers['Cookie'].split('"')[1] RedisDb.delete(cookie) self.clear_cookie('u') push_cid_obj = ClassHelper('PushCid').find_one( {'userid': self.user['_id']}) if push_cid_obj: push_cid = MeObject('PushCid', obj=push_cid_obj) push_cid['logout'] = True push_cid.save() self.write(ERR_SUCCESS.message) except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_INVALID.message)
def read(self): obj = self.jsonBody from_id = obj.get('from_id') m_id = obj.get('m_id') message_id = obj.get('message_id') # message_id = '59db35da51159a0e1b5145de' #for test args helper = ClassHelper('Message') r = helper.db.update_many( 'Message', { '_id': { '$lte': ObjectId(message_id) }, 'status': 0, 'from_id': from_id, 'msg_type': 2, 'm_id': m_id }, {'$set': { "status": 1 }}) logger.debug('read comment r:%s', r) self.write(ERR_SUCCESS.message)
def activate(self): logger.debug('invite code activate start ') code = self.jsonBody.get('code') device = self.jsonBody.get('device') invite_code = ClassHelper('InviteCode').find_one({'code': code, 'status': 0}) logger.debug('jsonBody:%s', self.jsonBody) if not invite_code: logger.debug('invite code error') result = deepcopy(ERR_PARA.message) result['errMsg'] = '邀请码错误' result['msg'] = 'invite code error' self.write(result) return else: active_device = MeObject('ActiveDevice') active_device['device'] = device active_device['code'] = code try: active_device.save() invite_code_obj = MeObject('InviteCode', obj=invite_code) invite_code_obj['status'] = 1 # invite_code_obj['to'] = self.user['_id'] invite_code_obj.save() logger.debug('success') self.write(ERR_SUCCESS.message) return except Exception, e: logger.debug('device already active') logger.error(e) msg = traceback.format_exc() logger.error(msg) result = deepcopy(ERR_DEVICE_ALREADY_ACTIVE.message) result['errMsg'] = '设备已激活,不能重复激活' result['msg'] = 'device already active' self.write(result) return
def send(self): try: logger.debug(self.jsonBody) obj = self.jsonBody logger.debug('to_id:' + obj.get('to_id')) logger.debug('c: %s', obj.get('c')) logger.debug('c_type: %s', obj.get('c_type')) logger.debug('m_id: %s', obj.get('m_id')) media_id = obj.get('m_id') from_id = self.user['_id'] logger.debug('from_id: %s', from_id) user_query = MeQuery("UserInfo") user_info = user_query.find_one({'user': from_id}) message_dict = { 'from_id': from_id, 'c': obj.get('c'), 'to_id': obj.get('to_id'), 'c_type': obj.get('c_type'), 'msg_type': 2, 'from_avatar': user_info['avatar'], 'from_name': user_info['nickName'], 'status': 0, 'm_id': media_id } message = MeObject('Message', obj=message_dict) message.save() # 格式化时间为long型 message_dict['create_at'] = long( message['createAt'].strftime('%s')) * 1000 message_dict['t'] = 'comment' message_dict['id'] = message['_id'] message_json = json.dumps(message_dict, ensure_ascii=False) logger.debug(message_json) print type(message['createAt']) rc = RedisDb.get_connection() rc.publish(Constants.REDIS_CHANNEL_FOR_PUSH, message_json) # 发push push_cid_obj = ClassHelper('PushCid').find_one( {'userid': obj.get('to_id')}) logger.debug('push_cid_obj: %s', push_cid_obj) if push_cid_obj: # push_cid = MeObject('PushCid', obj=push_cid_obj) title = user_info['nickName'] content = '新评论' data = 'honey://comment/' + from_id + '?m_id=' + media_id print title.encode('utf-8') print content.encode('utf-8') t = threading.Thread(target=MyGtUtil.pushMessageToSingle, args=( push_cid_obj['cid'], title.encode('utf-8'), content.encode('utf-8'), data, )) t.setDaemon(True) t.start() # logger.debug(ERR_SUCCESS.message) r = {} r['id'] = message['_id'] r['code'] = 0 r['create_at'] = message_dict['create_at'] self.write(r) except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def goodsInfo(self): try: userid = self.user['_id'] # userid = '5a08fbfbca714330cfd35ddc' message_id = self.get_argument('message_id', None) message = ClassHelper('Message').get(message_id) if not message: self.write(ERR_PARA.message) return logger.debug('message:%s', message) file_id = message['m_id'] media = ClassHelper('Media').find_one({'file': file_id}) logger.debug('media:%s', media) face = None if media: face = self.getFace(media, message['from_id'], message['to_id']) logger.debug('face1 %s:', face) if not face: face['goodsId'] = None face['mosaic'] = 2 face['price'] = 0 logger.debug('未找到face') else: face['goodsId'] = None face['mosaic'] = 10 face['price'] = 0 if face.get('assign', None): owner_id = face['assign']['user'] good = ClassHelper('Goods').find_one( {'goods': face['_id']}) if good: face['user'] = face['assign']['user'] face['goodsId'] = good['_id'] price = good['price'] if good else 0 face['price'] = price if media.get('uploader', None) and media['uploader'] == userid: # 照片贡献者 face['mosaic'] = 0 elif owner_id == userid: # 照片认领者 face['mosaic'] = 5 if face['mosaic'] != 0: charge_record = ClassHelper( 'ChargeFlow').find_one({ 'user': userid, 'goods': good['_id'], 'status': 1 }) if good else None logger.debug('charge_record%s', charge_record) if charge_record: face['mosaic'] = 1 else: logger.warn('goods is null') # self.write(ERR_PARA.message) # return userInfo = {} if media: logger.debug('uploader:%s', media.get('uploader', None)) user_info_obj = ClassHelper('UserInfo').find_one( {'user': media.get('uploader', None)}) logger.debug('user_info_obj:%s', user_info_obj) if user_info_obj: userInfo['_id'] = user_info_obj['_id'] userInfo['avatar'] = user_info_obj['avatar'] userInfo['nickName'] = user_info_obj['nickName'] logger.debug('userInfo:%s', userInfo) if media and face: r = {} r['errCode'] = 0 r['width'] = media.get('width', 0) r['height'] = media.get('height', 0) r['media'] = media['_id'] r['file'] = media['file'] r['goodsId'] = face['goodsId'] r['mosaic'] = face['mosaic'] r['price'] = face['price'] r['_id'] = face['_id'] r['user'] = face.get('user', None) r['userInfo'] = userInfo if face.get('rect', None) is not None: r['rect'] = face.get('rect') r['message_id'] = message_id self.write(r) else: r = {} r['errCode'] = 0 r['width'] = 0 r['height'] = 0 r['media'] = None r['file'] = None r['goodsId'] = None r['mosaic'] = 0 r['price'] = 0 r['_id'] = None r['user'] = None r['rect'] = None r['userInfo'] = None r['message_id'] = message_id self.write(r) except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def send(self): try: logger.debug(self.jsonBody) obj = self.jsonBody logger.debug('to_id:' + obj.get('to_id')) logger.debug('c: %s', obj.get('c')) logger.debug('c_type: %s', obj.get('c_type')) logger.debug('m_id: %s', obj.get('m_id')) media_id = obj.get('m_id') from_id = self.user['_id'] logger.debug('from_id: %s', from_id) user_query = MeQuery("UserInfo") user_info = user_query.find_one({'user': from_id}) message_dict = { 'from_id': from_id, 'c': obj.get('c'), 'to_id': obj.get('to_id'), 'c_type': obj.get('c_type'), 'msg_type': 2, 'from_avatar': user_info['avatar'], 'from_name': user_info['nickName'], 'status': 0, 'm_id': media_id } message = MeObject('Message', obj=message_dict) message['session'] = SessionUtil.create(from_id, obj.get('to_id')) message.save() # 格式化时间为long型 message_dict['create_at'] = long( message['createAt'].strftime('%s')) * 1000 message_dict['t'] = 'comment' message_dict['id'] = message['_id'] message_json = json.dumps(message_dict, ensure_ascii=False) logger.debug(message_json) print type(message['createAt']) rc = RedisDb.get_connection() rc.publish(Constants.REDIS_CHANNEL_FOR_PUSH, message_json) # 发push push_cid_obj = ClassHelper('PushCid').find_one( {'userid': obj.get('to_id')}) logger.debug('push_cid_obj: %s', push_cid_obj) if push_cid_obj and (push_cid_obj['logout'] is False): # push_cid = MeObject('PushCid', obj=push_cid_obj) title = user_info['nickName'] content = obj.get('c') content = PushEmoji.getPushContent(content) data = 'honey://comment/' + from_id + '?m_id=' + media_id print title.encode('utf-8') print content.encode('utf-8') claim_count = 0 message_count = 0 stat1 = ClassHelper('StatCount').find_one( {'name': 'toClaim_' + obj.get('to_id')}) if stat1: claim_count = stat1['count'] if claim_count < 0: claim_count = 0 stat2 = ClassHelper('StatCount').find_one( {'name': 'unreadMsg_' + obj.get('to_id')}) if stat2: message_count = stat2['count'] if message_count < 0: message_count = 0 badge = claim_count + message_count t = threading.Thread(target=MyGtUtil.pushMessageToSingle, args=( push_cid_obj['cid'], title.encode('utf-8'), content.encode('utf-8'), data, badge, )) t.setDaemon(True) t.start() # logger.debug(ERR_SUCCESS.message) r = {} r['id'] = message['_id'] r['code'] = 0 r['errCode'] = 0 r['create_at'] = message_dict['create_at'] self.write(r) # 计数 unreadMsg +1 logger.debug('update to_id:unreadMsg_%s unreadMsg count ', obj.get('to_id')) ClassHelper('StatCount').updateOne( {'name': 'unreadMsg_' + obj.get('to_id')}, {"$inc": { 'count': 1 }}, upsert=True) except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def listByFromId(self): try: # test msg_id # ObjectId("59dc380051159a123fe8a230") message_id = self.get_argument('message_id', default=None) count = int(self.get_argument('count', default=100)) logger.debug("count: %s", count) if count > 100: count = 100 logger.debug("message_id: %s, count: %s", message_id, count) # print self.user['_id'] to_id = self.user['_id'] # to_id = '5a018adeca714319e603ca09' # to_id = '5a018adeca714319e603ca09' # to_id = '5a0188ccca714319e603c9e8' from_id = self.get_argument('from_id') m_id = self.get_argument('m_id') logger.debug('from_id: %s, m_id: %s', from_id, m_id) helper = ClassHelper('Message') unread_list = [] if not message_id: query = { 'from_id': from_id, 'to_id': to_id, 'm_id': m_id, 'msg_type': 2, 'status': 0 } logger.debug('unread query:%s', query) cursor = helper.find(query, limit=count, sort={"_id": -1}) logger.debug('cursor when not message_id:%s', cursor) if cursor: for data in cursor: logger.debug('data:%s', data) unread_list.append(data) logger.debug('real unread_list:%s', unread_list) if not unread_list: if message_id: query = { "$or": [{ "to_id": to_id, "from_id": from_id }, { "to_id": from_id, "from_id": to_id }], "msg_type": 2, "m_id": m_id, "_id": { "$lt": ObjectId(message_id) } } else: query = { "$or": [{ "to_id": to_id, "from_id": from_id }, { "to_id": from_id, "from_id": to_id }], "msg_type": 2, "m_id": m_id } logger.debug('query: %s', query) cursor = helper.find(query, limit=count, sort={"_id": -1}) if cursor: for data in cursor: logger.debug('data:%s', data) unread_list.append(data) logger.debug('unread_list:%s', unread_list) if unread_list: unread_list.reverse() for unread_msg in unread_list: unread_msg['id'] = unread_msg['_id'] unread_msg['create_at'] = long( unread_msg['createAt'].strftime('%s')) * 1000 del unread_msg['_id'] if unread_msg.get('acl', None) is not None: del unread_msg['acl'] del unread_msg['createAt'] del unread_msg['updateAt'] if unread_msg['from_id'] == to_id: unread_msg['status'] = 1 result = {} result['errCode'] = 0 result['unread_list'] = unread_list r = json.dumps(result, ensure_ascii=False) self.write(str(r)) # , cls=CJsonEncoder #格式化时间 except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def read(self): obj = self.jsonBody logger.debug('comment read json body:%s', obj) to_id = self.user['_id'] # to_id = '5a018adeca714319e603ca09' from_id = obj.get('from_id') m_id = obj.get('m_id') message_id = obj.get('message_id', None) message_ids = obj.get('message_ids', None) helper = ClassHelper('Message') if message_id: r = helper.db.update_many( 'Message', { '_id': { '$lte': ObjectId(message_id) }, 'status': 0, 'from_id': from_id, 'msg_type': 2, 'to_id': to_id, 'm_id': m_id }, {'$set': { "status": 1 }}) logger.debug('read comment r:%s', r) self.write(ERR_SUCCESS.message) if r: logger.debug('nModified:%d', r['nModified']) if r['nModified'] > 0: logger.debug('reduce name :unreadMsg_%s unreadMsg count', self.user['_id']) ClassHelper('StatCount').updateOne( {'name': 'unreadMsg_' + self.user['_id']}, {"$inc": { 'count': -r['nModified'] }}, upsert=False) if message_ids: ids = [] for i in str(message_ids).split(','): ids.append(i) logger.debug('ids:%s', ids) r = helper.db.update_many( 'Message', { '_id': { '$in': ids }, 'status': 0, 'from_id': from_id, 'msg_type': 2, 'to_id': to_id, 'm_id': m_id }, {'$set': { "status": 1 }}) logger.debug('read comment r:%s', r) self.write(ERR_SUCCESS.message) if r: logger.debug('nModified:%d', r['nModified']) if r['nModified'] > 0: logger.debug('reduce name :unreadMsg_%s unreadMsg count', self.user['_id']) ClassHelper('StatCount').updateOne( {'name': 'unreadMsg_' + self.user['_id']}, {"$inc": { 'count': -r['nModified'] }}, upsert=False)
def unreadList(self): try: logger.debug('self.userid: %s:', self.user['_id']) all = int(self.get_argument('all', 0)) logger.debug('all: %s', all) userid = self.user['_id'] logger.debug('userid:%s', userid) # userid = '5a0188ccca714319e603c9e8' # userid = '5a0d4d88ca71432378862c53' if all == 1: # match = {"$match": {"to_id": self.user['_id'], # "msg_type": 2}} # {"$or": [{"to_id": to_id, "from_id": from_id}, {"to_id": from_id, "from_id": to_id}] match = { "$match": { "$or": [{ "to_id": userid }, { "from_id": userid }], "msg_type": 2 } } else: match = { "$match": { "to_id": userid, "status": 0, "msg_type": 2 } } # "59ca0b46ca714306705996dc" logger.debug('match:%s', match) message_query = MeQuery("Message") unread_list = message_query.aggregate([ match, { "$group": { "_id": { "from_id": "$session", "m_id": "$m_id" }, # "count": {"$sum": 1}, "c": { "$last": "$c" }, "id": { "$last": "$_id" }, "create_at": { "$last": "$createAt" }, "c_type": { "$last": "$c_type" }, "status": { "$last": "$status" }, "from_name": { "$last": "$from_name" }, "msg_type": { "$last": "$msg_type" }, "from_id": { "$last": "$from_id" }, "to_id": { "$last": "$t" "o_id" }, "from_avatar": { "$last": "$from_avatar" }, "m_id": { "$last": "$m_id" } } }, { "$sort": { "create_at": -1 } } ]) # 时间倒序 count_match = { "$match": { "to_id": userid, "status": 0, "msg_type": 2 } } count_list = message_query.aggregate([ count_match, { "$group": { "_id": { "from_id": "$session", "m_id": "$m_id" }, "count": { "$sum": 1 }, "from_id": { "$last": "$from_id" }, "m_id": { "$last": "$m_id" } } } ]) logger.debug('unread_list:%s', unread_list) logger.debug('count_list:%s', count_list) # 处理count_list count_dict = {} if count_list: for count_data in count_list: otherid = count_data['from_id'] mid = count_data['m_id'] count_dict[otherid + '_' + mid] = count_data['count'] logger.debug('count_dict:%s', count_dict) # 整理数据 # other_userinfo = None if unread_list: for unread_msg in unread_list: del unread_msg['_id'] # print type(unread_msg['id']) # print str(unread_msg['id']) # 转换objectId to string unread_msg['id'] = str(unread_msg['id']) # print type(unread_msg['create_at']) unread_msg['create_at'] = long( unread_msg['create_at'].strftime('%s')) * 1000 if unread_msg['from_id'] == userid: otherid = unread_msg['to_id'] # if not other_userinfo: other_userinfo = ClassHelper('UserInfo').find_one( {'user': unread_msg['to_id']}) logger.debug('other_userinfo:%s', other_userinfo) unread_msg['other_name'] = other_userinfo['nickName'] unread_msg['other_avatar'] = other_userinfo.get( 'avatar', None) else: otherid = unread_msg['from_id'] unread_msg['other_name'] = unread_msg['from_name'] unread_msg['other_avatar'] = unread_msg['from_avatar'] mid = unread_msg['m_id'] unread_msg['count'] = count_dict.get( otherid + '_' + mid, 0) logger.debug('unread_list after make data :%s', unread_list) result = {} result['errCode'] = 0 result['unread_list'] = unread_list r = json.dumps(result, ensure_ascii=False) self.write(str(r)) # , cls=CJsonEncoder #格式化时间 except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def base(self): version = self.request.headers.get("X-MeCloud-Client", None) platform = self.request.headers.get("X-MeCloud-Platform", None) app_version = self.request.headers.get("X-MeCloud-AppVersion", None) logger.debug('in header, version:%s , platform:%s, app_version:%s', version, platform, app_version) if not version: version = '1' if not platform: platform = 'android' cursor_config = ClassHelper('VersionControl').find({ 'platform': platform, 'version': version, 'settingName': { '$exists': True } }) config_list = [] if cursor_config: for data in cursor_config: if data.has_key('createAt'): del data['createAt'] del data['updateAt'] del data['version'] del data['_id'] del data['platform'] del data['_sid'] logger.debug('data:%s', data) config_list.append(data) if not config_list: cursor_config = ClassHelper('VersionControl').find({ 'platform': platform, 'versionNo': int(app_version), 'settingName': { '$exists': True } }) if cursor_config: for data in cursor_config: if data.has_key('createAt'): del data['createAt'] del data['updateAt'] del data['version'] del data['_id'] del data['platform'] del data['_sid'] logger.debug('data:%s', data) config_list.append(data) cursor_price = ClassHelper('PriceConfig').find( {}, sort={"price": 1}) # , sort={"price": 1} list_price = [] if cursor_price: for data in cursor_price: # d = {'id': data['_id'], 'price': data['price']} list_price.append(data['price']) logger.debug('list_price:%s', list_price) r = {} r['configs'] = config_list r['prices'] = list_price r['code'] = 0 r['errCode'] = 0 logger.debug('r:%s', r) # if BaseConfig.mode == 'online': # r = crypto.encrypt(r) self.write(r)
def readMessage(self): obj = self.jsonBody from_id = obj.get('from_id') to_id = self.user['_id'] message_id = obj.get('message_id') message_ids = obj.get('message_ids', None) logger.debug('from_id: %s, message_id: %s', from_id, message_id) # message_id = '59db35da51159a0e1b5145de' #for test args helper = ClassHelper('Message') if message_id: r = helper.db.update_many( 'Message', { '_id': { '$lte': ObjectId(message_id) }, 'status': 0, 'from_id': from_id, 'msg_type': 0, 'to_id': to_id }, {'$set': { "status": 1 }}) logger.debug('read message update r: %s', r) self.write(ERR_SUCCESS.message) if r: logger.debug('nModified:%d', r['nModified']) if r['nModified'] > 0: logger.debug('reduce name :unreadMsg_%s unreadMsg count', to_id) ClassHelper('StatCount').updateOne( {'name': 'unreadMsg_' + to_id}, {"$inc": { 'count': -r['nModified'] }}, upsert=False) if message_ids: ids = [] for i in str(message_ids).split(','): ids.append(i) logger.debug('ids:%s', ids) r = helper.db.update_many( 'Message', { '_id': { '$in': ids }, 'status': 0, 'from_id': from_id, 'msg_type': 0, 'to_id': to_id }, {'$set': { "status": 1 }}) logger.debug('read comment r:%s', r) self.write(ERR_SUCCESS.message) if r: logger.debug('nModified:%d', r['nModified']) if r['nModified'] > 0: logger.debug('reduce name :unreadMsg_%s unreadMsg count', to_id) ClassHelper('StatCount').updateOne( {'name': 'unreadMsg_' + to_id}, {"$inc": { 'count': -r['nModified'] }}, upsert=False)
def listByFromId(self): try: # test msg_id # ObjectId("59dc380051159a123fe8a230") message_id = self.get_argument('message_id', default=None) count = int(self.get_argument('count', default=20)) logger.debug("count: %s", count) if count > 50: count = 50 logger.debug("message_id: %s, count: %s", message_id, count) # print self.user['_id'] # to_id = "59ca0b46ca714306705996dc" to_id = self.user['_id'] from_id = self.get_argument('from_id') m_id = self.get_argument('m_id') logger.debug('from_id: %s, m_id: %s', from_id, m_id) if message_id: # query = {"to_id": to_id, "status": 0, # "_id": {"$lt": ObjectId(msg_id)}} query = { "$or": [{ "to_id": to_id, "from_id": from_id }, { "to_id": from_id, "from_id": to_id }], "status": 0, "msg_type": 2, "m_id": m_id, "_id": { "$lt": ObjectId(message_id) } } else: query = { "$or": [{ "to_id": to_id, "from_id": from_id }, { "to_id": from_id, "from_id": to_id }], "status": 0, "msg_type": 2, "m_id": m_id } logger.debug('query: %s', query) helper = ClassHelper('Message') unread_list = helper.find(query, limit=count) logger.debug(unread_list) print unread_list.__len__() if unread_list: for unread_msg in unread_list: unread_msg['id'] = unread_msg['_id'] unread_msg['create_at'] = long( unread_msg['createAt'].strftime('%s')) * 1000 del unread_msg['_id'] if unread_msg.get('acl', None) is not None: del unread_msg['acl'] del unread_msg['createAt'] del unread_msg['updateAt'] result = {} result['errCode'] = 0 result['unread_list'] = unread_list self.write(json.dumps( result, ensure_ascii=False)) # , cls=CJsonEncoder #格式化时间 except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def push(self): try: userid = self.jsonBody['userid'] otherid = self.jsonBody['otherid'] action = self.jsonBody.get('action') extra = self.jsonBody.get('extra', '') logger.debug('third push userid: %s, otherid: %s, action: %s', userid, otherid, action) if userid is None or action is None or otherid is None: self.write(ERR_PARA.message) return uri = action_uri_dict.get(action, None) if uri is None: self.write(ERR_PARA.message) return uri = 'honey://' + uri logger.debug('uri: %s', uri) if action == 'claimed' or action == 'newFeed': uri = uri + '/' + otherid elif action == 'similarFace' or action == 'intrestedFace': uri = uri + '?unreadCount=' + extra notify_content = self.getNotifyContent(action, userid, otherid, extra) logger.debug('notify_content: %s', notify_content) if notify_content is None: self.write(ERR_PARA.message) return # 长链接通知 message_dict = {'t': 'notify'} message_dict['title'] = notify_content['title'] # message_dict['title2'] = notify_content['title2'] message_dict['subtitle'] = notify_content['content'] message_dict['avatar'] = notify_content['avatar'] message_dict['to_id'] = userid message_dict['uri'] = uri message_json = json.dumps(message_dict, ensure_ascii=False) logger.debug('publish_message:%s', message_json) rc = RedisDb.get_connection() publish_result = rc.publish(Constants.REDIS_CHANNEL_FOR_PUSH, message_json) logger.debug('publish_result: %s', publish_result) push_cid_obj = ClassHelper('PushCid').find_one({'userid': userid}) logger.debug('push_cid_obj: %s', push_cid_obj) if (push_cid_obj is None) or push_cid_obj['logout'] is True: # 没有找到对应的push_cid self.write(ERR_PARA.message) return claim_count = 0 message_count = 0 stat1 = ClassHelper('StatCount').find_one( {'name': 'toClaim_' + userid}) # logger.debug('stat1:') if stat1: claim_count = stat1['count'] if claim_count < 0: claim_count = 0 stat2 = ClassHelper('StatCount').find_one( {'name': 'unreadMsg_' + userid}) if stat2: message_count = stat2['count'] if message_count < 0: message_count = 0 badge = claim_count + message_count push_cid = MeObject('PushCid', obj=push_cid_obj) result = MyGtUtil.pushMessageToSingle( push_cid['cid'], notify_content['title'].decode("utf-8"), notify_content['content'].decode("utf-8"), uri, badge) logger.debug('result:%s', result) # result = PushUtil.pushMessageToSingle() self.write(result) except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg) self.write(ERR_PARA.message)
def login(self): mid = self.jsonBody['mid'] device = self.jsonBody['device'] logger.debug('mid:%s', mid) userMigrateHelper = ClassHelper('UserMigrate') user_migrate = userMigrateHelper.find_one({'_sid': mid, 'isused': 0}) logger.debug('user_migrate:%s', user_migrate) if not user_migrate: self.write(ERR_QRCODE_TO_LOGIN.message) return else: logger.debug('user_migrate.createAt:%s', user_migrate['createAt']) user = ClassHelper('User').get(user_migrate['user']) # user = MeUser(obj=user_obj) # user = MeQuery('User').get(user_migrate['user']) if not user: self.write(ERR_USER_NOTFOUND.message) return else: # 长链接通知 notify_dict = {'to_id': user['_sid'], 't': 'logout'} message_json = json.dumps(notify_dict, ensure_ascii=False) logger.debug(message_json) # message_json. = long(message['createAt'].strftime('%s')) * 1000 rc = RedisDb.get_connection() r = rc.publish(Constants.REDIS_CHANNEL_FOR_PUSH, message_json) logger.debug('redis publish r:%s', r) # del user['password'] # del user['username'] user['device'] = device user_info = ClassHelper('UserInfo').find_one( {'user': user['_sid']}) del user['createAt'] del user['updateAt'] del user['password'] del user_info['createAt'] del user_info['updateAt'] result = {} result['user'] = user result['user_info'] = user_info result['errCode'] = 0 result['info'] = 'success' logger.debug('result: %s', json.dumps(result)) self.write(json.dumps(result)) self.set_secure_cookie("u", user['_id']) new_cookie = str(self._new_cookie.get('u')).split( '=')[1].split(';')[0].replace('"', '') print new_cookie print user['_id'] if new_cookie is not None: self.set_user_cookie_record(new_cookie, user['_id']) try: userMigrateHelper.update(mid, {'$set': {'isused': 1}}) ClassHelper('User').update( user['_sid'], {'$set': { 'username': device, 'device': device }}) self.save_login_log(user['_sid']) except Exception, e: logger.error(e) msg = traceback.format_exc() logger.error(msg)