| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197 |
- /**
- * 平台接口
- * ========
- * Web 版只需要三件东西:登录换 apiKey、补全身份、查积分。
- * 模型清单从统一网关拿(和桌面端 electron/llm.js 同一套 /v1/models)。
- *
- * 一律用 Node 自带 fetch,不引 axios —— 这里没有需要特殊处理的场景,
- * 少一个依赖就少一处供应链风险。
- */
- const CLIENT_ID = 'cocorobo-teacher-web'
- const API_PREFIX = '/agent/v1'
- const str = (...keys) => (obj) => {
- for (const k of keys) {
- const v = obj && obj[k]
- if (typeof v === 'string' && v.trim()) return v.trim()
- if (typeof v === 'number') return String(v)
- }
- return ''
- }
- /** 平台返回有三种包装:{code,data} / {data} / 扁平。统一拆一层。 */
- function unwrap (json) {
- if (json && typeof json === 'object' && json.data && typeof json.data === 'object' && !Array.isArray(json.data)) {
- return json.data
- }
- return json || {}
- }
- async function request (base, pathname, options = {}) {
- const url = `${base.replace(/\/+$/, '')}${pathname}`
- const controller = new AbortController()
- const timer = setTimeout(() => controller.abort(), options.timeoutMs || 20_000)
- timer.unref?.()
- try {
- const res = await fetch(url, {
- method: options.method || 'GET',
- headers: {
- accept: 'application/json',
- ...(options.body ? { 'content-type': 'application/json' } : {}),
- ...(options.headers || {})
- },
- body: options.body ? JSON.stringify(options.body) : undefined,
- signal: controller.signal
- })
- const text = await res.text()
- let json = null
- try { json = text ? JSON.parse(text) : null } catch { /* 非 JSON,下面按原文报错 */ }
- if (!res.ok) {
- const message = (json && (json.message || json.msg || json.error)) || text.slice(0, 200) || `HTTP ${res.status}`
- const err = new Error(String(message))
- err.status = res.status
- throw err
- }
- return json
- } finally {
- clearTimeout(timer)
- }
- }
- /** 平台登录:账号密码 / 短信验证码。返回 apiKey 与身份。 */
- export async function login ({ region, mode, account, password, code, deviceId, clientVersion }) {
- const base = region.platform
- const json = await request(base, `${API_PREFIX}/auth/login`, {
- method: 'POST',
- body: {
- mode: mode === 'sms' ? 'sms' : 'password',
- account,
- password: mode === 'sms' ? undefined : password,
- code: mode === 'sms' ? code : undefined,
- client: {
- id: CLIENT_ID,
- version: clientVersion || '',
- platform: 'web',
- deviceId
- }
- }
- })
- const data = unwrap(json)
- const apiKey = str('apiKey', 'api_key', 'token', 'accessToken', 'access_token', 'key')(data)
- if (!apiKey) throw Object.assign(new Error('登录成功但没有返回 apiKey'), { code: 'missing_api_key' })
- const user = data.user && typeof data.user === 'object' ? data.user : {}
- const id = {
- apiKey,
- userid: str('userid', 'userId')(data) || str('id', 'userid', 'userId')(user),
- username: str('username', 'name', 'nickname')(data) || str('name', 'nickname')(user),
- organizeId: str('organizeId', 'organizeid', 'orgId')(data) || str('orgId', 'organizeId')(user),
- organizeName: str('organizeName', 'orgName', 'schoolName')(data) || str('orgName', 'schoolName')(user),
- region: region.key
- }
- // 平台有时不带 organizeId:用 pbl 的 selectUser 补一次(桌面端同一套兜底)
- if (!id.organizeId && id.userid) {
- const fromPbl = await fetchPblUser(region, id.userid).catch(() => null)
- if (fromPbl) {
- id.organizeId = id.organizeId || fromPbl.organizeId || ''
- id.username = id.username || fromPbl.username || ''
- id.organizeName = id.organizeName || fromPbl.organizeName || ''
- }
- }
- return id
- }
- /** 直接用 apiKey 进来(老师手里已有 key 时不用再登一次) */
- export async function verifyKey ({ region, apiKey }) {
- const tried = []
- // 必须校验到"真实的 userid"。平台对未知路径会 301 到首页并回 200 HTML,
- // 只判 res.ok 会把任意字符串都当成有效 key(等于人人可登录)。
- for (const base of [region.points, region.platform]) {
- for (const pathname of [`${API_PREFIX}/auth/me`, '/api/profile']) {
- try {
- const json = await request(base, pathname, {
- headers: { authorization: `Bearer ${apiKey}` },
- timeoutMs: 10_000
- })
- const data = unwrap(json)
- if (!data || typeof data !== 'object') { tried.push(`${pathname}: 非对象`); continue }
- const user = data.user && typeof data.user === 'object' ? data.user : data
- const userid = str('userid', 'userId', 'id')(user) || str('userid', 'userId', 'id')(data)
- if (!userid) { tried.push(`${pathname}: 没有 userid`); continue }
- return {
- apiKey,
- userid,
- username: str('username', 'name', 'nickname', 'alias')(user) || str('username', 'name')(data),
- organizeId: str('organizeId', 'organizeid', 'orgId', 'orgid')(user) || str('organizeId', 'organizeid', 'orgId')(data),
- organizeName: str('organizeName', 'orgName', 'schoolName', 'defaultSchool')(user) || str('organizeName', 'orgName', 'schoolName')(data),
- region: region.key
- }
- } catch (err) {
- if (err.status === 401 || err.status === 403) {
- throw Object.assign(new Error('apiKey 无效'), { code: 'bad_key' })
- }
- tried.push(`${pathname}: ${err.status || err.message}`)
- }
- }
- }
- throw Object.assign(new Error('平台没有返回可用的用户信息,请用平台登录页登录'), {
- code: 'no_verify',
- detail: tried
- })
- }
- async function fetchPblUser (region, userid) {
- const host = region.platform.replace(/^https?:\/\//, '').replace(/^cloud\./, 'pbl.')
- const json = await request(`https://${host}`, `/api/pbl/selectUser?userid=${encodeURIComponent(userid)}`, {
- timeoutMs: 8000
- })
- const raw = Array.isArray(json) ? json[0] : unwrap(json)
- const list = Array.isArray(raw) ? raw[0] : raw
- const obj = Array.isArray(list) ? list[0] : list
- if (!obj || typeof obj !== 'object') return null
- return {
- userid: str('userid', 'userId')(obj),
- username: str('username', 'name', 'nickname')(obj),
- organizeId: str('organizeid', 'organizeId', 'orgid', 'orgId')(obj),
- organizeName: str('organizeName', 'orgName', 'schoolName')(obj)
- }
- }
- /** 积分用量(右侧积分条的数据源) */
- export async function pointsUsage ({ region, apiKey, userId }) {
- const json = await request(region.points, `/v1/points/usage${userId ? `?userId=${encodeURIComponent(userId)}` : ''}`, {
- headers: { authorization: `Bearer ${apiKey}` },
- timeoutMs: 8000
- })
- return unwrap(json)
- }
- export function pointsPageUrl ({ region, userId, locale }) {
- const params = []
- if (userId) params.push(`userId=${encodeURIComponent(userId)}`)
- params.push('pay=1', `lang=${encodeURIComponent(locale || 'zh-CN')}`)
- return `${region.points}/points?${params.join('&')}`
- }
- /** 网关模型清单。失败的返回不带异常,让调用方决定用默认模型还是报错。 */
- export async function listModels ({ baseURL, apiKey, modelsHint }) {
- const fallback = String(modelsHint || '').split(',').map((s) => s.trim()).filter(Boolean)
- .map((id) => ({ id, name: id }))
- try {
- const res = await fetch(`${baseURL.replace(/\/+$/, '')}/models`, {
- headers: { authorization: `Bearer ${apiKey}` },
- signal: AbortSignal.timeout(12_000)
- })
- if (!res.ok) return { ok: false, models: fallback, message: `HTTP ${res.status}` }
- const json = await res.json()
- const list = Array.isArray(json) ? json : (Array.isArray(json.models) ? json.models : [])
- const models = list
- .map((m) => ({ id: String(m.id || m.model || m.name || ''), name: String(m.name || m.id || '') }))
- .filter((m) => m.id)
- if (!models.length) return { ok: false, models: fallback, message: '模型清单为空' }
- return { ok: true, models }
- } catch (err) {
- return { ok: false, models: fallback, message: err.message }
- }
- }
|