starmusic-mobile
1/**
2 * 账号与云同步模块
3 *
4 * 服务端:官网/account.php(SQLite,见 inc.db.php / admin.php)
5 * 能力:注册(算术验证码 + IP 频控防批量注册)/ 登录 / 修改密码 /
6 * 歌单与自定义音源备份到云端 / 换机后从云端恢复
7 *
8 * 备份/恢复数据整体 base64 编码传输(请求与响应均是):
9 * 备份内容含音源脚本的 JS 代码,明文会被服务器 WAF 误判为攻击代码而拦截。
10 *
11 * 登录态:token 存本地(STORAGE_KEYS.USER_TOKEN),服务端单 token,
12 * 新设备登录会使旧设备 token 失效(code=2 时自动清理本地登录态)。
13 *
14 * 页面通过监听 accountChanged 事件感知登录态变化:
15 * - 事件参数为 null:已退出登录 / 登录失效
16 * - 事件参数为 { username }:已登录
17 */
18import event from './event.js'
19import { ACCOUNT_API, STORAGE_KEYS } from './constants.js'
20import { updateSetting } from './setting.js'
21import {
22 getData,
23 saveData,
24 removeData,
25 getSetting,
26 getUserApiList,
27 getUserApiScript,
28 addUserApi,
29} from './data.js'
30import {
31 addListMusics,
32 getList,
33 LIST_IDS,
34 getCustomLists,
35 createCustomList,
36 normalizeMusicInfo,
37} from './playlist.js'
38import { setApiSource } from './api-source.js'
39
40// ============ Base64 编解码(UTF-8 安全,纯 JS 实现,兼容 H5 / App) ============
41
42const B64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
43
44/** 字符串 → UTF-8 字节数组 */
45const strToUtf8Bytes = (str) => {
46 const bytes = []
47 for (let i = 0; i < str.length; i++) {
48 let code = str.charCodeAt(i)
49 // 代理对(emoji 等)合并为完整码点
50 if (code >= 0xd800 && code <= 0xdbff && i + 1 < str.length) {
51 const next = str.charCodeAt(i + 1)
52 if (next >= 0xdc00 && next <= 0xdfff) {
53 code = 0x10000 + ((code - 0xd800) << 10) + (next - 0xdc00)
54 i++
55 }
56 }
57 if (code < 0x80) {
58 bytes.push(code)
59 } else if (code < 0x800) {
60 bytes.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f))
61 } else if (code < 0x10000) {
62 bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f))
63 } else {
64 bytes.push(
65 0xf0 | (code >> 18),
66 0x80 | ((code >> 12) & 0x3f),
67 0x80 | ((code >> 6) & 0x3f),
68 0x80 | (code & 0x3f),
69 )
70 }
71 }
72 return bytes
73}
74
75/** UTF-8 字节数组 → 字符串 */
76const utf8BytesToStr = (bytes) => {
77 let out = ''
78 let i = 0
79 while (i < bytes.length) {
80 const b = bytes[i]
81 if (b < 0x80) {
82 out += String.fromCharCode(b)
83 i += 1
84 } else if (b < 0xe0) {
85 out += String.fromCharCode(((b & 0x1f) << 6) | (bytes[i + 1] & 0x3f))
86 i += 2
87 } else if (b < 0xf0) {
88 out += String.fromCharCode(((b & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f))
89 i += 3
90 } else {
91 // 四字节:还原为代理对
92 const cp = ((b & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f)
93 const offset = cp - 0x10000
94 out += String.fromCharCode(0xd800 + (offset >> 10), 0xdc00 + (offset & 0x3ff))
95 i += 4
96 }
97 }
98 return out
99}
100
101/** 字符串 → base64 */
102const utf8ToBase64 = (str) => {
103 const bytes = strToUtf8Bytes(str)
104 let out = ''
105 for (let i = 0; i < bytes.length; i += 3) {
106 const b1 = bytes[i]
107 const b2 = bytes[i + 1]
108 const b3 = bytes[i + 2]
109 out += B64_CHARS[b1 >> 2]
110 out += B64_CHARS[((b1 & 3) << 4) | (b2 === undefined ? 0 : b2 >> 4)]
111 out += b2 === undefined ? '=' : B64_CHARS[((b2 & 15) << 2) | (b3 === undefined ? 0 : b3 >> 6)]
112 out += b3 === undefined ? '=' : B64_CHARS[b3 & 63]
113 }
114 return out
115}
116
117/** base64 → 字符串 */
118const base64ToUtf8 = (str) => {
119 const clean = String(str).replace(/[^A-Za-z0-9+/]/g, '')
120 const bytes = []
121 let acc = 0
122 let bits = 0
123 for (const c of clean) {
124 const v = B64_CHARS.indexOf(c)
125 if (v < 0) continue
126 acc = (acc << 6) | v
127 bits += 6
128 if (bits >= 8) {
129 bits -= 8
130 bytes.push((acc >> bits) & 0xff)
131 }
132 }
133 return utf8BytesToStr(bytes)
134}
135
136// ============ 登录态(本地) ============
137
138/** 读取登录 token */
139export const getToken = () => getData(STORAGE_KEYS.USER_TOKEN, '')
140
141/** 读取本地账号信息 { username, user_id, created_at, sync_time, has_backup } */
142export const getLocalAccount = () => getData(STORAGE_KEYS.USER_INFO, null)
143
144/** 是否已登录 */
145export const isLoggedIn = () => !!getToken()
146
147/** 保存登录态(登录/注册成功后调用) */
148const saveLogin = (data) => {
149 saveData(STORAGE_KEYS.USER_TOKEN, data.token)
150 saveData(STORAGE_KEYS.USER_INFO, { username: data.username, user_id: data.user_id })
151 event.emit('accountChanged', { username: data.username })
152}
153
154/** 清除本地登录态并广播 */
155const clearLogin = () => {
156 removeData(STORAGE_KEYS.USER_TOKEN)
157 removeData(STORAGE_KEYS.USER_INFO)
158 event.emit('accountChanged', null)
159}
160
161// ============ 请求 ============
162
163/**
164 * 通用请求(POST JSON)
165 * @param {string} action 接口名
166 * @param {object} data 业务参数
167 * @param {object} [options] { auth: 携带 token, timeout }
168 * @returns {Promise<object>} data 字段
169 */
170const request = (action, data = {}, { auth = false, timeout = 15000 } = {}) =>
171 new Promise((resolve, reject) => {
172 if (auth && !getToken()) {
173 reject(new Error('请先登录'))
174 return
175 }
176 uni.request({
177 url: `${ACCOUNT_API}?action=${action}`,
178 method: 'POST',
179 header: { 'Content-Type': 'application/json' },
180 data: auth ? { ...data, token: getToken() } : data,
181 timeout,
182 success: (res) => {
183 // WAF 拦截通常返回 403/406 + HTML 页面
184 if (res.statusCode === 403 || res.statusCode === 406) {
185 reject(new Error('请求被服务器防火墙拦截,请联系管理员将接口加入白名单'))
186 return
187 }
188 const body = res.data
189 if (!body || typeof body.code !== 'number') {
190 reject(new Error('服务响应异常,请稍后重试'))
191 return
192 }
193 if (body.code === 0) {
194 resolve(body.data || {})
195 return
196 }
197 if (body.code === 2) {
198 // 登录失效:清理本地登录态,页面通过 accountChanged 事件感知
199 clearLogin()
200 }
201 reject(new Error(body.msg || '操作失败'))
202 },
203 fail: () => reject(new Error('网络连接失败,请检查网络')),
204 })
205 })
206
207// ============ 账号操作 ============
208
209/** 获取注册验证码(算术题,如 "3 + 5 = ?") */
210export const getCaptcha = () => request('captcha')
211
212/** 注册(成功后自动登录) */
213export const register = ({ username, password, captchaId, captchaAnswer }) =>
214 request('register', {
215 username,
216 password,
217 captcha_id: captchaId,
218 captcha_answer: String(captchaAnswer),
219 }).then((data) => {
220 saveLogin(data)
221 return data
222 })
223
224/** 登录 */
225export const login = ({ username, password }) =>
226 request('login', { username, password }).then((data) => {
227 saveLogin(data)
228 return data
229 })
230
231/** 退出登录(服务端失效 token + 本地清理;网络失败不阻塞本地退出) */
232export const logout = async () => {
233 try {
234 await request('logout', {}, { auth: true })
235 } catch (e) {}
236 clearLogin()
237}
238
239/** 拉取账号信息(含最近备份时间),并更新本地缓存 */
240export const fetchProfile = () =>
241 request('profile', {}, { auth: true }).then((data) => {
242 saveData(STORAGE_KEYS.USER_INFO, {
243 username: data.username,
244 user_id: data.user_id,
245 created_at: data.created_at,
246 sync_time: data.sync_time,
247 has_backup: data.has_backup,
248 })
249 return data
250 })
251
252/** 修改密码(成功后更新本地 token,当前设备保持登录) */
253export const changePassword = ({ oldPassword, newPassword }) =>
254 request(
255 'change_password',
256 { old_password: oldPassword, new_password: newPassword },
257 { auth: true },
258 ).then((data) => {
259 if (data.token) saveData(STORAGE_KEYS.USER_TOKEN, data.token)
260 return data
261 })
262
263// ============ 云同步 ============
264
265/** 收集本地待备份的数据(收藏/试听/自建歌单 + 自定义音源脚本) */
266export const buildBackupData = () => {
267 const playlist = {
268 love: getList(LIST_IDS.LOVE),
269 default: getList(LIST_IDS.DEFAULT),
270 // 自建歌单:按“名称 + 歌曲列表”备份,恢复时不依赖本地 id
271 custom: getCustomLists().map((info) => ({ name: info.name, songs: getList(info.id) })),
272 }
273 const currentApiId = getSetting()['common.apiSource']
274 const sources = []
275 let currentApiName = ''
276 for (const api of getUserApiList()) {
277 const script = getUserApiScript(api.id)
278 if (!script) continue
279 sources.push({
280 name: api.name,
281 author: api.author || '',
282 version: api.version || '',
283 description: api.description || '',
284 script,
285 })
286 if (api.id === currentApiId) currentApiName = api.name
287 }
288 return { version: 1, playlist, sources, currentApiName }
289}
290
291/**
292 * 备份本地数据到云端(覆盖云端旧备份)
293 * 备份数据整体 base64 编码后传输:内容含音源脚本的 JS 代码,
294 * 明文会被服务器 WAF 误判为攻击代码而拦截
295 * @returns {Promise<{playlistCount:number, sourcesCount:number}>}
296 */
297export const backupToCloud = async () => {
298 const payload = buildBackupData()
299 const encoded = utf8ToBase64(JSON.stringify(payload))
300 await request('backup', { data: encoded }, { auth: true, timeout: 30000 })
301 await fetchProfile()
302 const customCount = payload.playlist.custom.reduce((sum, item) => sum + item.songs.length, 0)
303 return {
304 playlistCount: payload.playlist.love.length + payload.playlist.default.length + customCount,
305 sourcesCount: payload.sources.length,
306 }
307}
308
309/**
310 * 从云端恢复数据到本地
311 * - 歌单按 id 去重合并进收藏/试听列表(不删除本地已有数据)
312 * - 自建歌单按名称匹配:同名合并,否则新建后再合并
313 * - 音源按脚本内容去重导入,本机已有的跳过
314 * - 自动恢复备份时启用的音源
315 * @returns {Promise<{loveCount:number, defaultCount:number, sourceCount:number, customCount:number}>}
316 */
317export const restoreFromCloud = async () => {
318 const res = await request('restore', {}, { auth: true, timeout: 30000 })
319 // 新协议:base64 编码返回;兼容旧协议明文对象
320 const data = typeof res.data === 'string' ? JSON.parse(base64ToUtf8(res.data)) : res
321 let loveCount = 0
322 let defaultCount = 0
323 let sourceCount = 0
324
325 // 歌单:只插入云端独有的歌(保序合并),不再把云端整段重排到本地前面。
326 // 早期实现是 'top' 插入整段云端列表,本地原有收藏会被整体挤到末尾,
327 // 用户看到的就是"恢复一次收藏顺序全乱"。
328 const playlist = data.playlist || {}
329 const mergeListMusics = (listId, cloudList, location) => {
330 if (!Array.isArray(cloudList) || !cloudList.length) return 0
331 const existIds = new Set(getList(listId).map((m) => m.id))
332 const missing = []
333 const added = new Set()
334 for (const item of cloudList) {
335 const info = normalizeMusicInfo(item)
336 if (!info.id || existIds.has(info.id) || added.has(info.id)) continue
337 added.add(info.id)
338 missing.push(info)
339 }
340 if (!missing.length) return 0
341 addListMusics(listId, missing, location)
342 return missing.length
343 }
344 // 收藏:追加到末尾,用户整理过的顺序保持不变
345 loveCount = mergeListMusics(LIST_IDS.LOVE, playlist.love, 'bottom')
346 // 试听:新歌在前更符合"最近试听"的语义;且该列表有 100 首上限、截断从尾部开始,
347 // 追加到末尾会被直接截掉,插到头部才不会丢
348 defaultCount = mergeListMusics(LIST_IDS.DEFAULT, playlist.default, 'top')
349
350 // 自建歌单:同名歌单合并进已有歌单,否则新建后再合并
351 let customCount = 0
352 const customLists = Array.isArray(playlist.custom) ? playlist.custom : []
353 for (const item of customLists) {
354 if (!item || !Array.isArray(item.songs) || !item.songs.length) continue
355 try {
356 const exist = getCustomLists().find((info) => info.name === item.name)
357 const target = exist || createCustomList(item.name || '恢复的歌单')
358 addListMusics(target.id, item.songs, 'bottom')
359 customCount += item.songs.length
360 } catch (err) {
361 console.log('[restore] 恢复自建歌单失败', err.message)
362 }
363 }
364
365 // 音源:按脚本内容去重导入
366 const sources = Array.isArray(data.sources) ? data.sources : []
367 if (sources.length) {
368 const localScripts = new Set(getUserApiList().map((api) => getUserApiScript(api.id)))
369 for (const source of sources) {
370 if (!source || !source.script || localScripts.has(source.script)) continue
371 try {
372 addUserApi(source.script)
373 localScripts.add(source.script)
374 sourceCount++
375 } catch (err) {
376 console.log('[restore] 导入音源失败', err.message)
377 }
378 }
379 // 恢复备份时启用的音源(新旧设备源 id 不同,按名称匹配)
380 if (data.currentApiName) {
381 const target = getUserApiList().find((api) => api.name === data.currentApiName)
382 if (target) setApiSource(target.id)
383 }
384 }
385 return { loveCount, defaultCount, sourceCount, customCount }
386}
387
388// ============ 自动备份 ============
389
390/** 自动备份防抖时长:连续变更合并为一次上传 */
391const AUTO_BACKUP_DEBOUNCE = 3000
392/** 两次自动备份的最小间隔:边听歌边增长试听列表时不至于频繁上传 */
393const AUTO_BACKUP_MIN_INTERVAL = 30000
394
395let autoBackupTimer = null
396let autoBackupRunning = false
397let autoBackupInited = false
398let lastAutoBackupAt = 0
399
400/** 自动备份是否已开启 */
401export const isAutoBackupEnabled = () => !!getSetting()['account.autoBackup']
402
403/**
404 * 安排一次自动备份
405 * 防抖(合并短时间内的连续变更)+ 最小间隔(限制上传频率);
406 * 未开启或未登录时不产生任何请求。
407 */
408const scheduleAutoBackup = () => {
409 if (!isAutoBackupEnabled() || !isLoggedIn()) return
410 if (autoBackupTimer) clearTimeout(autoBackupTimer)
411 const sinceLast = Date.now() - lastAutoBackupAt
412 const wait = Math.max(AUTO_BACKUP_DEBOUNCE, AUTO_BACKUP_MIN_INTERVAL - sinceLast)
413 autoBackupTimer = setTimeout(runAutoBackup, wait)
414}
415
416/** 本地快照是否为空(没有任何歌单内容与自定义音源) */
417const isBackupEmpty = () => {
418 const customSongs = getCustomLists().reduce((sum, info) => sum + getList(info.id).length, 0)
419 return (
420 getList(LIST_IDS.LOVE).length === 0 &&
421 getList(LIST_IDS.DEFAULT).length === 0 &&
422 customSongs === 0 &&
423 getUserApiList().length === 0
424 )
425}
426
427/** 执行自动备份:静默进行,失败只记录日志并广播结果,不打断用户操作 */
428const runAutoBackup = async () => {
429 autoBackupTimer = null
430 if (autoBackupRunning || !isAutoBackupEnabled() || !isLoggedIn()) return
431 autoBackupRunning = true
432 try {
433 // 空快照守卫:换机 / 清空数据后本地为空,此时自动上传会把云端备份覆盖成空,
434 // 之后就再也没东西可恢复。手动备份不走这里(那是用户明确要求的覆盖操作)。
435 if (isBackupEmpty()) {
436 console.log('[autoBackup] 本地没有可备份的数据,跳过上传以免覆盖云端备份')
437 return
438 }
439 await backupToCloud()
440 lastAutoBackupAt = Date.now()
441 event.emit('autoBackupDone', true)
442 } catch (err) {
443 console.log('[autoBackup]', err && err.message)
444 event.emit('autoBackupDone', false)
445 } finally {
446 autoBackupRunning = false
447 }
448}
449
450/**
451 * 开关自动备份;开启时立即安排一次备份,让用户马上得到云端快照
452 * @param {boolean} enable
453 */
454export const setAutoBackup = (enable) => {
455 updateSetting({ 'account.autoBackup': !!enable })
456 if (enable) scheduleAutoBackup()
457}
458
459/**
460 * 初始化自动备份:注册歌单与音源变更监听(应用启动时调用一次)
461 * - 歌单变化:listUpdated(增删歌曲 / 清空)、customListUpdated(新建 / 重命名 / 删除)
462 * - 音源变化:apiSourceUpdated(切换当前源)、userApiUpdated(导入 / 删除源脚本)
463 */
464export const initAutoBackup = () => {
465 if (autoBackupInited) return
466 autoBackupInited = true
467 event.on('listUpdated', scheduleAutoBackup)
468 event.on('customListUpdated', scheduleAutoBackup)
469 event.on('apiSourceUpdated', scheduleAutoBackup)
470 event.on('userApiUpdated', scheduleAutoBackup)
471}