def get_task_status(self, url, params, request, response): """ Get task status. [Arguments] task: string task name. 'rebuild_movie_keyword' 'patch_data' [Return] task_done: string task status. True is done, False is not yet. """ task = params.get_string('task', None) # check argument 'task' if not task: raise RequestError(ERR_REQUEST_ARG, str_data=("argument 'task' is need.", )) taskobj = g().get(task) # can't find task if not taskobj: return Response(success=False, err_msg="can't find task.") # some error occur if taskobj.error: return Response(success=False, err_msg=taskobj.error_message if taskobj.error_message else 'unhandle error') # return True: task done; False: not yet return Response(model_data={'task_done': taskobj.done})
def add_count(self, url, params, request, response): """ Add user action count of choosen AV. [Arguments] url[0] : string. AV ID. type : string. Action type. """ # API args av_id = url[0] if len(url) else None action_type = params.get_string('type', None) if not action_type or action_type not in [ USER_ACTION_VIEW, USER_ACTION_DOWNLOAD, USER_ACTION_PLAY ]: raise RequestError(ERR_REQUEST_ARG, str_data=('type error.')) db_inst = PGClient(db='av') cur, rowcount = db_inst.query(table='video', condition=['id=%(id)s', { 'id': av_id }]) if not rowcount: raise RequestError(ERR_DB_NOT_FOUND) count, total = self._add_user_action(action_type=action_type, av_id=av_id, db_inst=db_inst) db_inst.commit() return Response(content={'count': count, 'total': total})
def delete_addon(self, url, params, request, response): """ delete addon file. [Arguments] url[0] : string. Addon version of file to remove. """ # API args if len(url): version = url[0] else: raise RequestError(ERR_REQUEST_ARG, str_data=('version error.')) db_inst = PGClient(db='file', timeout=False) # check data exist cur, rowcount = db_inst.query( table='addons', fields=['version'], condition=[u'version=%(version)s', { 'version': version }]) if not rowcount: raise RequestError(ERR_REQUEST_ARG, str_data=('data does not exist.')) db_inst.remove( table='addons', condition=[u'version=%(version)s', { 'version': version }]) db_inst.commit() return Response({'version': version})
def get_addon_version(self, url, params, request, response): """ Get addon version. """ # API args version = url[0] if len(url) else None db_inst = PGClient(db='file') if version: addons, rowcount = db_inst.query( table='addons', fields=['version', 'md5sum'], condition=[u'version=%(version)s', { 'version': version }], ret_type='all') else: # latest version addons, rowcount = db_inst.query( table='addons', fields=['version', 'md5sum'], ret_type='all', else_sql='ORDER BY version DESC LIMIT 1') if not rowcount: raise RequestError(ERR_DB_NOT_FOUND) return Response({ 'version': addons[0]['version'], 'md5sum': addons[0]['md5sum'] })
def search_media(self, url, params, request, response): """ Search multimedia information. [Arguments] See _parse_args. """ args = self._parse_args(url, params) ret = { 'detail': True, # FIXME if this filed is not a common data. 'media_type': args['media_type'] } try: search_inst = { 'movies': search_movies, 'karaokes': search_karaokes, 'avs': search_avs, 'tvs': search_tvs }[args.pop('media_type')] except: raise RequestError(ERR_REQUEST_ARG, str_data=('media type error')) search_ret = search_inst(**args) ret.update(search_ret) return Response(model_data=ret)
def search_index(self, url, params, request, response): """ Search multimedia index. [Arguments] Take Args: keyword, lang. See _parse_args. range : list of string. Search range. """ args = self._parse_args(url, params) args['keyword'] = list(set(args['keyword'])) inst_map = { 'movies': m_total, 'karaokes': k_total, 'avs': a_total, 'tvs': t_total } # additional args search_range = params.get_list('range', inst_map.keys()) ret = {} for key in search_range: ret[key] = inst_map[key](args['keyword'], args['lang']) return Response(content=ret)
def get_movie_titles(self, url, params, request, response): """ Get movie titles of each source. [Arguments] url[0] : string. IMDB ID. """ # API args if not url: raise RequestError(ERR_REQUEST_ARG, str_data=('format error.')) imdbid = url[0] db_inst = PGClient() condition = ['imdbid = %(imdbid)s', {'imdbid': imdbid}] rows, rowcount = db_inst.query(table='movies', fields=['source, title'], condition=condition, ret_type='all') return Response( content={ 'titles': { source2lang(row['source']): row['title'] for row in rows if source2lang(row['source']) is not None } })
def patch_data(self, url, params, request, response): """ patch data to db create patcher by tablename and execute patch. :param url: :param params: :param request: :param response: :return: """ tablename = params.get_string('tablename', None) # check tablename argument if not tablename: raise RequestError(ERR_REQUEST_ARG, str_data=("argument 'tablename' is need.", )) # check patchfile argument if 'patchfile' not in params: raise RequestError(ERR_REQUEST_ARG, str_data=("argument 'patchfile' is need.", )) # get patcher patcher = create_patcher(tablename) if not patcher: raise RequestError( ERR_REQUEST_ARG, str_data=("argument 'tablename' is incorrect.", )) # execute patch task patcher.patch(params['patchfile'], 'patch_data') # return message return Response( model_data={ 'message': "start to patch %s" % patcher.get_tablename() })
def get_metadata(self, url, params, request, response): """ Use TV id of any source to get all metadata. [Arguments] ids : list string. IDs of TVs to get metadata. """ # API args ids = params.get_list('ids', None) if not ids: raise RequestError(ERR_REQUEST_ARG, str_data=('ids.')) resp = Response(content={'tvs': {}}) db_inst = PGClient() # Get items with ids condition = ['id IN %(id)s', {'id': tuple(ids)}] tvs, rowcount = db_inst.query(table='drama', condition=condition, ret_type='all') for tv in tvs: resp['tvs'][tv['id']] = {'dbid': tv['dbid'], 'metadata': {}} # Get metadata of each source. if tv['dbid']: condition = ['dbid = %(id)s', {'id': tv['dbid']}] rows, rowcount = db_inst.query(table='drama', condition=condition, ret_type='all') else: # only one record rows = [tv] for row in rows: resp['tvs'][tv['id']]['metadata'][row['source']] = { 'id': row['id'], 'source': row['source'], 'title': row['title'], 'akas': row['akas'], 'kind': row['kind'], 'genres': row['genres'], 'posterurl': tv['posterurl'], 'stars': row['stars'], 'year': row['year'], 'region': row['region'], 'description': row['description'], 'url': row['url'], 'update_eps': row['update_eps'], 'total_eps': row['total_eps'], 'completed': row['completed'], 'md5sum': row['md5sum'] } # patch up not found data. for missing_id in set(ids).difference(resp['tvs'].keys()): resp['tvs'][missing_id] = {} return resp
def process_view(self, request, view_func, view_args, view_kwargs): """静态文件及有"notauth" 属性view_func 免认证 """ # 获取原始代码的属性 check_view_func = self.get_check_view_func(request, view_func) # 视图类没有权限设置,则使用path找出function检查 if hasattr(check_view_func, 'as_view') and ( not is_notauth(check_view_func) or not is_notcheck(check_view_func) ): if 'path' in view_kwargs: check_view_func = getattr(check_view_func, view_kwargs['path'], None) or check_view_func # 不需要登陆 if is_notauth(check_view_func) or self.is_pass(view_func): # 不需处理的函数不管 is_allow = True if ((request.path_info.find('/login') == 0 or request.path_info.find( '/phone_login') == 0) and request.method == 'POST'): request.user = request.admin = User() request.user.id = 0 self.save_operate_log(request, '登录后台') else: user_id = request.session.get(SESSION_KEY, None) the_user = User.objects.filter(id=user_id, status__in=(User.Status.NORMAL, User.Status.NotActive)).first() request.user = request.admin = the_user if not request.user: if request.is_ajax() or request.is_json: return Response(request=request, code=-1, msg=_('请重新登录')) login_url = settings.LOGIN_URL return HttpResponseRedirect('%s?from_url=%s' % (login_url, request.get_full_path())) the_user.make_allow_map() request.allow = request.allow_menu = the_user.allow_menu is_allow = self.check_url_permsssion(request) if is_notcheck(check_view_func): is_allow = True if not is_allow: return Response(request=request, code=1, msg=_('没有权限'), template_name='myadmin/block.html')
def add_count(self, url, params, request, response): """ Add user action count of choosen karaoke. [Arguments] url[0] : string. Karaoke ID. type : string. Action type. """ # API args karaoke_id = url[0] if len(url) else None id_list = params.get_list('ids', []) action_type = params.get_string('type', None) if not action_type or action_type not in [USER_ACTION_VIEW, USER_ACTION_DOWNLOAD, USER_ACTION_PLAY]: raise RequestError(ERR_REQUEST_ARG, str_data=('type error.')) if karaoke_id: id_list = [karaoke_id] elif not id_list: raise RequestError(ERR_REQUEST_ARG, str_data=('id_list error.')) db_inst = PGClient(db='karaoke') cur, rowcount = db_inst.query(table='songs', condition=['keymd5 IN %(ids)s', {'ids': tuple(id_list)}]) if rowcount != len(id_list): raise RequestError(ERR_DB_NOT_FOUND) resp = Response() for ID in id_list: count, total = self._add_user_action(action_type=action_type, karaoke_id=ID, db_inst=db_inst) resp[ID] = { 'count': count, 'total': total } db_inst.commit() return resp.pop(karaoke_id) if karaoke_id else resp
def get_play_list(self, url, params, request, response): """ Get play list. [Arguments] url[0] : string. Drama ID. source : Video source. since : int string. Response rows start from. limit : int string. Number of response rows to display. """ # API args drama_id = url[0] if len(url) else None source = params.get_string('source', None) since = params.get_int('since', 0) limit = params.get_limit('limit', 30) if not drama_id: raise RequestError(http_status=404) condition = ['id=%(id)s', {'id': drama_id}] if source in self.allow_display_play_source(): fields = [ ''' ( ARRAY(SELECT json_array_elements(play_urls->'%s')) )[%s:%s] AS play_list ''' % ( source, since + 1 if since > 0 else 1, limit + since if limit > 0 else "json_array_length(play_urls->'%s')" % source # limit it if need. ) ] else: raise RequestError(ERR_REQUEST_ARG, str_data=('source.')) db_inst = PGClient() dramas, rowcount = db_inst.query(table='drama', fields=fields, condition=condition, ret_type='all') if not rowcount: raise RequestError(http_status=404) return Response(model_data={'data': dramas[0]})
def get_metadata(self, url, params, request, response): """ Use AV id of any source to get all metadata. [Arguments] ids : list string. IDs of AVs to get metadata. """ # API args ids = params.get_list('ids', None) if not ids: raise RequestError(ERR_REQUEST_ARG, str_data=('ids.')) resp = Response(content={'avs': {}}) db_inst = PGClient(db='av') condition = ['id IN %(id)s', {'id': tuple(ids)}] avs, rowcount = db_inst.query(table='video', condition=condition, ret_type='all') for av in avs: resp['avs'][av['id']] = {'metadata': {}} resp['avs'][av['id']]['metadata'][DB_SRC_DMM] = { 'id': av['id'], 'source': DB_SRC_DMM, 'title': av['title'], 'posterurl': av['posterurl'], 'duration': av['duration'], 'stars': av['performer'], 'genres': av['category'], 'rating': av['rating'], 'maker': av['maker'], 'series': av['series'], 'date': av['date'] and av['date'].strftime("%Y-%m-%d %H:%M:%S"), 'description': av['description'], 'samples': av['samples'], 'url': av['url'], 'date2': av['date2'] and av['date2'].strftime("%Y-%m-%d %H:%M:%S"), 'code': av['code'], 'md5sum': av['md5sum'] } # patch up not found data. for missing_id in set(ids).difference(resp['avs'].keys()): resp['avs'][missing_id] = {} return resp
def get_patch_columns(self, url, params, request, response): tablename = params.get_string('tablename', None) # check tablename argument if not tablename: raise RequestError(ERR_REQUEST_ARG, str_data=("argument 'tablename' is need.", )) # get patcher patcher = create_patcher(tablename) if not patcher: raise RequestError( ERR_REQUEST_ARG, str_data=("argument 'tablename' is incorrect.", )) # return patch columns return Response(model_data={'columns': patcher.get_columns()})
def wrapper(*args, **kwargs): try: # lock self.mutex.acquire() # check background task status self._check_bg_running() # if other task is running, return Response. if self.bg_task: return Response(success=False, err_msg='other task is runing.') else: self.bg_task = taskname # if no other task run, execute func. return func(*args, **kwargs) finally: # unlock self.mutex.release()
def get_metadata(self, url, params, request, response): """ Use karaokes id of any source to get all metadata. [Arguments] ids : list string. IDs of karaokes to get metadata. """ # API args ids = params.get_list('ids', None) if not ids: raise RequestError(ERR_REQUEST_ARG, str_data=('ids.')) resp = Response(content={'karaokes': {}}) db_inst = PGClient(db='karaoke') condition = ['keymd5 IN %(id)s', {'id': tuple(ids)}] karaokes, rowcount = db_inst.query(table='songs', condition=condition, ret_type='all') for karaoke in karaokes: resp['karaokes'][karaoke['keymd5']] = {'metadata': {}} # Get content data. condition = ['keymd5 = %(id)s', {'id': karaoke['keymd5']}] rows, rowcount = db_inst.query(table='song_content', condition=condition, ret_type='all') content = rows[0] if rows else {} # Key name use lang instead of source name and we only have TCH data, # because TCH dad is composed of cashbox, holiday and youtube. resp['karaokes'][karaoke['keymd5']]['metadata'][LANG_TCH] = { 'id': karaoke['keymd5'], 'source': karaoke['source'], 'title': karaoke['title'], 'artist': karaoke['artist'], 'song_lang': karaoke['lang'], # use content 'posterurl': content['poster_url'], 'description': content['description'], 'play_url': content['play_url'], 'md5sum': content['md5sum'] } # patch up not found data. for missing_id in set(ids).difference(resp['karaokes'].keys()): resp['karaokes'][missing_id] = {} return resp
def rebuild_keyword(self, url, params, request, response): tablename = params.get_string('tablename', None) # check tablename argument if not tablename: raise RequestError(ERR_REQUEST_ARG, str_data=("argument 'tablename' is need.", )) # get builder builder = create_keyword_builder(tablename) if not builder: raise RequestError( ERR_REQUEST_ARG, str_data=("argument 'tablename' is incorrect.", )) # execute rebuild keyword task builder.build('rebuild_keyword') # return message return Response( model_data={ 'message': 'start to rebuild %s' % builder.get_tablename() })
def handle_error(): """ Note: Not catch Httpd code 3XX~4XX exception. These exception will just response to client. """ excpetion_inst = _exc_info()[1] if isinstance(excpetion_inst, RequestError): cherrypy.response.headers['Content-Type'] = 'application/json' cherrypy.response.status = excpetion_inst.http_status resp = Response(success=False, err_code=excpetion_inst.code, err_msg=excpetion_inst.get_msg()) cherrypy.response.body = json.dumps(resp) else: # hide exception information cherrypy.response.show_tracebacks = False cherrypy.response.status = 500 cherrypy.response.body = [ "<html><body>%s</body></html>" % ERR_MSG[500] ]
def get_covers(self, url, params, request, response): """ Get karaoke covers. [Arguments] song_langs : list string. Karaoke ID. list_type : int string. """ song_langs = params.get_list('song_langs', []) song_langs = [v for v in song_langs if v in ARG_SONG_LANGS] if not song_langs: raise RequestError(ERR_REQUEST_ARG, str_data=('song_langs.')) list_type = params.get_int('list_type', 1) if list_type not in xrange(1, 4): raise RequestError(ERR_REQUEST_ARG, str_data=('list_type.')) # Take the cover of first row of each song lang as index cover. table = u''' song_content, ( SELECT DISTINCT ON (lang) keymd5, lang FROM song_list WHERE lang IN %(lang)s AND type=%(type)s ORDER BY lang, rank ) l ''' fields = ['song_content.poster_url', 'l.lang'] condition = [u'song_content.keymd5=l.keymd5', {'lang': tuple(song_langs), 'type': str(list_type)}] db_inst = PGClient(db='karaoke') rows, rowcount = db_inst.query(table=table, fields=fields, condition=condition, ret_type='all') covers = {row['lang']: row['poster_url'] for row in rows} return Response(content={ 'covers': {key: covers[key] if covers.has_key(key) else None for key in song_langs} })
def update_latest_movies(self, url, params, request, response): """ Update latest movies. [Arguments] imdbid_list: list The imdbid list to update latest table. [Return] rowcount: int The row count of 'movie_latest'. """ imdbid_list = params.get_list('imdbid_list', None) # check argument 'imdbid_list' if not imdbid_list: raise RequestError(ERR_REQUEST_ARG, str_data=("argument 'imdbid_list' is need.", )) values = '' for data in imdbid_list: # check imdbid pattern reslut = re.match('tt\d{7}', data[0]) if reslut is None: raise RequestError( ERR_REQUEST_ARG, str_data=('imdbid_list(%s) is not imdbid format.' % data[0], )) values += "('%s', '%s')," % (data[0], data[1]) values = values[:-1] # insert db db_inst = PGClient() db_inst.execute('truncate table movie_latest') db_inst.execute('insert into movie_latest values %s' % values) db_inst.commit() cur = db_inst.execute('select count(*) from movie_latest') rowcount = cur.fetchone()[0] return Response(model_data={'rowcount': rowcount})
def suggest_keyword(self, url, params, request, response): """ Suggest keyword. [Arguments] media_type : string. Media type. media_id : string. Target media ID. lang : string. To choose display content. """ media_type = params.get_string('media_type', None) media_id = params.get_string('media_id', None) lang = params.get_string('lang', None) if not media_id or not media_type or not lang: raise RequestError(ERR_REQUEST_ARG, str_data=('args missing')) try: search_inst = {'movies': m_keyword, 'avs': a_keyword}[media_type] except: raise RequestError(ERR_REQUEST_ARG, str_data=('media_type error')) return Response(content={'keywords': search_inst(media_id, lang)})
def get_last_timestamp(self, url, params, request, response): """ get last update timestamp create patcher by tablename and get timestamp. :param url: :param params: :param request: :param response: :return: """ tablename = params.get_string('entity', None) # check entity argument if not tablename: raise RequestError(ERR_REQUEST_ARG, str_data=("argument 'entity' is need.", )) # get patcher patcher = create_patcher(tablename) if not patcher: raise RequestError(ERR_REQUEST_ARG, str_data=("argument 'entity' is incorrect.", )) return Response(model_data={'timestamp': patcher.get_timestamp()})
def upload_addon(self, url, params, request, response): """ Upload addon file. [Arguments] url[0] : string. Addon version of this file. md5sum : string. (opt) md5sum of this file to check data is complete. """ # API args if len(url): version = url[0] else: raise RequestError(ERR_REQUEST_ARG, str_data=('version error.')) if not params.has_key('file'): raise RequestError(ERR_REQUEST_ARG, str_data=('file error.')) file_md5sum = params.get_string('md5sum', None) # check data exist db_inst = PGClient(db='file', timeout=False) cur, rowcount = db_inst.query( table='addons', fields=['version'], condition=[u'version=%(version)s', { 'version': version }]) if rowcount: raise RequestError(ERR_REQUEST_ARG, str_data=('data existed.')) # handle updating file upload_file = params['file'] tmp_file_path = '%s/%s' % (TMP_PATH, upload_file.filename) try: # save file md5 = hashlib.md5() with open(tmp_file_path, mode='wb') as fp: while True: data = upload_file.file.read(8192) if data: fp.write(data) md5.update(data) else: break # compare md5sum md5sum = md5.hexdigest() if file_md5sum and md5sum != file_md5sum: raise RequestError(ERR_REQUEST_ARG, str_data=('md5sum check error.')) # insert data to db with open(tmp_file_path, mode='rb') as f: db_inst.insert(table='addons', data={ 'version': version, 'name': upload_file.filename, 'data': Binary(f.read()), 'md5sum': md5sum, 'udate': datetime.utcnow().isoformat() }) # remove redundant data addons, rowcount = db_inst.query(table='addons', fields=['version'], ret_type='all', else_sql='ORDER BY version DESC') if rowcount > MAX_NUM_ADDONS: versions_to_remove = [ addons[-1 * index]['version'] for index in xrange(1, rowcount - MAX_NUM_ADDONS + 1) ] db_inst.remove(table='addons', condition=[ 'version IN %(versions)s', { 'versions': tuple(versions_to_remove) } ]) db_inst.commit() return Response({'version': version, 'md5sum': md5sum}) finally: os.remove(tmp_file_path)
def get_avs(self, url, params, request, response): """ Get AVs information. [API] 1) GET RESOURCE/${AV_ID} Get target AVs detail information. 2) GET RESOURCE?type=${TYPE} Get custom information. [Arguments] url[0] : string. Song ID to find. type : string. Information type. since : int string. Response data start from. limit : int string. Number of response rows to display. lang : string. To choose display content. """ # API args av_id = url[0] if len(url) else None request_type = params.get_string('type', REQUEST_LATEST) since = params.get_int('since', None) lang = params.get_string('lang', None) fields = None condition = [] ordering_sql = None if av_id: # Get one AV information limit = 0 condition = ['id=%(id)s', {'id': av_id}] else: limit = params.get_limit('limit', 20) if request_type == REQUEST_POPLAR: # Get popular AVs information ordering_sql = 'ORDER BY total_count DESC NULLS LAST, date DESC NULLS LAST' elif request_type == REQUEST_LATEST: # Get latest AVs information now_date = datetime.utcnow().isoformat().split('T')[0] condition = ['date <= %(date)s', {'date': now_date}] ordering_sql = 'ORDER BY date DESC NULLS LAST' else: raise RequestError(ERR_REQUEST_ARG, str_data=('type.')) db_inst = PGClient(db='av') else_sql = '%s %s %s' % (ordering_sql if ordering_sql else '', 'OFFSET %s' % since if since else '', 'LIMIT %s' % limit if MAX_RESPONSE_ROWS > limit > 0 else 'LIMIT %s' % MAX_RESPONSE_ROWS) avs, rowcount = db_inst.query(table='video', fields=fields, condition=condition, ret_type='all', else_sql=else_sql) if not rowcount and av_id: raise RequestError(http_status=404) return Response(model_data={ 'metadata': avs, 'detail': True if av_id else False })
def get_TVs(self, url, params, request, response): """ Get TVs information. [API] 1) GET RESOURCE/${DRAMA_ID} Get target dramas detail information. 2) GET RESOURCE?type=${TYPE} Get custom information. [Arguments] url[0] : string. Drama ID to find. since : int string. Response data start from. limit : int string. Number of response rows to display. lang : string. To choose display content. drama_kind : int string. To choose kind of dramas. type : string. The type to display information. """ # API args drama_id = url[0] if len(url) else None request_type = params.get_string('type', REQUEST_LATEST) since = params.get_int('since', None) lang = params.get_string('lang', None) condition_sql = '' condition_data = {} ordering_sql = None if drama_id: # Get one drama information limit = 0 condition_sql = 'id=%(id)s' condition_data = {'id': drama_id} else: # Get drama list information limit = params.get_limit('limit', 20) kind = params.get_int('drama_kind', 1) if kind not in xrange(0, 9): raise RequestError(ERR_REQUEST_ARG, str_data=('drama_kind.')) condition_sql = "kind='%s'" % kind condition_sql = "%s AND source='%s'" % (condition_sql, lang2source(lang)) condition_sql = "%s AND '%s' && ARRAY(SELECT json_object_keys(play_urls))" % ( condition_sql, self.sql_array_string()) if request_type == REQUEST_POPLAR: # Get popular drama information ordering_sql = "ORDER BY total_count DESC NULLS LAST, rdate DESC NULLS LAST" elif request_type == REQUEST_LATEST: # Get latest drama information ordering_sql = 'ORDER BY rdate DESC NULLS LAST' else: raise RequestError(ERR_REQUEST_ARG, str_data=('type.')) dramas_sql = u''' SELECT * FROM drama WHERE {0} {1} {2} {3} '''.format( condition_sql, ordering_sql if ordering_sql else '', 'OFFSET %s' % since if since else '', 'LIMIT %s' % limit if MAX_RESPONSE_ROWS > limit > 0 else 'LIMIT %s' % MAX_RESPONSE_ROWS) db_inst = PGClient() cur = db_inst.execute(cmd=gen_fetch_dramas_sql(dramas_sql=dramas_sql), data=condition_data) if not cur.rowcount and drama_id: raise RequestError(http_status=404) return Response(model_data={ 'data': cur.fetchall(), 'detail': False if drama_id else True })
def get_movies(self, url, params, request, response): """ Get movies information. [API] 1) GET RESOURCE/${MOVIE_ID} Get target movie detail information. 2) GET RESOURCE?type=${TYPE} Get custom information. 3) GET RESOURCE Get all movie information. [Arguments] url[0] : string. Movie ID to find. type : string. Information type. since : int string. Response data start from. limit : int string. Number of response rows to display. lang : string. To choose display content. """ # API args movie_id = url[0] if len(url) else None request_type = params.get_string('type', REQUEST_LATEST) since = params.get_int('since', None) lang = params.get_string('lang', None) table = 'movies' fields = None condition = ['source=%(source)s', {'source': lang2source(lang)}] ordering_sql = None if movie_id: # Get one moive information limit = 0 condition = ['id=%(id)s', {'id': movie_id}] elif request_type: limit = params.get_limit('limit', 20) constraint_sql = """title!='' AND (posterurl is not null OR thumbnailurl is not null) AND directors!='{}' AND writers!='{}' AND stars!='{}' AND description is not null""" condition[0] = '%s AND %s' % (condition[0], constraint_sql) if request_type == REQUEST_POPLAR: # Get popular moive information ordering_sql = "ORDER BY total_count DESC NULLS LAST, releasedate->>'Default' DESC NULLS LAST" elif request_type == REQUEST_LATEST: # Get latest moive information table = 'movies, movie_latest' condition[ 0] = 'movies.imdbid = movie_latest.imdbid AND %s' % condition[ 0] ordering_sql = 'ORDER BY movie_latest.rdate DESC' else: raise RequestError(ERR_REQUEST_ARG, str_data=('type.')) else: # Get all moive information limit = params.get_limit('limit', 20) ordering_sql = 'ORDER BY year DESC' db_inst = PGClient() else_sql = '%s %s %s' % (ordering_sql if ordering_sql else '', 'OFFSET %s' % since if since else '', 'LIMIT %s' % limit if MAX_RESPONSE_ROWS > limit > 0 else 'LIMIT %s' % MAX_RESPONSE_ROWS) movies, rowcount = db_inst.query(table=table, fields=fields, condition=condition, ret_type='all', else_sql=else_sql) if not rowcount and movie_id: raise RequestError(http_status=404) content = get_movies_content(movies_row=movies, db_inst=db_inst) return Response( model_data={ 'metadata': movies, 'content': content, 'detail': True if movie_id else False })
async def handler(request): username = request.match_info['username'] if username not in request.app.db: raise HTTPNotFound(reason=f'No such user with as {username} :(') return Response(f'Welcome, {username}')
def get_metadata(self, url, params, request, response): """ Use movie id of any source to get all metadata. [Arguments] ids : list string. IDs of movies to get metadata. """ # API args ids = params.get_list('ids', None) if not ids: raise RequestError(ERR_REQUEST_ARG, str_data=('ids.')) resp = Response(content={'movies': {}}) db_inst = PGClient() # Get items with ids condition = ['id IN %(id)s', {'id': tuple(ids)}] movies, rowcount = db_inst.query(table='movies', condition=condition, ret_type='all') for movie in movies: resp['movies'][movie['id']] = { 'imdbid': movie['imdbid'], 'metadata': {} } # Get metadata of each source. if movie['imdbid']: condition = [ 'imdbid = %(imdbid)s', { 'imdbid': movie['imdbid'] } ] rows, rowcount = db_inst.query(table='movies', condition=condition, ret_type='all') else: rows = [movie] for row in rows: resp['movies'][movie['id']]['metadata'][row['source']] = { 'id': row['id'], 'source': row['source'], 'title': row['title'], 'akas': row['akas'], 'genres': row['genres'], 'rating': row['rating'], 'posterurl': row['posterurl'], 'directors': row['directors'], 'stars': row['stars'], 'releasedate': row['releasedate'], 'countries': row['countries'], 'description': row['description'], 'url': row['url'], 'md5sum': row['md5sum'], 'thumbnailurl': row['thumbnailurl'] } # patch up not found data. for missing_id in set(ids).difference(resp['movies'].keys()): resp['movies'][missing_id] = {} return resp
def get_karaokes(self, url, params, request, response): """ Get karaokes information. [API] 1) GET RESOURCE/${KARAOKE_ID} Get target karaokes detail information. 2) GET RESOURCE?type=${TYPE} Get custom information. [Arguments] url[0] : string. Song ID to find. since : int string. Response data start from. limit : int string. Number of response rows to display. lang : string. To choose display content. song_lang : string. To choose language type of songs. list_type : int string. To choose songs list type. """ # API args karaoke_id = url[0] if len(url) else None since = params.get_int('since', None) lang = params.get_string('lang', None) table = 'songs' fields = None condition = [] ordering_sql = None if karaoke_id: # Get one song information limit = 0 condition = ['keymd5=%(id)s', {'id': karaoke_id}] else: # Get song list information limit = params.get_limit('limit', 20) song_lang = params.get_string('song_lang', 'M') if song_lang not in ARG_SONG_LANGS: raise RequestError(ERR_REQUEST_ARG, str_data=('song_lang.')) list_type = params.get_int('list_type', 1) if list_type not in xrange(1, 4): raise RequestError(ERR_REQUEST_ARG, str_data=('list_type.')) table = 'songs, song_list' fields = ['songs.*', 'song_list.udate AS list_udate'] condition = [ 'songs.keymd5=song_list.keymd5 AND (song_list.lang=%(lang)s AND song_list.type=%(type)s)', {'lang': song_lang, 'type': str(list_type)} ] ordering_sql = 'ORDER BY song_list.rank' db_inst = PGClient(db='karaoke') else_sql = '%s %s %s' % ( ordering_sql if ordering_sql else '', 'OFFSET %s' % since if since else '', 'LIMIT %s' % limit if MAX_RESPONSE_ROWS > limit > 0 else 'LIMIT %s' % MAX_RESPONSE_ROWS ) songs, rowcount = db_inst.query( table=table, fields=fields, condition=condition, ret_type='all', else_sql=else_sql ) if not rowcount and karaoke_id: raise RequestError(http_status=404) content = get_karaokes_content(karaokes_row=songs, db_inst=db_inst) return Response(model_data={ 'metadata': songs, 'content': content, 'detail': True if karaoke_id else False })