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)) PluginsMethods.plugin_set_active(name, int(state))
return {"message": "OK"}, 200 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): ) == create_hash(album):
perfect_match = track perfect_match = track
else:
track["saved"] = False
track_id = perfect_match["track_id"] track_id = perfect_match["track_id"]
downloaded = finder.download_lyrics(track_id, filepath) downloaded = finder.download_lyrics(track_id, filepath)

View File

@ -1,5 +1,6 @@
from flask import Blueprint, request 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.db.sqlite.settings import SettingsSQLMethods as sdb
from app.lib import populate from app.lib import populate
from app.lib.watchdogg import Watcher as WatchDog 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.generators import get_random_str
from app.utils.threading import background 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]): def get_child_dirs(parent: str, children: list[str]):
@ -160,6 +161,7 @@ def get_all_settings():
""" """
settings = sdb.get_all_settings() settings = sdb.get_all_settings()
plugins = pdb.get_all_plugins()
key_list = list(mapp.keys()) key_list = list(mapp.keys())
s = {} s = {}
@ -180,6 +182,7 @@ def get_all_settings():
root_dirs = sdb.get_root_dirs() root_dirs = sdb.get_root_dirs()
s["root_dirs"] = root_dirs s["root_dirs"] = root_dirs
s['plugins'] = plugins
return { return {
"settings": s, "settings": s,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,19 +1,20 @@
""" """
Requests related to artists Requests related to artists
""" """
import urllib.parse
import requests import requests
from requests import ConnectionError, HTTPError, ReadTimeout
from app import settings from app import settings
from app.utils.hashing import create_hash from app.utils.hashing import create_hash
from requests import ConnectionError, HTTPError, ReadTimeout
import urllib.parse
def fetch_similar_artists(name: str): def fetch_similar_artists(name: str):
""" """
Fetches similar artists from Last.fm 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: try:
response = requests.get(url, timeout=10) response = requests.get(url, timeout=10)

View File

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

View File

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