2019-02-16 22:53:35 +03:00
#!/usr/bin/env python3
import subprocess
import sys
import signal
import os
2019-02-16 23:04:13 +03:00
import stat
2019-03-28 17:54:39 +03:00
from doreah import settings
2019-02-16 22:53:35 +03:00
2018-12-06 15:36:42 +03:00
2018-12-08 02:01:44 +03:00
neededmodules = [
"bottle",
2019-02-16 23:21:29 +03:00
"waitress",
2019-03-31 14:14:41 +03:00
"setproctitle",
"doreah"
2018-12-08 02:01:44 +03:00
]
2018-12-06 15:36:42 +03:00
2019-02-18 02:34:25 +03:00
recommendedmodules = [
"wand"
]
2019-02-16 22:53:35 +03:00
SOURCE_URL = "https://github.com/krateng/maloja/archive/master.zip"
2019-03-28 17:54:39 +03:00
settings.config(files=["settings/default.ini","settings/settings.ini"])
2019-03-28 18:18:31 +03:00
#settings.update("settings/default.ini","settings/settings.ini")
2019-03-28 17:54:39 +03:00
2019-03-04 19:39:21 +03:00
def blue(txt): return "\033[94m" + txt + "\033[0m"
def green(txt): return "\033[92m" + txt + "\033[0m"
def yellow(txt): return "\033[93m" + txt + "\033[0m"
2019-02-22 17:03:38 +03:00
def gotodir():
if os.path.exists("./server.py"):
return True
elif os.path.exists("/opt/maloja/server.py"):
os.chdir("/opt/maloja/")
return True
2019-03-24 15:45:59 +03:00
2019-02-22 17:03:38 +03:00
print("Maloja installation could not be found.")
return False
2019-03-24 15:45:59 +03:00
2019-02-22 17:03:38 +03:00
def setup():
2019-03-24 15:45:59 +03:00
2019-03-28 17:54:39 +03:00
# LASTFM API KEY
key = settings.get_settings("LASTFM_API_KEY")
if key is None:
print("Currently not using an API key for image display. Only local images will be used.")
elif key == "ASK":
2019-03-04 19:39:21 +03:00
print("Please enter your Last.FM API key. If you do not want to display artist and track images, simply leave this empty and press Enter.")
key = input()
2019-03-28 17:54:39 +03:00
if key == "": key = None
2019-03-28 18:18:31 +03:00
settings.update_settings("settings/settings.ini",{"LASTFM_API_KEY":key},create_new=True)
2019-03-28 17:54:39 +03:00
else:
print("Last.FM API key found.")
# if os.path.exists("./apikey"):
# with open("apikey","r") as keyfile:
# apikey = keyfile.read().replace("\n","")
#
# if apikey == "NONE": print("Currently not using an API key for image display. Only local images will be used.")
# else:
# print("Please enter your Last.FM API key. If you do not want to display artist and track images, simply leave this empty and press Enter.")
# key = input()
# if key == "": key = "NONE"
# with open("apikey","w") as keyfile:
# keyfile.write(key)
2019-03-24 15:45:59 +03:00
2019-03-04 19:39:21 +03:00
# OWN API KEY
if os.path.exists("./clients/authenticated_machines.tsv"):
pass
else:
print("Do you want to set up a key to enable scrobbling? Your scrobble extension needs that key so that only you can scrobble tracks to your database. [Y/n]")
answer = input()
if answer.lower() in ["y","yes","yea","1","positive","true",""]:
import random
key = ""
for i in range(64):
key += str(random.choice(list(range(10)) + list("abcdefghijklmnopqrstuvwxyz") + list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")))
print("Your API Key: " + yellow(key))
with open("./clients/authenticated_machines.tsv","w") as keyfile:
keyfile.write(key + "\n" + "Default Generated Key")
elif answer.lower() in ["n","no","nay","0","negative","false"]:
pass
#file is generated my server itself if not found
2019-02-16 22:53:35 +03:00
def install():
toinstall = []
2019-02-18 02:34:25 +03:00
toinstallr = []
2019-02-16 22:53:35 +03:00
for m in neededmodules:
try:
exec("import " + m) #I'm sorry
except:
toinstall.append(m)
2019-03-24 15:45:59 +03:00
2019-02-18 02:34:25 +03:00
for m in recommendedmodules:
try:
exec("import " + m)
except:
toinstallr.append(m)
2019-03-24 15:45:59 +03:00
2019-02-16 22:53:35 +03:00
if toinstall != []:
print("The following python modules need to be installed:")
for m in toinstall:
print("\t" + m)
2019-02-18 02:34:25 +03:00
if toinstallr != []:
print("The following python modules are highly recommended, some features will not work without them:")
for m in toinstallr:
print("\t" + m)
2019-03-24 15:45:59 +03:00
2019-02-18 02:34:25 +03:00
if toinstall != [] or toinstallr != []:
if os.geteuid() != 0:
print("Installing python modules should be fairly straight-forward, but Maloja can try to install \
them automatically. For this, you need to run this script as a root user.")
return False
else:
print("Installing python modules should be fairly straight-forward, but Maloja can try to install \
them automatically, This might or might not work / bloat your system / cause a nuclear war.")
fail = False
if toinstall != []:
print("Attempt to install required modules? [Y/n]")
answer = input()
2019-03-24 15:45:59 +03:00
2019-03-04 19:39:21 +03:00
if answer.lower() in ["y","yes","yea","1","positive","true",""]:
2019-02-18 02:34:25 +03:00
for m in neededmodules:
try:
print("Installing " + m + " with pip...")
import pip
#os.system("pip3 install " + m)
pip.main(["install",m])
print("Success!")
except:
print("Failure!")
fail = True
2019-03-24 15:45:59 +03:00
2019-02-18 02:34:25 +03:00
elif answer.lower() in ["n","no","nay","0","negative","false"]:
return False #if you dont want to auto install required, you probably dont want to install recommended
else:
print("What?")
return False
2019-03-24 15:45:59 +03:00
if toinstallr != []:
2019-02-18 02:34:25 +03:00
print("Attempt to install recommended modules? [Y/n]")
answer = input()
2019-03-24 15:45:59 +03:00
2019-02-18 02:34:25 +03:00
if answer.lower() in ["y","yes","yea","1","positive","true",""]:
for m in recommendedmodules:
try:
print("Installing " + m + " with pip...")
import pip
#os.system("pip3 install " + m)
pip.main(["install",m])
print("Success!")
except:
print("Failure!")
fail = True
2019-03-24 15:45:59 +03:00
2019-02-18 02:34:25 +03:00
elif answer.lower() in ["n","no","nay","0","negative","false"]:
return False
else:
print("What?")
return False
2019-03-24 15:45:59 +03:00
2019-02-18 02:34:25 +03:00
if fail: return False
print("All modules successfully installed!")
return True
2019-03-24 15:45:59 +03:00
2019-02-18 02:34:25 +03:00
else:
print("All necessary modules seem to be installed.")
return True
2019-02-16 22:53:35 +03:00
def getInstance():
try:
output = subprocess.check_output(["pidof","Maloja"])
pid = int(output)
return pid
except:
return None
2019-03-24 15:45:59 +03:00
2019-02-16 22:53:35 +03:00
def start():
2019-02-18 02:34:25 +03:00
if install():
2019-03-24 15:45:59 +03:00
2019-02-22 17:03:38 +03:00
if gotodir():
2019-03-04 19:39:21 +03:00
setup()
2019-02-18 02:34:25 +03:00
p = subprocess.Popen(["python3","server.py"],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
2019-03-04 19:39:21 +03:00
print(green("Maloja started!") + " PID: " + str(p.pid))
2019-03-24 15:45:59 +03:00
2019-03-29 23:02:27 +03:00
port = settings.get_settings("WEB_PORT")
print("Visit your server address (Port " + str(port) + ") to see your web interface. Visit /setup to get started.")
2019-03-04 19:39:21 +03:00
print("If you're installing this on your local machine, these links should get you there:")
2019-03-29 23:02:27 +03:00
print("\t" + blue("http://localhost:" + str(port)))
print("\t" + blue("http://localhost:" + str(port) + "/setup"))
2019-02-18 02:34:25 +03:00
return True
2019-02-22 17:03:38 +03:00
#else:
# os.chdir("/opt/maloja/")
# p = subprocess.Popen(["python3","server.py"],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
# print("Maloja started! PID: " + str(p.pid))
# return True
2019-03-24 15:45:59 +03:00
2019-02-22 17:03:38 +03:00
print("Error while starting Maloja.")
return False
2019-03-24 15:45:59 +03:00
2019-02-16 22:53:35 +03:00
def restart():
#pid = getInstance()
#if pid == None:
# print("Server is not running.")
#else:
# stop()
#start()
2019-03-24 15:45:59 +03:00
2019-02-16 22:53:35 +03:00
wasrunning = stop()
start()
return wasrunning
2019-03-24 15:45:59 +03:00
2019-02-16 22:53:35 +03:00
def stop():
pid = getInstance()
if pid == None:
print("Server is not running")
return False
else:
os.kill(pid,signal.SIGTERM)
2019-02-18 02:34:25 +03:00
print("Maloja stopped! PID: " + str(pid))
2019-02-16 22:53:35 +03:00
return True
def update():
import urllib.request
import shutil
2019-02-18 18:45:36 +03:00
#import tempfile
2019-02-16 22:53:35 +03:00
import zipfile
import distutils.dir_util
2019-02-22 17:03:38 +03:00
if not gotodir(): return False
2019-02-16 22:53:35 +03:00
print("Updating Maloja...")
2019-02-18 18:45:36 +03:00
#with urllib.request.urlopen(SOURCE_URL) as response:
# with tempfile.NamedTemporaryFile(delete=True) as tmpfile:
# shutil.copyfileobj(response,tmpfile)
2019-03-24 15:45:59 +03:00
#
2019-02-18 18:45:36 +03:00
# with zipfile.ZipFile(tmpfile.name,"r") as z:
2019-03-24 15:45:59 +03:00
#
2019-02-18 18:45:36 +03:00
# for f in z.namelist():
# #print("extracting " + f)
# z.extract(f)
2019-03-24 15:45:59 +03:00
2019-02-18 18:45:36 +03:00
os.system("wget " + SOURCE_URL)
2019-02-18 19:22:44 +03:00
with zipfile.ZipFile("./master.zip","r") as z:
2019-03-24 15:45:59 +03:00
# if we ever have a separate directory for the code
# (the calling update script is not the same version as the current
# remote repository, so we better add this check just in case)
if "source/" in z.namelist():
for f in z.namelist():
if f.startswith("source/"):
z.extract(f)
for dir,_,files in os.walk("source"):
for f in files:
origfile = os.path.join(dir,f)
newfile = ps.path.join(dir[7:],f)
os.renames(origfile,newfile) #also prunes empty directory
else:
for f in z.namelist():
z.extract(f)
2019-02-18 19:22:44 +03:00
os.remove("./master.zip")
2019-03-24 15:45:59 +03:00
2019-02-16 22:53:35 +03:00
distutils.dir_util.copy_tree("./maloja-master/","./",verbose=2)
shutil.rmtree("./maloja-master")
print("Done!")
2019-03-24 15:45:59 +03:00
2019-02-16 23:04:13 +03:00
os.chmod("./maloja",os.stat("./maloja").st_mode | stat.S_IXUSR)
2019-03-24 15:45:59 +03:00
2019-02-16 22:53:35 +03:00
if stop(): start() #stop returns whether it was running before, in which case we restart it
2019-03-24 15:45:59 +03:00
2019-03-07 02:31:23 +03:00
def loadlastfm():
try:
filename = sys.argv[2]
filename = os.path.abspath(filename)
except:
print("Please specify a file!")
return
2019-03-24 15:45:59 +03:00
if gotodir():
2019-03-07 02:31:23 +03:00
if os.path.exists("./scrobbles/lastfmimport.tsv"):
print("Already imported Last.FM data. Overwrite? [y/N]")
if input().lower() in ["y","yes","yea","1","positive","true"]:
pass
else:
return
print("Please wait...")
os.system("python3 ./lastfmconverter.py " + filename + " ./scrobbles/lastfmimport.tsv")
print("Successfully imported your Last.FM scrobbles!")
2019-03-24 15:45:59 +03:00
2019-02-16 22:53:35 +03:00
if __name__ == "__main__":
2019-03-04 19:39:21 +03:00
if sys.argv[1] == "start": restart()
2019-02-16 22:53:35 +03:00
elif sys.argv[1] == "restart": restart()
elif sys.argv[1] == "stop": stop()
elif sys.argv[1] == "update": update()
2019-03-07 02:31:23 +03:00
elif sys.argv[1] == "import": loadlastfm()
2019-02-18 02:34:25 +03:00
else: print("Valid commands: start restart stop update")