100 lines
2.3 KiB
Python
100 lines
2.3 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 = ?
|
|
'''
|
|
|
|
find_buttons_for_group = r'''
|
|
SELECT * FROM buttons
|
|
WHERE page_group = ?
|
|
'''
|
|
|
|
find_groups_for_parent = r'''
|
|
SELECT * FROM groups
|
|
WHERE parent_group = ?
|
|
'''
|
|
|
|
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(config_json["db_name"])
|
|
|
|
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:
|
|
db = get_db()
|
|
|
|
group = request.args.get(key="group", default="Home")
|
|
|
|
template = Template(html_file.read())
|
|
return template.render({
|
|
"instance_name": config_json["instance_name"],
|
|
"current_group": group,
|
|
"buttons": db.execute(find_buttons_for_group, [group]).fetchall(),
|
|
"groups": db.execute(find_groups_for_parent, [group]).fetchall()
|
|
}), 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
|
|
|
|
db = get_db()
|
|
|
|
db.execute(disable_all_active)
|
|
db.execute(set_active_by_name_sql, [body["name"]])
|
|
db.commit()
|
|
|
|
return jsonify(body["name"]), 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)
|
|
|