def user_sub_obj_ids(cls, uid, page, pagesize, maxs): skey = UserSubShow.SUB_SHOW_IDS % {'uid': uid} gkey = UserSubGame.SUB_GAME_IDS % {'uid': uid} key = cls.USER_SUB_IDS % {'uid': uid} if not Redis.exists(skey): UserSubShow._load_sub_show_ids(uid) if not Redis.exists(gkey): UserSubGame._load_sub_game_ids(uid) # 始终合并以保证实时性 Redis.delete(key) all_keys = list() for k in [skey, gkey]: try: count = Redis.zcard(k) except exceptions.ResponseError: count = 0 count and all_keys.append(k) all_keys and Redis.zunionstore(key, all_keys) try: if maxs: ids = Redis.zrevrangebyscore(key, '(%.6f' % (maxs), '-inf', start=0, num=pagesize, withscores=True) else: start = (page - 1) * pagesize stop = start + pagesize - 1 ids = Redis.zrevrange(key, start, stop, withscores=True) except exceptions.ResponseError: ids = [] return list(ids)
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 {}
def user_sub_games(uid): """获取用户已订阅游戏 (GET) :uri: /users/<string:uid>/games :param maxs: 最后时间, 0代表当前时间, 无此参数按page来分页 :param page: 页码(数据可能有重复, 建议按照maxs分页) :param nbr: 每页数量 :returns: {'games': 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)) games = list() gids = list() while len(games) < pagesize: gids = UserSubGame.sub_game_ids(uid, page, pagesize, maxs) # 下线游戏也需要展示在用户订阅列表中 games.extend([ g.format(exclude_fields=['subscribed']) for g in Game.get_list(gids, check_online=False) ]) # 如果按照maxs分页, 不足pagesize个记录则继续查询 if maxs is not None: obj = UserSubGame.get_by_ship(uid, gids[-1]) if gids else None maxs = obj.create_at if obj else 1000 if len(gids) < pagesize: break else: break return {'games': games, 'end_page': len(gids) != pagesize, 'maxs': maxs}
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 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 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 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 home(): """获取首页信息 (GET) :uri: /home :param os: 平台 :param channels: 渠道(可选) :param version_code: 版本号 :returns: {'banners': list, 'categories': list, 'sub_games': list, 'hot_games': list, 'hot_lives': list} """ user = request.authed_user ret = dict() # banner广告 params = request.values os = params.get('os', None) channels = params.get('channels', None) version_code = int(params.get('version_code', 0)) no_gamefy = False # 不返回游戏风云视频及内容 if not os or not version_code: no_gamefy = True elif (os == 'ios' and version_code < 5920) or (os == 'android' and version_code < 416): no_gamefy = True uid = None province = None if user: uid = str(user._id) 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 banners = list() _ids = Banner.all_banner_ids() for b in Banner.get_list(_ids): if b.os and b.os != 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 province and province not in b.province: continue banners.append(b.format()) if version_code == 0 and not banners: _ids = Banner.all_banners_by_version() banners = [b.format() for b in Banner.get_list(_ids)] ret['banners'] = banners support_cates = ['video', 'game', 'user', 'show-video'] if no_gamefy: support_cates.pop(-1) categories = [] cate_ids = HomeCategory.all_category_ids() cates = HomeCategory.get_list(cate_ids) for cate in cates: ids = HomeCategoryConfig.category_object_ids(str(cate._id)) if not ids or cate.ctype not in support_cates: continue _category = cate.format() if cate.ctype in ['video', 'show-video']: ex_fields = [ 'is_favored', 'is_liked', 'author__is_followed', 'game__subscribed' ] if no_gamefy: _category['objects'] = [ v.format(exclude_fields=ex_fields) for v in Video.get_list(ids) if v.author ] else: _category['objects'] = [ v.format(exclude_fields=ex_fields) for v in Video.get_list(ids) ] elif cate.ctype == 'game': ex_fields = ['subscribed'] _category['objects'] = [ g.format(exclude_fields=ex_fields) for g in Game.get_list(ids) ] elif cate.ctype == 'user': ex_fields = ['is_followed'] _category['objects'] = [ u.format(exclude_fields=ex_fields) for u in User.get_list(ids) ] _category['objects'] = _category['objects'][:4] categories.append(_category) ret['categories'] = categories # 兼容老版本 ret['hottest_of_today'] = [] # 热门直播 all_lives = Xlive.get_all_lives() hot_lives = all_lives[:4] if len(all_lives) >= 4 else all_lives[:2] hot_lives = hot_lives if len(hot_lives) > 1 else [] ret['hot_lives'] = [Xlive.format(l) for l in hot_lives] # 用户已订阅游戏 sub_game_ids = [] if user: sub_game_ids = UserSubGame.sub_game_ids(str(user._id)) tmp = [] for game_id in sub_game_ids: ex_fields = [ 'is_favored', 'is_liked', 'author__is_followed', 'game__subscribed' ] vids = GameRecommendVideo.game_video_ids(game_id) or [] videos = [ v.format(exclude_fields=ex_fields) for v in Video.get_list(vids) ] # 补齐4个人气视频 if len(videos) < 4: hot_vids = Video.game_hotvideo_ids(game_id, 1, 4) for _vid in hot_vids: if len(videos) == 4: break if _vid in vids: continue v = Video.get_one(_vid, check_online=True) v and videos.append(v.format(exclude_fields=ex_fields)) if videos: tmp.append({'game': videos[0]['game'], 'videos': videos}) else: tmp = list() ret['sub_games'] = tmp # 热门游戏 gids = HotGame.hot_game_ids() # 去掉用户已订阅游戏 gids = [gid for gid in gids if gid not in sub_game_ids] tmp = [] for game_id in gids: ex_fields = [ 'is_favored', 'is_liked', 'author__is_followed', 'game__subscribed' ] vids = GameRecommendVideo.game_video_ids(game_id) or [] videos = [ v.format(exclude_fields=ex_fields) for v in Video.get_list(vids) ] # 补齐4个人气视频 if len(videos) < 4: hot_vids = Video.game_hotvideo_ids(game_id, 1, 4) for _vid in hot_vids: if len(videos) == 4: break if _vid in vids: continue v = Video.get_one(_vid, check_online=True) v and videos.append(v.format(exclude_fields=ex_fields)) if videos: tmp.append({'game': videos[0]['game'], 'videos': videos}) ret['hot_games'] = tmp return ret