Spaces:
Sleeping

File size: 7,882 Bytes
6d85a35
 
 
 
 
bb554d3
 
 
 
565e7ef
6d85a35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cf05e6
bb554d3
4d75cc2
6d85a35
e1ac476
 
6d85a35
e1ac476
 
 
 
 
 
bb554d3
6d85a35
f1803ea
 
6d85a35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565e7ef
 
16f016d
565e7ef
 
 
 
 
 
 
 
 
6d85a35
e1ac476
 
03c16b3
 
 
 
565e7ef
bb554d3
6d85a35
 
 
f1803ea
bb554d3
 
 
 
 
6d85a35
573e758
 
 
 
6d85a35
9c41fde
 
 
 
 
6d85a35
f1803ea
 
4d75cc2
 
f1803ea
 
9c41fde
f1803ea
9c41fde
 
f1803ea
6d85a35
bb554d3
f1803ea
16f016d
 
 
955c2a4
6d85a35
f1803ea
bb554d3
 
16f016d
6d85a35
955c2a4
 
 
bb554d3
 
ceff84d
 
 
 
 
 
16f016d
fc012c1
 
bb554d3
 
6d85a35
bb554d3
 
 
 
6d85a35
bb554d3
 
 
 
 
225dc9e
 
5cf05e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""
app.py
FastAPI のルーティング・起動設定のみを記述する。
変換ロジックは tools/ 配下の各モジュールに委譲する。
"""
import os
import shutil
import uuid
import time
import asyncio
import pathlib

from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks, Body
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from typing import List, Optional

# --- 共通モジュール ---
from tools.base_tool import (
    BASE_TEMP_DIR,
    tasks,
    init_db,
    get_colab_url,
    set_colab_url,
    get_session_paths,
    zip_output,
)

# --- 各ツールモジュール ---
from tools.image_tools   import convert_heic_to_jpg, convert_jpeg_to_pdf, convert_pdf_to_png
from tools.audio_tools   import convert_to_mp3
from tools.youtube_tools import download_youtube
from tools.file_tools import verify_password, list_files, build_zip  # ←追加①

SECRET_TOKEN = os.environ.get("SECRET_TOKEN", "")

app = FastAPI()

# --- CORS ---
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# --- DB 初期化 ---
init_db()

# --- 有効な tool_id と output_format の定義 ---
VALID_TOOL_IDS    = {"youtube", "heic-jpg", "m4a-mp3", "mp4-mp3", "jpeg-pdf", "pdf-png"}
VALID_FORMATS     = {"mp3", "mp4"}


# ------------------------------------------------------------------ #
#  バックグラウンドタスク:各ツールへの振り分け
# ------------------------------------------------------------------ #

def process_task(
    task_id: str,
    tool_id: str,
    url_text: str,
    filenames: List[str],
    output_format: str = "mp3"
):
    session_path, input_path, output_path = get_session_paths(task_id)

    try:
        # バリデーション
        if tool_id not in VALID_TOOL_IDS:
            raise ValueError(f"無効なtool_idです: {tool_id}")
        if output_format not in VALID_FORMATS:
            raise ValueError(f"無効なoutput_formatです: {output_format}")

        # --- ツール振り分け ---
        if tool_id == "youtube":
            download_youtube(task_id, url_text, session_path, output_path, output_format)

        elif tool_id == "heic-jpg":
            convert_heic_to_jpg(task_id, filenames, input_path, output_path)

        elif tool_id == "jpeg-pdf":
            convert_jpeg_to_pdf(task_id, filenames, input_path, output_path)

        elif tool_id == "pdf-png":
            convert_pdf_to_png(task_id, filenames, input_path, output_path)

        elif tool_id in ("m4a-mp3", "mp4-mp3"):
            convert_to_mp3(task_id, filenames, input_path, output_path)

        # --- 結果を ZIP 化 ---
        tasks[task_id]["last_log"] = "ファイルを圧縮中..."
        zip_output(session_path, output_path)

        tasks[task_id].update({
            "status": "completed",
            "progress": 100,
            "last_log": "完了",
            "completed_at": time.time(),
        })

    except Exception as e:
        print(f"[ERROR] task_id={task_id}, error={str(e)}")
        tasks[task_id].update({
            "status": "failed",
            "error": str(e),
            "completed_at": time.time(),
        })


# ------------------------------------------------------------------ #
#  定期クリーンアップ(1時間ごとに完了済みタスクを削除)
# ------------------------------------------------------------------ #

async def cleanup_loop():
    while True:
        await asyncio.sleep(3600)
        now = time.time()
        to_delete = [
            tid for tid, t in list(tasks.items())
            if t.get("completed_at") and now - t["completed_at"] > 3600
        ]
        for tid in to_delete:
            tasks.pop(tid, None)
            shutil.rmtree(os.path.join(BASE_TEMP_DIR, tid), ignore_errors=True)


@app.on_event("startup")
async def startup_event():
    try:
        asyncio.create_task(cleanup_loop())
    except Exception as e:
        print(f"Cleanup loop error: {e}")


# ------------------------------------------------------------------ #
#  エンドポイント
# ------------------------------------------------------------------ #

@app.get("/")
async def read_index():
    with open("index.html", "r", encoding="utf-8") as f:
        return HTMLResponse(content=f.read())


@app.get("/health")
async def health_check():
    return {"status": "ok"}


@app.get("/api/config")
async def get_config():
    url = get_colab_url()
    return {"youtube_enabled": url != "", "colab_url": url}


@app.post("/api/update_colab_url")
async def update_colab_url(payload: dict = Body(...)):
    if not SECRET_TOKEN or payload.get("token") != SECRET_TOKEN:
        raise HTTPException(status_code=403, detail="Forbidden")
    url = payload.get("url")
    if not url:
        raise HTTPException(status_code=400, detail="URLが必要です")
    set_colab_url(url)
    print(f"Colab URL Updated: {url}")
    return {"status": "success", "url": url}


@app.post("/api/convert")
async def convert_start(
    background_tasks: BackgroundTasks,
    tool_id: str = Form(...),
    url: Optional[str] = Form(None),
    files: List[UploadFile] = File(default=[]),
    output_format: str = Form("mp3"),
):
    task_id = str(uuid.uuid4())
    os.makedirs(os.path.join(BASE_TEMP_DIR, task_id, "input"), exist_ok=True)

    # 空リストは None として扱う
    if files is not None and len(files) == 0:
        files = None

    fnames = []
    if files:
        for f in files:
            safe_name = pathlib.Path(f.filename).name
            file_path = os.path.join(BASE_TEMP_DIR, task_id, "input", safe_name)
            with open(file_path, "wb") as buf:
                shutil.copyfileobj(f.file, buf)
            fnames.append(safe_name)

    tasks[task_id] = {"status": "processing", "progress": 10, "last_log": "タスクを開始しました"}
    background_tasks.add_task(process_task, task_id, tool_id, url, fnames, output_format)
    return {"task_id": task_id}


@app.get("/api/status/{task_id}")
async def get_status(task_id: str):
    return tasks.get(task_id, {"status": "failed", "error": "Task not found"})


@app.get("/api/download/{task_id}")
async def download_result(task_id: str):
    zip_path = os.path.join(BASE_TEMP_DIR, task_id, "result.zip")
    if os.path.exists(zip_path):
        return FileResponse(zip_path, filename="result.zip")
    if task_id in tasks:
        raise HTTPException(status_code=503, detail="ファイルが一時領域から消えました。再度変換をやり直してください。")
    raise HTTPException(status_code=404, detail="タスクが見つかりません。")


# --- ファイルダウンロード機能 ---  ←追加②

@app.post("/api/files/auth")
async def files_auth(payload: dict = Body(...)):
    """パスワードを照合し、正しければファイル一覧を返す"""
    password = payload.get("password", "")
    if not verify_password(password):
        raise HTTPException(status_code=401, detail="パスワードが正しくありません")
    return {"files": list_files()}


@app.post("/api/files/download")
async def files_download(payload: dict = Body(...)):
    """選択されたファイルをZIPにまとめて返す"""
    password = payload.get("password", "")
    if not verify_password(password):
        raise HTTPException(status_code=401, detail="パスワードが正しくありません")
    filenames = payload.get("filenames", [])
    if not filenames:
        raise HTTPException(status_code=400, detail="ファイルが選択されていません")
    try:
        zip_path = build_zip(filenames)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    return FileResponse(zip_path, filename="download.zip", media_type="application/zip")