-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_server.py
More file actions
1041 lines (900 loc) · 35.8 KB
/
file_server.py
File metadata and controls
1041 lines (900 loc) · 35.8 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
#!/usr/bin/env python3
"""
🚀 HIGH-PERFORMANCE FILE SERVER
Single-file solution for fast file sharing with professional UI
Author: Bibek Chand Sah
Features: Maximum speed, resume downloads, multi-user support, professional interface
"""
import os
import sys
import time
import socket
import mimetypes
import subprocess
import re
import atexit
import math
from flask import Flask, Response, request, render_template_string
from werkzeug.serving import WSGIRequestHandler
# ============================================================================
# SERVER CONFIGURATION - Maximum Performance Settings
# ============================================================================
class ServerConfig:
"""Pre-configured for maximum performance and features"""
# Performance Settings - Maximum Speed
CHUNK_SIZE_MB = 8 # 8 MB chunks for maximum throughput
SOCKET_BUFFER_MB = 4 # 4 MB socket buffers
MAX_FILE_SIZE_GB = 16 # 16 GB file size limit
# Calculated values
CHUNK_SIZE = CHUNK_SIZE_MB * 1024 * 1024
SOCKET_BUFFER_SIZE = SOCKET_BUFFER_MB * 1024 * 1024
MAX_CONTENT_LENGTH = MAX_FILE_SIZE_GB * 1024 * 1024 * 1024
# Features - All Enabled
ENABLE_RANGE_REQUESTS = True # Resume downloads support
ENABLE_THREADING = True # Multiple users & files
ENABLE_CACHE = True # HTTP caching
CACHE_HOURS = 1 # 1 hour cache
CACHE_MAX_AGE = CACHE_HOURS * 3600
# UI Settings
UI_STYLE = "professional" # Professional with file details
SHOW_FILE_DETAILS = True
# Server Settings (will be set by user)
SHARE_DIR = None
PORT = 8000
HOST = '0.0.0.0'
DEBUG_MODE = False
# Cloudflare Tunnel
CLOUDFLARE_URL = None
CLOUDFLARE_PROCESS = None
# Get user input for configuration
def get_user_configuration():
"""Prompt user for directory and port configuration"""
print("=" * 80)
print("🚀 HIGH-PERFORMANCE FILE SERVER 𝓓𝓮𝓿𝓮𝓵𝓸𝓹𝓮𝓭 𝓫𝔂 𝓑𝓲𝓫𝓮𝓴.....")
print("=" * 80)
print()
# Get share directory
print("📁 DIRECTORY CONFIGURATION:")
default_dir = r"D:\server\index"
while True:
share_dir = input(f"Enter directory path to share (or press Enter for '{default_dir}'): ").strip()
if not share_dir:
share_dir = default_dir
# Remove quotes if user pasted path with quotes
share_dir = share_dir.strip('"').strip("'")
# Normalize path
share_dir = os.path.abspath(share_dir)
if os.path.exists(share_dir) and os.path.isdir(share_dir):
ServerConfig.SHARE_DIR = share_dir
print(f"✅ Selected directory: {share_dir}")
break
else:
print(f"❌ Directory not found: {share_dir}")
print("Please enter a valid directory path.")
print()
# Count files in directory
try:
file_count = len([f for f in os.listdir(ServerConfig.SHARE_DIR)
if os.path.isfile(os.path.join(ServerConfig.SHARE_DIR, f))])
print(f"✅ Found {file_count} files in directory")
except:
file_count = 0
print()
# Get port
print("🌐 PORT CONFIGURATION:")
while True:
port_input = input(f"Enter port number (default: {ServerConfig.PORT}): ").strip()
if not port_input:
port_input = str(ServerConfig.PORT)
try:
port = int(port_input)
if 1024 <= port <= 65535:
ServerConfig.PORT = port
print(f"✅ Selected port: {port}")
break
else:
print("❌ Port must be between 1024 and 65535")
except ValueError:
print("❌ Invalid port number. Please enter a number.")
print()
print("-" * 80)
print()
# ============================================================================
# FLASK APPLICATION SETUP
# ============================================================================
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = ServerConfig.MAX_CONTENT_LENGTH
class OptimizedRequestHandler(WSGIRequestHandler):
"""Enhanced request handler with socket optimizations"""
def setup(self):
super().setup()
try:
# Set large socket buffers for maximum throughput
self.connection.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, ServerConfig.SOCKET_BUFFER_SIZE)
self.connection.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, ServerConfig.SOCKET_BUFFER_SIZE)
except Exception as e:
if ServerConfig.DEBUG_MODE:
print(f"⚠️ Socket buffer setup warning: {e}")
def format_size(size_bytes):
"""Format file size in human readable format"""
if size_bytes == 0:
return "0 B"
size_names = ["B", "KB", "MB", "GB", "TB"]
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return f"{s} {size_names[i]}"
# ============================================================================
# FILE DOWNLOAD ROUTE - Optimized for Maximum Speed
# ============================================================================
@app.route('/<path:filename>')
def download_file(filename):
"""High-performance file download with resume support"""
file_path = os.path.join(ServerConfig.SHARE_DIR, filename)
# Security and existence checks
if not os.path.exists(file_path) or not os.path.isfile(file_path):
return "❌ File not found", 404
if not os.path.abspath(file_path).startswith(os.path.abspath(ServerConfig.SHARE_DIR)):
return "❌ Access denied", 403
# File information
file_size = os.path.getsize(file_path)
mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
# Handle range requests for resume capability
range_header = request.headers.get('Range') if ServerConfig.ENABLE_RANGE_REQUESTS else None
if range_header:
return handle_range_request(file_path, file_size, range_header, mimetype, filename)
# Full file download with maximum speed streaming
def stream_file():
try:
with open(file_path, 'rb', buffering=ServerConfig.CHUNK_SIZE) as f:
while True:
chunk = f.read(ServerConfig.CHUNK_SIZE)
if not chunk:
break
yield chunk
except Exception as e:
print(f"❌ Error streaming {filename}: {e}")
return
# Prepare response headers
headers = {
'Content-Length': str(file_size),
'Content-Type': mimetype,
'Content-Disposition': f'attachment; filename="{filename}"',
'Accept-Ranges': 'bytes',
'Cache-Control': f'public, max-age={ServerConfig.CACHE_MAX_AGE}',
'Last-Modified': time.strftime('%a, %d %b %Y %H:%M:%S GMT',
time.gmtime(os.path.getmtime(file_path)))
}
return Response(stream_file(), headers=headers)
def handle_range_request(file_path, file_size, range_header, mimetype, filename):
"""Handle HTTP range requests for partial content/resume downloads"""
byte_start = 0
byte_end = file_size - 1
try:
if range_header.startswith('bytes='):
range_spec = range_header[6:]
ranges = range_spec.split(',')[0]
if '-' in ranges:
start, end = ranges.split('-', 1)
if start:
byte_start = int(start)
if end:
byte_end = min(int(end), file_size - 1)
except ValueError:
return "❌ Invalid range request", 400
if byte_start < 0 or byte_start >= file_size or byte_end < byte_start:
return "❌ Range not satisfiable", 416
content_length = byte_end - byte_start + 1
def stream_partial():
try:
with open(file_path, 'rb', buffering=ServerConfig.CHUNK_SIZE) as f:
f.seek(byte_start)
remaining = content_length
while remaining > 0:
chunk_size = min(ServerConfig.CHUNK_SIZE, remaining)
chunk = f.read(chunk_size)
if not chunk:
break
remaining -= len(chunk)
yield chunk
except Exception as e:
print(f"❌ Range request error for {filename}: {e}")
return
response = Response(
stream_partial(),
206, # Partial Content
headers={
'Content-Range': f'bytes {byte_start}-{byte_end}/{file_size}',
'Accept-Ranges': 'bytes',
'Content-Length': str(content_length),
'Content-Type': mimetype,
'Content-Disposition': f'attachment; filename="{filename}"'
}
)
return response
# ============================================================================
# FILE LISTING ROUTE - Professional UI
# ============================================================================
@app.route('/')
def list_files():
"""Professional file listing with detailed information"""
try:
files_info = []
total_size = 0
for filename in sorted(os.listdir(ServerConfig.SHARE_DIR)):
file_path = os.path.join(ServerConfig.SHARE_DIR, filename)
if os.path.isfile(file_path):
size = os.path.getsize(file_path)
total_size += size
file_info = {
'name': filename,
'size': format_size(size),
'raw_size': size,
'modified': time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime(os.path.getmtime(file_path)))
}
files_info.append(file_info)
return generate_professional_ui(files_info, total_size)
except Exception as e:
return f"❌ Error listing files: {str(e)}", 500
def generate_professional_ui(files_info, total_size):
"""Professional HTML interface with full features"""
template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>High-Performance File Server</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='0.9em' font-size='90'>🚀</text></svg>">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
min-height: 100vh;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: white;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 32px;
margin-bottom: 10px;
font-weight: 700;
}
.header p {
opacity: 0.9;
font-size: 16px;
}
.config-panel {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px 30px;
border-bottom: 1px solid rgba(102, 126, 234, 0.2);
}
.config-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin-top: 15px;
}
.config-item {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 15px;
border-radius: 8px;
border-left: 4px solid #8899e3;
}
.config-label {
font-size: 12px;
color: #eeeeff;
text-transform: uppercase;
font-weight: 600;
margin-bottom: 5px;
}
.config-value {
font-size: 18px;
color: #212529;
font-weight: 600;
}
.stats {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px 30px;
display: flex;
justify-content: space-around;
flex-wrap: wrap;
gap: 20px;
border-bottom: 1px solid rgba(102, 126, 234, 0.2);
}
.stat-item {
text-align: center;
}
.stat-value {
font-size: 28px;
font-weight: 700;
margin-bottom: 5px;
}
.stat-label {
font-size: 14px;
opacity: 0.9;
}
.content {
padding: 30px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
thead {
background: #f8f9fa;
}
th {
padding: 15px;
text-align: left;
font-weight: 600;
color: #495057;
border-bottom: 2px solid #dee2e6;
font-size: 14px;
text-transform: uppercase;
}
td {
padding: 15px;
border-bottom: 1px solid #dee2e6;
}
tr:hover {
background: #f8f9fa;
transition: background 0.2s;
}
.file-name {
display: flex;
align-items: center;
gap: 10px;
}
.file-icon {
font-size: 24px;
}
.file-link {
color: #667eea;
text-decoration: none;
font-weight: 500;
word-break: break-all;
}
.file-link:hover {
text-decoration: underline;
color: #764ba2;
}
.size-cell {
font-family: 'SF Mono', Monaco, 'Courier New', monospace;
color: #495057;
text-align: right;
}
.date-cell {
color: #6c757d;
font-size: 14px;
}
.download-btn {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 8px 16px;
border-radius: 6px;
text-decoration: none;
font-size: 13px;
font-weight: 600;
display: inline-block;
transition: transform 0.2s, box-shadow 0.2s;
}
.download-btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.empty-state {
text-align: center;
padding: 60px 20px;
color: #6c757d;
}
.empty-icon {
font-size: 64px;
margin-bottom: 20px;
}
.footer {
background: #f8f9fa;
padding: 20px 30px;
border-top: 1px solid #dee2e6;
text-align: center;
color: #6c757d;
font-size: 13px;
}
.feature-badge {
display: inline-block;
background: #28a745;
color: white;
padding: 2px 8px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
margin: 0 3px;
}
/* Mobile Responsive Styles */
@media (max-width: 768px) {
body {
padding: 10px;
}
.container {
border-radius: 8px;
}
.header h1 {
font-size: 24px;
}
.header p {
font-size: 14px;
}
.header {
padding: 20px;
}
.config-panel {
padding: 15px;
}
.config-grid {
grid-template-columns: 1fr;
gap: 10px;
}
.config-item {
padding: 12px;
}
.config-label {
font-size: 11px;
}
.config-value {
font-size: 16px;
}
.stats {
padding: 15px;
flex-direction: column;
gap: 15px;
}
.stat-item {
padding: 10px 0;
}
.stat-value {
font-size: 24px;
}
.stat-label {
font-size: 13px;
}
.content {
padding: 15px;
overflow-x: auto;
}
table {
display: block;
overflow-x: auto;
white-space: nowrap;
-webkit-overflow-scrolling: touch;
}
th, td {
padding: 10px 8px;
font-size: 13px;
}
th {
font-size: 11px;
}
.file-icon {
font-size: 20px;
}
.file-link {
font-size: 14px;
}
.size-cell {
font-size: 13px;
}
.date-cell {
font-size: 12px;
}
.download-btn {
padding: 6px 12px;
font-size: 12px;
}
.footer {
padding: 15px;
font-size: 12px;
}
.empty-state {
padding: 40px 15px;
}
.empty-icon {
font-size: 48px;
}
}
/* Extra small devices */
@media (max-width: 480px) {
.header h1 {
font-size: 20px;
}
.header p {
font-size: 13px;
}
.config-value {
font-size: 14px;
}
.stat-value {
font-size: 20px;
}
th, td {
padding: 8px 6px;
font-size: 12px;
}
.file-name {
gap: 5px;
}
.file-icon {
font-size: 18px;
}
.file-link {
font-size: 13px;
}
.download-btn {
padding: 5px 10px;
font-size: 11px;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🚀 High-Performance File Server</h1>
<p>Maximum Speed • Resume Support • Multi-User Ready</p>
</div>
<div class="config-panel">
<div style="font-size: 14px; font-weight: 600; color: #ffffff; margin-bottom: 10px;">
⚙️ Server Configuration
</div>
<div class="config-grid">
<div class="config-item">
<div class="config-label">Speed Mode</div>
<div class="config-value">⚡ Maximum</div>
</div>
<div class="config-item">
<div class="config-label">Chunk Size</div>
<div class="config-value">{{ chunk_size }}</div>
</div>
<div class="config-item">
<div class="config-label">Socket Buffer</div>
<div class="config-value">{{ socket_buffer }}</div>
</div>
<div class="config-item">
<div class="config-label">Features</div>
<div class="config-value" style="font-size: 14px;">
<span class="feature-badge">Resume</span>
<span class="feature-badge">Cache</span>
<span class="feature-badge">Multi-User</span>
</div>
</div>
</div>
</div>
<div class="stats">
<div class="stat-item">
<div class="stat-value">{{ file_count }}</div>
<div class="stat-label">Total Files</div>
</div>
<div class="stat-item">
<div class="stat-value">{{ total_size }}</div>
<div class="stat-label">Total Size</div>
</div>
<div class="stat-item">
<div class="stat-value">{{ max_file_size }}</div>
<div class="stat-label">Max File Limit</div>
</div>
</div>
<div class="content">
{% if files_info %}
<table>
<thead>
<tr>
<th style="width: 50%;">📁 File Name</th>
<th style="width: 15%;">📊 Size</th>
<th style="width: 20%;">🕒 Modified</th>
<th style="width: 15%; text-align: center;">⬇️ Action</th>
</tr>
</thead>
<tbody>
{% for file in files_info %}
<tr>
<td>
<div class="file-name">
<span class="file-icon">📄</span>
<a href="/{{ file.name }}" class="file-link" title="Click to download {{ file.name }}">
{{ file.name }}
</a>
</div>
</td>
<td class="size-cell">{{ file.size }}</td>
<td class="date-cell">{{ file.modified }}</td>
<td style="text-align: center;">
<a href="/{{ file.name }}" class="download-btn">
Download
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<div class="empty-state">
<div class="empty-icon">📂</div>
<h3>No Files Available</h3>
<p>The shared directory is empty.</p>
</div>
{% endif %}
</div>
<div class="footer">
<strong>High-Performance File Server</strong> •
Optimized for maximum speed with {{ chunk_size }} chunks •
Resume downloads enabled •
Multi-user support active
</div>
</div>
</body>
</html>
"""
return render_template_string(
template,
files_info=files_info,
file_count=len(files_info),
total_size=format_size(total_size),
chunk_size=format_size(ServerConfig.CHUNK_SIZE),
socket_buffer=format_size(ServerConfig.SOCKET_BUFFER_SIZE),
max_file_size=f"{ServerConfig.MAX_FILE_SIZE_GB} GB"
)
# ============================================================================
# MAIN EXECUTION
# ============================================================================
def get_local_ip():
"""Get local IP address for LAN access"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
except:
return "Unable to detect"
def display_startup_info():
"""Display server configuration and start info"""
print("=" * 80)
print("📋 SERVER CONFIGURATION:")
print("-" * 80)
print(f"📦 Chunk Size: {ServerConfig.CHUNK_SIZE_MB} MB")
print(f"🔧 Socket Buffer: {ServerConfig.SOCKET_BUFFER_MB} MB")
print(f"📊 Max File Size: {ServerConfig.MAX_FILE_SIZE_GB} GB")
print(f"⚡ Speed Mode: MAXIMUM")
print(f"♻️ Resume Downloads: {'✅ Enabled' if ServerConfig.ENABLE_RANGE_REQUESTS else '❌ Disabled'}")
print(f"👥 Multi-User Support: {'✅ Enabled (Threading)' if ServerConfig.ENABLE_THREADING else '❌ Disabled'}")
print(f"💾 HTTP Caching: {'✅ Enabled' if ServerConfig.ENABLE_CACHE else '❌ Disabled'} ({ServerConfig.CACHE_HOURS}h)")
print("=" * 80)
print()
print("✅ SERVER STARTED SUCCESSFULLY!")
print()
print("💡 SHARING TIPS:")
print(" • Use Local URLs on this computer")
print(" • Use Network URL on your local network (LAN)")
print(" • For internet sharing, we will use Cloudflare Tunnel")
print()
print("🛑 Press CTRL+C to stop the server")
print("-" * 80)
print()
def display_clarified_urls():
"""Display clarified URLs after Flask starts"""
time.sleep(1.5) # Wait for Flask to print its messages
local_ip = get_local_ip()
print()
print("📡 ACCESS YOUR FILES:")
print(f" • http://127.0.0.1:{ServerConfig.PORT} (for this pc)")
if local_ip != "Unable to detect":
print(f" • http://{local_ip}:{ServerConfig.PORT} (for same wifi pc)")
# Wait for Cloudflare URL to be captured (up to 10 seconds)
wait_time = 0
max_wait = 10
while not ServerConfig.CLOUDFLARE_URL and wait_time < max_wait:
time.sleep(0.5)
wait_time += 0.5
# Display Cloudflare URL if available
if ServerConfig.CLOUDFLARE_URL:
print(f" • {ServerConfig.CLOUDFLARE_URL} (for global share)")
else:
print(" • Cloudflare Tunnel starting... (check separate window for URL)")
print()
def find_cloudflared():
"""Find cloudflared.exe on the system or in bundled resources"""
# Check if running as PyInstaller bundle
if getattr(sys, 'frozen', False):
# Running as compiled executable
# PyInstaller creates a temp folder and stores path in _MEIPASS
bundle_dir = sys._MEIPASS
bundled_cloudflared = os.path.join(bundle_dir, "cloudflared.exe")
if os.path.exists(bundled_cloudflared):
return bundled_cloudflared
# Common installation paths
possible_paths = [
os.path.join(os.getcwd(), "cloudflared.exe"), # Current directory (for dev)
r"C:\Program Files\cloudflared\cloudflared.exe",
r"C:\Program Files (x86)\cloudflared\cloudflared.exe",
"cloudflared.exe", # Check if it's in PATH
]
for path in possible_paths:
if os.path.exists(path):
return path
# Try to find it using 'where' command
try:
result = subprocess.run(['where', 'cloudflared'],
capture_output=True,
text=True,
timeout=5)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip().split('\n')[0]
except:
pass
return None
def start_cloudflare_tunnel():
"""Start Cloudflare Tunnel and capture URL for display"""
cloudflared_path = find_cloudflared()
if not cloudflared_path:
print("⚠️ Cloudflare Tunnel: cloudflared.exe not found")
print(" Download from: https://github.com/cloudflare/cloudflared/releases")
print(" Or install with: winget install --id Cloudflare.cloudflared")
return
# Kill any existing cloudflared processes first
print("🔄 Checking for existing Cloudflare tunnels...")
kill_existing_cloudflared_processes()
try:
print("🌐 Starting Cloudflare Tunnel...")
# Start cloudflared with hidden window and captured output
startupinfo = None
if sys.platform == 'win32':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
process = subprocess.Popen(
[cloudflared_path, 'tunnel', '--protocol', 'http2', '--url', f'http://localhost:{ServerConfig.PORT}'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.DEVNULL,
text=True,
bufsize=0, # Unbuffered for immediate output
startupinfo=startupinfo,
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0
)
ServerConfig.CLOUDFLARE_PROCESS = process
# Read output asynchronously to capture URL without blocking tunnel performance
import threading
def read_tunnel_output():
url_pattern = re.compile(r'https://[a-z0-9-]+\.trycloudflare\.com')
try:
# Read only the first few lines to get the URL, then stop reading to avoid blocking
lines_read = 0
max_lines = 50 # Only read first 50 lines
for line in process.stdout:
if lines_read >= max_lines or ServerConfig.CLOUDFLARE_URL:
# Stop reading after getting URL to maintain maximum performance
break
match = url_pattern.search(line)
if match:
ServerConfig.CLOUDFLARE_URL = match.group(0)
time.sleep(0.5) # Small delay before printing
print(f"\n✅ Cloudflare Tunnel active: {ServerConfig.CLOUDFLARE_URL}")
# Try to copy to clipboard
try:
subprocess.run(['clip'], input=ServerConfig.CLOUDFLARE_URL,
text=True, check=True, timeout=2)
print("📋 URL copied to clipboard!")
except:
pass
break
lines_read += 1
except Exception as e:
if ServerConfig.DEBUG_MODE:
print(f"⚠️ Tunnel output read error: {e}")
tunnel_thread = threading.Thread(target=read_tunnel_output, daemon=True)
tunnel_thread.start()
except Exception as e:
print(f"⚠️ Failed to start Cloudflare Tunnel: {e}")
def stop_cloudflare_tunnel():
"""Stop Cloudflare Tunnel process"""
if ServerConfig.CLOUDFLARE_PROCESS:
try:
ServerConfig.CLOUDFLARE_PROCESS.terminate()
ServerConfig.CLOUDFLARE_PROCESS.wait(timeout=5)
except:
try:
ServerConfig.CLOUDFLARE_PROCESS.kill()
except:
pass
def kill_existing_cloudflared_processes():
"""Kill any existing cloudflared processes to prevent multiple tunnels"""
try:
if sys.platform == 'win32':
# Use taskkill on Windows to terminate any existing cloudflared processes
result = subprocess.run(['taskkill', '/F', '/IM', 'cloudflared.exe'],
capture_output=True, text=True, timeout=10)
# Also kill any processes listening on the port we want to use
try:
subprocess.run(['netstat', '-ano'], capture_output=True, text=True, timeout=5)
except:
pass
else:
# Use pkill on Unix-like systems
subprocess.run(['pkill', '-f', 'cloudflared'],
capture_output=True, text=True, timeout=10)
# Wait a moment for processes to fully terminate
time.sleep(2)
except Exception as e:
if ServerConfig.DEBUG_MODE:
print(f"⚠️ Note: Could not check for existing cloudflared processes: {e}")
pass
def cleanup_on_exit():
"""Enhanced cleanup function for application exit"""
try:
# Stop current process if it exists
stop_cloudflare_tunnel()
# Kill any remaining cloudflared processes
kill_existing_cloudflared_processes()
except:
pass
def main():
"""Main entry point"""
try:
# STEP 1: Clean up any existing cloudflared processes first
kill_existing_cloudflared_processes()
# STEP 2: Get user configuration
get_user_configuration()
# STEP 3: Display configuration
display_startup_info()
# STEP 4: Start Cloudflare Tunnel
start_cloudflare_tunnel()