Exemple #1
0
def game_host():
    """获取API的URL (GET)

    :uri: /games/host
    :param game_id: 游戏id
    :returns: {'host': url, 'live_host': url, 'under_test': bool,
               'migu_app': {'appid': string, 'secret': string}}
    """
    params = request.values
    gid = params.get('game_id', None)
    game = Game.get_one(gid, check_online=False)
    if not game:
        return error.GameNotExist

    if game.status is None or game.status == const.ONLINE:
        host = app.config.get('SERVER_URL')
        live_host = app.config.get('LIVE_SERVER_URL')
    elif game.status == const.OFFLINE:
        live_host = host = 'http://localhost'
    elif game.status == const.UNDER_TEST:
        from config import Stage
        host = Stage.SERVER_URL
        live_host = Stage.LIVE_SERVER_URL
    else:
        live_host = host = app.config.get('SERVER_URL')
    return {
        'host': host,
        'live_host': live_host,
        'under_test': game.status == const.UNDER_TEST,
        'migu_app': game.migu
    }
Exemple #2
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)}
Exemple #3
0
    def format(cls, live, exclude_fields=[]):
        user_ex_fields = []
        game_ex_fields = []
        for field in exclude_fields:
            if field.startswith('user__'):
                _, _field = field.split('__')
                user_ex_fields.append(_field)
            elif field.startswith('game__'):
                _, _field = field.split('__')
                game_ex_fields.append(_field)

        ut = request.values.get("ut", None)
        uid = User.uid_from_token(ut)

        user_id = live.get('user_id', None)

        from wanx.models.home import Share
        share_title = None
        if str(user_id) == uid:
            share_title = Share.get_by_self_live().title
        else:
            share_title = Share.get_by_others_live().title

        game = Game.get_one(str(live['game_id']), check_online=False)
        user = User.get_one(str(live['user_id']), check_online=False)
        live['user'] = user and user.format(exclude_fields=user_ex_fields)
        live['game'] = game and game.format(exclude_fields=game_ex_fields)
        live['from_following'] = live.get('from_following', False)
        live['share_title'] = share_title
        # 强行移除ut
        live.pop('ut', None)
        return live
Exemple #4
0
def do_task(worker, job):
    from wanx.base.log import print_log
    from wanx.base import const
    from wanx.models.video import Video
    from wanx.models.user import User
    from wanx.models.game import Game
    data = job.data
    # 记录日志
    print_log('create_live_video', data)

    data = json.loads(data)
    # 记录日志
    print_log('create_live_video',
              '%s ==========================> Start' % (data['event_id']))

    user = User.get_one(data['user_id'], check_online=False)
    if not user:
        return ''

    game = Game.get_one(data['game_id'], check_online=False)
    if not game:
        return ''

    video_id = Video.get_video_by_event_id(data['event_id'], str(user._id))
    video = Video.get_one(str(video_id), check_online=False)

    if not video:
        video = Video.init()
        video.author = ObjectId(data['user_id'])
        video.game = ObjectId(data['game_id'])
        video.title = data['title']
        video.duration = data['duration']
        video.ratio = data['ratio']
        video.cover = data['cover']
        video.url = data['url']
        video.event_id = data['event_id']
        video.status = const.ONLINE
        video.create_model()
    else:
        data['author'] = ObjectId(data.pop('user_id'))
        data['game'] = ObjectId(data.pop('game_id'))
        video.update_model({'$set': data})

    # 记录日志
    print_log('create_live_video',
              '%s ==========================> Finished' % (data['event_id']))

    from wanx.models.activity import Battle
    battle = Battle.get_live_battle(
        data['user_id'],
        data['title'].decode('unicode-escape').encode('utf-8'), None)
    if battle:
        Battle.set_video_id(battle['_id'], video_id)

    return ''
Exemple #5
0
    def format(self):
        data = model_to_dict(self)
        image = self.image
        if self.game_id and not image:
            game = Game.get_one(self.game_id, check_online=False)
            image = game and game.icon

        data['image'] = urljoin(app.config.get("MEDIA_URL"), image)
        data['cover'] = self.cover and urljoin(app.config.get("MEDIA_URL"),
                                               self.cover)
        return data
Exemple #6
0
def get_game(gid):
    """获取游戏详细信息 (GET)

    :uri: /games/<string:gid>
    :returns: object
    """
    game = Game.get_one(gid, check_online=False)
    if not game:
        return error.GameNotExist

    return game.format()
Exemple #7
0
def format_game(view, context, model, name):
    model = model if isinstance(model, dict) else model_to_dict(model)
    _value = model.get(name, None)
    obj = Game.get_one(str(_value), check_online=False)
    if obj:
        _value = '%s (%s)' % (obj.name, _value)
        html = u'<a href="/admin/gamesview/?flt1_0=%s">%s</a>' % (str(
            obj._id), _value)
        _value = widgets.HTMLString(html)
    else:
        _value = u'游戏不存在'
    return _value
Exemple #8
0
def migu_user_videos(openid):
    """获取用户创建的视频 (GET)

    :uri: /migu/users/<string:openid>/videos/
    :param game_id: 咪咕游戏id, 不传取用户所有游戏的视频
    :param maxs: 最后时间, 0代表当前时间, 无此参数按page来分页
    :param page: 页码(数据可能有重复, 建议按照maxs分页)
    :param nbr: 每页数量
    :returns: {'videos': list, 'end_page': bool, 'maxs': timestamp}
    """
    params = request.values
    maxs = params.get('maxs', None)
    maxs = time.time() if maxs is not None and int(
        float(maxs)) == 0 else maxs and float(maxs)
    page = int(params.get('page', 1))
    pagesize = int(params.get('nbr', 10))
    bid = params.get('game_id', None)

    game = Game.get_by_bid(bid)
    gid = str(game._id) if game else None
    user = User.get_platform_user('migu', openid)
    if not user:
        return error.UserNotExist
    uid = str(user._id)

    videos = list()
    vids = list()
    while len(videos) < pagesize:
        if gid:
            vids = Video.user_game_video_ids(uid, gid, page, pagesize, maxs)
        else:
            vids = Video.user_video_ids(uid, page, pagesize, maxs)

        for video in Video.get_list(vids):
            game = Game.get_one(str(video.game))
            # 过滤掉不是咪咕大厅游戏(游戏bid字段为空)的视频
            if game and game.bid:
                videos.append(video.format())

        # 如果按照maxs分页, 不足pagesize个记录则继续查询
        if maxs is not None:
            obj = Video.get_one(vids[-1], check_online=False) if vids else None
            maxs = obj.create_at if obj else 1000
            if len(vids) < pagesize:
                break
        else:
            break

    return {'videos': videos, 'end_page': len(vids) != pagesize, 'maxs': maxs}
Exemple #9
0
def user_videos(uid):
    """获取用户创建的视频 (GET)

    :uri: /users/<string:uid>/videos
    :params game_id: 游戏id, 不传取用户所有游戏的视频
    :param maxs: 最后时间, 0代表当前时间, 无此参数按page来分页
    :param page: 页码(数据可能有重复, 建议按照maxs分页)
    :param nbr: 每页数量
    :returns: {'videos': list, 'end_page': bool, 'maxs': timestamp}
    """
    params = request.values
    maxs = params.get('maxs', None)
    maxs = time.time() if maxs is not None and int(
        float(maxs)) == 0 else maxs and float(maxs)
    page = int(params.get('page', 1))
    pagesize = int(params.get('nbr', 10))
    gid = params.get('game_id', None)
    if gid and not Game.get_one(gid):
        return error.GameNotExist

    videos = list()
    vids = list()
    while len(videos) < pagesize:
        if gid:
            vids = Video.user_game_video_ids(uid, gid, page, pagesize, maxs)
        else:
            vids = Video.user_video_ids(uid, page, pagesize, maxs)
        ex_fields = [
            'is_favored', 'is_liked', 'author__is_followed', 'game__subscribed'
        ]
        videos.extend(
            [v.format(exclude_fields=ex_fields) for v in Video.get_list(vids)])

        # 如果按照maxs分页, 不足pagesize个记录则继续查询
        if maxs is not None:
            obj = Video.get_one(vids[-1], check_online=False) if vids else None
            maxs = obj.create_at if obj else 1000
            if len(vids) < pagesize:
                break
        else:
            break

    return {'videos': videos, 'end_page': len(vids) != pagesize, 'maxs': maxs}
Exemple #10
0
def unsub_game():
    """取消订阅游戏 (GET|POST&LOGIN)

    :uri: /user/opt/unsubscribe-game
    :param game_id: 游戏id
    :returns: {}
    """
    user = request.authed_user
    gid = request.values.get('game_id', None)
    game = Game.get_one(gid, check_online=False)
    if not game:
        return error.GameNotExist
    key = 'lock:unsubgame:%s' % (str(user._id))
    with util.Lockit(Redis, key) as locked:
        if locked:
            return error.SubGameFailed('取消订阅失败')
        usg = UserSubGame.get_by_ship(str(user._id), gid)
        usg.delete_model() if usg else None
    return {}
Exemple #11
0
def create_video():
    """创建视频 (POST&LOGIN)

    :uri: /videos/new-video
    :param game_id: 视频所属游戏id
    :param title: 视频标题
    :param duration: 视频时长
    :param ratio: 视频尺寸
    :returns: object
    """
    user = request.authed_user
    gid = request.values['game_id']
    game = Game.get_one(gid)
    if not game:
        return error.GameNotExist
    video = Video.init()
    video.author = ObjectId(user._id)
    video.game = ObjectId(gid)
    video.title = request.values['title']
    # 敏感词检查
    if Spam.filter_words(video.title, 'video'):
        return error.InvalidContent
    try:
        duration = int(request.values['duration'])
    except:
        return error.InvalidArguments

    video.duration = duration
    video.ratio = request.values['ratio']
    # 设置为文件上传状态, 文件上传成功之后更改为上线状态
    video.status = const.UPLOADING
    vid = video.create_model()

    # 任务检查
    if user:
        UserTask.check_user_tasks(str(user._id), CREATE_VIDEO, 1)

    return Video.get_one(vid, check_online=False).format()
Exemple #12
0
def user_subs():
    """
    用户订阅内容
    :uri: /user/subscribed/all
    :param: page
    :param: nbr
    :param: maxs
    :return: {'objs': <SubObj>list}
    """
    user = request.authed_user
    uid = str(user._id)

    params = request.values
    page = int(params.get('page', 1))
    pagesize = int(params.get('nbr', 10))
    maxs = params.get('maxs', None)
    maxs = time.time() if maxs is not None and int(
        float(maxs)) == 0 else maxs and float(maxs)

    objs = list()
    ids = list()
    while len(objs) < pagesize:
        ids = UserSubObj.user_sub_obj_ids(uid, page, pagesize, maxs)
        for _id, _ in ids:
            _obj = Game.get_one(_id) or Show.get_one(_id)
            _obj and objs.append(
                _obj.format(exclude_fields=['subscribed', 'obj_type']))

        # 如果按照maxs分页, 不足pagesize个记录则继续查询
        if maxs is not None:
            maxs = ids[-1][1] if ids else 1000
            if len(ids) < pagesize:
                break
        else:
            break

    return {'objs': objs, 'end_page': len(ids) != pagesize, 'maxs': maxs}
Exemple #13
0
def migu_elite_video():
    """获取精选视频 (GET)

    :uri: /migu/videos/elite/
    :param maxs: 最后时间, 0代表当前时间, 无此参数按page来分页
    :param page: 页码(数据可能有重复, 建议按照maxs分页)
    :param nbr: 每页数量
    :returns: {'videos': list, 'end_page': bool, 'maxs': timestamp}
    """
    params = request.values
    maxs = params.get('maxs', None)
    maxs = time.time() if maxs is not None and int(
        float(maxs)) == 0 else maxs and float(maxs)
    page = int(params.get('page', 1))
    pagesize = int(params.get('nbr', 10))

    videos = list()
    vids = list()
    while len(videos) < pagesize:
        vids = Video.elite_video_ids(page, pagesize, maxs)
        for video in Video.get_list(vids):
            game = Game.get_one(str(video.game))
            # 过滤掉不是咪咕大厅游戏(游戏bid字段为空)的视频
            if game and game.bid:
                videos.append(video.format())

        # 如果按照maxs分页, 不足pagesize个记录则继续查询
        if maxs is not None:
            obj = Video.get_one(vids[-1], check_online=False) if vids else None
            maxs = obj.release_time if obj else 1000
            if len(vids) < pagesize:
                break
        else:
            break

    return {'videos': videos, 'end_page': len(vids) != pagesize, 'maxs': maxs}
def do_task(worker, job):
    from wanx.base.log import print_log
    from wanx.base import const, util, jpush
    from wanx.models.user import User
    from wanx.models.game import Game
    from wanx.models.live import Live_Activity
    from wanx.models.activity import ActivityConfig
    from wanx.models.game import GameActivity
    from wanx.models.task import BEGIN_LIVE, UserTask
    from wanx.base.xredis import Redis
    from wanx.base.xmysql import MYDB
    from wanx.platforms.xmatch import Xmatch

    data = job.data
    # 记录日志
    print_log('create_live_activity', data)

    data = json.loads(data)
    # 记录日志
    print_log('create_live_activity',
              '%s ==========================> Start' % (data['event_id']))

    user = User.get_one(data['user_id'], check_online=False)
    if not user:
        return ''
    # 主播上线push推送
    push_content = u"您关注的主播 {0} 正在直播,点击围观".format(user.nickname)
    message_content = u"您关注的主播 {0} 正在直播,速速去围观吧!".format(user.nickname)
    an_link = "playsdk://video_live/{0}/".format(data['event_id'])
    ios_link = "playsdk://live/{0}".format(data['event_id'])
    jpush.jpush_schedule_create(data['event_id'], user, push_content,
                                message_content, an_link, ios_link)

    # 赛事预约直播上线推送
    battle = Xmatch.getbattle(user._id, data['name'])
    if battle:
        battle = battle['data']['battle']
        push_title = u'您预约的比赛正在进行'
        push_content = u"{0}  vs  {1}正在直播,点击围观".format(battle['team_1'],
                                                       battle['team_2'])
        message_content = u"您预约的比赛{0}  vs  {1}正在直播!".format(
            battle['team_1'], battle['team_2'])
        if battle.get('players', '') != "":
            push_content = message_content = battle['live_name']
        an_link = "playsdk://video_live/{0}/".format(data['event_id'])
        ios_link = "playsdk://live/{0}".format(data['event_id'])
        jpush.jpush_withtitle_create(data['event_id'], battle['_id'],
                                     push_title, push_content, message_content,
                                     an_link, ios_link)

    game = Game.get_one(data['game_id'], check_online=False)
    if not game:
        return ''

    aid = None
    aids = ActivityConfig.get_by_type(const.FROM_LIVE)
    for a in ActivityConfig.get_list(aids):
        gids = GameActivity.game_activity_ids(a['_id'])
        if gids and data['game_id'] not in gids:
            continue
        aid = a['_id']
        break

    if not aid:
        return ''
    print_log('create_live_activity',
              '%s ==========================> activity_id' % (aid))
    activity_live = Live_Activity.get_activity_live(str(user._id), aid)
    if not activity_live:
        key = 'lock:activity:live:%s:%s' % (str(user._id), aid)
        with util.Lockit(Redis, key) as locked:
            if locked:
                return ''
        activity_live = Live_Activity.init()
        activity_live.author = ObjectId(data['user_id'])
        activity_live.game = ObjectId(data['game_id'])
        activity_live.event_id = data['event_id']
        activity_live.activity_id = ObjectId(aid)
        activity_live.create_model()
        # 如果没有活动任务则创建
        UserTask.create_and_init_user_tasks(str(user._id))
    if not MYDB.is_closed():
        MYDB.close()
    try:
        UserTask.check_user_tasks(user._id, BEGIN_LIVE, 1, data['game_id'],
                                  aid)
    except Exception as e:
        print_log('create_live_activity', '%s ========' % e)
    if not MYDB.is_closed():
        MYDB.close()

    # 记录日志
    print_log('create_live_activity',
              '%s ==========================> Finished' % (data['event_id']))
    return ''