diff --git a/database.py b/database.py index 95aa74b..43fc3dd 100644 --- a/database.py +++ b/database.py @@ -12,6 +12,8 @@ SCROBBLES = [] # Format: tuple(track_ref,timestamp,saved) ARTISTS = [] # Format: artist TRACKS = [] # Format: tuple(frozenset(artist_ref,...),title) +lastsync = 0 + # by id #def getScrobbleObject(o): @@ -124,17 +126,21 @@ def post_scrobble(): createScrobble(artists,title,time) + if (time - lastsync) > 3600: + sync() + return "" -@route("/flush") +@route("/sync") def abouttoshutdown(): - flush() + sync() print("Database saved to disk.") #sys.exit() # Starts the server def runserver(DATABASE_PORT): - + global lastsync + lastsync = time = int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp()) #reload() #buildh() build_db() @@ -272,7 +278,7 @@ def reload(): DATABASE.append({"artists":artists,"title":title,"time":time,"saved":True}) # Saves all cached entries to disk -def flush(): +def sync(): for idx in range(len(SCROBBLES)): if not SCROBBLES[idx][2]: @@ -290,6 +296,9 @@ def flush(): SCROBBLES[idx] = (SCROBBLES[idx][0],SCROBBLES[idx][1],True) + global lastsync + lastsync = time = int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp()) + # Queries the database def db_query(artist=None,track=None,since=0,to=9999999999): diff --git a/server.py b/server.py index 71a4421..a8fcad5 100755 --- a/server.py +++ b/server.py @@ -5,6 +5,7 @@ import waitress import urllib.request import urllib.parse import sys +import signal MAIN_PORT = 12345 @@ -35,7 +36,10 @@ def database(pth): @route("/exit") def shutdown(): - urllib.request.urlopen("http://localhost:" + str(DATABASE_PORT) + "/flush") + graceful_exit() + +def graceful_exit(sig=None,frame=None): + urllib.request.urlopen("http://localhost:" + str(DATABASE_PORT) + "/sync") print("Server shutting down...") sys.exit() @@ -46,6 +50,7 @@ def static(pth): return static_file(pth,root="") +signal.signal(signal.SIGINT, graceful_exit) ## start database server _thread.start_new_thread(SourceFileLoader("database","database.py").load_module().runserver,(DATABASE_PORT,))