Exemplo n.º 1
0
def game_download(gid):
    """获取游戏下载地址(GET|POST)

    :uri: /games/<string:gid>/download
    :returns: {'url': url, 'download_id': string}
    """
    ua = request.headers.get('User-Agent')
    game = Game.get_one(gid, check_online=False)
    if not game:
        return error.GameNotExist

    url = game.format(exclude_fields=['subscribed'])['url']
    if game.bid and game.bcode:
        url = Migu.ota_download(ua, game.bcode, game.bid) or url

    # 增加下载记录
    gd = GameDownload.init()
    gd.user = request.authed_user._id if request.authed_user else None
    gd.device = request.values.get('device', None)
    gd.game = game._id
    gd.finish = False
    download_id = gd.create_model()

    #咪咕汇活动
    user = request.authed_user
    if user:
        Marketing.trigger_report(user.partner_migu['id'], user.phone,
                                 'download_game')
    return {'url': url, 'download_id': str(download_id)}
Exemplo n.º 2
0
    def add_product2user(self, user_id, num, action=None, extra={}):
        if self.product_type == EMPTY:  # 空
            return const.ORDER_FINISHED
        elif self.product_type == GEM:  # 游票
            uc = UserCredit.get_or_create_user_credit(user_id)
            uc.add_gem(num, action)
            return const.ORDER_FINISHED
        elif self.product_type == GOLD:  # 游米
            uc = UserCredit.get_or_create_user_credit(user_id)
            uc.add_gold(num, action)
            return const.ORDER_FINISHED
        elif self.product_type == GIFT:  # 礼物
            up = UserProduct.get_or_create_user_product(
                user_id, self.product_id, extra.get("is_money", False))
            up.add_product(num)

            return const.ORDER_FINISHED
        elif self.product_type in [
                WHOLE_TRAFFIC, MOBILE_TRAFFIC, UNICOM_TRAFFIC, TELECOM_TRAFFIC
        ]:
            ret = Marketing.draw_resource(extra['migu_id'], extra['phone'],
                                          extra['campaign_id'], 6, num)
            status = const.ORDER_IN_HAND if ret == True else const.ORDER_FAILED
            return status
        elif self.product_type == PHYSICAL_OBJECT:  # 实物物品, 比如:手机
            return const.ORDER_IN_HAND
        elif self.product_type == GIFT_BAG:  # 礼包, 比如:途牛券、游戏礼包
            return const.ORDER_FINISHED
        elif self.product_type == PHONE_FEE:  # 全网话费
            ret = Marketing.draw_resource(extra['migu_id'], extra['phone'],
                                          extra['campaign_id'], 4, num)
            status = const.ORDER_NEED_DRAW if ret == True else const.ORDER_IN_HAND
            return status

        return None
Exemplo n.º 3
0
def video_stay_time():
    # 1118 task2
    params = request.values
    user = request.authed_user
    video_stay_time = int(params.get('video_stay_time', 0))
    if video_stay_time > 180 and user:
        Marketing.trigger_report(user.partner_migu['id'], user.phone,
                                 'watch_video_3m')
    return {}
Exemplo n.º 4
0
def gift_codes():
    """获取礼包类物品的奖励信息(POST&LOGIN)

    :uri: /store/gift_codes
    :param store_id: 商店ID
    :param rid: 抽奖奖项ID
    :return: {'codes': <code>list}
    """
    user = request.authed_user
    store_id = request.values.get('store_id', None)
    rid = request.values.get('rid', None)

    if not store_id or not rid:
        return error.InvalidArguments

    store = Store.get_store(store_id)
    if not store or not store.online():
        return error.StoreError('该抽奖活动不存在或已下线')

    # 获取抽奖对应奖项的所有获奖记录
    codes = []
    page = 1
    end_page = False
    while not end_page:
        orders, end_page = Marketing.query_exchenged_prizes(str(
            user.partner_migu['id']),
                                                            store.campaign_id,
                                                            page=page,
                                                            pagesize=50)
        # 过滤奖项ID对应的兑换记录
        for order in orders:
            consume_ids = [
                str(res['resourceId']) for res in order['consumeResources']
            ]
            if [str(rid)] == consume_ids:
                codes.append({
                    'name':
                    order['exchengedResouce']['name'],
                    'code':
                    order['exchangeCode'],
                    'create_at':
                    int(order['exchangeTime']['time']) / 1000
                })

        page += 1

    return {'codes': codes}
Exemplo n.º 5
0
def lottery_info():
    """获取抽奖活动详细信息(GET)

    :uri: /store/lottery_info
    :param store_id: 兑换活动ID
    :return: {'lottery': <Store>object}
    """
    user = request.authed_user
    store_id = request.values.get('store_id', None)
    if not store_id:
        return error.InvalidArguments

    store = Store.get_store(store_id)
    if not store or not store.online():
        return error.StoreError('该抽奖活动不存在或已下线')

    if store.pause():
        return error.StoreError('该抽奖活动还未开始')

    lottery = store.format()
    items = [
        item.format() for item in StoreItem.get_store_items(store.store_id)
    ]
    lottery['items'] = items
    chances = 0
    if user:
        chances = Marketing.query_lottery_chance(user.partner_migu['id'],
                                                 store.campaign_id)
        if isinstance(chances, error.ApiError):
            return chances
        if int(chances) == 0:
            ors = UserOrder.get_user_store_orders(user._id, store_id, 1,
                                                  store.lotterynum)
            chances = store.lotterynum - len(ors)
        if store.yxmember:
            uservip = MiguPay.check_user_vip_level(user.phone)
            if isinstance(uservip, error.ApiError):
                return uservip
            if not (uservip['vip5']['subscribed']
                    or uservip['vip10']['subscribed']):
                chances = -1

    lottery['chances'] = chances
    return {'lottery': lottery}
Exemplo n.º 6
0
def draw_gift_code():
    """
    VIP用户获取礼包兑换码
    :uri: /games/vip/giftcode/draw
    :param: giftcode_id 会员游戏礼包id
    :return:
    """
    user = request.authed_user
    uid = str(user._id)
    gcid = request.values.get('giftcode_id')
    if not gcid:
        return error.InvalidArguments

    giftcode = VipGiftCode.get_one(gcid, check_online=True)
    if not giftcode:
        return error.GiftCodeNotExist

    if giftcode.left <= 0:
        return error.StoreError('没有可领取的礼包了!')

    vip = MiguPay.check_user_vip_level(user.phone)
    if isinstance(vip, error.ApiError):
        return vip
    if not (vip['vip5']['subscribed'] or vip['vip10']['subscribed']):
        return error.StoreError('没有领取权限!')

    # 查看是否有抽奖机会
    left_chances = Marketing.query_lottery_chance(user.partner_migu['id'],
                                                  giftcode.campaign_id)
    if isinstance(left_chances, error.ApiError):
        return error.StoreError('领取礼包失败,请稍后重试')

    # 当前没有剩余机会的时候,需要先验证是否可以抽奖并获取抽奖机会
    if left_chances <= 0:
        key = 'lock:store:%s' % (str(user._id))
        with util.Lockit(Redis, key) as locked:
            if locked:
                return error.StoreError('领取礼包太频繁')

            if gcid in UserGiftCodeOrder.get_user_gift_code_ids(uid):
                return error.StoreError('已经领取过该礼包')

            # 进行抽奖机会的兑换
            ret = Marketing.execute_campaign(user.partner_migu['id'],
                                             user.phone,
                                             [giftcode.campaign_id],
                                             trigger=10218)
            if not ret or isinstance(ret, error.ApiError):
                return error.StoreError('兑换领取机会失败')

    # 调用营销平台进行抽奖
    prize = Marketing.draw_lottery(user.partner_migu['id'],
                                   giftcode.campaign_id)
    if isinstance(prize, error.ApiError):
        return prize
    if not prize:
        return error.StoreError('获取游戏兑换码失败')

    exchange_code = None
    for row in prize.get('extensionInfo', []):
        if row['key'] == 'exchangeCode':
            exchange_code = row['value']
            break
    if not exchange_code:
        return error.StoreError('获取游戏兑换码失败')

    order = UserGiftCodeOrder.create(user_id=str(user._id),
                                     vgc_id=gcid,
                                     vgc_name=giftcode.name,
                                     campaign_id=giftcode.campaign_id,
                                     gift_code=exchange_code,
                                     result=json.dumps(prize),
                                     recid=prize.get('id', ''),
                                     expire_at=util.timestamp2datetime(
                                         giftcode.exchange_expire_at),
                                     status=const.ORDER_FINISHED,
                                     user_ip=request.access_route[0])
    UserGiftCodeOrder.clear_redis(str(user._id))

    # 更新库存
    giftcode.update_model({'$inc': {'left': -1, 'used': 1}})
    return {'order': order.format()}
Exemplo n.º 7
0
                    }
                }
              """)

if end_time > start_time:
    start_timestamp = time.mktime(start_time.timetuple())
    end_timestamp = time.mktime(end_time.timetuple())
    query = {"create_at": {"$gt": start_timestamp, "$lt": end_timestamp}}
    out_put = 'result'
    result = live.event.map_reduce(map_fun, reduce_fun, out_put, query=query)
    result = {
        ObjectId(i['_id']): i['value']
        for i in result.find() if i['value']
    }
    suit_uids = result.keys()
    # 测试用户
    suit_uids.append(ObjectId('5704b0d2268b6c0ff789b35e'))  # 海军手机号
    result = community.users.find({"_id": {
        "$in": suit_uids
    }}, {
        "phone": 1,
        'partner_migu': 1
    })
    items = [(i['phone'], i['partner_migu'], i['_id']) for i in result
             if i.get("phone")]
    print env, now_time, 'num', len(items)
    for phone, partner_migu, user_id in items:
        tag = Marketing.trigger_report(partner_migu['id'], phone, 'live_30m',
                                       str(user_id))
        print phone, partner_migu['id'], tag
Exemplo n.º 8
0
def send_gift():
    """赠送礼物 (GET|POST&LOGIN)

    :uri: /gifts/send_gift
    :param user_id: 主播ID
    :param gift_id: 礼物ID
    :param num: 礼物数量
    :param gift_from: 礼物来源(1:直播, 2:录播)
    :param from_id:来源ID(直播ID或者录播视频ID)
    :return: {'ret: bool}

    :if money need cs(充值来源),SDKVersion,dId 
    """
    user = request.authed_user
    gift_id = int(request.values.get('gift_id'))
    to_user_id = request.values.get('user_id')
    num = int(request.values.get('num', 1))
    gift_from = int(request.values.get('gift_from'))
    from_id = request.values.get('from_id')
    user_ip = request.remote_addr
    device = request.values.get('device', None)

    if not gift_id or not to_user_id or num < 1 or not gift_from:
        return error.InvalidArguments

    if to_user_id == str(user._id):
        return error.GiftError('不能给自己赠送礼物哦')

    to_user = User.get_one(to_user_id, check_online=False)
    if not to_user:
        return error.UserNotExist('该视频没有主播')

    available_num = _gift_num()
    if num not in available_num:
        return error.GiftError('礼物数量不符合规则')

    gift = Gift.get_gift(gift_id)
    if not gift:
        return error.GiftError('该礼物不能赠送')
    money_data = {}
    transactionId = ''
    if gift.credit_type == const.MONEY:
        # today_times = UserGiftLog.user_today_gift_id_times(user._id,gift_id,num)
        gift_data = gift.format()
        # max_times = gift_data['per_piece_limit'].get(num)
        # if max_times <= today_times:
        #     return error.GiftError('该档礼物今天的次数已用完')
        from wanx.platforms.migu import PayByMg
        consumeCode = gift_data['per_piece_id'].get(num)
        cs = 6
        SDKVersion = request.values.get('SDKVersion')
        dId = request.values.get('dId', 'null')
        goodsname = gift_data['product_name'] + '_' + str(num)

        pay_mg_data = PayByMg.get_payurl(user,
                                         cs,
                                         SDKVersion,
                                         dId,
                                         consumeCode,
                                         1,
                                         goodsname=goodsname)

        if isinstance(pay_mg_data, error.ApiError):
            return pay_mg_data
        # 创建订单
        pay_order_obj = PayOrder.init()
        # [set(pay_order_obj,attr,value) for attr,value in pay_mg_data.items()]
        pay_order_obj.pay_mg_data = pay_mg_data
        transactionId = pay_mg_data['resultData']['transactionId']
        pay_order_obj.transactionId = transactionId
        pay_order_obj.phone = user.phone
        pay_order_obj.nickname = user.nickname
        pay_order_obj.credit_value = gift.credit_value
        pay_order_obj.total_value = gift.credit_value * num
        pay_order_obj.gift_num = num
        pay_order_obj.finished = 0
        pay_order_obj.product_name = gift_data['product_name']
        pay_order_obj.check_pay_data = {}
        pay_order_obj.pay_info = {"from_user_id": user._id, 'to_user_id': to_user_id, "num": num,
                                  'gift_id': gift_id, \
                                  'gift_from': gift_from, "from_id": from_id}
        pay_order_obj.create_model()
        money_data = {
            'is_money': True,
            "pay_data": pay_mg_data.get("resultData", {})
        }

    ret = False
    key = 'lock:send_gift:%s' % (str(user._id))
    with util.Lockit(Redis, key) as locked:
        if locked:
            return error.GiftError('赠送礼物失败')

        ret = gift.send_to_user(str(user._id),
                                to_user_id,
                                num,
                                gift_from,
                                from_id,
                                transactionId=transactionId)

    if isinstance(ret, error.ApiError):
        return ret

    if money_data:
        return money_data
    # 录播发送消息到中心消息
    if ret and gift_from == const.FROM_RECORD:
        video = Video.get_one(from_id, check_online=False)
        if video:
            Message.send_gift_msg(str(user._id), from_id, 'gift')
            video.update_model({'$inc': {'gift_count': 1, 'gift_num': num}})

    # 直播发送广播信息
    if ret and gift_from == const.FROM_LIVE:
        total = Xlive.get_user_send_gift_count(from_id, str(user._id), gift_id,
                                               num)
        data = dict(user_id=str(user._id),
                    username=user.nickname or user.name,
                    userphoto=user.get_photo(),
                    gift_name=gift.format()['product_name'],
                    gift_image=gift.format()['product_image'],
                    gift_num=num,
                    event_id=from_id,
                    total=total)
        Xlive.send_live_msg(data)

    # 营销数据入库经分  打赏活动
    from wanx.models.activity import ActivityConfig, ActivityVideo
    from wanx.platforms.migu import Marketing
    activity_config = None
    if gift_from == const.FROM_RECORD:
        activity_video = ActivityVideo.get_activity_video_by_vid(from_id)
        if activity_video:
            activity_config = ActivityConfig.get_one(
                activity_video['activity_id'])
    else:
        aids = ActivityConfig.get_by_type(const.FROM_LIVE)
        for a in ActivityConfig.get_list(aids):
            activity_config = a
            break
    if activity_config:
        data_dict = dict(cmd="deliver_gift",
                         opt="{0}/{1}".format(gift.gold_price, to_user_id),
                         deviceid=request.values.get('device', ''),
                         mobile=user.phone,
                         source=request.values.get('source', 'activity'),
                         activityid=str(activity_config['_id']),
                         activityname=activity_config['name'])
        Marketing.jf_report(data_dict)
    # 1118 task1
    # Marketing.trigger_report(user.partner_migu['id'], user.phone, 'send_gift')
    return {'ret': ret}
Exemplo n.º 9
0
def gifts_exchange():
    user = request.authed_user

    requ_type = request.values.get('requ_type')

    value = PayForGift.get_all_value()  # 现已兑换的总金额

    cfg = GiftExchangeCfg.get_gift_config()
    total_exchange_value = cfg.total_exchange_value  # 兑换上限
    break_rate = cfg.break_rate  # 折损率
    exchange_thresthold = cfg.exchange_thresthold  # 兑换下限

    gift_value = UserProduct.get_total_money(user)  # 当前用户礼物价值
    _gift_value = float(gift_value) / float(100)
    # gift_value = UserCredit.get_or_create_user_credit(user._id).current_money  # 当前用户礼物价值

    _value = _gift_value * float(break_rate)
    exchange_value = int(_value) + 1 if _value > int(_value) else int(
        _value)  # 折损后的价值

    current_exchange_value = int(total_exchange_value) - int(
        value)  # 当前还可兑换的金额

    # 营销数据入库经分
    data_dict = dict(cmd="exchange_huafei",
                     deviceid=request.values.get('device', ''),
                     mobile=user.phone,
                     source=request.values.get('source', 'activity'),
                     activityid="0",
                     activityname=u"兑换话费活动")

    if requ_type == 'get_judge':

        certify_status = UserCertify.get_certify_status(user._id)

        is_anchor_wlist = AnchorWlist.is_anchor_wlist(user._id)  # 是否是签约主播
        if is_anchor_wlist:
            return {'exchange_status': 1, 'exchange_msg': '签约主播无法兑换'}

        user_certify = True if certify_status == 3 else False
        if not user_certify:
            return {
                'exchange_status': 2,
                'exchange_msg': '只有实名认证的用户才可以兑换哦,快去认证吧'
            }

        is_exchange_time = GiftExchangeCfg.is_exchange_time()  # 是否在兑换时间内
        if not is_exchange_time:
            return {
                'exchange_status': 3,
                'exchange_msg': '当前时间不在礼物兑换期内,请在兑换期内进行礼物兑换'
            }

        if int(exchange_value) >= int(current_exchange_value):  # 超过总额度
            return {
                'exchange_status': 4,
                'exchange_msg': '本月额度已经被全部兑换完啦,下个月请早了'
            }

        is_exchange = PayForGift.is_exchange(user)  # 兑换次数
        if is_exchange:
            return {
                'exchange_status': 5,
                'exchange_msg': '每个月只能兑换一次哦,您本月已经兑换过啦'
            }

        if int(exchange_value) < int(exchange_thresthold):  # 不满足兑换门槛
            return {'exchange_status': 6, 'exchange_msg': '您的礼物还不够提现哦'}

        data_dict["opt"] = "1:{0}:{1}".format(gift_value, exchange_value)
        Marketing.jf_report(data_dict)
        return {
            'exchange_status':
            0,
            'exchange_msg':
            '您有价值{0}元的礼物,可以兑换{1}元话费,话费将发放到您登录的手机号码内,兑换完成后付费礼物全部清零'.format(
                _gift_value, exchange_value)
        }

    elif requ_type == 'pay_exchange':
        is_anchor_wlist = AnchorWlist.is_anchor_wlist(user._id)  # 是否是签约主播
        if is_anchor_wlist:
            return error.StoreError

        certify_status = UserCertify.get_certify_status(user._id)
        user_certify = True if certify_status == 3 else False
        if not user_certify:
            return error.StoreError

        is_exchange_time = GiftExchangeCfg.is_exchange_time()
        if not is_exchange_time:
            return error.StoreError

        if int(exchange_value) >= int(current_exchange_value):
            return error.StoreError

        is_exchange = PayForGift.is_exchange(user)
        if is_exchange:
            return error.StoreError

        if int(exchange_value) < int(exchange_thresthold):
            return error.StoreError

        lock_key = 'lock:exchange_fee:%s' % (str(user._id))
        with util.Lockit(Redis, lock_key) as locked:
            if locked:
                return error.StoreError('兑换太频繁')

            try:
                uc = UserCredit.get_or_create_user_credit(user._id)
                uc.reduce_money(gift_value)

                UserProduct.clear_gifts_num(user, True)

                PayForGift.create_log(user, const.SUCCESS, _gift_value,
                                      exchange_value, const.GIFT_EXCHANGE)
                data_dict["opt"] = "1:{0}:{1}".format(gift_value,
                                                      exchange_value)
                Marketing.jf_report(data_dict)
                return {
                    'exchange_status':
                    0,
                    'exchange_msg':
                    '兑换成功,{0}元的话费将在30个工作日内发到您登录的咪咕游玩手机账户'.format(
                        exchange_value)
                }

            except:
                PayForGift.create_log(user, const.FAIL, _gift_value,
                                      exchange_value, const.GIFT_EXCHANGE)
                return {'exchange_status': 7, 'exchange_msg': '兑换失败,请稍后再试哦'}

    elif requ_type == 'gold_exchange':
        lock_key = 'lock:exchange_gold:%s' % (str(user._id))
        with util.Lockit(Redis, lock_key) as locked:
            if locked:
                return error.StoreError('兑换太频繁')

            try:
                total_gold_value = UserProduct.get_total_gold(user)
                uc = UserCredit.get_or_create_user_credit(user._id)
                uc.add_gold(total_gold_value, const.GIFT_EXCHANGE)

                UserProduct.clear_gifts_num(user, False)

                data_dict["opt"] = "1:{0}:{1}".format(gift_value,
                                                      exchange_value)
                Marketing.jf_report(data_dict)
                return {
                    'exchange_status': 0,
                    'exchange_msg': '您已兑换成功,请去游米账户中进行查询'
                }

            except:
                data_dict["opt"] = "0:0:0"
                Marketing.jf_report(data_dict)
                return {'exchange_status': 7, 'exchange_msg': '兑换失败,请稍后再试哦'}

    else:
        return {'exchange_status': 7, 'exchange_msg': '兑换失败,请稍后再试哦'}
Exemplo n.º 10
0
def share_activity_rewards():
    """
    请求分享活动奖励
    :uri: /activity/share/rewards
    :param: aid 活动ID
    :param: device 设备ID
    :return:
    """
    user = request.authed_user
    params = request.values
    aid = params.get('aid', None)
    device = params.get('device', None)
    uid = str(user._id)

    if not aid or not device:
        return error.InvalidArguments

    activity = ShareActivityConfig.get_one(aid, check_online=True)
    if not activity:
        return error.ActivityNotExist

    if not activity.get_left_today():
        return error.UserTrafficZero

    shared = UserShareActivityLog.check_user_activity(aid, user.phone, device)
    if shared:
        return error.UserTrafficExists

    # 获取分享活动的视频id
    vids = TopicVideo.topic_video_ids(activity.share_video_topic, 1, 99)

    # 查看用户活动期间内的分享数据
    user_shares = UserShare.get_user_shares_by_time(uid, activity.begin_at,
                                                    activity.end_at)
    finished = False
    for us_id in user_shares:
        us = UserShare.get_one(us_id)
        if not us:
            continue
        if us.target_type not in ['video', 'url']:
            continue
        if us.target_type == 'url' and us.target_value != activity.share_url:
            continue
        if us.target_type == 'video' and us.target_value not in vids:
            continue
        finished = True
        break
    # 如果活动期间,用户没有分享过,则不可领取
    if not finished:
        return error.UserTrafficInvalid(u'您还没有分享活动规定的URL或视频')

    key = 'lock:share:activity:%s' % (uid)
    with util.Lockit(Redis, key) as locked:
        if locked:
            return error.UserTrafficInvalid(u'领取分享活动奖励失败')

        # 创建用户参与分享活动记录
        usa_log = UserShareActivityLog.init()
        usa_log.activity = activity._id
        usa_log.owner = user._id
        usa_log.phone = user.phone
        usa_log.device = device
        usa_log.charge_status = 2
        usa_log.active_type = us.target_type
        usa_log.reward_order = activity.incr_counter()
        usa_log.create_model()

        # 只有序号尾数为9的订单,才能获得抽奖机会
        if usa_log.reward_order % 10 != 9:
            return {'ret': False}

        # 抽奖
        # 查看是否有抽奖机会
        left_chances = Marketing.query_lottery_chance(user.partner_migu['id'],
                                                      activity.campaign_id)
        if isinstance(left_chances, error.ApiError):
            # 抽奖失败则记录领取状态为失败
            usa_log.update_model({'$set': {'charge_status': 1}})
            return {'ret': False}
        # 进行抽奖机会的兑换
        ret = Marketing.execute_campaign(user.partner_migu['id'], user.phone,
                                         [activity.campaign_id])
        if not ret or isinstance(ret, error.ApiError):
            # 抽奖失败则记录领取状态为失败
            usa_log.update_model({'$set': {'charge_status': 1}})
            return {'ret': False}

        # 调用营销平台进行抽奖
        prize = Marketing.draw_lottery(user.partner_migu['id'],
                                       activity.campaign_id)
        if isinstance(prize, error.ApiError) or not prize:
            # 抽奖失败则记录领取状态为失败
            usa_log.update_model({'$set': {'charge_status': 1}})
            return {'ret': False}

        # 抽中物品则记录领取成功
        usa_log.update_model({'$set': {'charge_status': 0}})

        # 更新活动剩余奖励
        data = {
            '$set': {
                'left_num': activity.left_num - 1,
                'use_num': activity.use_num + 1
            }
        }
        activity.update_model(data)

        # 增加当日已领取次数
        ShareActivityConfig.incr_used_today(aid)

    return {'ret': True}
Exemplo n.º 11
0
def receive_order():
    """领取订单奖励(POST&LOGIN)

    :uri: /store/receive_order
    :param order_id: 订单ID
    :param name: 真实名字 (实物物品)
    :param id_card: 身份证 (实物物品)
    :param address: 地址 (实物物品)
    :return: {'order': <Order>object}
    """
    user = request.authed_user
    order_id = request.values.get('order_id', None)
    name = request.values.get('name', None)
    id_card = request.values.get('id_card', None)
    address = request.values.get('address')

    if not order_id:
        return error.InvalidArguments

    order = UserOrder.get_order(order_id)
    if not order or order.user_id != str(user._id):
        return error.StoreError('用户订单不存在')

    if order.status != const.ORDER_NEED_DRAW:
        return error.StoreError('用户订单状态错误')

    store = Store.get_store(order.store_id)
    if not store or not store.online():
        return error.StoreError('该抽奖活动不存在或已下线')

    product = Product.get_product(order.product_id)
    if product.product_type == PHYSICAL_OBJECT:  # 实物物品
        if not name or not id_card or not address:
            return error.InvalidArguments

        addr = UserOrderAddress.create(order_id=order_id,
                                       user_id=str(user._id),
                                       name=name,
                                       phone=user.phone,
                                       id_card=id_card,
                                       address=address)

    prize = json.loads(order.result)

    # 获取用户可兑换奖励信息
    exchenge_prizes = Marketing.query_exchengable_prizes(
        user.partner_migu['id'], order.campaign_id)
    if isinstance(exchenge_prizes, error.ApiError):
        return exchenge_prizes

    for _prize in exchenge_prizes:
        exchenge_ids = map(lambda x: x['id'], _prize['exchengeResources'])
        exchengeable_id = _prize['exchengableResource']['id']

        if [prize['id']] == exchenge_ids:
            exchenge_ids = [prize['id']]
            if product.product_type == PHYSICAL_OBJECT:  # 实物物品
                ret = Marketing.draw_exchengable_prize(
                    user.partner_migu['id'], order.campaign_id, exchenge_ids,
                    exchengeable_id, prize['amount'], addr.name, addr.phone,
                    addr.address, addr.id_card)
            else:
                ret = Marketing.draw_exchengable_prize(user.partner_migu['id'],
                                                       order.campaign_id,
                                                       exchenge_ids,
                                                       exchengeable_id,
                                                       prize['amount'])

            if isinstance(exchenge_prizes, error.ApiError):
                return ret

    # 由于对方没有返回订单ID, 只能通过获取用户最近一个已兑换奖励的订单ID
    ret, _ = Marketing.query_exchenged_prizes(user.partner_migu['id'],
                                              order.campaign_id,
                                              page=1,
                                              pagesize=1)
    if isinstance(ret, error.ApiError):
        return ret

    # 更新订单信息
    if isinstance(ret, list) and len(ret) > 0 and 'recId' in ret[0]:
        order.recid = ret[0]['recId']

    order.status = const.ORDER_IN_HAND
    order.save()

    extra = dict(migu_id=user.partner_migu['id'],
                 phone=user.phone,
                 campaign_id=store.resource_campaign_id)
    # 进行物品的发放
    status = product.add_product2user(str(user._id), order.product_num,
                                      const.LOTTERY, extra)

    # 订单状态更新
    if status != order.status:
        order.status = status
        order.save()

    return {'order': order.format()}
Exemplo n.º 12
0
def draw_lottery():
    """抽奖接口(POST&LOGIN)

    :uri: /store/draw_lottery
    :param store_id: 抽奖活动ID
    :return: {'item': <Item>object, 'order': <Order>object}
    """
    user = request.authed_user
    store_id = request.values.get('store_id', None)
    trigger = request.values.get('trigger', None)
    user_ip = request.remote_addr
    device = request.values.get('device', None)

    if not store_id:
        return error.InvalidArguments

    store = Store.get_store(store_id)
    if not store or not store.online():
        return error.StoreError('该抽奖活动不存在或已下线')

    if store.pause():
        return error.StoreError('该抽奖活动还未开始')

    if store.yxmember:
        uservip = MiguPay.check_user_vip_level(user.phone)
        if isinstance(uservip, error.ApiError):
            return uservip
        if not (uservip['vip5']['subscribed']
                or uservip['vip10']['subscribed']):
            return error.MemberError('该抽奖需要游戏会员才能参加')

    # 进行抽奖奖项库存判断
    items = StoreItem.get_store_items(store_id)
    left_num = sum(map(lambda x: x.left_num, items))
    if left_num < 0:
        return error.StoreError('该抽奖活动奖项已被领取完')

    # 判断号码是否符合规则
    info = Marketing.query_campaign(store.campaign_id)
    if isinstance(info, error.ApiError):
        return info
    if info['mobile_phone_only'] and not util.is_mobile_phone(user.phone):
        return error.StoreError('该抽奖活动只对移动手机号开放')

    # 查看是否有抽奖机会
    left_chances = Marketing.query_lottery_chance(user.partner_migu['id'],
                                                  store.campaign_id)
    if isinstance(left_chances, error.ApiError):
        return error.StoreError('获取抽奖机会失败')

    if left_chances <= 0:
        uc = UserCredit.get_or_create_user_credit(user_id=str(user._id))
        if store.credit_type == const.SALE_GEM and uc.gem < store.credit_value:
            return error.StoreError('你的游票不足,无法参与抽奖哦!')
        elif store.credit_type == const.SALE_GOLD and uc.gold < store.credit_value:
            return error.StoreError('你的游米不足,无法参与抽奖哦!')

        key = 'lock:store:%s' % (str(user._id))
        with util.Lockit(Redis, key) as locked:
            if locked:
                return error.StoreError('抽奖太频繁')

            # 进行抽奖机会的兑换
            if not trigger:
                ret = Marketing.execute_campaign(user.partner_migu['id'],
                                                 user.phone,
                                                 [store.campaign_id])
            else:
                ret = Marketing.execute_campaign(user.partner_migu['id'],
                                                 user.phone,
                                                 [store.campaign_id],
                                                 trigger=trigger)
            if not ret or isinstance(ret, error.ApiError):
                return error.StoreError('兑换抽奖机会失败')
            else:  # 扣除货币
                if store.credit_type == const.SALE_GEM:
                    uc.reduce_gem(store.credit_value, const.LOTTERY_REWAED)
                elif store.credit_type == const.SALE_GOLD:
                    uc.reduce_gold(store.credit_value, const.LOTTERY_REWAED)

    # 调用营销平台进行抽奖
    prize = Marketing.draw_lottery(user.partner_migu['id'], store.campaign_id)
    if isinstance(prize, error.ApiError):
        return prize

    # 营销数据入库经分  抽奖活动
    data_dict = dict(cmd="lottery",
                     opt="1",
                     deviceid=request.values.get('device', ''),
                     mobile=user.phone,
                     source=request.values.get('source', 'activity'),
                     activityid=store_id,
                     activityname=store.title)
    Marketing.jf_report(data_dict)
    # 营销平台奖项有各种限制, 会导致用户抽不中任何物品的可能。
    # 比如有A/B/C三个抽奖奖项,概率分别为20%/30%/50%,如果A物品配置为一个手机号只能中一次,
    # 那当用户抽中过A之后,以后再抽奖,就会有20%(A)的几率啥也抽不中。如果B物品库存又没有了,
    # 那用户就会有20%(A)+30%(B)的几率啥也抽不中。为了处理这种情况,目前默认如果抽不中就给
    # 用户发一个抽奖活动配置的"default"奖项(运营后台: 营销平台奖项ID配置为'default')
    if not prize:
        item = StoreItem.get_item_by_identity(store.store_id, 'default')
        if not item:
            return {'item': None, 'order': None}
        else:
            # 更新库存
            item.left_num -= 1
            item.use_num += 1
            item.save()
            # 生成兑奖订单
            order = UserOrder.create(
                user_id=str(user._id),
                item_id=item.item_id,
                store_id=item.store_id,
                store_type=store.store_type,
                campaign_id=store.campaign_id,
                title=item.title,
                product_id=item.product_id,
                product_num=item.product_num,
                status=const.ORDER_NEED_DRAW,
                result='',
                user_ip=request.access_route[0],
            )
            extra = dict(migu_id=user.partner_migu['id'],
                         phone=user.phone,
                         campaign_id=store.resource_campaign_id)
            # 进行物品的发放
            product = Product.get_product(item.product_id)
            status = product.add_product2user(str(user._id), item.product_num,
                                              const.LOTTERY, extra)

            # 订单状态更新
            if status != order.status:
                order.status = status
                order.save()

            return {'item': item.format(), 'order': order.format()}

    # 由于营销平台看不到id, 暂时只能用奖项名称进行对应
    prize_name = None
    for i in prize['extensionInfo']:
        if i['key'] == 'levelName':
            prize_name = i['value']
            break

    item = StoreItem.get_item_by_identity(store.store_id, prize_name)
    # 更新库存
    item.left_num -= 1
    item.use_num += 1
    item.save()

    # 无领取规则的活动营销平台会自动领取
    status = const.ORDER_NEED_DRAW if info[
        'is_exchange_rule'] else const.ORDER_IN_HAND
    # 生成兑奖订单
    order = UserOrder.create(
        user_id=str(user._id),
        item_id=item.item_id,
        store_id=item.store_id,
        store_type=store.store_type,
        campaign_id=store.campaign_id,
        title=item.title,
        product_id=item.product_id,
        product_num=item.product_num,
        status=status,
        result=json.dumps(prize),
        user_ip=request.access_route[0],
    )

    product = Product.get_product(item.product_id)
    if product.product_type != PHYSICAL_OBJECT:  # 非实物物品直接去营销平台进行奖励兑换
        # 有领取规则的抽奖活动的非实物物品自动领取, 无领取规则的活动营销平台会自动领取
        if info['is_exchange_rule']:
            # 获取用户可兑换奖励信息
            prizes = Marketing.query_exchengable_prizes(
                user.partner_migu['id'], order.campaign_id)
            if isinstance(prizes, error.ApiError):
                return prizes

            # 进行奖励的兑换, 目前最后一条为最近获得的奖励
            for _prize in prizes[::-1]:
                exchenge_ids = map(lambda x: x['id'],
                                   _prize['exchengeResources'])
                exchengeable_id = _prize['exchengableResource']['id']
                if [prize['id']] == exchenge_ids:
                    exchenge_ids = [prize['id']]
                    ret = Marketing.draw_exchengable_prize(
                        user.partner_migu['id'], order.campaign_id,
                        exchenge_ids, exchengeable_id, prize['amount'])

                    if isinstance(ret, error.ApiError):
                        return ret

        # 由于对方没有返回订单ID, 只能通过获取用户最近一个已兑换奖励的订单ID, 实物物品需要手动领取
        ret, _ = Marketing.query_exchenged_prizes(user.partner_migu['id'],
                                                  order.campaign_id,
                                                  page=1,
                                                  pagesize=1)
        if isinstance(ret, error.ApiError):
            return ret

        # 更新订单信息
        if isinstance(ret, list) and len(ret) > 0 and 'recId' in ret[0]:
            order.recid = ret[0]['recId']

        order.status = const.ORDER_IN_HAND
        order.save()

        extra = dict(migu_id=user.partner_migu['id'],
                     phone=user.phone,
                     campaign_id=store.resource_campaign_id)
        # 进行物品的发放
        status = product.add_product2user(str(user._id), item.product_num,
                                          const.LOTTERY, extra)

        # 订单状态更新
        if status != order.status:
            order.status = status
            order.save()

    return {'item': item.format(), 'order': order.format()}
Exemplo n.º 13
0
def grab_redpacket():
    """直播间红包争抢(POST)

    :uri: /lives/redpacket/grab
    :param os: 平台
    :param channels: 渠道(可选)
    :param version_code: 版本号
    :param live_id: 直播间ID
    :param source_id: 红包ID
    :return: {'ret': bool}
    """
    user = request.authed_user
    params = request.values
    os = params.get('os', None)
    channels = params.get('channels', None)
    version_code = int(params.get('version_code', 0))
    live_id = params.get('live_id', None)
    source_id = params.get('source_id', None)

    if not os or not version_code or not source_id or not live_id:
        return error.InvalidArguments

    uid = None
    province = None
    if user:
        uid = str(user._id)
        phone = str(user.phone)

        if user.province:
            province = user.province

        if not user.province and util.is_mobile_phone(phone):
            province = Migu.get_user_info_by_account_name(phone)
            if not isinstance(province, error.ApiError):
                user.update_model({'$set': {'province': province}})
            else:
                province = None

    red_packet = UserRedPacket.get_one(source_id)
    if not red_packet:
        return error.RedPacketError(u'红包不存在!')

    activity = LiveRedPacket.get_one(red_packet.active_id)
    if not activity:
        return error.RedPacketError(u'直播红包活动不存在!')

    # 查看是否有抽奖机会
    if red_packet.chance <= 0:
        return error.RedPacketError(u'已达到领取红包次数上限!')

    def get_user_redpackets():
        # 先获取已存在的红包,以及已经参与的直播间抢红包
        _red_packet, _red_packet_count = None, 0
        _ids = UserRedPacket.user_red_packets(uid)
        for urp in UserRedPacket.get_list(_ids):
            if not LiveRedPacket.get_one(urp.active_id):
                continue
            if urp.source == 0:
                # 过滤掉所有直播间抽奖机会
                continue
            if urp.chance <= 0:
                continue
            if _red_packet is None or _red_packet.expire_at > urp.expire_at:
                _red_packet = urp
            _red_packet_count += 1
        # 如果是直播间红包,返回直播间红包;如果不是,返回新红包
        if red_packet.from_user == red_packet.user_id:
            _red_packet = red_packet
        # 如果没有新红包,返回当前红包,并标记剩余红包数为0
        if not _red_packet:
            _red_packet = red_packet
        return _red_packet.format(_red_packet_count)

    def send_default_gift(uid, task_id, user, extra):
        return {
            'ret': True,
            'red_packet': get_user_redpackets(True),
            'item': None,
            'current_red_packet': red_packet.format(0, True)
        }

    extra = dict(migu_id=user.partner_migu['id'],
                 phone=user.phone,
                 campaign_id=red_packet.campaign_id)
    item = None

    key = 'lock:receive_red_packet:%s' % (uid)
    with util.Lockit(Redis, key) as locked:
        if locked:
            return error.RedPacketError(u'领取红包失败,请稍后再试!')

        # 如果是直播间红包抽奖,则需要先调用抽奖接口再获取红包物品
        if not red_packet.source:
            # 从营销中心查询/请求抽奖机会
            left_chances = Marketing.query_lottery_chance(
                user.partner_migu['id'], red_packet.campaign_id)
            if isinstance(left_chances, error.ApiError):
                return send_default_gift(uid, source_id, user, extra)
            if left_chances <= 0:
                # 进行抽奖机会的兑换
                ret = Marketing.execute_campaign(user.partner_migu['id'],
                                                 user.phone,
                                                 [red_packet.campaign_id])
                if not ret or isinstance(ret, error.ApiError):
                    return send_default_gift(uid, source_id, user, extra)

            # 扣除用户抽奖次数
            red_packet.take_chance()

            # 调用营销平台进行抽奖
            prize = Marketing.draw_lottery(user.partner_migu['id'],
                                           red_packet.campaign_id)
            if isinstance(prize, error.ApiError):
                prize = None
            if not prize:
                # 如果没有抽中奖品,发放默认奖品
                return send_default_gift(uid, source_id, user, extra)

            # 先请求红包机会
            extra.update({'campaign_id': activity.redpacket_id})
            ret = Marketing.execute_campaign(user.partner_migu['id'],
                                             user.phone,
                                             [activity.redpacket_id])
            if not ret or isinstance(ret, error.ApiError):
                return send_default_gift(uid, source_id, user, extra)
            # 抢红包
            rps = Marketing.query_red_package_by_user(user.partner_migu['id'],
                                                      activity.redpacket_id)
            if isinstance(rps, error.ApiError):
                return send_default_gift(uid, source_id, user, extra)
            if not rps:
                return send_default_gift(uid, source_id, user, extra)
            # 将最新的红包放到最前面
            rps.sort(key=lambda x: x['createDate']['time'], reverse=True)

            # 将红包放入用户可分享红包
            _urp = UserRedPacket.init()
            _urp.active_id = activity._id
            _urp.campaign_id = activity.redpacket_id
            _urp.resource_id = rps[0]['id']
            _urp.chance = 1
            _urp.expire_at = activity.share_expire_at
            _urp.item_count = activity.share_count
            _urp.user_id = uid
            _urp.from_user = uid
            _urp.source = 1
            _urp.create_model()
            red_packet = _urp

        # 扣除红包领取次数
        red_packet.take_chance()

        # 从分享红包获取物品
        prize = Marketing.grab_red_package(user.partner_migu['id'],
                                           red_packet.campaign_id,
                                           red_packet.resource_id)
        if isinstance(prize, error.ApiError):
            return {
                'ret': False,
                'red_packet': get_user_redpackets(),
                'item': None,
                'current_red_packet': red_packet.format(0, True)
            }

        if not prize:
            # 如果没有抽中奖品,发放默认奖品
            return send_default_gift(uid, source_id, user, extra)

        # 发放物品
        prize_name = prize.get('name')
        item = LiveRedPacketItem.get_item_by_identity(activity._id, prize_name)
        # 更新库存
        item.update_left()

        # 生成兑奖订单
        order = UserLiveOrder.create(user_id=str(user._id),
                                     item_id=str(item._id),
                                     activity_id=str(activity._id),
                                     activity_type=1,
                                     campaign_id=red_packet.campaign_id,
                                     title=item.title,
                                     product_id=item.product_id,
                                     product_num=item.product_num,
                                     status=const.ORDER_FINISHED,
                                     result=json.dumps(prize))
        order.save()

        # 进行物品的发放
        product = Product.get_product(item.product_id)
        product.add_product2user(uid, item.product_num, const.TASK, extra)

    return {
        'ret': True,
        'red_packet': get_user_redpackets(),
        'item': item and item.format(),
        'current_red_packet': red_packet.format(0, item is None)
    }
Exemplo n.º 14
0
def live_task():
    """观看直播时长任务 (GET)

    :uri: /lives/task
    :param task_id: 直播任务ID
    :param os: 平台
    :param channels: 渠道(可选)
    :param version_code: 版本号
    :param live_id: 直播间ID
    :return: {'ret': bool}
    """
    user = request.authed_user
    params = request.values
    task_id = params.get('task_id', None)
    os = params.get('os', None)
    channels = params.get('channels', None)
    version_code = int(params.get('version_code', 0))
    live_id = request.values.get('live_id')

    if not os or not version_code or not task_id or not live_id:
        return error.InvalidArguments

    uid = str(user._id)
    phone = str(user.phone)
    province = None
    if user.province:
        province = user.province

    if not user.province and util.is_mobile_phone(phone):
        province = Migu.get_user_info_by_account_name(phone)
        if not isinstance(province, error.ApiError):
            user.update_model({'$set': {'province': province}})
        else:
            province = None
    # 避免出现跨天时出现没有任务的情况
    tids = WatchLiveTask.get_user_tids(uid)
    task = WatchLiveTask.get_one(task_id)
    if not task:
        return error.TaskError(u'观看直播时长任务不存在!')

    if task.os not in ['all', os]:
        return error.TaskError(u'不符合任务条件!')

    if (task.version_code_mix and task.version_code_mix > version_code) or \
            (task.version_code_max and task.version_code_max < version_code):
        return error.TaskError(u'不符合任务条件!')

    if channels and task.channels and channels not in task.channels:
        return error.TaskError(u'不符合任务条件!')

    if task.login == 'login' and (
            not uid or not task.user_in_group(str(task.group), uid)):
        return error.TaskError(u'不符合任务条件!')

    if task.province and not province:
        return error.TaskError(u'不符合任务条件!')

    if task.province and province and province not in task.province:
        return error.TaskError(u'不符合任务条件!')

    extra = dict(migu_id=user.partner_migu['id'],
                 phone=user.phone,
                 campaign_id=task.campaign_id)
    msg = u"恭喜%(name)s获得%(gift)s"

    def send_default_gift(uid, task_id, user, extra, msg):
        item = WatchLiveTaskItem.get_item_by_identity(task_id, 'default')
        if not item:
            return {'ret': False, 'task': task.format(uid), 'item': None}
        # 更新库存
        item.update_left()

        # 进行物品的发放
        product = Product.get_product(item.product_id)
        status = product.add_product2user(uid, item.product_num, const.TASK,
                                          extra)
        _msg = msg % ({'name': user.nickname or user.name, 'gift': item.title})
        data = dict(message=_msg, event_id=live_id)
        Xlive.send_live_msg(data, 'activity')
        return {'ret': True, 'task': task.format(uid), 'item': item.format()}

    lockkey = 'lock:task:%s:%s' % (uid, task_id)
    with util.Lockit(Redis, lockkey) as locked:
        if locked:
            return error.TaskError(u'请求频率过高')
        # 查看是否有抽奖机会
        stat = WatchLiveTask.update_left_chance(uid, task_id)
        if not stat:
            return error.TaskError(u'无抽奖机会!')

        # 从营销中心查询/请求抽奖机会
        left_chances = Marketing.query_lottery_chance(user.partner_migu['id'],
                                                      task.campaign_id)
        if isinstance(left_chances, error.ApiError):
            return send_default_gift(uid, task_id, user, extra, msg)
        if left_chances <= 0:
            # 进行抽奖机会的兑换
            ret = Marketing.execute_campaign(user.partner_migu['id'],
                                             user.phone, [task.campaign_id])
            if not ret or isinstance(ret, error.ApiError):
                return send_default_gift(uid, task_id, user, extra, msg)

        # 调用营销平台进行抽奖
        prize = Marketing.draw_lottery(user.partner_migu['id'],
                                       task.campaign_id)
        if isinstance(prize, error.ApiError):
            prize = None

        if not prize:
            # 如果没有抽中奖品,发放默认奖品
            return send_default_gift(uid, task_id, user, extra, msg)

        prize_name = None
        for i in prize['extensionInfo']:
            if i['key'] == 'levelName':
                prize_name = i['value']
                break
        item = WatchLiveTaskItem.get_item_by_identity(task_id, prize_name)
        # 更新库存
        item.update_left()

        # 生成兑奖订单
        order = UserLiveOrder.create(user_id=uid,
                                     item_id=str(item._id),
                                     activity_id=task_id,
                                     activity_type=0,
                                     campaign_id=task.campaign_id,
                                     title=item.title,
                                     product_id=item.product_id,
                                     product_num=item.product_num,
                                     status=const.ORDER_FINISHED,
                                     result=json.dumps(prize))
        order.save()

        # 进行物品的发放
        product = Product.get_product(item.product_id)
        status = product.add_product2user(uid, item.product_num, const.TASK,
                                          extra)

        _msg = msg % ({'name': user.nickname or user.name, 'gift': item.title})
        data = dict(message=_msg, event_id=live_id)
        Xlive.send_live_msg(data, 'activity')
    return {'ret': True, 'task': task.format(uid), 'item': item.format()}
Exemplo n.º 15
0
def shipment_mg():
    params = request.values
    transactionId = params.get("transactionId")
    #200 成功,201 已发 , 202 无效transactionId
    data = {"resultCode": '200', "desc": 'ok', 'transactionId': transactionId}
    pay_order_obj = PayOrder.get_order(transactionId)
    if not pay_order_obj:
        data['resultCode'] = '202'
        return json.dumps(data)
    pay_info = pay_order_obj.pay_info
    if pay_order_obj.finished:
        data['resultCode'] = '201'
        return json.dumps(data)

    result = {}
    # 检查订单是否成功
    result = PayByMg.check_order(transactionId)
    if isinstance(result, error.ApiError):
        return result

    gift = Gift.get_gift(pay_info['gift_id'])
    # {"from_user_id":user._id,'to_user_id':to_user_id,"num":num,'gift_id':gift_id,\
    # 'gift_from':gift_from,"from_id":from_id}
    ret = gift.send_to_user(pay_info['from_user_id'], pay_info['to_user_id'],\
         pay_info['num'], pay_info['gift_from'], pay_info['from_id'],send_success=1,transactionId=transactionId)
    if ret == True:
        pay_order_obj.update_model({'$set': {'finished': 1}})
        pay_order_obj.update_model({'$set': {'check_pay_data': result}})
        data['resultCode'] = "200"
        # 营销数据入库经分
        user = User.get_one(pay_info['from_user_id'])
        data_dict = dict(cmd="deliver_money_gift",
                         deviceid=request.values.get('device', ''),
                         mobile=user.phone,
                         source=request.values.get('source', 'activity'),
                         activityid="1",
                         activityname=u"付费礼物打赏活动",
                         opt="1:{0}:{1}:{2}:{3}:{4}".format(
                             pay_order_obj["product_name"],
                             pay_order_obj["credit_value"],
                             pay_order_obj["gift_num"],
                             float(pay_order_obj["gift_num"]) *
                             float(pay_order_obj["credit_value"]),
                             pay_info['to_user_id']))
        Marketing.jf_report(data_dict)

    gift_from = pay_info['gift_from']
    from_user_id = pay_info['from_user_id']
    user = User.get_one(from_user_id)
    from_id = pay_info['from_id']
    gift_id = pay_info['gift_id']
    num = pay_info['num']
    # 录播发送消息到中心消息
    if ret and gift_from == const.FROM_RECORD:
        video = Video.get_one(from_id, check_online=False)
        if video:
            Message.send_gift_msg(str(user._id), from_id, 'gift')
            video.update_model({'$inc': {'gift_count': 1, 'gift_num': num}})

    # 直播发送广播信息
    if ret and gift_from == const.FROM_LIVE:
        total = Xlive.get_user_send_gift_count(from_id, str(user._id), gift_id,
                                               num)
        data_1 = dict(user_id=str(user._id),
                      username=user.nickname or user.name,
                      userphoto=user.get_photo(),
                      gift_name=gift.format()['product_name'],
                      gift_image=gift.format()['product_image'],
                      gift_num=num,
                      event_id=from_id,
                      total=total)
        Xlive.send_live_msg(data_1)
    data.update(data_1)
    return json.dumps(data)
Exemplo n.º 16
0
def exchange_product():
    """兑换物品接口(POST&LOGIN)

    :uri: /store/exchange_product
    :param store_id: 兑换活动ID
    :param item_id: 兑换物品ID
    :return: {'item': <Item>object, 'order': <Order>object}
    """
    user = request.authed_user
    store_id = request.values.get('store_id', None)
    item_id = request.values.get('item_id', None)

    user_ip = request.remote_addr
    device = request.values.get('device', None)

    if not store_id or not item_id:
        return error.InvalidArguments

    store = Store.get_store(store_id)
    if not store or not store.online():
        return error.StoreError('该兑换活动不存在或已下线')

    item = StoreItem.get_store_item(store_id, item_id)
    if not item:
        return error.StoreError('该兑换奖品不存在')

    # 库存判断
    if item.left_num < 1:
        return error.StoreError('该兑换奖品已卖完')

    product = Product.get_product(item.product_id)

    # 判断手机号
    if product.product_type == MOBILE_TRAFFIC and not util.is_mobile_phone(
            user.phone):
        return error.StoreError('非移动手机号不能兑换此商品')

    if product.product_type == UNICOM_TRAFFIC and not util.is_unicom_phone(
            user.phone):
        return error.StoreError('非联通手机号不能兑换此商品')

    if product.product_type == TELECOM_TRAFFIC and not util.is_telecom_phone(
            user.phone):
        return error.StoreError('非电信手机号不能兑换此商品')

    uc = UserCredit.get_or_create_user_credit(user_id=str(user._id))
    if item.credit_type == const.SALE_GEM and uc.gem < item.credit_value:
        return error.StoreError('你的游票不足,无法兑换此物品哦!')
    elif item.credit_type == const.SALE_GOLD and uc.gold < item.credit_value:
        return error.StoreError('你的游米不足,无法兑换此物品哦!')

    key = 'lock:store:%s' % (str(user._id))
    status = None
    with util.Lockit(Redis, key) as locked:
        if locked:
            return error.StoreError('兑换太频繁')

        extra = dict(migu_id=user.partner_migu['id'],
                     phone=user.phone,
                     campaign_id=store.resource_campaign_id)
        status = product.add_product2user(str(user._id), item.product_num,
                                          const.EXCHANGE, extra)
        if status == const.ORDER_FAILED:
            return error.StoreError('兑换失败')
        else:
            # 扣除货币
            if item.credit_type == const.SALE_GEM:
                uc.reduce_gem(item.credit_value, const.EXCHANGE)
            elif item.credit_type == const.SALE_GOLD:
                uc.reduce_gold(item.credit_value, const.EXCHANGE)

    # 更新库存
    item.left_num -= 1
    item.use_num += 1
    item.save()
    # 记录订单
    order = UserOrder.create(
        user_id=str(user._id),
        item_id=item.item_id,
        store_id=item.store_id,
        store_type=store.store_type,
        campaign_id=store.campaign_id,
        title=item.title,
        product_id=item.product_id,
        product_num=item.product_num,
        status=status,
        user_ip=request.access_route[0],
    )

    # 营销数据入库经分  兑换活动
    data_dict = dict(cmd="exchange",
                     opt="1",
                     deviceid=request.values.get('device', ''),
                     mobile=user.phone,
                     source=request.values.get('source', 'activity'),
                     activityid=store_id,
                     activityname=store.title)
    Marketing.jf_report(data_dict)

    return {'item': item.format(), 'order': order.format()}
Exemplo n.º 17
0
def activity_vote():
    """活动投票

    :uri: activity/vote
    :param source: 投票来源(app_play, activity, activity_share, video_share)
    :param device: 设备唯一ID
    :param video_id: 视频ID
    :param ut: 用户ut
    :return: {'vote_count': int}
    """
    user = request.authed_user
    params = request.values.to_dict()

    if not Guard.verify_sig(params):
        return error.InvalidRequest

    vid = params.get('video_id', None)
    source = params.get('source', None)
    device = params.get('device', None)
    uid = user and str(user._id)

    if not vid or not source or not device:
        return error.InvalidArguments

    # 增加ip限制,每个ip每天限制20次
    user_ip = request.remote_addr
    ip_key = 'ip_limit:%s:%s:%s' % (user_ip, vid, str(datetime.date.today()))
    ip_limit = Redis.incr(ip_key)
    if ip_limit == 1:  # 第一次设置key过期时间
        Redis.expire(ip_key, 86400)

    if ip_limit > 20:
        return error.ActivityVideoNotExist("超出IP限制")

    video = Video.get_one(vid)
    if not video:
        return error.VideoNotExist

    activity_video = ActivityVideo.get_activity_video_by_vid(vid)
    if not activity_video:
        return error.ActivityVideoNotExist("该视频未参赛")

    vote_count = activity_video['vote']
    activity_id = activity_video['activity_id']

    activity_config = ActivityConfig.get_one(activity_id)
    if not activity_config or not activity_config.online:
        return error.ActivityEnd

    is_voted = True if VoteVideo.get_vote(uid, device, vid) else False
    if is_voted:
        return error.VoteVideoLimited

    vote = VoteVideo.get_vote(uid=uid, device=device, vid=vid)
    if not vote:
        key = 'lock:vote_video:%s:%s' % (device, vid)
        with util.Lockit(Redis, key) as locked:
            if locked:
                return error.VoteVideoFailed
            vote = VoteVideo.init()
            vote.device = device
            vote.source = source
            vote.author = ObjectId(uid)
            vote.target = ObjectId(vid)
            vote.activity = ObjectId(activity_id)
            vote.create_model()
            # 票数加1
            vote_count = vote_count + 1

    # 营销数据入库经分  投票活动
    from wanx.platforms.migu import Marketing
    data_dict = dict(cmd="vote",
                     opt=vid,
                     deviceid=params.get('device', ''),
                     mobile=user.phone,
                     source=params.get('source', 'activity'),
                     activityid=str(activity_video['activity_id']),
                     activityname=activity_config['name'])
    Marketing.jf_report(data_dict)

    return {'vote_count': vote_count}