api.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. /**
  2. * API 工具类
  3. * 统一管理后端 API 调用
  4. */
  5. import { getUserId, getUserToken } from './storage';
  6. /** 后端返回 detail 为 { code: string } 或旧版字符串 */
  7. function getDetailCode(detail: unknown): string | undefined {
  8. if (detail && typeof detail === 'object' && 'code' in detail && typeof (detail as { code: unknown }).code === 'string') {
  9. return (detail as { code: string }).code;
  10. }
  11. if (typeof detail === 'string') return detail;
  12. return undefined;
  13. }
  14. /**
  15. * 解析 4xx/5xx 响应为带 code 的 ApiError,供前端用 t('error.' + code) 展示
  16. */
  17. export class ApiError extends Error {
  18. code: string;
  19. status: number;
  20. constructor(code: string, status: number, message?: string) {
  21. super(message ?? code);
  22. this.name = 'ApiError';
  23. this.code = code;
  24. this.status = status;
  25. }
  26. }
  27. export async function parseApiError(response: Response, fallbackCode = 'UNKNOWN'): Promise<ApiError> {
  28. let code = fallbackCode;
  29. const contentType = response.headers.get('content-type') || '';
  30. if (contentType.includes('application/json')) {
  31. try {
  32. const body = await response.json();
  33. const detail = body?.detail;
  34. const parsed = getDetailCode(detail);
  35. if (parsed) code = parsed;
  36. } catch {
  37. // ignore
  38. }
  39. }
  40. return new ApiError(code, response.status, response.statusText);
  41. }
  42. /**
  43. * 获取 API Key(从环境变量读取)
  44. */
  45. const getApiKey = (): string => {
  46. return import.meta.env.VITE_API_CLIENT_KEY || '';
  47. };
  48. /**
  49. * 获取统一的请求头(包含 API Key 与用户会话信息)
  50. */
  51. export const getApiHeaders = (): Record<string, string> => {
  52. const headers: Record<string, string> = {
  53. 'Content-Type': 'application/json',
  54. };
  55. const apiKey = getApiKey();
  56. if (apiKey) {
  57. headers['X-Client-Key'] = apiKey;
  58. }
  59. // 附加用户会话信息(用于后端基于 token 的 HTTP 鉴权)
  60. const userId = getUserId();
  61. const token = getUserToken();
  62. if (userId && token) {
  63. headers['X-User-Id'] = userId;
  64. headers['X-User-Token'] = token;
  65. }
  66. return headers;
  67. };
  68. /**
  69. * 会话确保逻辑:
  70. * - 若本地已有 userId + token,直接复用(依赖服务端滑动续期,不主动换 token)
  71. * - 若没有,则通过 /api/session/init 创建一次会话
  72. * - 使用单例 Promise 防抖,避免并发多次刷新导致 token 频繁变更
  73. */
  74. let ensureSessionPromise: Promise<{ userId: string; token: string }> | null = null;
  75. export const ensureSession = async (): Promise<{ userId: string; token: string }> => {
  76. // 已有未完成的会话初始化,直接复用
  77. if (ensureSessionPromise) {
  78. return ensureSessionPromise;
  79. }
  80. // 动态导入,避免循环依赖
  81. const { getUserId: loadUserId, getUserToken: loadUserToken, setUserId, setUserToken } = await import('./storage');
  82. const existingUserId = loadUserId();
  83. const existingToken = loadUserToken();
  84. // 本地已经有 userId + token,则认为会话有效,直接返回
  85. if (existingUserId && existingToken) {
  86. return { userId: existingUserId, token: existingToken };
  87. }
  88. // 没有有效会话时,串行化一次 /api/session/init 调用
  89. ensureSessionPromise = (async () => {
  90. const resp = await initSession(existingUserId || undefined);
  91. if (!resp.success || !resp.data?.token || !resp.data?.user_id) {
  92. throw new Error('Session init failed');
  93. }
  94. setUserId(resp.data.user_id);
  95. setUserToken(resp.data.token);
  96. return { userId: resp.data.user_id, token: resp.data.token };
  97. })();
  98. try {
  99. return await ensureSessionPromise;
  100. } finally {
  101. ensureSessionPromise = null;
  102. }
  103. };
  104. /**
  105. * 获取后端 API 基础 URL
  106. */
  107. export const getApiBaseUrl = (): string => {
  108. // 开发环境:使用相对路径,通过 Vite 代理访问后端
  109. // 这样可以避免 Safari 对自签名证书的跨域限制
  110. if (import.meta.env.DEV) {
  111. return ''; // 使用相对路径,Vite 会代理到后端
  112. }
  113. // 生产环境:使用完整 URL
  114. // 优先使用环境变量指定的 API 地址
  115. if (import.meta.env.VITE_API_BASE_URL) {
  116. return import.meta.env.VITE_API_BASE_URL;
  117. }
  118. // 从 WebSocket URL 推导 API 基础 URL
  119. const wsUrl = import.meta.env.VITE_WS_URL || 'ws://localhost:8000/ws';
  120. // 将 ws:// 或 wss:// 转换为 http:// 或 https://
  121. const apiUrl = wsUrl
  122. .replace(/^wss:\/\//, 'https://')
  123. .replace(/^ws:\/\//, 'http://')
  124. .replace(/\/ws$/, '');
  125. return apiUrl;
  126. };
  127. /**
  128. * 上报页面访问(每次打开任意界面时调用,保存到后台数据库)
  129. * 不阻塞 UI,失败静默忽略。
  130. */
  131. export const reportPageVisit = (path: string): void => {
  132. const apiBaseUrl = getApiBaseUrl();
  133. const body = JSON.stringify({ path: path || '/' });
  134. fetch(`${apiBaseUrl}/api/page-visit`, {
  135. method: 'POST',
  136. headers: getApiHeaders(),
  137. body,
  138. }).catch(() => {});
  139. };
  140. export interface UserEventPayload {
  141. event_id: string;
  142. user_id: string;
  143. event_name: string;
  144. event_label?: string;
  145. event_time: string;
  146. session_id?: string;
  147. platform: 'ios' | 'android' | 'web';
  148. app_version?: string;
  149. timezone_offset_minutes?: number;
  150. properties?: Record<string, unknown>;
  151. }
  152. /**
  153. * 上报单条用户事件(user_events)
  154. * - 不抛异常,失败静默
  155. * - 开发环境会打印请求与响应状态,便于排查未落库问题
  156. */
  157. export const reportUserEvent = (payload: UserEventPayload): void => {
  158. const apiBaseUrl = getApiBaseUrl();
  159. const url = `${apiBaseUrl}/api/user-events`;
  160. const headers = getApiHeaders();
  161. if (import.meta.env.DEV) {
  162. const hasAuth = !!(headers['X-User-Id'] && headers['X-User-Token']);
  163. const keys = Object.keys(payload);
  164. const required = ['event_id', 'user_id', 'event_name', 'event_time', 'platform'];
  165. const missing = required.filter((k) => !(k in payload) || payload[k as keyof UserEventPayload] == null);
  166. if (missing.length) {
  167. console.warn('[user_events] 请求体缺少必填字段:', missing, '当前 keys:', keys);
  168. }
  169. console.log('[user_events] 上报:', payload.event_name, { hasAuth, user_id: payload.user_id, keys });
  170. }
  171. fetch(url, {
  172. method: 'POST',
  173. headers,
  174. body: JSON.stringify(payload),
  175. })
  176. .then(async (res) => {
  177. if (import.meta.env.DEV && !res.ok) {
  178. const body = await res.text();
  179. try {
  180. const parsed = JSON.parse(body);
  181. const details = Array.isArray(parsed?.detail) ? parsed.detail : parsed?.detail ? [parsed.detail] : [];
  182. const first = details[0];
  183. const loc = first?.loc;
  184. console.warn('[user_events] 上报失败:', res.status, payload.event_name, '缺失/错误字段 loc:', loc, 'msg:', first?.msg, '详情:', details);
  185. } catch {
  186. console.warn('[user_events] 上报失败:', res.status, res.statusText, payload.event_name, body?.slice(0, 200));
  187. }
  188. }
  189. })
  190. .catch((err) => {
  191. if (import.meta.env.DEV) {
  192. console.warn('[user_events] 请求异常:', err?.message ?? err, payload.event_name);
  193. }
  194. });
  195. };
  196. /**
  197. * 创建用户
  198. */
  199. export interface CreateUserResponse {
  200. success: boolean;
  201. data: {
  202. user_id: string;
  203. username: string;
  204. user_type: string;
  205. user_level: number;
  206. current_background_image_id?: string;
  207. created_at: string;
  208. };
  209. }
  210. export const createUser = async (username: string = ''): Promise<CreateUserResponse> => {
  211. const apiBaseUrl = getApiBaseUrl();
  212. const url = `${apiBaseUrl}/api/users/create`;
  213. try {
  214. const response = await fetch(url, {
  215. method: 'POST',
  216. headers: getApiHeaders(),
  217. body: JSON.stringify({ username }),
  218. });
  219. if (!response.ok) {
  220. throw await parseApiError(response, 'CREATE_USER_FAILED');
  221. }
  222. const data = await response.json();
  223. // 同步背景图片到 localStorage(包括metadata中的透明度配置)
  224. if (data.success && data.data?.current_background_image_id) {
  225. const { syncBackgroundImageToStorage } = await import('./storage');
  226. syncBackgroundImageToStorage(
  227. data.data.current_background_image_id,
  228. data.data.current_background_image_metadata
  229. );
  230. }
  231. return data;
  232. } catch (error) {
  233. console.error('[API] 创建用户异常:', error);
  234. // 如果是网络错误,提供更友好的提示
  235. if (error instanceof TypeError && error.message.includes('fetch')) {
  236. throw new Error('网络请求失败,请检查后端服务是否运行');
  237. }
  238. throw error;
  239. }
  240. };
  241. /**
  242. * 初始化/刷新会话,返回 user_id + token
  243. */
  244. export interface InitSessionResponse {
  245. success: boolean;
  246. data: {
  247. user_id: string;
  248. token: string;
  249. expires_at: string;
  250. username?: string;
  251. user_level?: number;
  252. current_background_image_id?: string;
  253. current_background_image_metadata?: Record<string, any>;
  254. };
  255. }
  256. export const initSession = async (user_id?: string, username?: string): Promise<InitSessionResponse> => {
  257. const apiBaseUrl = getApiBaseUrl();
  258. const url = `${apiBaseUrl}/api/session/init`;
  259. const body: Record<string, string> = {};
  260. if (user_id) {
  261. body.user_id = user_id;
  262. }
  263. if (username) {
  264. body.username = username;
  265. }
  266. const response = await fetch(url, {
  267. method: 'POST',
  268. headers: getApiHeaders(),
  269. body: JSON.stringify(body),
  270. });
  271. if (!response.ok) {
  272. throw await parseApiError(response, 'INIT_SESSION_FAILED');
  273. }
  274. return response.json();
  275. };
  276. /**
  277. * 获取用户信息
  278. */
  279. export interface GetUserResponse {
  280. success: boolean;
  281. data: {
  282. user_id: string;
  283. username: string;
  284. user_type: string;
  285. user_segment?: string;
  286. org_id?: string | null;
  287. is_test_user?: boolean;
  288. region?: string | null;
  289. bot_name?: string;
  290. total_speech_duration_ms?: number;
  291. user_level?: number;
  292. current_background_image_id?: string;
  293. current_background_image_metadata?: Record<string, any>;
  294. preferred_language?: 'zh' | 'en';
  295. created_at: string;
  296. };
  297. }
  298. export const getUserInfo = async (user_id: string): Promise<GetUserResponse> => {
  299. const apiBaseUrl = getApiBaseUrl();
  300. const response = await fetch(`${apiBaseUrl}/api/users/${user_id}`, {
  301. method: 'GET',
  302. headers: getApiHeaders(),
  303. });
  304. if (!response.ok) {
  305. throw await parseApiError(response, 'GET_USER_INFO_FAILED');
  306. }
  307. const data = await response.json();
  308. // 同步背景图片到 localStorage(包括metadata中的透明度配置)
  309. if (data.success && data.data?.current_background_image_id) {
  310. const { syncBackgroundImageToStorage } = await import('./storage');
  311. syncBackgroundImageToStorage(
  312. data.data.current_background_image_id,
  313. data.data.current_background_image_metadata
  314. );
  315. }
  316. return data;
  317. };
  318. /**
  319. * 更新用户名
  320. */
  321. export interface UpdateUsernameResponse {
  322. success: boolean;
  323. message: string;
  324. }
  325. export const updateUsername = async (user_id: string, username: string): Promise<UpdateUsernameResponse> => {
  326. const apiBaseUrl = getApiBaseUrl();
  327. const response = await fetch(`${apiBaseUrl}/api/users/${user_id}/username`, {
  328. method: 'PUT',
  329. headers: getApiHeaders(),
  330. body: JSON.stringify({ username }),
  331. });
  332. if (!response.ok) {
  333. throw await parseApiError(response, 'UPDATE_USERNAME_FAILED');
  334. }
  335. return response.json();
  336. };
  337. /**
  338. * 更新背景图片ID
  339. */
  340. export interface UpdateBackgroundImageIdResponse {
  341. success: boolean;
  342. message: string;
  343. }
  344. export const updateBackgroundImageId = async (
  345. user_id: string,
  346. background_image_id: string,
  347. ): Promise<UpdateBackgroundImageIdResponse> => {
  348. const apiBaseUrl = getApiBaseUrl();
  349. const response = await fetch(`${apiBaseUrl}/api/users/${user_id}/background-image-id`, {
  350. method: 'PUT',
  351. headers: getApiHeaders(),
  352. body: JSON.stringify({ background_image_id }),
  353. });
  354. if (!response.ok) {
  355. throw await parseApiError(response, 'UPDATE_BG_IMAGE_FAILED');
  356. }
  357. return response.json();
  358. };
  359. /**
  360. * 更新机器人名字
  361. */
  362. export interface UpdateBotNameResponse {
  363. success: boolean;
  364. message: string;
  365. }
  366. export const updateBotName = async (user_id: string, bot_name: string): Promise<UpdateBotNameResponse> => {
  367. const apiBaseUrl = getApiBaseUrl();
  368. const response = await fetch(`${apiBaseUrl}/api/users/${user_id}/bot-name`, {
  369. method: 'PUT',
  370. headers: getApiHeaders(),
  371. body: JSON.stringify({ bot_name }),
  372. });
  373. if (!response.ok) {
  374. throw await parseApiError(response, 'UPDATE_BOT_NAME_FAILED');
  375. }
  376. return response.json();
  377. };
  378. /**
  379. * 用户 UI 状态相关接口
  380. */
  381. export interface UserUIState {
  382. current_page: string | null;
  383. visited_routes: string[];
  384. has_shown_tap_to_chat: boolean;
  385. has_shown_cancel_tooltip: boolean;
  386. has_shown_send_tooltip: boolean;
  387. has_shown_progress_bar_tooltip: boolean;
  388. has_shown_mission_stone_modal: boolean;
  389. has_shown_conversation_stone_modal: boolean;
  390. has_clicked_mission_stone: boolean;
  391. has_clicked_conversation_stone: boolean;
  392. subtitle_on: boolean;
  393. avatar_c_unlocked: boolean;
  394. has_shared_avatar: boolean;
  395. current_avatar_id?: string | null;
  396. }
  397. export interface GetUserUIStateResponse {
  398. success: boolean;
  399. data: {
  400. user_id: string;
  401. } & UserUIState;
  402. }
  403. export const getUserUIState = async (user_id: string): Promise<GetUserUIStateResponse> => {
  404. const apiBaseUrl = getApiBaseUrl();
  405. const response = await fetch(`${apiBaseUrl}/api/users/${user_id}/ui-state`, {
  406. method: 'GET',
  407. headers: getApiHeaders(),
  408. });
  409. if (!response.ok) {
  410. throw await parseApiError(response, 'GET_UI_STATE_FAILED');
  411. }
  412. return response.json();
  413. };
  414. export interface UpdateUserUIStateResponse {
  415. success: boolean;
  416. data: {
  417. user_id: string;
  418. } & UserUIState;
  419. }
  420. export type UpdateUserUIStatePayload = Partial<UserUIState>;
  421. export const updateUserUIState = async (
  422. user_id: string,
  423. payload: UpdateUserUIStatePayload,
  424. ): Promise<UpdateUserUIStateResponse> => {
  425. const apiBaseUrl = getApiBaseUrl();
  426. const response = await fetch(`${apiBaseUrl}/api/users/${user_id}/ui-state`, {
  427. method: 'PUT',
  428. headers: getApiHeaders(),
  429. body: JSON.stringify(payload),
  430. });
  431. if (!response.ok) {
  432. throw await parseApiError(response, 'UPDATE_UI_STATE_FAILED');
  433. }
  434. return response.json();
  435. };
  436. /** 亲密度:heart_count 0-3,days_since_last_visit 距上次访问天数 */
  437. export interface GetIntimacyResponse {
  438. success: boolean;
  439. data: { heart_count: number; days_since_last_visit: number };
  440. }
  441. export const getIntimacy = async (user_id: string): Promise<GetIntimacyResponse> => {
  442. const apiBaseUrl = getApiBaseUrl();
  443. const response = await fetch(`${apiBaseUrl}/api/users/${user_id}/intimacy`, {
  444. method: 'GET',
  445. headers: getApiHeaders(),
  446. });
  447. if (!response.ok) {
  448. throw await parseApiError(response, 'GET_INTIMACY_FAILED');
  449. }
  450. return response.json();
  451. };
  452. export interface LightUpIntimacyResponse {
  453. success: boolean;
  454. data: { heart_count: number };
  455. }
  456. export const lightUpIntimacy = async (user_id: string): Promise<LightUpIntimacyResponse> => {
  457. const apiBaseUrl = getApiBaseUrl();
  458. const response = await fetch(`${apiBaseUrl}/api/users/${user_id}/intimacy/light-up`, {
  459. method: 'POST',
  460. headers: getApiHeaders(),
  461. });
  462. if (!response.ok) {
  463. throw await parseApiError(response, 'LIGHT_UP_INTIMACY_FAILED');
  464. }
  465. return response.json();
  466. };
  467. export interface GetIntimacyStatusResponse {
  468. success: boolean;
  469. data: {
  470. heart_count: number;
  471. can_light_up_today: boolean;
  472. };
  473. }
  474. export const getIntimacyStatus = async (user_id: string): Promise<GetIntimacyStatusResponse> => {
  475. const apiBaseUrl = getApiBaseUrl();
  476. const response = await fetch(`${apiBaseUrl}/api/users/${user_id}/intimacy/status`, {
  477. method: 'GET',
  478. headers: getApiHeaders(),
  479. });
  480. if (!response.ok) {
  481. throw await parseApiError(response, 'GET_INTIMACY_STATUS_FAILED');
  482. }
  483. return response.json();
  484. };
  485. /**
  486. * 注册/登录相关接口
  487. */
  488. // 手机号注册
  489. export interface RegisterPhoneResponse {
  490. success: boolean;
  491. data: {
  492. user_id: string;
  493. username: string;
  494. area_code?: string;
  495. phone: string;
  496. user_type: string;
  497. user_level?: number;
  498. token?: string;
  499. expires_at?: string;
  500. created_at: string;
  501. };
  502. }
  503. export const registerWithPhone = async (
  504. phone: string,
  505. username: string = '',
  506. user_id?: string | null,
  507. area_code?: string,
  508. ): Promise<RegisterPhoneResponse> => {
  509. const apiBaseUrl = getApiBaseUrl();
  510. const body: { phone: string; username: string; user_id?: string; area_code?: string } = { phone, username };
  511. if (user_id) {
  512. body.user_id = user_id;
  513. }
  514. if (area_code) {
  515. body.area_code = area_code;
  516. }
  517. const response = await fetch(`${apiBaseUrl}/api/auth/register/phone`, {
  518. method: 'POST',
  519. headers: getApiHeaders(),
  520. body: JSON.stringify(body),
  521. });
  522. if (!response.ok) {
  523. throw await parseApiError(response, 'REGISTER_FAILED');
  524. }
  525. return response.json();
  526. };
  527. // 邮箱注册
  528. export interface RegisterEmailResponse {
  529. success: boolean;
  530. data: {
  531. user_id: string;
  532. username: string;
  533. email: string;
  534. user_type: string;
  535. user_level?: number;
  536. token?: string;
  537. expires_at?: string;
  538. created_at: string;
  539. };
  540. }
  541. export const registerWithEmail = async (email: string, username: string = '', user_id?: string | null): Promise<RegisterEmailResponse> => {
  542. const apiBaseUrl = getApiBaseUrl();
  543. const body: { email: string; username: string; user_id?: string } = { email, username };
  544. if (user_id) {
  545. body.user_id = user_id;
  546. }
  547. const response = await fetch(`${apiBaseUrl}/api/auth/register/email`, {
  548. method: 'POST',
  549. headers: getApiHeaders(),
  550. body: JSON.stringify(body),
  551. });
  552. if (!response.ok) {
  553. throw await parseApiError(response, 'REGISTER_FAILED');
  554. }
  555. return response.json();
  556. };
  557. // 微信登录
  558. export interface LoginWechatResponse {
  559. success: boolean;
  560. data: {
  561. user_id: string;
  562. username: string;
  563. wechat_openid?: string;
  564. user_type: string;
  565. user_level?: number;
  566. token?: string;
  567. expires_at?: string;
  568. created_at: string;
  569. };
  570. }
  571. export const loginWithWechat = async (openid: string, username: string = ''): Promise<LoginWechatResponse> => {
  572. const apiBaseUrl = getApiBaseUrl();
  573. const response = await fetch(`${apiBaseUrl}/api/auth/login/wechat`, {
  574. method: 'POST',
  575. headers: getApiHeaders(),
  576. body: JSON.stringify({ openid, username }),
  577. });
  578. if (!response.ok) {
  579. throw await parseApiError(response, 'LOGIN_FAILED');
  580. }
  581. return response.json();
  582. };
  583. // QQ登录
  584. export interface LoginQQResponse {
  585. success: boolean;
  586. data: {
  587. user_id: string;
  588. username: string;
  589. qq_openid?: string;
  590. user_type: string;
  591. user_level?: number;
  592. token?: string;
  593. expires_at?: string;
  594. created_at: string;
  595. };
  596. }
  597. export const loginWithQQ = async (openid: string, username: string = ''): Promise<LoginQQResponse> => {
  598. const apiBaseUrl = getApiBaseUrl();
  599. const response = await fetch(`${apiBaseUrl}/api/auth/login/qq`, {
  600. method: 'POST',
  601. headers: getApiHeaders(),
  602. body: JSON.stringify({ openid, username }),
  603. });
  604. if (!response.ok) {
  605. throw await parseApiError(response, 'LOGIN_FAILED');
  606. }
  607. return response.json();
  608. };
  609. // 手机号登录
  610. export interface LoginPhoneResponse {
  611. success: boolean;
  612. data: {
  613. user_id: string;
  614. username: string;
  615. area_code?: string;
  616. phone: string;
  617. user_type: string;
  618. user_level?: number;
  619. token?: string;
  620. expires_at?: string;
  621. created_at: string;
  622. };
  623. }
  624. export const loginWithPhone = async (phone: string, area_code?: string): Promise<LoginPhoneResponse> => {
  625. const apiBaseUrl = getApiBaseUrl();
  626. const response = await fetch(`${apiBaseUrl}/api/auth/login/phone`, {
  627. method: 'POST',
  628. headers: getApiHeaders(),
  629. body: JSON.stringify({ phone, area_code }),
  630. });
  631. if (!response.ok) {
  632. throw await parseApiError(response, 'LOGIN_FAILED');
  633. }
  634. return response.json();
  635. };
  636. // 邮箱登录
  637. export interface LoginEmailResponse {
  638. success: boolean;
  639. data: {
  640. user_id: string;
  641. username: string;
  642. email: string;
  643. user_type: string;
  644. user_level?: number;
  645. token?: string;
  646. expires_at?: string;
  647. created_at: string;
  648. };
  649. }
  650. export const loginWithEmail = async (email: string): Promise<LoginEmailResponse> => {
  651. const apiBaseUrl = getApiBaseUrl();
  652. const response = await fetch(`${apiBaseUrl}/api/auth/login/email`, {
  653. method: 'POST',
  654. headers: getApiHeaders(),
  655. body: JSON.stringify({ email }),
  656. });
  657. if (!response.ok) {
  658. throw await parseApiError(response, 'LOGIN_FAILED');
  659. }
  660. return response.json();
  661. };
  662. // 发送验证码
  663. export interface SendCodeRequest {
  664. area_code?: string; // 手机区号(如 +86)
  665. phone?: string;
  666. email?: string;
  667. send_type: 'domestic_sms' | 'international_sms' | 'email';
  668. }
  669. export interface SendCodeResponse {
  670. success: boolean;
  671. data: {
  672. code_id: string;
  673. message: string;
  674. };
  675. }
  676. export const sendCode = async (request: SendCodeRequest): Promise<SendCodeResponse> => {
  677. const apiBaseUrl = getApiBaseUrl();
  678. const response = await fetch(`${apiBaseUrl}/api/auth/send-code`, {
  679. method: 'POST',
  680. headers: getApiHeaders(),
  681. body: JSON.stringify(request),
  682. });
  683. if (!response.ok) {
  684. throw await parseApiError(response, 'SEND_CODE_FAILED');
  685. }
  686. return response.json();
  687. };
  688. // 验证验证码
  689. export interface VerifyCodeRequest {
  690. phone?: string;
  691. email?: string;
  692. code: string;
  693. send_type: 'domestic_sms' | 'international_sms' | 'email';
  694. }
  695. export interface VerifyCodeResponse {
  696. success: boolean;
  697. data: {
  698. valid: boolean;
  699. message: string;
  700. };
  701. }
  702. export const verifyCode = async (request: VerifyCodeRequest): Promise<VerifyCodeResponse> => {
  703. const apiBaseUrl = getApiBaseUrl();
  704. const response = await fetch(`${apiBaseUrl}/api/auth/verify-code`, {
  705. method: 'POST',
  706. headers: getApiHeaders(),
  707. body: JSON.stringify(request),
  708. });
  709. if (!response.ok) {
  710. throw await parseApiError(response, 'VERIFY_CODE_FAILED');
  711. }
  712. return response.json();
  713. };
  714. // V2.0:验证码通过后统一登录/注册
  715. export interface VerifyAndAuthRequest {
  716. type: 'email' | 'phone';
  717. code: string;
  718. email?: string;
  719. phone?: string;
  720. area_code?: string;
  721. preferred_language?: 'zh' | 'en';
  722. }
  723. export interface VerifyAndAuthResponse {
  724. success: boolean;
  725. data: {
  726. user_id: string;
  727. username?: string;
  728. email?: string;
  729. phone?: string;
  730. user_type: string;
  731. user_level?: number;
  732. token?: string;
  733. expires_at?: string;
  734. is_new_user: boolean;
  735. [key: string]: unknown;
  736. };
  737. }
  738. export const verifyAndAuth = async (request: VerifyAndAuthRequest): Promise<VerifyAndAuthResponse> => {
  739. const apiBaseUrl = getApiBaseUrl();
  740. const response = await fetch(`${apiBaseUrl}/api/auth/verify-and-auth`, {
  741. method: 'POST',
  742. headers: getApiHeaders(),
  743. body: JSON.stringify(request),
  744. });
  745. if (!response.ok) {
  746. throw await parseApiError(response, 'CODE_INVALID');
  747. }
  748. return response.json();
  749. };
  750. // V2.0:获取「退出早期共创社区」选项(登录页回显)
  751. export const getCommunityChoice = async (userId: string): Promise<{ success: boolean; data: { opted_out?: boolean } }> => {
  752. const apiBaseUrl = getApiBaseUrl();
  753. const response = await fetch(`${apiBaseUrl}/api/users/${userId}/community-choice`, {
  754. method: 'GET',
  755. headers: getApiHeaders(),
  756. });
  757. if (!response.ok) throw await parseApiError(response, 'SERVER_ERROR');
  758. return response.json();
  759. };
  760. // V2.0:更新「退出早期共创社区」选项
  761. export const updateCommunityChoice = async (userId: string, optedOut: boolean): Promise<{ success: boolean }> => {
  762. const apiBaseUrl = getApiBaseUrl();
  763. const response = await fetch(`${apiBaseUrl}/api/users/${userId}/community-choice`, {
  764. method: 'PUT',
  765. headers: getApiHeaders(),
  766. body: JSON.stringify({ opted_out: optedOut }),
  767. });
  768. if (!response.ok) throw await parseApiError(response, 'SERVER_ERROR');
  769. return response.json();
  770. };
  771. // V2.0:获取早期共创状态
  772. export const getEarlyCommunity = async (userId: string): Promise<{ success: boolean; data: { popup_shown?: boolean; email?: string | null } }> => {
  773. const apiBaseUrl = getApiBaseUrl();
  774. const response = await fetch(`${apiBaseUrl}/api/users/${userId}/early-community`, {
  775. method: 'GET',
  776. headers: getApiHeaders(),
  777. });
  778. if (!response.ok) throw await parseApiError(response, 'SERVER_ERROR');
  779. return response.json();
  780. };
  781. // V2.0:提交早期共创(标记弹窗已展示,可选留邮箱)
  782. export const submitEarlyCommunity = async (userId: string, email?: string | null): Promise<{ success: boolean; data: Record<string, unknown> }> => {
  783. const apiBaseUrl = getApiBaseUrl();
  784. const response = await fetch(`${apiBaseUrl}/api/users/${userId}/early-community`, {
  785. method: 'POST',
  786. headers: getApiHeaders(),
  787. body: JSON.stringify({ email: email || undefined }),
  788. });
  789. if (!response.ok) throw await parseApiError(response, 'SERVER_ERROR');
  790. return response.json();
  791. };
  792. /**
  793. * OAuth 授权相关接口
  794. */
  795. // 获取微信授权URL
  796. export const getWechatAuthUrl = (): string => {
  797. const apiBaseUrl = getApiBaseUrl();
  798. return `${apiBaseUrl}/api/auth/wechat/authorize`;
  799. };
  800. // 获取QQ授权URL
  801. export const getQQAuthUrl = (from?: string, user_id?: string | null): string => {
  802. const apiBaseUrl = getApiBaseUrl();
  803. const url = `${apiBaseUrl}/api/auth/qq/authorize`;
  804. const params = new URLSearchParams();
  805. if (from) {
  806. params.append('from', from);
  807. }
  808. if (user_id) {
  809. params.append('user_id', user_id);
  810. }
  811. const queryString = params.toString();
  812. return queryString ? `${url}?${queryString}` : url;
  813. };
  814. /**
  815. * 头像 GIF 配置
  816. */
  817. export interface AvatarGifSet {
  818. default: string;
  819. positive: string;
  820. negative: string;
  821. talking: string;
  822. }
  823. export interface AvatarGifConfigResponse {
  824. success: boolean;
  825. data: {
  826. avatar_default?: Partial<AvatarGifSet>;
  827. avatar_registered_cap?: Partial<AvatarGifSet>;
  828. };
  829. }
  830. export const getAvatarGifs = async (): Promise<AvatarGifConfigResponse> => {
  831. const apiBaseUrl = getApiBaseUrl();
  832. const response = await fetch(`${apiBaseUrl}/api/avatar-gifs`, {
  833. method: 'GET',
  834. headers: getApiHeaders(),
  835. });
  836. if (!response.ok) {
  837. throw await parseApiError(response, 'GET_AVATARS_FAILED');
  838. }
  839. return response.json();
  840. };
  841. /**
  842. * 分享图片
  843. */
  844. export interface ShareImageItem {
  845. id: string;
  846. url: string;
  847. title?: string;
  848. sort_order?: number;
  849. is_active?: boolean;
  850. }
  851. export interface GetShareImagesResponse {
  852. success: boolean;
  853. data: ShareImageItem[];
  854. }
  855. export const getShareImages = async (): Promise<GetShareImagesResponse> => {
  856. const apiBaseUrl = getApiBaseUrl();
  857. const response = await fetch(`${apiBaseUrl}/api/share-images`, {
  858. method: 'GET',
  859. headers: getApiHeaders(),
  860. });
  861. if (!response.ok) {
  862. throw await parseApiError(response, 'GET_CONFIG_FAILED');
  863. }
  864. return response.json();
  865. };
  866. /**
  867. * 领取分享奖励
  868. */
  869. export interface ClaimShareRewardResponse {
  870. success: boolean;
  871. data?: {
  872. user_id: string;
  873. background_image_id: string;
  874. background_image_metadata?: Record<string, any>;
  875. message: string;
  876. };
  877. message?: string;
  878. }
  879. export const claimShareReward = async (user_id: string): Promise<ClaimShareRewardResponse> => {
  880. const apiBaseUrl = getApiBaseUrl();
  881. const response = await fetch(`${apiBaseUrl}/api/users/${user_id}/claim-share-reward`, {
  882. method: 'POST',
  883. headers: getApiHeaders(),
  884. });
  885. if (!response.ok) {
  886. throw await parseApiError(response, 'CLAIM_SHARE_REWARD_FAILED');
  887. }
  888. const data = await response.json();
  889. // 如果成功,同步背景图片到 localStorage
  890. if (data.success && data.data?.background_image_id) {
  891. const { syncBackgroundImageToStorage } = await import('./storage');
  892. syncBackgroundImageToStorage(
  893. data.data.background_image_id,
  894. data.data.background_image_metadata || { opacity: 0.5 } // 使用后端返回的metadata,或默认透明度
  895. );
  896. }
  897. return data;
  898. };
  899. /**
  900. * 获取所有背景图片配置
  901. */
  902. export interface BackgroundImageConfig {
  903. image_id: string;
  904. image_name: string;
  905. image_url: string;
  906. thumbnail_url?: string;
  907. unlock_type: 'default' | 'level' | 'purchase' | 'mission';
  908. unlock_level?: number;
  909. unlock_mission_type?: string;
  910. display_order: number;
  911. is_active: boolean;
  912. description?: string;
  913. metadata?: Record<string, any>;
  914. created_at?: string;
  915. updated_at?: string;
  916. }
  917. export interface GetBackgroundImagesResponse {
  918. success: boolean;
  919. data: BackgroundImageConfig[];
  920. }
  921. export const getBackgroundImages = async (): Promise<GetBackgroundImagesResponse> => {
  922. const apiBaseUrl = getApiBaseUrl();
  923. const response = await fetch(`${apiBaseUrl}/api/background-images`, {
  924. method: 'GET',
  925. headers: getApiHeaders(),
  926. });
  927. if (!response.ok) {
  928. throw await parseApiError(response, 'GET_BG_CONFIG_FAILED');
  929. }
  930. return response.json();
  931. };