refactor: 架构整固——分层单向化、全量 TypeScript、直接运行

- 移除 bd/mg 两平台及磁盘残留产物;清理 api-test 死脚本、musicSdk/message+options 死模块、infSign vendor
- musicSdk/ 改名 sdk/;src/common、src/auth、src/apis 整体移入 sdk/,依赖方向定为 src → sdk 严格单向
- src/ 手写 JS 全量转 .ts,删除 JS 类型垫片 modules.d.ts;源码 import 统一 .ts 后缀
- Node 原生类型剥离直接运行 .ts(engines >=22.18),取消 tsc 发射产物,tsc 仅类型检查(pnpm typecheck)
- 删除 kwdes 备用实现与 src/index.ts 转发垫片;测试移至 test/smoke-test.ts
- common/request.ts 补显式导出类型;修复 set-cookie 单值形态、ApiError 类字段等隐患

验证:tsc 零错误,smoke-test 41/41
This commit is contained in:
snowy-yang committed 2026-09-25 23:06:23 +08:00
1 parent c8c939aa32
commit 354df2e739
126 files changed
+413 -2942

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
import { filterMusicInfoItem } from './singer.ts'
import { createMusicuFetch } from './utils/index.ts'
export default {
/**
* 通过专辑 mid 获取专辑详情与曲目列表
* @param {*} id 专辑 mid(搜索结果中的 albumId)
* @param {*} page
* @param {*} limit
*/
async getAlbumDetail(id, page = 1, limit = 100) {
const body = await createMusicuFetch({
req: {
module: 'music.musichallAlbum.AlbumSongList',
method: 'GetAlbumSongList',
// 注意:参数名是驼峰 albumMid,下划线形态会被上游以 104400 拒绝
param: { albumMid: id, begin: (page - 1) * limit, num: limit },
},
})
if (body.req.code != 0) throw new Error('get album song list faild.')
const data = body.req.data
const songList = data.songList ?? []
// GetAlbumInfo 详情接口已停用:专辑名取自曲目自带的 album 信息,
// 作者由曲目歌手去重合成,封面用平台固定图片 URL 规则
const first = songList[0]?.songInfo
const authors = [...new Set(songList.flatMap(item => item.songInfo?.singer?.map(s => s.name) ?? []))]
return {
source: 'tx',
info: {
name: first?.album?.name ?? null,
img: `https://y.gtimg.cn/music/photo_new/T002R500x500M000${id}.jpg`,
desc: null,
author: authors.join('、') || null,
},
list: this.filterSongList(songList),
page,
limit,
total: data.totalNum,
}
},
filterSongList(raw) {
return (raw ?? []).map(item => filterMusicInfoItem(item.songInfo))
},
}
+284
View File
@@ -0,0 +1,284 @@
import type { HttpRequestObject } from '../types.ts'
import { httpFetch } from '../request.ts'
import { dateFormat2 } from '../index.ts'
import getMusicInfo from './musicInfo.ts'
const emojis = {
e400846: '😘',
e400874: '😴',
e400825: '😃',
e400847: '😙',
e400835: '😍',
e400873: '😳',
e400836: '😎',
e400867: '😭',
e400832: '😊',
e400837: '😏',
e400875: '😫',
e400831: '😉',
e400855: '😡',
e400823: '😄',
e400862: '😨',
e400844: '😖',
e400841: '😓',
e400830: '😈',
e400828: '😆',
e400833: '😋',
e400822: '😀',
e400843: '😕',
e400829: '😇',
e400824: '😂',
e400834: '😌',
e400877: '😷',
e400132: '🍉',
e400181: '🍺',
e401067: '☕️',
e400186: '🥧',
e400343: '🐷',
e400116: '🌹',
e400126: '🍃',
e400613: '💋',
e401236: '❤️',
e400622: '💔',
e400637: '💣',
e400643: '💩',
e400773: '🔪',
e400102: '🌛',
e401328: '🌞',
e400420: '👏',
e400914: '🙌',
e400408: '👍',
e400414: '👎',
e401121: '✋',
e400396: '👋',
e400384: '👉',
e401115: '✊',
e400402: '👌',
e400905: '🙈',
e400906: '🙉',
e400907: '🙊',
e400562: '👻',
e400932: '🙏',
e400644: '💪',
e400611: '💉',
e400185: '🎁',
e400655: '💰',
e400325: '🐥',
e400612: '💊',
e400198: '🎉',
e401685: '⚡️',
e400631: '💝',
e400768: '🔥',
e400432: '👑',
}
const songIdMap = new Map()
const promises = new Map()
export default {
_requestObj: null as HttpRequestObject | null,
_requestObj2: null as HttpRequestObject | null,
async getSongId({ songId, songmid }) {
if (songId) return songId
if (songIdMap.has(songmid)) return songIdMap.get(songmid)
if (promises.has(songmid)) return (await promises.get(songmid)).songId
const promise = getMusicInfo(songmid)
promises.set(songmid, promise)
const info = await promise
if (!info) throw new Error('获取歌曲信息失败')
songIdMap.set(songmid, info.songId)
promises.delete(songmid)
return info.songId
},
async getComment(mInfo, page = 1, limit = 20) {
if (this._requestObj) this._requestObj.cancelHttp()
const songId = await this.getSongId(mInfo)
const _requestObj = httpFetch('http://c.y.qq.com/base/fcgi-bin/fcg_global_comment_h5.fcg', {
method: 'POST',
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
},
form: {
uin: '0',
format: 'json',
cid: '205360772',
reqtype: '2',
biztype: '1',
topid: songId,
cmd: '8',
needmusiccrit: '1',
pagenum: page - 1,
pagesize: limit,
},
})
const { body, statusCode } = await _requestObj.promise
if (statusCode != 200 || body.code !== 0) throw new Error('获取评论失败')
// console.log(body, statusCode)
const comment = body.comment
return {
source: 'tx',
comments: this.filterNewComment(comment.commentlist),
total: comment.commenttotal,
page,
limit,
maxPage: Math.ceil(comment.commenttotal / limit) || 1,
}
},
async getHotComment(mInfo, page = 1, limit = 20) {
// const _requestObj2 = httpFetch('http://c.y.qq.com/base/fcgi-bin/fcg_global_comment_h5.fcg', {
// method: 'POST',
// headers: {
// 'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
// },
// form: {
// uin: '0',
// format: 'json',
// cid: '205360772',
// reqtype: '2',
// biztype: '1',
// topid: songId,
// cmd: '9',
// needmusiccrit: '1',
// pagenum: page - 1,
// pagesize: limit,
// },
// })
if (this._requestObj2) this._requestObj2.cancelHttp()
const songId = await this.getSongId(mInfo)
const _requestObj2 = httpFetch('https://u.y.qq.com/cgi-bin/musicu.fcg', {
method: 'POST',
body: {
comm: {
cv: 4747474,
ct: 24,
format: 'json',
inCharset: 'utf-8',
outCharset: 'utf-8',
notice: 0,
platform: 'yqq.json',
needNewCode: 1,
uin: 0,
},
req: {
module: 'music.globalComment.CommentRead',
method: 'GetHotCommentList',
param: {
BizType: 1,
BizId: String(songId),
LastCommentSeqNo: '',
PageSize: limit,
PageNum: page - 1,
HotType: 1,
WithAirborne: 0,
PicEnable: 1,
},
},
},
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.0.0',
referer: 'https://y.qq.com/',
origin: 'https://y.qq.com',
},
})
const { body, statusCode } = await _requestObj2.promise
// console.log('body', body)
if (statusCode != 200 || body.code !== 0 || body.req.code !== 0) throw new Error('获取热门评论失败')
const comment = body.req.data.CommentList
return {
source: 'tx',
comments: this.filterHotComment(comment.Comments),
total: comment.Total,
page,
limit,
maxPage: Math.ceil(comment.Total / limit) || 1,
}
},
filterNewComment(rawList) {
return rawList.map(item => {
let time = this.formatTime(item.time)
let timeStr = time ? dateFormat2(time) : null
if (item.middlecommentcontent) {
let firstItem = item.middlecommentcontent[0]
firstItem.avatarurl = item.avatarurl
firstItem.praisenum = item.praisenum
item.avatarurl = null
item.praisenum = null
item.middlecommentcontent.reverse()
}
return {
id: `${item.rootcommentid}_${item.commentid}`,
rootId: item.rootcommentid,
text: item.rootcommentcontent ? this.replaceEmoji(item.rootcommentcontent).replace(/\\n/g, '\n') : '',
time: item.rootcommentid == item.commentid ? time : null,
timeStr: item.rootcommentid == item.commentid ? timeStr : null,
userName: item.rootcommentnick ? item.rootcommentnick.substring(1) : '',
avatar: item.avatarurl,
userId: item.encrypt_rootcommentuin,
likedCount: item.praisenum,
reply: item.middlecommentcontent
? item.middlecommentcontent.map(c => {
// let index = c.subcommentid.lastIndexOf('_')
return {
id: `sub_${item.rootcommentid}_${c.subcommentid}`,
text: this.replaceEmoji(c.subcommentcontent).replace(/\\n/g, '\n'),
time: c.subcommentid == item.commentid ? time : null,
timeStr: c.subcommentid == item.commentid ? timeStr : null,
userName: c.replynick.substring(1),
avatar: c.avatarurl,
userId: c.encrypt_replyuin,
likedCount: c.praisenum,
}
})
: [],
}
})
},
filterHotComment(rawList) {
return rawList.map(item => {
return {
id: `${item.SeqNo}_${item.CmId}`,
rootId: item.SeqNo,
text: item.Content ? this.replaceEmoji(item.Content).replace(/\\n/g, '\n') : '',
time: item.PubTime ? this.formatTime(item.PubTime) : null,
timeStr: item.PubTime ? dateFormat2(this.formatTime(item.PubTime)) : null,
userName: item.Nick ?? '',
images: item.Pic ? [item.Pic] : [],
avatar: item.Avatar,
location: item.Location ? item.Location : '',
userId: item.EncryptUin,
likedCount: item.PraiseNum,
reply: item.SubComments
? item.SubComments.map(c => {
return {
id: `sub_${c.SeqNo}_${c.CmId}`,
text: this.replaceEmoji(c.Content).replace(/\\n/g, '\n'),
time: c.PubTime ? this.formatTime(c.PubTime) : null,
timeStr: c.PubTime ? dateFormat2(this.formatTime(c.PubTime)) : null,
userName: c.Nick ?? '',
avatar: c.Avatar,
images: c.Pic ? [c.Pic] : [],
userId: c.EncryptUin,
likedCount: c.PraiseNum,
}
})
: [],
}
})
},
replaceEmoji(msg) {
let rxp = /^\[em\](e\d+)\[\/em\]$/
let result = msg.match(/\[em\]e\d+\[\/em\]/g)
if (!result) return msg
result = Array.from(new Set(result))
for (let item of result) {
let code = item.replace(rxp, '$1')
msg = msg.replace(new RegExp(item.replace('[em]', '\\[em\\]').replace('[/em]', '\\[\\/em\\]'), 'g'), emojis[code] || '')
}
return msg
},
formatTime(time) {
return String(time).length < 10 ? null : parseInt(time + '000')
},
}
+55
View File
@@ -0,0 +1,55 @@
import type { HttpRequestObject } from '../types.ts'
import { httpFetch } from '../request.ts'
export default {
_requestObj: null as HttpRequestObject | null,
async getList(retryNum = 0) {
if (this._requestObj) this._requestObj.cancelHttp()
if (retryNum > 2) return Promise.reject(new Error('try max num'))
// const _requestObj = httpFetch('https://c.y.qq.com/splcloud/fcgi-bin/gethotkey.fcg', {
// method: 'get',
// headers: {
// Referer: 'https://y.qq.com/portal/player.html',
// },
// })
const _requestObj = httpFetch('https://u.y.qq.com/cgi-bin/musicu.fcg', {
method: 'post',
body: {
comm: {
ct: '19',
cv: '1803',
guid: '0',
patch: '118',
psrf_access_token_expiresAt: 0,
psrf_qqaccess_token: '',
psrf_qqopenid: '',
psrf_qqunionid: '',
tmeAppID: 'qqmusic',
tmeLoginType: 0,
uin: '0',
wid: '0',
},
hotkey: {
method: 'GetHotkeyForQQMusicPC',
module: 'tencent_musicsoso_hotkey.HotkeyService',
param: {
search_id: '',
uin: 0,
},
},
},
headers: {
Referer: 'https://y.qq.com/portal/player.html',
},
})
const { body, statusCode } = await _requestObj.promise
// console.log(body)
if (statusCode != 200 || body.code !== 0) throw new Error('获取热搜词失败')
// console.log(body)
return { source: 'tx', list: this.filterList(body.hotkey.data.vec_hotkey) }
},
filterList(rawList) {
return rawList.map(item => item.query)
},
}
+37
View File
@@ -0,0 +1,37 @@
import leaderboard from './leaderboard.ts'
import lyric from './lyric.ts'
import songList from './songList.ts'
import musicSearch from './musicSearch.ts'
import { apis } from '../api-source.ts'
import hotSearch from './hotSearch.ts'
import comment from './comment.ts'
import singer from './singer.ts'
import album from './album.ts'
// import tipSearch from './tipSearch.ts'
const tx = {
// tipSearch,
leaderboard,
songList,
musicSearch,
hotSearch,
comment,
singer,
album,
getMusicUrl(songInfo, type) {
return apis('tx')!.getMusicUrl(songInfo, type)
},
getLyric(songInfo) {
// let singer = songInfo.singer.indexOf('、') > -1 ? songInfo.singer.split('、')[0] : songInfo.singer
return lyric.getLyric(songInfo)
},
async getPic(songInfo) {
return `https://y.gtimg.cn/music/photo_new/T002R500x500M000${songInfo.albumId}.jpg`
},
getMusicDetailPageUrl(songInfo) {
return `https://y.qq.com/n/yqq/song/${songInfo.songmid}.html`
},
}
export default tx
+248
View File
@@ -0,0 +1,248 @@
import type { HttpRequestObject, SongInfo, SongType, Quality, QualityInfo } from '../types.ts'
import { httpFetch } from '../request.ts'
import { formatPlayTime, sizeFormate } from '../index.ts'
import { formatSingerName } from '../utils.ts'
let boardList = [{ id: 'tx__4', name: '流行指数榜', bangid: '4' }, { id: 'tx__26', name: '热歌榜', bangid: '26' }, { id: 'tx__27', name: '新歌榜', bangid: '27' }, { id: 'tx__62', name: '飙升榜', bangid: '62' }, { id: 'tx__58', name: '说唱榜', bangid: '58' }, { id: 'tx__57', name: '喜力电音榜', bangid: '57' }, { id: 'tx__28', name: '网络歌曲榜', bangid: '28' }, { id: 'tx__5', name: '内地榜', bangid: '5' }, { id: 'tx__3', name: '欧美榜', bangid: '3' }, { id: 'tx__59', name: '香港地区榜', bangid: '59' }, { id: 'tx__16', name: '韩国榜', bangid: '16' }, { id: 'tx__60', name: '抖快榜', bangid: '60' }, { id: 'tx__29', name: '影视金曲榜', bangid: '29' }, { id: 'tx__17', name: '日本榜', bangid: '17' }, { id: 'tx__52', name: '腾讯音乐人原创榜', bangid: '52' }, { id: 'tx__36', name: 'K歌金曲榜', bangid: '36' }, { id: 'tx__61', name: '台湾地区榜', bangid: '61' }, { id: 'tx__63', name: 'DJ舞曲榜', bangid: '63' }, { id: 'tx__64', name: '综艺新歌榜', bangid: '64' }, { id: 'tx__65', name: '国风热歌榜', bangid: '65' }, { id: 'tx__67', name: '听歌识曲榜', bangid: '67' }, { id: 'tx__72', name: '动漫音乐榜', bangid: '72' }, { id: 'tx__73', name: '游戏音乐榜', bangid: '73' }, { id: 'tx__75', name: '有声榜', bangid: '75' }, { id: 'tx__131', name: '校园音乐人排行榜', bangid: '131' }]
export default {
limit: 300,
list: [
{
id: 'txlxzsb',
name: '流行榜',
bangid: '4',
},
{
id: 'txrgb',
name: '热歌榜',
bangid: '26',
},
{
id: 'txwlhgb',
name: '网络榜',
bangid: '28',
},
{
id: 'txdyb',
name: '抖音榜',
bangid: '60',
},
{
id: 'txndb',
name: '内地榜',
bangid: '5',
},
{
id: 'txxgb',
name: '香港榜',
bangid: '59',
},
{
id: 'txtwb',
name: '台湾榜',
bangid: '61',
},
{
id: 'txoumb',
name: '欧美榜',
bangid: '3',
},
{
id: 'txhgb',
name: '韩国榜',
bangid: '16',
},
{
id: 'txrbb',
name: '日本榜',
bangid: '17',
},
{
id: 'txtybb',
name: 'YouTube榜',
bangid: '128',
},
],
listDetailRequest(id, period, limit) {
// console.log(id, period, limit)
return httpFetch('https://u.y.qq.com/cgi-bin/musicu.fcg', {
method: 'post',
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
},
body: {
toplist: {
module: 'musicToplist.ToplistInfoServer',
method: 'GetDetail',
param: {
topid: id,
num: limit,
period,
},
},
comm: {
uin: 0,
format: 'json',
ct: 20,
cv: 1859,
},
},
}).promise
},
regExps: {
periodList: /<i class="play_cover__btn c_tx_link js_icon_play" data-listkey=".+?" data-listname=".+?" data-tid=".+?" data-date=".+?" .+?<\/i>/g,
period: /data-listname="(.+?)" data-tid=".*?\/(.+?)" data-date="(.+?)" .+?<\/i>/,
},
periods: {},
periodUrl: 'https://c.y.qq.com/node/pc/wk_v15/top.html',
_requestBoardsObj: null as HttpRequestObject | null,
getBoardsData() {
if (this._requestBoardsObj) this._requestBoardsObj.cancelHttp()
this._requestBoardsObj = httpFetch('https://c.y.qq.com/v8/fcg-bin/fcg_myqq_toplist.fcg?g_tk=1928093487&inCharset=utf-8&outCharset=utf-8&notice=0&format=json&uin=0&needNewCode=1&platform=h5')
return this._requestBoardsObj.promise
},
getData(url) {
const requestDataObj = httpFetch(url)
return requestDataObj.promise
},
filterData(rawList) {
// console.log(rawList)
return rawList.map(item => {
let types: SongType[] = []
let _types: Partial<Record<Quality, QualityInfo>> = {}
if (item.file.size_128mp3 !== 0) {
let size = sizeFormate(item.file.size_128mp3)
types.push({ type: '128k', size })
_types['128k'] = {
size,
}
}
if (item.file.size_320mp3 !== 0) {
let size = sizeFormate(item.file.size_320mp3)
types.push({ type: '320k', size })
_types['320k'] = {
size,
}
}
if (item.file.size_flac !== 0) {
let size = sizeFormate(item.file.size_flac)
types.push({ type: 'flac', size })
_types.flac = {
size,
}
}
if (item.file.size_hires !== 0) {
let size = sizeFormate(item.file.size_hires)
types.push({ type: 'flac24bit', size })
_types.flac24bit = {
size,
}
}
// types.reverse()
return {
singer: formatSingerName(item.singer, 'name'),
name: item.title,
albumName: item.album.name,
albumId: item.album.mid,
source: 'tx',
interval: formatPlayTime(item.interval),
songId: item.id,
albumMid: item.album.mid,
strMediaMid: item.file.media_mid,
songmid: item.mid,
img: (item.album.name === '' || item.album.name === '空')
? item.singer?.length ? `https://y.gtimg.cn/music/photo_new/T001R500x500M000${item.singer[0].mid}.jpg` : ''
: `https://y.gtimg.cn/music/photo_new/T002R500x500M000${item.album.mid}.jpg`,
lrc: null,
otherSource: null,
types,
_types,
typeUrl: {},
}
})
},
getPeriods(bangid) {
return this.getData(this.periodUrl).then(({ body: html }) => {
let result = html.match(this.regExps.periodList)
if (!result) return Promise.reject(new Error('get data failed'))
result.forEach(item => {
let result = item.match(this.regExps.period)
if (!result) return
this.periods[result[2]] = {
name: result[1],
bangid: result[2],
period: result[3],
}
})
const info = this.periods[bangid]
return info && info.period
})
},
filterBoardsData(rawList) {
// console.log(rawList)
let list: any[] = []
for (const board of rawList) {
// 排除 MV榜
if (board.id == 201) continue
if (board.topTitle.startsWith('巅峰榜·')) {
board.topTitle = board.topTitle.substring(4, board.topTitle.length)
}
if (!board.topTitle.endsWith('榜')) board.topTitle += '榜'
list.push({
id: 'tx__' + board.id,
name: board.topTitle,
bangid: String(board.id),
})
}
return list
},
async getBoards(retryNum = 0) {
// if (++retryNum > 3) return Promise.reject(new Error('try max num'))
// let response
// try {
// response = await this.getBoardsData()
// } catch (error) {
// return this.getBoards(retryNum)
// }
// // console.log(response.body)
// if (response.statusCode !== 200 || response.body.code !== 0) return this.getBoards(retryNum)
// const list = this.filterBoardsData(response.body.data.topList)
// console.log(list)
// console.log(JSON.stringify(list))
// this.list = list
// return {
// list,
// source: 'tx',
// }
this.list = boardList
return {
list: boardList,
source: 'tx',
}
},
getList(bangid, page, retryNum = 0) {
if (++retryNum > 3) return Promise.reject(new Error('try max num'))
bangid = parseInt(bangid)
let info = this.periods[bangid]
let p = info ? Promise.resolve(info.period) : this.getPeriods(bangid)
return p.then(period => {
return this.listDetailRequest(bangid, period, this.limit).then(resp => {
if (resp.body.code !== 0) return this.getList(bangid, page, retryNum)
return {
total: resp.body.toplist.data.songInfoList.length,
list: this.filterData(resp.body.toplist.data.songInfoList),
limit: this.limit,
page: 1,
source: 'tx',
}
})
})
},
getDetailPageUrl(id) {
if (typeof id == 'string') id = id.replace('tx__', '')
return `https://y.qq.com/n/ryqq/toplist/${id}`
},
}
+296
View File
@@ -0,0 +1,296 @@
import type { HttpRequestObject } from '../types.ts'
import { httpFetch } from '../request.ts'
import getMusicInfo from './musicInfo.ts'
import { rendererInvoke } from '../common/rendererIpc.ts'
import { WIN_MAIN_RENDERER_EVENT_NAME } from '../common/ipcNames.ts'
const songIdMap = new Map()
const promises = new Map()
export const decodeLyric = (lrc: any, tlrc?: any, rlrc?: any): Promise<any> => rendererInvoke(WIN_MAIN_RENDERER_EVENT_NAME.handle_tx_decode_lyric, { lrc, tlrc, rlrc })
const parseTools = {
rxps: {
info: /^{"/,
lineTime: /^\[(\d+),\d+\]/,
lineTime2: /^\[([\d:.]+)\]/,
wordTime: /\(\d+,\d+\)/,
wordTimeAll: /(\(\d+,\d+\))/g,
timeLabelFixRxp: /(?:\.0+|0+)$/,
},
msFormat(timeMs) {
if (Number.isNaN(timeMs)) return ''
let ms = timeMs % 1000
timeMs /= 1000
let m = Math.floor(timeMs / 60).toString().padStart(2, '0')
timeMs %= 60
let s = Math.floor(timeMs).toString().padStart(2, '0')
return `[${m}:${s}.${String(ms).padStart(3, '0')}]`
},
parseLyric(lrc) {
lrc = lrc.trim()
lrc = lrc.replace(/\r/g, '')
if (!lrc) return { lyric: '', yrc: '' }
const lines = lrc.split('\n')
const yrcLines: string[] = []
const lrcLines: string[] = []
for (let line of lines) {
line = line.trim()
let result = this.rxps.lineTime.exec(line)
if (!result) {
if (line.startsWith('[offset')) {
yrcLines.push(line)
lrcLines.push(line)
}
if (this.rxps.lineTime2.test(line)) {
// yrcLines.push(line)
lrcLines.push(line)
}
continue
}
const startMsTime = parseInt(result[1])
const startTimeStr = this.msFormat(startMsTime)
if (!startTimeStr) continue
let words = line.replace(this.rxps.lineTime, '')
lrcLines.push(`${startTimeStr}${words.replace(this.rxps.wordTimeAll, '')}`)
let times = words.match(this.rxps.wordTimeAll)
if (!times) continue
times = times.map(time => {
const result = /\((\d+),(\d+)\)/.exec(time)!
return `<${Math.max(parseInt(result[1]) - startMsTime, 0)},${result[2]}>`
})
const wordArr = words.split(this.rxps.wordTime)
const newWords = times.map((time, index) => `${time}${wordArr[index]}`).join('')
yrcLines.push(`${startTimeStr}${newWords}`)
}
return {
lyric: lrcLines.join('\n'),
yrc: yrcLines.join('\n'),
}
},
parseRlyric(lrc) {
lrc = lrc.trim()
lrc = lrc.replace(/\r/g, '')
if (!lrc) return { lyric: '', yrc: '' }
const lines = lrc.split('\n')
const lrcLines: string[] = []
for (let line of lines) {
line = line.trim()
let result = this.rxps.lineTime.exec(line)
if (!result) continue
const startMsTime = parseInt(result[1])
const startTimeStr = this.msFormat(startMsTime)
if (!startTimeStr) continue
let words = line.replace(this.rxps.lineTime, '')
lrcLines.push(`${startTimeStr}${words.replace(this.rxps.wordTimeAll, '')}`)
}
return lrcLines.join('\n')
},
removeTag(str) {
return str.replace(/^[\S\s]*?LyricContent="/, '').replace(/"\/>[\S\s]*?$/, '')
},
getIntv(interval) {
if (!interval) return 0
if (!interval.includes('.')) interval += '.0'
let arr = interval.split(/:|\./)
while (arr.length < 3) arr.unshift('0')
const [m, s, ms] = arr
return parseInt(m) * 3600000 + parseInt(s) * 1000 + parseInt(ms)
},
fixRlrcTimeTag(rlrc, lrc) {
// console.log(lrc)
// console.log(rlrc)
const rlrcLines = rlrc.split('\n')
let lrcLines = lrc.split('\n')
// let temp: string[] = []
let newLrc: string[] = []
rlrcLines.forEach((line) => {
const result = this.rxps.lineTime2.exec(line)
if (!result) return
const words = line.replace(this.rxps.lineTime2, '')
if (!words.trim()) return
const t1 = this.getIntv(result[1])
while (lrcLines.length) {
const lrcLine = lrcLines.shift()
const lrcLineResult = this.rxps.lineTime2.exec(lrcLine)
if (!lrcLineResult) continue
const t2 = this.getIntv(lrcLineResult[1])
if (Math.abs(t1 - t2) < 100) {
newLrc.push(line.replace(this.rxps.lineTime2, lrcLineResult[0]))
break
}
// temp.push(line)
}
// lrcLines = [...temp, ...lrcLines]
// temp = []
})
return newLrc.join('\n')
},
fixTlrcTimeTag(tlrc, lrc) {
// console.log(lrc)
// console.log(tlrc)
const tlrcLines = tlrc.split('\n')
let lrcLines = lrc.split('\n')
// let temp: string[] = []
let newLrc: string[] = []
tlrcLines.forEach((line) => {
const result = this.rxps.lineTime2.exec(line)
if (!result) return
const words = line.replace(this.rxps.lineTime2, '')
if (!words.trim()) return
let time = result[1]
if (time.includes('.')) {
time += ''.padStart(3 - time.split('.')[1].length, '0')
}
const t1 = this.getIntv(time)
while (lrcLines.length) {
const lrcLine = lrcLines.shift()
const lrcLineResult = this.rxps.lineTime2.exec(lrcLine)
if (!lrcLineResult) continue
const t2 = this.getIntv(lrcLineResult[1])
if (Math.abs(t1 - t2) < 100) {
newLrc.push(line.replace(this.rxps.lineTime2, lrcLineResult[0]))
break
}
// temp.push(line)
}
// lrcLines = [...temp, ...lrcLines]
// temp = []
})
return newLrc.join('\n')
},
parse(lrc, tlrc, rlrc) {
const info = {
lyric: '',
tlyric: '',
rlyric: '',
yrc: '',
}
if (lrc) {
let { lyric, yrc } = this.parseLyric(this.removeTag(lrc))
info.lyric = lyric
info.yrc = yrc
// console.log(lyric)
// console.log(yrc)
}
if (rlrc) info.rlyric = this.fixRlrcTimeTag(this.parseRlyric(this.removeTag(rlrc)), info.lyric)
if (tlrc) info.tlyric = this.fixTlrcTimeTag(tlrc, info.lyric)
// console.log(info.lyric)
// console.log(info.tlyric)
// console.log(info.rlyric)
return info
},
}
export default {
successCode: 0,
async getSongId({ songId, songmid }) {
if (songId) return songId
if (songIdMap.has(songmid)) return songIdMap.get(songmid)
if (promises.has(songmid)) return (await promises.get(songmid)).songId
const promise = getMusicInfo(songmid)
promises.set(songmid, promise)
const info = await promise
if (!info) throw new Error('获取歌曲信息失败')
songIdMap.set(songmid, info.songId)
promises.delete(songmid)
return info.songId
},
async parseLyric(lrc, tlrc, rlrc) {
const { lyric, tlyric, rlyric } = await decodeLyric(lrc, tlrc, rlrc)
// return {
// }
// console.log(lyric)
// console.log(tlyric)
// console.log(rlyric)
return parseTools.parse(lyric, tlyric, rlyric)
},
getLyric(mInfo, retryNum = 0) {
if (retryNum > 3) return Promise.reject(new Error('Get lyric failed'))
return {
cancelHttp() {
},
promise: this.getSongId(mInfo).then(songId => {
const requestObj = httpFetch('https://u.y.qq.com/cgi-bin/musicu.fcg', {
method: 'post',
headers: {
referer: 'https://y.qq.com',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
},
body: {
comm: {
ct: '19',
cv: '1859',
uin: '0',
},
req: {
method: 'GetPlayLyricInfo',
module: 'music.musichallSong.PlayLyricInfo',
param: {
format: 'json',
crypt: 1,
ct: 19,
cv: 1873,
interval: 0,
lrc_t: 0,
qrc: 1,
qrc_t: 0,
roma: 1,
roma_t: 0,
songID: songId,
trans: 1,
trans_t: 0,
type: -1,
},
},
},
})
return requestObj.promise.then(({ body }) => {
// console.log(body)
if (body.code != this.successCode || body.req.code != this.successCode) return this.getLyric(songId, ++retryNum)
const data = body.req.data
return this.parseLyric(data.lyric, data.trans, data.roma)
})
}),
}
},
}
// export default {
// regexps: {
// matchLrc: /.+"lyric":"([\w=+/]*)".+/,
// },
// getLyric(songmid) {
// const requestObj = httpFetch(`https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?songmid=${songmid}&g_tk=5381&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&platform=yqq`, {
// headers: {
// Referer: 'https://y.qq.com/portal/player.html',
// },
// })
// requestObj.promise = requestObj.promise.then(({ body }) => {
// if (body.code != 0 || !body.lyric) return Promise.reject(new Error('Get lyric failed'))
// return {
// lyric: decodeName(b64DecodeUnicode(body.lyric)),
// tlyric: decodeName(b64DecodeUnicode(body.trans)),
// }
// })
// return requestObj
// },
// }
+99
View File
@@ -0,0 +1,99 @@
import type { HttpRequestObject, SongType, Quality, QualityInfo } from '../types.ts'
import { httpFetch } from '../request.ts'
import { formatPlayTime, sizeFormate } from '../index.ts'
const getSinger = (singers) => {
let arr: string[] = []
singers.forEach(singer => {
arr.push(singer.name)
})
return arr.join('、')
}
export default (songmid) => {
const requestObj = httpFetch('https://u.y.qq.com/cgi-bin/musicu.fcg', {
method: 'post',
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
},
body: {
comm: {
ct: '19',
cv: '1859',
uin: '0',
},
req: {
module: 'music.pf_song_detail_svr',
method: 'get_song_detail_yqq',
param: {
song_type: 0,
song_mid: songmid,
},
},
},
})
return requestObj.promise.then(({ body }) => {
// console.log(body)
if (body.code != 0 || body.req.code != 0) return Promise.reject(new Error('获取歌曲信息失败'))
const item = body.req.data.track_info
if (!item.file?.media_mid) return null
let types: SongType[] = []
let _types: Partial<Record<Quality, QualityInfo>> = {}
const file = item.file
if (file.size_128mp3 != 0) {
let size = sizeFormate(file.size_128mp3)
types.push({ type: '128k', size })
_types['128k'] = {
size,
}
}
if (file.size_320mp3 !== 0) {
let size = sizeFormate(file.size_320mp3)
types.push({ type: '320k', size })
_types['320k'] = {
size,
}
}
if (file.size_flac !== 0) {
let size = sizeFormate(file.size_flac)
types.push({ type: 'flac', size })
_types.flac = {
size,
}
}
if (file.size_hires !== 0) {
let size = sizeFormate(file.size_hires)
types.push({ type: 'flac24bit', size })
_types.flac24bit = {
size,
}
}
// types.reverse()
let albumId = ''
let albumName = ''
if (item.album) {
albumName = item.album.name
albumId = item.album.mid
}
return {
singer: getSinger(item.singer),
name: item.title,
albumName,
albumId,
source: 'tx',
interval: formatPlayTime(item.interval),
songId: item.id,
albumMid: item.album?.mid ?? '',
strMediaMid: item.file.media_mid,
songmid: item.mid,
img: (albumId === '' || albumId === '空')
? item.singer?.length ? `https://y.gtimg.cn/music/photo_new/T001R500x500M000${item.singer[0].mid}.jpg` : ''
: `https://y.gtimg.cn/music/photo_new/T002R500x500M000${albumId}.jpg`,
types,
_types,
typeUrl: {},
}
})
}
+169
View File
@@ -0,0 +1,169 @@
import { formatPlayTime, sizeFormate } from '../index.ts'
import { formatSingerName } from '../utils.ts'
import { signRequest } from './utils/index.ts'
import type { SongInfo, SongType, Quality, QualityInfo } from '../types.ts'
export default {
limit: 50,
total: 0,
page: 0,
allPage: 1,
successCode: 0,
musicSearch(str, page, limit, retryNum = 0) {
if (retryNum > 5) return Promise.reject(new Error('搜索失败'))
const searchRequest = signRequest({
comm: {
ct: '11',
cv: '14090508',
v: '14090508',
tmeAppID: 'qqmusic',
phonetype: 'EBG-AN10',
deviceScore: '553.47',
devicelevel: '50',
newdevicelevel: '20',
rom: 'HuaWei/EMOTION/EmotionUI_14.2.0',
os_ver: '12',
OpenUDID: '0',
OpenUDID2: '0',
QIMEI36: '0',
udid: '0',
chid: '0',
aid: '0',
oaid: '0',
taid: '0',
tid: '0',
wid: '0',
uid: '0',
sid: '0',
modeSwitch: '6',
teenMode: '0',
ui_mode: '2',
nettype: '1020',
v4ip: '',
},
req: {
module: 'music.search.SearchCgiService',
method: 'DoSearchForQQMusicMobile',
param: {
search_type: 0,
searchid: Math.random().toString().slice(2),
query: str,
page_num: page,
num_per_page: limit,
highlight: 0,
nqc_flag: 0,
multi_zhida: 0,
cat: 2,
grp: 1,
sin: 0,
sem: 0,
},
},
})
return searchRequest.then(({ body }) => {
// console.log(body)
if (!body || !body.req || body.code != this.successCode || body.req.code != this.successCode) {
return this.musicSearch(str, page, limit, ++retryNum)
}
return body.req.data
})
},
// randomInt(min, max) {
// return Math.floor(Math.random() * (max - min + 1)) + min
// },
// getSearchId() {
// const e = BigInt(this.randomInt(1, 20))
// const t = e * 18014398509481984n
// const n = BigInt(this.randomInt(0, 4194304)) * 4294967296n
// const a = BigInt(Date.now())
// const r = (a * 1000n) % (24n * 60n * 60n * 1000n)
// return String(t + n + r)
// },
handleResult(rawList) {
// console.log(rawList)
if (!rawList || !Array.isArray(rawList)) return []
const list: SongInfo[] = []
rawList.forEach(item => {
if (!item.file?.media_mid) return
let types: SongType[] = []
let _types: Partial<Record<Quality, QualityInfo>> = {}
const file = item.file
if (file.size_128mp3 != 0) {
let size = sizeFormate(file.size_128mp3)
types.push({ type: '128k', size })
_types['128k'] = {
size,
}
}
if (file.size_320mp3 !== 0) {
let size = sizeFormate(file.size_320mp3)
types.push({ type: '320k', size })
_types['320k'] = {
size,
}
}
if (file.size_flac !== 0) {
let size = sizeFormate(file.size_flac)
types.push({ type: 'flac', size })
_types.flac = {
size,
}
}
if (file.size_hires !== 0) {
let size = sizeFormate(file.size_hires)
types.push({ type: 'flac24bit', size })
_types.flac24bit = {
size,
}
}
// types.reverse()
let albumId = ''
let albumName = ''
if (item.album) {
albumName = item.album.name
albumId = item.album.mid
}
list.push({
singer: formatSingerName(item.singer, 'name'),
// name: item.name + (item.title_extra ?? ''),
name: item.title,
albumName,
albumId,
source: 'tx',
interval: formatPlayTime(item.interval),
songId: item.id,
albumMid: item.album?.mid ?? '',
strMediaMid: item.file.media_mid,
songmid: item.mid,
img: (albumId === '' || albumId === '空')
? item.singer?.length ? `https://y.gtimg.cn/music/photo_new/T001R500x500M000${item.singer[0].mid}.jpg` : ''
: `https://y.gtimg.cn/music/photo_new/T002R500x500M000${albumId}.jpg`,
types,
_types,
typeUrl: {},
})
})
// console.log(list)
return list
},
search(str, page = 1, limit) {
if (limit == null) limit = this.limit
// http://newlyric.kuwo.cn/newlyric.lrc?62355680
return this.musicSearch(str, page, limit).then(({ body, meta }) => {
let list = this.handleResult(body.item_song)
this.total = meta.estimate_sum
this.page = page
this.allPage = Math.ceil(this.total / limit)
return Promise.resolve({
list,
allPage: this.allPage,
limit,
total: this.total,
source: 'tx',
})
})
},
}
+181
View File
@@ -0,0 +1,181 @@
import type { SongType, Quality, QualityInfo } from '../types.ts'
import { formatPlayTime, sizeFormate } from '../index.ts'
import { formatSingerName } from '../utils.ts'
import { createMusicuFetch } from './utils/index.ts'
export const filterMusicInfoItem = item => {
const types: SongType[] = []
const _types: Partial<Record<Quality, QualityInfo>> = {}
if (item.file.size_128mp3 != 0) {
let size = sizeFormate(item.file.size_128mp3)
types.push({ type: '128k', size })
_types['128k'] = {
size,
}
}
if (item.file.size_320mp3 !== 0) {
let size = sizeFormate(item.file.size_320mp3)
types.push({ type: '320k', size })
_types['320k'] = {
size,
}
}
if (item.file.size_flac !== 0) {
let size = sizeFormate(item.file.size_flac)
types.push({ type: 'flac', size })
_types.flac = {
size,
}
}
if (item.file.size_hires !== 0) {
let size = sizeFormate(item.file.size_hires)
types.push({ type: 'flac24bit', size })
_types.flac24bit = {
size,
}
}
const albumId = item.album.id ?? ''
const albumMid = item.album.mid ?? ''
const albumName = item.album.name ?? ''
return {
source: 'tx',
singer: formatSingerName(item.singer, 'name'),
name: item.title,
albumName,
albumId,
albumMid,
interval: formatPlayTime(item.interval),
songId: item.id,
songmid: item.mid,
strMediaMid: item.file.media_mid,
img: (albumId === '' || albumId === '空')
? item.singer?.length ? `https://y.gtimg.cn/music/photo_new/T001R500x500M000${item.singer[0].mid}.jpg` : ''
: `https://y.gtimg.cn/music/photo_new/T002R500x500M000${albumMid}.jpg`,
types,
_types,
typeUrl: {},
}
}
// 歌手详情接口(musichallSinger.GetSingerDetail 等)已停用(104403):
// 歌手名/统计由 GetSingerSongList 与 GetAlbumList 合成,头像走固定图片 URL 规则
export default {
/**
* 获取歌手信息
* @param {*} id
*/
getInfo(id) {
return Promise.all([
createMusicuFetch({ req: { module: 'musichall.song_list_server', method: 'GetSingerSongList', param: { singerMid: id, order: 1, begin: 0, num: 1 } } }),
createMusicuFetch({ req: { module: 'music.musichallAlbum.AlbumListServer', method: 'GetAlbumList', param: { singerMid: id, order: 0, begin: 0, num: 1, songNumTag: 0, singerID: 0 } } }),
]).then(([songBody, albumBody]) => {
if (songBody.req.code != 0 || albumBody.req.code != 0) throw new Error('get singer info faild.')
const songData = songBody.req.data
const albumData = albumBody.req.data
// 详情接口停用:歌手名从歌曲条目反查,头像用平台的固定图片 URL 规则
const singers = songData.songList?.[0]?.songInfo?.singer ?? []
const self = singers.find(s => s.mid === id) ?? singers[0]
return {
source: 'tx',
id,
info: {
name: self?.name ?? '',
desc: null,
avatar: `https://y.gtimg.cn/music/photo_new/T001R500x500M000${id}.jpg`,
gender: null,
},
count: {
music: songData.totalNum,
album: albumData.total,
},
}
})
},
/**
* 获取歌手专辑列表
* @param {*} id
* @param {*} page
* @param {*} limit
*/
getAlbumList(id, page = 1, limit = 10) {
return createMusicuFetch({
req: {
module: 'music.musichallAlbum.AlbumListServer',
method: 'GetAlbumList',
param: {
singerMid: id,
order: 0,
begin: (page - 1) * limit,
num: limit,
songNumTag: 0,
singerID: 0,
},
},
}).then(body => {
if (body.req.code != 0) throw new Error('get singer album faild.')
const list = this.filterAlbumList(body.req.data.albumList)
return {
source: 'tx',
list,
limit,
page,
total: body.req.data.total,
}
})
},
/**
* 获取歌手歌曲列表
* @param {*} id
* @param {*} page
* @param {*} limit
*/
async getSongList(id, page = 1, limit = 100) {
const body = await createMusicuFetch({
req: {
module: 'musichall.song_list_server',
method: 'GetSingerSongList',
param: {
singerMid: id,
order: 1,
begin: (page - 1) * limit,
num: limit,
},
},
})
if (body.req.code != 0) throw new Error('get singer song list faild.')
const list = this.filterSongList(body.req.data.songList)
return {
source: 'tx',
list,
limit,
page,
total: body.req.data.totalNum,
}
},
filterAlbumList(raw) {
return raw.map(item => {
return {
id: item.albumID,
mid: item.albumMid,
count: item.totalNum,
info: {
name: item.albumName,
author: item.singerName,
img: `https://y.gtimg.cn/music/photo_new/T002R500x500M000${item.albumMid}.jpg`,
desc: null,
},
}
})
},
filterSongList(raw) {
return raw.map(item => {
return filterMusicInfoItem(item.songInfo)
})
},
}
+329
View File
@@ -0,0 +1,329 @@
import type { HttpRequestObject, SongType, Quality, QualityInfo } from '../types.ts'
import { httpFetch } from '../request.ts'
import { decodeName, formatPlayTime, sizeFormate, dateFormat, formatPlayCount } from '../index.ts'
import { formatSingerName } from '../utils.ts'
export default {
_requestObj_tags: null as HttpRequestObject | null,
_requestObj_hotTags: null as HttpRequestObject | null,
_requestObj_list: null as HttpRequestObject | null,
limit_list: 36,
limit_song: 100000,
successCode: 0,
sortList: [
{
name: '最热',
id: 5,
},
{
name: '最新',
id: 2,
},
],
regExps: {
hotTagHtml: /class="c_bg_link js_tag_item" data-id="\w+">.+?<\/a>/g,
hotTag: /data-id="(\w+)">(.+?)<\/a>/,
// https://y.qq.com/n/yqq/playlist/7217720898.html
// https://i.y.qq.com/n2/m/share/details/taoge.html?platform=11&appshare=android_qq&appversion=9050006&id=7217720898&ADTAG=qfshare
listDetailLink: /\/playlist\/(\d+)/,
listDetailLink2: /id=(\d+)/,
},
tagsUrl: 'https://u.y.qq.com/cgi-bin/musicu.fcg?loginUin=0&hostUin=0&format=json&inCharset=utf-8&outCharset=utf-8&notice=0&platform=wk_v15.json&needNewCode=0&data=%7B%22tags%22%3A%7B%22method%22%3A%22get_all_categories%22%2C%22param%22%3A%7B%22qq%22%3A%22%22%7D%2C%22module%22%3A%22playlist.PlaylistAllCategoriesServer%22%7D%7D',
hotTagUrl: 'https://c.y.qq.com/node/pc/wk_v15/category_playlist.html',
getListUrl(sortId, id, page) {
if (id) {
id = parseInt(id)
return `https://u.y.qq.com/cgi-bin/musicu.fcg?loginUin=0&hostUin=0&format=json&inCharset=utf-8&outCharset=utf-8&notice=0&platform=wk_v15.json&needNewCode=0&data=${encodeURIComponent(JSON.stringify({
comm: { cv: 1602, ct: 20 },
playlist: {
method: 'get_category_content',
param: {
titleid: id,
caller: '0',
category_id: id,
size: this.limit_list,
page: page - 1,
use_page: 1,
},
module: 'playlist.PlayListCategoryServer',
},
}))}`
}
return `https://u.y.qq.com/cgi-bin/musicu.fcg?loginUin=0&hostUin=0&format=json&inCharset=utf-8&outCharset=utf-8&notice=0&platform=wk_v15.json&needNewCode=0&data=${encodeURIComponent(JSON.stringify({
comm: { cv: 1602, ct: 20 },
playlist: {
method: 'get_playlist_by_tag',
param: { id: 10000000, sin: this.limit_list * (page - 1), size: this.limit_list, order: sortId, cur_page: page },
module: 'playlist.PlayListPlazaServer',
},
}))}`
},
getListDetailUrl(id) {
return `https://c.y.qq.com/qzone/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg?type=1&json=1&utf8=1&onlysong=0&new_format=1&disstid=${id}&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0`
},
// http://nplserver.kuwo.cn/pl.svc?op=getlistinfo&pid=2849349915&pn=0&rn=100&encode=utf8&keyset=pl2012&identity=kuwo&pcmp4=1&vipver=MUSIC_9.0.5.0_W1&newver=1
// 获取标签
getTag(tryNum = 0) {
if (this._requestObj_tags) this._requestObj_tags.cancelHttp()
if (tryNum > 2) return Promise.reject(new Error('try max num'))
this._requestObj_tags = httpFetch(this.tagsUrl)
return this._requestObj_tags!.promise.then(({ body }) => {
if (body.code !== this.successCode) return this.getTag(++tryNum)
return this.filterTagInfo(body.tags.data.v_group)
})
},
// 获取标签
getHotTag(tryNum = 0) {
if (this._requestObj_hotTags) this._requestObj_hotTags.cancelHttp()
if (tryNum > 2) return Promise.reject(new Error('try max num'))
this._requestObj_hotTags = httpFetch(this.hotTagUrl)
return this._requestObj_hotTags!.promise.then(({ statusCode, body }) => {
if (statusCode !== 200) return this.getHotTag(++tryNum)
return this.filterInfoHotTag(body)
})
},
filterInfoHotTag(html) {
let hotTag = html.match(this.regExps.hotTagHtml)
const hotTags: any[] = []
if (!hotTag) return hotTags
hotTag.forEach(tagHtml => {
let result = tagHtml.match(this.regExps.hotTag)
if (!result) return
hotTags.push({
id: parseInt(result[1]),
name: result[2],
source: 'tx',
})
})
return hotTags
},
filterTagInfo(rawList) {
return rawList.map(type => ({
name: type.group_name,
list: type.v_item.map(item => ({
parent_id: type.group_id,
parent_name: type.group_name,
id: item.id,
name: item.name,
source: 'tx',
})),
}))
},
// 获取列表数据
getList(sortId, tagId, page, tryNum = 0) {
if (this._requestObj_list) this._requestObj_list.cancelHttp()
if (tryNum > 2) return Promise.reject(new Error('try max num'))
this._requestObj_list = httpFetch(
this.getListUrl(sortId, tagId, page),
)
// console.log(this.getListUrl(sortId, tagId, page))
return this._requestObj_list!.promise.then(({ body }) => {
if (body.code !== this.successCode) return this.getList(sortId, tagId, page, ++tryNum)
return tagId ? this.filterList2(body.playlist.data, page) : this.filterList(body.playlist.data, page)
})
},
filterList(data, page) {
return {
list: data.v_playlist.map(item => ({
play_count: formatPlayCount(item.access_num),
id: String(item.tid),
author: item.creator_info.nick,
name: item.title,
time: item.modify_time ? dateFormat(item.modify_time * 1000, 'Y-M-D') : '',
img: item.cover_url_medium,
// grade: item.favorcnt / 10,
total: item.song_ids?.length,
desc: decodeName(item.desc).replace(/<br>/g, '\n'),
source: 'tx',
})),
total: data.total,
page,
limit: this.limit_list,
source: 'tx',
}
},
filterList2({ content }, page) {
// console.log(content.v_item)
return {
list: content.v_item.map(({ basic }) => ({
play_count: formatPlayCount(basic.play_cnt),
id: String(basic.tid),
author: basic.creator.nick,
name: basic.title,
// time: basic.publish_time,
img: basic.cover.medium_url || basic.cover.default_url,
// grade: basic.favorcnt / 10,
desc: decodeName(basic.desc).replace(/<br>/g, '\n'),
source: 'tx',
})),
total: content.total_cnt,
page,
limit: this.limit_list,
source: 'tx',
}
},
async handleParseId(link, retryNum = 0) {
if (retryNum > 2) return Promise.reject(new Error('link try max num'))
const requestObj_listDetailLink = httpFetch(link)
const { headers: { location }, statusCode } = await requestObj_listDetailLink.promise
// console.log(headers)
if (statusCode > 400) return this.handleParseId(link, ++retryNum)
return location == null ? link : location
},
async getListId(id) {
if ((/[?&:/]/.test(id))) {
if (!this.regExps.listDetailLink.test(id)) {
id = await this.handleParseId(id)
}
let result = this.regExps.listDetailLink.exec(id)
if (!result) {
result = this.regExps.listDetailLink2.exec(id)
if (!result) throw new Error('failed')
}
id = result[1]
// console.log(id)
}
return id
},
// 获取歌曲列表内的音乐
async getListDetail(id, tryNum = 0) {
if (tryNum > 2) return Promise.reject(new Error('try max num'))
id = await this.getListId(id)
const requestObj_listDetail = httpFetch(this.getListDetailUrl(id), {
headers: {
Origin: 'https://y.qq.com',
Referer: `https://y.qq.com/n/yqq/playsquare/${id}.html`,
},
})
const { body } = await requestObj_listDetail.promise
if (body.code !== this.successCode) return this.getListDetail(id, ++tryNum)
const cdlist = body.cdlist[0]
return {
list: this.filterListDetail(cdlist.songlist),
page: 1,
limit: cdlist.songlist.length + 1,
total: cdlist.songlist.length,
source: 'tx',
info: {
name: cdlist.dissname,
img: cdlist.logo,
desc: decodeName(cdlist.desc).replace(/<br>/g, '\n'),
author: cdlist.nickname,
play_count: formatPlayCount(cdlist.visitnum),
},
}
},
filterListDetail(rawList) {
// console.log(rawList)
return rawList.map(item => {
let types: SongType[] = []
let _types: Partial<Record<Quality, QualityInfo>> = {}
if (item.file.size_128mp3 !== 0) {
let size = sizeFormate(item.file.size_128mp3)
types.push({ type: '128k', size })
_types['128k'] = {
size,
}
}
if (item.file.size_320mp3 !== 0) {
let size = sizeFormate(item.file.size_320mp3)
types.push({ type: '320k', size })
_types['320k'] = {
size,
}
}
if (item.file.size_flac !== 0) {
let size = sizeFormate(item.file.size_flac)
types.push({ type: 'flac', size })
_types.flac = {
size,
}
}
if (item.file.size_hires !== 0) {
let size = sizeFormate(item.file.size_hires)
types.push({ type: 'flac24bit', size })
_types.flac24bit = {
size,
}
}
// types.reverse()
return {
singer: formatSingerName(item.singer, 'name'),
name: item.title,
albumName: item.album.name,
albumId: item.album.mid,
source: 'tx',
interval: formatPlayTime(item.interval),
songId: item.id,
albumMid: item.album.mid,
strMediaMid: item.file.media_mid,
songmid: item.mid,
img: (item.album.name === '' || item.album.name === '空')
? item.singer?.length ? `https://y.gtimg.cn/music/photo_new/T001R500x500M000${item.singer[0].mid}.jpg` : ''
: `https://y.gtimg.cn/music/photo_new/T002R500x500M000${item.album.mid}.jpg`,
lrc: null,
otherSource: null,
types,
_types,
typeUrl: {},
}
})
},
getTags() {
return Promise.all([this.getTag(), this.getHotTag()]).then(([tags, hotTag]) => ({ tags, hotTag, source: 'tx' }))
},
async getDetailPageUrl(id) {
id = await this.getListId(id)
return `https://y.qq.com/n/ryqq/playlist/${id}`
},
search(text, page, limit = 20, retryNum = 0) {
if (retryNum > 5) throw new Error('max retry')
return httpFetch(`http://c.y.qq.com/soso/fcgi-bin/client_music_search_songlist?page_no=${page - 1}&num_per_page=${limit}&format=json&query=${encodeURIComponent(text)}&remoteplace=txt.yqq.playlist&inCharset=utf8&outCharset=utf-8`, {
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
Referer: 'http://y.qq.com/portal/search.html',
},
})
.promise.then(({ body }) => {
if (body.code != 0) return this.search(text, page, limit, ++retryNum)
// console.log(body.data.list)
return {
list: body.data.list.map(item => {
return {
play_count: formatPlayCount(item.listennum),
id: String(item.dissid),
author: decodeName(item.creator.name),
name: decodeName(item.dissname),
time: dateFormat(item.createtime, 'Y-M-D'),
img: item.imgurl,
// grade: item.favorcnt / 10,
total: item.song_count,
desc: decodeName(decodeName(item.introduction)).replace(/<br>/g, '\n'),
source: 'tx',
}
}),
limit,
total: body.data.sum,
source: 'tx',
}
})
},
}
// getList
// getTags
// getListDetail
+30
View File
@@ -0,0 +1,30 @@
import type { HttpRequestObject } from '../types.ts'
import { httpFetch } from '../request.ts'
export default {
// regExps: {
// relWord: /RELWORD=(.+)/,
// },
requestObj: null as HttpRequestObject | null,
tipSearch(str) {
this.cancelTipSearch()
this.requestObj = httpFetch(`https://c.y.qq.com/splcloud/fcgi-bin/smartbox_new.fcg?is_xml=0&format=json&key=${encodeURIComponent(str)}&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0`, {
headers: {
Referer: 'https://y.qq.com/portal/player.html',
},
})
return this.requestObj.promise.then(({ statusCode, body }) => {
if (statusCode != 200 || body.code != 0) return Promise.reject(new Error('请求失败'))
return body.data
})
},
handleResult(rawData) {
return rawData.map(info => `${info.name} - ${info.singer}`)
},
cancelTipSearch() {
if (this.requestObj && this.requestObj.cancelHttp) this.requestObj.cancelHttp()
},
async search(str) {
return this.tipSearch(str).then(result => this.handleResult(result.song.itemlist))
},
}
+28
View File
@@ -0,0 +1,28 @@
import crypto from 'node:crypto'
const PART_1_INDEXES = [23, 14, 6, 36, 16, 40, 7, 19]
const PART_2_INDEXES = [16, 1, 32, 12, 19, 27, 8, 5]
const SCRAMBLE_VALUES = [89, 39, 179, 150, 218, 82, 58, 252, 177, 52, 186, 123, 120, 64, 242, 133, 143, 161, 121, 179]
async function hashSHA1(data) {
return crypto.createHash('sha1').update(data).digest('hex')
}
function pickHashByIdx(hash, indexes) {
return indexes.map((idx) => hash[idx]).join('')
}
function base64Encode(data) {
return Buffer.from(data)
.toString('base64')
.replace(/[\\/+=]/g, '')
}
export async function zzcSign(text) {
const hash = await hashSHA1(text)
const part1 = pickHashByIdx(hash, PART_1_INDEXES)
const part2 = pickHashByIdx(hash, PART_2_INDEXES)
const part3 = SCRAMBLE_VALUES.map((value, i) => value ^ parseInt(hash.slice(i * 2, i * 2 + 2), 16))
const b64Part = base64Encode(part3).replace(/[\\/+=]/g, '')
return `zzc${part1}${b64Part}${part2}`.toLowerCase()
}
+45
View File
@@ -0,0 +1,45 @@
import type { HttpRequestObject } from '../../types.ts'
import { httpFetch } from '../../request.ts'
import { zzcSign } from './crypto.ts'
export const signRequest = async(data) => {
// console.log(data)
const sign = await zzcSign(JSON.stringify(data))
// console.log('sign', sign)
return httpFetch(`https://u.y.qq.com/cgi-bin/musics.fcg?sign=${sign}`, {
method: 'post',
headers: {
'User-Agent': 'QQMusic 14090508(android 12)',
},
body: data,
}).promise
}
/**
* musicu.fcg 通用请求(comm 参数对齐榜单模块的可用配置;
* musichallSinger/musichallAlbum 的部分详情接口在该通道已停用,见各模块说明)
*/
export const createMusicuFetch = async(data, retryNum = 0) => {
if (retryNum > 2) throw new Error('try max num')
let result
try {
result = await httpFetch('https://u.y.qq.com/cgi-bin/musicu.fcg', {
method: 'post',
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
},
body: {
comm: { uin: 0, format: 'json', ct: 20, cv: 1859 },
...data,
},
}).promise
} catch (err) {
console.log(err)
return createMusicuFetch(data, ++retryNum)
}
if (result.statusCode !== 200 || result.body.code != 0) return createMusicuFetch(data, ++retryNum)
return result.body
}