1
0
mirror of https://github.com/krateng/maloja.git synced 2023-08-10 21:12:55 +03:00

Various Fixes

This commit is contained in:
Krateng 2019-01-09 23:29:01 +01:00
parent bfff37a549
commit 1a3a172089
5 changed files with 26 additions and 91 deletions

View File

@ -2,6 +2,8 @@ import re
import utilities import utilities
# need to do this as a class so it can retain loaded settings from file # need to do this as a class so it can retain loaded settings from file
# apparently this is not true
# I'm dumb
class CleanerAgent: class CleanerAgent:
def __init__(self): def __init__(self):

View File

@ -519,6 +519,7 @@ def issues():
@dbserver.post("/rebuild") @dbserver.post("/rebuild")
def rebuild(): def rebuild():
keys = FormsDict.decode(request.forms)
apikey = keys.pop("key",None) apikey = keys.pop("key",None)
if (checkAPIkey(apikey)): if (checkAPIkey(apikey)):
global db_rulestate global db_rulestate
@ -612,7 +613,7 @@ def sync():
global lastsync global lastsync
lastsync = int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp()) lastsync = int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp())
print("Database saved to disk.") log("Database saved to disk.")

View File

@ -3,6 +3,7 @@
from bottle import Bottle, route, get, post, error, run, template, static_file, request, response, FormsDict from bottle import Bottle, route, get, post, error, run, template, static_file, request, response, FormsDict
from importlib.machinery import SourceFileLoader from importlib.machinery import SourceFileLoader
from htmlgenerators import removeIdentical from htmlgenerators import removeIdentical
from utilities import *
import _thread import _thread
import waitress import waitress
import urllib.request import urllib.request
@ -68,7 +69,7 @@ def shutdown():
def graceful_exit(sig=None,frame=None): def graceful_exit(sig=None,frame=None):
urllib.request.urlopen("http://localhost:" + str(DATABASE_PORT) + "/sync") urllib.request.urlopen("http://localhost:" + str(DATABASE_PORT) + "/sync")
print("Server shutting down...") log("Server shutting down...")
sys.exit() sys.exit()

View File

@ -138,7 +138,10 @@ def addEntries(filename,al):
### Logging ### Logging
def log(msg): def log(msg):
print(msg) import inspect
module = inspect.getmodule(inspect.stack()[1][0]).__name__
if module == "__main__": module = "mainserver"
print("[" + module + "] " + msg)
# best function ever # best function ever
@ -178,16 +181,17 @@ def apirequest(artists=None,artist=None,title=None):
except: except:
pass pass
# if nothing worked, just return the artist image
if len(artists) == 1: if len(artists) == 1:
return {"image":apirequest(artist=artists[0])["image"]} #return {"image":apirequest(artist=artists[0])["image"]}
#return {"image":None,"desc":None} return {"image":None}
# try the same track with every single artist # try the same track with every single artist
for a in artists: for a in artists:
rec = apirequest(artists=[a],title=title) rec = apirequest(artists=[a],title=title)
if rec["image"] is not None: if rec["image"] is not None:
return rec return rec
return {"image":None}
# ARTISTS # ARTISTS
else: else:
@ -202,6 +206,7 @@ def apirequest(artists=None,artist=None,title=None):
return {"image":""} return {"image":""}
# I think I've only just understood modules
cachedTracks = {} cachedTracks = {}
cachedArtists = {} cachedArtists = {}
@ -231,33 +236,13 @@ def getTrackInfo(artists,title):
pass pass
result = apirequest(artists=artists,title=title) result = apirequest(artists=artists,title=title)
cachedTracks[(frozenset(artists),title)] = result["image"] if result.get("image") is not None:
return result cachedTracks[(frozenset(artists),title)] = result["image"]
return result
# with open("apikey","r") as keyfile: else:
# apikey = keyfile.read().replace("\n","") result = getArtistInfo(artist=artists[0])
# cachedTracks[(frozenset(artists),title)] = result["image"]
# return result
# for a in artists:
# try:
# url = "https://ws.audioscrobbler.com/2.0/?method=track.getinfo&track=" + urllib.parse.quote(title) + "&artist=" + urllib.parse.quote(a) + "&api_key=" + apikey + "&format=json"
# response = urllib.request.urlopen(url)
# lastfm_data = json.loads(response.read())
# imgurl = lastfm_data["track"]["album"]["image"][2]["#text"]
# break
# except:
# pass
#
# try:
# return {"image":imgurl}
# except:
# for a in artists:
# try:
# return {"image":getArtistInfo(a)["image"]}
# except:
# pass
#
# return {"image":""}
def getArtistInfo(artist): def getArtistInfo(artist):
import re import re
@ -280,25 +265,7 @@ def getArtistInfo(artist):
imgurl = "/" + filepath + ".jpeg" imgurl = "/" + filepath + ".jpeg"
return {"image":imgurl} return {"image":imgurl}
#check if cached image exists
# elif os.path.exists(filepath_cache + ".png"):
# imgurl = "/" + filepath_cache + ".png"
# elif os.path.exists(filepath_cache + ".jpg"):
# imgurl = "/" + filepath_cache + ".jpg"
# elif os.path.exists(filepath_cache + ".jpeg"):
# imgurl = "/" + filepath_cache + ".jpeg"
# check if custom desc exists
# if os.path.exists(filepath + ".txt"):
# with open(filepath + ".txt","r") as descfile:
# desc = descfile.read().replace("\n","")
#
# #check if cached desc exists
# elif os.path.exists(filepath_cache + ".txt"):
# with open(filepath_cache + ".txt","r") as descfile:
# desc = descfile.read().replace("\n","")
try: try:
return {"image":cachedArtists[artist]} return {"image":cachedArtists[artist]}
except: except:
@ -307,43 +274,6 @@ def getArtistInfo(artist):
result = apirequest(artist=artist) result = apirequest(artist=artist)
cachedArtists[artist] = result["image"] cachedArtists[artist] = result["image"]
return result return result
# # if we neither have a custom image nor a cached version, we return the address from lastfm, but cache that image for later use
# with open("apikey","r") as keyfile:
# apikey = keyfile.read().replace("\n","")
#
#
# try:
# url = "https://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" + urllib.parse.quote(artist) + "&api_key=" + apikey + "&format=json"
# response = urllib.request.urlopen(url)
# lastfm_data = json.loads(response.read())
# try:
# imgurl
# except NameError:
# imgurl = lastfm_data["artist"]["image"][2]["#text"]
# if imgurl == "":
# imgurl = "/info/artists/default.jpg"
# else:
# _thread.start_new_thread(cacheImage,(imgurl,"info/artists_cache",filename))
# try:
# desc
# except NameError:
# desc = lastfm_data["artist"]["bio"]["summary"].split("(1) ")[-1]
# with open(filepath_cache + ".txt","w") as descfile:
# descfile.write(desc)
# # this feels so dirty
#
#
# return {"image":imgurl,"info":desc}
# except:
# return {"image":"/info/artists/default.jpg","info":"No information available"}
#def cacheImage(url,path,filename):
# import urllib.request
# response = urllib.request.urlopen(url)
# target = path + "/" + filename + "." + response.info().get_content_subtype()
# urllib.request.urlretrieve(url,target)

View File

@ -37,7 +37,8 @@ def replacedict(keys,dbport):
elif keys.get("artist") is not None: elif keys.get("artist") is not None:
imgurl = getArtistInfo(keys.get("artist")).get("image") imgurl = getArtistInfo(keys.get("artist")).get("image")
elif (len(scrobbles) != 0): elif (len(scrobbles) != 0):
imgurl = getArtistInfo(scrobbles[0]["artists"][0]).get("image") imgurl = getTrackInfo(scrobbles[0]["artists"],scrobbles[0]["title"]).get("image")
#imgurl = getArtistInfo(scrobbles[0]["artists"][0]).get("image")
else: else:
imgurl = "" imgurl = ""