import os import uuid from typing import BinaryIO from minio import Minio from minio.error import S3Error from werkzeug.utils import secure_filename from app.core.config.settings import config, ACTIVE_ENV_NAME cfg = config[ACTIVE_ENV_NAME] class MinioService: def __init__(self): self.client = Minio( cfg.MINIO_ENDPOINT, access_key=cfg.MINIO_ACCESS_KEY, secret_key=cfg.MINIO_SECRET_KEY, secure=cfg.MINIO_SECURE, ) self.bucket_name = cfg.MINIO_AGENT_GUIDES_BUCKET self._ensure_bucket_exists() def _ensure_bucket_exists(self): try: if not self.client.bucket_exists(self.bucket_name): self.client.make_bucket(self.bucket_name) # Set bucket policy to public read policy = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"AWS": ["*"]}, "Action": ["s3:GetObject"], "Resource": [f"arn:aws:s3:::{self.bucket_name}/*"] } ] } import json self.client.set_bucket_policy(self.bucket_name, json.dumps(policy)) except Exception as e: # log or print error print(f"MinIO bucket error (or not reachable): {e}") def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str: """ Uploads a file to MinIO and returns the generated object name. """ # If MinIO is not running, we could fallback to local storage or raise clear error try: self._ensure_bucket_exists() except Exception: pass ext = os.path.splitext(filename)[1] unique_filename = f"{uuid.uuid4().hex}{ext}" try: self.client.put_object( bucket_name=self.bucket_name, object_name=unique_filename, data=file_stream, length=file_size, content_type=content_type ) except Exception as e: # For development, if minio is down, let's mock it so UI can continue print(f"Warning: Minio upload failed ({e}). Fallback to local storage.") # fallback to local storage os.makedirs('data/agent-guides', exist_ok=True) local_path = os.path.join('data/agent-guides', unique_filename) file_stream.seek(0) with open(local_path, 'wb') as f: f.write(file_stream.read()) return unique_filename def get_public_url(self, object_name: str) -> str: """ 返回同源的指南文件代理地址。 用途:避免 HTTPS 页面直接加载 HTTP MinIO 对象时被移动端浏览器拦截。 参数约束:object_name 必须是系统生成的对象名;返回地址由指南文件接口提供 Range 响应。 """ return f"/api/agents/guides/files/{object_name}" def open_file_stream(self, object_name: str, *, offset: int = 0, length: int | None = None): """ 按指定字节范围打开 MinIO 指南对象流。 用途:供同源指南文件接口透传视频数据,满足 iOS 媒体播放器的 Range/206 请求。 参数约束:offset 从 0 开始,length 为本次最多读取字节数;调用方必须关闭返回流。 """ return self.client.get_object( self.bucket_name, object_name, offset=offset, length=length, ) def stat_file(self, object_name: str): """ 获取 MinIO 指南对象元数据。 用途:在返回视频前确定文件大小和 MIME 类型,以生成 iOS 可识别的媒体响应头。 参数约束:object_name 必须是系统保存的对象名;对象不存在时由 MinIO 异常上抛。 """ return self.client.stat_object(self.bucket_name, object_name) def get_file_bytes(self, object_name: str) -> bytes: """ 读取对象的原始字节内容。 用途:给后台解析 PDF、图片等资料时复用统一文件读取入口,避免业务层自己判断本地回退还是 MinIO。 参数约束:object_name 必须是已存储的对象名,不接受外部 URL。 """ local_path = os.path.join('data/agent-guides', object_name) if os.path.exists(local_path): with open(local_path, 'rb') as file_obj: return file_obj.read() response = self.client.get_object(self.bucket_name, object_name) try: return response.read() finally: response.close() response.release_conn() def delete_file(self, object_name: str): try: self.client.remove_object(self.bucket_name, object_name) except S3Error as e: print(f"Error deleting file from MinIO: {e}") minio_service = MinioService()