mpv_commander/mpv_server.py
2025-04-24 15:28:53 -04:00

91 lines
2.2 KiB
Python

from flask import Flask, request, jsonify, g
from jinja2 import Template
import json
import sys
import sqlite3
disable_all_active = r'''
UPDATE buttons SET is_active = 0
'''
set_active_by_name_sql = r'''
UPDATE buttons SET is_active = 1
WHERE button_name = ?
'''
with open("config.json", "r") as config_file:
config_json = json.loads(config_file.read())
app = Flask(__name__)
def get_db():
db = getattr(g, "_database", None)
if db is None:
db = g._database = sqlite3.connect("mpvcommander.db")
return db
def set_active_by_name(name):
db = get_db()
db.execute(disable_all_active)
db.execute(set_active_by_name, name)
db.commit()
@app.route("/")
def root_route():
with open("index.html", "r") as html_file:
template = Template(html_file.read())
return template.render(config_json), 200
@app.route("/stream", methods=["POST"])
def stream_route():
if request.content_type == 'application/json':
body = request.get_json()
if not "name" in body.keys():
error_response = {
'status': "ERROR",
"reason": "A name must be specified in the body of the request"
}
return jsonify(error_response), 400
resource_list = [element for element in config_json["buttons"] if element["name"] == body["name"]]
if(len(resource_list) == 0):
error_response = {
'status': "ERROR",
"reason": "The name {name} does not exist in config['buttons'], check your config".format(name = body["name"])
}
return jsonify(error_response), 400
db = get_db()
db.execute(disable_all_active)
db.execute(set_active_by_name_sql, [body["name"]])
db.commit()
return jsonify(resource_list[0]), 200
else:
error_response = {
'status': 'ERROR',
'reason': 'Posted body must be of content type application/json'
}
return jsonify(error_response)
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=1801)