-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloud_connection.py
More file actions
832 lines (702 loc) · 34.2 KB
/
cloud_connection.py
File metadata and controls
832 lines (702 loc) · 34.2 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
import socketio
import subprocess
import json
import time
import threading
import uuid
import os
import sys
from pathlib import Path
import requests
from colorama import init, Fore, Back, Style
def print_status(message, status_type="info"):
if status_type == "success":
print(Fore.GREEN + message)
elif status_type == "error":
print(Fore.RED + message)
elif status_type == "warning":
print(Fore.YELLOW + message)
else:
print(Fore.BLUE + message)
def load_cloud_config():
settings_dir = Path(__file__).parent / "settings"
cloud_config_path = settings_dir / "cloud.json"
if cloud_config_path.exists():
try:
with open(cloud_config_path, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, FileNotFoundError):
return {}
return {}
def save_cloud_config(config_data):
settings_dir = Path(__file__).parent / "settings"
settings_dir.mkdir(exist_ok=True)
cloud_config_path = settings_dir / "cloud.json"
with open(cloud_config_path, 'w') as f:
json.dump(config_data, f, indent=2)
DEFAULT_CLOUD_URL = "https://bridge.bbarni.hackclub.app"
DEFAULT_SERVER_ID = None
DEFAULT_SERVER_NAME = None
DEFAULT_HEARTBEAT_INTERVAL = 30
DEFAULT_COMMAND_TIMEOUT = 30
class ShareifyLocalClient:
def __init__(self, cloud_url="https://bridge.bbarni.hackclub.app", server_id=None, server_name=None, user_id=None, auth_token=None, username=None, password=None):
self.cloud_url = DEFAULT_CLOUD_URL
self.cloud_config = load_cloud_config()
self.server_id = self._get_or_create_server_id(server_id)
self.server_name = server_name or DEFAULT_SERVER_NAME or f"Shareify-{self.server_id[:8]}"
self.user_id = user_id or self.cloud_config.get('user_id')
self.auth_token = auth_token or self.cloud_config.get('auth_token')
self.username = username or self.cloud_config.get('username')
self.password = password or self.cloud_config.get('password')
self.enabled = self.cloud_config.get('enabled', True)
self.authenticated = False
self.sio = socketio.Client(
reconnection=True,
reconnection_attempts=5,
reconnection_delay=1,
reconnection_delay_max=5,
logger=False,
engineio_logger=False
)
self.connected = False
self.heartbeat_interval = DEFAULT_HEARTBEAT_INTERVAL
self.command_timeout = DEFAULT_COMMAND_TIMEOUT
self.last_successful_ping = time.time()
self.reconnect_attempts = 0
self.max_reconnect_attempts = 5
self.setup_handlers()
def setup_handlers(self):
@self.sio.event
def connect():
print(f"Connected to cloud bridge at {self.cloud_url}")
self.connected = True
self.authenticate_user()
@self.sio.event
def disconnect():
print("Disconnected from cloud bridge")
self.connected = False
self.authenticated = False
@self.sio.on('authentication_success')
def on_auth_success(data):
print(f"Authentication successful: {data['username']}")
self.user_id = data['user_id']
self.auth_token = data.get('auth_token')
self.authenticated = True
config_data = {
'user_id': self.user_id,
'auth_token': self.auth_token,
'username': data['username'],
'server_id': self.server_id,
'server_name': self.server_name,
'cloud_url': self.cloud_url,
'enabled': self.enabled,
'last_authentication': time.time()
}
save_cloud_config(config_data)
print(f"Authentication data saved to cloud.json")
self.register_server()
@self.sio.on('authentication_failed')
def on_auth_failed(data):
print_status(f"Authentication failed: {data['error']}", "error")
self.authenticated = False
if self.auth_token and self.username and self.password:
print_status("Auth token failed, trying username/password fallback...", "warning")
self.sio.emit('authenticate_user', {
'username': self.username,
'password': self.password
})
else:
print_status("No fallback credentials available", "error")
@self.sio.on('registration_success')
def on_registration_success(data):
if 'server_id' in data:
print(f"Server registration successful: {data['message']}")
print(f"Server ID: {data['server_id']}")
config_data = load_cloud_config()
config_data.update({
'server_registered': True,
'registration_timestamp': time.time(),
'server_id': self.server_id,
'server_name': self.server_name,
'user_id': self.user_id,
'auth_token': self.auth_token,
'username': self.username,
'cloud_url': self.cloud_url,
'enabled': self.enabled
})
save_cloud_config(config_data)
print(f"Server registration data saved to cloud.json")
else:
print(f"User registration successful: {data['username']}")
self.user_id = data['user_id']
self.auth_token = data.get('auth_token')
self.authenticated = True
config_data = {
'user_id': self.user_id,
'auth_token': self.auth_token,
'username': data['username'],
'password': self.password,
'server_id': self.server_id,
'server_name': self.server_name,
'cloud_url': self.cloud_url,
'enabled': self.enabled,
'user_registered': True,
'user_registration_timestamp': time.time()
}
save_cloud_config(config_data)
print(f"User registration data saved to cloud.json")
self.register_server()
@self.sio.on('registration_failed')
def on_registration_failed(data):
if 'server_id' in str(data):
print(f"Server registration failed: {data['error']}")
else:
print(f"User registration failed: {data['error']}")
self.authenticated = False
@self.sio.on('execute_command')
def on_execute_command(data):
command_id = data['command_id']
command = data['command']
method = data.get('method', 'GET')
body = data.get('body', {})
timestamp = data.get('timestamp')
shareify_jwt = data.get('shareify_jwt')
print(f"Received command {command_id}: {command} (method: {method})")
try:
self.execute_api_request(command_id, command, method, body, shareify_jwt)
except Exception as e:
print(f"Failed to handle command: {e}")
if self.sio.connected:
try:
self.sio.emit('command_response', {
'command_id': command_id,
'response': {'error': str(e)}
})
except Exception as emit_error:
print(f"Failed to emit command error: {emit_error}")
@self.sio.on('pong')
def on_pong(data):
self.last_successful_ping = time.time()
self.reconnect_attempts = 0
print(f"Ping response: {data.get('timestamp', 'no timestamp')}")
def authenticate_user(self):
if self.user_id and self.auth_token:
print_status(f"Authenticating with saved token for user: {self.user_id}", "info")
self.sio.emit('authenticate_user', {
'user_id': self.user_id,
'auth_token': self.auth_token
})
elif self.username and self.password:
print_status(f"Authenticating with username/password for user: {self.username}", "info")
self.sio.emit('authenticate_user', {
'username': self.username,
'password': self.password
})
else:
print_status("No authentication credentials found, registering new user", "warning")
new_username = f"shareify_user_{str(uuid.uuid4())[:8]}"
new_password = str(uuid.uuid4())
self.sio.emit('register_user', {
'username': new_username,
'password': new_password
})
self.username = new_username
self.password = new_password
def register_server(self):
if not self.authenticated:
print("Cannot register server: not authenticated")
return
self.sio.emit('register_server', {
'server_id': self.server_id,
'name': self.server_name,
'user_id': self.user_id,
'auth_token': self.auth_token
})
def _get_or_create_server_id(self, provided_id=None):
if provided_id:
print_status(f"Using provided server ID: {provided_id}", "info")
return provided_id
saved_server_id = self.cloud_config.get('server_id')
if saved_server_id:
print_status(f"Using saved server ID from cloud.json: {saved_server_id}", "success")
return saved_server_id
if DEFAULT_SERVER_ID:
print_status(f"Using default server ID: {DEFAULT_SERVER_ID}", "info")
return DEFAULT_SERVER_ID
new_id = str(uuid.uuid4())
print_status(f"Generated new server ID: {new_id}", "warning")
return new_id
def get_server_info(self):
return {
'server_id': self.server_id,
'server_name': self.server_name,
'cloud_url': self.cloud_url,
'connected': self.connected,
'enabled': self.enabled,
'heartbeat_interval': self.heartbeat_interval,
'command_timeout': self.command_timeout
}
def handle_shareify_command(self, command):
parts = command.split(' ', 1)
action = parts[0]
if action == 'status':
return {
'server_id': self.server_id,
'server_name': self.server_name,
'connected': self.connected,
'enabled': self.enabled,
'uptime': time.time(),
'platform': sys.platform,
'heartbeat_interval': self.heartbeat_interval,
'command_timeout': self.command_timeout
}
elif action == 'info':
return self.get_server_info()
elif action == 'restart_service':
return {'message': 'Shareify service restart initiated'}
elif action == 'get_logs':
return {'logs': 'Recent log entries...'}
elif action == 'update':
return {'message': 'Update process started'}
elif action == 'change_name':
if len(parts) > 1:
new_name = parts[1].strip()
old_name = self.server_name
self.set_server_name(new_name)
return {'message': f'Server name changed from "{old_name}" to "{new_name}" and saved'}
else:
return {'error': 'New name required. Usage: shareify:change_name <new_name>'}
elif action == 'change_id':
if len(parts) > 1:
new_id = parts[1].strip()
old_id = self.server_id
self.set_server_id(new_id)
return {'message': f'Server ID changed from "{old_id}" to "{new_id}" and saved'}
else:
return {'error': 'New ID required. Usage: shareify:change_id <new_id>'}
elif action == 'generate_new_id':
old_id = self.server_id
new_id = self.generate_new_id()
return {'message': f'Server ID changed from "{old_id}" to "{new_id}" and saved'}
elif action == 'enable':
self.set_enabled(True)
return {'message': 'Cloud connection enabled'}
elif action == 'disable':
self.set_enabled(False)
return {'message': 'Cloud connection disabled'}
elif action == 'toggle':
new_state = not self.enabled
self.set_enabled(new_state)
return {'message': f'Cloud connection {"enabled" if new_state else "disabled"}'}
else:
return {'error': f'Unknown Shareify command: {action}'}
def generate_new_id(self):
old_id = self.server_id
self.server_id = str(uuid.uuid4())
config_data = load_cloud_config()
config_data['server_id'] = self.server_id
save_cloud_config(config_data)
print_status(f"Server ID changed from {old_id} to {self.server_id} and saved to cloud.json", "success")
return self.server_id
def set_server_name(self, new_name):
old_name = self.server_name
self.server_name = new_name
config_data = load_cloud_config()
config_data['server_name'] = new_name
save_cloud_config(config_data)
print_status(f"Server name changed from '{old_name}' to '{new_name}' and saved to cloud.json", "success")
return self.server_name
def set_server_id(self, new_id):
old_id = self.server_id
self.server_id = new_id
config_data = load_cloud_config()
config_data['server_id'] = new_id
save_cloud_config(config_data)
print_status(f"Server ID changed from '{old_id}' to '{new_id}' and saved to cloud.json", "success")
return self.server_id
def set_enabled(self, enabled):
self.enabled = enabled
config_data = load_cloud_config()
config_data['enabled'] = enabled
save_cloud_config(config_data)
print(f"Cloud connection {'enabled' if enabled else 'disabled'}")
return self.enabled
def is_enabled(self):
return self.enabled
def start_heartbeat(self):
def heartbeat():
while self.connected and self.enabled:
try:
if self.authenticated:
self.sio.emit('ping', {
'server_id': self.server_id,
'user_id': self.user_id,
'timestamp': time.time()
})
if time.time() - self.last_successful_ping > (self.heartbeat_interval * 6):
print_status("No pong received for extended period, connection might be dead", "warning")
if self.reconnect_attempts < self.max_reconnect_attempts:
self.reconnect_attempts += 1
print_status(f"Attempting reconnection ({self.reconnect_attempts}/{self.max_reconnect_attempts})", "info")
self.disconnect()
time.sleep(5)
if self.connect():
print_status("Reconnection successful", "success")
continue
else:
print_status("Max reconnection attempts reached", "error")
break
time.sleep(self.heartbeat_interval)
except Exception as e:
print_status(f"Heartbeat error: {e}", "error")
time.sleep(self.heartbeat_interval)
if not self.connected:
break
heartbeat_thread = threading.Thread(target=heartbeat, daemon=True)
heartbeat_thread.start()
def connect(self):
if not self.enabled:
print("Cloud connection is disabled. Use 'shareify:enable' to enable it.")
return False
try:
if self.connected:
self.sio.disconnect()
time.sleep(2)
except:
pass
max_retries = 3
retry_delay = 5
for attempt in range(max_retries):
try:
print_status(f"Connecting to cloud bridge at {self.cloud_url} (attempt {attempt + 1}/{max_retries})")
self.sio.connect(
self.cloud_url,
wait_timeout=15,
socketio_path='/socket.io/',
headers={'User-Agent': f'Shareify-Client/{self.server_id}'}
)
self.start_heartbeat()
return True
except Exception as e:
print_status(f"Connection attempt {attempt + 1} failed: {e}", "error")
if attempt < max_retries - 1:
print_status(f"Retrying in {retry_delay} seconds...", "warning")
time.sleep(retry_delay)
retry_delay += 2
else:
print_status(f"All connection attempts failed", "error")
return False
def disconnect(self):
print_status("Disconnecting from cloud bridge...", "info")
self.connected = False
self.authenticated = False
if self.sio.connected:
try:
self.sio.disconnect()
time.sleep(1)
except Exception as e:
print_status(f"Error during disconnect: {e}", "warning")
def wait(self):
try:
while self.connected and self.enabled:
time.sleep(1)
except KeyboardInterrupt:
print("\nShutting down...")
self.disconnect()
def execute_api_request(self, command_id, url, method='GET', body=None, shareify_jwt=None):
try:
base_url = "http://127.0.0.1:6969/api"
if url.startswith('/'):
full_url = base_url + url
else:
full_url = base_url + '/' + url
print(f"Making {method} request to: {full_url}")
allowed_endpoints = [
'/resources', 'resources',
'/is_up', 'is_up',
'/user/get_self', 'user/get_self',
'/user/login', 'user/login',
'/get_logs', '/finder', '/get_file'
]
if not any(url == ep or url.startswith(ep) for ep in allowed_endpoints):
if self.sio.connected:
try:
self.sio.emit('command_response', {
'command_id': command_id,
'response': {'error': 'Not allowed (security reasons) to access this endpoint.'}
})
except Exception as emit_error:
print(f"Failed to emit security error: {emit_error}")
return
headers = {'Content-Type': 'application/json'}
if shareify_jwt:
headers['Authorization'] = f'Bearer {shareify_jwt}'
if method.upper() == 'GET':
if isinstance(body, dict) and body:
import urllib.parse
query_string = urllib.parse.urlencode(body)
if '?' in full_url:
full_url = f"{full_url}&{query_string}"
else:
full_url = f"{full_url}?{query_string}"
response = requests.get(full_url, headers=headers, timeout=self.command_timeout)
elif method.upper() == 'POST':
response = requests.post(full_url, json=body, headers=headers, timeout=self.command_timeout)
elif method.upper() == 'PUT':
response = requests.put(full_url, json=body, headers=headers, timeout=self.command_timeout)
elif method.upper() == 'DELETE':
response = requests.delete(full_url, headers=headers, timeout=self.command_timeout)
elif method.upper() == 'PATCH':
response = requests.patch(full_url, json=body, headers=headers, timeout=self.command_timeout)
elif method.upper() == 'HEAD':
response = requests.head(full_url, headers=headers, timeout=self.command_timeout)
elif method.upper() == 'OPTIONS':
response = requests.options(full_url, headers=headers, timeout=self.command_timeout)
else:
raise ValueError(f"Unsupported HTTP method: {method}")
try:
response_data = response.json()
except json.JSONDecodeError:
response_data = response.text
is_file_endpoint = url.endswith('/get_file') or 'get_file' in url
if is_file_endpoint and isinstance(response_data, dict) and 'content' in response_data:
self.handle_large_file_response(command_id, response_data)
else:
self.send_standard_response(command_id, response_data)
except requests.exceptions.Timeout:
print(f"API request timeout for command {command_id}")
if self.sio.connected:
try:
self.sio.emit('command_response', {
'command_id': command_id,
'response': {'error': 'API request timeout'}
})
except Exception as emit_error:
print(f"Failed to emit timeout error: {emit_error}")
except requests.exceptions.ConnectionError:
print(f"API connection error for command {command_id}")
if self.sio.connected:
try:
self.sio.emit('command_response', {
'command_id': command_id,
'response': {'error': 'Failed to connect to local API server'}
})
except Exception as emit_error:
print(f"Failed to emit connection error: {emit_error}")
except Exception as e:
print(f"General error for command {command_id}: {e}")
if self.sio.connected:
try:
self.sio.emit('command_response', {
'command_id': command_id,
'response': {'error': str(e)}
})
except Exception as emit_error:
print(f"Failed to emit general error: {emit_error}")
def send_standard_response(self, command_id, response_data):
if self.sio.connected:
try:
self.sio.emit('command_response', {
'command_id': command_id,
'response': response_data
})
print(f"Successfully emitted response for command {command_id}")
time.sleep(0.1)
except Exception as emit_error:
print(f"Failed to emit response: {emit_error}")
else:
print("Socket not connected, cannot emit response")
def handle_large_file_response(self, command_id, response_data):
if 'content' not in response_data:
self.send_standard_response(command_id, response_data)
return
content = response_data['content']
content_type = response_data.get('type', 'text')
filename = response_data.get('filename')
if content_type == 'binary':
content_size = len(content) * 3 // 4 if isinstance(content, str) else len(content)
else:
content_size = len(content.encode('utf-8')) if isinstance(content, str) else len(content)
file_storage_threshold = 512 * 1024
if content_size > file_storage_threshold:
print(f"File content size ({content_size} bytes) exceeds threshold ({file_storage_threshold} bytes), using file storage...")
self.send_file_via_storage(command_id, response_data)
else:
print(f"File content size ({content_size} bytes) within limit, sending normally")
self.send_standard_response(command_id, response_data)
def send_file_via_storage(self, command_id, response_data):
try:
content = response_data['content']
content_type = response_data.get('type', 'text')
filename = response_data.get('filename')
if content_type == 'binary':
content_size = len(content) * 3 // 4 if isinstance(content, str) else len(content)
else:
content_size = len(content.encode('utf-8')) if isinstance(content, str) else len(content)
dynamic_timeout = min(300, max(30, 30 + (content_size // (100 * 1024))))
print(f"Using timeout of {dynamic_timeout}s for file size {content_size} bytes")
storage_data = {
'content': content,
'content_type': content_type,
'filename': filename,
'server_id': self.server_id,
'user_id': self.user_id,
'auth_token': self.auth_token
}
print(f"Storing file on bridge server...")
max_retries = 3
last_error = None
for attempt in range(max_retries):
try:
print(f"Storage attempt {attempt + 1}/{max_retries}")
store_response = requests.post(
f"{self.cloud_url}/cloud/file/store",
json=storage_data,
timeout=dynamic_timeout,
headers={'Connection': 'close'}
)
if store_response.status_code == 200:
storage_result = store_response.json()
if storage_result.get('success'):
file_id = storage_result['file_id']
password = storage_result['password']
print(f"File stored successfully with ID: {file_id}")
file_response = {
'status': response_data.get('status', 'File stored successfully'),
'type': 'file_storage',
'file_id': file_id,
'password': password,
'original_type': content_type,
'filename': filename,
'file_size': content_size
}
self.send_standard_response(command_id, file_response)
return
else:
error_msg = storage_result.get('error', 'Unknown error')
print(f"Failed to store file: {error_msg}")
self.send_error_response(command_id, f"Failed to store file: {error_msg}")
return
else:
last_error = f"HTTP {store_response.status_code}: {store_response.text}"
print(f"File storage request failed with status {store_response.status_code}")
if 400 <= store_response.status_code < 500:
self.send_error_response(command_id, f"File storage failed: {last_error}")
return
if attempt < max_retries - 1:
wait_time = (attempt + 1) * 2
print(f"Retrying in {wait_time} seconds...")
time.sleep(wait_time)
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as e:
last_error = str(e)
print(f"Network error on attempt {attempt + 1}: {e}")
if attempt < max_retries - 1:
wait_time = (attempt + 1) * 3
print(f"Retrying in {wait_time} seconds...")
time.sleep(wait_time)
except Exception as e:
last_error = str(e)
print(f"Unexpected error on attempt {attempt + 1}: {e}")
if attempt < max_retries - 1:
wait_time = (attempt + 1) * 2
print(f"Retrying in {wait_time} seconds...")
time.sleep(wait_time)
print(f"All {max_retries} storage attempts failed")
self.send_fallback_response(command_id, response_data, last_error)
except Exception as e:
print(f"Error in file storage process: {e}")
self.send_error_response(command_id, f"File storage error: {str(e)}")
def send_fallback_response(self, command_id, response_data, storage_error):
try:
content = response_data['content']
content_type = response_data.get('type', 'text')
filename = response_data.get('filename', 'unknown')
if content_type == 'binary':
content_size = len(content) * 3 // 4 if isinstance(content, str) else len(content)
else:
content_size = len(content.encode('utf-8')) if isinstance(content, str) else len(content)
if content_type == 'text' and isinstance(content, str):
max_fallback_size = 50 * 1024
if len(content.encode('utf-8')) > max_fallback_size:
truncated_content = content[:max_fallback_size // 2]
fallback_response = {
'status': f'File too large for cloud storage, showing first {len(truncated_content)} characters',
'content': truncated_content + f"\n\n[TRUNCATED - Original file was {content_size} bytes]",
'type': 'text',
'filename': filename,
'truncated': True,
'original_size': content_size,
'storage_error': str(storage_error)
}
print(f"Sending truncated content fallback for {filename}")
self.send_standard_response(command_id, fallback_response)
return
error_response = {
'error': f'File storage failed and content too large for direct transfer',
'filename': filename,
'file_size': content_size,
'content_type': content_type,
'storage_error': str(storage_error),
'suggestion': 'Try downloading smaller files or check network connection'
}
print(f"Sending error fallback for {filename}")
self.send_standard_response(command_id, error_response)
except Exception as e:
print(f"Error in fallback response: {e}")
self.send_error_response(command_id, f"File storage and fallback failed: {str(e)}")
def send_error_response(self, command_id, error_message):
if self.sio.connected:
try:
self.sio.emit('command_response', {
'command_id': command_id,
'response': {
'error': error_message,
'status': 'error'
}
})
print(f"Sent error response for command {command_id}: {error_message}")
except Exception as emit_error:
print(f"Failed to emit error response: {emit_error}")
else:
print("Socket not connected, cannot emit error response")
def send_chunked_file_response(self, command_id, response_data):
print("Warning: send_chunked_file_response called, redirecting to file storage")
self.send_file_via_storage(command_id, response_data)
def main():
try:
client = ShareifyLocalClient()
print()
print_status(f"\n=== Shareify Cloud Client Starting ===")
print_status(f"Cloud URL: {client.cloud_url}")
print_status(f"Server ID: {client.server_id}")
print_status(f"Server Name: {client.server_name}")
print_status(f"User ID: {client.user_id}")
print_status(f"Username: {client.username}")
print_status(f"Enabled: {client.enabled}")
print_status(f"Heartbeat Interval: {client.heartbeat_interval}s")
print_status(f"Command Timeout: {client.command_timeout}s")
print_status("="*50)
print()
if not client.enabled:
print_status("Cloud connection is disabled. Use 'shareify:enable' to enable it.", "warning")
sys.exit(0)
if client.connect():
print_status("Client started successfully", "success")
print("Waiting for commands from cloud...")
client.wait()
else:
print_status("Failed to start client after all retry attempts", "error")
print_status("This could be because:", "info")
print_status("1. The cloud server is not running", "info")
print_status("2. Network connectivity issues", "info")
print_status("3. Incorrect cloud URL configuration", "info")
print()
sys.exit(1)
except Exception as e:
print_status(f"Unexpected error in main: {e}", "error")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()