RockCoder23's picture
Update app.py
637537b verified
Raw History Blame Contribute Delete
3.88 kB
import os
import json
from typing import List, Any, Optional
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel
import httpx
app = FastAPI(title="Roblox Data Migration Bridge")
OLD_UNIVERSE_ID = os.getenv("OLD_UNIVERSE_ID")
NEW_UNIVERSE_ID = os.getenv("NEW_UNIVERSE_ID")
OLD_API_KEY = os.getenv("OLD_API_KEY")
NEW_API_KEY = os.getenv("NEW_API_KEY")
SERVER_SECRET = os.getenv("SERVER_SECRET")
BASE_URL = "https://apis.roblox.com/datastores/v1/universes"
class ReadRequest(BaseModel):
user_id: int
datastore_names: List[str]
scope: Optional[str] = "global"
class TransferRequest(BaseModel):
user_id: int
datastore_names: List[str]
scope: Optional[str] = "global"
def verify_auth(auth_header: Optional[str]):
if not SERVER_SECRET:
return
if not auth_header or auth_header != f"Bearer {SERVER_SECRET}":
raise HTTPException(status_code=401, detail="Unauthorized request")
async def fetch_opencloud_entry(client: httpx.AsyncClient, universe_id: str, api_key: str, ds_name: str, key: str, scope: str) -> Any:
url = f"{BASE_URL}/{universe_id}/standard-datastores/datastore/entries/entry"
params = {"datastoreName": ds_name, "entryKey": key, "scope": scope}
headers = {"x-api-key": api_key}
res = await client.get(url, params=params, headers=headers)
if res.status_code == 200:
try:
return res.json()
except json.JSONDecodeError:
return res.text
elif res.status_code == 404:
return None
else:
raise HTTPException(status_code=res.status_code, detail=f"Open Cloud Read Error ({ds_name}): {res.text}")
async def write_opencloud_entry(client: httpx.AsyncClient, universe_id: str, api_key: str, ds_name: str, key: str, scope: str, data: Any) -> bool:
url = f"{BASE_URL}/{universe_id}/standard-datastores/datastore/entries/entry"
params = {"datastoreName": ds_name, "entryKey": key, "scope": scope}
headers = {
"x-api-key": api_key,
"content-type": "application/json"
}
payload_str = json.dumps(data)
res = await client.post(url, params=params, headers=headers, content=payload_str)
if res.status_code in (200, 204):
return True
raise HTTPException(status_code=res.status_code, detail=f"Open Cloud Write Error ({ds_name}): {res.text}")
@app.get("/")
def read_root():
return {"status": "online", "message": "Roblox Data Transfer API is running"}
@app.post("/read-old-datastores")
async def read_old_datastores(payload: ReadRequest, authorization: Optional[str] = Header(None)):
verify_auth(authorization)
key = str(payload.user_id)
results = {}
async with httpx.AsyncClient(timeout=10.0) as client:
for ds in payload.datastore_names:
data = await fetch_opencloud_entry(client, OLD_UNIVERSE_ID, OLD_API_KEY, ds, key, payload.scope)
results[ds] = data
return {"status": "success", "user_id": payload.user_id, "data": results}
@app.post("/transfer-datastores")
async def transfer_datastores(payload: TransferRequest, authorization: Optional[str] = Header(None)):
verify_auth(authorization)
key = str(payload.user_id)
transfer_results = {}
async with httpx.AsyncClient(timeout=15.0) as client:
for ds in payload.datastore_names:
old_data = await fetch_opencloud_entry(client, OLD_UNIVERSE_ID, OLD_API_KEY, ds, key, payload.scope)
if old_data is not None:
success = await write_opencloud_entry(client, NEW_UNIVERSE_ID, NEW_API_KEY, ds, key, payload.scope, old_data)
transfer_results[ds] = {"migrated": success, "data": old_data}
else:
transfer_results[ds] = {"migrated": False, "reason": "No old data found"}
return {"status": "success", "user_id": payload.user_id, "results": transfer_results}