-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_utils.py
More file actions
105 lines (93 loc) · 3.76 KB
/
file_utils.py
File metadata and controls
105 lines (93 loc) · 3.76 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
import os
import shutil
import time
from logging_utils import log
from config import Config
video_dir = Config.VIDEO_CONFIG['VIDEO_DIR']
# todo: refactorizar para aplicar config global a variable local
formatos_validos = Config.VIDEO_CONFIG['FORMATOS_DE_VIDEO_ADMITIDOS']
# Calcula hash de los videos en video_dir
def calcular_hash(file_list):
hashes = []
missing_files = []
for f in sorted(file_list):
file_path = os.path.join(video_dir, f)
try:
size = os.path.getsize(file_path)
hashes.append(f"{size}-{f}")
except (FileNotFoundError, PermissionError) as e:
missing_files.append(f)
log(f"WARNING: No se puede acceder al archivo para hashearlo {f}: {e}")
return ";" if not hashes else ";".join(hashes)
def limpiar_archivos_temporales(incluir_activos=False):
"""
Limpia archivos temporales del sistema.
Args:
incluir_activos (bool): Si True, también limpia los archivos en uso actual
"""
def _eliminar_seguro(path):
"""Elimina un archivo o directorio de forma segura"""
try:
if os.path.isfile(path):
os.remove(path)
elif os.path.isdir(path):
# Intentar primero con shutil.rmtree
try:
shutil.rmtree(path, ignore_errors=True)
except:
# Si falla, intentar con comando del sistema
if os.name == 'nt': # Windows
os.system(f'rd /s /q "{path}"')
else: # Unix/Linux
os.system(f'rm -rf "{path}"')
# Esperar un momento después de la eliminación
if os.path.exists(path):
time.sleep(1)
except Exception as e:
log(f"Error al eliminar {path}: {str(e)}")
temp_paths = []
if incluir_activos:
temp_paths.extend([
Config.PATHS['TEMP_VIDEO_DIR'],
Config.PATHS['PLAYLIST_PATH'],
Config.PATHS['HASH_FILE']
])
for path in temp_paths:
try:
if os.path.isfile(path):
os.remove(path)
elif os.path.isdir(path):
shutil.rmtree(path, ignore_errors=True)
except Exception as e:
log(f"Advertencia: No se pudo limpiar {path}: {e}")
def validar_dir(video_dir):
"""Encuentra videos en el directorio especificado según las extensiones permitidas"""
extensiones = Config.VIDEO_CONFIG['FORMATOS_DE_VIDEO_ADMITIDOS']
archivos = []
for f in os.listdir(video_dir):
if any(f.lower().endswith(ext.lower()) for ext in extensiones):
archivos.append(f)
return archivos
def copiar_archivos(files, src_dir, dest_dir):
"""Crea y si no existe y copia archivos de un directorio a otro"""
os.makedirs(dest_dir, exist_ok=True)
for f in files:
src = os.path.join(src_dir, f)
dst = os.path.join(dest_dir, f)
try:
shutil.copy2(src, dst)
log(f"Archivo copiado: {f}")
except Exception as e:
log(f"ERROR al copiar {f}: {e}")
def generar_playlist(files, dest_dir, playlist_path):
"""Genera una playlist para VLC"""
with open(playlist_path, "w", encoding=Config.LOG_CONFIG['LOG_ENCODING']) as pl:
for f in files:
if any(f.lower().endswith(ext.lower()) for ext in Config.VIDEO_CONFIG['FORMATOS_DE_VIDEO_ADMITIDOS']):
pl.write(os.path.join(dest_dir, f) + "\n")
log(f"Playlist generada. Incluye: {', '.join(files)}")
def escribir_hash(hash_value, hash_file):
"""Escribe el hash en el archivo especificado."""
with open(hash_file, "w", encoding="utf-8") as hf:
hf.write(hash_value)
log(f"Hash escrito en {hash_file}.")