starmusic-mobile
1/**
2 * 咪咕音乐 (mg) 源 SDK(迁移自 lx-music-mobile/src/utils/musicSdk/mg)
3 */
4import { httpFetch } from './request.js'
5import { decodeName, formatPlayTime, sizeFormate } from '../utils.js'
6import { md5 } from '../crypto.js'
7
8const createSignature = (time, str) => {
9 const deviceId = '963B7AA0D21511ED807EE5846EC87D20'
10 const signatureMd5 = '6cdc72a439cef99a3418d2a78aa28c73'
11 const sign = md5(`${str}${signatureMd5}yyapp2d16148780a1dcc7408e06336b98cfd50${deviceId}${time}`)
12 return { sign, deviceId }
13}
14
15const formatSingerName = (singers) => {
16 if (Array.isArray(singers)) {
17 return decodeName(singers.map((item) => item.name).join('、'))
18 }
19 return decodeName(String(singers || ''))
20}
21
22const mg = {
23 name: '咪咕音乐',
24 limit: 20,
25 total: 0,
26 page: 0,
27 allPage: 1,
28
29 /** 搜索请求 */
30 musicSearch(str, page, limit) {
31 const time = Date.now().toString()
32 const signData = createSignature(time, str)
33 const searchRequest = httpFetch(
34 `https://jadeite.migu.cn/music_search/v3/search/searchAll?isCorrect=0&isCopyright=1&searchSwitch=%7B%22song%22%3A1%2C%22album%22%3A0%2C%22singer%22%3A0%2C%22tagSong%22%3A1%2C%22mvSong%22%3A0%2C%22bestShow%22%3A1%2C%22songlist%22%3A0%2C%22lyricSong%22%3A0%7D&pageSize=${limit}&text=${encodeURIComponent(str)}&pageNo=${page}&sort=0&sid=USS`,
35 {
36 headers: {
37 uiVersion: 'A_music_3.6.1',
38 deviceId: signData.deviceId,
39 timestamp: time,
40 sign: signData.sign,
41 channel: '0146921',
42 'User-Agent': 'Mozilla/5.0 (Linux; U; Android 11.0.0; zh-cn; MI 11 Build/OPR1.170623.032) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
43 },
44 },
45 )
46 return searchRequest.promise.then(({ body }) => body)
47 },
48
49 /** 过滤搜索结果 */
50 filterData(rawData) {
51 const list = []
52 const ids = new Set()
53
54 rawData.forEach((item) => {
55 item.forEach((data) => {
56 if (!data.songId || !data.copyrightId || ids.has(data.copyrightId)) return
57 ids.add(data.copyrightId)
58
59 const types = []
60 const _types = {}
61 data.audioFormats && data.audioFormats.forEach((type) => {
62 let size
63 switch (type.formatType) {
64 case 'PQ':
65 size = sizeFormate(type.asize ?? type.isize)
66 types.push({ type: '128k', size })
67 _types['128k'] = { size }
68 break
69 case 'HQ':
70 size = sizeFormate(type.asize ?? type.isize)
71 types.push({ type: '320k', size })
72 _types['320k'] = { size }
73 break
74 case 'SQ':
75 size = sizeFormate(type.asize ?? type.isize)
76 types.push({ type: 'flac', size })
77 _types.flac = { size }
78 break
79 case 'ZQ24':
80 size = sizeFormate(type.asize ?? type.isize)
81 types.push({ type: 'flac24bit', size })
82 _types.flac24bit = { size }
83 break
84 }
85 })
86
87 // 注意:判断对象必须是最终取到的 img,而非固定的 img3
88 // (img3 为空时可能回退到 img2/img1,若仍判断 img3 会给完整 URL 错误地再拼一次域名)
89 let img = data.img3 || data.img2 || data.img1 || null
90 if (img && !/^https?:/.test(img)) img = 'http://d.musicapp.migu.cn' + img
91
92 list.push({
93 singer: formatSingerName(data.singerList),
94 name: data.name,
95 albumName: data.album,
96 albumId: data.albumId,
97 songmid: data.songId,
98 copyrightId: data.copyrightId,
99 source: 'mg',
100 interval: formatPlayTime(data.duration),
101 img,
102 lrc: null,
103 lrcUrl: data.lrcUrl,
104 mrcUrl: data.mrcurl,
105 trcUrl: data.trcUrl,
106 types,
107 _types,
108 typeUrl: {},
109 })
110 })
111 })
112 return list
113 },
114
115 /** 搜索 */
116 search(str, page = 1, limit, retryNum = 0) {
117 if (++retryNum > 3) return Promise.reject(new Error('try max num'))
118 if (limit == null) limit = this.limit
119 return this.musicSearch(str, page, limit).then((result) => {
120 if (!result || result.code !== '000000') return Promise.reject(new Error(result ? result.info : '搜索失败'))
121 const songResultData = result.songResultData || { resultList: [], totalCount: 0 }
122
123 const list = this.filterData(songResultData.resultList)
124 if (list == null) return this.search(str, page, limit, retryNum)
125
126 this.total = parseInt(songResultData.totalCount)
127 this.page = page
128 this.allPage = Math.ceil(this.total / limit)
129
130 return {
131 list,
132 allPage: this.allPage,
133 limit,
134 total: this.total,
135 source: 'mg',
136 }
137 })
138 },
139
140 /** 获取封面 */
141 getPic(songInfo) {
142 if (songInfo.img) return Promise.resolve(songInfo.img)
143 return httpFetch(`http://music.migu.cn/v3/api/music/audioPlayer/getSongPic?songId=${songInfo.songmid}`, {
144 headers: {
145 Referer: 'http://music.migu.cn/v3/music/player/audio?from=migu',
146 },
147 }).promise.then(({ body }) => {
148 if (body.returnCode !== '000000') return Promise.reject(new Error('图片获取失败'))
149 let url = body.largePic || body.mediumPic || body.smallPic
150 if (!url) return Promise.reject(new Error('图片获取失败'))
151 if (!/https?:/.test(url)) url = 'http:' + url
152 return url
153 })
154 },
155
156 /**
157 * 获取歌词
158 * 咪咕的搜索结果里直接带 lrcUrl(纯文本 LRC),优先使用;
159 * trcUrl 为翻译歌词,同样是 LRC 格式。
160 */
161 getLyric(songInfo) {
162 const lrcUrl = songInfo.lrcUrl
163 if (!lrcUrl) return Promise.reject(new Error('该歌曲没有歌词地址'))
164
165 const fetchLrc = (url) =>
166 httpFetch(url).promise.then(({ body }) => (typeof body === 'string' ? body : ''))
167
168 return fetchLrc(lrcUrl).then((lyric) => {
169 if (!lyric || !/\[\d{1,2}:\d{1,2}/.test(lyric)) return Promise.reject(new Error('获取歌词失败'))
170 // 翻译歌词是可选项,失败不影响主歌词
171 if (!songInfo.trcUrl) return { lyric: decodeName(lyric), tlyric: '' }
172 return fetchLrc(songInfo.trcUrl)
173 .then((tlyric) => ({ lyric: decodeName(lyric), tlyric: decodeName(tlyric || '') }))
174 .catch(() => ({ lyric: decodeName(lyric), tlyric: '' }))
175 })
176 },
177}
178
179export default mg