def format(self): from wanx.models.user import User from wanx.models.comment import Comment from wanx.models.video import Video operator = User.get_one(str(self.operator), check_online=False) if self.ctype == 'comment': obj = Comment.get_one(str(self.obj_id), check_online=False) obj = obj and obj.format() elif self.ctype == 'video': obj = Video.get_one(str(self.obj_id), check_online=False) obj = obj and obj.format() elif self.ctype == 'reply': obj = Reply.get_one(str(self.obj_id), check_online=False) comment_id = obj and str(obj.comment) obj = obj and obj.format() if obj: comment = Comment.get_one(comment_id, check_online=False) obj['video_id'] = comment.video and str(comment.video) else: obj = None data = { 'msg_id': str(self._id), 'ctype': self.ctype, 'obj': obj, 'action': self.action, 'operator': operator and operator.format(), 'create_at': self.create_at } return data
def get_share_video(vid): """获取视频分享数据(GET) :uri: /share/video/<string:vid> :returns: {'video': object, 'hot_videos': list, 'comments': comments, 'game_url': url, 'app_url': url} """ video = Video.get_one(vid) if not video: return error.VideoNotExist cids = Comment.video_comment_ids(vid, 1, 10) comments = [c.format() for c in Comment.get_list(cids)] vids = Video.game_hotvideo_ids(str(video.game), 1, 10) videos = [v.format() for v in Video.get_list(vids)] video = video.format() _from = request.values.get('ywfrom', None) mgyxdt_url = 'http://g.10086.cn/s/clientd/?t=GH_JFDX' game_url = video['game'][ 'url'] if _from != 'miguyouxidating' else mgyxdt_url app_url = "http://video.cmgame.com/userfiles/wapapp/mgyw.apk" app_url = app_url if _from != 'miguyouxidating' else '#' return dict(video=video, hot_videos=videos, comments=comments, game_url=game_url, app_url=app_url)
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 {}
def latest_video(): """获取最新视频 (GET) :uri: /videos/current/ :param maxs: 最后时间, 0代表当前时间, 无此参数按page来分页 :param page: 页码 :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.latest_video_ids(page, pagesize, maxs) ex_fields = ['is_favored', '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}
def migu_create_comment(vid): """咪咕平台创建评论 (GET|POST) :uri: /migu/videos/<string:vid>/comments/submit :param user_id: 咪咕用户id :param content: 评论内容 :returns: {} """ params = request.values openid = params.get('user_id', '') content = params.get('content', '') if len(openid) < 1 or len(content) < 1: return error.InvalidArguments video = Video.get_one(vid) if not video: return error.VideoNotExist user = User.get_platform_user('migu', openid) if not user: info = dict(name='$mg$%s%s' % (openid[-4:], random.randint(1000, 9999))) user = User.create_platform_user('migu', openid, data=info) comment = Comment.init() comment.author = ObjectId(str(user._id)) comment.content = content comment.video = ObjectId(vid) comment.create_model() return {}
def update_video(vid): """修改视频--文件上传走第三方,供第三方进行回调 (POST) :uri: /videos/<string:vid>/update-video :param cover: 背景相对路径 :param url: 视频相对路径 :param upload_sig: 验证串 :return: {'url': string} """ cover = request.values.get('cover') url = request.values.get('url') valid_sig = request.values.get('upload_sig') md5 = hashlib.md5(vid) secret = '&%s' % ('29eb78ff3c8f20fe') md5.update(secret) if valid_sig != md5.hexdigest() or not cover or not url: return error.InvalidArguments video = Video.get_one(vid, check_online=False) if not video: return error.VideoNotExist data = {'cover': cover, 'url': url, 'status': const.ONLINE} video = video.update_model({"$set": data}) return {'video': video.format()}
def upload_large_file(): """大文件上传(POST&LOGIN) :uri: /upload/upload-large-file :param type: 类型(videos.cover, videos.url, users.log, users.photo) :param target_id: 对象id :param size: 文件大小 :param ext: 文件后缀 :returns: {'file_id': string, 'url': string} """ _type = request.form.get("type", None) target_id = request.form.get("target_id", None) size = request.form.get("size", type=int) ext = request.form.get("ext") if _type not in { "videos.cover", "videos.url", "users.logo", "users.photo" }: return error.InvalidArguments if not size or size <= 0: 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 file_id = os.urandom(12).encode("hex") # 上传文件 tmp_dir = os.path.join(app.config.get("STATIC_BASE"), "temp") file_path = os.path.join(tmp_dir, "l-%s.%s" % (file_id, ext)) meta = dict(request.form.to_dict()) meta['size'] = int(meta['size']) meta["file_id"] = file_id meta['path'] = file_path meta['user_id'] = str(user._id) meta['ranges'] = list() try: _set_upload_file_meta(file_id, meta) except: return error.RedisFailed with open(file_path, "wb") as f: f.truncate( size) # Pre-alloc file to get better performance on some fs. return { "file_id": file_id, "url": url_for("upload_put_file", file_id=file_id) }
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 ''
def format_video(view, context, model, name): model = model if isinstance(model, dict) else model_to_dict(model) _value = model.get(name, None) obj = Video.get_one(str(_value), check_online=False) if obj: _value = '%s (%s)' % (obj.title, _value) html = u'<a href="/admin/videosview/?flt1_0=%s">%s</a>' % (str( obj._id), _value) _value = widgets.HTMLString(html) else: _value = u'视频不存在' return _value
def get_video(vid): """获取视频详细信息 (GET) :uri: /videos/<string:vid> :uri migu: /migu/videos/<string:vid> :returns: object """ video = Video.get_one(vid, check_online=False) if not video: return error.VideoNotExist return video.format()
def send_gift_msg(cls, operator_id, obj_id, action='gift'): owner_id = str(Video.get_one(obj_id).author) obj = cls.init() obj.owner = ObjectId(owner_id) obj.ctype = 'video' obj.obj_id = ObjectId(obj_id) obj.action = action obj.operator = ObjectId(operator_id) msg_id = obj.create_model() # 发送消息到队列 channel = User.USER_ASYNC_MSG % ({'uid': owner_id}) msg = dict(obj_type='Message', obj_id=str(msg_id), count=1) MRedis.publish(channel, json.dumps(msg))
def delete_video(vid): """删除视频 (POST&LOGIN) :uri: /videos/<string:vid>/delete :returns: {} """ user = request.authed_user video = Video.get_one(vid, check_online=False) if not video: return error.VideoNotExist if str(user._id) != str(video.author): return error.AuthFailed video.delete_model() return {}
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}
def game_videos(gid): """获取游戏的视频 (GET) :uri: /games/<string:gid>/videos :param maxs: 最后时间, 0代表当前时间, 无此参数按page来分页 :param page: 页码(数据可能有重复, 建议按照maxs分页) :param nbr: 每页数量 :param orderby: 排序方式 ('create_at': 创建时间, 'vv':播放次数) :returns: {'videos': list, 'end_page': bool, 'maxs': timestamp} """ params = request.values orderby = params.get('orderby', 'create_at') maxs = params.get('maxs', None) if orderby == 'vv': maxs = 10000000 if maxs is not None and int( maxs) == 0 else maxs and int(maxs) else: 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: if orderby == 'vv': vids = Video.game_hotvideo_ids(gid, page, pagesize, maxs) else: vids = Video.game_video_ids(gid, 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 if orderby == 'vv': maxs = obj.vv if obj else -1 else: 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}
def create_model(self): _id = super(Comment, self).create_model() if _id: # 更新视频评论数 from wanx.models.video import Video video = Video.get_one(str(self.video), check_online=False) video.update_model({'$inc': {'comment_count': 1}}) key = self.VIDEO_COMMENT_IDS % ({'vid': str(self.video)}) # 列表为空时key对应的value是一个string try: if Redis.exists(key): Redis.zadd(key, self.create_at, str(_id)) except exceptions.ResponseError: Redis.delete(key) return _id
def delete_model(self): ret = super(Comment, self).delete_model() if ret: # 更新视频评论数 from wanx.models.video import Video video = Video.get_one(str(self.video), check_online=False) video.update_model({'$inc': {'comment_count': -1}}) key = self.VIDEO_COMMENT_IDS % ({'vid': str(self.video)}) try: Redis.zrem(key, str(self._id)) except exceptions.ResponseError: Redis.delete(key) # 删除全部回复 Reply.delete_comment_replies(str(self._id)) return ret
def send_video_msg(cls, operator_id, obj_id, action='like'): video = Video.get_one(obj_id) # 如果视频没有作者,则不创建视频评论消息。 if not video or not video.author: return owner_id = str(video.author) obj = cls.init() obj.owner = ObjectId(owner_id) obj.ctype = 'video' obj.obj_id = ObjectId(obj_id) obj.action = action obj.operator = ObjectId(operator_id) msg_id = obj.create_model() # 发送消息到队列 channel = User.USER_ASYNC_MSG % ({'uid': owner_id}) msg = dict(obj_type='Message', obj_id=str(msg_id), count=1) MRedis.publish(channel, json.dumps(msg))
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()
def get_video_id(): """通过直播间id获取视频(GET) :uri: /videos/event_id :param: event_id: 直播间id :return: {'video': Object} """ uid = request.authed_user and str(request.authed_user._id) eid = request.values.get('event_id', None) if not eid: return error.LiveError("直播间id不存在") vid = Video.get_video_by_event_id(eid, uid=uid) video = Video.get_one(vid) if not video: return error.VideoNotExist return {'video': video.format()}
def category_videos(): """获取游戏下某个视频分类的所有视频(GET) :uri: /videos/category_videos :param: category_id: 分类ID :param: game_id: 游戏ID :param maxs: 最后时间, 0代表当前时间, 无此参数按page来分页 :param page: 页码(数据可能有重复, 建议按照maxs分页) :param nbr: 每页数量 :return: {'videos': <Video>list, 'end_page': bool, 'maxs': timestamp} """ cid = request.values.get('category_id', None) gid = request.values.get('game_id', None) maxs = request.values.get('maxs', None) maxs = time.time() if maxs is not None and int( float(maxs)) == 0 else maxs and float(maxs) page = int(request.values.get('page', 1)) pagesize = int(request.values.get('nbr', 10)) if not cid or not gid: return error.InvalidArguments videos = list() vids = list() while len(videos) < pagesize: vids = CategoryVideo.category_game_video_ids(cid, gid, 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}
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}
def unfavorite_video(): """取消收藏视频 (GET|POST&LOGIN) :uri: /user/opt/unfavorite-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:unfavor_video:%s:%s' % (str(user._id), vid) with util.Lockit(Redis, key) as locked: if locked: return error.FavorVideoFailed('取消收藏失败') ufv = UserFaverVideo.get_by_ship(str(user._id), vid) ufv.delete_model() if ufv else None return {}
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()
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 {}
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())
def tags_videos(cid): """获取标签下所有视频 (GET) :uri: /tags/<string:tid>/videos :uri migu: /migu/tags/<string:tid>/videos/ :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)) gids = CategoryGame.category_game_ids(cid) gids = [ObjectId(_gid) for _gid in gids] videos = list() vids = list() while len(videos) < pagesize: vids = Video.games_video_ids(gids, 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}
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()
def user_followings_videos(uid): """获取用户偶像的视频 (GET&LOGIN) :uri: /users/<string:uid>/followings/videos :param maxs: 最后时间, 0代表当前时间, 无此参数按page来分页 :param page: 页码(数据可能有重复, 建议按照maxs分页) :param nbr: 每页数量 :returns: {'videos': list, 'end_page': bool, 'maxs': timestamp} """ params = request.values user = request.authed_user 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) uids = FriendShip.following_ids(str(user._id)) uids = [ObjectId(_uid) for _uid in uids] videos = list() vids = list() while len(videos) < pagesize: vids = Video.users_video_ids(uids, gid, page, pagesize, maxs) ex_fields = ['is_favored', '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]) 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}
def favorite_video(): """收藏视频 (GET|POST&LOGIN) :uri: /user/opt/favorite-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 ufv = UserFaverVideo.get_by_ship(str(user._id), vid) if not ufv: key = 'lock:favor_video:%s:%s' % (str(user._id), vid) with util.Lockit(Redis, key) as locked: if locked: return error.FavorVideoFailed ufv = UserFaverVideo.init() ufv.source = ObjectId(str(user._id)) ufv.target = ObjectId(vid) ufv.create_model() return {}
def modify_video(vid): """更新视频信息接口 (POST&LOGIN) :uri: /videos/<string:vid>/modify-video :param title: 视频标题 :return: {'video': <Video>object} """ user = request.authed_user title = request.values.get('title') if not title: return error.InvalidArguments video = Video.get_one(vid, check_online=False) if not video or video.author != user._id: return error.VideoNotExist("视频不存在或视频不属于此用户") # 敏感词检查 if Spam.filter_words(title, 'video'): return error.InvalidContent data = {'title': title} video = video.update_model({"$set": data}) return {'video': video.format()}