refactor(api)!: 平台 id 回退——joox/5sing/bili/apple 恢复全名,目录对齐 bd/mg
- 撤销 3381e9b/1b972ec 中 jx/5s/bl/ap 四个短码,恢复 joox/5sing/bili/apple; qian→bd、migu→mg 保留 - 目录与文件对齐保留的新 id:sdk/qian/→sdk/bd/、sdk/migu/→sdk/mg/、 sdk/apis/qian.ts→bd.ts、migu.ts→mg.ts、src/http/migu-stream.ts→mg-stream.ts (规则改为「目录=对外 id」,聚合入口的模块变量同步更名;music.migu.cn 等域名、 上游 music-lib 对照注释、miguGet 等功能标识符不动) - 对外 id 全表:kw kg tx wy qs xm me qt lr mg bd joox 5sing bili apple **破坏性变更**:joox/5sing/bili/apple 四平台的 URL、/sources 返回与 data/auth.json 凭据键恢复全名,已存短码键的登录态需重新登录。 验证:typecheck ✓、pnpm test 112/112 ✓
This commit is contained in:
1 parent
8c02fb5c15
commit
e1357dd412
50 files changed
+178
-178
No files matched your search
+180
@@ -0,0 +1,180 @@
|
||||
// 千千音乐专辑
|
||||
// 搜索:/v1/search?type=3(特殊字符触发 errno 23001 时用清洗后的关键词重试,见 searchAlbumItems)
|
||||
// 详情:/v1/album/info?albumAssetCode=P...(P 码可直接用;纯数字旧 id 走 /v1/album/albumid2psid 转换)
|
||||
// 专辑链接:https://music.91q.com/album/<albumAssetCode>
|
||||
import { APP_ID, apiGet, apiOk, joinArtists, normalizeAlbumAssetCode, mapTrack, releaseDate10, sanitizeAlbumKeyword, albumLink } from './util.ts'
|
||||
|
||||
export interface QianAlbumSearchItem {
|
||||
albumAssetCode?: string
|
||||
title?: string
|
||||
pic?: string
|
||||
introduce?: string
|
||||
releaseDate?: string
|
||||
genre?: string
|
||||
lang?: string
|
||||
artist?: any[]
|
||||
trackList?: any[]
|
||||
}
|
||||
|
||||
const mapAlbumSummary = (item: QianAlbumSearchItem) => {
|
||||
const id = normalizeAlbumAssetCode(item?.albumAssetCode)
|
||||
return {
|
||||
id,
|
||||
name: String(item?.title ?? '').trim(),
|
||||
cover: String(item?.pic ?? '').trim(),
|
||||
trackCount: Array.isArray(item?.trackList) ? item.trackList.length : 0,
|
||||
creator: joinArtists(item?.artist),
|
||||
description: String(item?.introduce ?? '').trim(),
|
||||
releaseDate: releaseDate10(item?.releaseDate),
|
||||
genre: String(item?.genre ?? '').trim(),
|
||||
lang: String(item?.lang ?? '').trim(),
|
||||
link: id ? albumLink(id) : '',
|
||||
source: 'bd' as const,
|
||||
}
|
||||
}
|
||||
|
||||
/** 单次专辑搜索;23001(词非法)时抛出带 retryWithSanitized 标记的错误 */
|
||||
const searchAlbumOnce = async(word: string, page = 1, limit = 10) => {
|
||||
const body = await apiGet('/v1/search', {
|
||||
word,
|
||||
type: '3',
|
||||
pageNo: String(Math.max(1, page)),
|
||||
pageSize: String(Math.max(1, limit)),
|
||||
appid: APP_ID,
|
||||
})
|
||||
if (!apiOk(body)) {
|
||||
const err: any = new Error(body?.errmsg || `千千专辑搜索失败(errno ${body?.errno})`)
|
||||
err.retryWithSanitized = Number(body?.errno) === 23001
|
||||
throw err
|
||||
}
|
||||
const list = body?.data?.typeAlbum
|
||||
return Array.isArray(list) ? (list as QianAlbumSearchItem[]) : []
|
||||
}
|
||||
|
||||
/** 上游 searchAlbumItems:原词失败(23001)时用 sanitizeQianqianAlbumKeyword 清洗后重试一次 */
|
||||
export const searchAlbumItems = async(keyword: string, page = 1, limit = 10): Promise<QianAlbumSearchItem[]> => {
|
||||
const words = [String(keyword ?? '').trim()]
|
||||
const sanitized = sanitizeAlbumKeyword(keyword)
|
||||
if (sanitized && sanitized !== words[0]) words.push(sanitized)
|
||||
|
||||
let lastErr: Error | null = null
|
||||
for (const word of words) {
|
||||
try {
|
||||
return await searchAlbumOnce(word, page, limit)
|
||||
} catch (err: any) {
|
||||
lastErr = err
|
||||
// 仅 23001 允许换清洗后的词重试;其余错误(网络/服务端)直接上抛
|
||||
if (!err?.retryWithSanitized) break
|
||||
}
|
||||
}
|
||||
if (lastErr) throw lastErr
|
||||
return []
|
||||
}
|
||||
|
||||
/** 搜索专辑(返回歌单/专辑统一摘要形状) */
|
||||
export const searchAlbum = async(keyword: string, page = 1, limit = 10) => {
|
||||
const word = String(keyword ?? '').trim()
|
||||
const empty = { source: 'bd' as const, list: [] as any[], total: 0, page, limit }
|
||||
if (!word) return empty
|
||||
|
||||
const items = await searchAlbumItems(word, page, limit)
|
||||
const list = items
|
||||
.map(mapAlbumSummary)
|
||||
.filter((album) => album.id)
|
||||
.slice(0, limit)
|
||||
return { source: 'bd' as const, list, total: items.length, page, limit }
|
||||
}
|
||||
|
||||
/** 旧数字专辑 id → PSID(P 码);已是 P 码则原样返回 */
|
||||
export const resolveAlbumAssetCode = async(id: string): Promise<string> => {
|
||||
const raw = String(id ?? '').trim()
|
||||
if (!raw) throw new Error('千千专辑 id 为空')
|
||||
|
||||
const normalized = normalizeAlbumAssetCode(raw)
|
||||
if (normalized) return normalized
|
||||
|
||||
const body = await apiGet('/v1/album/albumid2psid', { albumid: raw, appid: APP_ID })
|
||||
if (!apiOk(body)) throw new Error(body?.errmsg || `千千专辑 id 转换失败(errno ${body?.errno})`)
|
||||
for (const item of Array.isArray(body?.data) ? body.data : []) {
|
||||
const psid = normalizeAlbumAssetCode(item?.psid)
|
||||
if (psid) return psid
|
||||
}
|
||||
throw new Error('千千专辑 asset code 未找到')
|
||||
}
|
||||
|
||||
const fetchAlbumInfo = async(id: string) => {
|
||||
const albumId = await resolveAlbumAssetCode(id)
|
||||
const body = await apiGet('/v1/album/info', { albumAssetCode: albumId, appid: APP_ID })
|
||||
if (!apiOk(body)) throw new Error(body?.errmsg || `千千专辑详情获取失败(errno ${body?.errno})`)
|
||||
const data = body?.data ?? {}
|
||||
if (!normalizeAlbumAssetCode(data?.albumAssetCode)) throw new Error('千千专辑不存在或已下架')
|
||||
return { albumId, data }
|
||||
}
|
||||
|
||||
/** 专辑详情(MusicServer 统一形状;album/info 一次返回全部曲目,这里按 page/limit 切片) */
|
||||
export const getAlbumDetail = async(id: string, page = 1, limit = 30) => {
|
||||
const { albumId, data } = await fetchAlbumInfo(id)
|
||||
const title = String(data?.title ?? '').trim()
|
||||
const cover = String(data?.pic ?? '').trim()
|
||||
const creator = joinArtists(data?.artist)
|
||||
const all = Array.isArray(data?.trackList) ? data.trackList : []
|
||||
|
||||
const list = all
|
||||
.map((item: any) => {
|
||||
const song = mapTrack(item, { albumId, albumName: title, img: cover, singer: creator })
|
||||
return {
|
||||
...song,
|
||||
// 专辑内曲目补上时长/序号(上游 Extra.track / sort)
|
||||
track: Number(item?.sort) > 0 ? Number(item.sort) : undefined,
|
||||
}
|
||||
})
|
||||
.filter((song: any) => song.songmid)
|
||||
|
||||
const start = (Math.max(1, page) - 1) * Math.max(1, limit)
|
||||
const paged = list.slice(start, start + Math.max(1, limit))
|
||||
|
||||
const albumInfo = {
|
||||
id: albumId,
|
||||
name: title,
|
||||
img: cover,
|
||||
desc: String(data?.introduce ?? '').trim(),
|
||||
author: creator,
|
||||
releaseDate: releaseDate10(data?.releaseDate),
|
||||
genre: String(data?.genre ?? '').trim(),
|
||||
lang: String(data?.lang ?? '').trim(),
|
||||
total: list.length,
|
||||
}
|
||||
|
||||
return {
|
||||
source: 'bd' as const,
|
||||
info: albumInfo,
|
||||
list: paged,
|
||||
page,
|
||||
limit,
|
||||
total: list.length,
|
||||
allPage: Math.ceil(list.length / Math.max(1, limit)) || 1,
|
||||
}
|
||||
}
|
||||
|
||||
/** 上游 GetAlbumSongs:只取曲目列表 */
|
||||
export const getAlbumSongs = async(id: string) => {
|
||||
const { list } = await getAlbumDetail(id, 1, 10000)
|
||||
return list
|
||||
}
|
||||
|
||||
/** 上游 ParseAlbum:支持 P 码链接 / albumAssetCode= / albumid= 三种形态 */
|
||||
export const parseAlbumLink = async(link: string) => {
|
||||
const raw = String(link ?? '').trim()
|
||||
const patterns = [
|
||||
/music\.91q\.com\/album\/([A-Za-z0-9]+)/,
|
||||
/albumAssetCode=([A-Za-z0-9]+)/,
|
||||
/albumid=(\d+)/,
|
||||
]
|
||||
for (const pattern of patterns) {
|
||||
const match = pattern.exec(raw)
|
||||
if (match) return getAlbumDetail(match[1])
|
||||
}
|
||||
throw new Error('无效的千千专辑链接')
|
||||
}
|
||||
|
||||
export default { searchAlbum, searchAlbumItems, getAlbumDetail, getAlbumSongs, parseAlbumLink, resolveAlbumAssetCode }
|
||||
@@ -0,0 +1,86 @@
|
||||
// 千千音乐(music.91q.com)平台模块
|
||||
// 上游 music-lib/qianqian 的 Node/TS 移植。匿名可用面(2026-10-02 实测):
|
||||
// 搜索(type=1)/ 专辑搜索+详情(type=3、album/info)/ 歌单详情+分类+分类歌单 /
|
||||
// 歌词(song/info 返回 txt URL)/ 免费曲目 128k/320k/flac 明文直链(tracklink 签名通道)。
|
||||
// 限制:
|
||||
// - VIP/版权曲目 tracklink 无 path(需登录态会员 cookie),搜索保留但标记 payPlay;
|
||||
// - 歌单关键词搜索(/v1/search?type=6)服务端已下线(errno 23001),searchPlaylist 返回空列表;
|
||||
// - 上游 GetUserPlaylists 明确 Unsupported,本移植不提供 userPlaylist。
|
||||
// 凭据:上游 New(cookie) 的 cookie 从 sdk/auth/store.ts 的 getCredentials('bd') 读取(可选)。
|
||||
import bdApi from '../apis/bd.ts'
|
||||
import musicSearch from './musicSearch.ts'
|
||||
import lyric from './lyric.ts'
|
||||
import { getSongInfo } from './musicInfo.ts'
|
||||
import album from './album.ts'
|
||||
import playlist from './playlist.ts'
|
||||
import parse from './parse.ts'
|
||||
import { getQianCookie } from './util.ts'
|
||||
|
||||
const bd = {
|
||||
musicSearch,
|
||||
|
||||
getMusicUrl(songInfo, type) {
|
||||
return bdApi.getMusicUrl(songInfo, type)
|
||||
},
|
||||
|
||||
getLyric(songInfo) {
|
||||
return lyric.getLyric(songInfo)
|
||||
},
|
||||
|
||||
// 千千无独立封面接口;搜索结果/专辑/歌单均自带 pic,缺失时回退 song/info
|
||||
async getPic(songInfo) {
|
||||
if (songInfo?.img) return songInfo.img
|
||||
try {
|
||||
const info = await getSongInfo(String(songInfo?.songmid ?? ''))
|
||||
return info?.img || null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
|
||||
getMusicInfo(songInfo) {
|
||||
return getSongInfo(String(songInfo?.songmid ?? ''))
|
||||
},
|
||||
|
||||
getMusicDetailPageUrl(songInfo) {
|
||||
const tsid = String(songInfo?.songmid ?? '').trim()
|
||||
return tsid ? `https://music.91q.com/song/${tsid}` : 'https://music.91q.com/'
|
||||
},
|
||||
|
||||
album: {
|
||||
getAlbumDetail: album.getAlbumDetail,
|
||||
searchAlbum: album.searchAlbum,
|
||||
parseAlbumLink: album.parseAlbumLink,
|
||||
},
|
||||
|
||||
// MusicServer 的 songList 契约:getList(sortId, tagId, page) / getTags()
|
||||
// 千千无“榜单”概念,这里以歌单分类作为标签体系(tagId 为 /v1/tracklist/category 的 subCate id)
|
||||
songList: {
|
||||
getList(sortId, tagId, page = 1) {
|
||||
const cate = String(tagId || sortId || '').trim()
|
||||
return playlist.getCategoryPlaylists(/^\d+$/.test(cate) ? cate : '', page, 30)
|
||||
},
|
||||
getTags() {
|
||||
return playlist.getCategories()
|
||||
},
|
||||
},
|
||||
|
||||
playlist: {
|
||||
searchPlaylist: playlist.searchPlaylist,
|
||||
getPlaylistDetail: playlist.getPlaylistDetail,
|
||||
getPlaylistSongs: playlist.getPlaylistSongs,
|
||||
getCategories: playlist.getCategories,
|
||||
getCategoryPlaylists: playlist.getCategoryPlaylists,
|
||||
parsePlaylistLink: playlist.parsePlaylistLink,
|
||||
},
|
||||
|
||||
parse,
|
||||
}
|
||||
|
||||
/** 凭据存在性(cookie 仅用于 VIP/登录态资源,匿名不影响搜索与免费取流) */
|
||||
export const status = () => {
|
||||
const cookie = getQianCookie()
|
||||
return cookie ? { logged: true } : { logged: false }
|
||||
}
|
||||
|
||||
export default bd
|
||||
@@ -0,0 +1,34 @@
|
||||
// 千千音乐歌词
|
||||
// 链路:/v1/song/info → data[0].lyric 为歌词文本 URL(static-qianqian.taihe.com/*.txt)→ 直接下载文本。
|
||||
// 返回 { lyric, tlyric: '' }(千千只有原文歌词,无翻译)。
|
||||
import { httpFetch } from '../common/request.ts'
|
||||
import { getSongInfo } from './musicInfo.ts'
|
||||
import { requestHeaders } from './util.ts'
|
||||
|
||||
export const getLyric = (songInfo: any) => {
|
||||
const requestObj: any = { promise: null, cancelHttp() {} }
|
||||
const tsid = String(songInfo?.songmid ?? songInfo?.TSID ?? '').trim()
|
||||
let lyricReq: any = null
|
||||
|
||||
requestObj.cancelHttp = () => {
|
||||
lyricReq?.cancelHttp?.()
|
||||
lyricReq = null
|
||||
}
|
||||
|
||||
requestObj.promise = (async() => {
|
||||
if (!tsid) throw new Error('千千歌词需要 songmid(TSID)')
|
||||
const info = await getSongInfo(tsid)
|
||||
const lyricUrl = info?.lyricUrl
|
||||
if (!lyricUrl) throw new Error('千千该歌曲暂无歌词')
|
||||
|
||||
lyricReq = httpFetch(lyricUrl, { headers: requestHeaders(), timeout: 15000 })
|
||||
const { statusCode, body, raw } = await lyricReq.promise as any
|
||||
if (statusCode != 200) throw new Error(`千千歌词下载失败(HTTP ${statusCode})`)
|
||||
const lyric = typeof body === 'string' ? body : raw?.toString('utf8') ?? ''
|
||||
return { lyric, tlyric: '' }
|
||||
})()
|
||||
|
||||
return requestObj
|
||||
}
|
||||
|
||||
export default { getLyric }
|
||||
@@ -0,0 +1,26 @@
|
||||
// 千千音乐单曲信息(/v1/song/info)
|
||||
// 接口返回 data[]:title/albumTitle/albumAssetCode/pic/duration/artist/lyric(歌词文本 URL)
|
||||
import { APP_ID, apiGet, apiOk, mapTrack } from './util.ts'
|
||||
|
||||
/** 由 TSID 取单曲信息(归一为 Song 形状,并附 lyricUrl) */
|
||||
export const getSongInfo = async(tsid: string) => {
|
||||
const id = String(tsid ?? '').trim()
|
||||
if (!id) throw new Error('千千歌曲 id(TSID)为空')
|
||||
const body = await apiGet('/v1/song/info', { TSID: id, appid: APP_ID })
|
||||
if (!apiOk(body) && !Array.isArray(body?.data)) {
|
||||
throw new Error(body?.errmsg || `千千歌曲信息获取失败(errno ${body?.errno})`)
|
||||
}
|
||||
const item = Array.isArray(body?.data) ? body.data[0] : null
|
||||
if (!item) throw new Error('千千歌曲不存在或已下架')
|
||||
|
||||
const song = mapTrack(item)
|
||||
return {
|
||||
...song,
|
||||
// 以入参 id 兜底(song/info 的 TSID 字段缺失时仍可继续取流/歌词)
|
||||
songmid: song.songmid || id,
|
||||
lyricUrl: String(item?.lyric ?? '').trim(),
|
||||
raw: item,
|
||||
}
|
||||
}
|
||||
|
||||
export default { getSongInfo }
|
||||
@@ -0,0 +1,35 @@
|
||||
// 千千音乐搜索(/v1/search?word=&type=1&pageNo=&pageSize=,appid + 签名)
|
||||
// 响应 data.typeTrack[]:TSID/title/albumTitle/albumAssetCode/pic/duration/artist/rateFileInfo/isVip
|
||||
// 注:上游会跳过 isVip != 0 的曲目(VIP 无法匿名取流);本实现保留并标记 payPlay,
|
||||
// 以便聚合搜索/顺播时仍能展示(取流失败会返回明确错误,路由可走兜底链路)。
|
||||
import { APP_ID, apiGet, apiOk, mapTrack } from './util.ts'
|
||||
|
||||
export const search = async(keyword: string, page = 1, limit = 20) => {
|
||||
const word = String(keyword ?? '').trim()
|
||||
const empty = { list: [] as any[], allPage: 1, total: 0, limit, source: 'bd' as const }
|
||||
if (!word) return empty
|
||||
|
||||
const body = await apiGet('/v1/search', {
|
||||
word,
|
||||
type: '1',
|
||||
pageNo: String(page),
|
||||
pageSize: String(limit),
|
||||
appid: APP_ID,
|
||||
})
|
||||
if (!apiOk(body) && Number(body?.errno) !== 23001) {
|
||||
throw new Error(body?.errmsg || `千千搜索失败(errno ${body?.errno})`)
|
||||
}
|
||||
const tracks = Array.isArray(body?.data?.typeTrack) ? body.data.typeTrack : []
|
||||
const total = Number(body?.data?.total) || tracks.length
|
||||
const haveMore = Number(body?.data?.haveMore) === 1
|
||||
|
||||
return {
|
||||
list: tracks.map((item: any) => mapTrack(item)).filter((song: any) => song.songmid),
|
||||
allPage: haveMore ? page + 1 : Math.max(page, Math.ceil(total / Math.max(1, limit)) || 1),
|
||||
total,
|
||||
limit,
|
||||
source: 'bd' as const,
|
||||
}
|
||||
}
|
||||
|
||||
export default { search }
|
||||
@@ -0,0 +1,35 @@
|
||||
// 千千音乐链接解析
|
||||
// 歌曲:music.91q.com/song/<TSID>(上游 Parse:取 song/info 后顺带取直链,失败不影响返回)
|
||||
// 专辑:music.91q.com/album/<P码> / ?albumAssetCode= / ?albumid=
|
||||
// 歌单:music.91q.com/songlist|tracklist|playlist/<id> / ?*id= / 裸歌单 id
|
||||
import { getDownloadUrl } from '../apis/bd.ts'
|
||||
import { getSongInfo } from './musicInfo.ts'
|
||||
import { parseAlbumLink } from './album.ts'
|
||||
import { parsePlaylistLink } from './playlist.ts'
|
||||
import { firstNonEmpty } from './util.ts'
|
||||
|
||||
const TSID_RE = /music\.91q\.com\/song\/(\w+)/
|
||||
|
||||
/** 上游 Parse:歌曲链接 → Song(尽力附带直链 url/type) */
|
||||
export const parseSong = async(link: string) => {
|
||||
const match = TSID_RE.exec(String(link ?? ''))
|
||||
if (!match) throw new Error('无效的千千歌曲链接')
|
||||
const tsid = match[1]
|
||||
|
||||
const song: any = await getSongInfo(tsid)
|
||||
try {
|
||||
const hit = await getDownloadUrl(tsid)
|
||||
song.url = hit.url
|
||||
song.type = hit.type
|
||||
} catch {
|
||||
// 与上游一致:直链获取失败忽略(VIP/下架曲目仍返回元数据)
|
||||
}
|
||||
delete song.lyricUrl
|
||||
delete song.raw
|
||||
return { ...song, songmid: firstNonEmpty(song.songmid, tsid), source: 'bd' as const }
|
||||
}
|
||||
|
||||
export const parseAlbum = async(link: string) => parseAlbumLink(link)
|
||||
export const parsePlaylist = async(link: string) => parsePlaylistLink(link)
|
||||
|
||||
export default { parseSong, parseAlbum, parsePlaylist }
|
||||
@@ -0,0 +1,158 @@
|
||||
// 千千音乐歌单
|
||||
// 详情:/v1/tracklist/info?id=&type=0&pageNo=&pageSize=(支持分页,默认 pageSize=20)
|
||||
// 分类:/v1/tracklist/category(group.categoryName + subCate[])
|
||||
// 分类歌单:/v1/tracklist/list?subCateId=&pageNo=&pageSize=(不传 subCateId 为全部)
|
||||
// 搜索:上游用 /v1/search?type=6,但 2026-10 实测服务端已下线该搜索类型
|
||||
// (errno 23001 "不被支持的搜索类型(10000)"),官网搜索页也只有 单曲/歌手/专辑 三个 tab;
|
||||
// 上游在 !state 时静默返回空列表,本实现保持一致并保留 typeSonglist 解析以备恢复。
|
||||
import { APP_ID, apiGet, apiOk, firstNonEmpty, mapTrack, playlistLink } from './util.ts'
|
||||
|
||||
const mapPlaylistSummary = (item: any) => {
|
||||
const id = item?.id == null ? '' : String(item.id)
|
||||
const rawDesc = String(item?.desc ?? '').trim()
|
||||
const tagList = Array.isArray(item?.tagList) ? item.tagList : []
|
||||
return {
|
||||
id,
|
||||
name: String(item?.title ?? '').trim(),
|
||||
cover: String(item?.pic ?? '').trim(),
|
||||
trackCount: Number(item?.trackCount ?? 0) || 0,
|
||||
creator: firstNonEmpty(item?.creator, item?.author, item?.userName, item?.nickName, item?.ownerName),
|
||||
description: rawDesc || tagList.join('、'),
|
||||
link: id ? playlistLink(id) : '',
|
||||
source: 'bd' as const,
|
||||
}
|
||||
}
|
||||
|
||||
/** 上游 SearchPlaylist(type=6 歌单搜索;服务端已停用,返回空列表) */
|
||||
export const searchPlaylist = async(keyword: string, page = 1, limit = 10) => {
|
||||
const word = String(keyword ?? '').trim()
|
||||
const empty = { source: 'bd' as const, list: [] as any[], total: 0, page, limit }
|
||||
if (!word) return empty
|
||||
|
||||
const body = await apiGet('/v1/search', {
|
||||
word,
|
||||
type: '6',
|
||||
pageNo: String(page),
|
||||
pageSize: String(limit),
|
||||
appid: APP_ID,
|
||||
})
|
||||
if (!body?.state) return empty
|
||||
|
||||
const items = Array.isArray(body?.data?.typeSonglist) ? body.data.typeSonglist : []
|
||||
const list = items.map(mapPlaylistSummary).filter((item: any) => item.id)
|
||||
return { source: 'bd' as const, list, total: Number(body?.data?.total) || list.length, page, limit }
|
||||
}
|
||||
|
||||
/** 歌单详情(含曲目;tracklist/info 支持 pageNo/pageSize) */
|
||||
export const getPlaylistDetail = async(id: string, page = 1, limit = 50) => {
|
||||
const playlistId = String(id ?? '').trim()
|
||||
if (!playlistId) throw new Error('千千歌单 id 为空')
|
||||
|
||||
const body = await apiGet('/v1/tracklist/info', {
|
||||
id: playlistId,
|
||||
type: '0',
|
||||
pageNo: String(Math.max(1, page)),
|
||||
pageSize: String(Math.max(1, limit)),
|
||||
appid: APP_ID,
|
||||
})
|
||||
if (!apiOk(body)) throw new Error(body?.errmsg || `千千歌单获取失败(errno ${body?.errno})`)
|
||||
|
||||
const data = body?.data ?? {}
|
||||
const rawTracks = Array.isArray(data?.trackList) ? data.trackList : []
|
||||
const list = rawTracks.map((item: any) => mapTrack(item)).filter((song: any) => song.songmid)
|
||||
|
||||
const title = firstNonEmpty(data?.title, playlistId)
|
||||
const tagList = Array.isArray(data?.tagList) ? data.tagList : []
|
||||
const cover = firstNonEmpty(data?.pic, list[0]?.img)
|
||||
const creator = firstNonEmpty(data?.creator, data?.author, data?.userName, data?.nickName, data?.ownerName)
|
||||
const description = firstNonEmpty(data?.desc, data?.description) || tagList.join('、')
|
||||
const total = Number(data?.trackCount) || list.length
|
||||
|
||||
return {
|
||||
source: 'bd' as const,
|
||||
info: { id: playlistId, name: title, img: cover, desc: description, author: creator, link: playlistLink(playlistId) },
|
||||
list,
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
allPage: Math.ceil(total / Math.max(1, limit)) || 1,
|
||||
}
|
||||
}
|
||||
|
||||
/** 上游 GetPlaylistSongs:只取曲目列表 */
|
||||
export const getPlaylistSongs = async(id: string) => {
|
||||
const { list } = await getPlaylistDetail(id, 1, 1000)
|
||||
return list
|
||||
}
|
||||
|
||||
/**
|
||||
* 上游 GetPlaylistCategories
|
||||
* 返回 { source, list: [{ id, name, group, count }] },首项为 "全部"(id='')。
|
||||
*/
|
||||
export const getCategories = async() => {
|
||||
const body = await apiGet('/v1/tracklist/category', { appid: APP_ID })
|
||||
if (!apiOk(body)) throw new Error(body?.errmsg || `千千歌单分类获取失败(errno ${body?.errno})`)
|
||||
|
||||
const list: Array<{ id: string; name: string; group: string; count?: number }> = [
|
||||
{ id: '', name: '全部', group: '全部' },
|
||||
]
|
||||
for (const group of Array.isArray(body?.data) ? body.data : []) {
|
||||
const groupName = String(group?.categoryName ?? '').trim()
|
||||
for (const item of Array.isArray(group?.subCate) ? group.subCate : []) {
|
||||
const id = String(item?.id ?? '').trim()
|
||||
const name = String(item?.categoryName ?? '').trim()
|
||||
if (!id || !name) continue
|
||||
list.push({ id, name, group: groupName, count: Number(item?.count ?? 0) || 0 })
|
||||
}
|
||||
}
|
||||
return { source: 'bd' as const, list }
|
||||
}
|
||||
|
||||
/** 上游 GetCategoryPlaylists(page >= 1,limit 1..100) */
|
||||
export const getCategoryPlaylists = async(categoryId: string | number, page = 1, limit = 30) => {
|
||||
const cateId = String(categoryId ?? '').trim()
|
||||
const pageNo = Math.max(1, Number(page) || 1)
|
||||
const pageSize = Math.min(100, Math.max(1, Number(limit) || 30))
|
||||
|
||||
const params: Record<string, any> = { appid: APP_ID, pageNo: String(pageNo), pageSize: String(pageSize) }
|
||||
if (cateId) params.subCateId = cateId
|
||||
|
||||
const body = await apiGet('/v1/tracklist/list', params)
|
||||
if (!apiOk(body)) throw new Error(body?.errmsg || `千千分类歌单获取失败(errno ${body?.errno})`)
|
||||
|
||||
const result = Array.isArray(body?.data?.result) ? body.data.result : []
|
||||
const list = result
|
||||
.map((item: any) => ({ ...mapPlaylistSummary(item), categoryId: cateId }))
|
||||
.filter((item: any) => item.id)
|
||||
return {
|
||||
source: 'bd' as const,
|
||||
list,
|
||||
total: Number(body?.data?.total) || list.length,
|
||||
page: pageNo,
|
||||
limit: pageSize,
|
||||
}
|
||||
}
|
||||
|
||||
/** 上游 ParsePlaylist:songlist/tracklist/playlist 链接、*id= 参数、或裸歌单 id */
|
||||
export const parsePlaylistLink = async(link: string) => {
|
||||
const raw = String(link ?? '').trim()
|
||||
const patterns = [
|
||||
/music\.91q\.com\/(?:songlist|tracklist|playlist)\/([A-Za-z0-9]+)/,
|
||||
/(?:songlistid|tracklistid|playlistid|id)=([A-Za-z0-9]+)/,
|
||||
]
|
||||
for (const pattern of patterns) {
|
||||
const match = pattern.exec(raw)
|
||||
if (match) return getPlaylistDetail(match[1])
|
||||
}
|
||||
if (raw && !raw.includes('/')) return getPlaylistDetail(raw)
|
||||
throw new Error('无效的千千歌单链接')
|
||||
}
|
||||
|
||||
export default {
|
||||
searchPlaylist,
|
||||
getPlaylistDetail,
|
||||
getPlaylistSongs,
|
||||
getCategories,
|
||||
getCategoryPlaylists,
|
||||
parsePlaylistLink,
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
// 千千音乐(music.91q.com / 91q.com)公共请求层
|
||||
// 上游 music-lib/qianqian 的全部接口都走 /v1/*,参数 = 业务参数 + appid + timestamp + sign:
|
||||
// sign = md5(按 key 升序拼接 "k=v&..."(不含 sign)+ Secret)
|
||||
// 该平台匿名即可搜索 / 查专辑 / 查歌单 / 拿免费曲目直链;cookie 仅影响 VIP、收藏等登录态资源,
|
||||
// MusicServer 从 sdk/auth/store.ts 的 getCredentials('bd') 读取(可选,未登录留空)。
|
||||
import crypto from 'node:crypto'
|
||||
import { httpFetch } from '../common/request.ts'
|
||||
import { getCredentials } from '../auth/store.ts'
|
||||
|
||||
export const APP_ID = '16073360'
|
||||
export const SECRET = '0b50b02fd0d73a9c4c8c3a781c30845f'
|
||||
export const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36'
|
||||
export const REFERER = 'https://music.91q.com/player'
|
||||
export const API_BASE = 'https://music.91q.com'
|
||||
|
||||
/** 上游音质档位顺序(3000 = flac,其余为 kbps) */
|
||||
export const RATE_ORDER = ['3000', '320', '128', '64']
|
||||
|
||||
/** 千千平台 cookie(未绑定返回空串;上游所有请求都会带上该 header,此处保持一致) */
|
||||
export const getQianCookie = (): string => {
|
||||
const cred = getCredentials('bd') as { cookie?: string } | null
|
||||
return cred?.cookie ? String(cred.cookie) : ''
|
||||
}
|
||||
|
||||
/** 上游 signParams:写入当前秒级时间戳,按 key 字典序拼串后追加 Secret 做 md5 */
|
||||
export const signParams = (params: Record<string, any>): Record<string, any> => {
|
||||
const signed: Record<string, any> = { ...params, timestamp: String(Math.floor(Date.now() / 1000)) }
|
||||
const keys = Object.keys(signed).sort()
|
||||
const payload = keys.map((key) => `${key}=${signed[key]}`).join('&') + SECRET
|
||||
signed.sign = crypto.createHash('md5').update(payload, 'utf8').digest('hex')
|
||||
return signed
|
||||
}
|
||||
|
||||
export const signedUrl = (path: string, params: Record<string, any>): string =>
|
||||
`${API_BASE}${path}?${new URLSearchParams(signParams(params) as any).toString()}`
|
||||
|
||||
export const requestHeaders = (): Record<string, string> => {
|
||||
const cookie = getQianCookie()
|
||||
return {
|
||||
'User-Agent': USER_AGENT,
|
||||
Referer: REFERER,
|
||||
Accept: 'application/json, text/plain, */*',
|
||||
...(cookie ? { Cookie: cookie } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** 发起带签名的 GET,返回可取消的请求对象;promise resolve 为响应 JSON body */
|
||||
export const apiRequest = (path: string, params: Record<string, any>) => {
|
||||
const req = httpFetch(signedUrl(path, params), { headers: requestHeaders(), timeout: 15000 })
|
||||
req.promise = req.promise.then(({ statusCode, body }: any) => {
|
||||
if (statusCode != 200) throw new Error(`千千音乐接口失败(HTTP ${statusCode})`)
|
||||
return body ?? {}
|
||||
})
|
||||
return req
|
||||
}
|
||||
|
||||
/** 发起带签名的 GET,promise resolve 为响应 JSON body */
|
||||
export const apiGet = (path: string, params: Record<string, any>): Promise<any> =>
|
||||
apiRequest(path, params).promise as Promise<any>
|
||||
|
||||
/** 上游状态判定:state=true 或 errno=22000 视为成功 */
|
||||
export const apiOk = (body: any): boolean => body?.state === true || Number(body?.errno) === 22000
|
||||
|
||||
/** tracklink 单档位请求(data 内含 path/format/rate/size;VIP 曲目无 path) */
|
||||
export const trackLink = (tsid: string, rate: string, register?: (req: any) => void): Promise<any> => {
|
||||
const req = apiRequest('/v1/song/tracklink', { TSID: tsid, appid: APP_ID, rate })
|
||||
register?.(req)
|
||||
return req.promise as Promise<any>
|
||||
}
|
||||
|
||||
/** 时间格式 mm:ss(duration 为秒;0 显示 0) */
|
||||
export const intervalOf = (duration: any): string | number => {
|
||||
const seconds = Number(duration)
|
||||
if (!Number.isFinite(seconds) || seconds <= 0) return 0
|
||||
const m = Math.trunc(seconds / 60)
|
||||
const s = Math.trunc(seconds % 60)
|
||||
return `${m < 10 ? '0' + m : m}:${s < 10 ? '0' + s : s}`
|
||||
}
|
||||
|
||||
/** 千千歌手数组 → 展示名(优先 artistType=38 歌手;去重后以 、 连接) */
|
||||
export const joinArtists = (artists: any): string => {
|
||||
if (!Array.isArray(artists) || !artists.length) return ''
|
||||
const names: string[] = []
|
||||
const seen = new Set<string>()
|
||||
const add = (name: any) => {
|
||||
const n = String(name ?? '').trim()
|
||||
if (!n || seen.has(n)) return
|
||||
seen.add(n)
|
||||
names.push(n)
|
||||
}
|
||||
for (const item of artists) if (Number(item?.artistType) === 38) add(item?.name)
|
||||
if (!names.length) for (const item of artists) add(item?.name)
|
||||
return names.join('、')
|
||||
}
|
||||
|
||||
/** 上游 normalizeQianqianAlbumAssetCode:仅接受 p/P 开头(长度 >=2)并归一为大写 P */
|
||||
export const normalizeAlbumAssetCode = (id: any): string => {
|
||||
const s = String(id ?? '').trim()
|
||||
if (s.length < 2) return ''
|
||||
return s[0] === 'p' || s[0] === 'P' ? `P${s.slice(1)}` : ''
|
||||
}
|
||||
|
||||
/** 上游 sanitizeQianqianAlbumKeyword:特殊字符替换为空格并折叠空白(服务端 23001 时重试用) */
|
||||
export const sanitizeAlbumKeyword = (keyword: any): string => {
|
||||
const trimmed = String(keyword ?? '').trim()
|
||||
if (!trimmed) return ''
|
||||
return trimmed
|
||||
.replace(/[::"'“”‘’()()[\]【】,,/\\\-.]/g, ' ')
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
export const firstNonEmpty = (...values: any[]): string => {
|
||||
for (const value of values) {
|
||||
const s = String(value ?? '').trim()
|
||||
if (s) return s
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** 上游 qianqianReleaseDate:只取前 10 位(YYYY-MM-DD) */
|
||||
export const releaseDate10 = (raw: any): string => {
|
||||
const s = String(raw ?? '').trim()
|
||||
return s.length >= 10 ? s.slice(0, 10) : s
|
||||
}
|
||||
|
||||
/** 上游 qianqianRateStats:从 rateFileInfo 取最高可用档位的文件大小与码率(kbps) */
|
||||
export const rateStats = (rateFileInfo: any, duration: number): { size: number; bitrate: number } => {
|
||||
for (const rate of RATE_ORDER) {
|
||||
const info = rateFileInfo?.[rate]
|
||||
const size = Number(info?.size ?? 0)
|
||||
if (!info || !(size > 0)) continue
|
||||
if (duration > 0) return { size, bitrate: Math.trunc((size * 8) / 1000 / duration) }
|
||||
return { size, bitrate: rate === '3000' ? 800 : Number(rate) }
|
||||
}
|
||||
return { size: 0, bitrate: 0 }
|
||||
}
|
||||
|
||||
// 千千 rateFileInfo → MusicServer 既有 Quality 桶(64k 不参与 types 展示,仅影响取流回退)
|
||||
const RATE_LABEL: Record<string, '128k' | '320k' | 'flac'> = { '128': '128k', '320': '320k', '3000': 'flac' }
|
||||
|
||||
export const rateTypes = (rateFileInfo: any) => {
|
||||
const types: Array<{ type: '128k' | '320k' | 'flac'; size: string }> = []
|
||||
const _types: Partial<Record<'128k' | '320k' | 'flac', { size: string }>> = {}
|
||||
for (const rate of ['128', '320', '3000']) {
|
||||
const info = rateFileInfo?.[rate]
|
||||
const size = Number(info?.size ?? 0)
|
||||
if (!info || !(size > 0)) continue
|
||||
const label = RATE_LABEL[rate]
|
||||
const sizeText = sizeMB(size)
|
||||
types.push({ type: label, size: sizeText })
|
||||
_types[label] = { size: sizeText }
|
||||
}
|
||||
return { types, _types }
|
||||
}
|
||||
|
||||
const sizeMB = (size: number): string => {
|
||||
if (!size) return '0 B'
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
const i = Math.min(units.length - 1, Math.floor(Math.log(size) / Math.log(1024)))
|
||||
return `${(size / Math.pow(1024, i)).toFixed(2)} ${units[i]}`
|
||||
}
|
||||
|
||||
export interface MapTrackOptions {
|
||||
albumId?: string
|
||||
albumName?: string
|
||||
img?: string | null
|
||||
singer?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 千千曲目字段 → MusicServer 统一 Song 形状
|
||||
* 搜索用 TSID/albumAssetCode,专辑详情用 assetId(无 albumAssetCode,需外部补 albumId),
|
||||
* 歌单详情用 TSID + albumTitle + pic。
|
||||
* 注:上游 Search 会跳过 isVip != 0 的曲目;MusicServer 聚合列表保留它们并标记 payPlay,
|
||||
* 取流端对无直链的 VIP 曲目给出明确错误(路由可走外部音源/kw 兜底)。
|
||||
*/
|
||||
export const mapTrack = (item: any, opts: MapTrackOptions = {}) => {
|
||||
const duration = Number(item?.duration ?? 0)
|
||||
const stats = rateStats(item?.rateFileInfo, duration)
|
||||
const { types, _types } = rateTypes(item?.rateFileInfo)
|
||||
const albumId = firstNonEmpty(normalizeAlbumAssetCode(item?.albumAssetCode), opts.albumId)
|
||||
return {
|
||||
songmid: firstNonEmpty(item?.TSID, item?.assetId, item?.tsid),
|
||||
name: String(item?.title ?? '').trim(),
|
||||
singer: firstNonEmpty(joinArtists(item?.artist), opts.singer),
|
||||
albumId,
|
||||
albumName: firstNonEmpty(item?.albumTitle, opts.albumName),
|
||||
interval: intervalOf(duration),
|
||||
size: stats.size || 0,
|
||||
bitrate: stats.bitrate || 0,
|
||||
payPlay: Number(item?.isVip ?? 0) !== 0 || Number(item?.isPaid ?? 0) !== 0,
|
||||
img: firstNonEmpty(item?.pic, opts.img) || null,
|
||||
lrc: null,
|
||||
lrcx: '',
|
||||
types,
|
||||
_types,
|
||||
source: 'bd' as const,
|
||||
}
|
||||
}
|
||||
|
||||
export const songLink = (tsid: string): string => `https://music.91q.com/song/${tsid}`
|
||||
export const albumLink = (id: string): string => `https://music.91q.com/album/${id}`
|
||||
export const playlistLink = (id: string): string => `https://music.91q.com/songlist/${id}`
|
||||
|
||||
export default {
|
||||
APP_ID,
|
||||
SECRET,
|
||||
getUserAgent: () => USER_AGENT,
|
||||
getQianCookie,
|
||||
signParams,
|
||||
signedUrl,
|
||||
apiRequest,
|
||||
apiOk,
|
||||
trackLink,
|
||||
mapTrack,
|
||||
rateTypes,
|
||||
rateStats,
|
||||
sanitizeAlbumKeyword,
|
||||
normalizeAlbumAssetCode,
|
||||
}
|
||||
Reference in new issue
Block a user