Spaces:
Sleeping

File size: 1,865 Bytes
6e21e9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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