// 与服务器通信:所有接口沿用原有地址和格式,只是换了界面。 const PASSWORD_KEY = 'xiaoshuo_app_password' const LEGACY_KEYS = ['xiaoshuo_fanqie_password'] export function getPassword(): string { try { const v = localStorage.getItem(PASSWORD_KEY) if (v) return v for (const k of LEGACY_KEYS) { const old = localStorage.getItem(k) if (old) return old } } catch {} return '' } export function setPassword(v: string) { try { if (v) localStorage.setItem(PASSWORD_KEY, v) else localStorage.removeItem(PASSWORD_KEY) } catch {} } export class ApiError extends Error { status: number data: any constructor(status: number, message: string, data?: any) { super(message) this.status = status this.data = data } } let onUnauthorized: (() => void) | null = null export function setUnauthorizedHandler(fn: () => void) { onUnauthorized = fn } function headers(extra?: Record) { const h: Record = { ...(extra || {}) } const pw = getPassword() if (pw) h['x-app-password'] = encodeURIComponent(pw) return h } export async function request(method: string, url: string, body?: unknown): Promise { const init: RequestInit = { method, headers: headers(body !== undefined ? { 'Content-Type': 'application/json' } : undefined) } if (body !== undefined) init.body = JSON.stringify(body) let res: Response try { res = await fetch(url, init) } catch { throw new ApiError(0, '网络连接失败,请稍后再试') } const text = await res.text() let data: any = null try { data = text ? JSON.parse(text) : null } catch { data = text } if (res.status === 401) { onUnauthorized?.() throw new ApiError(401, '需要访问密码', data) } if (!res.ok) throw new ApiError(res.status, (data && data.error) || `请求失败(${res.status})`, data) return data as T } export const get = (url: string) => request('GET', url) export const post = (url: string, body: unknown = {}) => request('POST', url, body) export const put = (url: string, body: unknown = {}) => request('PUT', url, body) export const patch = (url: string, body: unknown = {}) => request('PATCH', url, body) export const del = (url: string) => request('DELETE', url) export function qs(params: Record) { const u = new URLSearchParams() for (const [k, v] of Object.entries(params)) { if (v === undefined || v === null || v === '' || v === false) continue u.set(k, String(v === true ? 1 : v)) } const s = u.toString() return s ? `?${s}` : '' } export async function checkPassword(pw: string): Promise { const res = await fetch('/api/auth/check', { headers: { 'x-app-password': encodeURIComponent(pw) } }) return res.ok } export async function authRequired(): Promise { try { const r = await fetch('/api/auth') const d = await r.json() return Boolean(d?.required) } catch { return true } } // 下载需要密码的文件 export async function download(url: string, filename: string) { const res = await fetch(url, { headers: headers() }) if (res.status === 401) { onUnauthorized?.(); throw new ApiError(401, '需要访问密码') } if (!res.ok) throw new ApiError(res.status, `下载失败(${res.status})`) const blob = await res.blob() const a = document.createElement('a') a.href = URL.createObjectURL(blob) a.download = filename document.body.appendChild(a) a.click() setTimeout(() => { URL.revokeObjectURL(a.href); a.remove() }, 1000) } /* ---------- 数据类型 ---------- */ export interface Project { project_id: string title: string genre: string target_platform: string target_words: number pov: string style: string premise: string status: string created_at: string updated_at: string revision: number current_chapter_id: string | null } export interface Chapter { chapter_id: string project_id: string number: number volume: string title: string goal: string outline: string scenes: any[] previous_summary: string status: string current_version_id: string | null created_at: string updated_at: string revision: number versions?: VersionMeta[] } export interface VersionMeta { version_id: string; chapter_id: string; created_at: string; kind: string; summary: string; word_count: number } export interface Version extends VersionMeta { project_id: string; text: string; notes: string; source_version_id: string | null; created_by: string } export interface Bible { story_core: string; main_plot: string; ending_direction: string; reader_expectation: string characters: any[]; relationships: any[]; timeline: any[]; settings: any[]; foreshadowing: any[] open_questions: any[]; style_rules: any[]; safety_rules: any[]; source_material_uids: any[] updated_at?: string; [k: string]: any } export interface Outline { three_act: any[]; volumes: any[]; chapters: any[]; updated_at?: string; [k: string]: any } export interface Material { uid: string; ch: string; at: string; d: string; q: number; g: string; k: string; sum: string; text: string why?: string; edits?: [string, string][]; src?: string | null; react?: number; score?: number card?: MaterialCard } export interface MaterialCard { uid: string; use?: boolean; motifs?: string[]; logline?: string; beats?: string[] people?: { role?: string; trait?: string; want?: string }[]; arc?: string; details?: string[] scene?: string; hook?: string; twist?: string; roles?: string[] } export interface ProjectBundle { project: Project; bible: Bible; outline: Outline; materials: { items: any[] }; chapters: Chapter[] } const P = '/fanqie/api/projects' export const projectsApi = { list: () => get<{ projects: Project[] }>(P), create: (body: Partial) => post(P, body), get: (id: string) => get(`${P}/${id}`), update: (id: string, body: Partial) => patch(`${P}/${id}`, body), remove: (id: string) => del(`${P}/${id}`), saveBible: (id: string, body: Bible) => put(`${P}/${id}/bible`, body), saveOutline: (id: string, body: Outline) => put(`${P}/${id}/outline`, body), saveMaterials: (id: string, items: any[]) => put<{ items: any[] }>(`${P}/${id}/materials`, { items }), chapters: (id: string) => get(`${P}/${id}/chapters`), createChapter: (id: string, body: Partial) => post(`${P}/${id}/chapters`, body), chapter: (id: string, cid: string) => get<{ project: Project; chapter: Chapter; versions: VersionMeta[] }>(`${P}/${id}/chapters/${cid}`), updateChapter: (id: string, cid: string, body: Partial) => patch(`${P}/${id}/chapters/${cid}`, body), versions: (id: string, cid: string) => get(`${P}/${id}/chapters/${cid}/versions`), version: (id: string, cid: string, vid: string) => get(`${P}/${id}/chapters/${cid}/versions/${vid}`), saveVersion: (id: string, cid: string, body: { text: string; kind?: string; summary?: string; notes?: string; source_version_id?: string | null; created_by?: string }) => post(`${P}/${id}/chapters/${cid}/versions`, body), rollback: (id: string, cid: string, vid: string) => post<{ chapter: Chapter; version: Version }>(`${P}/${id}/chapters/${cid}/versions/${vid}/rollback`, {}), check: (id: string, cid: string) => post(`${P}/${id}/chapters/${cid}/check`, {}), getCheck: (id: string, vid: string) => get(`${P}/${id}/checks/${vid}`), context: (id: string, cid?: string) => get(`${P}/${id}/context${qs({ chapter_id: cid })}`), requests: (id: string) => get<{ requests: any[] }>(`${P}/${id}/requests`), createRequest: (id: string, body: { type: string; instruction: string; chapter_id?: string | null }) => post(`${P}/${id}/requests`, body), } const M = '/fanqie/api/materials' export const materialsApi = { stats: () => get(`${M}/stats`), list: (p: Record) => get<{ total: number; page: number; size: number; items: Material[] }>(`${M}${qs(p)}`), random: (p: Record) => get<{ total: number; items: Material[] }>(`${M}/random${qs(p)}`), item: (uid: string) => get(`${M}/item${qs({ uid })}`), motifs: () => get(`${M}/motifs`), motif: (id: string, page = 1, size = 20) => get(`${M}/motif${qs({ id, page, size })}`), search: (p: Record) => get<{ total: number; motifs: string[]; items: Material[] }>(`${M}/search${qs(p)}`), compose: (p: Record) => get(`${M}/compose${qs(p)}`), }