仰望星辰工作室

starmusic-pc

1/**
2 * 咪咕音乐 (mg) 歌单导入
3 *
4 * 迁移自 lx-music-mobile/src/utils/musicSdk/mg/songList.js + musicInfo.js(精简)
5 * 接口(明文,需 UA/Referer 头):
6 * - 歌单歌曲:https://app.c.nf.migu.cn/MIGUM3.0/resource/playlist/song/v2.0?playlistId=xxx
7 * - 歌单信息:https://c.musicapp.migu.cn/MIGUM3.0/resource/playlist/v2.0?playlistId=xxx
8 * 支持:
9 * - https://music.migu.cn/v5/#/playlist?playlistId=xxx
10 * - https://h5.nf.migu.cn/app/v4/p/share/playlist/index.html?id=xxx
11 * - https://music.migu.cn/v3/music/playlist/xxx
12 * - 短链接(c.migu.cn 等):跟随跳转后解析
13 */
14import { httpFetch } from '../request.js'
15import { formatPlayTime, sizeFormate } from '../../utils.js'
16
17const SUCCESS_CODE = '000000'
18const LIMIT_SONG = 30
19
20const defaultHeaders = {
21 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
22 Referer: 'https://m.music.migu.cn/',
23}
24
25const regExps = {
26 // https://music.migu.cn/v3/music/playlist/161044573?page=1
27 listDetailLink: /^.+\/playlist\/(\d+)(?:\?.*|&.*$|#.*$|$)/,
28}
29
30/** 短链接 → 跟随跳转拿真实地址 */
31const getDetailUrl = (link, retryNum = 0) => {
32 if (retryNum > 3) return Promise.reject(new Error('link try max num'))
33 return httpFetch(link, { headers: defaultHeaders }).promise.then(({ url: location, statusCode }) => {
34 if (statusCode > 400) return getDetailUrl(link, retryNum + 1)
35 if (location.split('?')[0] != link.split('?')[0]) return location
36 return Promise.reject(new Error('link get failed'))
37 })
38}
39
40/** 解析歌单链接 → 歌单 id(含短链接跟随) */
41const getListId = async (id) => {
42 if (/\/playlist[/?]/.test(id)) {
43 const m = /(?:playlistId|id)=(\d+)/.exec(id)
44 if (!m) throw new Error('list detail id parse failed')
45 id = m[1]
46 } else if (regExps.listDetailLink.test(id)) {
47 id = id.replace(regExps.listDetailLink, '$1')
48 } else if (/[?&:/]/.test(id)) {
49 // 短链接:跟随跳转后递归解析
50 const url = await getDetailUrl(id)
51 return getListId(url)
52 }
53 return id
54}
55
56/**
57 * 获取歌单歌曲列表(分页拉取全部)
58 * 咪咕接口一次最多 30 首,需按 totalCount 循环翻页
59 */
60const getListDetailList = async (id, page = 1, total = null, accList = [], tryNum = 0) => {
61 if (tryNum > 2) return Promise.reject(new Error('try max num'))
62 const { body } = await httpFetch(
63 `https://app.c.nf.migu.cn/MIGUM3.0/resource/playlist/song/v2.0?pageNo=${page}&pageSize=${LIMIT_SONG}&playlistId=${id}`,
64 { headers: defaultHeaders },
65 ).promise
66 if (body.code !== SUCCESS_CODE) return getListDetailList(id, page, total, accList, tryNum + 1)
67
68 const songList = body.data.songList || []
69 const allList = accList.concat(filterMusicInfoListV5(songList))
70 const totalCount = total != null ? total : body.data.totalCount
71
72 // 还有更多 → 继续翻页(最多 100 页 = 3000 首,防止异常接口死循环)
73 if (allList.length < totalCount && page < 100) {
74 return getListDetailList(id, page + 1, totalCount, allList, 0)
75 }
76 return { list: allList, total: totalCount, source: 'mg' }
77}
78
79/** 获取歌单信息 */
80const getListDetailInfo = (id, tryNum = 0) => {
81 if (tryNum > 2) return Promise.reject(new Error('try max num'))
82 return httpFetch(`https://c.musicapp.migu.cn/MIGUM3.0/resource/playlist/v2.0?playlistId=${id}`, {
83 headers: defaultHeaders,
84 }).promise.then(({ body }) => {
85 if (body.code !== SUCCESS_CODE) return getListDetailInfo(id, tryNum + 1)
86 return {
87 name: body.data.title,
88 img: body.data.imgItem && body.data.imgItem.img,
89 desc: body.data.summary,
90 author: body.data.ownerName,
91 play_count: body.data.opNumItem && body.data.opNumItem.playNum,
92 }
93 })
94}
95
96/** 歌手数组 → "、" 拼接 */
97const formatSingerName = (singers) => (singers || []).map((s) => s.name).join('、')
98
99/** 咪咕歌曲格式化(v5 结构:audioFormats / singerList) */
100const filterMusicInfoListV5 = (rawList) => {
101 const ids = new Set()
102 const list = []
103 rawList.forEach((item) => {
104 if (!item.songId || ids.has(item.songId)) return
105 ids.add(item.songId)
106 const types = []
107 const _types = {}
108 ;(item.audioFormats || []).forEach((type) => {
109 const size = sizeFormate(type.size ?? type.androidSize)
110 switch (type.formatType) {
111 case 'PQ':
112 types.push({ type: '128k', size })
113 _types['128k'] = { size }
114 break
115 case 'HQ':
116 types.push({ type: '320k', size })
117 _types['320k'] = { size }
118 break
119 case 'SQ':
120 types.push({ type: 'flac', size })
121 _types.flac = { size }
122 break
123 case 'ZQ':
124 types.push({ type: 'flac24bit', size })
125 _types.flac24bit = { size }
126 break
127 }
128 })
129 list.push({
130 singer: formatSingerName(item.singerList),
131 name: item.songName,
132 albumName: item.album,
133 albumId: item.albumId,
134 songmid: item.songId,
135 copyrightId: item.copyrightId,
136 source: 'mg',
137 interval: formatPlayTime(item.duration || 0),
138 img: item.img3 || item.img2 || item.img1 || null,
139 lrc: null,
140 lrcUrl: item.lrcUrl,
141 mrcUrl: item.mrcUrl,
142 trcUrl: item.trcUrl,
143 otherSource: null,
144 types,
145 _types,
146 typeUrl: {},
147 })
148 })
149 return list
150}
151
152export default {
153 /** 获取歌单内歌曲列表 */
154 async getListDetail(rawId) {
155 const id = await getListId(rawId)
156
157 const [listData, info] = await Promise.all([
158 getListDetailList(id),
159 getListDetailInfo(id),
160 ])
161
162 return {
163 list: listData.list,
164 page: 1,
165 limit: LIMIT_SONG,
166 total: listData.total,
167 source: 'mg',
168 info,
169 }
170 },
171}