generated from nathanwoodburn/python-webserver-template
feat: Add a ton of features to make it better
All checks were successful
Build Docker / BuildImage (push) Successful in 2m15s
All checks were successful
Build Docker / BuildImage (push) Successful in 2m15s
This commit is contained in:
62
server.py
62
server.py
@@ -18,9 +18,24 @@ import dotenv
|
||||
|
||||
dotenv.load_dotenv()
|
||||
|
||||
SPEAKER_NAME = os.getenv("SPEAKER_NAME", "Family Room Speakers")
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
|
||||
def log(message: str):
|
||||
"""
|
||||
Log a message to the server log file.
|
||||
"""
|
||||
log_path = "server.log"
|
||||
if not os.path.exists(log_path):
|
||||
with open(log_path, "w") as f:
|
||||
f.write("")
|
||||
|
||||
with open(log_path, "a") as f:
|
||||
f.write(f"{datetime.now().isoformat()} - {message}\n")
|
||||
print(f"{datetime.now().isoformat()} - {message}") # Also print to console for debugging
|
||||
|
||||
def find(name, path):
|
||||
for root, dirs, files in os.walk(path):
|
||||
if name in files:
|
||||
@@ -85,11 +100,21 @@ def restart():
|
||||
"""
|
||||
# Execute a `pkill spotifyd` command to stop the spotifyd process
|
||||
status = os.system("pkill spotifyd")
|
||||
|
||||
hookPath = os.path.join(os.getcwd(), "song-hook.sh")
|
||||
|
||||
# Clear the server log
|
||||
log_path = "server.log"
|
||||
if os.path.exists(log_path):
|
||||
with open(log_path, "w") as f:
|
||||
f.write("")
|
||||
|
||||
# Start with a new process
|
||||
os.system("spotifyd -d 'Family Room Speakers'")
|
||||
|
||||
|
||||
|
||||
output = os.system(f"spotifyd -d '{SPEAKER_NAME}' --onevent {hookPath}")
|
||||
if output != 0:
|
||||
log("Failed to restart spotifyd")
|
||||
else:
|
||||
log("spotifyd restarted successfully")
|
||||
|
||||
return redirect('/')
|
||||
|
||||
@@ -141,6 +166,35 @@ def api_data():
|
||||
return jsonify(data)
|
||||
|
||||
|
||||
@app.route("/api/v1/logs", methods=["GET"])
|
||||
def api_logs():
|
||||
"""
|
||||
Returns the last 100 lines of the server log.
|
||||
"""
|
||||
log_path = "server.log"
|
||||
|
||||
# Check if the log file exists
|
||||
if not os.path.isfile(log_path):
|
||||
return jsonify({"logs": "Server not running"}), 404
|
||||
|
||||
lines = []
|
||||
try:
|
||||
with open(log_path, "r") as f:
|
||||
lines = f.readlines()[-100:]
|
||||
except Exception as e:
|
||||
lines = [f"Error reading log file: {e}"]
|
||||
return jsonify({"logs": "".join(lines)})
|
||||
|
||||
@app.route("/api/v1/current_track", methods=["GET"])
|
||||
def api_current_track():
|
||||
# If the current_track.json file exists, read it and return its contents
|
||||
if os.path.isfile("current_track.json"):
|
||||
with open("current_track.json", "r") as f:
|
||||
track_data = json.load(f)
|
||||
return jsonify(track_data)
|
||||
else:
|
||||
return jsonify({"error": "No current track data available"}), 404
|
||||
|
||||
# endregion
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user