Exemplo n.º 1
0
def migu_register():
    """用户注册(GET|POST)

    :uri: /migu/register_phone
    :param phone: 手机号
    :param password: 密码
    :param code: 验证码
    :param sessionid: 短信sessionid
    :returns: {'user': object, 'ut': string}
    """
    params = request.values.to_dict()
    phone = params.get('phone', None)
    code = params.get('code', None)
    sessionid = params.get('sessionid', None)
    password = params.get('password', None)
    if not phone or not code or not password or not sessionid:
        return error.InvalidArguments

    invalid_error = User.invalid_password(password)
    if invalid_error:
        return invalid_error

    # 用户中心注册
    ret = Migu.center_register(phone, password, const.CENTER_ACCOUNT_PHONE,
                               code, sessionid)
    if isinstance(ret, error.ApiError):
        return ret

    # 进行用户绑定
    migu_uid = Migu.get_identityid(phone, password, const.CENTER_ACCOUNT_PHONE)
    if isinstance(migu_uid, error.ApiError):
        return migu_uid

    user = User.get_platform_user('migu', migu_uid)
    if not user:
        user = User.get_by_phone(phone)
        if user:
            info = dict(partner_migu={'id': migu_uid},
                        nickname=u'咪咕用户%s%s' %
                        (migu_uid[-4:], random.randint(1000, 9999)),
                        gender=random.randint(1, 2),
                        name='$mg$%s%s' %
                        (migu_uid[-4:], random.randint(1000, 9999)))
            user = user.update_model({'$set': info})
        else:
            info = dict(phone=phone,
                        nickname=u'咪咕用户%s%s' %
                        (migu_uid[-4:], random.randint(1000, 9999)),
                        gender=random.randint(1, 2),
                        name='$mg$%s%s' %
                        (migu_uid[-4:], random.randint(1000, 9999)))
            user = User.create_platform_user('migu', migu_uid, data=info)
    else:
        # 如果用户没有绑定手机并且手机号没有被绑定, 则自动进行手机号绑定
        if not user.phone and not User.get_by_phone(phone):
            info = dict(phone=phone)
            user.update_model({'$set': info})

    ut = User.gen_token(str(user._id))
    return {'user': user.format(), 'ut': ut}
Exemplo n.º 2
0
def migu_change_pwd():
    """更改密码(GET|POST)

    :uri: /migu/change_password
    :param phone: 手机号
    :param old_pwd: 旧密码
    :param new_pwd: 新密码
    :returns: {}
    """
    user = request.authed_user
    params = request.values
    old_pwd = params.get('old_pwd', None)
    new_pwd = params.get('new_pwd', None)
    phone = params.get('phone', None) or (user and user.phone)

    if not old_pwd or not new_pwd or not phone:
        return error.InvalidArguments

    invalid_error = User.invalid_password(new_pwd)
    if invalid_error:
        return invalid_error

    openid = Migu.get_identityid(phone, old_pwd, const.CENTER_ACCOUNT_PHONE)
    if isinstance(openid, error.ApiError):
        return openid

    ret = Migu.center_update_pwd(openid, old_pwd, new_pwd)
    if isinstance(ret, error.ApiError):
        return ret

    return {}
Exemplo n.º 3
0
def send_migu_code():
    """发送短信验证码 (GET|POST)

    :uri: /migu/sms_code
    :param phone: 手机号
    :param action: (注册:reg  重置:reset  升级:up)
    :returns: {'sessionid': string}
    """
    params = request.values
    phone = params.get('phone', None)
    action = params.get('action', None)
    if not phone:
        return error.InvalidArguments
    # 如果是注册验证码,提前判断手机号是否已存在
    ret = Migu.center_check_account(phone, const.CENTER_ACCOUNT_PHONE)
    if isinstance(ret, error.ApiError):
        return ret
    if action == 'reg' and not ret:
        return error.UserExists

    ret = Migu.center_sms_code(phone, action)
    if isinstance(ret, error.ApiError):
        return ret

    return {'sessionid': ret}
Exemplo n.º 4
0
def game_poplists():
    """
    获取所有游戏排行
    :uri: /games/toplists
    :param os: 平台
    :param channels: 渠道号【可选】
    :param version_code: 版本号
    :return: {'toplists': <TopList> list}
    """
    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))

    if not os or not version_code:
        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

    toplists = list()
    _ids = TopList.all_ids_by_os(os)
    for b in TopList.get_list(_ids):
        if b.os and b.os != os:
            continue

        if (b.version_code_mix and b.version_code_mix > version_code) or\
                (b.version_code_max and b.version_code_max < version_code):
            continue

        if channels and b.channels and channels not in b.channels:
            continue

        if b.login == 'login' and (not uid
                                   or not b.user_in_group(str(b.group), uid)):
            continue

        if b.province and not province:
            continue

        if b.province and province and province not in b.province:
            continue

        toplists.append(b.format())

    return {'toplists': toplists}
Exemplo n.º 5
0
def migu_present_record():
    """
    获取咪咕币赠送记录
    :uri: /migupay/present/record
    :param: start_at 查询起始时间,格式 yyyymmddHHMMSS
    :param: end_at 查询结束时间,格式 yyyymmddHHMMSS
    :param: page 页码,int
    :param: nbr 页长度, int,范围1到500
    :return: {'records': <MiguPresentRecord>list, 'end_page': bool}
    """
    user = request.authed_user
    params = request.values
    start_at = params.get('start_at')
    end_at = params.get('end_at')
    page_no = params.get('page')
    page_size = params.get('nbr')

    if not all([start_at, end_at, page_no, page_size]):
        return error.InvalidArguments

    passid = user.partner_migu and user.partner_migu.get('passid')
    if not passid:
        passid = Migu.get_user_info_by_account_name(user.phone,
                                                    keyword='passID')
        if passid:
            user.update_model({'$set': {'partner_migu.passid': passid}})
    data = {'records': [], 'end_page': False}
    # passid = '6484464505210'
    if passid:
        data = MiguPay.query_present_record(passid, start_at, end_at, page_no,
                                            page_size)
    return data
Exemplo n.º 6
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.º 7
0
def migu_reset_password():
    """重置密码 (GET|POST)

    :uri: /migu/reset_password
    :param phone: 手机号
    :param password: 密码
    :param code: 短信验证码
    :param sessionid: 短信sessionid
    :returns: {}
    """
    params = request.values.to_dict()
    phone = params.get('phone', None)
    code = params.get('code', None)
    sessionid = params.get('sessionid', None)
    password = params.get("password", None)
    if not phone or not code or not password or not sessionid:
        return error.InvalidArguments

    invalid_error = User.invalid_password(password)
    if invalid_error:
        return invalid_error

    ret = Migu.center_reset_pwd(phone, password, const.CENTER_ACCOUNT_PHONE,
                                code, sessionid)
    if isinstance(ret, error.ApiError):
        return ret

    return {}
Exemplo n.º 8
0
def game_mainstays():
    """获取主推游戏 (GET)

    :uri: /games/mainstays
    :param os: 平台
    :param channels: 渠道(可选)
    :param version_code: 版本号
    :returns: {'mainstays': list}
    """
    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))

    if not os or not version_code:
        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

    banners = list()
    _ids = GameMainstay.all_ids()
    for b in GameMainstay.get_list(_ids):
        if b.os and b.os != os:
            continue

        if (b.version_code_mix and b.version_code_mix > version_code) or\
                (b.version_code_max and b.version_code_max < version_code):
            continue

        if channels and b.channels and channels not in b.channels:
            continue

        if b.login == 'login' and (not uid
                                   or not b.user_in_group(str(b.group), uid)):
            continue

        if b.province and not province:
            continue

        if b.province and province and province not in b.province:
            continue
        banners.append(b.format())

    return {'mainstays': sorted(banners, key=lambda x: x['order'])}
Exemplo n.º 9
0
def migu_hf_userid():
    user = request.authed_user
    hf_userid = Migu.get_user_info_by_account_name(str(user.phone),
                                                   keyword='hfUserID')
    if isinstance(hf_userid, error.ApiError):
        return hf_userid

    return {'hf_userid': hf_userid}
Exemplo n.º 10
0
def all_game_grids():
    """
    获取游戏页所有宫格
    uri: /games/grids
    :param: os
    :return:  {'grids': list}
    """
    user = request.authed_user
    params = request.values
    os = params.get('os', None)
    channels = params.get('channels', None)
    version_code = int(params.get('version_code', 1))

    if not os or not version_code:
        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

    grids = list()
    _ids = GameGrid.all_ids()
    for b in GameGrid.get_list(_ids):
        if b.os and b.os != os:
            continue

        if (b.version_code_mix and b.version_code_mix > version_code) or\
                (b.version_code_max and b.version_code_max < version_code):
            continue

        if channels and b.channels and channels not in b.channels:
            continue

        if b.login == 'login' and (not uid
                                   or not b.user_in_group(str(b.group), uid)):
            continue

        if b.province and not province:
            continue

        if b.province and province and province not in b.province:
            continue
        grids.append(b.format())

    return {'grids': grids}
Exemplo n.º 11
0
def migu_verify_upgrade():
    """手机号码验证 (GET|POST)

    :uri: /migu/verify_upgrade
    :returns: {}
    """
    user = request.authed_user
    phone = user.phone

    if not phone:
        return error.InvalidArguments
    ret = Migu.get_user_info_by_account_name(phone, keyword='passID')
    if isinstance(ret, error.ApiError):
        return ret
    if ret:
        return error.UserAlreadyUpgraded

    return {}
Exemplo n.º 12
0
def migu_verify_phone():
    """手机号码验证 (GET|POST)

    :uri: /migu/verify_phone
    :param phone: 手机号
    :returns: {}
    """
    params = request.values.to_dict()
    phone = params.get('phone', None)

    if not phone:
        return error.InvalidArguments
    ret = Migu.center_check_account(phone, const.CENTER_ACCOUNT_PHONE)
    if isinstance(ret, error.ApiError):
        return ret
    elif not ret:
        return error.UserExists("手机号已被注册")

    return {}
Exemplo n.º 13
0
def phone_province():
    """
    查询手机号码归属地
    :uri: /migu/phone/province
    :param: phone
    :return:
    """
    phone = request.values.get('phone', None)
    if not phone:
        return error.InvalidArguments

    user = User.get_by_phone(phone)
    if user and user.province:
        return {'province': user.province}
    province = Migu.get_user_info_by_account_name(phone)
    if isinstance(province, error.ApiError):
        return province
    user.update_model({'$set': {'province': province}})
    return {'province': province}
Exemplo n.º 14
0
def service_up():
    """升级咪咕通行证 (GET|POST&LOGIN)

    :uri: /migu/upgrade
    :param phone: 手机号
    :param password: 升级密码
    :param code: 短信验证码
    :param sessionid: 短信sessionid
    :returns: {}
    """
    params = request.values
    phone = params.get('phone', None)
    password = params.get('password', None)
    code = params.get('code', None)
    sessionid = params.get('sessionid', None)
    if not phone or not password or not code or not sessionid:
        return error.InvalidArguments

    ret = Migu.center_service_up(phone, password, code, sessionid)
    if isinstance(ret, error.ApiError):
        return ret

    return {}
Exemplo n.º 15
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.º 16
0
def live_redpacket():
    """直播间红包活动(GET)

    :uri: /lives/redpacket/info
    :param os: 平台
    :param channels: 渠道(可选)
    :param version_code: 版本号
    :param live_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)

    if not os or not version_code 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

    live = Xlive.get_live(live_id)
    # live = Xlive.test_lives()[0]
    if not live:
        return error.LiveError('直播不存在')

    red_packet = None
    red_packet_count = 0

    # 先获取已存在的红包,以及已经参与的直播间抢红包
    _ids = UserRedPacket.user_red_packets(uid)
    # user_rps = []
    lrp_ids = []
    for urp in UserRedPacket.get_list(_ids):
        # 查找用户直播间抽取红包记录
        # if urp.resource_id is None:
        #    user_rps.append((urp.campaign_id, urp.resource_id))
        lrp_ids.append(str(urp.active_id))
        if not LiveRedPacket.get_one(urp.active_id):
            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 += urp.chance
    red_packet = red_packet.format(
        red_packet_count) if red_packet else red_packet

    cdrp = None
    rp_ids = LiveRedPacket.all_ids()
    for rp in LiveRedPacket.get_list(rp_ids):
        # 过滤非观看时长红包
        if rp.mode != 2:
            continue
        # 过滤已参与的红包活动id
        if str(rp._id) in lrp_ids:
            continue

        if rp.os and rp.os not in ['all', os]:
            continue

        if (rp.version_code_mix and rp.version_code_mix > version_code) or \
                (rp.version_code_max and rp.version_code_max < version_code):
            continue

        if channels and rp.channels and channels not in rp.channels:
            continue

        if rp.login == 'login' and (not uid or
                                    not rp.user_in_group(str(rp.group), uid)):
            continue

        if rp.province and not province:
            continue

        if rp.province and province and province not in rp.province:
            continue

        # 过滤主播
        live_authors = [] if not rp.live_authors else rp.live_authors.split(
            '\r\n')
        if live_authors and live['user_id'] not in live_authors:
            continue

        # 过滤游戏
        live_games = [] if not rp.live_games else rp.live_games.split('\r\n')
        if live_games and live['game_id'] not in live_games:
            continue

        # 过滤关键字
        key_words = [] if not rp.keyword else rp.keyword.split(u',')
        if key_words and not any(map(lambda x: x in live['name'], key_words)):
            continue

        cdrp = rp.format()
        break

    return {'red_packet': red_packet, 'cdrp': cdrp}
Exemplo n.º 17
0
def async_msg():
    """服务器给客户端发消息接口(GET|POST)

    :uri: /async/msg
    :returns: {'has_new_msg': bool, 'has_new_follow': bool, 'has_new_task': 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))

    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

    retry_seconds = 60
    retry_times = 0
    msgs = []
    while len(msgs) <= 0 and retry_times < 10:
        ts = time.time()
        if user:
            pubsub = MRedis.pubsub()
            with gevent.Timeout(retry_seconds, False):
                user_channel = User.USER_ASYNC_MSG % ({'uid': uid})
                pubsub.subscribe(user_channel)
                for item in pubsub.listen():
                    if item['type'] == 'message':
                        msgs.append(item['data'])
                        break
                pubsub.unsubscribe(user_channel)

            pubsub.close()
            msgs = [json.loads(m) for m in msgs]

            # 获取发给用户的系统消息
            for sys_msg in SysMessage.sys_user_messages(ts, uid):
                _msg = dict(obj_type='SysMessage',
                            obj_id=str(sys_msg._id),
                            count=1)
                msgs.append(_msg)
        else:
            time.sleep(retry_seconds)

        # 获取并过滤系统消息(平台、渠道、版本、用户组、有效期)
        for msg in SysMessage.sys_new_messages(ts, time.time()):
            if msg.os and msg.os not in ['all', os]:
                continue

            if (msg.version_code_mix and msg.version_code_mix > version_code) or \
                    (msg.version_code_max and msg.version_code_max < version_code):
                continue

            if channels and msg.channels and channels not in msg.channels:
                continue

            if msg.login == 'login' and (
                    not uid or not msg.user_in_group(str(msg.group), uid)):
                continue

            if msg.province and not province:
                continue

            if msg.province and province and province not in msg.province:
                continue

            _msg = dict(obj_type='SysMessage', obj_id=str(msg._id), count=1)
            msgs.append(_msg)
            break

        retry_times += 1

    has_new_msg = False
    has_new_follow = False
    has_new_task = False
    for msg in msgs:
        if msg['obj_type'] == 'FriendShip':
            has_new_follow = True
        elif msg['obj_type'] == 'Message':
            has_new_msg = True
        elif msg['obj_type'] == 'Letter':
            has_new_msg = True
        elif msg['obj_type'] == 'SysMessage':
            has_new_msg = True
        elif msg['obj_type'] == 'Task':
            has_new_task = True

    return {
        'has_new_msg': has_new_msg,
        'has_new_follow': has_new_follow,
        'has_new_task': has_new_task
    }
Exemplo n.º 18
0
def play_live():
    """观看直播接口 (GET)

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

    if not os or not version_code or live_id is None:
        return error.InvalidArguments

    live = Xlive.get_live(live_id)
    if not live:
        return error.LiveError('直播不存在')

    uid = None
    province = None
    if user:
        uid = str(user._id)
        UserTask.check_user_tasks(uid, PLAY_LIVE, 1)
        task_ids = WatchLiveTask.get_user_tids(uid)

        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

    else:
        task_ids = WatchLiveTask.get_live_tids()

    task = None
    for b in WatchLiveTask.get_list(task_ids):
        if b.os and b.os not in ['all', os]:
            continue

        if (b.version_code_mix and b.version_code_mix > version_code) or \
                (b.version_code_max and b.version_code_max < version_code):
            continue

        if channels and b.channels and channels not in b.channels:
            continue

        if b.login == 'login' and (not uid
                                   or not b.user_in_group(str(b.group), uid)):
            continue

        if b.province and not province:
            continue

        if b.province and province and province not in b.province:
            continue

        task = b.format(uid)
        break

    red_packet, red_packet_count = None, 0
    _ids = UserRedPacket.user_red_packets(uid)
    lrp_ids = []
    for urp in UserRedPacket.get_list(_ids):
        lrp_ids.append(str(urp.active_id))
        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
    red_packet = red_packet.format(
        red_packet_count) if red_packet else red_packet

    cdrp = None
    rp_ids = LiveRedPacket.all_ids()
    for rp in LiveRedPacket.get_list(rp_ids):
        # 过滤非观看时长红包
        if rp.mode != 2:
            continue
        # 过滤已参与的红包活动id
        if str(rp._id) in lrp_ids:
            continue

        if rp.os and rp.os not in ['all', os]:
            continue

        if (rp.version_code_mix and rp.version_code_mix > version_code) or \
                (rp.version_code_max and rp.version_code_max < version_code):
            continue

        if channels and rp.channels and channels not in rp.channels:
            continue

        if rp.login == 'login' and (not uid or
                                    not rp.user_in_group(str(rp.group), uid)):
            continue

        if rp.province and not province:
            continue

        if rp.province and province and province not in rp.province:
            continue

        # 过滤主播
        live_authors = [] if not rp.live_authors else rp.live_authors.split(
            '\r\n')
        if live_authors and live['user_id'] not in live_authors:
            continue

        # 过滤游戏
        live_games = [] if not rp.live_games else rp.live_games.split('\r\n')
        if live_games and live['game_id'] not in live_games:
            continue

        # 过滤关键字
        key_words = [] if not rp.keyword else rp.keyword.split(u',')
        if key_words and not any(map(lambda x: x in live['name'], key_words)):
            continue

        cdrp = rp.format()
        break

    return {'ret': True, 'task': task, 'red_packet': red_packet, 'cdrp': cdrp}
Exemplo n.º 19
0
def user_migupay_info():
    """
    用户咪咕币信息及会员信息
    :return:
    """
    user = request.authed_user
    os = request.values.get('os', 'andriod')
    channels = request.values.get('channels', None)
    version_code = int(request.values.get('version_code', 1))

    if not os or not version_code:
        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

    vip_zone = None
    _ids = GameGrid.all_ids()
    for b in GameGrid.get_list(_ids):
        if b.name != u'会员':
            continue

        if b.os and b.os != os:
            continue

        if (b.version_code_mix and b.version_code_mix > version_code) or\
                (b.version_code_max and b.version_code_max < version_code):
            continue

        if channels and b.channels and channels not in b.channels:
            continue

        if b.login == 'login' and (not uid
                                   or not b.user_in_group(str(b.group), uid)):
            continue

        if b.province and not province:
            continue

        if b.province and province and province not in b.province:
            continue

        vip_zone = b
        break

    if os == 'ios':
        hide_migumoney = Config.fetch('ios_hide_migu_money', False, int)
    else:
        hide_migumoney = False
    migu_money = {
        'miguTotalCount': 0,
        'miguMoneyCount': 0,
        'miguMarketingCount': 0
    }

    # 当登录用户访问且显示咪咕币时,去一级支付中心获取用户咪咕币信息
    if not hide_migumoney and user:
        passid = user.partner_migu and user.partner_migu.get('passid')
        if not passid:
            passid = Migu.get_user_info_by_account_name(user.phone,
                                                        keyword='passID')
            if passid:
                user.update_model({'$set': {'partner_migu.passid': passid}})
        # passid = '6484464505210'
        if passid:
            migu_money = MiguPay.query_balance_available_new(passid)
            if isinstance(migu_money, error.ApiError):
                # TODO 生产环境中需要返回错误信息
                # return migu_money
                migu_money = {
                    'miguTotalCount': 0,
                    'miguMoneyCount': 0,
                    'miguMarketingCount': 0
                }

    vip = {
        'vip5': {
            'subscribed': False,
            'can_sub': True
        },
        'vip10': {
            'subscribed': False,
            'can_sub': True
        }
    }
    if user and user.phone:
        vip = MiguPay.check_user_vip_level(user.phone)
        if isinstance(vip, error.ApiError):
            return vip
    data = {
        'hide_migu_money': bool(hide_migumoney),
        'migu_money': migu_money,
        'vip': vip,
        'vip_action': vip_zone and vip_zone.action
    }
    return data
Exemplo n.º 20
0
def game_home():
    """
    获取游戏页首页内容
    uri: /games/home
    :param os: 平台
    :param channels: 渠道(可选)
    :param version_code: 版本号
    :return:  {'grids': list}
    """
    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))

    if not os or not version_code:
        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

    def my_filter(data):
        result = list()
        for b in data:
            if b.os and b.os != os:
                continue

            if (b.version_code_mix and b.version_code_mix > version_code) or\
                    (b.version_code_max and b.version_code_max < version_code):
                continue

            if channels and b.channels and channels not in b.channels:
                continue

            if b.login == 'login' and (not uid or
                                       not b.user_in_group(str(b.group), uid)):
                continue

            if b.province and not province:
                continue

            if b.province and province and province not in b.province:
                continue

            result.append(b.format())
        return result

    # 游戏页宫格
    _ids = GameGrid.all_ids()
    grids = my_filter(GameGrid.get_list(_ids))

    # 游戏页广告
    _ids = GameAds.all_ad_ids()
    banners = my_filter(GameAds.get_list(_ids))

    # 游戏页主推游戏
    _ids = GameMainstay.all_ids()
    mainstays = my_filter(GameMainstay.get_list(_ids))

    # 游戏页热门游戏
    _ids = HotRecommendGame.hot_game_ids()
    hot_games = [g.format() for g in Game.get_list(_ids)]

    # 游戏页模块内容
    _ids = GameModule.all_ids_by_os(os)
    modules = [
        i.format() for i in GameModule.get_list(_ids)
        if ModuleGame.module_game_ids(str(i._id))
    ]

    return {
        'grids': grids,
        'ads': banners,
        'mainstays': mainstays,
        'hot_games': hot_games,
        'modules': modules
    }
Exemplo n.º 21
0
def query_new_redpacket():
    """
    :uri: /lives/redpacket/query_new
    :param os: 平台
    :param channels: 渠道(可选)
    :param version_code: 版本号
    :param live_id: 直播间ID
    :param active_id: 活动ID
    :return:
    """
    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)
    active_id = params.get('active_id', None)

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

    live = Xlive.get_live(live_id)
    if not live:
        return error.LiveError(u'直播不存在')

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

    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
    else:
        return {'red_packet': activity.format()}

    live_authors = [] if not activity.live_authors else activity.live_authors.split(
        '\r\n')
    live_games = [] if not activity.live_games else activity.live_games.split(
        '\r\n')
    key_words = [] if not activity.keyword else activity.keyword.split(u',')

    # 过滤主播
    if live_authors and live['user_id'] not in live_authors:
        return error.RedPacketError(u'不符合活动条件!')
    # 过滤游戏
    if live_games and live['game_id'] not in live_games:
        return error.RedPacketError(u'不符合活动条件!')
    # 过滤关键字
    if key_words and not any(map(lambda x: x in live['name'], key_words)):
        return error.RedPacketError(u'不符合活动条件!')

    if activity.os not in ['all', os]:
        return error.RedPacketError(u'不符合活动条件!')

    if (activity.version_code_mix and activity.version_code_mix > version_code) or \
            (activity.version_code_max and activity.version_code_max < version_code):
        return error.RedPacketError(u'不符合活动条件!')

    if channels and activity.channels and channels not in activity.channels:
        return error.RedPacketError(u'不符合活动条件!')

    if activity.login == 'login' and (
            not uid or not activity.user_in_group(str(activity.group), uid)):
        return error.RedPacketError(u'不符合活动条件!')

    if activity.province and not province:
        return error.RedPacketError(u'不符合活动条件!')

    if activity.province and province and province not in activity.province:
        return error.RedPacketError(u'不符合活动条件!')

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

        # 查看用户是否已领取该红包
        if UserRedPacket.check_live_redpacket(uid, activity._id):
            return error.RedPacketError(u'用户已领取该红包!')

        _urp = UserRedPacket.init()
        _urp.active_id = activity._id
        _urp.campaign_id = activity.campaign_id
        _urp.chance = activity.chance
        _urp.expire_at = activity.expire_at
        _urp.user_id = uid
        _urp.source = 0  # 不可被分享
        _urp.create_model()
        return {'red_packet': _urp.format(activity.chance)}
Exemplo n.º 22
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.º 23
0
def user_msg_home():
    """获取消息首页信息(GET|POST)

    :uri: /messages/home
    :param lrt: 系统消息最后阅读时间
    :returns: {'msgs': list, 'sys_msgs': list, 'letters': list}
    """
    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))
    ts = params.get('lrt', None)

    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

    # 默认取7天前的系统个人消息
    cts = time.time()
    if ts:
        ts = ts_user = float(ts)
    else:
        ts_user = (cts - 7 * 24 * 3600)

    sys_msgs = []
    # 过滤系统消息(平台、渠道、版本、用户组、有效期)
    for msg in SysMessage.sys_new_messages(ts, cts):
        if msg.os and msg.os not in ['all', os]:
            continue

        if (msg.version_code_mix and msg.version_code_mix > version_code) or\
                (msg.version_code_max and msg.version_code_max < version_code):
            continue

        if channels and msg.channels and channels not in msg.channels:
            continue

        if msg.login == 'login' and (
                not uid or not msg.user_in_group(str(msg.group), uid)):
            continue

        if msg.province and not province:
            continue

        if msg.province and province and province not in msg.province:
            continue

        sys_msgs.append(msg.format())

    msgs = []
    letters = []
    if user:
        uid = str(user._id)

        # 用户系统消息推送
        sys_user_msg = [
            msg.format() for msg in SysMessage.sys_user_messages(ts_user, uid)
        ]
        sys_msgs.extend(sys_user_msg)

        msgs = [msg.format() for msg in Message.user_new_messages(uid)]
        letters = list()
        _letters = Letter.new_letter_count(uid)
        for _letter in _letters:
            last_letter = Letter.get_one(_letter['last_id'])
            temp = dict(last_letter=last_letter.format(),
                        count=_letter['count'])
            letters.append(temp)
    return {'msgs': msgs, 'sys_msgs': sys_msgs, 'letters': letters}
Exemplo n.º 24
0
def platform_login():
    """第三方平台token登录 (GET|POST)

    :uri: /platform/users/login
    :param platform: 平台标识{'csdk':付费SDK, 'weixin':微信, 'qq':QQ, 'migu':咪咕}
    :param token: 用户平台token
    :returns: {'user': object, 'ut': string}
    """
    params = request.values
    platform = params.get('platform', None)
    token = params.get("token", None)
    if not token or platform not in const.PARTNER:
        return error.InvalidArguments

    data = Migu.token_validate(token)
    if isinstance(data, error.ApiError):
        return data

    openid = data.get('msisdn', None)
    migu_uid = data.get('identityID', None)
    passid = data.get('passID', None)
    if isinstance(migu_uid, error.ApiError):
        return migu_uid

    if platform == 'migu':
        # 进行用户绑定
        user = User.get_platform_user('migu', migu_uid)
        if not user:
            user = User.get_by_phone(openid)
            if user:
                info = dict(partner_migu={
                    'id': migu_uid,
                    'passid': passid
                },
                            name='$mg$%s%s' %
                            (migu_uid[-4:], random.randint(1000, 9999)))
                user = user.update_model({'$set': info})
            else:
                info = dict(phone=openid,
                            nickname=u'咪咕用户%s%s' %
                            (migu_uid[-4:], random.randint(1000, 9999)),
                            name='$mg$%s%s' %
                            (migu_uid[-4:], random.randint(1000, 9999)),
                            partner_migu={
                                'id': migu_uid,
                                'passid': passid
                            })
                user = User.create_platform_user('migu', migu_uid, data=info)
        else:
            info = {}
            # 如果用户没有绑定手机并且手机号没有被绑定, 则自动进行手机号绑定
            if not user.phone and not User.get_by_phone(openid):
                info = dict(phone=openid)
            # 如果用户未绑定passid,则自动进行passid绑定
            if passid not in user.partner_migu:
                info.update(
                    dict(partner_migu={
                        'id': migu_uid,
                        'passid': passid
                    }))
            if info:
                user = user.update_model({'$set': info})

        # 同步咪咕用户名密码
        if user:
            User.change_pwd(user, token)
    else:
        # 判断平台用户是否已经用户系统中存在
        user = User.get_platform_user(platform, openid)
        first_login = not user

        info = {}
        if platform == 'csdk':
            info = ChargeSDK(token).get_open_info()
        elif platform == 'weixin':
            info = WeiXin(token, openid).get_open_info(first_login)
        elif platform == 'qq':
            info = QQ(token, openid).get_open_info(first_login)

        if not info:
            return error.LoginFailed

        # 如果平台用户在用户系统中不存在, 则创建, 通过平台ID(openid)进行关联
        if first_login:
            open_id = info.pop('openid')
            user = User.create_platform_user(platform, open_id, data=info)
            # 给咪咕平台发送请求进行咪咕账号注册并登录绑定
            try:
                if platform in ['qq', 'weixin'] and user:
                    password = '******' % (openid[-4:])
                    ret = Migu.center_register(open_id, password,
                                               const.CENTER_ACCOUNT_INDIV)
                    if not isinstance(ret, error.ApiError):
                        openid = Migu.get_identityid(
                            open_id, password, const.CENTER_ACCOUNT_INDIV)
                        if not isinstance(openid, error.ApiError):
                            if not User.get_platform_user('migu', openid):
                                info = {'partner_migu': {'id': openid}}
                                user.update_model({'$set': info})
            except:
                pass

    if not user:
        return error.LoginFailed

    ut = User.gen_token(str(user._id))
    return {'user': user.format(include_fields=['passid']), 'ut': ut}