-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsole.py
131 lines (112 loc) · 4.44 KB
/
console.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
from flask import Flask, request, jsonify, render_template, redirect, Response
from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps
from monitor import AudioMonitor
import configparser
import threading
import logging
app = Flask(__name__)
config_path='config.ini'
config = configparser.ConfigParser()
config.read(config_path)
users = {
config['Security']['username']: generate_password_hash(config['Security']['password'])
}
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
monitor = AudioMonitor(True)
def check_auth(username, password):
return username in users and check_password_hash(users.get(username), password)
def authenticate():
return Response(
'Unauthorized', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'}
)
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
config.read(config_path)
if config['Security']['auth_enabled'] == "false":
return f(*args, **kwargs)
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@app.route('/')
@requires_auth
def home():
config.read(config_path)
profiles = ["Night","Morning"]
if not request.args.get('p') or request.args.get('p') not in profiles:
selected_profile = profiles[0]
else:
selected_profile = request.args.get('p')
error = ""
if request.args.get('e') == "integers":
error="Form values must be positive integers greater than zero"
current_profile = monitor.profile
testing = monitor.testing
return render_template('console.html',
profiles=profiles,
selected_profile=selected_profile,
enabled=monitor.enabled,
threshold=config[selected_profile]['threshold'],
window=config[selected_profile]['window_size'],
cooldown=config[selected_profile]['cooldown_minutes'],
night_start=config['Times']["night_start"],
morning_start=config['Times']["morning_start"],
morning_end=config['Times']["morning_end"],
error=error,
current_profile=current_profile,
testing=testing)
@app.route('/update', methods=['POST'])
@requires_auth
def update_config():
config.read(config_path)
form_data = request.form.to_dict()
try:
for v in form_data.values():
if "-" in v or v == "0":
raise ValueError
config[form_data['profile']]['threshold'] = str(int(form_data['threshold']))
config[form_data['profile']]['window_size'] = str(int(form_data['window']))
config[form_data['profile']]['cooldown_minutes'] = str(int(form_data['cooldown']))
except ValueError:
return redirect('/?e=integers&p='+form_data['profile'])
with open(config_path, 'w') as configfile:
config.write(configfile)
monitor.logger.info("Updated "+form_data['profile']+" profile")
return redirect('/?p='+form_data['profile'])
@app.route('/change-status', methods=['GET'])
@requires_auth
def change_status():
if monitor.enabled:
monitor.enabled = False
else:
monitor.enabled = True
monitor.logger.info("Updated status - enabled: "+str(monitor.enabled))
return redirect('/')
@app.route('/test', methods=['GET'])
@requires_auth
def test_profile():
if not monitor.testing:
if request.args.get('profile') == "Night":
monitor.test_profile("Night")
if request.args.get('profile') == "Morning":
monitor.test_profile("Morning")
monitor.logger.info("Testing "+request.args.get('profile')+" profile")
else:
monitor.test_profile("")
monitor.logger.info("Stopped testing")
return redirect('/?p='+request.args.get('profile'))
@app.route('/average', methods=['GET'])
def get_average():
return jsonify({'average': monitor.get_window_average()}), 200
if __name__ == '__main__':
monitor_thread = threading.Thread(target=monitor.run, daemon=True)
monitor_thread.start()
if config['Security']['tls_enabled'] == "true":
app.run('0.0.0.0',ssl_context=('cert.pem', 'key.pem'))
else:
app.run('0.0.0.0')