Godotmaker / app.py
Cnass's picture
Upload folder using huggingface_hub
454c57c verified
Raw History Blame Contribute Delete
18 kB
"""Riaslink Godotmaker — FastAPI arayüzü (rpgmaker/app.py iskeletinden).
Rotalar:
GET / form (static/index.html)
POST /api/uploads oyun zip'ini depoya al
GET /api/uploads depodaki oyunlar
DELETE /api/uploads/{id} depodan sil
GET /api/inspect/{id} oyun bilgisi (sürüm, ad, destek durumu)
POST /api/fonts/{id}/check yazı tiplerinde eksik Türkçe harf → tamamlanmış hâlin önizlemesi
POST /api/fonts/{id}/approve önizlenen yazı tiplerini onayla (sonraki derlemelerde uygulanır)
POST /api/fonts/{id}/reject onayı geri al
POST /api/build derleme başlat → {build_id}
GET /api/build/{id}/stream SSE canlı log
GET /api/build/{id}/download APK
"""
from __future__ import annotations
import asyncio
import hashlib
import hmac
import json
import os
import shutil
import tempfile
import threading
import uuid
import zipfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Literal
from fastapi import FastAPI, File, Form, Header, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from starlette.background import BackgroundTask
import upload_cache
import godot_android as ga
import godot_fonts as gf
import godot_overlay as go
import zipcheck
from build_pipeline import (BuildRequest, BuildResult, build_apk, check_fonts_zip, data_dir, inspect_zip,
slugify, translation_source_zip)
STATIC_DIR = Path(__file__).parent / "static"
_DATA_DIR, DATA_IS_PERSISTENT = data_dir()
UPLOADS_ROOT = _DATA_DIR / "uploads" if DATA_IS_PERSISTENT else Path("/tmp/godotmaker-uploads")
if not DATA_IS_PERSISTENT:
print("UYARI: kalıcı depolama (/data) yok — yüklenen oyunlar ve Godot şablonları "
"Space yeniden başlayınca silinir.", flush=True)
UPLOADS = upload_cache.UploadCache(UPLOADS_ROOT)
FONTS_ROOT = _DATA_DIR / "fonts" if DATA_IS_PERSISTENT else Path("/tmp/godotmaker-fonts")
BUILDS_ROOT = Path("/tmp/godotmaker-builds")
VALID_ABIS = {"arm64-v8a", "armeabi-v7a", "x86_64"}
MAX_TRANSLATION_BYTES = 20 << 20
PACKER_PASSWORD_ENV = "PACKER_PASSWORD"
app = FastAPI(title="Riaslink Godotmaker")
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
@dataclass
class BuildState:
status: Literal["queued", "running", "success", "failed"] = "queued"
log_lines: list[str] = field(default_factory=list)
apk_path: str | None = None
error_message: str | None = None
_builds: dict[str, BuildState] = {}
_builds_lock = threading.Lock()
# Gradle 4+ GB bellek istiyor; aynı anda tek derleme.
_gradle_slot = threading.Semaphore(1)
_MAX_KEPT_BUILDS = 10
_kept_builds: list[Path] = []
def _keep_only_apk(work_root: Path, apk_path: str) -> str:
kept = work_root / Path(apk_path).name
if Path(apk_path) != kept:
os.replace(apk_path, kept)
for child in work_root.iterdir():
if child != kept:
shutil.rmtree(child, ignore_errors=True) if child.is_dir() else child.unlink(missing_ok=True)
_kept_builds.append(work_root)
while len(_kept_builds) > _MAX_KEPT_BUILDS:
shutil.rmtree(_kept_builds.pop(0), ignore_errors=True)
return str(kept)
def _run_build(build_id: str, req: BuildRequest, upload_id: str) -> None:
def log(msg: str) -> None:
with _builds_lock:
_builds[build_id].log_lines.append(msg)
work_root = BUILDS_ROOT / build_id
work_root.mkdir(parents=True, exist_ok=True)
try:
if not _gradle_slot.acquire(blocking=False):
log("Başka bir derleme sürüyor; sıra bekleniyor…")
_gradle_slot.acquire()
with _builds_lock:
_builds[build_id].status = "running"
try:
result: BuildResult = build_apk(UPLOADS.path_of(upload_id), req, log, work_root)
except Exception as exc: # noqa: BLE001 — beklenmeyen hata da kullanıcıya ulaşsın
result = BuildResult(False, None, f"Beklenmeyen hata: {exc!r}")
finally:
_gradle_slot.release()
finally:
UPLOADS.release(upload_id)
kept = _keep_only_apk(work_root, result.apk_path) if result.success else None
if not result.success:
shutil.rmtree(work_root, ignore_errors=True)
with _builds_lock:
state = _builds[build_id]
state.status = "success" if result.success else "failed"
state.apk_path = kept
state.error_message = None if result.success else result.message
def build_password_error(given: str) -> str | None:
expected = os.environ.get(PACKER_PASSWORD_ENV, "").strip()
if not expected:
return (f"Derleme kapalı: Space secret'ı {PACKER_PASSWORD_ENV} tanımlı değil. "
"Space ayarlarından bir şifre tanımla.")
if not hmac.compare_digest(given.encode("utf-8"), expected.encode("utf-8")):
return "Şifre yanlış."
return None
async def _password_refusal(given: str) -> JSONResponse | None:
error = build_password_error(given)
if error is None:
return None
await asyncio.sleep(1) # tahmin denemelerini yavaşlatır
return JSONResponse({"detail": error}, status_code=403)
async def _stream_to_store(upload: UploadFile) -> upload_cache.CachedUpload:
entry_id, part_path = UPLOADS.new_staging_path()
hasher = hashlib.sha256()
try:
with part_path.open("wb") as target:
while True:
chunk = await upload.read(1024 * 1024)
if not chunk:
break
hasher.update(chunk)
await asyncio.to_thread(target.write, chunk)
await asyncio.to_thread(target.flush)
try:
await asyncio.to_thread(os.fsync, target.fileno())
except OSError:
pass
except BaseException:
UPLOADS.abort(entry_id)
raise
finally:
await upload.close()
return await asyncio.to_thread(
UPLOADS.commit, entry_id, part_path, upload.filename or "oyun.zip", hasher.hexdigest())
def _check_stored(entry: upload_cache.CachedUpload) -> JSONResponse | None:
path = UPLOADS.path_of(entry.id)
if entry.size == 0:
UPLOADS.remove(entry.id)
return JSONResponse({"detail": "Yüklenen dosya boş."}, status_code=400)
health = zipcheck.derin_denetle(path)
if not health.ok:
UPLOADS.remove(entry.id)
member = f" (ilk bozuk dosya: {health.bozuk_uye})" if health.bozuk_uye else ""
return JSONResponse({"detail": (
f"Yüklenen dosya açılabilir bir zip değil — {health.hata}{member}. "
"Yükleme yarıda kalmış olabilir, tekrar dene.")}, status_code=400)
return None
async def _store_upload(upload: UploadFile):
entry = await _stream_to_store(upload)
refusal = await asyncio.to_thread(_check_stored, entry)
return (None, refusal) if refusal else (entry, None)
PASSWORD_HEADER = Header("", alias="X-Build-Password")
@app.get("/", response_class=HTMLResponse)
async def index() -> HTMLResponse:
return HTMLResponse((STATIC_DIR / "index.html").read_text(encoding="utf-8"))
@app.post("/api/uploads")
async def upload_game(game_zip: UploadFile = File(...), build_password: str = Form("")):
refusal = await _password_refusal(build_password)
if refusal:
return refusal
if not game_zip.filename:
return JSONResponse({"detail": "Bir dosya seçilmedi."}, status_code=400)
entry, refusal = await _store_upload(game_zip)
return refusal or {"upload": entry.public()}
@app.get("/api/uploads")
async def list_uploads(build_password: str = PASSWORD_HEADER):
refusal = await _password_refusal(build_password)
if refusal:
return refusal
entries = UPLOADS.list()
return {"uploads": [e.public() for e in entries], "free_bytes": UPLOADS.free_bytes(),
"persistent": DATA_IS_PERSISTENT}
@app.delete("/api/uploads/{upload_id}")
async def delete_upload(upload_id: str, build_password: str = PASSWORD_HEADER):
refusal = await _password_refusal(build_password)
if refusal:
return refusal
if UPLOADS.get(upload_id) is None:
return JSONResponse({"detail": "Bu oyun listede yok."}, status_code=404)
if not UPLOADS.remove(upload_id):
return JSONResponse({"detail": "Oyun şu anda bir derlemede kullanılıyor."}, status_code=409)
return {"ok": True}
@app.get("/api/inspect/{upload_id}")
async def inspect_upload(upload_id: str, build_password: str = PASSWORD_HEADER):
refusal = await _password_refusal(build_password)
if refusal:
return refusal
entry = UPLOADS.acquire(upload_id)
if entry is None:
return JSONResponse({"detail": "Bu oyun listede yok."}, status_code=404)
try:
return await asyncio.to_thread(inspect_zip, UPLOADS.path_of(upload_id))
finally:
UPLOADS.release(upload_id)
@app.post("/api/fonts/{upload_id}/check")
async def fonts_check(upload_id: str, build_password: str = PASSWORD_HEADER):
refusal = await _password_refusal(build_password)
if refusal:
return refusal
entry = UPLOADS.acquire(upload_id)
if entry is None:
return JSONResponse({"detail": "Bu oyun listede yok."}, status_code=404)
try:
items = await asyncio.to_thread(check_fonts_zip, UPLOADS.path_of(upload_id))
await asyncio.to_thread(gf.save_pending, FONTS_ROOT, upload_id, items)
except Exception as exc: # noqa: BLE001 - oyun okunamazsa form yine de çalışsın
return JSONResponse({"detail": f"Yazı tipleri denetlenemedi: {exc}"}, status_code=422)
finally:
UPLOADS.release(upload_id)
onayli = [v["kaynak"] for v in gf.approved(FONTS_ROOT, upload_id).values()]
return {"fontlar": [i.as_json() for i in items], "onayli": onayli}
@app.post("/api/fonts/{upload_id}/approve")
async def fonts_approve(upload_id: str, build_password: str = PASSWORD_HEADER):
refusal = await _password_refusal(build_password)
if refusal:
return refusal
try:
return {"onayli": gf.approve(FONTS_ROOT, upload_id)}
except gf.FontError as exc:
return JSONResponse({"detail": str(exc)}, status_code=400)
@app.post("/api/fonts/{upload_id}/reject")
async def fonts_reject(upload_id: str, build_password: str = PASSWORD_HEADER):
refusal = await _password_refusal(build_password)
if refusal:
return refusal
try:
gf.reject(FONTS_ROOT, upload_id)
except gf.FontError as exc:
return JSONResponse({"detail": str(exc)}, status_code=400)
return {"onayli": []}
def _parse_controls(text: str) -> list[go.ActionChoice] | None:
"""Formdaki kontrol seçimleri: [{"name", "enabled", "label", "caption"}] JSON'u."""
if not text.strip():
return None
try:
items = json.loads(text)
except json.JSONDecodeError as exc:
raise ValueError("Kontrol listesi okunamadı.") from exc
if not isinstance(items, list):
raise ValueError("Kontrol listesi bir dizi olmalı.")
out = []
for it in items[:64]:
if not isinstance(it, dict) or not str(it.get("name", "")).strip():
raise ValueError("Kontrol listesinde adı olmayan öğe var.")
out.append(go.ActionChoice(str(it["name"]).strip(), str(it.get("label") or "")[:3],
str(it.get("caption") or "")[:12], bool(it.get("enabled", True))))
return out
@app.post("/api/build")
async def start_build(
game_zip: UploadFile | None = None,
cached_zip_id: str = Form(""),
app_name: str = Form(""),
application_id: str = Form(""),
version_name: str = Form("1.0"),
version_code: str = Form(""),
abis: str = Form("arm64-v8a"),
template_version: str = Form(""),
build_password: str = Form(""),
overlay: str = Form("1"),
controls_json: str = Form(""),
optimize: str = Form("1"),
renderer: str = Form("auto"),
translation_file: UploadFile | None = None,
):
refusal = await _password_refusal(build_password)
if refusal:
return refusal
abi_list = [a.strip() for a in abis.split(",") if a.strip()] or ["arm64-v8a"]
try:
code = int(version_code.strip() or 0)
except ValueError:
return JSONResponse({"detail": "Sürüm kodu sayı olmalı (boş = otomatik)."}, status_code=400)
if any(a not in VALID_ABIS for a in abi_list):
return JSONResponse({"detail": f"Geçersiz ABI. Seçenekler: {', '.join(sorted(VALID_ABIS))}"},
status_code=400)
if renderer not in ga.RENDERERS:
return JSONResponse({"detail": f"Geçersiz görüntü motoru. Seçenekler: {', '.join(ga.RENDERERS)}"},
status_code=400)
try:
choices = _parse_controls(controls_json)
except ValueError as exc:
return JSONResponse({"detail": str(exc)}, status_code=400)
translation = None
if translation_file is not None and translation_file.filename:
raw = await translation_file.read(MAX_TRANSLATION_BYTES + 1)
if len(raw) > MAX_TRANSLATION_BYTES:
return JSONResponse({"detail": "Çeviri dosyası çok büyük (en çok 20 MB)."}, status_code=413)
try:
translation = go.load_translation(raw)
except (ValueError, zipfile.BadZipFile) as exc:
return JSONResponse({"detail": str(exc)}, status_code=400)
if cached_zip_id.strip():
entry = UPLOADS.acquire(cached_zip_id.strip())
if entry is None:
return JSONResponse({"detail": "Seçilen oyun artık depoda yok; yeniden yükle."}, status_code=410)
elif game_zip is not None and game_zip.filename:
stored, refusal = await _store_upload(game_zip)
if refusal:
return refusal
entry = UPLOADS.acquire(stored.id)
if entry is None:
return JSONResponse({"detail": "Yüklenen oyun depoya alınamadı."}, status_code=500)
else:
return JSONResponse({"detail": "Bir oyun zip'i yükle ya da listeden seç."}, status_code=400)
req = BuildRequest(app_name=app_name.strip(), application_id=application_id.strip(),
version_name=version_name.strip() or "1.0", version_code=code,
abis=abi_list, template_version=template_version.strip(),
overlay=overlay.strip() not in ("0", "false", ""), actions=choices,
translation=translation, optimize=optimize.strip() not in ("0", "false", ""),
renderer=renderer, fonts=gf.approved(FONTS_ROOT, entry.id) or None)
build_id = uuid.uuid4().hex
with _builds_lock:
_builds[build_id] = BuildState()
threading.Thread(target=_run_build, args=(build_id, req, entry.id), daemon=True).start()
return {"build_id": build_id}
def _sse(payload: dict) -> str:
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
@app.get("/api/uploads/{upload_id}/translation-source")
async def translation_source(upload_id: str, build_password: str = PASSWORD_HEADER):
"""Oyunun yalnız sahne/betik dosyaları (zip): Gemini Translator'a yüklenir, çıktısı derleme
formundaki çeviri alanına geri gelir."""
refusal = await _password_refusal(build_password)
if refusal:
return refusal
entry = UPLOADS.acquire(upload_id)
if entry is None:
return JSONResponse({"detail": "Bu oyun listede yok."}, status_code=404)
out = Path(tempfile.mkdtemp(prefix="godotmaker-ceviri-")) / "kaynak.zip"
try:
count = await asyncio.to_thread(translation_source_zip, UPLOADS.path_of(upload_id), out)
except Exception as exc: # noqa: BLE001 - desteklenmeyen/bozuk oyun
shutil.rmtree(out.parent, ignore_errors=True)
return JSONResponse({"detail": f"Çeviri dosyaları çıkarılamadı: {exc}"}, status_code=400)
finally:
UPLOADS.release(upload_id)
if not count:
shutil.rmtree(out.parent, ignore_errors=True)
return JSONResponse({"detail": "Oyunda sahne/betik dosyası bulunamadı."}, status_code=400)
stem = slugify(Path(entry.name).stem) or "oyun"
return FileResponse(out, media_type="application/zip", filename=f"{stem}-ceviri-kaynak.zip",
background=BackgroundTask(shutil.rmtree, out.parent, ignore_errors=True))
@app.get("/api/build/{build_id}/stream")
async def stream_build_log(build_id: str) -> StreamingResponse:
async def events():
sent = 0
while True:
with _builds_lock:
state = _builds.get(build_id)
if state is None:
yield _sse({"type": "error", "message": "Bilinmeyen derleme."})
return
new = state.log_lines[sent:]
sent = len(state.log_lines)
status, ready, err = state.status, state.apk_path is not None, state.error_message
for line in new:
yield _sse({"type": "log", "line": line})
if status in ("success", "failed"):
yield _sse({"type": "done", "status": status, "error_message": err,
"download_url": f"/api/build/{build_id}/download" if ready else None})
return
await asyncio.sleep(0.5)
return StreamingResponse(events(), media_type="text/event-stream")
@app.get("/api/build/{build_id}/download")
async def download_apk(build_id: str):
with _builds_lock:
state = _builds.get(build_id)
if state is None or state.apk_path is None or not Path(state.apk_path).exists():
return HTMLResponse("APK bulunamadı ya da derleme bitmedi.", status_code=404)
path = Path(state.apk_path)
return FileResponse(path, media_type="application/vnd.android.package-archive", filename=path.name)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)