-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_simple.py
More file actions
2024 lines (1690 loc) · 95.2 KB
/
main_simple.py
File metadata and controls
2024 lines (1690 loc) · 95.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
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
# -*- coding: utf-8 -*-
"""
Aplicación de Copia de Seguridad Rápida para Windows
Versión Simplificada y Funcional
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
import shutil
import zipfile
import threading
from datetime import datetime
from pathlib import Path
import json
import time
import hashlib
import subprocess
from collections import defaultdict
import re
# Importación opcional de psutil
try:
import psutil
PSUTIL_AVAILABLE = True
except ImportError:
PSUTIL_AVAILABLE = False
print("Advertencia: psutil no está disponible. Algunas funciones de monitoreo del sistema estarán deshabilitadas.")
# Nombres reservados de Windows
NOMBRES_RESERVADOS_WINDOWS = {
'con', 'prn', 'aux', 'nul',
'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9',
'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9'
}
# Caracteres problemáticos en nombres de archivos
CARACTERES_PROBLEMATICOS = r'[<>:"|?*\x00-\x1f]'
def es_nombre_reservado_windows(nombre):
"""Verificar si un nombre de archivo es reservado en Windows"""
if not nombre:
return False
# Obtener solo el nombre base sin extensión
nombre_base = os.path.splitext(nombre.lower())[0]
return nombre_base in NOMBRES_RESERVADOS_WINDOWS
def tiene_caracteres_problematicos(ruta):
"""Verificar si una ruta contiene caracteres problemáticos"""
return bool(re.search(CARACTERES_PROBLEMATICOS, ruta))
def normalizar_ruta(ruta):
"""Normalizar ruta convirtiendo separadores mixtos y resolviendo problemas"""
if not ruta:
return ""
try:
# Convertir todos los separadores a formato Windows
ruta_normalizada = ruta.replace('/', '\\')
# Remover separadores duplicados
while '\\\\' in ruta_normalizada:
ruta_normalizada = ruta_normalizada.replace('\\\\', '\\')
# Normalizar la ruta usando os.path
ruta_normalizada = os.path.normpath(ruta_normalizada)
return ruta_normalizada
except Exception:
return ruta
def es_ruta_muy_larga(ruta):
"""Verificar si una ruta excede el límite de Windows (260 caracteres)"""
ruta_normalizada = normalizar_ruta(ruta)
return len(ruta_normalizada) > 260
def truncar_nombre_inteligente(nombre, max_length=100):
"""Truncar nombre de archivo de forma inteligente preservando extensión"""
if not nombre or len(nombre) <= max_length:
return nombre
# Separar nombre y extensión
nombre_base, extension = os.path.splitext(nombre)
# Calcular espacio disponible para el nombre base
espacio_disponible = max_length - len(extension) - 3 # -3 para "..."
if espacio_disponible <= 0:
return nombre[:max_length]
# Truncar y agregar indicador
nombre_truncado = nombre_base[:espacio_disponible] + "..." + extension
return nombre_truncado
def sanitizar_nombre_archivo(nombre):
"""Sanitizar nombre de archivo removiendo caracteres problemáticos"""
if not nombre:
return "archivo_sin_nombre"
# Remover caracteres problemáticos
nombre_limpio = re.sub(CARACTERES_PROBLEMATICOS, '_', nombre)
# Si es nombre reservado, agregar prefijo
if es_nombre_reservado_windows(nombre_limpio):
nombre_limpio = f"backup_{nombre_limpio}"
# Truncar si es muy largo
nombre_limpio = truncar_nombre_inteligente(nombre_limpio)
return nombre_limpio
def validar_ruta_archivo(ruta_completa):
"""
Validar si una ruta de archivo es segura para procesar
Retorna (es_valida, razon_error)
"""
try:
if not ruta_completa:
return False, "Ruta vacía"
# Normalizar la ruta primero
ruta_normalizada = normalizar_ruta(ruta_completa)
# Intentar acceso básico primero
try:
# Verificar si el archivo existe usando ruta normalizada
if not os.path.exists(ruta_normalizada):
return False, "Archivo no existe"
except (OSError, ValueError) as e:
# Si falla con ruta normalizada, intentar con UNC
try:
ruta_unc = obtener_ruta_segura(ruta_normalizada)
if not os.path.exists(ruta_unc):
return False, f"Archivo inaccesible: {str(e)}"
ruta_normalizada = ruta_unc
except Exception:
return False, f"Ruta problemática: {str(e)}"
# Verificar permisos de lectura
try:
if not os.access(ruta_normalizada, os.R_OK):
return False, "Sin permisos de lectura"
except Exception:
return False, "Error verificando permisos"
# Obtener nombre del archivo
nombre_archivo = os.path.basename(ruta_normalizada)
# Verificar nombre reservado
if es_nombre_reservado_windows(nombre_archivo):
return False, f"Nombre reservado de Windows: {nombre_archivo}"
# Verificar caracteres problemáticos en el nombre original
if tiene_caracteres_problematicos(nombre_archivo):
return False, "Contiene caracteres problemáticos"
return True, "OK"
except Exception as e:
return False, f"Error de validación: {str(e)}"
def obtener_ruta_segura(ruta_original):
"""Convertir ruta a formato seguro usando prefijo UNC si es necesario"""
try:
# Normalizar primero
ruta_normalizada = normalizar_ruta(ruta_original)
# Si la ruta es muy larga y no tiene prefijo UNC
if es_ruta_muy_larga(ruta_normalizada) and not ruta_normalizada.startswith('\\\\?\\'):
# Usar prefijo UNC para rutas largas
if ruta_normalizada.startswith('\\\\'):
# Ruta de red
return f'\\\\?\\UNC\\{ruta_normalizada[2:]}'
else:
# Ruta local - obtener ruta absoluta primero
try:
ruta_absoluta = os.path.abspath(ruta_normalizada)
return f'\\\\?\\{ruta_absoluta}'
except Exception:
return f'\\\\?\\{ruta_normalizada}'
return ruta_normalizada
except Exception:
return ruta_original
def detectar_archivos_problematicos_especificos(directorio):
"""
SISTEMA ULTRA-AGRESIVO de pre-escaneo para detectar TODOS los archivos problemáticos
que causan el error 'path is on mount \\\\?\\nul'
"""
archivos_problematicos = []
# Lista COMPLETA de nombres reservados (incluyendo variaciones)
nombres_reservados_completos = {
'nul', 'con', 'prn', 'aux', 'clock$',
'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9',
'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9',
# Variaciones con extensiones
'nul.txt', 'con.txt', 'prn.txt', 'aux.txt',
'nul.log', 'con.log', 'prn.log', 'aux.log',
# Variaciones con espacios y puntos
'nul.', 'con.', 'prn.', 'aux.',
' nul', ' con', ' prn', ' aux',
'nul ', 'con ', 'prn ', 'aux '
}
# Caracteres ULTRA-problemáticos
caracteres_ultra_problematicos = ['<', '>', ':', '"', '|', '?', '*', '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f']
try:
print(f"🔍 ESCANEO ULTRA-AGRESIVO iniciado en: {directorio}")
# Usar listdir para escaneo inicial más seguro
items = []
try:
items = os.listdir(directorio)
except Exception as e:
print(f"❌ Error listando directorio {directorio}: {e}")
return archivos_problematicos
for item in items:
item_path = os.path.join(directorio, item)
nombre_lower = item.lower().strip()
# 1. DETECTAR NOMBRES RESERVADOS (ultra-agresivo)
es_reservado = False
for reservado in nombres_reservados_completos:
if nombre_lower == reservado or nombre_lower.startswith(reservado + '.'):
es_reservado = True
break
if es_reservado:
archivos_problematicos.append({
'ruta': item_path,
'nombre': item,
'razon': f'NOMBRE RESERVADO DETECTADO: {nombre_lower}',
'tipo': 'nombre_reservado_critico'
})
print(f"🚫 CRÍTICO: Nombre reservado detectado: {item}")
continue
# 2. DETECTAR CARACTERES ULTRA-PROBLEMÁTICOS
tiene_caracteres_criticos = False
for char in caracteres_ultra_problematicos:
if char in item:
tiene_caracteres_criticos = True
break
if tiene_caracteres_criticos:
archivos_problematicos.append({
'ruta': item_path,
'nombre': item,
'razon': 'CARACTERES CRÍTICOS DETECTADOS',
'tipo': 'caracteres_criticos'
})
print(f"🚫 CRÍTICO: Caracteres problemáticos en: {item}")
continue
# 3. DETECTAR RUTAS EXTREMADAMENTE LARGAS (límite ultra-conservador)
if len(item_path) > 200: # Límite MUY conservador
archivos_problematicos.append({
'ruta': item_path,
'nombre': item,
'razon': f'RUTA CRÍTICA: {len(item_path)} caracteres (límite: 200)',
'tipo': 'ruta_critica'
})
print(f"🚫 CRÍTICO: Ruta muy larga: {item}")
continue
# 4. DETECTAR NOMBRES QUE EMPIEZAN/TERMINAN CON ESPACIOS O PUNTOS
if item.startswith(' ') or item.endswith(' ') or item.startswith('.') or item.endswith('.'):
archivos_problematicos.append({
'ruta': item_path,
'nombre': item,
'razon': 'FORMATO CRÍTICO: espacios/puntos al inicio/final',
'tipo': 'formato_critico'
})
print(f"🚫 CRÍTICO: Formato problemático: '{item}'")
continue
# 5. DETECTAR NOMBRES VACÍOS O SOLO ESPACIOS
if not item.strip():
archivos_problematicos.append({
'ruta': item_path,
'nombre': item,
'razon': 'NOMBRE VACÍO O SOLO ESPACIOS',
'tipo': 'nombre_vacio'
})
print(f"🚫 CRÍTICO: Nombre vacío detectado")
continue
except Exception as e:
print(f"❌ ERROR CRÍTICO en pre-escaneo de {directorio}: {e}")
if archivos_problematicos:
print(f"⚠️ TOTAL ARCHIVOS PROBLEMÁTICOS DETECTADOS: {len(archivos_problematicos)}")
return archivos_problematicos
def listdir_recursivo_seguro(directorio, archivos_problematicos_globales):
"""
FALLBACK RECURSIVO: Implementación manual de walk usando listdir()
para casos donde os.walk() falla completamente
"""
resultados = []
try:
print(f"🔄 FALLBACK RECURSIVO activado para: {directorio}")
# Listar contenido del directorio actual
try:
items = os.listdir(directorio)
except Exception as e:
print(f"❌ Error listando {directorio}: {e}")
return resultados
archivos_actuales = []
directorios_actuales = []
for item in items:
item_path = os.path.join(directorio, item)
# Verificar si es problemático
es_problematico = False
for prob in archivos_problematicos_globales:
if prob['ruta'] == item_path:
es_problematico = True
break
if es_problematico:
print(f"🚫 FALLBACK: Saltando item problemático: {item}")
continue
try:
if os.path.isfile(item_path):
archivos_actuales.append(item)
elif os.path.isdir(item_path):
directorios_actuales.append(item)
except Exception as e:
print(f"⚠️ FALLBACK: Error verificando {item}: {e}")
continue
# Agregar resultado actual
resultados.append((directorio, directorios_actuales.copy(), archivos_actuales))
# Recursión en subdirectorios
for subdir in directorios_actuales:
subdir_path = os.path.join(directorio, subdir)
try:
sub_resultados = listdir_recursivo_seguro(subdir_path, archivos_problematicos_globales)
resultados.extend(sub_resultados)
except Exception as e:
print(f"⚠️ FALLBACK: Error en subdirectorio {subdir}: {e}")
continue
except Exception as e:
print(f"❌ FALLBACK: Error crítico en {directorio}: {e}")
return resultados
def os_walk_seguro(directorio_origen, callback_estado=None):
"""
🚀 SISTEMA RADICAL ANTI-NUL: NUNCA USA os.walk()
Implementación 100% recursiva manual que ELIMINA completamente el error 'nul'
"""
def actualizar_estado(mensaje):
print(mensaje)
if callback_estado:
try:
callback_estado(mensaje)
except Exception:
pass # Ignorar errores de callback
actualizar_estado(f"🚀 SISTEMA RADICAL ANTI-NUL activado para: {directorio_origen}")
actualizar_estado("⚡ NUNCA usaremos os.walk() - Solo listdir() recursivo")
# INTERCEPTOR INMEDIATO: Verificar si el directorio raíz es problemático
try:
nombre_base = os.path.basename(directorio_origen).lower()
if nombre_base in NOMBRES_RESERVADOS_WINDOWS:
actualizar_estado(f"🚫 DIRECTORIO RAÍZ PROBLEMÁTICO DETECTADO: {nombre_base}")
actualizar_estado("⚠️ SALTANDO directorio completo para evitar error 'nul'")
return
except Exception as e:
actualizar_estado(f"⚠️ Error verificando directorio raíz: {e}")
# FASE 1: PRE-ESCANEO ULTRA-AGRESIVO (OPCIONAL)
actualizar_estado("🔍 FASE 1: Pre-escaneo ultra-agresivo...")
archivos_problematicos_globales = []
try:
archivos_problematicos_globales = detectar_archivos_problematicos_especificos(directorio_origen)
if archivos_problematicos_globales:
actualizar_estado(f"⚠️ DETECTADOS {len(archivos_problematicos_globales)} archivos problemáticos:")
for item in archivos_problematicos_globales[:3]:
actualizar_estado(f" 🚫 {item['nombre']}: {item['razon']}")
if len(archivos_problematicos_globales) > 3:
actualizar_estado(f" ... y {len(archivos_problematicos_globales) - 3} más")
except Exception as e:
actualizar_estado(f"⚠️ Error en pre-escaneo (continuando sin él): {e}")
# Continuar sin pre-escaneo si falla
# FASE 2: LISTDIR RECURSIVO RADICAL (NUNCA os.walk)
actualizar_estado("🔄 FASE 2: Iniciando listdir recursivo RADICAL...")
try:
for resultado in listdir_recursivo_radical(directorio_origen, archivos_problematicos_globales, callback_estado):
yield resultado
except Exception as e:
actualizar_estado(f"🚫 ERROR EN LISTDIR RADICAL: {e}")
# Último recurso: devolver directorio vacío
actualizar_estado("🆘 ÚLTIMO RECURSO: Devolviendo directorio vacío...")
yield directorio_origen, [], []
def listdir_recursivo_radical(directorio, archivos_problematicos_globales, callback_estado=None):
"""
🔥 IMPLEMENTACIÓN RADICAL: Listdir recursivo que NUNCA falla con 'nul'
"""
def actualizar_estado(mensaje):
print(mensaje)
if callback_estado:
try:
callback_estado(mensaje)
except Exception:
pass # Ignorar errores de callback
try:
actualizar_estado(f"📁 Procesando directorio: {directorio}")
# INTERCEPTOR INMEDIATO: Verificar nombre del directorio
try:
nombre_dir = os.path.basename(directorio).lower()
if nombre_dir in NOMBRES_RESERVADOS_WINDOWS:
actualizar_estado(f"🚫 DIRECTORIO RESERVADO DETECTADO: {nombre_dir}")
actualizar_estado(" ⏭️ SALTANDO directorio completo...")
return # Saltar este directorio completamente
except Exception:
pass # Continuar si no se puede verificar el nombre
# Intentar listar contenido del directorio con MÁXIMA PROTECCIÓN
items = []
try:
items = os.listdir(directorio)
except OSError as e:
error_msg = str(e).lower()
if 'nul' in error_msg or 'mount' in error_msg:
actualizar_estado(f"🚫 DIRECTORIO PROBLEMÁTICO DETECTADO: {directorio}")
actualizar_estado(f" Error: {e}")
actualizar_estado(" ⏭️ SALTANDO directorio completo...")
return # Saltar este directorio completamente
else:
actualizar_estado(f"⚠️ Error de acceso en {directorio}: {e}")
return
except Exception as e:
actualizar_estado(f"⚠️ Error inesperado listando {directorio}: {e}")
return
# Separar archivos y directorios de forma ULTRA-SEGURA
archivos_seguros = []
directorios_seguros = []
for item in items:
# INTERCEPTOR INMEDIATO: Verificar nombre del item
try:
nombre_base = item.lower()
if nombre_base in NOMBRES_RESERVADOS_WINDOWS:
actualizar_estado(f"🚫 ITEM RESERVADO DETECTADO: {item}")
continue # Saltar inmediatamente
except Exception:
pass # Continuar si no se puede verificar el nombre
item_path = os.path.join(directorio, item)
# Verificar si está en la lista de problemáticos
es_problematico = False
for prob in archivos_problematicos_globales:
if prob['ruta'] == item_path:
actualizar_estado(f"🚫 SALTANDO item problemático: {item}")
es_problematico = True
break
if es_problematico:
continue
# Verificar tipo de item de forma ULTRA-SEGURA
try:
if os.path.isfile(item_path):
archivos_seguros.append(item)
elif os.path.isdir(item_path):
directorios_seguros.append(item)
except OSError as e:
error_msg = str(e).lower()
if 'nul' in error_msg or 'mount' in error_msg:
actualizar_estado(f"🚫 ITEM PROBLEMÁTICO DETECTADO: {item}")
actualizar_estado(f" Error: {e}")
continue # Saltar este item
else:
actualizar_estado(f"⚠️ Error verificando {item}: {e}")
continue
except Exception as e:
actualizar_estado(f"⚠️ Error inesperado con {item}: {e}")
continue
# Devolver resultado para el directorio actual
yield directorio, directorios_seguros, archivos_seguros
# Procesar subdirectorios recursivamente
for subdir in directorios_seguros:
subdir_path = os.path.join(directorio, subdir)
try:
for resultado in listdir_recursivo_radical(subdir_path, archivos_problematicos_globales, callback_estado):
yield resultado
except Exception as e:
actualizar_estado(f"⚠️ Error procesando subdirectorio {subdir}: {e}")
continue
except Exception as e:
actualizar_estado(f"🚫 ERROR CRÍTICO en listdir_recursivo_radical: {e}")
return
def validar_directorio_origen(directorio):
"""Validar directorio origen antes de os.walk()"""
try:
if not directorio:
return False, "Directorio vacío"
# Normalizar ruta
dir_normalizado = normalizar_ruta(directorio)
# Verificar existencia
if not os.path.exists(dir_normalizado):
return False, "Directorio no existe"
# Verificar que es directorio
if not os.path.isdir(dir_normalizado):
return False, "No es un directorio"
# Verificar permisos
if not os.access(dir_normalizado, os.R_OK):
return False, "Sin permisos de lectura"
# Intentar listar contenido básico
try:
list(os.listdir(dir_normalizado))
except Exception as e:
return False, f"Error accediendo al directorio: {str(e)}"
return True, "OK"
except Exception as e:
return False, f"Error validando directorio: {str(e)}"
class CopyNestApp:
def __init__(self, root):
self.root = root
self.root.title("🗂️ CopyNest - Backup Inteligente v2.0")
self.root.geometry("800x600")
self.root.minsize(700, 500)
# Configurar colores
self.bg_color = '#2c3e50'
self.fg_color = '#ecf0f1'
self.accent_color = '#3498db'
self.root.configure(bg=self.bg_color)
# Variables
self.carpeta_origen = tk.StringVar()
self.carpeta_destino = tk.StringVar()
self.nombre_copia = tk.StringVar()
self.incluir_ocultos = tk.BooleanVar()
self.modo_eficiente = tk.BooleanVar(value=True)
self.usar_nombre_carpeta = tk.BooleanVar(value=True)
self.verificar_integridad = tk.BooleanVar(value=False)
self.nivel_compresion = tk.IntVar(value=6)
self.crear_log = tk.BooleanVar(value=True)
self.progreso = tk.DoubleVar()
self.estado_texto = tk.StringVar(value="✨ Listo para crear copia de seguridad")
# Variables para estadísticas
self.tiempo_inicio = None
self.tiempo_estimado = tk.StringVar(value="")
self.velocidad_procesamiento = tk.StringVar(value="")
# Historial de copias
self.historial_copias = []
# Filtros personalizados
self.filtros_personalizados = set()
# Lista de archivos problemáticos para logging
self.archivos_problematicos = []
# Configuración por defecto
self.nombre_copia.set(f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}")
# Carpetas y archivos a excluir en modo eficiente
self.exclusiones_eficientes = {
'node_modules', 'dist', 'build', '.next', '.nuxt', 'out',
'.git', '.svn', '.hg', 'coverage', '.nyc_output',
'logs', '*.log', 'npm-debug.log*', 'yarn-debug.log*',
'yarn-error.log*', '.DS_Store', 'Thumbs.db',
'__pycache__', '*.pyc', '*.pyo', '*.pyd', '.Python',
'env', 'venv', '.venv', '.env.local', '.env.development.local',
'.env.test.local', '.env.production.local', 'target',
'bin', 'obj', '.vs', '.vscode/settings.json'
}
self.crear_interfaz()
self.cargar_configuracion()
self.centrar_ventana()
def crear_interfaz(self):
"""Crear la interfaz de usuario"""
# Canvas y scrollbar para scroll vertical
canvas = tk.Canvas(self.root, bg=self.bg_color, highlightthickness=0)
scrollbar = tk.Scrollbar(self.root, orient="vertical", command=canvas.yview)
scrollable_frame = tk.Frame(canvas, bg=self.bg_color)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
# Configurar scroll con rueda del mouse
def _on_mousewheel(event):
canvas.yview_scroll(int(-1*(event.delta/120)), "units")
canvas.bind_all("<MouseWheel>", _on_mousewheel)
# Empaquetar canvas y scrollbar
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
# Frame principal con padding dentro del canvas
main_frame = tk.Frame(scrollable_frame, bg=self.bg_color)
main_frame.pack(fill='both', expand=True, padx=20, pady=20)
# Título
title_label = tk.Label(main_frame,
text="🗂️ Copia de Seguridad Rápida",
font=('Segoe UI', 18, 'bold'),
bg=self.bg_color, fg=self.fg_color)
title_label.pack(pady=(0, 10))
subtitle_label = tk.Label(main_frame,
text="Crea copias de seguridad comprimidas de forma rápida y sencilla",
font=('Segoe UI', 10),
bg=self.bg_color, fg='#bdc3c7')
subtitle_label.pack(pady=(0, 20))
# Sección de carpetas
self.crear_seccion_carpetas(main_frame)
# Sección de configuración
self.crear_seccion_configuracion(main_frame)
# Sección de configuración avanzada
self.crear_seccion_avanzada(main_frame)
# Sección de estadísticas
self.crear_seccion_estadisticas(main_frame)
# Sección de progreso
self.crear_seccion_progreso(main_frame)
# Sección de historial
self.crear_seccion_historial(main_frame)
# Botones
self.crear_botones(main_frame)
def crear_seccion_carpetas(self, parent):
"""Crear sección de selección de carpetas"""
# Frame para carpetas
carpetas_frame = tk.LabelFrame(parent, text="📁 Selección de Carpetas",
font=('Segoe UI', 12, 'bold'),
bg=self.bg_color, fg=self.fg_color,
bd=2, relief='groove')
carpetas_frame.pack(fill='x', pady=(0, 15))
# Carpeta origen
tk.Label(carpetas_frame, text="Carpeta de origen:",
font=('Segoe UI', 10), bg=self.bg_color, fg=self.fg_color).pack(anchor='w', padx=10, pady=(10, 5))
origen_frame = tk.Frame(carpetas_frame, bg=self.bg_color)
origen_frame.pack(fill='x', padx=10, pady=(0, 10))
self.entry_origen = tk.Entry(origen_frame, textvariable=self.carpeta_origen,
font=('Segoe UI', 10), width=50)
self.entry_origen.pack(side='left', fill='x', expand=True)
tk.Button(origen_frame, text="📂 Seleccionar",
command=self.seleccionar_origen,
bg=self.accent_color, fg='white',
font=('Segoe UI', 9, 'bold'),
relief='flat', padx=15).pack(side='right', padx=(10, 0))
# Carpeta destino
tk.Label(carpetas_frame, text="Carpeta de destino:",
font=('Segoe UI', 10), bg=self.bg_color, fg=self.fg_color).pack(anchor='w', padx=10, pady=(10, 5))
destino_frame = tk.Frame(carpetas_frame, bg=self.bg_color)
destino_frame.pack(fill='x', padx=10, pady=(0, 15))
self.entry_destino = tk.Entry(destino_frame, textvariable=self.carpeta_destino,
font=('Segoe UI', 10), width=50)
self.entry_destino.pack(side='left', fill='x', expand=True)
tk.Button(destino_frame, text="📂 Seleccionar",
command=self.seleccionar_destino,
bg=self.accent_color, fg='white',
font=('Segoe UI', 9, 'bold'),
relief='flat', padx=15).pack(side='right', padx=(10, 0))
def crear_seccion_configuracion(self, parent):
"""Crear sección de configuración"""
config_frame = tk.LabelFrame(parent, text="⚙️ Configuración",
font=('Segoe UI', 12, 'bold'),
bg=self.bg_color, fg=self.fg_color,
bd=2, relief='groove')
config_frame.pack(fill='x', pady=(0, 15))
# Checkbox para usar nombre de carpeta automáticamente
self.check_nombre_auto = tk.Checkbutton(config_frame,
text="📁 Usar nombre de carpeta origen + timestamp",
variable=self.usar_nombre_carpeta,
command=self.actualizar_nombre_archivo,
font=('Segoe UI', 10),
bg=self.bg_color, fg=self.fg_color,
selectcolor=self.bg_color,
activebackground=self.bg_color,
activeforeground=self.fg_color)
self.check_nombre_auto.pack(anchor='w', padx=10, pady=(10, 5))
# Nombre del archivo
tk.Label(config_frame, text="Nombre del archivo de copia:",
font=('Segoe UI', 10), bg=self.bg_color, fg=self.fg_color).pack(anchor='w', padx=10, pady=(10, 5))
self.entry_nombre = tk.Entry(config_frame, textvariable=self.nombre_copia,
font=('Segoe UI', 10), width=50)
self.entry_nombre.pack(fill='x', padx=10, pady=(0, 10))
# Checkbox para modo eficiente
self.check_eficiente = tk.Checkbutton(config_frame,
text="⚡ Modo eficiente (excluir node_modules, dist, .git, etc.)",
variable=self.modo_eficiente,
command=self.mostrar_exclusiones,
font=('Segoe UI', 10),
bg=self.bg_color, fg=self.fg_color,
selectcolor=self.bg_color,
activebackground=self.bg_color,
activeforeground=self.fg_color)
self.check_eficiente.pack(anchor='w', padx=10, pady=(0, 5))
# Checkbox para archivos ocultos
self.check_ocultos = tk.Checkbutton(config_frame,
text="🔍 Incluir archivos y carpetas ocultos",
variable=self.incluir_ocultos,
font=('Segoe UI', 10),
bg=self.bg_color, fg=self.fg_color,
selectcolor=self.bg_color,
activebackground=self.bg_color,
activeforeground=self.fg_color)
self.check_ocultos.pack(anchor='w', padx=10, pady=(0, 5))
# Botón para ver exclusiones
tk.Button(config_frame, text="📋 Ver carpetas excluidas en modo eficiente",
command=self.mostrar_exclusiones,
bg='#95a5a6', fg='white',
font=('Segoe UI', 9),
relief='flat', padx=10, pady=5).pack(anchor='w', padx=10, pady=(0, 15))
def crear_seccion_avanzada(self, parent):
"""Crear sección de configuración avanzada"""
avanzada_frame = tk.LabelFrame(parent, text="🔧 Configuración Avanzada",
font=('Segoe UI', 12, 'bold'),
bg=self.bg_color, fg=self.fg_color,
bd=2, relief='groove')
avanzada_frame.pack(fill='x', pady=(0, 15))
# Frame para organizar en columnas
columnas_frame = tk.Frame(avanzada_frame, bg=self.bg_color)
columnas_frame.pack(fill='x', padx=10, pady=10)
# Columna izquierda
col_izq = tk.Frame(columnas_frame, bg=self.bg_color)
col_izq.pack(side='left', fill='both', expand=True)
# Nivel de compresión
tk.Label(col_izq, text="🗜️ Nivel de compresión (0-9):",
font=('Segoe UI', 10), bg=self.bg_color, fg=self.fg_color).pack(anchor='w', pady=(0, 5))
compresion_frame = tk.Frame(col_izq, bg=self.bg_color)
compresion_frame.pack(fill='x', pady=(0, 10))
self.scale_compresion = tk.Scale(compresion_frame, from_=0, to=9, orient='horizontal',
variable=self.nivel_compresion,
bg=self.bg_color, fg=self.fg_color,
highlightthickness=0, length=200)
self.scale_compresion.pack(side='left')
tk.Label(compresion_frame, text="(0=Rápido, 9=Máximo)",
font=('Segoe UI', 8), bg=self.bg_color, fg='#95a5a6').pack(side='left', padx=(10, 0))
# Checkbox verificar integridad
self.check_integridad = tk.Checkbutton(col_izq,
text="🔐 Verificar integridad (MD5)",
variable=self.verificar_integridad,
font=('Segoe UI', 10),
bg=self.bg_color, fg=self.fg_color,
selectcolor=self.bg_color,
activebackground=self.bg_color,
activeforeground=self.fg_color)
self.check_integridad.pack(anchor='w', pady=(0, 5))
# Checkbox crear log
self.check_log = tk.Checkbutton(col_izq,
text="📝 Crear archivo de log",
variable=self.crear_log,
font=('Segoe UI', 10),
bg=self.bg_color, fg=self.fg_color,
selectcolor=self.bg_color,
activebackground=self.bg_color,
activeforeground=self.fg_color)
self.check_log.pack(anchor='w', pady=(0, 10))
# Columna derecha
col_der = tk.Frame(columnas_frame, bg=self.bg_color)
col_der.pack(side='right', fill='both', expand=True, padx=(20, 0))
# Botones de utilidades
tk.Button(col_der, text="🎯 Filtros Personalizados",
command=self.gestionar_filtros,
bg='#9b59b6', fg='white',
font=('Segoe UI', 9, 'bold'),
relief='flat', padx=15, pady=5).pack(fill='x', pady=(0, 5))
tk.Button(col_der, text="📊 Analizar Carpeta",
command=self.analizar_carpeta,
bg='#e67e22', fg='white',
font=('Segoe UI', 9, 'bold'),
relief='flat', padx=15, pady=5).pack(fill='x', pady=(0, 5))
tk.Button(col_der, text="🧹 Limpiar Temporales",
command=self.limpiar_temporales,
bg='#16a085', fg='white',
font=('Segoe UI', 9, 'bold'),
relief='flat', padx=15, pady=5).pack(fill='x')
def crear_seccion_estadisticas(self, parent):
"""Crear sección de estadísticas en tiempo real"""
stats_frame = tk.LabelFrame(parent, text="📈 Estadísticas",
font=('Segoe UI', 12, 'bold'),
bg=self.bg_color, fg=self.fg_color,
bd=2, relief='groove')
stats_frame.pack(fill='x', pady=(0, 15))
# Frame para estadísticas en columnas
stats_content = tk.Frame(stats_frame, bg=self.bg_color)
stats_content.pack(fill='x', padx=10, pady=10)
# Tiempo estimado
tk.Label(stats_content, text="⏱️ Tiempo estimado:",
font=('Segoe UI', 10), bg=self.bg_color, fg=self.fg_color).grid(row=0, column=0, sticky='w', padx=(0, 10))
self.label_tiempo = tk.Label(stats_content, textvariable=self.tiempo_estimado,
font=('Segoe UI', 10, 'bold'),
bg=self.bg_color, fg='#f39c12')
self.label_tiempo.grid(row=0, column=1, sticky='w')
# Velocidad de procesamiento
tk.Label(stats_content, text="🚀 Velocidad:",
font=('Segoe UI', 10), bg=self.bg_color, fg=self.fg_color).grid(row=1, column=0, sticky='w', padx=(0, 10), pady=(5, 0))
self.label_velocidad = tk.Label(stats_content, textvariable=self.velocidad_procesamiento,
font=('Segoe UI', 10, 'bold'),
bg=self.bg_color, fg='#27ae60')
self.label_velocidad.grid(row=1, column=1, sticky='w', pady=(5, 0))
# Información del sistema
if PSUTIL_AVAILABLE:
memoria_disponible = psutil.virtual_memory().available / (1024**3) # GB
memoria_text = f"💾 RAM disponible: {memoria_disponible:.1f} GB"
else:
memoria_text = "💾 RAM disponible: N/A"
espacio_disco = shutil.disk_usage(os.path.expanduser('~')).free / (1024**3) # GB
tk.Label(stats_content, text=memoria_text,
font=('Segoe UI', 9), bg=self.bg_color, fg='#95a5a6').grid(row=2, column=0, columnspan=2, sticky='w', pady=(10, 0))
tk.Label(stats_content, text=f"💿 Espacio en disco: {espacio_disco:.1f} GB",
font=('Segoe UI', 9), bg=self.bg_color, fg='#95a5a6').grid(row=3, column=0, columnspan=2, sticky='w')
def crear_seccion_historial(self, parent):
"""Crear sección de historial de copias"""
historial_frame = tk.LabelFrame(parent, text="📚 Historial de Copias Recientes",
font=('Segoe UI', 12, 'bold'),
bg=self.bg_color, fg=self.fg_color,
bd=2, relief='groove')
historial_frame.pack(fill='x', pady=(0, 15))
# Frame con scroll para historial
hist_scroll_frame = tk.Frame(historial_frame, bg=self.bg_color)
hist_scroll_frame.pack(fill='both', expand=True, padx=10, pady=10)
# Scrollbar para historial
hist_scrollbar = tk.Scrollbar(hist_scroll_frame)
hist_scrollbar.pack(side='right', fill='y')
# Listbox para historial
self.listbox_historial = tk.Listbox(hist_scroll_frame,
yscrollcommand=hist_scrollbar.set,
font=('Consolas', 9),
bg='#34495e', fg='white',
selectbackground='#3498db',
height=4)
self.listbox_historial.pack(side='left', fill='both', expand=True)
hist_scrollbar.config(command=self.listbox_historial.yview)
# Botones para historial
hist_botones = tk.Frame(historial_frame, bg=self.bg_color)
hist_botones.pack(fill='x', padx=10, pady=(0, 10))
tk.Button(hist_botones, text="🔄 Repetir Copia",
command=self.repetir_copia_seleccionada,
bg='#3498db', fg='white',
font=('Segoe UI', 9),
relief='flat', padx=10).pack(side='left', padx=(0, 5))
tk.Button(hist_botones, text="📂 Abrir Ubicación",
command=self.abrir_ubicacion_historial,
bg='#f39c12', fg='white',
font=('Segoe UI', 9),
relief='flat', padx=10).pack(side='left', padx=(0, 5))
tk.Button(hist_botones, text="🗑️ Limpiar Historial",
command=self.limpiar_historial,
bg='#e74c3c', fg='white',
font=('Segoe UI', 9),
relief='flat', padx=10).pack(side='right')
def crear_seccion_progreso(self, parent):
"""Crear sección de progreso"""
progress_frame = tk.LabelFrame(parent, text="📊 Progreso",
font=('Segoe UI', 12, 'bold'),
bg=self.bg_color, fg=self.fg_color,
bd=2, relief='groove')
progress_frame.pack(fill='x', pady=(0, 15))
# Barra de progreso
self.barra_progreso = ttk.Progressbar(progress_frame,
variable=self.progreso,
maximum=100,
length=400)
self.barra_progreso.pack(fill='x', padx=10, pady=(10, 5))
# Estado
self.label_estado = tk.Label(progress_frame, textvariable=self.estado_texto,
font=('Segoe UI', 10),
bg=self.bg_color, fg='#95a5a6')
self.label_estado.pack(padx=10, pady=(0, 15))
def crear_botones(self, parent):
"""Crear botones de acción"""
botones_frame = tk.Frame(parent, bg=self.bg_color)
botones_frame.pack(fill='x', pady=10)
# Botón crear copia
self.btn_crear = tk.Button(botones_frame, text="🚀 Crear Copia de Seguridad",
command=self.crear_copia_seguridad,
bg='#27ae60', fg='white',
font=('Segoe UI', 12, 'bold'),
relief='flat', padx=30, pady=10)
self.btn_crear.pack(side='left', padx=(0, 10))
# Botón limpiar
tk.Button(botones_frame, text="🧹 Limpiar Formulario",
command=self.limpiar_formulario,
bg='#e74c3c', fg='white',
font=('Segoe UI', 10, 'bold'),
relief='flat', padx=20, pady=10).pack(side='left')
# Botón abrir destino
tk.Button(botones_frame, text="📂 Abrir Destino",
command=self.abrir_carpeta_destino,
bg='#f39c12', fg='white',
font=('Segoe UI', 10, 'bold'),
relief='flat', padx=20, pady=10).pack(side='right')
def seleccionar_origen(self):
"""Seleccionar carpeta de origen"""
carpeta = filedialog.askdirectory(title="Seleccionar carpeta de origen")
if carpeta:
self.carpeta_origen.set(carpeta)