diff --git a/frontends/ycdl_flask/ycdl_flask/ycdl_flask.py b/frontends/ycdl_flask/ycdl_flask/ycdl_flask.py index 948b223..a98b72d 100644 --- a/frontends/ycdl_flask/ycdl_flask/ycdl_flask.py +++ b/frontends/ycdl_flask/ycdl_flask/ycdl_flask.py @@ -156,16 +156,22 @@ def get_channel(channel_id=None, download_filter=None): else: channel = None - videos = ycdldb.get_videos(channel_id=channel_id, download_filter=download_filter) - - 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)] + orderby = request.args.get('orderby', None) video_id = request.args.get('v', '') if video_id: ycdldb.insert_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) if limit is not None: diff --git a/ycdl/ycdldb.py b/ycdl/ycdldb.py index fe61b63..11e037b 100644 --- a/ycdl/ycdldb.py +++ b/ycdl/ycdldb.py @@ -222,8 +222,10 @@ class YCDLDB: video = {key: video[SQL_VIDEO[key]] for key in SQL_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 = [] + orderbys = [] + bindings = [] if channel_id is not None: wheres.append('author_id') @@ -235,18 +237,30 @@ class YCDLDB: if wheres: wheres = [x + ' == ?' for x in wheres] - wheres = ' WHERE ' + ' AND '.join(wheres) + wheres = ' AND '.join(wheres) + wheres = ' WHERE ' + wheres else: 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) videos = self.cur.fetchall() if not videos: return [] 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 def insert_video(self, video, *, add_channel=True, commit=True):