Spaces:
Running
Running
| import requests | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| IMGBB_UPLOAD_URL = "https://api.imgbb.com/1/upload" | |
| def upload_image_to_imgbb(base64_str: str, api_key: str = None) -> str: | |
| """ | |
| Subir una imagen en formato base64 a ImgBB usando la clave de la iglesia y retornar la URL. | |
| Si ya es una URL válida, se retorna directamente. | |
| """ | |
| if not base64_str: | |
| return base64_str | |
| if base64_str.startswith("http://") or base64_str.startswith("https://"): | |
| return base64_str | |
| if not api_key or not api_key.strip(): | |
| logger.error("Intento de subida de imagen sin clave de ImgBB configurada.") | |
| raise ValueError("La iglesia no tiene configurada una clave de almacenamiento de imágenes (ImgBB). Por favor, pide al administrador que la configure en Conexiones.") | |
| try: | |
| # Remover prefijos como 'data:image/jpeg;base64,' si existen | |
| clean_base64 = base64_str | |
| if "," in base64_str: | |
| clean_base64 = base64_str.split(",", 1)[1] | |
| payload = { | |
| "key": api_key.strip(), | |
| "image": clean_base64 | |
| } | |
| response = requests.post(IMGBB_UPLOAD_URL, data=payload, timeout=20) | |
| if response.status_code in [400, 403]: | |
| logger.error(f"Clave ImgBB inválida o rechazada: {response.text}") | |
| raise ValueError("La clave de ImgBB configurada en esta iglesia ya no es válida o ha caducado.") | |
| response.raise_for_status() | |
| data = response.json() | |
| if data.get("success"): | |
| return data["data"]["url"] | |
| else: | |
| logger.error(f"Error subiendo a ImgBB: {data}") | |
| raise ValueError("No se pudo completar la subida de la imagen a ImgBB.") | |
| except ValueError as ve: | |
| raise ve | |
| except Exception as e: | |
| logger.error(f"Excepción subiendo a ImgBB: {e}") | |
| raise ValueError("Ocurrió un error de conexión al subir la imagen.") | |
| def validate_imgbb_key(api_key: str) -> bool: | |
| """ | |
| Valida una clave de ImgBB subiendo un pixel PNG 1x1 estándar. | |
| """ | |
| if not api_key or not api_key.strip(): | |
| return False | |
| # Pixel PNG 1x1 en Base64 | |
| tiny_png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==" | |
| payload = { | |
| "key": api_key.strip(), | |
| "image": tiny_png | |
| } | |
| try: | |
| response = requests.post(IMGBB_UPLOAD_URL, data=payload, timeout=10) | |
| if response.status_code == 200 and response.json().get("success"): | |
| return True | |
| return False | |
| except Exception as e: | |
| logger.warning(f"Fallo en validación de clave ImgBB: {e}") | |
| return False | |