def online_games(): """获取所有在线游戏列表 (GET) :uri: /games :return: {'games': list} """ games = Game.online_games() gids = [str(gid) for gid, _ in games] games = [g.format() for g in Game.get_list(gids)] return {'games': games}
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_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 }
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)}
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
def migu_home(): """获取首页信息 (GET) :uri: /migu/home/ :returns: {'popular': list, 'whats_new': list, 'hottest_of_today': list, 'recommend': list, 'tags': list} """ ret = dict() ret['popular'] = [] ret['whats_new'] = [] ret['hottest_of_today'] = [] ret['recommend'] = [] tags = [] cids = Category.all_category_ids() categories = Category.get_list(cids) for category in categories: gids = CategoryGame.category_game_ids(str(category._id)) games = [g.format() for g in Game.get_list(gids)] tags.append( dict(games=games, tag_id=str(category._id), name=category.name)) ret['tags'] = tags return ret
def edit_form(self, obj=None): form = super(CategoryGameAdmin, self).edit_form(obj) cids = Category.all_category_ids() categories = Category.get_list(cids) form.category.choices = [(c._id, c.name) for c in categories] form.game.choices = Game.online_games() return form
def apply(self, query, value): reload(sys) sys.setdefaultencoding('utf-8') value = apply(self.field_func, [value]) gids = Game.get_by_name(value) gidobj = [ObjectId(g) for g in gids] query.append({self.column: {'$in': gidobj}}) return query
def recommend_subscribe_games(): """获取推荐订阅游戏 (GET) :uri: /recommend/subscribe/games :returns: {'games': list} """ gids = GameRecommendSubscribe.recommend_sub_ids() games = [g.format() for g in Game.get_list(gids)] return {'games': games}
def hot_games(): """获取游戏页的所有热门游戏 (GET) :uri: /games/hot_games :returns: {'games': list} """ gids = HotRecommendGame.hot_game_ids() games = [ g.format(exclude_fields=['subscribed']) for g in Game.get_list(gids) ] return {'games': games}
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 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()
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
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
def category_games(cid): """获取分类下的所有游戏 (GET) :uri: /tags/<string:cid>/games :uri migu: /migu/tags/<string:cid>/games/ :returns: {'games': list} """ gids = CategoryGame.category_game_ids(cid) games = [ g.format(exclude_fields=['subscribed']) for g in Game.get_list(gids) ] return {'games': games}
def live_games(): """ 获取直播标签游戏列表 (GET) :uri: /user/opt/live_games :return: {'games': list} """ user = request.authed_user games = Game.live_games() # 设置直播标签的游戏 gids = [str(gid) for gid, _ in games] if user: pids = UserPopularGame.get_game_ids(user._id) if pids: [gids.remove(p) for p in pids if p in gids] else: pids = LiveHotGame.hot_game_ids() if pids: [gids.remove(p) for p in pids if p in gids] games = [g.format() for g in Game.get_list(gids)] return {'games': games}
def topic_games(): """获取专题游戏 (GET) :uri: /games/topic_games :param: topic_id: 专题ID :param maxs: 最后时间, 0代表当前时间, 无此参数按page来分页 :param page: 页码(数据可能有重复, 建议按照maxs分页) :param nbr: 每页数量 :return: {'games': <Game>list, 'topic':<GameTopic>, 'end_page': bool, 'maxs': timestamp} """ tid = request.values.get('topic_id', None) maxs = request.values.get('maxs', None) page = int(request.values.get('page', 1)) pagesize = int(request.values.get('nbr', 10)) if not tid: return error.InvalidArguments topic = GameTopic.get_one(tid) if not topic: return error.GameTopicNotExist # 增加访问次数 count = int(topic.get('visitor_count', 0) + 1) topic.update_model({'$set': {'visitor_count': count}}) topic.visitor_count = count topic = topic.format() games = list() while len(games) < pagesize: ids = TopicGame.topic_game_ids(tid, page, pagesize, maxs) tgids, gids = [i[0] for i in ids], [i[1] for i in ids] gms = [g.format() for g in Game.get_list(gids)] games.extend(gms) # 如果按照maxs分页, 不足pagesize个记录则继续查询 if maxs is not None: obj = TopicGame.get_one(tgids[-1], check_online=False) if tgids else None maxs = obj.order if obj else 0 if len(gids) < pagesize: break else: break return { 'games': games, 'topic': topic, 'end_page': len(gids) != pagesize, 'maxs': maxs }
def game_popular_users(gid): """获取游戏热门用户 (GET) :uri: /games/<string:gid>/popularusers :param page: 页码 :param nbr: 每页数量 :returns: {'users': list, 'end_page': bool} """ params = request.values page = int(params.get('page', 1)) pagesize = int(params.get('nbr', 10)) uids = Game.popular_user_ids(gid, page, pagesize) users = [u.format() for u in User.get_list(uids)] return {'users': users, 'end_page': len(uids) != pagesize}
def pop_game(): """设置常用游戏 (GET|POST&LOGIN) :uri: /user/opt/popular_game :param game_id: 游戏id(批量订阅游戏id以逗号隔开) :returns: {} """ user = request.authed_user gids = request.values.get('game_id', None) uid = UserPopularGame.get_user_id(user._id) game_ids_list = UserPopularGame.get_game_ids(user._id) if not gids: for game_id in game_ids_list: usg = UserPopularGame.get_by_ship(str(user._id), str(game_id)) usg.delete_model() if usg else None if not uid: usg = UserPopularGame.init() usg.source = ObjectId(str(user._id)) usg.create_model() return {} gids = [gid.strip() for gid in gids.split(',')] games = Game.get_list(gids, check_online=False) if not games: return error.GameNotExist key = 'lock:popgame:%s' % (str(user._id)) with util.Lockit(Redis, key) as locked: if locked: return error.PopGameFailed # 删除游戏 for game_id in game_ids_list: # if game_id not in gids: usg = UserPopularGame.get_by_ship(str(user._id), str(game_id)) usg.delete_model() if usg else None # 保存游戏 for index, game in enumerate(games): # usg = UserPopularGame.get_by_ship(str(user._id), str(game._id)) # if not usg: usg = UserPopularGame.init() usg.source = ObjectId(str(user._id)) usg.target = ObjectId(str(game._id)) usg.order = index usg.create_model() return {}
def format(self): _ids = GameRecommendConfigAdmin.all_module_game_ids(str(self._id)) games = [g.format() for g in Game.get_list(_ids)] if _ids else [] data = { 'module_id': str(self._id), 'module_label': urljoin(app.config.get("MEDIA_URL"), self.module_label), 'module_name': self.module_name, 'display_position': self.display_position, 'display_form': self.display_form, 'begin_at': self.begin_at, 'expire_at': self.expire_at, 'games': games } return data
def get_category_games(): """获取直播分类列表(游戏) (GET) :uri: /lives/cate-games :returns: {'games': list} """ user = request.authed_user gids = LiveHotGame.hot_game_ids() if user: for sgid in UserSubGame.sub_game_ids(str(user._id)): if sgid not in gids: gids.append(sgid) games = [g.format() for g in Game.get_list(gids)] return {'games': games}
def migu_game_popular_videos(bid): """获取游戏热门视频 (GET) :uri: /migu/games/<string:bid>/popular/ :param page: 页码 :param nbr: 每页数量 :returns: {'videos': list, 'end_page': bool} """ params = request.values page = int(params.get('page', 1)) pagesize = int(params.get('nbr', 10)) game = Game.get_by_bid(bid) if not game: return error.GameNotExist vids = Video.game_hotvideo_ids(str(game._id), page, pagesize) videos = [v.format() for v in Video.get_list(vids)] ret = {'videos': videos, 'end_page': len(vids) != pagesize} return ret
def sub_game_videos(uid): """获取用户已订阅游戏的视频 (GET) :uri: /users/<string:uid>/subscriptions :returns: {'videos': list} """ gids = UserSubGame.sub_game_ids(uid) games = Game.get_list(gids) ret = [] for game in games: vids = Video.game_video_ids(str(game._id), 1, 4, time.time()) ex_fields = [ 'is_favored', 'is_liked', 'author__is_followed', 'game__subscribed' ] videos = [ v.format(exclude_fields=ex_fields) for v in Video.get_list(vids) ] ret.append({'game': game.format(), 'videos': videos}) return {'videos': ret}
def chess_games(): """获取棋牌分类下的游戏 (GET) :uri: /games/chess_games :param: chess_id: 棋牌分类ID :return: {'games': <Game>list, 'chess_config':<ChessConfig>} """ tid = request.values.get('chess_id', None) if not tid: return error.InvalidArguments chess_config = ChessConfig.get_one(tid) if not chess_config: return error.ChessConfigNotExist ids = ChessGames.chess_game_ids(tid) games = [g.format() for g in Game.get_list(ids)] return {'games': games, 'chess_config': chess_config.format()}
def vip_games(): """获取会员专区下的游戏 (GET) :uri: /games/vip_games :param: vip_id: 会员专区ID :return: {'games': <Game>list, 'vip_config':<VipConfig>} """ tid = request.values.get('vip_id', None) if not tid: return error.InvalidArguments vip_config = VipConfig.get_one(tid) if not vip_config: return error.VipConfigNotExist ids = VipGames.vip_game_ids(tid) games = [g.format() for g in Game.get_list(ids)] return {'games': games, 'vip_config': vip_config.format()}
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 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 {}
def toplist_games(): """获取排行游戏 (GET) :uri: /games/toplist_games :param: toplist_id: 排行ID :return: {'games': <Game>list, 'toplist':<TopList>list} """ tid = request.values.get('toplist_id', None) if not tid: return error.InvalidArguments toplist = TopList.get_one(tid) if not toplist: return error.GameTopListNotExist ids = TopListGames.toplist_game_ids(tid) games = [g.format() for g in Game.get_list(ids)] return {'games': games, 'toplist': toplist.format()}
def recommend_users(): """获取推荐关注 (GET&LOGIN) :uri: /recommend/users :returns: {'users': list} """ user = request.authed_user uids = [] gids = UserSubGame.sub_game_ids(str(user._id)) for gid in gids: uids.extend(Game.popular_user_ids(gid)) if not uids: uids = User.user_recommend_attention() uids = list(set(uids)) if str(user._id) in uids: uids.remove(str(user._id)) if len(uids) > const.RECOMMEND_ATTENTION: uids = random.sample(uids, const.RECOMMEND_ATTENTION) users = [u.format() for u in User.get_list(uids)] return {'users': users}
def get_hot_games(): """获取常用游戏列表(游戏) (GET) :uri: /lives/hot_games :returns: {'games': list} """ user = request.authed_user if user: uid = UserPopularGame.get_user_id(user._id) gids = UserPopularGame.get_game_ids(user._id) if not gids: if uid: gids = None else: gids = LiveHotGame.hot_game_ids() else: gids = LiveHotGame.hot_game_ids() games = [g.format() for g in Game.get_list(gids)] return {'games': games}