From c0a1415eaea2287607a7f812c6a2781fbfd2d992 Mon Sep 17 00:00:00 2001 From: dsc Date: Wed, 4 Aug 2021 18:53:56 +0200 Subject: [PATCH] Add JSON API for searches. Introduces new settings.py config option 'enable_search_route' --- ircradio/routes.py | 48 ++++++++++++++++++++++++++++++++++++++++++++- settings.py_example | 2 ++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/ircradio/routes.py b/ircradio/routes.py index 6a212fb..0a4fd09 100644 --- a/ircradio/routes.py +++ b/ircradio/routes.py @@ -3,7 +3,7 @@ from datetime import datetime from typing import Tuple, Optional -from quart import request, render_template, abort +from quart import request, render_template, abort, jsonify import settings from ircradio.factory import app @@ -39,6 +39,52 @@ async def history(): return data +@app.route("/search") +async def search(): + # search json api endpoint + # e.g: /search?name=test&limit=5&offset=0 + if not settings.enable_search_route: + abort(404) + + from ircradio.models import Song + name = request.args.get("name") + limit = request.args.get("limit", '20') + offset = request.args.get("offset", '0') + + try: + limit = int(limit) + offset = int(offset) + except: + limit = 50 + offset = 0 + + if not name or len(name) <= 2: + abort(404) + + if limit > 50: + limit = 50 + + name = f"%{name}%" + + try: + q = Song.select() + q = q.where((Song.added_by ** name) | (Song.title ** name)) + q = q.order_by(Song.date_added.desc()) + q = q.limit(limit).offset(offset) + results = [{ + "added_by": s.added_by, + "karma": s.karma, + "id": s.id, + "title": s.title, + "utube_id": s.utube_id, + "date_added": s.date_added.strftime("%Y-%m-%d") + } for s in q] + except: + return jsonify([]) + + return jsonify(results) + + @app.route("/library") async def user_library(): from ircradio.models import Song diff --git a/settings.py_example b/settings.py_example index 5a07bfe..6adff01 100644 --- a/settings.py_example +++ b/settings.py_example @@ -16,6 +16,8 @@ timezone = "Europe/Amsterdam" dir_music = os.environ.get("DIR_MUSIC", os.path.join(cwd, "data", "music")) +enable_search_route = bool_env(os.environ.get("ENABLE_SEARCH_ROUTE", False)) + irc_admins_nicknames = ["dsc_"] irc_host = os.environ.get('IRC_HOST', 'localhost') irc_port = int(os.environ.get('IRC_PORT', 6667))