nomadro/apps/taro/api/main.py

188 lines
7.3 KiB
Python

"""Standalone Taro preview API; local state, no production routing or provider credentials."""
import asyncio
import copy
import hmac
import json
import os
import secrets
import time
from datetime import datetime, timezone
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from starlette.middleware.trustedhost import TrustedHostMiddleware
from store import Store
class Login(BaseModel):
password: str
class ConfigWrite(BaseModel):
config: dict
version: int = Field(ge=1)
def create_app(database=None):
app = FastAPI(title='Taro Web independent preview API')
app.add_middleware(TrustedHostMiddleware, allowed_hosts=['localhost', '127.0.0.1', 'testserver'])
store = Store(database) if database else Store()
app.state.store = store
sessions = {}
@app.middleware('http')
async def local_origin(request: Request, call_next):
origin = request.headers.get('origin', '')
if origin and origin not in {'http://localhost:10087', 'http://127.0.0.1:10087',
'http://localhost:10088', 'http://127.0.0.1:10088'}:
return Response(status_code=403)
return await call_next(request)
def require_admin(request):
token = request.cookies.get('taro_admin_session', '')
if sessions.get(token, 0) < time.monotonic():
sessions.pop(token, None)
raise HTTPException(401, '请登录 Taro 独立后台')
@app.get('/health')
def health():
return {'ok': True, 'project': 'taro-web', 'storage': 'independent-sqlite', 'livePayments': False}
@app.post('/api/admin/login')
def login(body: Login, response: Response):
expected = os.getenv('TARO_ADMIN_PASSWORD', 'taro-preview-local')
if not hmac.compare_digest(body.password.encode(), expected.encode()):
raise HTTPException(401, '密码不正确')
token = secrets.token_urlsafe(32)
sessions[token] = time.monotonic() + 8 * 3600
response.set_cookie('taro_admin_session', token, httponly=True, samesite='strict', max_age=8 * 3600)
return {'ok': True, 'project': 'taro-web'}
@app.post('/api/admin/logout')
def logout(request: Request, response: Response):
sessions.pop(request.cookies.get('taro_admin_session'), None)
response.delete_cookie('taro_admin_session')
return {'ok': True}
@app.get('/api/admin/config')
def admin_config(request: Request):
require_admin(request)
return {'config': store.get('config')}
@app.put('/api/admin/config')
def write_config(body: ConfigWrite, request: Request):
require_admin(request)
if not all(isinstance(body.config.get(key), dict) for key in ['modules', 'flags', 'copy']):
raise HTTPException(422, 'modules、flags、copy 必须是对象')
candidate = {**body.config, 'updatedAt': datetime.now(timezone.utc).isoformat()}
try:
config = store.save_config(candidate, body.version)
except ValueError:
raise HTTPException(409, '配置已更新,请重新加载后编辑')
return {'ok': True, 'config': config}
@app.get('/api/admin/catalogs')
def catalogs(request: Request):
require_admin(request)
return store.get('catalogs')
@app.put('/api/admin/catalogs/{name}')
async def write_catalog(name: str, request: Request):
require_admin(request)
catalogs = store.get('catalogs')
if name not in catalogs or name == 'stats':
raise HTTPException(404, 'unknown_catalog')
value = await request.json()
if not isinstance(value, list) or any(not isinstance(item, dict) for item in value):
raise HTTPException(422, '目录必须是对象数组')
store.update_catalog(name, value)
return {'ok': True}
@app.api_route('/api/config', methods=['GET', 'POST'])
@app.post('/api/config/pull')
def config():
return {'config': store.get('config')}
@app.get('/api/config/meta')
def meta():
config = store.get('config')
return {'version': config['version'], 'updatedAt': config['updatedAt']}
@app.get('/api/config/stream')
async def stream(request: Request):
async def events():
previous = None
while not await request.is_disconnected():
config = store.get('config')
if config['version'] != previous:
previous = config['version']
yield f'event: config\ndata: {json.dumps({"version": previous})}\n\n'
else:
yield ': keepalive\n\n'
await asyncio.sleep(2)
return StreamingResponse(events(), media_type='text/event-stream', headers={'Cache-Control': 'no-store'})
@app.get('/api/ebook/books/{book_id}')
def book(book_id: str):
return {**store.seed['book']['book'], 'id': book_id}
@app.get('/api/ebook/books/{book_id}/read')
def read(book_id: str):
payload = copy.deepcopy(store.seed['book'])
payload['book']['id'] = book_id
return payload
@app.post('/api/ebook/track')
def track():
return {'ok': True, 'project': 'taro-web'}
@app.api_route('/api/ebook/pay/{path:path}', methods=['GET', 'POST'])
@app.api_route('/api/pay/{path:path}', methods=['GET', 'POST'])
def payments(path: str):
raise HTTPException(409, 'Taro 独立预览不创建真实支付订单')
@app.get('/api/v1/{name}')
def public_catalog(name: str):
if name not in ['destinations', 'meetups', 'visas', 'testimonials', 'stats']:
raise HTTPException(404, 'unknown_catalog')
return store.get('catalogs')[name]
@app.get('/api/v1/destinations/{slug}')
def destination(slug: str):
row = next((item for item in store.get('catalogs')['destinations'] if item.get('slug') == slug), None)
if not row:
raise HTTPException(404, 'destination_not_found')
return row
@app.get('/api/social/v1/{name}')
def social_catalog(name: str):
catalog = store.get('catalogs')
key = 'socialMeetups' if name == 'meetups' else name
if key not in ['channels', 'roster', 'gigs', 'cafes', 'cities', 'socialMeetups', 'videos', 'ebooks']:
raise HTTPException(404, 'unknown_catalog')
return {'items': catalog[key], 'source': 'taro-preview'}
@app.get('/api/social/v1/channels/{channel}/messages')
def messages(channel: str):
items = store.get('messages:' + channel) or []
return {'items': items, 'seq': len(items)}
@app.post('/api/social/v1/channels/{channel}/messages')
async def post_message(channel: str, request: Request):
body = await request.json()
if not isinstance(body, dict) or not isinstance(body.get('text'), str) or not body['text'].strip():
raise HTTPException(422, 'text_required')
if len(body['text']) > 4000:
raise HTTPException(422, 'message_too_long')
item = {'id': secrets.token_hex(8), 'author': str(body.get('author') or '预览用户'),
'text': body['text'], 'channelId': channel,
'at': datetime.now(timezone.utc).isoformat(), 'clientId': body.get('clientId')}
return store.append_message(channel, item)
return app
app = create_app()