Exemple #1
0
def follow_user():
    """关注用户 (GET|POST&LOGIN)

    :uri: /user/opt/follow-user
    :param target_user_id: 被关注用户id
    :returns: {}
    """
    user = request.authed_user
    params = request.values
    target_uid = params.get('target_user_id', None)
    target_user = User.get_one(target_uid)
    if not target_user:
        return error.UserNotExist

    if target_uid == str(user._id):
        return error.FollowFailed("不能关注自己哦")

    fs = FriendShip.get_by_ship(str(user._id), target_uid)
    if not fs:
        key = 'lock:follow:%s:%s' % (str(user._id), target_uid)
        with util.Lockit(Redis, key) as locked:
            if locked:
                return error.FollowFailed

            fs = FriendShip.init()
            fs.source = ObjectId(str(user._id))
            fs.target = ObjectId(target_uid)
            fs.create_model()
            # 关注主播任务检查
            if user:
                UserTask.check_user_tasks(str(user._id), FOLLOW_USER, 1)

    return {}
Exemple #2
0
def login():
    """用户登录 (GET|POST)

    :uri: /users/login
    :param name: 用户名
    :param password: 密码
    :param type: 登陆类型(name, phone,)
    :returns: {'user': object, 'ut': string}
    """
    params = request.values
    login_type = params.get('type', 'name')
    name = params.get("name", None)
    password = params.get("password", None)
    if name is None or password is None or login_type not in ['name', 'phone']:
        return error.InvalidArguments

    user = User.login(name, password, login_type=login_type)
    if not user:
        return error.LoginFailed

    # 初始化用户任务
    UserTask.create_and_init_user_tasks(str(user._id))

    token = User.gen_token(str(user._id))
    return {'user': user.format(), 'ut': token}
Exemple #3
0
def share_video():
    """分享视频 (POST)

    :uri: /users/share
    :param platform: 分享平台(moments, qzone, qq, weixin, other)
    :param target_type:分享数据类型(video, game, live, url)
    :param target_value: 分享数据值
    :returns: {}
    """
    user = request.authed_user
    params = request.values
    platform = params.get('platform', 'other')
    target_type = params.get('target_type', 'video')
    target_value = params.get('target_value')

    if not platform:
        return error.InvalidArguments

    rv = UserShare.init()
    rv.user = str(user._id) if user else None
    rv.platform = platform
    rv.target_type = target_type
    rv.target_value = target_value
    rv.create_model()
    # 分享视频任务检查
    if user and target_type == 'video':
        UserTask.check_user_tasks(str(user._id), SHARE_VIDEO, 1)

    return {}
Exemple #4
0
def game_download_finish(download_id):
    """游戏下载完成(POST)

    :uri: /games/<string:download_id>/finish_download
    :returns: {}
    """
    gd = GameDownload.get_one(download_id)
    if gd:
        gd.update_model({'$set': {'finish': True}})
        # 下载游戏任务检查
        if request.authed_user:
            UserTask.check_user_tasks(str(request.authed_user._id),
                                      DOWNLOAD_GAME, 1, str(gd.game))
    return {}
Exemple #5
0
    def get_or_create_user_credit(cls, user_id):
        uc, created = cls.get_or_create(user_id=user_id,
                                        defaults={
                                            'task_at': datetime.datetime.now(),
                                            'gift_at': datetime.datetime.now()
                                        })
        if created:
            # 初始化用户任务
            from wanx.models.task import UserTask
            UserTask.init_tasks(user_id)
            # 初始化免费礼物
            from wanx.models.product import UserProduct
            UserProduct.refresh_daily_free_gifts(user_id)

        return uc
Exemple #6
0
def share_live():
    """分享直播接口 (GET)

    :uri: /lives/share
    :param live_id: 直播ID
    :return: {'ret': bool}
    """
    user = request.authed_user
    live_id = request.values.get('live_id')
    live = Xlive.get_live(live_id)
    if not live:
        return error.LiveError('直播不存在')

    if user:
        UserTask.check_user_tasks(str(user._id), SHARE_LIVE, 1)

    return {'ret': True}
Exemple #7
0
def refresh_token():
    """刷新用户token时间 (GET|POST&LOGIN)

    :uri: /users/refresh_token
    :returns: {'user': Object}
    """
    ut = request.values.get("ut", None)
    user = request.authed_user
    token = User.set_token(ut, str(user._id))
    if token:
        User.recommend_users(str(user._id))
        # 更新用户活跃时间
        user.update_model({'$set': {'update_at': time.time()}})
    # 初始化用户任务
    UserTask.create_and_init_user_tasks(str(user._id))

    return {'user': user.format(include_fields=['passid'])}
Exemple #8
0
def create_comment():
    """创建评论 (GET|POST&LOGIN)

    :uri: /user/opt/submit-comment
    :param video_id: 被评论视频id
    :param content: 评论内容
    :returns: {'comment': object}
    """
    user = request.authed_user
    params = request.values
    vid = params.get('video_id', None)
    content = params.get('content', None)
    if not vid or not content:
        return error.InvalidArguments

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

    # 敏感词检查
    if Spam.filter_words(content, 'comment'):
        return error.InvalidContent
    comment = Comment.init()
    comment.author = ObjectId(str(user._id))
    comment.content = content
    comment.video = ObjectId(vid)
    cid = comment.create_model()
    if cid:
        # 发送评论消息
        Message.send_video_msg(str(user._id), str(vid), 'comment')

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

        # 更新活动评论数
        avideos = ActivityVideo.get_activity_video(vid=vid)
        for avideo in avideos:
            ts = time.time()
            aconfig = ActivityConfig.get_one(str(avideo['activity_id']), check_online=False)
            if aconfig and aconfig.status == const.ACTIVITY_BEGIN \
                    and (aconfig.begin_at < ts and aconfig.end_at > ts):
                avideo = ActivityVideo.get_one(avideo['_id'], check_online=False)
                avideo.update_model({'$inc': {'comment_count': 1}})

    return Comment.get_one(str(cid)).format()
Exemple #9
0
def register():
    """用户注册 (GET|POST)

    :uri: /users/register
    :param name: 用户名
    :param password: 密码
    :param nickname: 昵称
    :returns: {'user': object, 'ut': string}
    """
    params = request.values.to_dict()
    name = params.get("name", None)
    # delete password from data so that we don't save it to mongo
    password = str(params.pop("password", None))
    nickname = params.get('nickname', None)
    if not name or not password or not nickname:
        return error.InvalidArguments

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

    invalid_error = User.invalid_nickname(nickname)
    if invalid_error:
        return invalid_error

    if User.get_by_name(name):
        return error.UserExists

    user = User.init()
    user.update(params)

    salt = os.urandom(const.PWD_HASH_LEN)
    pwd = User.gen_pwd_hash(password, salt)
    user._salt = Binary(salt)
    user._password = Binary(pwd)
    uid = user.create_model()
    new_user = User.get_one(uid)

    # 初始化用户任务
    UserTask.create_and_init_user_tasks(str(new_user._id))

    token = User.gen_token(str(uid))
    return {'user': new_user.format(), 'ut': token}
Exemple #10
0
def activity_create_video(aid):
    """创建活动视频 (POST&LOGIN)

    :uri: activity/<string:aid>/new-video
    :param video_id: 原始视频id
    :returns: object
    """
    user = request.authed_user
    vid = request.values['video_id']
    video = Video.get_one(str(vid))
    if not video:
        return error.VideoNotExist

    if str(user._id) != str(video.author):
        return error.AuthFailed

    activity_video = ActivityVideo.get_activity_video_by_vid(vid)
    if activity_video:
        return error.ActivityVideoExist

    activity_video = ActivityVideo.init()
    activity_video.title = video.title
    activity_video.video_id = ObjectId(vid)
    activity_video.like_count = video.like
    activity_video.comment_count = video.comment_count
    activity_video.vv = video.vv
    activity_video.author = ObjectId(str(user._id))
    activity_video.activity_id = ObjectId(str(aid))
    activity_video.cover = video.cover
    activity_video.duration = video.duration
    activity_video.game = video.game

    avid = activity_video.create_model()
    video.update_model({'$set': {'activity_ids': [avid]}})

    # 任务检查
    if user:
        UserTask.check_user_tasks(str(user._id), JOIN_COLLECT, 1,
                                  str(video.game), str(aid))

    return ActivityVideo.get_one(avid, check_online=False).format()
Exemple #11
0
def play_video(vid):
    """播放视频 (GET)

    :uri: /videos/<string:vid>/play
    :returns: redirect(real_url)
    """
    ut = request.values.get("ut", None)
    uid = User.uid_from_token(ut)

    start = int(time.time() * 1000)
    video = Video.get_one(vid)
    if not video:
        result = {
            'status': error.VideoNotExist.errno,
            'errmsg': error.VideoNotExist.errmsg,
            'data': {},
            'time': int(time.time() * 1000) - start,
        }
        return jsonify(result)
    video.update_model({'$inc': {'vv': 1}})
    # 如果是栏目视频,给对应频道增加播放量
    channel = ShowChannel.get_one(video.channel)
    channel and channel.update_model({'$inc': {'play_count': 1}})

    # 观看视频任务检查
    if uid:
        UserTask.check_user_tasks(uid, PLAY_VIDEO, 1)

    # 更新活动播放量
    avideos = ActivityVideo.get_activity_video(vid=vid)
    for avideo in avideos:
        ts = time.time()
        aconfig = ActivityConfig.get_one(str(avideo['activity_id']),
                                         check_online=False)
        if aconfig and aconfig.status == const.ACTIVITY_BEGIN \
                and (aconfig.begin_at < ts and aconfig.end_at > ts):
            avideo = ActivityVideo.get_one(avideo['_id'], check_online=False)
            avideo.update_model({'$inc': {'vv': 1}})

    return redirect(video.real_url())
Exemple #12
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 #13
0
def sub_game():
    """订阅游戏 (GET|POST&LOGIN)

    :uri: /user/opt/subscribe-game
    :param game_id: 游戏id(批量订阅游戏id以逗号隔开)
    :returns: {}
    """
    user = request.authed_user
    gids = request.values.get('game_id', None)
    if not gids:
        return error.GameNotExist
    gids = [gid.strip() for gid in gids.split(',')]
    games = Game.get_list(gids, check_online=False)
    if not games:
        return error.GameNotExist

    key = 'lock:subgame:%s' % (str(user._id))
    with util.Lockit(Redis, key) as locked:
        if locked:
            return error.SubGameFailed

        sub_num = 0
        for game in games:
            usg = UserSubGame.get_by_ship(str(user._id), str(game._id))
            if not usg:
                usg = UserSubGame.init()
                usg.source = ObjectId(str(user._id))
                usg.target = ObjectId(str(game._id))
                usg.create_model()
                sub_num += 1

        # 订阅游戏任务检查
        if user:
            UserTask.check_user_tasks(str(user._id), SUB_GAME, sub_num)

    return {}
Exemple #14
0
def upload_small_file():
    """文件上传(POST&LOGIN)

    :uri: /upload/upload-small-file
    :param type: 类型(videos.cover, videos.url, users.logo, users.photo, teams.logo, user_certify.ID_photo)
    :param target_id: 对象id
    :param file: 上传文件
    :returns: {'target_id': string, 'type': string, 'url': string}
    """
    _type = request.form.get("type", None)
    target_id = request.form.get("target_id", None)
    if _type not in {
            "videos.cover", "videos.url", "users.logo", "users.photo",
            "teams.logo", "user_certify.ID_photo", "user_certify.ID_photo_2"
    }:
        return error.InvalidArguments

    try:
        ObjectId(target_id)
    except:
        return error.InvalidArguments

    user = request.authed_user
    if _type.startswith("users.") and str(user._id) != target_id:
        return error.AuthFailed

    if _type.startswith("videos."):
        video = Video.get_one(str(target_id), check_online=False)
        if str(user._id) != str(video.author):
            return error.AuthFailed

    if _type.startswith("teams."):
        team = Team.get_one(str(target_id), check_online=False)
        if not user and not team:
            return error.AuthFailed

    if _type.startswith("user_certify."):
        user_certify = UserCertify.get_one(str(target_id), check_online=False)
        if not user and not user_certify:
            return error.AuthFailed

    # 上传文件
    _path = 'videos' if _type == 'videos.url' else 'images'
    if _type == 'user_certify.ID_photo' or _type == 'user_certify.ID_photo_2':
        _path = 'user_certify'

    _file = Media(app.config.get("STATIC_BASE"), _path, request.files['file'])
    try:
        url = _file.upload_file()
    except:
        return error.UploadFailed
    # 更新对象
    obj, attr = _type.split(".")
    data = {attr: url}
    if obj == 'videos':
        if attr == 'url':
            data['status'] = const.ONLINE
        model = Video.get_one(target_id, check_online=False)
    elif obj == 'users':
        model = User.get_one(target_id, check_online=False)

    elif obj == 'teams':
        model = Team.get_one(target_id, check_online=False)

    elif obj == 'user_certify':
        model = UserCertify.get_one(target_id, check_online=False)

    model.update_model({"$set": data})

    # 设置头像任务检查
    if obj == 'users' and user:
        UserTask.check_user_tasks(str(user._id), SET_HEADER, 1)

    abs_url = urljoin(app.config.get('STATIC_URL'), url)
    return {'target_id': target_id, 'type': _type, 'url': abs_url}
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 ''
Exemple #16
0
 def after_model_delete(self, model):
     super(TaskAdmin, self).after_model_delete(model)
     UserTask.delete().where(UserTask.task_id==model.task_id).execute()
     Redis.delete(TASK_KEY)
Exemple #17
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}