-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblueQ-backend.py
More file actions
1146 lines (947 loc) · 43.5 KB
/
blueQ-backend.py
File metadata and controls
1146 lines (947 loc) · 43.5 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
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 import Flask, send_from_directory, request, jsonify
from flask_cors import CORS
import os
import uuid
import time
import requests
from datetime import datetime
import sys
import base64
from werkzeug.utils import secure_filename
app = Flask(__name__, static_folder='static')
CORS(app) # Enable CORS for Angular frontend
# Configuration for file uploads
UPLOAD_FOLDER = 'uploads'
MAX_FILE_SIZE = 5 * 1024 * 1024 # 5MB limit
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = MAX_FILE_SIZE
# Create uploads directory if it doesn't exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
def image_to_base64(file_path):
"""Convert an image file to base64 string"""
try:
with open(file_path, 'rb') as f:
image_data = f.read()
base64_data = base64.b64encode(image_data).decode('utf-8')
file_extension = os.path.splitext(file_path)[1].lower()
# Create data URL format
mime_type = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.webp': 'image/webp'
}.get(file_extension, 'image/jpeg')
return f"data:{mime_type};base64,{base64_data}"
except Exception as e:
print(f"❌ Error converting image to base64: {e}")
return None
def base64_to_image(base64_data, output_path):
"""Convert base64 string to image file"""
try:
# Remove data URL prefix if present
if base64_data.startswith('data:'):
base64_data = base64_data.split(',', 1)[1]
image_data = base64.b64decode(base64_data)
with open(output_path, 'wb') as f:
f.write(image_data)
return True
except Exception as e:
print(f"❌ Error converting base64 to image: {e}")
return False
# In-memory storage (replace with database in production)
users = {}
messages = {}
contacts = {}
# Device mesh management (for Bluetooth mesh network)
connected_devices = {} # Device ID -> Device info
device_sessions = {} # Session ID -> Device ID mapping
mesh_users = {} # Store mesh network users from Bluetooth clients
# Client Manager Integration
CLIENT_MANAGER_URL = "http://localhost:8001" # URL where client manager runs
# Device mesh management functions
def register_device(device_id, device_info):
"""Register a new device to the mesh network"""
connected_devices[device_id] = {
'id': device_id,
'name': device_info.get('name', f'Device-{device_id[:8]}'),
'type': device_info.get('type', 'unknown'),
'mac_address': device_info.get('mac_address', ''),
'capabilities': device_info.get('capabilities', []),
'connected_at': datetime.now().isoformat(),
'last_seen': datetime.now().isoformat(),
'is_online': True,
'session_id': device_info.get('session_id', None)
}
# Map session to device if provided
if device_info.get('session_id'):
device_sessions[device_info['session_id']] = device_id
return connected_devices[device_id]
def disconnect_device(device_id):
"""Remove a device from the mesh network"""
if device_id in connected_devices:
device = connected_devices[device_id]
device['is_online'] = False
device['disconnected_at'] = datetime.now().isoformat()
# Clean up session mapping
session_id = device.get('session_id')
if session_id and session_id in device_sessions:
del device_sessions[session_id]
# Remove from active devices
del connected_devices[device_id]
return True
return False
def update_device_status(device_id, status_data):
"""Update device status (capabilities, etc.)"""
if device_id in connected_devices:
device = connected_devices[device_id]
device['last_seen'] = datetime.now().isoformat()
# Update provided fields
for field in ['capabilities']:
if field in status_data:
device[field] = status_data[field]
return device
return None
def get_device_by_session(session_id):
"""Get device info by session ID"""
device_id = device_sessions.get(session_id)
if device_id and device_id in connected_devices:
return connected_devices[device_id]
return None
# Data stores start empty - no demo data
# Users, devices, and messages will be populated through API calls
# User endpoints
@app.route('/api/users', methods=['GET'])
def get_users():
# Get optional excludeUserId parameter to filter out specific user
exclude_user_id = request.args.get('excludeUserId')
all_users = list(users.values())
# Filter out the excluded user if specified
if exclude_user_id:
all_users = [user for user in all_users if user['id'] != exclude_user_id]
return jsonify(all_users)
@app.route('/api/users/<user_id>', methods=['GET'])
def get_user(user_id):
if user_id in users:
return jsonify(users[user_id])
return jsonify({'error': 'User not found'}), 404
@app.route('/api/users/register', methods=['POST'])
def register_user():
data = request.get_json()
# Use the frontend-provided ID if available, otherwise generate a UUID
user_id = data.get('id', str(uuid.uuid4()))
user = {
'id': user_id,
'name': data.get('name', ''),
'username': data.get('username', '')
}
users[user_id] = user
# Automatically trigger Bluetooth connection for the new user
try:
response = requests.post(
f"{CLIENT_MANAGER_URL}/api/connect",
json={'user_id': user_id, 'user_name': user['name']},
timeout=10
)
if response.status_code == 200:
print(f"✅ Automatically connected user {user['name']} to Bluetooth mesh")
else:
print(f"⚠️ Failed to auto-connect user {user['name']} to Bluetooth mesh")
except requests.exceptions.RequestException as e:
print(f"⚠️ Client manager not available for auto-connection: {e}")
return jsonify(user), 201
# Device mesh management endpoints
@app.route('/api/devices', methods=['GET'])
def get_connected_devices():
"""Get list of all connected devices in the mesh network"""
return jsonify(list(connected_devices.values()))
@app.route('/api/devices/<device_id>', methods=['GET'])
def get_device(device_id):
"""Get specific device information"""
if device_id in connected_devices:
return jsonify(connected_devices[device_id])
return jsonify({'error': 'Device not found'}), 404
@app.route('/api/devices/connect', methods=['POST'])
def connect_device():
"""Register a new device connection to the mesh"""
data = request.get_json()
# Generate device ID if not provided
device_id = data.get('device_id', str(uuid.uuid4()))
# Validate required fields
if not data.get('name') and not data.get('mac_address'):
return jsonify({'error': 'Device name or MAC address required'}), 400
device_info = {
'name': data.get('name'),
'type': data.get('type', 'unknown'),
'mac_address': data.get('mac_address', ''),
'capabilities': data.get('capabilities', []),
'session_id': data.get('session_id')
}
device = register_device(device_id, device_info)
return jsonify(device), 201
@app.route('/api/devices/<device_id>/disconnect', methods=['POST'])
def disconnect_device_endpoint(device_id):
"""Disconnect a device from the mesh"""
success = disconnect_device(device_id)
if success:
return jsonify({'success': True, 'message': f'Device {device_id} disconnected'})
return jsonify({'error': 'Device not found or already disconnected'}), 404
@app.route('/api/devices/<device_id>/status', methods=['PUT'])
def update_device_status_endpoint(device_id):
"""Update device status information"""
data = request.get_json()
device = update_device_status(device_id, data)
if device:
return jsonify(device)
return jsonify({'error': 'Device not found'}), 404
@app.route('/api/devices/<device_id>/heartbeat', methods=['POST'])
def device_heartbeat(device_id):
"""Device heartbeat to maintain connection"""
if device_id in connected_devices:
connected_devices[device_id]['last_seen'] = datetime.now().isoformat()
return jsonify({'success': True, 'timestamp': datetime.now().isoformat()})
return jsonify({'error': 'Device not found'}), 404
@app.route('/api/devices/session/<session_id>', methods=['GET'])
def get_device_by_session_endpoint(session_id):
"""Get device info by session ID (for web clients)"""
device = get_device_by_session(session_id)
if device:
return jsonify(device)
return jsonify({'error': 'No device associated with this session'}), 404
@app.route('/api/devices/cleanup', methods=['POST'])
def cleanup_inactive_devices():
"""Remove devices that haven't been seen for a while"""
data = request.get_json()
timeout_minutes = data.get('timeout_minutes', 10) # Default 10 minutes
current_time = datetime.now()
devices_to_remove = []
for device_id, device in connected_devices.items():
last_seen = datetime.fromisoformat(device['last_seen'])
time_diff = (current_time - last_seen).total_seconds() / 60
if time_diff > timeout_minutes:
devices_to_remove.append(device_id)
removed_count = 0
for device_id in devices_to_remove:
if disconnect_device(device_id):
removed_count += 1
return jsonify({
'removed_devices': removed_count,
'removed_device_ids': devices_to_remove,
'active_devices': len(connected_devices)
})
@app.route('/api/devices/stats', methods=['GET'])
def get_mesh_stats():
"""Get comprehensive mesh network statistics"""
device_types = {}
total_devices = len(connected_devices)
for device in connected_devices.values():
# Count device types
device_type = device.get('type', 'unknown')
device_types[device_type] = device_types.get(device_type, 0) + 1
return jsonify({
'total_devices': total_devices,
'device_types': device_types,
'mesh_health': 'good' if total_devices >= 3 else 'poor'
})
# Mesh users management endpoints
@app.route('/api/mesh/users', methods=['POST'])
def update_bluetooth_users():
"""Update the list of users discovered in the Bluetooth mesh network"""
data = request.get_json()
source_client = data.get('source_client', 'unknown')
users = data.get('mesh_users', []) # Keep mesh_users for compatibility
timestamp = data.get('timestamp', time.time())
# Store the bluetooth mesh users with metadata
mesh_users[source_client] = {
'users': users,
'last_updated': datetime.now().isoformat(),
'timestamp': timestamp,
'source_client': source_client
}
# Also register each user as a bluetooth device if not already present
for user in users:
device_id = f"bluetooth_user_{user}"
if device_id not in connected_devices:
device_info = {
'name': user,
'type': 'bluetooth_user',
'mac_address': 'unknown',
'capabilities': ['chat', 'bluetooth_communication'],
'discovered_by': source_client
}
register_device(device_id, device_info)
return jsonify({
'success': True,
'message': f'Updated bluetooth users from {source_client}',
'users_count': len(users),
'users': users
}), 201
@app.route('/api/mesh/users', methods=['GET'])
def get_bluetooth_users():
"""Get all bluetooth users discovered by all clients"""
all_bluetooth_users = {}
unique_users = set()
for source_client, data in mesh_users.items():
all_bluetooth_users[source_client] = data
unique_users.update(data['users'])
return jsonify({
'mesh_clients': all_bluetooth_users,
'unique_users': list(unique_users),
'total_unique_users': len(unique_users),
'reporting_clients': len(mesh_users)
})
@app.route('/api/mesh/users/<client_name>', methods=['GET'])
def get_bluetooth_users_by_client(client_name):
"""Get bluetooth users discovered by a specific client"""
if client_name in mesh_users:
return jsonify(mesh_users[client_name])
return jsonify({'error': 'Client not found or no users reported'}), 404
@app.route('/api/mesh/users/cleanup', methods=['POST'])
def cleanup_bluetooth_users():
"""Remove stale bluetooth user data"""
data = request.get_json()
timeout_minutes = data.get('timeout_minutes', 30) # Default 30 minutes
current_time = datetime.now()
clients_to_remove = []
for client_name, data in mesh_users.items():
last_updated = datetime.fromisoformat(data['last_updated'])
time_diff = (current_time - last_updated).total_seconds() / 60
if time_diff > timeout_minutes:
clients_to_remove.append(client_name)
removed_count = 0
for client_name in clients_to_remove:
del mesh_users[client_name]
removed_count += 1
return jsonify({
'removed_clients': removed_count,
'removed_client_names': clients_to_remove,
'active_bluetooth_clients': len(mesh_users)
})
@app.route('/api/mesh/scan', methods=['POST'])
def trigger_bluetooth_scan():
"""Trigger a bluetooth mesh scan (this would ideally communicate with the Python client)"""
# For now, this is a placeholder endpoint that the UI can call
# In a real implementation, this would send a command to the Python client
# to perform a bluetooth scan and update the mesh users
return jsonify({
'success': True,
'message': 'Bluetooth mesh scan request received. Please run "scan" command in your Python client.',
'instructions': 'To see updated users, run the "scan" command in your bluetooth mesh client application.'
})
# Client Manager Integration Endpoints
@app.route('/api/bluetooth/manager/status', methods=['GET'])
def get_client_manager_status():
"""Get the status of the Bluetooth client manager"""
try:
response = requests.get(f"{CLIENT_MANAGER_URL}/api/status", timeout=5)
if response.status_code == 200:
return jsonify(response.json())
else:
return jsonify({'error': 'Client manager not responding'}), 503
except requests.exceptions.RequestException:
return jsonify({
'error': 'Client manager not available',
'manager_running': False,
'total_clients': 0,
'connected_users': []
}), 503
@app.route('/api/bluetooth/manager/connect/<user_id>', methods=['POST'])
def connect_user_to_bluetooth(user_id):
"""Manually trigger connection for a specific user"""
if user_id not in users:
return jsonify({'error': 'User not found'}), 404
try:
user = users[user_id]
response = requests.post(
f"{CLIENT_MANAGER_URL}/api/connect",
json={'user_id': user_id, 'user_name': user['name']},
timeout=10
)
return jsonify(response.json()), response.status_code
except requests.exceptions.RequestException as e:
return jsonify({'error': f'Failed to connect to client manager: {str(e)}'}), 503
@app.route('/api/bluetooth/manager/disconnect/<user_id>', methods=['POST'])
def disconnect_user_from_bluetooth(user_id):
"""Manually disconnect a specific user"""
try:
response = requests.post(
f"{CLIENT_MANAGER_URL}/api/disconnect",
json={'user_id': user_id},
timeout=5
)
return jsonify(response.json()), response.status_code
except requests.exceptions.RequestException as e:
return jsonify({'error': f'Failed to connect to client manager: {str(e)}'}), 503
@app.route('/api/bluetooth/send_image_base64', methods=['POST'])
def send_bluetooth_image_base64():
"""Send an image as base64 through the Bluetooth mesh"""
data = request.get_json()
print(f"🔍 Received Bluetooth base64 image send request")
user_id = data.get('user_id')
destination = data.get('destination', 'broadcast')
image_base64 = data.get('image_base64')
filename = data.get('filename', 'image.jpg')
if not all([user_id, image_base64]):
print(f"❌ Missing required fields: user_id={user_id}, image_base64={'present' if image_base64 else 'missing'}")
return jsonify({'error': 'user_id and image_base64 are required'}), 400
try:
print(f"📡 Sending base64 image to client manager")
print(f" 👤 User: {user_id}")
print(f" 👥 To: {destination}")
print(f" 📄 Filename: {filename}")
print(f" 📊 Base64 size: {len(image_base64)} characters")
response = requests.post(
f"{CLIENT_MANAGER_URL}/api/send_image_base64",
json={
'user_id': user_id,
'destination': destination,
'image_base64': image_base64,
'filename': filename
},
timeout=30
)
print(f"📨 Client manager response: status={response.status_code}")
if response.status_code == 200:
print(f"✅ Base64 image transfer started from user {user_id} to {destination}")
return jsonify({
'success': True,
'message': 'Base64 image transfer started via Bluetooth mesh',
'destination': destination,
'filename': filename
})
else:
error_msg = f"Client manager returned status {response.status_code}"
if response.text:
try:
error_data = response.json()
error_msg = error_data.get('error', error_msg)
except:
error_msg = response.text
print(f"❌ Failed to start base64 image transfer: {error_msg}")
return jsonify({'error': error_msg}), 502
except requests.exceptions.RequestException as e:
error_msg = f'Failed to connect to client manager: {str(e)}'
print(f"❌ {error_msg}")
return jsonify({'error': error_msg}), 503
def send_bluetooth_image():
"""Send an image through the Bluetooth mesh for a specific user"""
data = request.get_json()
print(f"🔍 Received Bluetooth image send request: {data}")
user_id = data.get('user_id')
destination = data.get('destination', 'broadcast')
image_path = data.get('image_path')
if not all([user_id, image_path]):
print(f"❌ Missing required fields: user_id={user_id}, image_path={image_path}")
return jsonify({'error': 'user_id and image_path are required'}), 400
# Check if image file exists
if not os.path.isabs(image_path):
# If relative path, assume it's in uploads folder
image_path = os.path.join(UPLOAD_FOLDER, image_path)
if not os.path.exists(image_path):
print(f"❌ Image file not found: {image_path}")
return jsonify({'error': 'Image file not found'}), 404
try:
print(f"📡 Sending image to client manager: user_id={user_id}, destination={destination}, image_path={image_path}")
response = requests.post(
f"{CLIENT_MANAGER_URL}/api/send_image",
json={
'user_id': user_id,
'destination': destination,
'image_path': image_path
},
timeout=30 # Longer timeout for image transfers
)
print(f"📨 Client manager response: status={response.status_code}")
if response.status_code == 200:
print(f"✅ Bluetooth image transfer started from user {user_id} to {destination}")
return jsonify({
'success': True,
'message': 'Image transfer started via Bluetooth mesh',
'destination': destination,
'image_path': os.path.basename(image_path)
})
else:
error_msg = f"Client manager returned status {response.status_code}"
if response.text:
try:
error_data = response.json()
error_msg = error_data.get('error', error_msg)
except:
error_msg = response.text
print(f"❌ Failed to start Bluetooth image transfer: {error_msg}")
return jsonify({'error': error_msg}), 502
except requests.exceptions.RequestException as e:
error_msg = f'Failed to connect to client manager: {str(e)}'
print(f"❌ {error_msg}")
return jsonify({'error': error_msg}), 503
@app.route('/api/bluetooth/send', methods=['POST', 'OPTIONS'])
def send_bluetooth_message():
"""Send a message through the Bluetooth mesh for a specific user"""
# Handle CORS preflight requests
if request.method == 'OPTIONS':
return jsonify({'status': 'ok'}), 200
data = request.get_json()
print(f"🔍 Received Bluetooth send request: {data}")
user_id = data.get('user_id')
destination = data.get('destination', 'broadcast')
message = data.get('message')
if not all([user_id, message]):
print(f"❌ Missing required fields: user_id={user_id}, message={message}")
return jsonify({'error': 'user_id and message are required'}), 400
# Sanitize the message
sanitized_message = message.replace('<', '<').replace('>', '>').strip()
try:
print(f"📡 Sending to client manager: user_id={user_id}, destination={destination}, message={sanitized_message}")
response = requests.post(
f"{CLIENT_MANAGER_URL}/api/send",
json={
'user_id': user_id,
'destination': destination,
'message': sanitized_message
},
timeout=10
)
print(f"📨 Client manager response: status={response.status_code}")
if response.status_code == 200:
print(f"✅ Bluetooth message sent from user {user_id} to {destination}: {sanitized_message}")
return jsonify({
'success': True,
'message': 'Message sent via Bluetooth mesh',
'destination': destination,
'content': sanitized_message
})
else:
error_msg = f"Client manager returned status {response.status_code}"
if response.text:
try:
error_data = response.json()
error_msg = error_data.get('error', error_msg)
except:
error_msg = response.text
print(f"❌ Failed to send Bluetooth message: {error_msg}")
return jsonify({'error': error_msg}), 502
except requests.exceptions.RequestException as e:
error_msg = f'Failed to connect to client manager: {str(e)}'
print(f"❌ {error_msg}")
return jsonify({'error': error_msg}), 503
@app.route('/api/bluetooth/received', methods=['POST'])
def receive_bluetooth_message():
"""Receive a message from the Bluetooth mesh via client"""
data = request.get_json()
print(f"🔍 Received Bluetooth message from client: {data}")
sender = data.get('sender')
recipient = data.get('recipient')
content = data.get('content')
timestamp = data.get('timestamp')
client_name = data.get('client_name')
if not all([sender, recipient, content]):
print(f"❌ Missing required fields in received message")
return jsonify({'error': 'sender, recipient, and content are required'}), 400
# Find the recipient user ID by matching the client name to user name
recipient_user_id = None
for user_id, user in users.items():
if user['name'].lower() == recipient.lower():
recipient_user_id = user_id
break
if not recipient_user_id:
print(f"❌ Could not find user ID for recipient: {recipient}")
return jsonify({'error': f'Recipient user not found: {recipient}'}), 404
# Create a message object
message = {
'id': f"bt_received_{int(timestamp)}_{sender}_{recipient}",
'senderId': f"bluetooth_user_{sender}",
'receiverId': recipient_user_id,
'content': content,
'timestamp': datetime.fromtimestamp(timestamp).isoformat(),
'isRead': False,
'messageType': 'text',
'source': 'bluetooth_mesh'
}
# Store the message using the conversation key format
conversation_key = f"{min(message['senderId'], recipient_user_id)}_{max(message['senderId'], recipient_user_id)}"
if conversation_key not in messages:
messages[conversation_key] = []
# Check for duplicates before adding
existing_ids = [msg.get('id') for msg in messages[conversation_key]]
if message['id'] not in existing_ids:
messages[conversation_key].append(message)
print(f"✅ Stored received Bluetooth message: {sender} -> {recipient}")
else:
print(f"⚠️ Duplicate message ignored: {message['id']}")
return jsonify({'success': True, 'message': 'Message received and stored'})
@app.route('/api/bluetooth/received_image_base64', methods=['POST'])
def receive_bluetooth_image_base64():
"""Receive a base64 image from the Bluetooth mesh via client"""
data = request.get_json()
print(f"🔍 Received Bluetooth base64 image from client")
sender = data.get('sender')
recipient = data.get('recipient')
image_base64 = data.get('image_base64')
original_filename = data.get('original_filename', 'image.jpg')
timestamp = data.get('timestamp', time.time())
client_name = data.get('client_name')
if not all([sender, recipient, image_base64]):
print(f"❌ Missing required fields in received base64 image message")
return jsonify({'error': 'sender, recipient, and image_base64 are required'}), 400
try:
print(f" 📄 Original filename: {original_filename}")
print(f" 📊 Base64 size: {len(image_base64)} characters")
# Generate unique filename for the saved image
file_extension = os.path.splitext(original_filename)[1] or '.jpg'
unique_filename = f"{uuid.uuid4()}{file_extension}"
file_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
# Convert base64 to image file
if base64_to_image(image_base64, file_path):
print(f" ✅ Saved base64 image as: {unique_filename}")
# Find the recipient user ID by matching the client name to user name
recipient_user_id = None
for user_id, user in users.items():
if user['name'].lower() == recipient.lower():
recipient_user_id = user_id
break
if not recipient_user_id:
print(f"❌ Could not find user ID for recipient: {recipient}")
return jsonify({'error': f'Recipient user not found: {recipient}'}), 404
# Create an image message object
message = {
'id': f"bt_received_img_{int(timestamp)}_{sender}_{recipient}",
'senderId': f"bluetooth_user_{sender}",
'receiverId': recipient_user_id,
'content': f"/api/images/{unique_filename}", # URL to the saved image
'originalFilename': original_filename,
'timestamp': datetime.fromtimestamp(timestamp).isoformat(),
'isRead': False,
'messageType': 'image',
'source': 'bluetooth_mesh'
}
# Store the message using the conversation key format
conversation_key = f"{min(message['senderId'], recipient_user_id)}_{max(message['senderId'], recipient_user_id)}"
if conversation_key not in messages:
messages[conversation_key] = []
# Check for duplicates before adding
existing_ids = [msg.get('id') for msg in messages[conversation_key]]
if message['id'] not in existing_ids:
messages[conversation_key].append(message)
print(f"✅ Stored received Bluetooth base64 image: {sender} -> {recipient} ({original_filename})")
else:
print(f"⚠️ Duplicate base64 image message ignored: {message['id']}")
return jsonify({'success': True, 'message': 'Base64 image received and stored'})
else:
print(f"❌ Failed to convert base64 to image file")
return jsonify({'error': 'Failed to convert base64 image'}), 500
except Exception as e:
print(f"❌ Error processing received base64 image: {e}")
return jsonify({'error': f'Failed to process base64 image: {str(e)}'}), 500
def receive_bluetooth_image():
"""Receive an image from the Bluetooth mesh via client"""
data = request.get_json()
print(f"🔍 Received Bluetooth image from client: {data}")
sender = data.get('sender')
recipient = data.get('recipient')
content = data.get('content') # This will be the image URL
original_filename = data.get('original_filename')
timestamp = data.get('timestamp')
client_name = data.get('client_name')
if not all([sender, recipient, content]):
print(f"❌ Missing required fields in received image message")
return jsonify({'error': 'sender, recipient, and content are required'}), 400
# Find the recipient user ID by matching the client name to user name
recipient_user_id = None
for user_id, user in users.items():
if user['name'].lower() == recipient.lower():
recipient_user_id = user_id
break
if not recipient_user_id:
print(f"❌ Could not find user ID for recipient: {recipient}")
return jsonify({'error': f'Recipient user not found: {recipient}'}), 404
# Create an image message object
message = {
'id': f"bt_received_img_{int(timestamp)}_{sender}_{recipient}",
'senderId': f"bluetooth_user_{sender}",
'receiverId': recipient_user_id,
'content': content, # URL to the saved image
'originalFilename': original_filename,
'timestamp': datetime.fromtimestamp(timestamp).isoformat(),
'isRead': False,
'messageType': 'image',
'source': 'bluetooth_mesh'
}
# Store the message using the conversation key format
conversation_key = f"{min(message['senderId'], recipient_user_id)}_{max(message['senderId'], recipient_user_id)}"
if conversation_key not in messages:
messages[conversation_key] = []
# Check for duplicates before adding
existing_ids = [msg.get('id') for msg in messages[conversation_key]]
if message['id'] not in existing_ids:
messages[conversation_key].append(message)
print(f"✅ Stored received Bluetooth image: {sender} -> {recipient} ({original_filename})")
else:
print(f"⚠️ Duplicate image message ignored: {message['id']}")
return jsonify({'success': True, 'message': 'Image received and stored'})
# Chat endpoints
@app.route('/api/chat/messages/<contact_id>', methods=['GET'])
def get_messages(contact_id):
# Get the current user from query parameter
current_user_id = request.args.get('userId')
if not current_user_id:
return jsonify({'error': 'User ID required'}), 400
# Create conversation key consistent with send_message
conversation_key = f"{min(current_user_id, contact_id)}_{max(current_user_id, contact_id)}"
print(f"🔍 Getting messages for contact_id: {contact_id}, user_id: {current_user_id}")
print(f"🔍 Conversation key: {conversation_key}")
print(f"🔍 Available conversation keys: {list(messages.keys())}")
# Get messages for this conversation
contact_messages = messages.get(conversation_key, [])
print(f"🔍 Found {len(contact_messages)} messages")
return jsonify(contact_messages)
@app.route('/api/chat/messages', methods=['POST'])
def send_message():
# Check if this is a file upload (multipart/form-data) or JSON
if request.content_type and 'multipart/form-data' in request.content_type:
return send_image_message()
else:
return send_text_message()
def send_text_message():
"""Handle text message sending"""
data = request.get_json()
contact_id = data.get('contactId')
content = data.get('content')
from_user_id = data.get('fromUserId')
if not all([contact_id, content, from_user_id]):
return jsonify({'error': 'Missing required fields'}), 400
message_id = str(uuid.uuid4())
message = {
'id': message_id,
'senderId': from_user_id,
'receiverId': contact_id,
'content': content,
'timestamp': datetime.now().isoformat(),
'isRead': False,
'messageType': 'text'
}
# Create a conversation key that's consistent regardless of who sends the message
conversation_key = f"{min(from_user_id, contact_id)}_{max(from_user_id, contact_id)}"
# Store message in the conversation
if conversation_key not in messages:
messages[conversation_key] = []
messages[conversation_key].append(message)
return jsonify(message), 201
def send_image_message():
"""Handle image message sending"""
try:
print("📤 Processing image upload request...")
# Get form data
contact_id = request.form.get('contactId')
from_user_id = request.form.get('fromUserId')
print(f" 👤 From user: {from_user_id}")
print(f" 👥 To contact: {contact_id}")
if not all([contact_id, from_user_id]):
print("❌ Missing required fields in request")
return jsonify({'error': 'Missing required fields'}), 400
# Check if file was uploaded
if 'image' not in request.files:
print("❌ No image file in request")
return jsonify({'error': 'No image file provided'}), 400
file = request.files['image']
if file.filename == '':
print("❌ Empty filename in request")
return jsonify({'error': 'No file selected'}), 400
print(f" 📄 Original filename: {file.filename}")
# Ensure uploads directory exists
if not os.path.exists(app.config['UPLOAD_FOLDER']):
print(f" 📁 Creating uploads directory: {app.config['UPLOAD_FOLDER']}")
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Generate unique filename with original extension
file_extension = file.filename.rsplit('.', 1)[1].lower() if '.' in file.filename else 'png'
unique_filename = f"{uuid.uuid4()}.{file_extension}"
file_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
print(f" 💾 Saving file as: {unique_filename}")
print(f" 📂 Full path: {file_path}")
# Save the file
file.save(file_path)
print(f" ✅ File saved successfully")
# Verify file was saved
if not os.path.exists(file_path):
raise FileNotFoundError(f"File not found after saving: {file_path}")
file_size = os.path.getsize(file_path)
print(f" 📊 Saved file size: {file_size} bytes")
# Create message
message_id = str(uuid.uuid4())
message = {
'id': message_id,
'senderId': from_user_id,
'receiverId': contact_id,
'content': f"/api/images/{unique_filename}", # URL to access the image
'originalFilename': secure_filename(file.filename),
'timestamp': datetime.now().isoformat(),
'isRead': False,
'messageType': 'image'
}
# Store message in conversation
conversation_key = f"{min(from_user_id, contact_id)}_{max(from_user_id, contact_id)}"
if conversation_key not in messages:
messages[conversation_key] = []
messages[conversation_key].append(message)
# Get the sender's name to use as Bluetooth destination
sender_name = users.get(from_user_id, {}).get('name', 'Unknown')
receiver_name = users.get(contact_id, {}).get('name', 'Unknown')
print(f"\n📡 Initiating Bluetooth transfer")
print(f" 👤 From: {sender_name}")
print(f" 👥 To: {receiver_name}")
print(f" 📄 File: {os.path.basename(file_path)}")
# Convert image to base64 for Bluetooth transfer
base64_data = image_to_base64(file_path)
if base64_data:
print(f" 📊 Base64 size: {len(base64_data)} characters")
# Send image as base64 via Bluetooth mesh
bluetooth_response = requests.post(
f"{CLIENT_MANAGER_URL}/api/send_image_base64",
json={
'user_id': from_user_id,
'destination': receiver_name,
'image_base64': base64_data,
'filename': secure_filename(file.filename)
},
timeout=30
)
else:
print(f" ❌ Failed to convert image to base64")
bluetooth_response = None
print(f" 📨 Response status: {bluetooth_response.status_code if bluetooth_response else 'N/A'}")
if bluetooth_response and bluetooth_response.status_code == 200:
print(f" ✅ Bluetooth transfer initiated successfully")
print(f" ⏳ Transfer will continue in background")
else:
if bluetooth_response:
print(f" ❌ Bluetooth transfer failed")
print(f" ℹ️ Status code: {bluetooth_response.status_code}")
if bluetooth_response.text:
try:
error_data = bluetooth_response.json()
print(f" ⚠️ Error: {error_data.get('error', 'Unknown error')}")
except:
print(f" ⚠️ Error: {bluetooth_response.text}")
else:
print(f" ❌ Failed to prepare image for Bluetooth transfer")
return jsonify(message), 201