Example #1
0
def delete_comment():
    """删除评论 (GET|POST&LOGIN)

    :uri: /user/opt/delete-comment
    :param comment_id: 评论id
    :returns: {}
    """
    user = request.authed_user
    params = request.values
    cid = params.get('comment_id', None)
    comment = Comment.get_one(cid)
    if not comment:
        return error.CommentNotExist
    if str(comment.author) != str(user._id):
        return error.AuthFailed
    comment.delete_model()
    # 更新活动评论数
    avideos = ActivityVideo.get_activity_video(vid=str(comment.video))
    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 {}
Example #2
0
def activity_create_comment():
    """创建评论 (GET|POST&LOGIN)

    :uri: /activity/user/submit-comment
    :param activity_id: 被评论活动id
    :param content: 评论内容
    :returns: {'comment': object}
    """
    user = request.authed_user
    params = request.values
    aid = params.get('activity_id', None)
    content = params.get('content', None)
    if not aid or not content:
        return error.InvalidArguments

    if not ActivityConfig.get_one(aid, check_online=False):
        return error.ActivityNotExist

    # 敏感词检查
    if Spam.filter_words(content, 'comment'):
        return error.InvalidContent

    comment = ActivityComment.init()
    comment.activity = ObjectId(aid)
    comment.author = ObjectId(str(user._id))
    comment.content = content
    cid = comment.create_model()
    return ActivityComment.get_one(str(cid)).format()
Example #3
0
def activity_top_videos(aid):
    """获取结束时获奖视频

    :uri: activity/<string:aid>/top/videos
    :param page: 页码
    :param nbr: 每页数量
    :returns: {'activity_videos': list, 'end_page': bool, 'activity_config': Object }
    """

    params = request.values
    page = int(params.get('page', 1))
    pagesize = int(params.get('nbr', 10))

    activity_videos = list()
    activity_config = ActivityConfig.get_one(str(aid), check_online=False)
    if not activity_config:
        return error.ActivityNotExist

    avids = ActivityVideo.top_video_end(aid, page, pagesize, activity_config)
    activity_videos.extend([a.format() for a in ActivityVideo.get_list(avids)])
    return {
        'activity_videos': activity_videos,
        'end_page': len(avids) != pagesize,
        'activity_config': activity_config.format()
    }
Example #4
0
def activity_popular_videos(aid):
    """获取人气视频

    :uri: activity/<string:aid>/popular/videos
    :param page: 页码
    :param nbr: 每页数量
    :param device: 终端ID
    :returns: {'activity_videos': list, 'end_page': bool, 'activity_config': Object }
    """

    params = request.values
    page = int(params.get('page', 1))
    pagesize = int(params.get('nbr', 10))

    activity_videos = list()
    activity_config = ActivityConfig.get_one(str(aid), check_online=False)
    if not activity_config:
        return error.ActivityNotExist
    sort = activity_config.sort

    avids = ActivityVideo.popular_video_ids(aid, sort, page, pagesize)
    activity_videos.extend([v.format() for v in ActivityVideo.get_list(avids)])
    return {
        'activity_videos': activity_videos,
        'end_page': len(avids) != pagesize,
        'activity_config': activity_config.format()
    }
Example #5
0
def live_duration_user():
    """
    主播招募活动按最高直播时长排序的用户
    :uri: /activity/live/recruit/duration
    :param: activity_id 活动ID
    :param: maxs
    :return: {'latest_users': <ActivityLiveMaster> list}
    """
    params = request.values
    aid = params.get('activity_id', None)
    maxs = params.get('maxs', None)
    page = int(params.get('page', 1))
    pagesize = int(params.get('nbr', 10))

    if aid is None:
        return error.InvalidArguments

    activity_config = ActivityConfig.get_one(aid, check_online=True)
    if not activity_config:
        return error.ActivityNotExist

    uids = ActivityLiveMaster.duration_uids(aid, activity_config.begin_at,
                                            activity_config.end_at, page,
                                            pagesize, maxs)
    users = [u.format() for u in ActivityLiveMaster.get_list(uids)]

    return {'duration_users': users, 'end_page': len(uids) != pagesize}
Example #6
0
def activity_top(aid):
    """获取结束时获奖视频(手动)

    :uri: activity/<string:aid>/manual/top
    :param page:
    :param nbr:
    :return: {'activity_videos': list, 'end_page': bool}
    """

    params = request.values
    page = int(params.get('page', 1))
    pagesize = int(params.get('nbr', 10))

    activity_videos = list()
    activity_config = ActivityConfig.get_one(str(aid), check_online=False)
    if not activity_config:
        return error.ActivityNotExist

    avids = ActivityVideo.get_manual_top(aid, page, pagesize)
    activity_videos.extend([
        a.format() for a in ActivityVideo.get_list(avids, check_online=False)
    ])
    return {
        'activity_videos': activity_videos,
        'end_page': len(avids) != pagesize
    }
Example #7
0
def activity_video_config(vid):
    """获取app内视频的活动相关配置

    :uri: activity/video/config/<string:vid>
    :return:{"activity": Object, "is_voted": bool, "is_join": bool, "activity_status": bool}
    """
    user = request.authed_user
    params = request.values
    device = params.get('device', None)
    uid = user and str(user._id)

    activity = dict()
    is_join = False
    activity_status = False

    activity_video = ActivityVideo.get_activity_video_by_vid(vid)
    if activity_video:
        is_join = True
        aid = activity_video["activity_id"]
        activity_config = ActivityConfig.get_one(aid, check_online=False)
        if not activity_config.online:
            activity_status = False
        else:
            activity_status = True
        activity = activity_config.format()

    is_voted = True if VoteVideo.get_vote(uid, device, vid) else False
    return {
        "activity": activity,
        "is_voted": is_voted,
        "is_join": is_join,
        "activity_status": activity_status
    }
Example #8
0
    def get_export_csv(self):
        if not self.export_columns:
            self.export_columns = [
                column_name for column_name, _ in self._list_columns
            ]

        io = StringIO()
        rows = csv.DictWriter(io, self.export_columns)

        data = self._get_data_for_export()

        rows.writeheader()
        for item in data:
            row = dict()
            for column in self.export_columns:
                if column == 'author':
                    obj = User.get_one(item[column], check_online=False)
                    item[column] = obj.nickname
                elif column == 'activity':
                    obj = ActivityConfig.get_one(item[column],
                                                 check_online=False)
                    item[column] = obj.name
                elif column == 'create_at':
                    item[column] = datetime.fromtimestamp(
                        item[column]).strftime('%Y-%m-%d %H:%M:%S')
                elif column not in item:
                    item[column] = None

                row.update({column: unicode(item[column]).encode("utf8")})

            # print row
            rows.writerow(row)

        io.seek(0)
        return io.getvalue()
Example #9
0
def unlike_video():
    """取消赞视频 (GET|POST&LOGIN)

    :uri: /user/opt/like-video
    :param video_id: 被赞视频id
    :returns: {}
    """
    user = request.authed_user
    vid = request.values.get('video_id', None)
    video = Video.get_one(vid)
    if not video:
        return error.VideoNotExist

    key = 'lock:unlike_video:%s:%s' % (str(user._id), vid)
    with util.Lockit(Redis, key) as locked:
        if locked:
            return error.LikeVideoFailed('取消赞失败')
        ulv = UserLikeVideo.get_by_ship(str(user._id), vid)
        ulv.delete_model() if ulv else None
        # 更新活动点赞数
        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': {'like_count': -1}})
    return {}
Example #10
0
def format_activity(view, context, model, name):
    _value = model.get(name, None)
    obj = ActivityConfig.get_one(str(_value), check_online=False)
    if obj:
        _value = '%s (%s)' % (obj.name, _value)
        html = u'<a href="/admin/activity_configview/?flt1_0=%s">%s</a>' % (
            str(obj._id), _value)
        _value = widgets.HTMLString(html)
    else:
        _value = u'活动不存在'
    return _value
Example #11
0
def activity_config(aid):
    """获取活动配置接口(GET)

    :uri: /activity/<string:aid>/config
    :return: {"activity_games": list, "status": string, "buttons": list, "activity_config": Object}
    """

    activity_games = GameActivity.get_by_aid(aid)
    activity_games = [game.format() for game in activity_games]

    status = ActivityConfig.activity_status(aid)

    activity_config = ActivityConfig.get_one(aid)

    if activity_config:
        activity_config = activity_config.format()

    return {
        "activity_games": activity_games,
        "status": status,
        "buttons": [],
        'activity_config': activity_config
    }
Example #12
0
def live_hot_user(aid):
    """获取热门主播

    :uri: activity/live/hot_user/<string:aid>
    :param maxs: 分页标示, 0最新
    :param nbr: 每页数量
    :returns: {'hot_users': list, 'end_page': bool,  'maxs': long}
    """

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

    activity_config = ActivityConfig.get_one(aid, check_online=True)
    if not activity_config:
        return error.ActivityNotExist

    hot_users = list()
    while len(hot_users) < pagesize:
        user_scores = Live_Activity.get_live_hot_user(aid, pagesize,
                                                      activity_config.begin_at,
                                                      activity_config.end_at,
                                                      maxs)
        for us in user_scores:
            user = User.get_one(str(us[0]), check_online=True)
            if user:
                total_gold = UserGiftLog.get_user_total_gold(
                    str(us[0]), activity_config.begin_at,
                    activity_config.end_at)
                hot_users.append({
                    'user': user.format(),
                    'gold': total_gold,
                    'top': us[2]
                })
        # 如果按照maxs分页, 不足pagesize个记录则继续查询
        obj = user_scores[-1] if user_scores else None
        maxs = obj[1] if obj else time.time() * 10000000000
        if len(user_scores) < pagesize:
            break

    return {
        'hot_users': hot_users,
        'end_page': len(hot_users) != pagesize,
        'maxs': maxs
    }
Example #13
0
def join_in():
    """
    主播招募活动报名
    :uri: /activity/live/recruit/join
    :param: activity_id 活动ID
    :param: name 姓名
    :param: gender 性别
    :param: phone 联系电话
    :param: identity 身份证号码
    :param: content 个人宣言
    :return: {'ret' : bool, 'user': ActivityLiveMaster}
    """
    user = request.authed_user
    params = request.values
    aid = params.get('activity_id', None)
    name = params.get('name', None)
    gender = int(params.get('gender', None))
    phone = params.get('phone', None)
    identity = params.get('identity', None)
    content = params.get('content', None)

    if any(
            map(lambda x: x is None,
                [aid, name, gender, phone, identity, content])):
        return error.InvalidArguments

    activity_config = ActivityConfig.get_one(aid, check_online=True)
    if not activity_config:
        return error.ActivityNotExist

    uid = str(user._id)
    if ActivityLiveMaster.check_activity_user(aid, uid):
        return error.UserExists

    alm = ActivityLiveMaster.init()
    alm.activity_id = aid
    alm.user_id = uid
    alm.name = name
    alm.gender = gender
    alm.phone = phone
    alm.identity = identity
    alm.content = content
    alm.duration = 0
    alm.create_model()

    return {'ret': True, 'user': alm.format()}
Example #14
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()
Example #15
0
def live_user_info(aid):
    """获取主播信息

    :uri: activity/live/<string:aid>/user/info
    :returns: {'user': Object, 'top': int, 'gold': int}
    """

    user = request.authed_user
    activity_config = ActivityConfig.get_one(aid, check_online=True)
    if not activity_config:
        return error.ActivityNotExist
    top = Live_Activity.get_live_user_top(aid, str(user._id),
                                          activity_config.begin_at,
                                          activity_config.end_at)
    total_gold = UserGiftLog.get_user_total_gold(str(user._id),
                                                 activity_config.begin_at,
                                                 activity_config.end_at)
    return {'user': user.format(), 'top': top, 'gold': total_gold}
Example #16
0
def live_new_user(aid):
    """获取新秀主播

    :uri: activity/live/new_user/<string:aid>
    :param maxs: 分页标示, 0最新
    :param nbr: 每页数量
    :returns: {'new_users': list, 'end_page': bool,  'maxs': long}
    """
    params = request.values
    maxs = params.get('maxs', 0)
    maxs = time.time() if maxs is not None and int(
        float(maxs)) == 0 else maxs and float(maxs)
    pagesize = int(params.get('nbr', 10))

    activity_config = ActivityConfig.get_one(aid, check_online=True)
    if not activity_config:
        return error.ActivityNotExist

    users = list()
    uids = list()
    while len(users) < pagesize:
        uids = Live_Activity.get_live_new_user(aid, pagesize, maxs)
        for u in User.get_list(uids):
            top = Live_Activity.get_live_user_top(aid, str(u._id),
                                                  activity_config.begin_at,
                                                  activity_config.end_at)
            total_gold = UserGiftLog.get_user_total_gold(
                u._id, activity_config.begin_at, activity_config.end_at)
            users.append({'user': u.format(), 'gold': total_gold, 'top': top})
        # 如果按照maxs分页, 不足pagesize个记录则继续查询
        if maxs is not None:
            obj = User.get_one(uids[-1]) if uids else None
            maxs = obj.create_at if obj else 1000
            if len(uids) < pagesize:
                break
        else:
            break
    return {
        'new_users': users,
        'end_page': len(uids) != pagesize,
        'maxs': maxs
    }
Example #17
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())
Example #18
0
def like_video():
    """赞视频 (GET|POST&LOGIN)

    :uri: /user/opt/like-video
    :param video_id: 被赞视频id
    :returns: {}
    """
    user = request.authed_user
    vid = request.values.get('video_id', None)
    video = Video.get_one(vid)
    if not video:
        return error.VideoNotExist

    ulv = UserLikeVideo.get_by_ship(str(user._id), vid)
    if not ulv:
        key = 'lock:like_video:%s:%s' % (str(user._id), vid)
        with util.Lockit(Redis, key) as locked:
            if locked:
                return error.LikeVideoFailed
            ulv = UserLikeVideo.init()
            ulv.source = ObjectId(str(user._id))
            ulv.target = ObjectId(vid)
            _id = ulv.create_model()
            if _id:
                # 发送点赞消息
                Message.send_video_msg(str(user._id), str(vid), 'like')
                # 更新活动点赞数
                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': {'like_count': 1}})

    return {}
Example #19
0
def latest_video(aid):
    """获取最新参赛视频

    :uri: activity/<string:aid>/video/current
    :param maxs: 最后时间, 0代表当前时间
    :param nbr: 每页数量
    :param device: 终端ID
    :returns: {'activity_videos': list, 'end_page': bool, 'activity_config': Object,
               '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)
    pagesize = int(params.get('nbr', 10))

    activity_config = ActivityConfig.get_one(aid, check_online=False)
    if not activity_config:
        return error.ActivityNotExist

    avideos = list()
    avids = list()
    while len(avideos) < pagesize:
        avids = ActivityVideo.latest_video_ids(aid, pagesize, maxs)
        avideos.extend([v.format() for v in ActivityVideo.get_list(avids)])
        # 如果按照maxs分页, 不足pagesize个记录则继续查询
        if maxs is not None:
            obj = ActivityVideo.get_one(avids[-1]) if avids else None
            maxs = obj.create_at if obj else 1000
            if len(avids) < pagesize:
                break
        else:
            break
    return {
        'activity_videos': avideos,
        'end_page': len(avids) != pagesize,
        'activity_config': activity_config.format(),
        'maxs': maxs
    }
Example #20
0
def user_videos(aid):
    """获取我的参赛视频(GET&LOGIN)

    :uri: activity/<string:aid>/videos
    :param type: 活动结束时参数(type=end)
    :param device: 终端ID
    :return: {'activity_videos': list, 'activity_config': Object}
    """
    user = request.authed_user
    type = request.values.get('type', None)

    activity_config = ActivityConfig.get_one(str(aid), check_online=False)
    if not activity_config:
        return error.ActivityNotExist
    sort = activity_config.sort

    activity_videos = ActivityVideo.user_compete_video_ids(aid, user._id)
    if not type:
        top_compete_videos = ActivityVideo.top_video_ids(aid, sort)
    videos = list()

    for activity_video in activity_videos:
        avid = str(activity_video['_id'])
        activity_video = ActivityVideo.get_one(avid)
        activity_video = activity_video.format()
        if type:
            videos.append(activity_video)
            continue

        if avid in top_compete_videos:
            top = top_compete_videos.index(avid)
            activity_video['top'] = top + 1
            videos.append(activity_video)
        else:
            continue
    return {
        'activity_videos': videos,
        'activity_config': activity_config.format()
    }
Example #21
0
def get_activity_video(vid):
    """获取参赛视频信息(GET&LOGIN)

    :uri: activity/video/<string:vid>
    :param device: 终端ID
    :return: {'activity_video': Object, 'activity_config': Object}
    """

    activity_video = ActivityVideo.get_activity_video_by_vid(vid)
    if not activity_video:
        return error.ActivityVideoNotExist
    activity_config = ActivityConfig.get_one(activity_video['activity_id'])
    top_compete_videos = ActivityVideo.top_video_ids(
        activity_video['activity_id'], activity_config.sort)

    top = top_compete_videos.index(str(activity_video['_id']))
    activity_video = activity_video.format()
    activity_video['top'] = top + 1

    return {
        'activity_video': activity_video,
        'activity_config': activity_config.format()
    }
Example #22
0
def check_user():
    """
    主播招募活动用户报名信息检查
    :uri: /activity/live/recruit/check_user
    :param: activity_id 活动ID
    :return: {'ret' : bool, 'user': ActivityLiveMaster}
    """
    user = request.authed_user
    params = request.values
    aid = params.get('activity_id', None)

    if aid is None:
        return error.InvalidArguments

    activity_config = ActivityConfig.get_one(aid, check_online=True)
    if not activity_config:
        return error.ActivityNotExist

    uid = str(user._id)
    alm_id = ActivityLiveMaster.check_activity_user(aid, uid)
    if not alm_id:
        return {'ret': False, 'user': None}
    author = ActivityLiveMaster.get_one(alm_id)
    return {'ret': True, 'user': author.format()}
Example #23
0
def search(aid):
    """搜索 (GET|POST)

    :uri: /activity/live/search/<string:aid>
    :param type: 搜索类型{'user':用户}
    :param keyword: 关键字
    :returns: {'user':list}
    """
    params = request.values
    stype = params.get('type', 'user')
    keyword = params.get('keyword', '')
    keyword = keyword.strip()

    if not stype or not keyword:
        return error.InvalidArguments

    users = list()

    activity_config = ActivityConfig.get_one(aid, check_online=True)
    if not activity_config:
        return error.ActivityNotExist

    if stype in ['user']:
        uids = User.search(keyword)
        _uids = Live_Activity.get_activity_live_by_authors(aid, uids)
        for _uid in _uids:
            user = User.get_one(_uid).format()
            top = Live_Activity.get_live_user_top(aid, _uid,
                                                  activity_config.begin_at,
                                                  activity_config.end_at)
            gold = UserGiftLog.get_user_total_gold(_uid,
                                                   activity_config.begin_at,
                                                   activity_config.end_at)
            users.append({'user': user, 'top': top, 'gold': gold})

    return {'users': users}
Example #24
0
def compete_videos(aid):
    """获取可参赛视频(GET&LOGIN)

    :uri: /activity/<string:aid>/compete_videos
    :param page: 页数
    :param nbr: 每页数量
    :return: {'videos': list, 'max_video': int, 'end_page': bool}
    """
    params = request.values
    user = request.authed_user
    page = int(params.get('page', 1))
    pagesize = int(params.get('nbr', 10))

    activity_config = ActivityConfig.get_one(str(aid), check_online=False)
    if not activity_config:
        return error.ActivityNotExist

    activity_videos = ActivityVideo.user_compete_video_ids(aid, str(user._id))
    avids = [a['video_id'] for a in activity_videos]

    videos = list()
    gids = GameActivity.game_activity_ids(aid)
    gids = [ObjectId(_gid) for _gid in gids]

    vids = Video.activity_video_ids(str(user._id), pagesize, page, gids,
                                    activity_config)
    vids = [vid for vid in vids]
    videos.extend([v.format() for v in Video.get_list(vids)])
    # 允许参赛最大视频数
    max_video = activity_config.max_video - len(avids)

    return {
        'videos': videos,
        'end_page': len(vids) != pagesize,
        'max_video': max_video
    }
Example #25
0
def traffic_send():
    """发放流量 (GET|POST&LOGIN)

    :uri: /traffic/send
    :param traffic_type: (first_login, video_share)
    :returns: {'message': str}
    """
    user = request.authed_user
    traffic_type = request.values.get('traffic_type', None)
    device = request.values.get('device', None)

    status = ActivityConfig.activity_status()
    if const.ACTIVITY_PAUSE == status:
        print_log('app_traffic',
                  '[%s][%s]: activity is pause' % (traffic_type, user.phone))
        return error.TrafficSendFail(u'小伙伴们太热情了,稍后再来吧!')
    elif const.ACTIVITY_END == status:
        print_log('app_traffic',
                  '[%s][%s]: activity is end' % (traffic_type, user.phone))
        return error.UserTrafficZero(u'亲,我们的奖品已经送完啦,下次要早点来哦!')

    utl = UserTrafficLog.get_traffic_by_type(str(user._id), traffic_type)
    if not utl and traffic_type == 'video_share':
        print_log('app_traffic',
                  '[video_share][%s]: UserTrafficExists' % user.phone)
        return error.UserTrafficExists(u'亲,你还没有分享自己的作品哦,赶快去分享你的游戏视频,再来领取吧!')
    elif utl and utl.status in [
            const.TRAFFIC_SUCCESS, const.TRAFFIC_RECEIVED_SUCCESS,
            const.TRAFFIC_RECEIVED_PROCESS
    ]:
        print_log('app_traffic',
                  '[%s][%s]: TrafficExists' % (traffic_type, user.phone))
        return error.TrafficExists

    utl_device = UserTrafficLog.get_traffic_by_device(device, traffic_type)
    if utl_device:
        print_log(
            'app_traffic',
            '[%s][%s][%s]: device repeat' % (traffic_type, user.phone, device))
        return error.UserTrafficInvalid(u'亲,同一部终端只能领取一次流量哦!')

    utl_count = UserTrafficLog.traffic_count_by_type(traffic_type)
    if utl_count and utl_count > const.TRAFFIC_CATEGORY_NUM.get(
            traffic_type, None):
        print_log('app_traffic',
                  '[%s][%s]: UserTrafficZero' % (traffic_type, user.phone))
        return error.UserTrafficZero(u'亲,我们的奖品已经送完啦,下次要早点来哦!')

    key = 'lock:traffic:%s:%s' % (user.phone, utl.order_id)
    with util.Lockit(Redis, key) as locked:
        if locked:
            return error.TrafficSendFail
        # 移动接口返回
        if Traffic.send_traffic(utl.order_id, user.phone):
            utl.update_model(
                {'$set': {
                    'status': const.TRAFFIC_SUCCESS,
                    'device': device
                }})
        else:
            utl.update_model({'$set': {'status': const.TRAFFIC_FAIL}})
            return error.TrafficSendFail(u'小伙伴们太热情了,稍后再来吧!')
    return {"message": "你已经成功分享视频, 恭喜你获得免费流量150M, 礼物将以光速飞到你的碗里去哦, 请注意查收!"}
Example #26
0
def send_gift():
    """赠送礼物 (GET|POST&LOGIN)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    # 营销数据入库经分  打赏活动
    from wanx.models.activity import ActivityConfig, ActivityVideo
    from wanx.platforms.migu import Marketing
    activity_config = None
    if gift_from == const.FROM_RECORD:
        activity_video = ActivityVideo.get_activity_video_by_vid(from_id)
        if activity_video:
            activity_config = ActivityConfig.get_one(
                activity_video['activity_id'])
    else:
        aids = ActivityConfig.get_by_type(const.FROM_LIVE)
        for a in ActivityConfig.get_list(aids):
            activity_config = a
            break
    if activity_config:
        data_dict = dict(cmd="deliver_gift",
                         opt="{0}/{1}".format(gift.gold_price, to_user_id),
                         deviceid=request.values.get('device', ''),
                         mobile=user.phone,
                         source=request.values.get('source', 'activity'),
                         activityid=str(activity_config['_id']),
                         activityname=activity_config['name'])
        Marketing.jf_report(data_dict)
    # 1118 task1
    # Marketing.trigger_report(user.partner_migu['id'], user.phone, 'send_gift')
    return {'ret': ret}
Example #27
0
 def edit_form(self, obj=None):
     form = super(GameActivityAdmin, self).edit_form(obj)
     form.game.choices = Game.online_games()
     form.activity.choices = ActivityConfig.activity()
     return form
Example #28
0
 def edit_form(self, obj=None):
     form = super(ActivityCommentAdmin, self).edit_form(obj)
     form.activity.choices = ActivityConfig.activity()
     return form
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 ''
Example #30
0
def activity_vote():
    """活动投票

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

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

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

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

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

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

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

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

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

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

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

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

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

    return {'vote_count': vote_count}