仰望星辰工作室

starmusic-mobile

starmusic-mobile/ common/share.js 3.3 KB · 91 行 原始文件
1/**
2 * 歌曲分享模块(与 PC 端 pc/frontend/src/common/share.js 保持同构)
3 *
4 * 服务端:官网/share.php + /s/{code} 分享播放页
5 * 能力:把当前播放的歌曲解析成一条新鲜播放直链提交到云端,
6 * 生成短码分享链接(扫码打开网页在线播放,音频由服务端代理)。
7 *
8 * 鉴权:与 account.php 共用 token 登录态(需登录才能分享);
9 * code=2 登录失效时与 account.js 一致:清理本地登录态并广播 accountChanged。
10 */
11import event from './event.js'
12import { SHARE_API, STORAGE_KEYS } from './constants.js'
13import { getToken } from './account.js'
14import { removeData } from './data.js'
15
16/** 分享接口请求(POST JSON,{code,msg,data} 协议与 account.php 一致) */
17const request = (action, data = {}, { timeout = 15000 } = {}) =>
18 new Promise((resolve, reject) => {
19 if (!getToken()) {
20 reject(new Error('请先登录后再分享'))
21 return
22 }
23 uni.request({
24 url: `${SHARE_API}?action=${action}`,
25 method: 'POST',
26 header: { 'Content-Type': 'application/json' },
27 data: { ...data, token: getToken() },
28 timeout,
29 success: (res) => {
30 if (res.statusCode === 403 || res.statusCode === 406) {
31 reject(new Error('请求被服务器防火墙拦截,请联系管理员'))
32 return
33 }
34 const body = res.data
35 if (!body || typeof body.code !== 'number') {
36 reject(new Error('服务响应异常,请稍后重试'))
37 return
38 }
39 if (body.code === 0) {
40 resolve(body.data || {})
41 return
42 }
43 if (body.code === 2) {
44 // 登录失效:与 account.js 同步清理并广播
45 removeData(STORAGE_KEYS.USER_TOKEN)
46 removeData(STORAGE_KEYS.USER_INFO)
47 event.emit('accountChanged', null)
48 }
49 reject(new Error(body.msg || '操作失败'))
50 },
51 fail: () => reject(new Error('网络连接失败,请检查网络')),
52 })
53 })
54
55/**
56 * 创建分享
57 * @param {object} p
58 * @param {object} p.musicInfo 当前歌曲(name/singer/albumName/interval/source/songmid|id)
59 * @param {string} p.quality 本次分享的音质
60 * @param {string} p.playUrl 客户端已解析好的新鲜播放直链
61 * @param {string} [p.coverUrl] 封面地址(服务端会缓存到本地)
62 * @returns {Promise<{shareCode:string, shareUrl:string, expireAt:number}>}
63 */
64export const createShare = async ({ musicInfo, quality, playUrl, coverUrl }) => {
65 const data = await request('create', {
66 name: musicInfo.name || '',
67 singer: musicInfo.singer || '',
68 album: musicInfo.albumName || musicInfo.album || '',
69 interval: musicInfo.interval || '',
70 source: musicInfo.source || '',
71 sourceId: String(musicInfo.songmid || musicInfo.id || ''),
72 quality: quality || '',
73 coverUrl: coverUrl || '',
74 playUrl: playUrl || '',
75 })
76 return {
77 shareCode: data.share_code || '',
78 shareUrl: data.share_url || '',
79 expireAt: data.expire_at || 0,
80 }
81}
82
83/** 我的分享列表(最近 50 条) */
84export const getMyShares = () =>
85 request('mine').then((data) => ({
86 total: data.total || 0,
87 list: data.list || [],
88 }))
89
90/** 删除自己的分享 */
91export const deleteShare = (code) => request('delete', { code })