-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
825 lines (683 loc) · 25.5 KB
/
Copy pathmain.py
File metadata and controls
825 lines (683 loc) · 25.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
from flask import (
Flask,
render_template,
request,
redirect,
url_for,
send_file,
flash,
jsonify,
)
import os
import zipfile
from werkzeug.utils import secure_filename
from datetime import datetime
import shutil
import socket
import mimetypes
import json
import time
app = Flask(__name__)
# Upload progress tracking
upload_progress = {}
# Load configuration
try:
from config import *
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config["MAX_CONTENT_LENGTH"] = MAX_FILE_SIZE
app.secret_key = SECRET_KEY
except ImportError:
# Fallback configuration
UPLOAD_FOLDER = "uploads"
ALLOWED_EXTENSIONS = {
"txt",
"pdf",
"png",
"jpg",
"jpeg",
"gif",
"bmp",
"webp",
"doc",
"docx",
"xls",
"xlsx",
"ppt",
"pptx",
"zip",
"rar",
"7z",
"mp3",
"wav",
"ogg",
"mp4",
"avi",
"mov",
"mkv",
"webm",
"flv",
"wmv",
}
MAX_FILE_SIZE = 100 * 1024 * 1024 # 100MB
HOST = "0.0.0.0"
PORT = 5000
DEBUG = True
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config["MAX_CONTENT_LENGTH"] = MAX_FILE_SIZE
app.secret_key = "your-secret-key-here"
# Create upload directory if it doesn't exist
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
def allowed_file(filename):
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
def get_file_size(filepath):
"""Get file size in human readable format"""
size = os.path.getsize(filepath)
for unit in ["B", "KB", "MB", "GB"]:
if size < 1024.0:
return f"{size:.1f} {unit}"
size /= 1024.0
return f"{size:.1f} TB"
def get_total_storage_used():
"""Calculate total storage used"""
total_size = 0
if os.path.exists(UPLOAD_FOLDER):
for filename in os.listdir(UPLOAD_FOLDER):
filepath = os.path.join(UPLOAD_FOLDER, filename)
if os.path.isfile(filepath):
total_size += os.path.getsize(filepath)
return total_size
def get_local_ip():
"""Get the local IP address"""
try:
# Connect to a remote server to get local IP
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 "127.0.0.1"
@app.route("/")
def index():
current_folder = request.args.get("folder", "")
upload_path = os.path.join(UPLOAD_FOLDER, current_folder)
if not os.path.exists(upload_path):
upload_path = UPLOAD_FOLDER
current_folder = ""
# Get list of uploaded files and folders
files = []
folders = []
if os.path.exists(upload_path):
for item in os.listdir(upload_path):
item_path = os.path.join(upload_path, item)
if os.path.isdir(item_path):
folders.append(
{
"name": item,
"path": (
os.path.join(current_folder, item).replace("\\", "/")
if current_folder
else item
),
}
)
elif os.path.isfile(item_path):
files.append(
{
"name": item,
"size": get_file_size(item_path),
"modified": datetime.fromtimestamp(
os.path.getmtime(item_path)
).strftime("%Y-%m-%d %H:%M:%S"),
"path": (
os.path.join(current_folder, item).replace("\\", "/")
if current_folder
else item
),
}
)
# Sort files by modification time (newest first)
files.sort(key=lambda x: x["modified"], reverse=True)
# Parent folder navigation
parent_folder = None
if current_folder:
parent_parts = current_folder.split("/")
if len(parent_parts) > 1:
parent_folder = "/".join(parent_parts[:-1])
else:
parent_folder = ""
# Get storage info
total_used = get_total_storage_used()
total_used_mb = total_used / (1024 * 1024)
return render_template(
"index.html",
files=files,
folders=folders,
current_folder=current_folder,
parent_folder=parent_folder,
total_used=(
get_file_size(UPLOAD_FOLDER) if os.path.exists(UPLOAD_FOLDER) else "0 B"
),
file_count=len(files),
)
@app.route("/upload", methods=["POST"])
def upload_file():
if "file" not in request.files:
flash("Aucun fichier sélectionné")
return redirect(request.url)
current_folder = request.form.get("current_folder", "")
upload_path = os.path.join(UPLOAD_FOLDER, current_folder)
if not os.path.exists(upload_path):
os.makedirs(upload_path)
files = request.files.getlist("file")
uploaded_files = []
errors = []
# Check total storage limit
current_storage = get_total_storage_used()
for file in files:
if file.filename == "":
continue
# Check if file type is allowed
if not allowed_file(file.filename):
errors.append(f"Type de fichier non autorisé: {file.filename}")
continue
# Check storage limit (if defined)
try:
if "MAX_TOTAL_SIZE" in globals() and current_storage > MAX_TOTAL_SIZE:
errors.append("Limite de stockage atteinte")
break
except:
pass
filename = secure_filename(file.filename)
filepath = os.path.join(upload_path, filename)
# Handle duplicate filenames
counter = 1
original_filename = filename
while os.path.exists(filepath):
name, ext = os.path.splitext(original_filename)
filename = f"{name}_{counter}{ext}"
filepath = os.path.join(upload_path, filename)
counter += 1
try:
file.save(filepath)
uploaded_files.append(filename)
current_storage += os.path.getsize(filepath)
except Exception as e:
errors.append(f"Erreur lors de l'upload de {file.filename}: {str(e)}")
# Show results
if uploaded_files:
flash(f'Fichier(s) uploadé(s) avec succès: {", ".join(uploaded_files)}')
for error in errors:
flash(error)
folder_param = f"?folder={current_folder}" if current_folder else ""
return redirect(url_for("index") + folder_param)
@app.route("/upload_with_progress", methods=["POST"])
def upload_file_with_progress():
"""Upload files with progress tracking"""
if "file" not in request.files:
return jsonify({"error": "Aucun fichier sélectionné"}), 400
current_folder = request.form.get("current_folder", "")
upload_path = os.path.join(UPLOAD_FOLDER, current_folder)
if not os.path.exists(upload_path):
os.makedirs(upload_path)
files = request.files.getlist("file")
session_id = request.form.get("session_id", str(time.time()))
# Initialize progress tracking
upload_progress[session_id] = {
"total_files": len(files),
"completed_files": 0,
"current_file": "",
"current_file_progress": 0,
"total_bytes": 0,
"transferred_bytes": 0,
"status": "starting",
"uploaded_files": [],
"errors": [],
}
# Calculate total bytes
total_bytes = 0
file_sizes = []
for file in files:
if file.filename:
# Get file size by seeking to end
file.seek(0, 2)
size = file.tell()
file.seek(0)
file_sizes.append(size)
total_bytes += size
upload_progress[session_id]["total_bytes"] = total_bytes
# Check total storage limit
current_storage = get_total_storage_used()
if "MAX_TOTAL_SIZE" in globals() and current_storage + total_bytes > MAX_TOTAL_SIZE:
upload_progress[session_id]["status"] = "error"
upload_progress[session_id]["errors"].append("Limite de stockage dépassée")
return jsonify({"error": "Limite de stockage dépassée"}), 413
uploaded_files = []
errors = []
transferred_bytes = 0
for i, file in enumerate(files):
if file.filename == "":
continue
# Update progress
upload_progress[session_id]["current_file"] = file.filename
upload_progress[session_id]["current_file_progress"] = 0
upload_progress[session_id]["status"] = "uploading"
# Check if file type is allowed
if not allowed_file(file.filename):
error_msg = f"Type de fichier non autorisé: {file.filename}"
errors.append(error_msg)
upload_progress[session_id]["errors"].append(error_msg)
continue
filename = secure_filename(file.filename)
filepath = os.path.join(upload_path, filename)
# Handle duplicate filenames
counter = 1
original_filename = filename
while os.path.exists(filepath):
name, ext = os.path.splitext(original_filename)
filename = f"{name}_{counter}{ext}"
filepath = os.path.join(upload_path, filename)
counter += 1
try:
# Save file with progress tracking
file_size = file_sizes[i] if i < len(file_sizes) else 0
chunk_size = 64 * 1024 # 64KB chunks
with open(filepath, "wb") as f:
bytes_written = 0
while True:
chunk = file.read(chunk_size)
if not chunk:
break
f.write(chunk)
bytes_written += len(chunk)
transferred_bytes += len(chunk)
# Update progress
file_progress = (
(bytes_written / file_size * 100) if file_size > 0 else 100
)
upload_progress[session_id]["current_file_progress"] = file_progress
upload_progress[session_id]["transferred_bytes"] = transferred_bytes
uploaded_files.append(filename)
upload_progress[session_id]["uploaded_files"].append(filename)
upload_progress[session_id]["completed_files"] += 1
except Exception as e:
error_msg = f"Erreur lors de l'upload de {file.filename}: {str(e)}"
errors.append(error_msg)
upload_progress[session_id]["errors"].append(error_msg)
# Final status
upload_progress[session_id]["status"] = "completed"
upload_progress[session_id]["current_file"] = ""
upload_progress[session_id]["current_file_progress"] = 100
return jsonify(
{
"success": True,
"uploaded_files": uploaded_files,
"errors": errors,
"session_id": session_id,
}
)
@app.route("/upload_progress/<session_id>")
def get_upload_progress(session_id):
"""Get upload progress for a session"""
if session_id not in upload_progress:
return jsonify({"error": "Session non trouvée"}), 404
progress = upload_progress[session_id].copy()
# Calculate overall progress percentage
if progress["total_bytes"] > 0:
progress["overall_progress"] = (
progress["transferred_bytes"] / progress["total_bytes"]
) * 100
else:
progress["overall_progress"] = 100 if progress["status"] == "completed" else 0
# Clean up completed sessions after 60 seconds
if progress["status"] == "completed":
import threading
def cleanup():
time.sleep(60)
if session_id in upload_progress:
del upload_progress[session_id]
threading.Thread(target=cleanup).start()
return jsonify(progress)
@app.route("/download/<filename>")
def download_file(filename):
try:
return send_file(
os.path.join(app.config["UPLOAD_FOLDER"], filename),
as_attachment=True,
download_name=filename,
)
except FileNotFoundError:
flash("Fichier non trouvé")
return redirect(url_for("index"))
@app.route("/preview/image/<filename>")
def preview_image(filename):
"""Serve image files for preview"""
try:
return send_file(
os.path.join(app.config["UPLOAD_FOLDER"], filename), as_attachment=False
)
except FileNotFoundError:
# Return a default image or error image
return "", 404
@app.route("/preview/video/<filename>")
def preview_video(filename):
"""Serve video files for preview with range support"""
try:
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
if not os.path.exists(filepath):
return "", 404
# Get file size and mime type
file_size = os.path.getsize(filepath)
mime_type, _ = mimetypes.guess_type(filepath)
if not mime_type or not mime_type.startswith("video/"):
# Fallback for video files
ext = filename.rsplit(".", 1)[-1].lower()
video_types = {
"mp4": "video/mp4",
"avi": "video/x-msvideo",
"mov": "video/quicktime",
"mkv": "video/x-matroska",
"webm": "video/webm",
}
mime_type = video_types.get(ext, "video/mp4")
# Handle range requests for video streaming
range_header = request.headers.get("Range", None)
if range_header:
# Parse range header
byte_start = 0
byte_end = file_size - 1
range_match = range_header.replace("bytes=", "").split("-")
if len(range_match) == 2:
if range_match[0]:
byte_start = int(range_match[0])
if range_match[1]:
byte_end = int(range_match[1])
# Ensure byte_end doesn't exceed file size
byte_end = min(byte_end, file_size - 1)
content_length = byte_end - byte_start + 1
# Read the requested range
with open(filepath, "rb") as f:
f.seek(byte_start)
data = f.read(content_length)
# Create response with partial content
from flask import Response
response = Response(
data,
206, # Partial Content
headers={
"Content-Range": f"bytes {byte_start}-{byte_end}/{file_size}",
"Accept-Ranges": "bytes",
"Content-Length": str(content_length),
"Content-Type": mime_type,
},
)
return response
else:
# Return full file if no range requested
from flask import Response
with open(filepath, "rb") as f:
data = f.read()
response = Response(
data,
200,
headers={
"Content-Length": str(file_size),
"Content-Type": mime_type,
"Accept-Ranges": "bytes",
},
)
return response
except FileNotFoundError:
return "", 404
except Exception as e:
print(f"Error serving video: {e}")
return "", 500
@app.route("/preview/text/<filename>")
def preview_text(filename):
"""Serve text files content for preview"""
try:
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
# Check if file exists
if not os.path.exists(filepath):
return jsonify({"error": "Fichier non trouvé"}), 404
# Get file extension
ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
# Define text file extensions
text_extensions = [
"txt",
"md",
"py",
"js",
"html",
"css",
"json",
"xml",
"csv",
"log",
"ini",
"cfg",
"yml",
"yaml",
]
if ext not in text_extensions:
return (
jsonify({"error": "Type de fichier non supporté pour la lecture"}),
400,
)
# Try to read the file with different encodings
encodings = ["utf-8", "latin-1", "cp1252", "iso-8859-1"]
content = None
encoding_used = None
for encoding in encodings:
try:
with open(filepath, "r", encoding=encoding) as file:
content = file.read()
encoding_used = encoding
break
except UnicodeDecodeError:
continue
if content is None:
return (
jsonify(
{
"error": "Impossible de lire le fichier avec les encodages supportés"
}
),
400,
)
# Limit content size for display (max 50KB)
if len(content) > 50000:
content = (
content[:50000]
+ "\n\n... [Fichier tronqué - trop volumineux pour l'affichage]"
)
return jsonify(
{
"content": content,
"encoding": encoding_used,
"size": os.path.getsize(filepath),
"lines": len(content.split("\n")),
}
)
except Exception as e:
return jsonify({"error": f"Erreur lors de la lecture: {str(e)}"}), 500
@app.route("/delete/<filename>")
def delete_file(filename):
try:
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
if os.path.exists(filepath):
os.remove(filepath)
flash(f"Fichier {filename} supprimé avec succès")
else:
flash("Fichier non trouvé")
except Exception as e:
flash(f"Erreur lors de la suppression: {str(e)}")
return redirect(url_for("index"))
@app.route("/download_all")
def download_all():
"""Create a zip file with all uploaded files and download it"""
try:
if not os.path.exists(app.config["UPLOAD_FOLDER"]) or not os.listdir(
app.config["UPLOAD_FOLDER"]
):
flash("Aucun fichier à télécharger")
return redirect(url_for("index"))
zip_filename = f'all_files_{datetime.now().strftime("%Y%m%d_%H%M%S")}.zip'
zip_path = os.path.join(app.config["UPLOAD_FOLDER"], zip_filename)
with zipfile.ZipFile(zip_path, "w") as zip_file:
for filename in os.listdir(app.config["UPLOAD_FOLDER"]):
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
if os.path.isfile(filepath) and filename != zip_filename:
zip_file.write(filepath, filename)
return send_file(zip_path, as_attachment=True, download_name=zip_filename)
except Exception as e:
flash(f"Erreur lors de la création du zip: {str(e)}")
return redirect(url_for("index"))
@app.route("/clear_all", methods=["POST"])
def clear_all():
"""Delete all uploaded files"""
try:
count = 0
for filename in os.listdir(app.config["UPLOAD_FOLDER"]):
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
if os.path.isfile(filepath):
os.remove(filepath)
count += 1
flash(f"Tous les fichiers ont été supprimés ({count} fichiers)")
except Exception as e:
flash(f"Erreur lors de la suppression: {str(e)}")
return redirect(url_for("index"))
@app.route("/api/stats")
def api_stats():
"""API endpoint for statistics"""
files = []
if os.path.exists(UPLOAD_FOLDER):
for filename in os.listdir(UPLOAD_FOLDER):
filepath = os.path.join(UPLOAD_FOLDER, filename)
if os.path.isfile(filepath):
files.append(filename)
return jsonify(
{
"file_count": len(files),
"total_storage": get_total_storage_used(),
"files": files,
}
)
@app.route("/test_video.html")
def test_video():
"""Test page for video player"""
return send_file("test_video.html")
@app.route("/create_folder", methods=["POST"])
def create_folder():
"""Create a new folder"""
folder_name = request.form.get("folder_name", "").strip()
current_folder = request.form.get("current_folder", "")
if not folder_name:
flash("Nom de dossier requis")
folder_param = f"?folder={current_folder}" if current_folder else ""
return redirect(url_for("index") + folder_param)
folder_name = secure_filename(folder_name)
new_folder_path = os.path.join(UPLOAD_FOLDER, current_folder, folder_name)
try:
if not os.path.exists(new_folder_path):
os.makedirs(new_folder_path)
flash(f"Dossier '{folder_name}' créé avec succès")
else:
flash(f"Le dossier '{folder_name}' existe déjà")
except Exception as e:
flash(f"Erreur lors de la création du dossier: {str(e)}")
folder_param = f"?folder={current_folder}" if current_folder else ""
return redirect(url_for("index") + folder_param)
@app.route("/move_file", methods=["POST"])
def move_file():
"""Move file to different folder via drag & drop"""
filename = request.form.get("filename")
source_folder = request.form.get("source_folder", "")
target_folder = request.form.get("target_folder", "")
if not filename:
return jsonify({"success": False, "message": "Nom de fichier requis"})
source_path = os.path.join(UPLOAD_FOLDER, source_folder, filename)
target_path = os.path.join(UPLOAD_FOLDER, target_folder, filename)
try:
if not os.path.exists(source_path):
return jsonify({"success": False, "message": "Fichier source introuvable"})
target_dir = os.path.dirname(target_path)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
# Handle duplicate filenames
counter = 1
original_filename = filename
while os.path.exists(target_path):
name, ext = os.path.splitext(original_filename)
new_filename = f"{name}_{counter}{ext}"
target_path = os.path.join(UPLOAD_FOLDER, target_folder, new_filename)
counter += 1
shutil.move(source_path, target_path)
return jsonify({"success": True, "message": "Fichier déplacé avec succès"})
except Exception as e:
return jsonify({"success": False, "message": f"Erreur: {str(e)}"})
@app.route("/download/<path:filepath>")
def download_file_with_path(filepath):
"""Download file with folder path"""
try:
full_path = os.path.join(UPLOAD_FOLDER, filepath)
if not os.path.exists(full_path):
flash("Fichier non trouvé")
return redirect(url_for("index"))
filename = os.path.basename(filepath)
return send_file(full_path, as_attachment=True, download_name=filename)
except Exception as e:
flash(f"Erreur lors du téléchargement: {str(e)}")
return redirect(url_for("index"))
@app.route("/delete/<path:filepath>")
def delete_file_with_path(filepath):
"""Delete file with folder path"""
try:
full_path = os.path.join(UPLOAD_FOLDER, filepath)
if os.path.exists(full_path):
os.remove(full_path)
flash(f"Fichier '{os.path.basename(filepath)}' supprimé avec succès")
else:
flash("Fichier non trouvé")
except Exception as e:
flash(f"Erreur lors de la suppression: {str(e)}")
# Redirect to the folder containing the file
folder = os.path.dirname(filepath)
folder_param = f"?folder={folder}" if folder else ""
return redirect(url_for("index") + folder_param)
@app.route("/preview/image/<path:filepath>")
def preview_image_with_path(filepath):
"""Serve image files for preview with folder path"""
try:
full_path = os.path.join(UPLOAD_FOLDER, filepath)
if not os.path.exists(full_path):
return "", 404
return send_file(full_path, as_attachment=False)
except Exception:
return "", 404
@app.route("/preview/text/<path:filepath>")
def preview_text_with_path(filepath):
"""Serve text files for preview with folder path"""
try:
full_path = os.path.join(UPLOAD_FOLDER, filepath)
if not os.path.exists(full_path):
return jsonify({"error": "Fichier non trouvé"}), 404
with open(full_path, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
return jsonify({"content": content, "filename": os.path.basename(filepath)})
except Exception as e:
return jsonify({"error": f"Erreur lors de la lecture: {str(e)}"}), 500
if __name__ == "__main__":
local_ip = get_local_ip()
print("\n" + "=" * 50)
print(" LocalTransfer - Application de transfert de fichiers")
print("=" * 50)
print(f"🌐 Application accessible à:")
print(f" • Localement: http://localhost:{PORT}")
print(f" • Sur le réseau: http://{local_ip}:{PORT}")
print("\n💡 Partagez l'URL du réseau avec votre famille!")
print("📁 Les fichiers sont stockés dans le dossier 'uploads'")
print("⚠️ Appuyez sur Ctrl+C pour arrêter l'application")
print("=" * 50 + "\n")
app.run(debug=DEBUG, host=HOST, port=PORT)