Spaces:
Sleeping

MediaMasterAsyncPre / tools /file_tools.py
KeyBow's picture
Create file_tools.py
6e21e9a verified
Raw History Blame Contribute Delete
1.87 kB
"""
file_tools.py
ファイルダウンロード機能
- パスワード照合
- ファイル一覧取得
- 選択ファイルのZIP生成
"""
import os
import zipfile
import tempfile
from typing import List
DOWNLOAD_FILES_DIR = "/app/download_files"
DOWNLOAD_PASSWORD = os.environ.get("DOWNLOAD_PASSWORD", "")
# --- パスワード照合 ---
def verify_password(password: str) -> bool:
"""入力されたパスワードが正しいか照合する"""
if not DOWNLOAD_PASSWORD:
return False
return password == DOWNLOAD_PASSWORD
# --- ファイル一覧取得 ---
def list_files() -> List[str]:
"""download_files ディレクトリ内のファイル一覧を返す"""
if not os.path.exists(DOWNLOAD_FILES_DIR):
return []
return sorted([
f for f in os.listdir(DOWNLOAD_FILES_DIR)
if os.path.isfile(os.path.join(DOWNLOAD_FILES_DIR, f))
])
# --- ZIP生成 ---
def build_zip(filenames: List[str]) -> str:
"""
指定されたファイルをZIPにまとめ、一時ファイルのパスを返す。
呼び出し元でファイルを返却後に削除すること。
"""
if not filenames:
raise ValueError("ファイルが選択されていません")
tmp = tempfile.NamedTemporaryFile(
delete=False, suffix=".zip", dir="/tmp/media_master"
)
tmp.close()
with zipfile.ZipFile(tmp.name, "w", zipfile.ZIP_DEFLATED) as zf:
for fname in filenames:
# パストラバーサル対策:ファイル名のみ取り出す
safe_name = os.path.basename(fname)
full_path = os.path.join(DOWNLOAD_FILES_DIR, safe_name)
if not os.path.isfile(full_path):
raise ValueError(f"ファイルが見つかりません: {safe_name}")
zf.write(full_path, safe_name)
return tmp.name