platform.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. /**
  2. * 平台接口
  3. * ========
  4. * Web 版只需要三件东西:登录换 apiKey、补全身份、查积分。
  5. * 模型清单从统一网关拿(和桌面端 electron/llm.js 同一套 /v1/models)。
  6. *
  7. * 一律用 Node 自带 fetch,不引 axios —— 这里没有需要特殊处理的场景,
  8. * 少一个依赖就少一处供应链风险。
  9. */
  10. const CLIENT_ID = 'cocorobo-teacher-web'
  11. const API_PREFIX = '/agent/v1'
  12. const str = (...keys) => (obj) => {
  13. for (const k of keys) {
  14. const v = obj && obj[k]
  15. if (typeof v === 'string' && v.trim()) return v.trim()
  16. if (typeof v === 'number') return String(v)
  17. }
  18. return ''
  19. }
  20. /** 平台返回有三种包装:{code,data} / {data} / 扁平。统一拆一层。 */
  21. function unwrap (json) {
  22. if (json && typeof json === 'object' && json.data && typeof json.data === 'object' && !Array.isArray(json.data)) {
  23. return json.data
  24. }
  25. return json || {}
  26. }
  27. async function request (base, pathname, options = {}) {
  28. const url = `${base.replace(/\/+$/, '')}${pathname}`
  29. const controller = new AbortController()
  30. const timer = setTimeout(() => controller.abort(), options.timeoutMs || 20_000)
  31. timer.unref?.()
  32. try {
  33. const res = await fetch(url, {
  34. method: options.method || 'GET',
  35. headers: {
  36. accept: 'application/json',
  37. ...(options.body ? { 'content-type': 'application/json' } : {}),
  38. ...(options.headers || {})
  39. },
  40. body: options.body ? JSON.stringify(options.body) : undefined,
  41. signal: controller.signal
  42. })
  43. const text = await res.text()
  44. let json = null
  45. try { json = text ? JSON.parse(text) : null } catch { /* 非 JSON,下面按原文报错 */ }
  46. if (!res.ok) {
  47. const message = (json && (json.message || json.msg || json.error)) || text.slice(0, 200) || `HTTP ${res.status}`
  48. const err = new Error(String(message))
  49. err.status = res.status
  50. throw err
  51. }
  52. return json
  53. } finally {
  54. clearTimeout(timer)
  55. }
  56. }
  57. /** 平台登录:账号密码 / 短信验证码。返回 apiKey 与身份。 */
  58. export async function login ({ region, mode, account, password, code, deviceId, clientVersion }) {
  59. const base = region.platform
  60. const json = await request(base, `${API_PREFIX}/auth/login`, {
  61. method: 'POST',
  62. body: {
  63. mode: mode === 'sms' ? 'sms' : 'password',
  64. account,
  65. password: mode === 'sms' ? undefined : password,
  66. code: mode === 'sms' ? code : undefined,
  67. client: {
  68. id: CLIENT_ID,
  69. version: clientVersion || '',
  70. platform: 'web',
  71. deviceId
  72. }
  73. }
  74. })
  75. const data = unwrap(json)
  76. const apiKey = str('apiKey', 'api_key', 'token', 'accessToken', 'access_token', 'key')(data)
  77. if (!apiKey) throw Object.assign(new Error('登录成功但没有返回 apiKey'), { code: 'missing_api_key' })
  78. const user = data.user && typeof data.user === 'object' ? data.user : {}
  79. const id = {
  80. apiKey,
  81. userid: str('userid', 'userId')(data) || str('id', 'userid', 'userId')(user),
  82. username: str('username', 'name', 'nickname')(data) || str('name', 'nickname')(user),
  83. organizeId: str('organizeId', 'organizeid', 'orgId')(data) || str('orgId', 'organizeId')(user),
  84. organizeName: str('organizeName', 'orgName', 'schoolName')(data) || str('orgName', 'schoolName')(user),
  85. region: region.key
  86. }
  87. // 平台有时不带 organizeId:用 pbl 的 selectUser 补一次(桌面端同一套兜底)
  88. if (!id.organizeId && id.userid) {
  89. const fromPbl = await fetchPblUser(region, id.userid).catch(() => null)
  90. if (fromPbl) {
  91. id.organizeId = id.organizeId || fromPbl.organizeId || ''
  92. id.username = id.username || fromPbl.username || ''
  93. id.organizeName = id.organizeName || fromPbl.organizeName || ''
  94. }
  95. }
  96. return id
  97. }
  98. /** 直接用 apiKey 进来(老师手里已有 key 时不用再登一次) */
  99. export async function verifyKey ({ region, apiKey }) {
  100. const tried = []
  101. // 必须校验到"真实的 userid"。平台对未知路径会 301 到首页并回 200 HTML,
  102. // 只判 res.ok 会把任意字符串都当成有效 key(等于人人可登录)。
  103. for (const base of [region.points, region.platform]) {
  104. for (const pathname of [`${API_PREFIX}/auth/me`, '/api/profile']) {
  105. try {
  106. const json = await request(base, pathname, {
  107. headers: { authorization: `Bearer ${apiKey}` },
  108. timeoutMs: 10_000
  109. })
  110. const data = unwrap(json)
  111. if (!data || typeof data !== 'object') { tried.push(`${pathname}: 非对象`); continue }
  112. const user = data.user && typeof data.user === 'object' ? data.user : data
  113. const userid = str('userid', 'userId', 'id')(user) || str('userid', 'userId', 'id')(data)
  114. if (!userid) { tried.push(`${pathname}: 没有 userid`); continue }
  115. return {
  116. apiKey,
  117. userid,
  118. username: str('username', 'name', 'nickname', 'alias')(user) || str('username', 'name')(data),
  119. organizeId: str('organizeId', 'organizeid', 'orgId', 'orgid')(user) || str('organizeId', 'organizeid', 'orgId')(data),
  120. organizeName: str('organizeName', 'orgName', 'schoolName', 'defaultSchool')(user) || str('organizeName', 'orgName', 'schoolName')(data),
  121. region: region.key
  122. }
  123. } catch (err) {
  124. if (err.status === 401 || err.status === 403) {
  125. throw Object.assign(new Error('apiKey 无效'), { code: 'bad_key' })
  126. }
  127. tried.push(`${pathname}: ${err.status || err.message}`)
  128. }
  129. }
  130. }
  131. throw Object.assign(new Error('平台没有返回可用的用户信息,请用平台登录页登录'), {
  132. code: 'no_verify',
  133. detail: tried
  134. })
  135. }
  136. async function fetchPblUser (region, userid) {
  137. const host = region.platform.replace(/^https?:\/\//, '').replace(/^cloud\./, 'pbl.')
  138. const json = await request(`https://${host}`, `/api/pbl/selectUser?userid=${encodeURIComponent(userid)}`, {
  139. timeoutMs: 8000
  140. })
  141. const raw = Array.isArray(json) ? json[0] : unwrap(json)
  142. const list = Array.isArray(raw) ? raw[0] : raw
  143. const obj = Array.isArray(list) ? list[0] : list
  144. if (!obj || typeof obj !== 'object') return null
  145. return {
  146. userid: str('userid', 'userId')(obj),
  147. username: str('username', 'name', 'nickname')(obj),
  148. organizeId: str('organizeid', 'organizeId', 'orgid', 'orgId')(obj),
  149. organizeName: str('organizeName', 'orgName', 'schoolName')(obj)
  150. }
  151. }
  152. /** 积分用量(右侧积分条的数据源) */
  153. export async function pointsUsage ({ region, apiKey, userId }) {
  154. const json = await request(region.points, `/v1/points/usage${userId ? `?userId=${encodeURIComponent(userId)}` : ''}`, {
  155. headers: { authorization: `Bearer ${apiKey}` },
  156. timeoutMs: 8000
  157. })
  158. return unwrap(json)
  159. }
  160. export function pointsPageUrl ({ region, userId, locale }) {
  161. const params = []
  162. if (userId) params.push(`userId=${encodeURIComponent(userId)}`)
  163. params.push('pay=1', `lang=${encodeURIComponent(locale || 'zh-CN')}`)
  164. return `${region.points}/points?${params.join('&')}`
  165. }
  166. /** 网关模型清单。失败的返回不带异常,让调用方决定用默认模型还是报错。 */
  167. export async function listModels ({ baseURL, apiKey, modelsHint }) {
  168. const fallback = String(modelsHint || '').split(',').map((s) => s.trim()).filter(Boolean)
  169. .map((id) => ({ id, name: id }))
  170. try {
  171. const res = await fetch(`${baseURL.replace(/\/+$/, '')}/models`, {
  172. headers: { authorization: `Bearer ${apiKey}` },
  173. signal: AbortSignal.timeout(12_000)
  174. })
  175. if (!res.ok) return { ok: false, models: fallback, message: `HTTP ${res.status}` }
  176. const json = await res.json()
  177. const list = Array.isArray(json) ? json : (Array.isArray(json.models) ? json.models : [])
  178. const models = list
  179. .map((m) => ({ id: String(m.id || m.model || m.name || ''), name: String(m.name || m.id || '') }))
  180. .filter((m) => m.id)
  181. if (!models.length) return { ok: false, models: fallback, message: '模型清单为空' }
  182. return { ok: true, models }
  183. } catch (err) {
  184. return { ok: false, models: fallback, message: err.message }
  185. }
  186. }