Spaces:
Sleeping
Sleeping
File size: 18,037 Bytes
cdbb344 454c57c cdbb344 d3c3907 cdbb344 b8b0315 cdbb344 d3c3907 cdbb344 1fb292d 454c57c b8b0315 cdbb344 454c57c cdbb344 454c57c cdbb344 b8b0315 cdbb344 454c57c b8b0315 cdbb344 e894d0d cdbb344 b8b0315 1fb292d b8b0315 cdbb344 e894d0d cdbb344 1fb292d b8b0315 cdbb344 e894d0d b8b0315 1fb292d 454c57c cdbb344 d3c3907 cdbb344 | 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 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 | """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)
|