-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
159 lines (129 loc) · 4.77 KB
/
Copy pathapp.py
File metadata and controls
159 lines (129 loc) · 4.77 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
from flask import Flask, redirect, render_template, send_file, request, jsonify
from Funciones import Qr_Generator
from Funciones import Show_File as Show_File
from Funciones.paths import ensure_runtime_dirs, qr_path, static_dir, templates_dir
import os
from werkzeug.utils import secure_filename
import secrets
import urllib.request
import sys
import threading
import webview
import time
# Funciones propias
from Funciones.ip import sacar_ip
from Funciones.configuracion import ALLOWED_EXTENSIONS, MAX_FILE_SIZE
from Funciones.abrirNavegador import abrir_navegador
from Funciones.close import esta_cerrado
#Lanzador
from Lanzador.main import Iniciador
app = Flask(__name__, template_folder=templates_dir(), static_folder=static_dir())
app.config['SECRET_KEY'] = secrets.token_hex(32)
app.config['MAX_CONTENT_LENGTH'] = MAX_FILE_SIZE
# Carpeta de destino en static/File
Files_Carpet = os.path.join(app.static_folder, 'Files')
if not os.path.exists(Files_Carpet):
os.makedirs(Files_Carpet)
def allowed_file(filename):
"""Permite archivos con extensiones válidas o archivos sin extensión (opcional)."""
if '.' not in filename:
return True # Permitimos archivos sin extensión por si son binarios de Linux
return filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# --- RUTAS ---
@app.route('/')
def index():
File = Show_File.Show_File()
return render_template('index.html', File=File)
@app.route('/upload', methods=['POST'])
def upload():
if request.method == 'POST':
if 'UPFile' not in request.files:
return redirect('/update')
f = request.files.get('UPFile')
if not f or f.filename == '':
return redirect('/update')
filename = secure_filename(f.filename)
if allowed_file(filename):
file_path = os.path.join(Files_Carpet, filename)
try:
f.save(file_path)
return redirect('/')
except Exception as e:
return redirect('/update')
else:
print(f"🚫 Extensión no permitida: {filename}")
return redirect('/update')
return redirect('/')
@app.route('/descarga/<filename>', methods=['GET'])
def descarga(filename):
filename = secure_filename(filename)
file_path = os.path.join(Files_Carpet, filename)
if not os.path.exists(file_path):
return redirect('/')
try:
return send_file(file_path, as_attachment=True, download_name=filename)
except Exception as e:
print(f"Error al descargar {filename}: {e}")
return redirect('/')
@app.route('/eliminar/<filename>', methods=['POST', 'GET'])
def eliminar(filename):
filename = secure_filename(filename)
file_path = os.path.join(Files_Carpet, filename)
if not os.path.exists(file_path):
return redirect('/')
try:
os.remove(file_path)
print(f"✓ Archivo eliminado: {filename}")
except Exception as e:
print(f"Error al eliminar {filename}: {e}")
return redirect('/')
@app.route('/update')
def update():
return render_template('Up_Data.html')
@app.route('/qrgenerator')
def QR_Generador_Vista():
return render_template('Qr_Generator.html')
@app.route('/qr-image')
def qr_image():
if not os.path.exists(qr_path()):
Qr_Generator.Generar_QR()
return send_file(qr_path())
@app.route('/qr')
def qr():
Qr_Generator.Generar_QR()
return redirect('/qrgenerator')
def ejecutar_servidor():
"""Función para correr Flask en el hilo secundario."""
app.run(debug=True, host="0.0.0.0", port=5000, use_reloader=False)
def arrancar_webview():
"""Función para correr la interfaz ligera nativa en el hilo principal."""
time.sleep(0.8)
webview.create_window(
title='NetDrop Desktop',
url='http://127.0.0.1:5000',
width=850,
height=650,
min_size=(850, 650),
resizable=True
)
webview.start()
if __name__ == '__main__':
if esta_cerrado():
# Escenario 1: El servidor está apagado. Arrancamos de cero.
if not os.environ.get('WERKZEUG_RUN_MAIN'):
print(f"🚀 Iniciando NetDrop en: http://{sacar_ip()}:5000")
Qr_Generator.Generar_QR()
# 1. Lanzamos el servidor Flask en segundo plano
servidor_thread = threading.Thread(target=ejecutar_servidor)
servidor_thread.daemon = True
servidor_thread.start()
# 2. Levantamos el WebView ligero en el hilo principal
arrancar_webview()
else:
# Escenario 2: Ya hay una instancia de NetDrop abierta.
print("\n" + "="*40)
print("⚠️ NETDROP YA ESTÁ EN EJECUCIÓN")
print(f"🔗 Abriendo pestaña en: http://{sacar_ip()}:5000")
print("="*40 + "\n")
abrir_navegador()
sys.exit()