コード例 #1
0
 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)
コード例 #2
0
ファイル: SearchHandler.py プロジェクト: zhouchunlu/MeCloud
    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)
コード例 #3
0
 def post(self, action=None):
     logger.debug('post action:%s', action)
     logger.debug('json.body:%s', self.jsonBody)
     if action == 'send':
         self.send()
     elif action == 'read':
         self.read()
     else:
         print "action error: " + action
コード例 #4
0
ファイル: QRCodeHandler.py プロジェクト: zhouchunlu/MeCloud
 def post(self, action=None):
     try:
         logger.debug('action: %s', action)
         if action == 'login':
             self.login()
         else:
             print "action error: " + action
     except Exception, e:
         logger.error(e)
         msg = traceback.format_exc()
         logger.error(msg)
         self.write(ERR_PARA.message)
コード例 #5
0
 def getNotifyContent(self, action, toid, otherid, extra):
     nickname = ''
     avatar = None
     if otherid:
         other_user1 = MeQuery('UserInfo').find_one({'user': otherid})
         if other_user1:
             nickname = other_user1['nickName']
             avatar = other_user1['avatar']
             logger.debug('nickname:%s, avatar:%s', nickname, avatar)
         else:
             logger.debug('other_user1 is null')
     if action == 'followed':
         title = '新粉丝'
         content = nickname + '关注了你'
     elif action == 'assigned':
         title = nickname
         content = '给你贡献了1张照片,快来看~'
     elif action == 'claimed':
         title = nickname
         content = '认领了你贡献的照片'
     elif action == 'assignedBought':
         title = '获得' + extra + '个蜂蜜新收益'
         content = nickname + '购买了你贡献的照片'
     elif action == 'ownedBought':
         title = '获得' + extra + '个蜂蜜新收益'
         content = nickname + '购买了你的照片'
     elif action == 'newFeed':
         title = nickname
         content = '认领了新照片,快来看~'
     elif action == 'similarFace':
         title = '来自智能探索的新发现'
         if toid:
             toid1 = MeQuery('UserInfo').find_one({'user': toid})
             if toid1:
                 nickname = toid1['nickName']
                 if nickname:
                     content = '发现了' + extra + '张可能和你(' + nickname + ')有关的照片'
                 else:
                     content = '发现了' + extra + '张可能和你有关的照片'
     elif action == 'intrestedFace':
         title = '来自智能探索的新发现'
         if toid:
             toid1 = MeQuery('UserInfo').find_one({'user': toid})
             if toid1:
                 nickname = toid1['nickName']
                 if nickname:
                     content = '发现了' + extra + '张你(' + nickname + ')可能感兴趣照片'
                 else:
                     content = '发现了' + extra + '张你可能感兴趣照片'
     else:
         logger.warn('push action error:%s', action)
         return None
     return {'title': title, 'content': content, 'avatar': avatar}
コード例 #6
0
 def get(self, action=None):
     logger.debug('get action:%s', action)
     # logger.debug('json.body:%s', self.jsonBody)
     if action == 'unreadList':
         self.unreadList()
     elif action == 'unreadListByFromId':
         self.unreadListByFromId()
     elif action == 'listByFromId':
         self.listByFromId()
     elif action == 'goodsInfo':
         self.goodsInfo()
     else:
         print "action error: " + action
コード例 #7
0
 def post(self):
     xml = self.request.body
     logger.debug('xml: %s', xml)
     pub = Wxpay_server_pub()
     pub.saveData(xml)
     logger.debug('pub.data: %s', pub.data)
     if pub.data['return_code'] == 'SUCCESS' and pub.data[
             'result_code'] == 'SUCCESS':
         print 'wx call back result is success'
     # TODO update order status and notify cilent with websocket
     self.write(
         '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>'
     )
コード例 #8
0
ファイル: PushHandler.py プロジェクト: zhouchunlu/MeCloud
 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')
         # 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": 0
         }
         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:%s', 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)
コード例 #9
0
 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')
コード例 #10
0
 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)
コード例 #11
0
    def createWxAppOrder(self):
        logger.debug(self.jsonBody)
        obj = self.jsonBody
        coin_setting_id = obj.get('id')  # coinSettingId
        channel = obj.get('channel', '')
        version = obj.get('version', '')
        logger.debug('coin_setting_id: %s', coin_setting_id)
        coin_setting = MeObject('CoinSetting').get(coin_setting_id)
        logger.debug('coin_setting: %s', coin_setting)
        if coin_setting is None:
            # 未找到充值条目
            self.write(ERR_PAY_NOT_FIND_COIN_SETTING.message)
            return
        out_trade_no = PayUtil.createOrderNo()
        logger.debug('out_trade_no: %s', out_trade_no)
        pub = UnifiedOrder_pub()
        pub.parameters['out_trade_no'] = out_trade_no  # 设置参数自己的订单号
        pub.parameters['body'] = '黑密虚拟商品-黑密滴' + str(
            coin_setting['amount']) + '个'  # 设置商品描述
        pub.parameters['total_fee'] = str(coin_setting['price'])  # 设置总金额
        pub.parameters['notify_url'] = WxPayConf_pub.NOTIFY_URL  # 设置回调url
        pub.parameters['trade_type'] = 'APP'  # 支付类型,固定为app
        wx_result = pub.getResult()
        logger.info('wx create order result: %s', wx_result)

        if wx_result['return_code'] == 'SUCCESS':
            logger.debug('prepay_id: %s', wx_result['prepay_id'])
            result = {}
            result['code'] = 0
            result['prepayid'] = wx_result['prepay_id']
            result['appid'] = wx_result['appid']
            result['partnerid'] = wx_result['mch_id']  # 商户号
            # 创建充值流水记录
            rf = MeObject('RechargeFlow')
            rf['user'] = self.user['_id']
            rf['recharge'] = coin_setting['price']
            rf['amount'] = coin_setting['amount']
            rf['os'] = coin_setting['os']
            rf['platform'] = 1  # 微信APP
            if channel:
                rf['channel'] = channel
            rf['version'] = version
            rf['status'] = 0
            rf['orderNo'] = out_trade_no
            rf['order'] = ''
            rf.save()
            self.write(result)
        else:
            self.write(ERR_PAY_CREATE_ORDERN0_ERROR.message)
コード例 #12
0
ファイル: ConfigHandler.py プロジェクト: zhouchunlu/MeCloud
 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')
コード例 #13
0
 def createInviteCode(self):
     count = int(self.get_argument('count', 1))
     if count > 100:
         count = 100
     i = 0
     while (True):
         try:
             invite_code = MeObject('InviteCode')
             invite_code['code'] = InviteCodeUtil.create_code()
             invite_code['status'] = 0
             invite_code.save()
             i = i + 1
             logger.debug('create invite code finish %d', i)
             if i >= count:
                 break
         except Exception, e:
             logger.error(e)
コード例 #14
0
ファイル: LogoutHandler.py プロジェクト: zhouchunlu/MeCloud
 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)
コード例 #15
0
ファイル: PayHandler.py プロジェクト: zhouchunlu/MeCloud
 def post(self, action=None):
     logger.debug('action:%s', action)
     try:
         if action == 'createWxAppOrder':
             self.createWxAppOrder()
         elif action == 'createAppleAppOrder':
             self.createAppleAppOrder()
         elif action == 'completeAppleAppOrder':
             self.completeAppleAppOrder()
         elif action == 'createAlipayAppOrder':
             self.createAlipayAppOrder()
         elif action == 'charge':  # 消费
             self.charge()
         else:
             print "action error: " + action
     except Exception, e:
         logger.error(e)
         msg = traceback.format_exc()
         logger.error(msg)
         self.write(ERR_PARA.message)
コード例 #16
0
 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
コード例 #17
0
 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)
コード例 #18
0
 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)
コード例 #19
0
 def post(self):
     try:
         xml = self.request.body
         logger.debug('xml: %s', xml)
         pub = Wxpay_server_pub()
         pub.saveData(xml)
         logger.debug('pub.data: %s', pub.data)
         if pub.data['return_code'] == 'SUCCESS' and pub.data[
                 'result_code'] == 'SUCCESS':
             print 'wx call back result is success'
             order_no = pub.data.get('out_trade_no', None)
             logger.debug('out_trade_no:%s', order_no)
             if order_no:
                 flow = ClassHelper("RechargeFlow").find_one({
                     'orderNo': order_no,
                     'status': 0
                 })
                 if flow:
                     payUtil.orderCallback(flow['_id'], flow['user'], 1,
                                           pub.data)
         else:
             order_no = pub.data.get('out_trade_no', None)
             if order_no:
                 flow = ClassHelper("RechargeFlow").find_one({
                     'orderNo': order_no,
                     'status': 0
                 })
                 if flow:
                     payUtil.orderCallback(flow['_id'], flow['user'], -1,
                                           pub.data)
     except Exception, e:
         logger.error(e)
         msg = traceback.format_exc()
         logger.error(msg)
コード例 #20
0
ファイル: PayHandler.py プロジェクト: zhouchunlu/MeCloud
    def pushMessage(self, good, owner_income_show, uploader_income_show):
        '''
        author:arther
        '''
        logger.debug('good:%s', good)

        def callback(response):
            log.info('Push:%s', response.body)
            self.finish()

        pushUrl = BaseConfig.pushUrl
        face = ClassHelper('Face').get(good['goods'])
        if face:
            if self.user['_id'] != face['assign']['user']:
                ##ownedBought 购买了我主页的照片 排除掉照片主人购买自身主页照片的情况
                ownedBoughtPushData = {
                    'userid': face['assign']['user'],
                    'action': 'ownedBought',
                    'otherid': self.user['_id'],
                    'extra': owner_income_show
                }
                client = tornado.httpclient.AsyncHTTPClient()
                client.fetch(pushUrl,
                             callback=callback,
                             method="POST",
                             body=json.dumps(ownedBoughtPushData),
                             headers={'X-MeCloud-Debug': '1'})
            ##assignedBought 购买了我共享的照片
            assignedBoughtPushData = {
                'userid': face['assign']['assigner'],
                'action': 'assignedBought',
                'otherid': self.user['_id'],
                'extra': uploader_income_show
            }
            client = tornado.httpclient.AsyncHTTPClient()
            client.fetch(pushUrl,
                         callback=callback,
                         method="POST",
                         body=json.dumps(assignedBoughtPushData),
                         headers={'X-MeCloud-Debug': '1'})
コード例 #21
0
    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)
コード例 #22
0
 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
コード例 #23
0
ファイル: PayHandler.py プロジェクト: zhouchunlu/MeCloud
    def make_payment_info(self,
                          out_trade_no=None,
                          subject=None,
                          total_amount=None,
                          body=None,
                          passback_params=None):
        public = {  # public args
            "app_id": alipay_config.appid,
            "method": "alipay.trade.app.pay",
            "charset": "utf-8",
            "timestamp": datetime.datetime.now().strftime(
                '%Y-%m-%d %H:%M:%S'),  # 2017-01-01 00:00:00
            "version": "1.0",
            "notify_url": "http://n01.me-yun.com:8000/1.0/alicallback",
            "sign_type": "RSA"
        }

        order_info = {
            "product_code": "QUICK_MSECURITY_PAY",
            # 业务参数
            "out_trade_no": None,
            "subject": None,
            "total_amount": total_amount,
            "body": body,
        }
        if passback_params:
            order_info['passback_params'] = passback_params
        order_info["out_trade_no"] = "%s" % (out_trade_no)
        order_info["subject"] = "%s" % (subject)
        if total_amount <= 0.0:
            total_amount = 0.01
        order_info["total_amount"] = "%s" % (total_amount)

        public['biz_content'] = json.dumps(order_info, ensure_ascii=False)
        logger.debug('public:%s', public)
        return public
コード例 #24
0
 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)
コード例 #25
0
    def createAlipayAppOrder(self):
        logger.debug(self.jsonBody)
        obj = self.jsonBody
        coin_setting_id = obj.get('id')  # coinSettingId
        channel = obj.get('channel', '')
        version = obj.get('version', '')
        logger.debug('coin_setting_id: %s', coin_setting_id)
        coin_setting = MeObject('CoinSetting').get(coin_setting_id)
        logger.debug('coin_setting: %s', coin_setting)
        if coin_setting is None:
            # 未找到充值条目
            self.write(ERR_PAY_NOT_FIND_COIN_SETTING.message)
            return
        out_trade_no = PayUtil.createOrderNo()
        logger.debug('out_trade_no: %s', out_trade_no)

        total_fee = 0.01  # 这里将金额设为1分钱,方便测试
        body = '黑密虚拟商品-黑密滴' + str(coin_setting['amount']) + '个'
        subject = '黑密滴'
        payment_info = self.make_payment_info(out_trade_no=out_trade_no,
                                              subject=subject,
                                              total_amount=total_fee,
                                              body=body)
        res = alipay_core.make_payment_request(payment_info)
        result = {}
        result['code'] = 0
        result['res'] = res
        print res
        # 创建充值流水记录
        rf = MeObject('RechargeFlow')
        rf['user'] = self.user['_id']
        rf['recharge'] = coin_setting['price']
        rf['amount'] = coin_setting['amount']
        rf['os'] = coin_setting['os']
        rf['platform'] = 0  # 支付宝APP
        if channel:
            rf['channel'] = channel
        rf['version'] = version
        rf['status'] = 0
        rf['orderNo'] = out_trade_no
        rf['order'] = ''
        rf.save()
        self.write(result)
コード例 #26
0
 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)
コード例 #27
0
    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)
コード例 #28
0
 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)
コード例 #29
0
 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)
コード例 #30
0
 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)