-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·283 lines (225 loc) · 9.07 KB
/
Copy pathapp.py
File metadata and controls
executable file
·283 lines (225 loc) · 9.07 KB
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
from flask import Flask, request, render_template, make_response, redirect, abort, jsonify
import time
import datetime
import os
import secrets
from common import *
app = Flask(__name__)
settings = ReadSettings()
@app.route('/', methods=['POST','GET'])
def index():
global settings
if (request.method == 'POST'):
response = request.form
if('listorder' in response):
if(response['listorder'] == 'topdown'):
settings['misc']['listorder'] = 'topdown'
else:
settings['misc']['listorder'] = 'bottomup'
WriteSettings(settings)
if('24htime' in response):
if(response['24htime'] == 'true'):
settings['misc']['24htime'] = True
else:
settings['misc']['24htime'] = False
WriteSettings(settings)
return render_template('index.html', pagetheme=settings['misc']['theme'], settings=settings)
@app.route('/status')
def doorstatus():
states = ReadStates()
return render_template('doorstatus.html', state=states['inputs']['switch'])
@app.route('/shortlog')
def shortlog():
global settings
door_history, events = ReadLog(10, twentyfourhtime=settings['misc']['24htime'])
return render_template('shortlog.html', door_history=door_history, events=events, settings=settings)
@app.route('/button')
def button():
states = ReadStates()
states['outputs']['button'] = True # Button pressed - Set state to 'on'
WriteStates(states) # Write button press to file
ipaddress = request.remote_addr
event = 'Button Press from WebUI [' + ipaddress + ']'
WriteLog(event)
return redirect('/')
@app.route('/history', methods=['POST','GET'])
def history():
global settings
if (request.method == 'POST'):
response = request.form
if('listorder' in response):
if(response['listorder'] == 'topdown'):
settings['misc']['listorder'] = 'topdown'
else:
settings['misc']['listorder'] = 'bottomup'
WriteSettings(settings)
if('24htime' in response):
if(response['24htime'] == 'true'):
settings['misc']['24htime'] = True
else:
settings['misc']['24htime'] = False
WriteSettings(settings)
door_history, events = ReadLog(twentyfourhtime=settings['misc']['24htime'])
return render_template('history.html', door_history=door_history, events=events, pagetheme=settings['misc']['theme'], settings=settings)
@app.route('/admin/<action>', methods=['POST','GET'])
@app.route('/admin', methods=['POST','GET'])
def admin(action=None):
states = ReadStates()
global settings
settings = ReadSettings()
if action == 'reboot':
event = "Reboot Requested."
WriteLog(event)
os.system("sleep 3 && sudo reboot &")
#Show Reboot Splash
return render_template('shutdown.html', action=action, pagetheme=settings['misc']['theme'])
if action == 'shutdown':
event = "Shutdown Requested."
WriteLog(event)
os.system("sleep 3 && sudo shutdown -h now &")
#Show Shutdown Splash
return render_template('shutdown.html', action=action, pagetheme=settings['misc']['theme'])
if (request.method == 'POST') and (action == 'settings'):
response = request.form
if('from_email' in response):
if(response['from_email']!=''):
print("from_email: " + response['from_email'])
settings['email']['FromEmail'] = response['from_email']
if('to_email' in response):
if(response['to_email']!=''):
print("to_email: " + response['to_email'])
settings['email']['ToEmail'] = response['to_email']
if('server' in response):
if(response['server']!=''):
print("Server: " + response['server'])
settings['email']['SMTPServer'] = response['server']
if('port' in response):
if(response['port']!=''):
print("Port: " + response['port'])
settings['email']['SMTPPort'] = int(response['port'])
if('username' in response):
if(response['username']!=''):
print("username: " + response['username'])
settings['email']['Username'] = response['username']
if('password' in response):
if(response['password']!=''):
print("password: " + response['password'])
settings['email']['Password'] = response['password']
use_tls = 'use_tls' in response
if(use_tls!=settings['email']['UseTLS']):
print("useTLS: %s" % use_tls)
settings['email']['UseTLS'] = use_tls
if('public_url' in response):
if(response['public_url']!=''):
print("public_url: " + response['public_url'])
settings['misc']['PublicURL'] = response['public_url']
if('timeout' in response):
if(response['timeout']!=''):
print("Timeout: " + response['timeout'])
settings['notification']['minutes'] = int(response['timeout'])
if('reminder' in response):
if(response['reminder']!=''):
print("Reminder: " + response['reminder'])
settings['notification']['reminder'] = int(response['reminder'])
if('iftttapi' in response):
if(response['iftttapi']!=''):
print("IFTTT API Key: " + response['iftttapi'])
settings['ifttt']['APIKey'] = response['iftttapi']
settings['notification']['notify_on_open'] = "off" # Turn off notify_on_open if no response from POST
if('notify_on_open' in response):
if(response['notify_on_open']!=''):
print("Notify on Open: " + response['notify_on_open'])
settings['notification']['notify_on_open'] = response['notify_on_open']
if('pushover_apikey' in response):
if(response['pushover_apikey']!=settings['pushover']['APIKey']):
print("Pushover API key: " + response['pushover_apikey'])
settings['pushover']['APIKey'] = response['pushover_apikey']
if('pushover_userkeys' in response):
if(response['pushover_userkeys']!=settings['pushover']['UserKeys']):
print("Pushover User keys: " + response['pushover_userkeys'])
settings['pushover']['UserKeys'] = response['pushover_userkeys']
if('theme' in response):
print(response['theme'])
settings['misc']['theme'] = response['theme']
if('enable_api' in response):
print(response['enable_api'])
if response['enable_api'] == 'true':
settings['api_config']['enable'] = True
if settings['api_config']['apikey'] == '':
settings['api_config']['apikey'] = gen_api_key(32)
else:
settings['api_config']['enable'] = False
if('gen_api' in response):
print(response['gen_api'])
if response['gen_api'] == 'true':
settings['api_config']['apikey'] = gen_api_key(32)
WriteSettings(settings)
event = "Settings Updated."
WriteLog(event)
uptime = os.popen('uptime').readline()
cpuinfo = os.popen('cat /proc/cpuinfo').readlines()
return render_template('admin.html', action=action, uptime=uptime, cpuinfo=cpuinfo, settings=settings, pagetheme=settings['misc']['theme'])
@app.route('/manifest')
def manifest():
res = make_response(render_template('manifest.json'), 200)
res.headers["Content-Type"] = "text/cache-manifest"
return res
@app.route('/api/<action>', methods=['POST','GET'])
def api(action=None):
global settings
apikey = settings['api_config']['apikey']
doorname = settings['misc']['doorname']
if (settings['api_config']['enable'] == True) and (apikey == action):
if (request.method == 'POST'):
if not request.json:
event = 'Local API Call Failed - Local API interface not enabled.'
WriteLog(event)
abort(400)
else:
if('DoorButton' in request.json):
states = ReadStates()
states['outputs']['button'] = True # Button pressed - Set state to 'on'
WriteStates(states) # Write button press to file
event = f'Local API Call Success. Door button [{doorname}] pressed.'
WriteLog(event)
return jsonify({'result': 'success'}), 201
return jsonify({'result': 'failed'}), 201
if (request.method == 'GET'):
door_output = {}
door_output = {
doorname: {
'id': settings['misc']['id'],
'status': {
'limitsensorclosed': ''
}
}
}
states = ReadStates()
state=states['inputs']['switch']
door_output[doorname]['status']['limitsensorclosed'] = 'open' if state == 1 else 'closed'
event = 'Local API Call Success. [GET]'
WriteLog(event)
return jsonify(door_output), 201
event = 'Local API Call Failed.'
WriteLog(event)
abort(404)
@app.route('/haexample')
def haexample():
global settings
doorname = "Garage Door"
server_ip = request.environ['HTTP_HOST']
#print(request.environ)
site_url_api = f"http://{server_ip}/api/{settings['api_config']['apikey']}"
value_template = "{{ value_json['" + doorname + "']['status']['limitsensorclosed'] }}"
resp = make_response(render_template('ha_example.yaml', site_url_api=site_url_api, value_template=value_template, doorname=doorname))
resp.mimetype = 'text/plain'
return resp
"""
Supporting Functions
"""
# Attribution to Vladimir Ignatyev on Stack Overflow
# https://stackoverflow.com/questions/41969093/how-to-generate-passwords-in-python-2-and-python-3-securely
def gen_api_key(length, charset="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"):
return "".join([secrets.choice(charset) for _ in range(0, length)])
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True) # use ,debug=True for debug mode