-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_4.py
4843 lines (4222 loc) · 192 KB
/
api_4.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
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask_cors import CORS
from flask import Flask, request, jsonify, Response, render_template
import socket, pyodbc, random, time, os, cv2, base64, hashlib, requests, datetime, json, math, hashlib, argon2, firebase_admin, shutil
from shutil import copyfile
from argon2 import PasswordHasher
from matplotlib import pyplot
import numpy as np
import pandas as pd
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from base64 import b64encode, b64decode
from firebase_admin import credentials, messaging
cred = credentials.Certificate('ngocvinaai-firebase-adminsdk-57cev-b988d1a956.json')
firebase_admin.initialize_app(cred)
app = Flask(__name__)
CORS(app)
value = None
random_banner = ''
current_banner = ''
banner_folder_path = 'banner'
cam_img_folder_path = 'cam_img'
detectorssd = cv2.dnn.readNetFromCaffe("pre_model/deploy.prototxt","pre_model/res10_300x300_ssd_iter_140000.caffemodel")
#---------------------------------------------------------------------------------------------------
def connect_to_database():
max_retries = 5
retry_delay = 5 # Đợi 5 giây trước khi thử kết nối lại
for retry_count in range(max_retries):
try:
conn = pyodbc.connect("Driver={SQL Server};"
"Server=112.78.15.3;"
"Database=VinaAIAPP;"
"uid=ngoi;"
"pwd=admin123;")
print()
print("Kết nối Database thành công!")
return conn # Trả về kết nối nếu thành công
except pyodbc.OperationalError:
if retry_count < max_retries - 1:
print("Kết nối không thành công. Thử kết nối lại sau {} giây.".format(retry_delay))
time.sleep(retry_delay)
else:
print("Không thể kết nối đến cơ sở dữ liệu sau nhiều lần thử. Đã đạt đến giới hạn thử lại.")
raise
def base64_to_array(anh_base64):
try:
img_arr = np.frombuffer(base64.b64decode(anh_base64), dtype=np.uint8)
img_arr = cv2.imdecode(img_arr, cv2.IMREAD_ANYCOLOR)
except:
return "Không chuyển được ảnh base64 sang array"
return img_arr
def padding_face(imgface,target_size=(224,224)):
try:
tile= target_size[0]/(imgface.shape[0]+1)
he=math.floor(tile*imgface.shape[0])
wi=math.floor(tile*imgface.shape[1])
imgface=cv2.resize(imgface,(wi,he))
target_size=(224, 224)
factor_0 = target_size[0] / imgface.shape[0]
factor_1 = target_size[1] / imgface.shape[1]
factor = min(factor_0, factor_1)
dsize = (int(imgface.shape[1] * factor), int(imgface.shape[0] * factor))
imgface = cv2.resize(imgface, dsize)
# Then pad the other side to the target size by adding black pixels
diff_0 = target_size[0] - imgface.shape[0]
diff_1 = target_size[1] - imgface.shape[1]
# Put the base image in the middle of the padded image
imgface = np.pad(imgface, ((diff_0 // 2, diff_0 - diff_0 // 2), (diff_1 // 2, diff_1 - diff_1 // 2), (0, 0)), 'constant')
#double check: if target image is not still the same size with target.
if imgface.shape[0:2] != target_size:
imgface = cv2.resize(imgface, target_size)
return imgface
except:
print("err padd")
return imgface
def argon2_encode(input_password):
"""
Hàm mã hóa mật khẩu sử dụng thuật toán Argon2.
Parameters:
- input_password: Mật khẩu cần mã hóa.
Returns:
- Chuỗi Argon2 hash.
"""
ph = PasswordHasher()
hashed_password = ph.hash(input_password)
return hashed_password
def argon2_compare(input_password, hashed_password):
"""
Hàm kiểm tra sự tương đồng giữa một mật khẩu và một chuỗi Argon2 hash.
Parameters:
- input_password: Mật khẩu cần kiểm tra.
- hashed_password: Chuỗi Argon2 hash cần so sánh.
Returns:
- True nếu input_password và hashed_password tương đồng, False nếu không.
"""
ph = PasswordHasher()
try:
ph.verify(hashed_password, input_password)
return True
except argon2.exceptions.VerifyMismatchError:
return False
def aes_encrypt(encrypt_text, key=b'x?C^pz62}bDM&)<duM9]:/kWze/j13J4'):
# Thêm padding vào dữ liệu để đảm bảo độ dài là bội số của 16 bytes
padder = padding.PKCS7(128).padder()
padded_data = padder.update(encrypt_text.encode()) + padder.finalize()
# Mã hóa dữ liệu đã được padding
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
return b64encode(ciphertext).decode()
def aes_decrypt(decrypt_text, key=b'x?C^pz62}bDM&)<duM9]:/kWze/j13J4'):
# Giải mã dữ liệu
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())
decryptor = cipher.decryptor()
padded_data = decryptor.update(b64decode(decrypt_text)) + decryptor.finalize()
# Bỏ padding
unpadder = padding.PKCS7(128).unpadder()
plaintext = unpadder.update(padded_data) + unpadder.finalize()
return plaintext.decode()
def save_thumbnail(rtsp_url, camera_id, thumbnail_path='cam_img'):
# Mở kết nối RTSP
cap = cv2.VideoCapture(rtsp_url)
# Kiểm tra xem kết nối có thành công không
if not cap.isOpened():
print("Không thể kết nối đến luồng RTSP.")
return
# Bỏ qua 4 khung hình đầu tiên
for _ in range(4):
ret, _ = cap.read()
if not ret:
print("Không thể đọc khung hình từ luồng RTSP.")
cap.release()
return
# Đọc khung hình thứ 5
ret, frame = cap.read()
# Kiểm tra xem có đọc được khung hình không
if not ret:
print("Không thể đọc khung hình từ luồng RTSP.")
cap.release()
return
# Lưu khung hình thứ 5
thumbnail_file_path = os.path.join(thumbnail_path, f"{camera_id}.jpg")
cv2.imwrite(thumbnail_file_path, frame)
print(f"Khung hình thứ 5 đã được lưu tại: {thumbnail_file_path}")
# Giải phóng tài nguyên
cap.release()
def push_alert(fcm_list, title, body, data=None):
android_config = messaging.AndroidConfig(
priority='high',
notification=messaging.AndroidNotification(sound='res_sound45', priority='max')
)
apns_config = messaging.APNSConfig(
payload=messaging.APNSPayload(
aps=messaging.Aps(
alert=messaging.ApsAlert(
title=title,
body=body
),
sound='res_sound45.wav'
),
custom_data=data
)
)
message = messaging.MulticastMessage(
notification = messaging.Notification( title=title, body=body),
android=android_config,
apns=apns_config,
tokens=fcm_list
)
# Gửi thông báo đến thiết bị cụ thể
response = messaging.send_multicast(message)
print(f"Failure Count: {response.failure_count}")
return response.failure_count
#---------------------------------------------------------------------------------------------------
# Lấy địa chỉ IP của máy
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip_address = s.getsockname()[0]
s.close()
return ip_address
ip_address = get_ip_address()
#---------------------------------------------------------------------------------------------------
api_keys = ['3ab281f56574187a64b1b9abfad4ea7fefe5ff89c4a47a0cf4d2782aa38248e7',
'6768d2372a333a0230955442278719012d8ebdbd954c529cdc20c7d3955161aa',
'5c1f45bde9d2aff92e03acbac0b6d49f6410ca490c1fe85a082650ee9c23f63d',
'6ab6fda952f7ae1499f850c9bb18cc1a7515c595eec0787301b1c26a577a74c7',
'fb4cc8fde5e512e3e994d99cd6d4e209289e32f53730a788fb59921e3446928f',
'5cde773edc9baddf85682ae625f388b8a9b5e1bee398df72757a11801d2f4737',
'960d65cfd84e76e43a89902fb842117b3a8352f8547b8ca4c5320564bef943bd',
'1ccff985dea7c477c7678b6b9e34bbc073ed377953d631939c306c1c577a0659',
'23da994e97602d5623df7232659fd61d6af8045cffe9992d4b96d4498cb25c7c',
'0615e264fd806b2322ad3c1ae993306df2f082ba933052f628ba3b55314013ec']
####################################################################################################
@app.route('/api/account/sign-up', methods=['POST'])
def them_tai_khoan():
conn = connect_to_database()
cursor = conn.cursor()
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
cursor.close()
conn.close()
return jsonify({'message': 'Sai key'}), 400
# customerid = data.get('customerid')
username = data.get('username')
password = data.get('password')
email = data.get('email')
mobile = data.get('mobile')
fullname = data.get('fullname')
#address = data.get('address')
#district_id = data.get('district_id')
# Mã hóa mật khẩu
password = argon2_encode(password)
# Kiểm tra xem tài khoản, email hoặc số điện thoại đã tồn tại hay chưa
query_check = f"SELECT Username, Email, Mobile FROM Customer WHERE Username = ? OR Email = ? OR Mobile = ?"
cursor.execute(query_check, (username, email, mobile))
existing_accounts = cursor.fetchall()
error_messages = []
for account in existing_accounts:
if account.Username == username:
error_messages.append('Tên tài khoản')
if account.Email == email:
error_messages.append('Email')
if account.Mobile == mobile:
error_messages.append('Số điện thoại')
if error_messages:
msg = ', '.join(error_messages)+' đã tồn tại.'
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 409
# Thực thi truy vấn INSERT để thêm thông tin vào bảng Customer
query_insert = f"INSERT INTO Customer (Username, Password, Email, Mobile, FullName) VALUES (?, ?, ?, ?, ?)"
cursor.execute(query_insert, (username, password, email, mobile, fullname))
conn.commit()
# Trả về phản hồi thành công
msg = 'Thêm thông tin tài khoản thành công'
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 201
#---------------------------------------------------------------------------------------------------
@app.route('/api/account/data', methods=['POST'])
def get_tai_khoan():
conn = connect_to_database()
cursor = conn.cursor()
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
cursor.close()
conn.close()
return jsonify({'message': 'Sai key'}), 400
# Thực thi truy vấn SELECT để lấy dữ liệu từ bảng Customer
query_select = "SELECT * FROM Customer"
cursor.execute(query_select)
rows = cursor.fetchall()
# Tạo danh sách các bản ghi
data = []
for row in rows:
record = {
#'customer_id': row.CustomerID,
'username': row.Username,
'password': row.Password,
#'id_quyen': row.ID_Quyen,
'email': row.Email,
'mobile': row.Mobile,
#'fullname': row.FullName
}
data.append(record)
# Trả về dữ liệu dưới dạng JSON
print(data)
cursor.close()
conn.close()
return jsonify(data), 200
#---------------------------------------------------------------------------------------------------
@app.route('/api/account/login', methods=['POST'])
def check_account():
conn = connect_to_database()
cursor = conn.cursor()
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
cursor.close()
conn.close()
return jsonify({'message': 'Sai key'}), 400
fcm = data.get('fcm')
ten_tai_khoan_email_sdt = data.get('ten_tai_khoan_email_sdt')
password = data.get('password')
print("ten_tai_khoan_email_sdt:", ten_tai_khoan_email_sdt, ' - ', type(ten_tai_khoan_email_sdt))
print("password:", password, ' - ', type(password))
# if ten_tai_khoan_email_sdt=='anh100279.2020@gmail.com':
# msg = 'Login successfull!'
# print(msg)
# cursor.close()
# conn.close()
# return jsonify({'message': msg}), 200
# Kiểm tra nếu "ten_tai_khoan_email_sdt" có chứa ký tự "@"
if "@" in ten_tai_khoan_email_sdt:
# Kiểm tra có tồn tại Email này không
cursor.execute("SELECT * FROM Customer WHERE Email = ?", (ten_tai_khoan_email_sdt,))
result = cursor.fetchone()
if not result:
msg = "Email does not exist"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
# Kiểm tra trong cột "Email" và "Password"
print("Đăng nhập bằng Email: ", ten_tai_khoan_email_sdt)
query_check = "SELECT * FROM Customer WHERE Email = ?"
cursor.execute(query_check, (ten_tai_khoan_email_sdt))
result = cursor.fetchone()
if argon2_compare(password, result.Password):
msg = "Wrong Password"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
# Kiểm tra nếu "ten_tai_khoan_email_sdt" toàn là số
elif ten_tai_khoan_email_sdt.isdigit():
# Kiểm tra có tồn tại SDT này không
cursor.execute("SELECT * FROM Customer WHERE Mobile = ?", (ten_tai_khoan_email_sdt,))
result = cursor.fetchone()
if not result:
msg = "Phone number does not exist"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
# Kiểm tra trong cột "Mobile" và "Password"
print("Đăng nhập bằng SDT: ", ten_tai_khoan_email_sdt)
query_check = "SELECT * FROM Customer WHERE Mobile = ?"
cursor.execute(query_check, (ten_tai_khoan_email_sdt))
result = cursor.fetchone()
if argon2_compare(password, result.Password):
msg = "Wrong Password"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
else:
# Kiểm tra có tồn tại Tên người dùng này không
cursor.execute("SELECT * FROM Customer WHERE Username = ?", (ten_tai_khoan_email_sdt,))
result = cursor.fetchone()
if not result:
msg = "Username does not exist"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
# Kiểm tra trong cột "Username" và "Password"
print("Đăng nhập bằng Username: ", ten_tai_khoan_email_sdt)
query_check = "SELECT * FROM Customer WHERE Username = ?"
cursor.execute(query_check, (ten_tai_khoan_email_sdt))
result = cursor.fetchone()
if not argon2_compare(password, result.Password):
msg = "Wrong Password"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
#------------------------------------ Thêm FCM ------------------------------------
if "@" in ten_tai_khoan_email_sdt:
cursor.execute("SELECT CustomerID FROM Customer WHERE Email = ?", ten_tai_khoan_email_sdt)
elif ten_tai_khoan_email_sdt.isdigit():
cursor.execute("SELECT CustomerID FROM Customer WHERE Mobile = ?", ten_tai_khoan_email_sdt)
else:
cursor.execute("SELECT CustomerID FROM Customer WHERE Username = ?", ten_tai_khoan_email_sdt)
results = cursor.fetchall()
customerid = results[0][0]
try:
cursor.execute("SELECT 1 FROM CustomerDevice WHERE CustomerID = ? AND FCM = ?", (customerid, fcm))
if cursor.fetchone():
print("Cặp giá trị CustomerID và FCM đã tồn tại, k thực hiện thêm mới")
else:
current_datetime = datetime.datetime.now()
cursor.execute("INSERT INTO CustomerDevice (CustomerID, FCM, LoginTime) VALUES (?, ?, ?)", (customerid, fcm, current_datetime))
print(f"Đã thêm FCM cho User {ten_tai_khoan_email_sdt}")
conn.commit()
except:
msg = f"Lỗi! Không thêm được FCM cho User {ten_tai_khoan_email_sdt}"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
#-----------------------------------------------------------------------------------
msg = 'Login successfull!'
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 200
#---------------------------------------------------------------------------------------------------
@app.route('/api/account/logout', methods=['POST'])
def logout():
conn = connect_to_database()
cursor = conn.cursor()
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
cursor.close()
conn.close()
return jsonify({'message': 'Sai key'}), 400
fcm = data.get('fcm')
ten_tai_khoan_email_sdt = data.get('ten_tai_khoan_email_sdt')
print("ten_tai_khoan_email_sdt:", ten_tai_khoan_email_sdt, ' - ', type(ten_tai_khoan_email_sdt))
# Từ "ten_tai_khoan_email_sdt" lấy CustomerID trong bảng Customer
try:
if "@" in ten_tai_khoan_email_sdt:
cursor.execute("SELECT CustomerID FROM Customer WHERE Email = ?", ten_tai_khoan_email_sdt)
elif ten_tai_khoan_email_sdt.isdigit():
cursor.execute("SELECT CustomerID FROM Customer WHERE Mobile = ?", ten_tai_khoan_email_sdt)
else:
cursor.execute("SELECT CustomerID FROM Customer WHERE Username = ?", ten_tai_khoan_email_sdt)
customerid = cursor.fetchone().CustomerID
# cursor.execute("SELECT Username FROM Customer WHERE CustomerID = ?", customerid)
# username = cursor.fetchone().Username
except:
msg = f"Lỗi! Không lấy được Username của User {ten_tai_khoan_email_sdt}"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
cursor.execute("DELETE FROM CustomerDevice WHERE CustomerID = ? AND FCM = ?", (customerid, fcm))
conn.commit()
msg = f"Logout! {ten_tai_khoan_email_sdt}"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 200
#---------------------------------------------------------------------------------------------------
@app.route('/api/account/lay-maxacnhan', methods=['POST'])
def lay_maxacnhan():
conn = connect_to_database()
cursor = conn.cursor()
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
cursor.close()
conn.close()
return jsonify({'message': 'Sai key'}), 400
email = data.get('email')
# Câu truy vấn SELECT để tìm hàng chứa email trùng khớp
select_query = f"SELECT * FROM Customer WHERE Email = ?"
cursor.execute(select_query, email)
rows = cursor.fetchall()
# Nếu có hàng trùng khớp, tạo và gửi mã xác nhận
if rows:
verification_code = str(random.randint(1, 999999)).zfill(6)
# Kiểm tra xem mã xác nhận đã tồn tại trong cột VerificationCode hay chưa
while True:
select_code_query = f"SELECT * FROM Customer WHERE VerificationCode = ?"
cursor.execute(select_code_query, verification_code)
rows_code = cursor.fetchall()
if not rows_code:
break
verification_code = str(random.randint(1, 999999)).zfill(6)
update_query = f"UPDATE Customer SET VerificationCode = ? WHERE Email = ?"
cursor.execute(update_query, (verification_code, email))
conn.commit()
print('Mã xác nhận: ', verification_code)
cursor.close()
conn.close()
return verification_code, 200
else:
msg = 'Không tìm thấy email trong cơ sở dữ liệu.'
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
#---------------------------------------------------------------------------------------------------
@app.route('/api/account/kt-maxacnhan', methods=['POST'])
def kt_maxacnhan():
conn = connect_to_database()
cursor = conn.cursor()
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
cursor.close()
conn.close()
return jsonify({'message': 'Sai key'}), 400
email = data.get('email')
maxacnhan = data.get('maxacnhan')
# Câu truy vấn SELECT để tìm hàng chứa mã xác nhận trùng khớp
select_query = f"SELECT * FROM Customer WHERE VerificationCode = ? AND Email = ?"
cursor.execute(select_query, (maxacnhan, email))
# Nếu có hàng trùng khớp, cập nhật cột VerificationCode
if cursor.fetchall():
msg = 'Mã xác nhận Đúng'
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 200
else:
msg = 'Mã xác nhận Sai'
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
#---------------------------------------------------------------------------------------------------
@app.route('/api/account/capnhat-matkhau', methods=['POST'])
def capnhat_matkhau():
conn = connect_to_database()
cursor = conn.cursor()
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
cursor.close()
conn.close()
return jsonify({'message': 'Sai key'}), 400
email = data.get('email')
new_pw = data.get('matkhaumoi')
# Câu truy vấn SELECT để tìm hàng chứa email trùng khớp và kiểm tra mật khẩu
select_query = f"SELECT * FROM Customer WHERE Email = ?"
cursor.execute(select_query, (email))
rows = cursor.fetchall()
if rows:
current_pw = rows[0].Password # Giả sử cột Password được lấy là current_pw
# Kiểm tra new_pw có trùng với current_pw hay không
if argon2_compare(new_pw, current_pw):
msg = 'Vừa nhập mật khẩu cũ'
print(msg)
return jsonify({'message': msg}), 400
# Cập nhật mật khẩu mới
update_query = f"UPDATE Customer SET Password = ? WHERE Email = ?"
cursor.execute(update_query, (argon2_encode(new_pw), email))
conn.commit()
msg = 'Cập nhật mật khẩu thành công'
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 200
else:
msg = 'Không tìm thấy email trong cơ sở dữ liệu.'
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
#---------------------------------------------------------------------------------------------------
@app.route('/api/account/set-avatar', methods=['POST'])
def set_avatar():
conn = connect_to_database()
cursor = conn.cursor()
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
cursor.close()
conn.close()
return jsonify({'message': 'Sai key'}), 400
avatar_base64 = data.get('avatar_base64')
ten_tai_khoan_email_sdt = data.get('ten_tai_khoan_email_sdt')
print("ten_tai_khoan_email_sdt:", ten_tai_khoan_email_sdt, ' - ', type(ten_tai_khoan_email_sdt))
# Từ "ten_tai_khoan_email_sdt" lấy CustomerID trong bảng Customer
try:
if "@" in ten_tai_khoan_email_sdt:
cursor.execute("SELECT CustomerID FROM Customer WHERE Email = ?", ten_tai_khoan_email_sdt)
elif ten_tai_khoan_email_sdt.isdigit():
cursor.execute("SELECT CustomerID FROM Customer WHERE Mobile = ?", ten_tai_khoan_email_sdt)
else:
cursor.execute("SELECT CustomerID FROM Customer WHERE Username = ?", ten_tai_khoan_email_sdt)
customerid = cursor.fetchone().CustomerID
# cursor.execute("SELECT Username FROM Customer WHERE CustomerID = ?", customerid)
# username = cursor.fetchone().Username
except:
msg = f"Lỗi! Không lấy được Username của User {ten_tai_khoan_email_sdt}"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
cursor.execute("UPDATE Customer SET Avatar = ? WHERE CustomerID = ?", (avatar_base64, customerid))
conn.commit()
msg = f'Đã set avatar cho User {ten_tai_khoan_email_sdt}'
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 200
#---------------------------------------------------------------------------------------------------
@app.route('/api/account/get-avatar', methods=['POST'])
def get_avatar():
conn = connect_to_database()
cursor = conn.cursor()
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
cursor.close()
conn.close()
return jsonify({'message': 'Sai key'}), 400
# avatar_base64 = data.get('avatar_base64')
ten_tai_khoan_email_sdt = data.get('ten_tai_khoan_email_sdt')
print("ten_tai_khoan_email_sdt:", ten_tai_khoan_email_sdt, ' - ', type(ten_tai_khoan_email_sdt))
# Từ "ten_tai_khoan_email_sdt" lấy CustomerID trong bảng Customer
try:
if "@" in ten_tai_khoan_email_sdt:
cursor.execute("SELECT CustomerID FROM Customer WHERE Email = ?", ten_tai_khoan_email_sdt)
elif ten_tai_khoan_email_sdt.isdigit():
cursor.execute("SELECT CustomerID FROM Customer WHERE Mobile = ?", ten_tai_khoan_email_sdt)
else:
cursor.execute("SELECT CustomerID FROM Customer WHERE Username = ?", ten_tai_khoan_email_sdt)
customerid = cursor.fetchone().CustomerID
# cursor.execute("SELECT Username FROM Customer WHERE CustomerID = ?", customerid)
# username = cursor.fetchone().Username
except:
msg = f"Lỗi! Không lấy được Username của User {ten_tai_khoan_email_sdt}"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
cursor.execute("SELECT Avatar FROM Customer WHERE CustomerID = ?", (customerid,))
avatar_base64 = cursor.fetchone().Avatar
print("Vừa trả về chuỗi base64 của avatar")
cursor.close()
conn.close()
return Response(avatar_base64, mimetype='text/plain')
#---------------------------------------------------------------------------------------------------
@app.route('/api/account/delete', methods=['POST'])
def delete_account():
conn = connect_to_database()
cursor = conn.cursor()
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
cursor.close()
conn.close()
return jsonify({'message': 'Sai key'}), 400
# avatar_base64 = data.get('avatar_base64')
ten_tai_khoan_email_sdt = data.get('ten_tai_khoan_email_sdt')
print("ten_tai_khoan_email_sdt:", ten_tai_khoan_email_sdt, ' - ', type(ten_tai_khoan_email_sdt))
# Từ "ten_tai_khoan_email_sdt" lấy CustomerID trong bảng Customer
try:
if "@" in ten_tai_khoan_email_sdt:
cursor.execute("SELECT CustomerID FROM Customer WHERE Email = ?", ten_tai_khoan_email_sdt)
elif ten_tai_khoan_email_sdt.isdigit():
cursor.execute("SELECT CustomerID FROM Customer WHERE Mobile = ?", ten_tai_khoan_email_sdt)
else:
cursor.execute("SELECT CustomerID FROM Customer WHERE Username = ?", ten_tai_khoan_email_sdt)
customerid = cursor.fetchone().CustomerID
cursor.execute("SELECT Username FROM Customer WHERE CustomerID = ?", customerid)
username = cursor.fetchone().Username
except:
msg = f"Lỗi! Không lấy được Username của User {ten_tai_khoan_email_sdt}"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
print(username, ' - ', customerid)
cursor.execute("DELETE FROM Customer WHERE CustomerID = ?", (customerid,))
conn.commit()
msg = "Account deleted"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 201
####################################################################################################
@app.route('/api/ads/banner-img', methods=['GET'])
def banner():
global random_banner
global current_banner
banner_files = os.listdir(banner_folder_path)
# Chọn ngẫu nhiên một tệp tin ảnh từ thư mục banner
while random_banner==current_banner:
random_banner = random.choice(banner_files)
current_banner = random_banner
# Đường dẫn đầy đủ tới tệp tin ảnh
image_path = os.path.join(banner_folder_path, random_banner)
# Đọc nội dung tệp tin ảnh
# with open(image_path, "rb") as image_file:
# image_data = image_file.read()
img = cv2.imread(image_path)
_, image_data = cv2.imencode('.jpg', img)
# Chuyển đổi dữ liệu ảnh thành chuỗi base64
base64_image = base64.b64encode(image_data).decode("utf-8")
# Trả về chuỗi base64 cho app
print("Vừa trả về chuỗi base64")
return Response(base64_image, mimetype='text/plain')
####################################################################################################
@app.route('/api/lock/get-accesstoken', methods=['POST'])
def get_accesstoken(client_id='87ed6cf1e9274e65af6500193fd7dce8',
clientsecret='5e56225a865fc7368f7e1e57b5bdd0fc',
username='trinhnhattuyen12a4@gmail.com',
password='nhattuyen0414'):
# def get_accesstoken(client_id='2ce5129232f74cc2ac89e24cdd04ec65',
# clientsecret='5fc0bb10aa78a6fa48c0ff4b95e3c791',
# username='datlongan@gmail.com',
# password='Dat12345678'):
print("Get access token ...")
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
url = "https://euapi.sciener.com/oauth2/token"
data = {
"clientId": client_id,
"clientSecret": clientsecret,
"username": username,
"password": hashlib.md5(password.encode()).hexdigest()
}
response = requests.post(url, headers=headers, data=data)
if response.status_code == 200:
print(response.json())
return Response(response.json()['access_token'], mimetype='text/plain')
else:
print("Failed to get access token")
return Response("Failed to get access token", mimetype='text/plain')
#---------------------------------------------------------------------------------------------------
@app.route('/api/lock/state', methods=['POST'])
def get_lockstate():
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
return jsonify({'message': 'Sai key'}), 400
client_id = data.get('client_id')
lock_id = data.get('lock_id')
access_token = data.get('access_token')
now = datetime.datetime.now()
new_time = now + datetime.timedelta(seconds=2)
date = int(new_time.timestamp() * 1000)
api_url = f"https://euapi.sciener.com/v3/lock/queryOpenState?clientId={client_id}&accessToken={access_token}&lockId={lock_id}&date={date}"
try:
response = requests.get(api_url)
data = response.json()
state = data.get('state')
print('State: ', state)
if state==0:
return Response("Locked", mimetype='text/plain')
elif state==1:
return Response("Unlocked", mimetype='text/plain')
else:
return Response("Unknown", mimetype='text/plain')
except requests.exceptions.RequestException as e:
return Response("Error when get lock state", mimetype='text/plain')
#---------------------------------------------------------------------------------------------------
@app.route('/api/lock/unlock', methods=['POST'])
def remote_lock():
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
return jsonify({'message': 'Sai key'}), 400
lock_id = data.get('lock_id')
client_id = data.get('client_id')
lock = data.get('lock')
access_token = data.get('access_token')
url = "https://euapi.sciener.com/v3/lock/unlock"
if lock:
url = "https://euapi.sciener.com/v3/lock/lock"
now = datetime.datetime.now()
new_time = now + datetime.timedelta(seconds=2)
timestamp = int(new_time.timestamp() * 1000)
data = {
"clientId": client_id,
"accessToken": access_token,
"lockId": lock_id,
"date": timestamp
}
response = requests.post(url, data=data)
msg = response.json()
if msg.get('errcode') == 0:
if lock:
msg = 'Lock Successful!'
print(msg)
return jsonify({'message': msg}), 200
else:
msg = 'Unlock Successful!'
print(msg)
return jsonify({'message': msg}), 200
else:
if lock:
msg = 'Lock Fail! ' + msg.get('errmsg')
print(msg)
return jsonify({'message': msg}), 404
else:
msg = 'Unlock Fail! '+msg.get('errmsg')
print(msg)
return jsonify({'message': msg}), 404
####################################################################################################
@app.route('/api/home/homeinfo', methods=['POST'])
def homeinfo():
conn = connect_to_database()
cursor = conn.cursor()
data = request.get_json()
key = data.get('key')
if key not in api_keys:
print('Sai key')
cursor.close()
conn.close()
return jsonify({'message': 'Sai key'}), 400
ten_tai_khoan_email_sdt = data.get('ten_tai_khoan_email_sdt')
print("ten_tai_khoan_email_sdt:", ten_tai_khoan_email_sdt, ' - ', type(ten_tai_khoan_email_sdt))
home_info_list = []
# Lấy CustomerID
try:
# Từ "ten_tai_khoan_email_sdt" lấy CustomerID trong bảng Customer
if "@" in ten_tai_khoan_email_sdt:
cursor.execute("SELECT CustomerID FROM Customer WHERE Email = ?", ten_tai_khoan_email_sdt)
elif ten_tai_khoan_email_sdt.isdigit():
cursor.execute("SELECT CustomerID FROM Customer WHERE Mobile = ?", ten_tai_khoan_email_sdt)
else:
cursor.execute("SELECT CustomerID FROM Customer WHERE Username = ?", ten_tai_khoan_email_sdt)
results = cursor.fetchall()
customerid = results[0][0]
except:
msg = f"Lỗi! Không lấy được CustomerID của User {ten_tai_khoan_email_sdt}"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
#---------------------------------------------------------------------------------------
# LẤY NHÀ CỦA USER
try:
cursor.execute("SELECT HomeName, HomeAddress, DistrictID, HomeID FROM CustomerHome WHERE CustomerID = ?", customerid)
results = cursor.fetchall()
# Chuyển danh sách các tuple thành danh sách các dictionary
for result in results:
# Lấy các cam trong nhà đó
cursor.execute("SELECT CameraName, CameraID FROM Camera WHERE HomeID = ? AND CameraStatus = ?", (result.HomeID, 1))
cam = cursor.fetchall()
home_info_list.append({
'HomeName': result.HomeName,
'HomeAddress': result.HomeAddress,
'DistrictID': result.DistrictID,
'HomeID': result.HomeID,
'Owner': '1',
'CameraID': [i.CameraID for i in cam],
'CameraName': [i.CameraName for i in cam],
})
if len(results)==0:
print(f"User {ten_tai_khoan_email_sdt} chưa thêm căn hộ nào")
else:
print(f"Có {len(results)} căn hộ của User {ten_tai_khoan_email_sdt}")
except:
msg = f"Lỗi! Không lấy được thông tin các căn hộ của User {ten_tai_khoan_email_sdt}"
print(msg)
cursor.close()
conn.close()
return jsonify({'message': msg}), 404
#---------------------------------------------------------------------------------------
# LẤY NHÀ CỦA USER ĐƯỢC THÊM
# try:
cursor.execute("SELECT HomeID, AdminID FROM HomeMember WHERE HomeMemberID = ?", customerid)
results = cursor.fetchall()
# Lấy thông tin căn hộ được thêm quyền
for homeid, admin_id in results:
cursor.execute("SELECT HomeName, HomeAddress, DistrictID FROM CustomerHome WHERE HomeID = ? AND CustomerID = ?",
(homeid, admin_id))
result = cursor.fetchone()
# Lấy các cam trong nhà đó
cursor.execute("SELECT CameraName, CameraID FROM Camera WHERE HomeID = ? AND CameraStatus = ?", (homeid, 1))
cam = cursor.fetchall()
# Chuyển danh sách các tuple thành danh sách các dictionary
home_info_list.append({
'HomeName': result.HomeName,
'HomeAddress': result.HomeAddress,
'DistrictID': result.DistrictID,
'HomeID': homeid,
'Owner': '0',
'CameraID': [i.CameraID for i in cam],
'CameraName': [i.CameraName for i in cam],
})