Add ?orderby url parameter.

This commit is contained in:
voussoir 2020-03-11 18:02:09 -07:00
parent 672abf9d86
commit b5f892d595
2 changed files with 29 additions and 9 deletions

View file

@ -156,16 +156,22 @@ def get_channel(channel_id=None, download_filter=None):
else: else:
channel = None channel = None
videos = ycdldb.get_videos(channel_id=channel_id, download_filter=download_filter) orderby = request.args.get('orderby', None)
search_terms = request.args.get('q', '').lower().strip().replace('+', ' ').split()
if search_terms:
videos = [v for v in videos if all(term in v['title'].lower() for term in search_terms)]
video_id = request.args.get('v', '') video_id = request.args.get('v', '')
if video_id: if video_id:
ycdldb.insert_video(video_id) ycdldb.insert_video(video_id)
videos = [ycdldb.get_video(video_id)] videos = [ycdldb.get_video(video_id)]
else:
videos = ycdldb.get_videos(
channel_id=channel_id,
download_filter=download_filter,
orderby=orderby,
)
search_terms = request.args.get('q', '').lower().strip().replace('+', ' ').split()
if search_terms:
videos = [v for v in videos if all(term in v['title'].lower() for term in search_terms)]
limit = request.args.get('limit', None) limit = request.args.get('limit', None)
if limit is not None: if limit is not None:

View file

@ -222,8 +222,10 @@ class YCDLDB:
video = {key: video[SQL_VIDEO[key]] for key in SQL_VIDEO} video = {key: video[SQL_VIDEO[key]] for key in SQL_VIDEO}
return video return video
def get_videos(self, channel_id=None, download_filter=None): def get_videos(self, channel_id=None, *, download_filter=None, orderby=None):
wheres = [] wheres = []
orderbys = []
bindings = [] bindings = []
if channel_id is not None: if channel_id is not None:
wheres.append('author_id') wheres.append('author_id')
@ -235,18 +237,30 @@ class YCDLDB:
if wheres: if wheres:
wheres = [x + ' == ?' for x in wheres] wheres = [x + ' == ?' for x in wheres]
wheres = ' WHERE ' + ' AND '.join(wheres) wheres = ' AND '.join(wheres)
wheres = ' WHERE ' + wheres
else: else:
wheres = '' wheres = ''
query = 'SELECT * FROM videos' + wheres if orderby is not None:
orderby = orderby.lower()
if orderby == 'random':
orderby = 'random()'
if orderby in ['views', 'duration', 'random()']:
orderbys.append(f'{orderby} DESC')
orderbys.append('published DESC')
if orderbys:
orderbys = ', '.join(orderbys)
orderbys = ' ORDER BY ' + orderbys
query = 'SELECT * FROM videos' + wheres + orderbys
self.cur.execute(query, bindings) self.cur.execute(query, bindings)
videos = self.cur.fetchall() videos = self.cur.fetchall()
if not videos: if not videos:
return [] return []
videos = [{key: video[SQL_VIDEO[key]] for key in SQL_VIDEO} for video in videos] videos = [{key: video[SQL_VIDEO[key]] for key in SQL_VIDEO} for video in videos]
videos.sort(key=lambda x: x['published'], reverse=True)
return videos return videos
def insert_video(self, video, *, add_channel=True, commit=True): def insert_video(self, video, *, add_channel=True, commit=True):