-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.py
More file actions
522 lines (412 loc) · 14.9 KB
/
Server.py
File metadata and controls
522 lines (412 loc) · 14.9 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import base64
import collections
import datetime
import json
import multiprocessing
import os
import shutil
import time
# import RPi.GPIO as GPIO
import pigpio
from threading import Timer
from warnings import warn
import cv2
import base64
import flask
from flask import Flask, render_template, send_file, request, redirect, url_for, jsonify, Response
from flask_restful import Api, Resource
from waitress import serve
from VideoScrapper import VideoScrapperModule as module_bp
from Basic_Light import LightStrip
path = os.path.dirname(os.path.realpath(__file__))
light_strip = LightStrip()
display = False
try:
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_BRIGHTNESS, 60)
cap.set(cv2.CAP_PROP_CONTRAST, 14)
cap.set(cv2.CAP_PROP_SATURATION, 15)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
nocam = False
except Exception as e:
nocam = True
warn("Camera has not been loaded. Either because it is not connected or something else.")
"""
# setup interrupt to have a light switch
button_pin = 9
GPIO.setmode(GPIO.BCM)
def light_switch(x):
print(x)
print("hi")
if light_strip.on:
light_strip.setBrightness(0)
light_strip.showAll({"all": [0, 0, 0, 0]})
else:
light_strip.showAll({"all": [50, 20, 0, 255]})
light_strip.setBrightness(255)
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(button_pin, GPIO.BOTH, callback=light_switch bouncetime=50)
"""
# TODO push to github
pi = pigpio.pi()
if not pi.connected:
warn("GPIO not connected, some features may not work properly.")
button_pin = 9
pi.set_mode(button_pin, pigpio.INPUT)
pi.set_pull_up_down(button_pin, pigpio.PUD_DOWN)
def light_switch(gpio, level, tick):
if level == pigpio.TIMEOUT:
return
if light_strip.on:
light_strip.setBrightness(0)
light_strip.showAll({"all": [0, 0, 0, 0]})
else:
light_strip.showAll({"all": [50, 20, 0, 255]})
light_strip.setBrightness(255)
pi.set_glitch_filter(button_pin, 100000)
cb = pi.callback(button_pin, pigpio.EITHER_EDGE, light_switch)
with open(path + '/assets/settings/settings.json', 'r') as fp:
settings = json.load(fp)
server_ip = settings['IP']
timer = {}
# logged_in of the form {ip: user, ...}
logged_in = {}
with open(path + '/assets/settings/saved_users.json', 'r') as fp:
users = json.load(fp)
for ip in users['ip_address'].keys():
if users['ip_address'][ip]['keep_login']:
logged_in[ip] = users['ip_address'][ip]['user']
# Init app, flask, ...
app = Flask(__name__)
app.register_blueprint(module_bp("/media/Series"), url_prefix="/VideoScrapper")
api = Api(app)
planning = {}
def show_from_dict(data, t=None):
if 'alpha' in data:
light_strip.setBrightness(int(data['alpha']))
if 'color' in data:
light_strip.showAll(data['color'])
if t is not None:
del_from_planning(t)
def show_steps(data, t=None):
if 'steps' in data:
light_strip.progressive(data)
if t is not None:
del_from_planning(t)
def dump_to_planning(time, data, save=True):
if time in planning:
planning[time][0].cancel()
if time == "now":
func = show_steps if 'steps' in data else show_from_dict
func(data, time)
return
date_time = datetime.datetime.strptime(time, '%d/%m/%Y %H:%M:%S')
seconds = (date_time - datetime.datetime.now()).total_seconds()
if seconds <= 0:
return
func = show_steps if 'steps' in data else show_from_dict
t = Timer(seconds, func, (data, time))
t.start()
planning[time] = [t, data]
if save:
with open(path + '/assets/settings/timer.json', 'w') as fp:
json.dump(planning, fp, default=lambda a: str(a), indent=4, separators=(',', ': '))
def load_from_planning():
if not os.path.isfile(path + '/assets/settings/timer.json'):
with open(path + '/assets/settings/timer.json', 'w') as fp:
plan = {}
json.dump(plan, fp, default=lambda a: str(a), indent=4, separators=(',', ': '))
else:
with open(path + '/assets/settings/timer.json', 'r') as fp:
plan = json.load(fp)
for k, v in plan.items():
dump_to_planning(k, v[1], False)
def del_from_planning(time):
if time not in planning:
return 404
planning[time][0].cancel()
del planning[time]
with open(path + '/assets/settings/timer.json', 'w') as fp:
json.dump(planning, fp, default=lambda a: str(a), indent=4, separators=(',', ': '))
return 202
def get_dir_size(dir):
size = 0
for f in os.listdir(dir):
size += 1
return f'{size} items'
def sizeof_fmt(num, suffix="b"):
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if abs(num) < 1000.0:
return f"{num:3.1f}".rstrip('0').rstrip('.') + f" {unit}{suffix}"
num /= 1000.0
return f"{num:.1f}".removesuffix('0').removesuffix('.') + f"{suffix}"
def change_address(ip, user, keep_login):
global users
with open(path + '/assets/settings/saved_users.json', 'r') as fp:
users = json.load(fp)
users['ip_address'][ip] = {"user": user, "keep_login": keep_login}
with open(path + '/assets/settings/saved_users.json', 'w') as fp:
json.dump(users, fp, indent=4, separators=(',', ': '))
@app.route('/login')
@app.route('/login/<string:endpoint>')
def login(endpoint='/'):
return render_template('login.html', endpoint=endpoint)
@app.route('/')
def home():
ip = request.remote_addr
if ip not in list(timer.keys()):
timer[ip] = 0
return render_template('home.html', connect_time=timer[ip])
def gen():
"""Video streaming generator function."""
while True:
frame = cap.read()[1]
frame = cv2.imencode('.jpg', frame)[1]
frame = frame.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
@app.route('/camera')
def camera():
if nocam:
return
return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/discord')
def discord():
return render_template('discord.html')
@app.route('/lights')
def lights():
return render_template('lights.html')
@app.route('/file_explorer')
def file_explorer():
return render_template('file_explorer.html')
@app.route('/favicon.ico')
def favicon():
return redirect(url_for('static', filename='/images/favicon.ico'))
@app.before_request
def redirection():
ip = request.remote_addr
if request.endpoint != 'login' \
and ip not in list(logged_in.keys()) \
and '/static/' not in request.path \
and '/api/' not in request.path:
return render_template(f'login.html', endpoint=request.path)
class Auth(Resource):
def get(self, user: str, mp, keep):
user = user.rstrip()
if user in users['users'].keys() and users['users'][user] == mp:
logged_in[request.remote_addr] = user
change_address(request.remote_addr, user, (keep == '1'))
return True
else:
return False
class Logout(Resource):
def get(self):
logged_in.pop(request.remote_addr)
print(logged_in)
class KeepLogin(Resource):
def get(self):
if not request.remote_addr in users['ip_address']:
return False
return users['ip_address'][request.remote_addr]['keep_login']
class AddTime(Resource):
def get(self):
ip = request.remote_addr
timer[ip] += 1
return timer[ip]
class SubTime(Resource):
def get(self):
ip = request.remote_addr
timer[ip] -= 1
return timer[ip]
class Webcam(Resource):
def get(self):
url = path + '/static/images/webcam0.jpeg'
ret, frame = cap.read()
cv2.imwrite(url, frame)
return send_file(url)
class DiscordRestart(Resource):
def get(self):
pass
class DiscordDisplay(Resource):
def get(self):
pass
"""
{
'time': dd/mm/yy h:m:s,
'color': {'1': [r, g, b, w], 'all': [r, g, b, w]},
'alpha': alpha
'steps':{
"data": {"color": {"all": [r, g, b, w]}, "alpha": alpha}
},
{
"time": 10,
"data": {"color": {"all": [r, g, b, w]}, "alpha": alpha}
},
}
}
"""
class LightColor(Resource):
def put(self):
dict = request.get_json(force=True)
data = {k: v for k, v in dict.items() if k in ['alpha', 'color', 'steps']}
if 'time' not in dict:
show_from_dict(data)
else:
time = dict['time']
dump_to_planning(time, data)
return dict
def get(self):
return {
'alpha': light_strip.LED_BRIGHTNESS,
'color': light_strip.get_color(),
'END_LED': light_strip.END_LED,
'START_LED': light_strip.START_LED,
}
class LightProgressive(Resource):
def put(self):
dict = request.get_json(force=True)
light_strip.progressive(dict)
class LightRainbow(Resource):
def put(self, speed=50):
light_strip.rainbow(speed)
class LightFlashRainbow(Resource):
def put(self, speed=50):
light_strip.flash_rainbow(speed)
class LightStrobe(Resource):
def put(self, speed=50):
light_strip.strobe(speed)
class LightTimer(Resource):
"""
accessible through: api/lights/timer
"""
def get(self):
return {"Timers": list(planning.keys())}
def delete(self):
dict = request.get_json(force=True)
time = dict['timer']
return del_from_planning(time)
class FilesExplorer(Resource):
def get(self, dir: str):
dir = base64.b64decode(dir.encode('ascii')).decode('ascii')
files = {}
for file in os.listdir(dir):
path = dir + '/' + file
if os.path.isfile(path):
date = os.path.getmtime(path)
date = time.strftime('%d.%m.%Y %H:%M:%S', time.strptime(time.ctime(date)))
size = os.path.getsize(path)
size = sizeof_fmt(size)
files[file] = [date, size]
return collections.OrderedDict(sorted(files.items(), key=lambda i: i[0].lower()))
class DirsExplorer(Resource):
def get(self, dir: str):
dir = base64.b64decode(dir.encode('ascii')).decode('ascii')
dirs = {}
for d in os.listdir(dir):
path = dir + '/' + d
if os.path.isdir(path):
date = os.path.getmtime(path)
date = time.strftime('%d.%m.%Y %H:%M:%S', time.strptime(time.ctime(date)))
size = get_dir_size(path)
dirs[d] = [date, size]
return collections.OrderedDict(sorted(dirs.items(), key=lambda i: i[0].lower()))
class GetFile(Resource):
def get(self, file: str):
file = base64.b64decode(file.encode('ascii')).decode('ascii')
path = os.path.split(file)
name = path[1].removeprefix('.')
return flask.send_from_directory(path[0], path[1], as_attachment=True, download_name=name)
class Copy(Resource):
def get(self, copy, dest):
copy = base64.b64decode(copy.encode('ascii')).decode('ascii')
dest = base64.b64decode(dest.encode('ascii')).decode('ascii')
copypart = copy.rpartition('/')
dest_file = rename_if_exist(copypart[2], dest, os.path.isfile(copy))
if os.path.isfile(copy):
response = shutil.copy(copy, dest + '/' + dest_file)
else:
response = shutil.copytree(copy, dest + '/' + dest_file, symlinks=True, copy_function=shutil.copy)
return jsonify(copy, response)
class Cut(Resource):
def get(self, copy, dest):
copy = base64.b64decode(copy.encode('ascii')).decode('ascii')
dest = base64.b64decode(dest.encode('ascii')).decode('ascii')
copypart = copy.rpartition('/')
tmp_name = copypart[0] + copypart[1] + '*.123.3.whynot'
os.rename(copy, tmp_name)
dest_file = rename_if_exist(copypart[2], dest, os.path.isfile(copy))
return jsonify(copy, shutil.move(tmp_name, dest + '/' + dest_file))
class Delete(Resource):
def get(self, file):
file = base64.b64decode(file.encode('ascii')).decode('ascii')
if os.path.isfile(file):
os.remove(file)
else:
shutil.rmtree(file)
return file
def rename_if_exist(file, dest, isfile, first=True):
def func(f):
if isfile:
d_file = file.rpartition('.')
name = d_file[0]
return os.path.isfile(f), d_file, name
else:
d_file = ('', '', file)
name = ''
return os.path.isdir(f), d_file, name
f = func(dest + '/' + file)
d_file = f[1]
name = f[2]
if f[0]:
extension = d_file[1] + d_file[2]
if len(name) <= 0:
name = extension
extension = ''
if name[-1] == ')':
isok = True
lastpos = -2
for i in range(len(name) - 2, 0, -1):
char = name[i]
if not char.isnumeric() and not char == '(':
isok = False
break
if char == '(':
break
lastpos = i
if isok:
name = name[:lastpos - 1] + ('' if first else '(' + str(int(name[lastpos:-1]) + 1) + ')')
new_name = name + extension
else:
new_name = name + '(1)' + extension
else:
new_name = name + '(1)' + extension
file = rename_if_exist(new_name, dest, isfile, False)
return file
api.add_resource(Auth, '/api/login/auth', '/api/login/auth/<string:user>/<string:mp>/<string:keep>')
api.add_resource(Logout, '/api/login/logout')
api.add_resource(KeepLogin, '/api/login/keep_login')
api.add_resource(AddTime, '/api/time/add')
api.add_resource(SubTime, '/api/time/sub')
api.add_resource(Webcam, '/api/webcam')
api.add_resource(DiscordRestart, '/api/discord/restart')
api.add_resource(DiscordDisplay, '/api/discord/display')
api.add_resource(LightColor, '/api/lights/color')
api.add_resource(LightProgressive, '/api/lights/progressive')
api.add_resource(LightRainbow, '/api/lights/rainbow', '/api/lights/rainbow/<int:speed>')
api.add_resource(LightFlashRainbow, '/api/lights/flash_rb', '/api/lights/flash_rb/<int:speed>')
api.add_resource(LightStrobe, '/api/lights/strobe', '/api/lights/strobe/<int:speed>')
api.add_resource(LightTimer, '/api/lights/timer')
api.add_resource(FilesExplorer, '/api/file_explorer/files/<string:dir>')
api.add_resource(DirsExplorer, '/api/file_explorer/dirs/<string:dir>')
api.add_resource(GetFile, '/api/file_explorer/get_file/<string:file>')
api.add_resource(Copy, '/api/file_explorer/copy/<string:copy>/<string:dest>')
api.add_resource(Cut, '/api/file_explorer/cut/<string:copy>/<string:dest>')
api.add_resource(Delete, '/api/file_explorer/delete/<string:file>')
if __name__ == '__main__':
try:
load_from_planning()
serve(app, host=server_ip, port=4000)
finally:
cb.cancel()
pi.stop()