handle new env vars during build

+ misc
This commit is contained in:
mungai-njoroge 2023-11-08 00:07:55 +03:00
parent de5b2a53b1
commit 89b05ff80c
11 changed files with 63 additions and 36 deletions

View File

@ -24,3 +24,19 @@ def activate_deactivate_plugin():
PluginsMethods.plugin_set_active(name, int(state))
return {"message": "OK"}, 200
@api.route("/settings", methods=["POST"])
def update_plugin_settings():
data = request.get_json()
plugin = data.get("plugin", None)
settings = data.get("settings", None)
if not plugin or not settings:
return {"error": "Missing plugin or settings"}, 400
PluginsMethods.update_plugin_settings(plugin_name=plugin, settings=settings)
plugin = PluginsMethods.get_plugin_by_name(plugin)
return {"status": "success", "settings": plugin.settings}

View File

@ -33,9 +33,6 @@ def search_lyrics():
) == create_hash(album):
perfect_match = track
else:
track["saved"] = False
track_id = perfect_match["track_id"]
downloaded = finder.download_lyrics(track_id, filepath)

View File

@ -1,5 +1,6 @@
from flask import Blueprint, request
from app.db.sqlite.plugins import PluginsMethods as pdb
from app.db.sqlite.settings import SettingsSQLMethods as sdb
from app.lib import populate
from app.lib.watchdogg import Watcher as WatchDog
@ -11,7 +12,7 @@ from app.store.tracks import TrackStore
from app.utils.generators import get_random_str
from app.utils.threading import background
api = Blueprint("settings", __name__, url_prefix="/")
api = Blueprint("settings", __name__, url_prefix="")
def get_child_dirs(parent: str, children: list[str]):
@ -160,6 +161,7 @@ def get_all_settings():
"""
settings = sdb.get_all_settings()
plugins = pdb.get_all_plugins()
key_list = list(mapp.keys())
s = {}
@ -180,6 +182,7 @@ def get_all_settings():
root_dirs = sdb.get_root_dirs()
s["root_dirs"] = root_dirs
s['plugins'] = plugins
return {
"settings": s,

View File

@ -43,24 +43,28 @@ class HandleArgs:
print("https://www.youtube.com/watch?v=wZv62ShoStY")
sys.exit(0)
lastfm_key = settings.Keys.LASTFM_API
posthog_key = settings.Keys.POSTHOG_API_KEY
config_keys = [
"LASTFM_API_KEY",
"POSTHOG_API_KEY",
"PLUGIN_LYRICS_AUTHORITY",
"PLUGIN_LYRICS_ROOT_URL",
]
if not lastfm_key:
log.error("ERROR: LASTFM_API_KEY not set in environment")
sys.exit(0)
lines = []
if not posthog_key:
log.error("ERROR: POSTHOG_API_KEY not set in environment")
sys.exit(0)
for key in config_keys:
value = settings.Keys.get(key)
if not value:
log.error(f"ERROR: {key} not set in environment")
sys.exit(0)
lines.append(f'{key} = "{value}"\n')
try:
with open("./app/configs.py", "w", encoding="utf-8") as file:
# copy the api keys to the config file
line1 = f'LASTFM_API_KEY = "{lastfm_key}"\n'
line2 = f'POSTHOG_API_KEY = "{posthog_key}"\n'
file.write(line1)
file.write(line2)
file.writelines(lines)
_s = ";" if is_windows() else ":"
@ -80,10 +84,8 @@ class HandleArgs:
finally:
# revert and remove the api keys for dev mode
with open("./app/configs.py", "w", encoding="utf-8") as file:
line1 = "LASTFM_API_KEY = ''\n"
line2 = "POSTHOG_API_KEY = ''\n"
file.write(line1)
file.write(line2)
lines = [f'{key} = ""\n' for key in config_keys]
file.writelines(lines)
sys.exit(0)

View File

@ -1,4 +1,4 @@
LASTFM_API_KEY = ''
POSTHOG_API_KEY = ''
LASTFM_API_KEY = ""
POSTHOG_API_KEY = ""
PLUGIN_LYRICS_AUTHORITY = ""
PLUGIN_LYRICS_ROOT_URL = ""
PLUGIN_LYRICS_ROOT_URL = ""

View File

@ -1,6 +1,7 @@
import json
from app.models.plugins import Plugin
from ..utils import SQLiteManager
@ -48,7 +49,7 @@ class PluginsMethods:
name="lyrics_finder",
description="Find lyrics from the internet",
active=False,
settings={},
settings={"auto_download": False},
)
cls.insert_plugin(plugin)
@ -70,11 +71,12 @@ class PluginsMethods:
cur.execute("UPDATE plugins SET active=? WHERE name=?", (state, name))
cur.close()
def update_plugin_settings(self, plugin: Plugin):
@classmethod
def update_plugin_settings(cls, plugin_name: str, settings: dict):
with SQLiteManager(userdata_db=True) as cur:
cur.execute(
"UPDATE plugins SET settings=? WHERE name=?",
(json.dumps(plugin.settings), plugin.name),
(json.dumps(settings), plugin_name),
)
cur.close()

View File

@ -44,7 +44,7 @@ CREATE TABLE IF NOT EXISTS lastfm_similar_artists (
CREATE TABLE IF NOT EXISTS plugins (
id integer PRIMARY KEY,
name text NOT NULL,
name text NOT NULL UNIQUE,
description text NOT NULL,
active integer NOT NULL DEFAULT 0,
settings text

View File

@ -143,7 +143,6 @@ class LyricsProvider(LRCProvider):
res = self._get(
"track.search",
[
("q_track_artist", f"{title} {artist}"),
("q_track", title),
("q_artist", artist),
("page_size", "5"),
@ -159,7 +158,10 @@ class LyricsProvider(LRCProvider):
except AttributeError:
return []
tracks = body["track_list"]
try:
tracks = body["track_list"]
except TypeError:
return []
return [
{

View File

@ -1,19 +1,20 @@
"""
Requests related to artists
"""
import urllib.parse
import requests
from requests import ConnectionError, HTTPError, ReadTimeout
from app import settings
from app.utils.hashing import create_hash
from requests import ConnectionError, HTTPError, ReadTimeout
import urllib.parse
def fetch_similar_artists(name: str):
"""
Fetches similar artists from Last.fm
"""
url = f"https://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist={urllib.parse.quote_plus(name, safe='')}&api_key={settings.Keys.LASTFM_API}&format=json&limit=250"
url = f"https://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist={urllib.parse.quote_plus(name, safe='')}&api_key={settings.Keys.LASTFM_API_KEY}&format=json&limit=250"
try:
response = requests.get(url, timeout=10)

View File

@ -239,7 +239,7 @@ class TCOLOR:
class Keys:
# get last fm api key from os environment
LASTFM_API = os.environ.get("LASTFM_API_KEY")
LASTFM_API_KEY = os.environ.get("LASTFM_API_KEY")
POSTHOG_API_KEY = os.environ.get("POSTHOG_API_KEY")
PLUGIN_LYRICS_AUTHORITY = os.environ.get("PLUGIN_LYRICS_AUTHORITY")
PLUGIN_LYRICS_ROOT_URL = os.environ.get("PLUGIN_LYRICS_ROOT_URL")
@ -247,13 +247,17 @@ class Keys:
@classmethod
def load(cls):
if IS_BUILD:
cls.LASTFM_API = configs.LASTFM_API_KEY
cls.LASTFM_API_KEY = configs.LASTFM_API_KEY
cls.POSTHOG_API_KEY = configs.POSTHOG_API_KEY
cls.verify_keys()
@classmethod
def verify_keys(cls):
if not cls.LASTFM_API:
if not cls.LASTFM_API_KEY:
print("ERROR: LASTFM_API_KEY not set in environment")
sys.exit(0)
@classmethod
def get(cls, key: str):
return getattr(cls, key, None)

View File

@ -72,7 +72,6 @@ def serve_client():
@background
def bg_run_setup() -> None:
run_setup()
run_periodic_scans()
@ -90,6 +89,7 @@ def run_swingmusic():
Keys.load()
HandleArgs()
log_startup_info()
run_setup()
bg_run_setup()
register_plugins()