55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
# processors/converter.py
|
|
|
|
import os
|
|
import zipfile
|
|
import rarfile
|
|
import tempfile
|
|
import shutil
|
|
|
|
from processors.validator import validate_comic
|
|
|
|
|
|
def convert_comic(path, desired_format="cbz"):
|
|
validation = validate_comic(path)
|
|
|
|
if validation.errors:
|
|
raise Exception(f"Archivo corrupto: {path}")
|
|
|
|
real = validation.real_format
|
|
|
|
# Si ya está en el formato deseado → nada que hacer
|
|
if desired_format == "cbz" and real == "zip":
|
|
return {"needs_conversion": False, "target_path": path}
|
|
|
|
if desired_format == "cbr" and real == "rar":
|
|
return {"needs_conversion": False, "target_path": path}
|
|
|
|
# Abrir según formato real
|
|
archive = zipfile.ZipFile(path, "r") if real == "zip" else rarfile.RarFile(path, "r")
|
|
|
|
temp_dir = tempfile.mkdtemp()
|
|
archive.extractall(temp_dir)
|
|
archive.close()
|
|
|
|
base, _ = os.path.splitext(path)
|
|
target_path = f"{base}.{desired_format}"
|
|
|
|
if desired_format == "cbz":
|
|
with zipfile.ZipFile(target_path, "w", zipfile.ZIP_DEFLATED) as new_zip:
|
|
for root, _, files in os.walk(temp_dir):
|
|
for f in files:
|
|
full = os.path.join(root, f)
|
|
rel = os.path.relpath(full, temp_dir)
|
|
new_zip.write(full, rel)
|
|
|
|
elif desired_format == "cbr":
|
|
raise NotImplementedError("Crear CBR requiere 'rar' instalado")
|
|
|
|
shutil.rmtree(temp_dir)
|
|
|
|
# Mover original a backup
|
|
from core.backup import move_to_backup
|
|
move_to_backup(path)
|
|
|
|
return {"needs_conversion": True, "target_path": target_path}
|