diff --git a/.gitignore b/.gitignore index 97633ff..8d06288 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ node_modules/ .next/ +.next-*/ out/ .DS_Store *.log diff --git a/eslint.config.mjs b/eslint.config.mjs index 52ca236..5c9e351 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -17,6 +17,7 @@ const eslintConfig = defineConfig([ globalIgnores([ // Default ignores of eslint-config-next: ".next/**", + ".next-*/**", "out/**", "build/**", "next-env.d.ts", diff --git a/next.config.ts b/next.config.ts index d441857..9d20e4d 100644 --- a/next.config.ts +++ b/next.config.ts @@ -8,9 +8,18 @@ const serverApiBaseUrl = ( ).replace(/\/+$/, ""); const nextConfig: NextConfig = { + distDir: process.env.NEXT_DIST_DIR || ".next", output: "standalone", async rewrites() { return [ + { + source: "/api/music/:path*", + destination: "/api/music/:path*", + }, + { + source: "/api/music", + destination: "/api/music", + }, { source: "/api/:path*", destination: `${serverApiBaseUrl}/:path*`, diff --git a/package-lock.json b/package-lock.json index ff65576..9462c0a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,7 @@ "lucide-react": "^1.21.0", "next": "16.2.9", "ogl": "^1.0.11", + "opencc-js": "^1.4.0", "react": "19.2.4", "react-dom": "19.2.4" }, @@ -5683,6 +5684,12 @@ "integrity": "sha512-kUpC154AFfxi16pmZUK4jk3J+8zxwTWGPo03EoYA8QPbzikHoaC82n6pNTbd+oEaJonaE8aPWBlX7ad9zrqLsA==", "license": "Unlicense" }, + "node_modules/opencc-js": { + "version": "1.4.0", + "resolved": "https://registry.npmmirror.com/opencc-js/-/opencc-js-1.4.0.tgz", + "integrity": "sha512-SEb4huI5+lT4CFPA4sgs+NAOOgpcmdHZ+vYxhRLR1bQWIt6VRwpFPjWgTJAWAg1MviDcXTBe5zVoUOVxVxNK8w==", + "license": "MIT AND Apache-2.0" + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmmirror.com/optionator/-/optionator-0.9.4.tgz", diff --git a/package.json b/package.json index 7b63976..d685a8f 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "version": "0.1.0", "private": true, "scripts": { - "dev": "next dev", + "dev": "next dev --turbo", "build": "next build", "start": "next start", "lint": "eslint" @@ -20,6 +20,7 @@ "lucide-react": "^1.21.0", "next": "16.2.9", "ogl": "^1.0.11", + "opencc-js": "^1.4.0", "react": "19.2.4", "react-dom": "19.2.4" }, diff --git a/src/api/config.ts b/src/api/config.ts index 942223a..74228d4 100644 --- a/src/api/config.ts +++ b/src/api/config.ts @@ -1,10 +1,38 @@ import request, { getServerApiURL } from './request' +import { cache } from 'react' + +export interface PublicConfigItem { + configKey: string + configValue: string +} export function getPublicConfig() { return request.get('/config/public') } export async function fetchPublicConfigForServer(init?: Parameters[1]) { - const response = await fetch(getServerApiURL('/config/public'), init) - return response.json() + try { + const response = await fetch(getServerApiURL('/config/public'), { + ...init, + // 容错超时防刷屏 + signal: AbortSignal.timeout(3000) + }) + if (!response.ok) { + return { code: response.status, data: [] } + } + return await response.json() + } catch { + // 静默兜底,避免打印庞大的 Socket 异常日志 + return { code: 500, data: [] } + } } + +export const getPublicConfigSnapshot = cache(async (): Promise => { + const payload = await fetchPublicConfigForServer({ next: { revalidate: 10 } }) + if (payload.code !== 200 || !Array.isArray(payload.data)) return [] + return payload.data.filter((item: unknown): item is PublicConfigItem => { + if (!item || typeof item !== 'object') return false + const candidate = item as Partial + return typeof candidate.configKey === 'string' && typeof candidate.configValue === 'string' + }) +}) diff --git a/src/api/music.ts b/src/api/music.ts new file mode 100644 index 0000000..750ebb7 --- /dev/null +++ b/src/api/music.ts @@ -0,0 +1,272 @@ +import axios, { AxiosError } from 'axios'; +import { + ApiSearchResult, + MusicApiErrorPayload, + MusicSource, + TrackDetail, +} from '@/interface/music'; + +const MUSIC_API_URL = '/api/music'; + +export class MusicApiError extends Error { + code: MusicApiErrorPayload['code']; + status?: number; + + constructor(message: string, code: MusicApiErrorPayload['code'] = 'UPSTREAM_UNAVAILABLE', status?: number) { + super(message); + this.name = 'MusicApiError'; + this.code = code; + this.status = status; + } +} + +function normalizeMusicError(error: unknown) { + if (error instanceof MusicApiError) return error; + if (error instanceof AxiosError) { + const payload = error.response?.data as Partial | undefined; + return new MusicApiError( + payload?.message || '音乐服务暂时不可用', + payload?.code || 'UPSTREAM_UNAVAILABLE', + error.response?.status, + ); + } + return new MusicApiError(error instanceof Error ? error.message : '音乐服务暂时不可用'); +} + +export function buildMusicStreamUrl(id: string, source: MusicSource = 'netease', name?: string, br = 320000) { + const params = new URLSearchParams({ types: 'stream', source, id, br: String(br) }); + if (name) params.set('name', name); + return `${MUSIC_API_URL}?${params.toString()}`; +} + +import { toSimplifiedChinese } from '@/lib/chinese'; + +/** + * 搜索音乐列表 + * @param name 搜索关键词(歌曲/歌手/专辑) + * @param source 音乐源 (默认 netease) + * @param count 返回数量 + */ +export async function searchMusic( + name: string, + source: MusicSource = 'netease', + count = 12 +): Promise { + if (!name.trim()) return []; + try { + const res = await axios.get(MUSIC_API_URL, { + params: { + types: 'search', + source, + name: name.trim(), + count, + pages: 1, + }, + timeout: 8000, + }); + const items = Array.isArray(res.data) ? res.data : []; + return items.map((item) => ({ + ...item, + name: toSimplifiedChinese(item.name || ''), + artist: Array.isArray(item.artist) + ? item.artist.map((a) => toSimplifiedChinese(a)) + : toSimplifiedChinese(item.artist || ''), + album: toSimplifiedChinese(item.album || ''), + })); + } catch (error) { + throw normalizeMusicError(error); + } +} + +/** + * 获取音频真实播放 URL (320k 优先) + */ +export async function fetchMusicUrl( + id: string, + source: MusicSource = 'netease', + br = 320000 +): Promise { + try { + const res = await axios.get(MUSIC_API_URL, { + params: { + types: 'url', + source, + id, + br, + }, + timeout: 8000, + }); + return res.data?.url || ''; + } catch (error) { + throw normalizeMusicError(error); + } +} + +/** + * 获取专辑封面 URL + */ +export async function fetchMusicPic( + picId: string, + source: MusicSource = 'netease', + size = 300 +): Promise { + if (!picId) return ''; + if (picId.startsWith('http://') || picId.startsWith('https://')) { + return picId; + } + try { + const res = await axios.get(MUSIC_API_URL, { + params: { + types: 'pic', + source, + id: picId, + size, + }, + timeout: 6000, + }); + return res.data?.url || ''; + } catch (error) { + throw normalizeMusicError(error); + } +} + +/** + * 获取 LRC 歌词 + */ +export async function fetchMusicLyric( + lyricId: string, + source: MusicSource = 'netease', + name?: string +): Promise<{ lyric: string; tlyric: string }> { + if (!lyricId && !name) return { lyric: '', tlyric: '' }; + try { + const res = await axios.get(MUSIC_API_URL, { + params: { + types: 'lyric', + source, + id: lyricId || name, + ...(name ? { name } : {}), + }, + timeout: 6000, + }); + return { + lyric: toSimplifiedChinese(res.data?.lyric || ''), + tlyric: toSimplifiedChinese(res.data?.tlyric || ''), + }; + } catch (error) { + throw normalizeMusicError(error); + } +} + +/** + * 懒加载解析:当用户点击播放搜索出来的曲目时,按需请求音频 URL 和 封面 + */ +export async function resolveTrackDetails(searchResult: ApiSearchResult): Promise { + const rawArtist = Array.isArray(searchResult.artist) + ? searchResult.artist.join(' / ') + : searchResult.artist || '未知歌手'; + const formattedArtist = toSimplifiedChinese(rawArtist); + + const [coverResult, lyricResult] = await Promise.allSettled([ + fetchMusicPic(searchResult.pic_id, searchResult.source), + fetchMusicLyric(searchResult.lyric_id || searchResult.id, searchResult.source, searchResult.name), + ]); + + let cover = coverResult.status === 'fulfilled' ? coverResult.value : ''; + if (!cover && (searchResult.pic_id?.startsWith('http://') || searchResult.pic_id?.startsWith('https://'))) { + cover = searchResult.pic_id; + } + + const lyrics = lyricResult.status === 'fulfilled' + ? lyricResult.value + : { lyric: '', tlyric: '' }; + + return { + id: searchResult.id, + title: toSimplifiedChinese(searchResult.name), + artist: formattedArtist, + album: toSimplifiedChinese(searchResult.album || '单曲'), + src: buildMusicStreamUrl(searchResult.url_id || searchResult.id, searchResult.source, searchResult.name), + cover, + picId: searchResult.pic_id, + urlId: searchResult.url_id || searchResult.id, + lyricId: searchResult.lyric_id || searchResult.id, + lyric: lyrics.lyric, + tlyric: lyrics.tlyric, + source: searchResult.source, + }; +} + +export interface ParsedPlaylist { + source: MusicSource; + id: string; +} + +/** + * 智能解析网易云音乐歌单分享链接或纯数字ID + */ +export function parsePlaylistUrl(input: string, defaultSource: MusicSource = 'netease'): ParsedPlaylist | null { + const text = input.trim(); + if (!text) return null; + + // 网易云音乐 (netease) + if (text.includes('163.com') || text.includes('163cn.tv')) { + const idMatch = text.match(/[?&]id=(\d+)/); + if (idMatch) return { source: 'netease', id: idMatch[1] }; + } + + // 纯数字/字母 ID,默认设为 netease + if (/^[a-zA-Z0-9_]+$/.test(text)) { + return { source: defaultSource, id: text }; + } + + return null; +} + +/** + * 歌单导入:1 次请求拉取全歌单元数据,每首曲目的播放流与资源采用懒加载机制 + */ +export async function fetchPlaylist( + id: string, + source: MusicSource = 'netease' +): Promise { + try { + const res = await axios.get(MUSIC_API_URL, { + params: { + types: 'playlist', + source, + id, + }, + timeout: 12000, + }); + + const items = Array.isArray(res.data) ? res.data : []; + if (items.length === 0) { + throw new MusicApiError('未在歌单中找到有效曲目,请检查歌单ID或公开权限', 'TRACK_UNAVAILABLE'); + } + + return items.map((item) => { + const rawArtist = Array.isArray(item.artist) + ? item.artist.join(' / ') + : item.artist || '未知歌手'; + const formattedArtist = toSimplifiedChinese(rawArtist); + + return { + id: item.id, + title: toSimplifiedChinese(item.name || '未知曲目'), + artist: formattedArtist, + album: toSimplifiedChinese(item.album || '歌单导入'), + src: buildMusicStreamUrl(item.url_id || item.id, item.source || source, item.name), + cover: '', + picId: item.pic_id, + urlId: item.url_id || item.id, + lyricId: item.lyric_id || item.id, + lyric: '', + tlyric: '', + source: item.source || source, + }; + }); + } catch (error) { + throw normalizeMusicError(error); + } +} diff --git a/src/app/api/music/route.ts b/src/app/api/music/route.ts new file mode 100644 index 0000000..6729406 --- /dev/null +++ b/src/app/api/music/route.ts @@ -0,0 +1,395 @@ +import { isIP } from 'node:net'; +import { NextResponse } from 'next/server'; +import type { MusicApiErrorCode, MusicSource } from '@/interface/music'; + +const MUSIC_API_URL = 'https://music-api.gdstudio.xyz/api.php'; +const ALLOWED_SOURCES = new Set(['netease', 'tencent', 'kugou', 'kuwo', 'bilibili', 'joox']); +const ALLOWED_TYPES = new Set(['search', 'url', 'pic', 'lyric', 'stream', 'playlist']); + +function errorResponse(code: MusicApiErrorCode, message: string, status: number) { + return NextResponse.json({ code, message }, { status }); +} + +function isPrivateIpv4(hostname: string) { + const parts = hostname.split('.').map(Number); + if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part))) return false; + return parts[0] === 10 || parts[0] === 127 || + (parts[0] === 169 && parts[1] === 254) || + (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) || + (parts[0] === 192 && parts[1] === 168); +} + +function isSafeStreamUrl(value: string) { + try { + const url = new URL(value); + const hostname = url.hostname.toLowerCase(); + if ((url.protocol !== 'https:' && url.protocol !== 'http:') || hostname === 'localhost' || hostname.endsWith('.local')) return false; + if (isPrivateIpv4(hostname)) return false; + if (isIP(hostname) === 6 && (hostname === '::1' || hostname.startsWith('fc') || hostname.startsWith('fd'))) return false; + return true; + } catch { + return false; + } +} + +async function requestMusicApi( + requestType: string, + params: { source: MusicSource; name?: string; id?: string; br?: string; size?: string; count?: string; pages?: string }, +) { + const targetUrl = new URL(MUSIC_API_URL); + targetUrl.searchParams.set('types', requestType); + targetUrl.searchParams.set('source', params.source); + if (params.name) targetUrl.searchParams.set('name', params.name); + if (params.id) targetUrl.searchParams.set('id', params.id); + if (params.br) targetUrl.searchParams.set('br', params.br); + if (params.size) targetUrl.searchParams.set('size', params.size); + if (params.count) targetUrl.searchParams.set('count', params.count); + if (params.pages) targetUrl.searchParams.set('pages', params.pages); + + const response = await fetch(targetUrl, { + headers: { + Accept: 'application/json, text/plain, */*', + 'Accept-Language': 'zh-CN,zh;q=0.9', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122 Safari/537.36', + }, + cache: requestType === 'url' ? 'no-store' : undefined, + next: requestType === 'url' ? undefined : { revalidate: 60 }, + signal: AbortSignal.timeout(8_000), + }); + + if (!response.ok) throw new Error(`第三方接口响应失败 (${response.status})`); + const text = await response.text(); + if (!text.trim()) throw new Error('第三方接口返回无内容'); + + let data: unknown; + try { + data = JSON.parse(text); + } catch { + throw new Error('解析第三方接口响应失败'); + } + + if (data && typeof data === 'object' && !Array.isArray(data)) { + const obj = data as Record; + if (obj.error && typeof obj.error === 'string' && obj.error.length > 0) throw new Error(obj.error); + if (obj.message && typeof obj.code === 'number' && obj.code !== 200 && obj.code !== 0) { + throw new Error(String(obj.message)); + } + } + + return data; +} + +/** + * 智能多源音频 URL 降级解析 + * 1. 尝试当前源不同码率 (320k -> 192k -> 128k) + * 2. 若缺少 name,根据 id 尝试查找歌名 + * 3. 跨源(netease -> kuwo -> joox -> bilibili)同名匹配多码率可播放音轨 + */ +async function resolveAudioUrlWithFallback(source: MusicSource, id: string, name?: string, br = '320000'): Promise { + const bitrates = [br, '320000', '192000', '128000'].filter((v, i, a) => a.indexOf(v) === i); + + // 1. 尝试当前源的多码率 + for (const rate of bitrates) { + try { + const res = (await requestMusicApi('url', { source, id, br: rate })) as { url?: string }; + if (res?.url && isSafeStreamUrl(res.url)) return res.url; + } catch { + // continue + } + } + + // 2. 如果缺少 name,尝试通过 search 反查歌名 + let trackName = name?.trim(); + if (!trackName) { + try { + const searchRes = (await requestMusicApi('search', { source, name: id, count: '1' })) as Array<{ name?: string }>; + if (Array.isArray(searchRes) && searchRes[0]?.name) { + trackName = searchRes[0].name; + } + } catch { + // ignore + } + } + + // 3. 跨源降级匹配同名音轨 (只使用 netease, kuwo, bilibili,绝不使用会偷换音轨的 joox) + if (trackName) { + const fallbackSources: MusicSource[] = (['netease', 'kuwo', 'bilibili'] as MusicSource[]).filter((s) => s !== source); + for (const fbSource of fallbackSources) { + try { + const searchRes = (await requestMusicApi('search', { source: fbSource, name: trackName, count: '3' })) as Array<{ id: string; name?: string }>; + if (Array.isArray(searchRes)) { + for (const item of searchRes) { + // 确保匹配到的歌曲名称包含要找的歌名关键字 + if (item.name && !item.name.toLowerCase().includes(trackName.toLowerCase()) && !trackName.toLowerCase().includes(item.name.toLowerCase())) { + continue; + } + for (const rate of ['320000', '128000']) { + try { + const fbUrlRes = (await requestMusicApi('url', { source: fbSource, id: item.id, br: rate })) as { url?: string }; + if (fbUrlRes?.url && isSafeStreamUrl(fbUrlRes.url)) { + return fbUrlRes.url; + } + } catch { + continue; + } + } + } + } + } catch { + continue; + } + } + } + + return ''; +} + +import { toSimplifiedChinese } from '@/lib/chinese'; + +/** + * 智能多源歌词降级解析 + * 当指定源(如 joox)无歌词时,自动尝试其他源(netease -> kuwo)检索同名曲目获取歌词 + */ +async function resolveLyricWithFallback(source: MusicSource, id: string, name?: string): Promise<{ lyric: string; tlyric: string; from: string }> { + try { + const res = (await requestMusicApi('lyric', { source, id })) as { lyric?: string; tlyric?: string; from?: string }; + if (res?.lyric && res.lyric.trim().length > 0) { + return { + lyric: toSimplifiedChinese(res.lyric), + tlyric: toSimplifiedChinese(res.tlyric || ''), + from: res.from || 'music.gdstudio.xyz', + }; + } + } catch { + // continue to fallback + } + + if (name) { + const fallbackSources: MusicSource[] = (['netease', 'kuwo', 'bilibili'] as MusicSource[]).filter((s) => s !== source); + for (const fbSource of fallbackSources) { + try { + const searchRes = (await requestMusicApi('search', { source: fbSource, name, count: '1' })) as Array<{ lyric_id?: string; id: string }>; + if (Array.isArray(searchRes) && searchRes.length > 0) { + const fbLyricRes = (await requestMusicApi('lyric', { source: fbSource, id: searchRes[0].lyric_id || searchRes[0].id })) as { lyric?: string; tlyric?: string; from?: string }; + if (fbLyricRes?.lyric && fbLyricRes.lyric.trim().length > 0) { + return { + lyric: toSimplifiedChinese(fbLyricRes.lyric), + tlyric: toSimplifiedChinese(fbLyricRes.tlyric || ''), + from: fbLyricRes.from || 'music.gdstudio.xyz', + }; + } + } + } catch { + continue; + } + } + } + + return { lyric: '', tlyric: '', from: 'music.gdstudio.xyz' }; +} + +export async function GET(request: Request) { + const { searchParams } = new URL(request.url); + const requestType = searchParams.get('types') || 'search'; + const source = (searchParams.get('source') || 'netease') as MusicSource; + const name = searchParams.get('name')?.trim() || ''; + const id = searchParams.get('id')?.trim() || ''; + const br = searchParams.get('br') || '320000'; + const size = searchParams.get('size') || '300'; + const count = searchParams.get('count') || '12'; + const pages = searchParams.get('pages') || '1'; + + if (!ALLOWED_TYPES.has(requestType)) return errorResponse('INVALID_REQUEST', '不支持的音乐请求类型', 400); + if (!ALLOWED_SOURCES.has(source)) return errorResponse('INVALID_REQUEST', '不支持的音乐来源', 400); + if (requestType === 'search' && !name) return errorResponse('INVALID_REQUEST', '搜索关键词不能为空', 400); + if (requestType !== 'search' && !id) return errorResponse('INVALID_REQUEST', '曲目标识不能为空', 400); + + const params = { source, name, id, br, size, count, pages }; + + try { + if (requestType === 'search') { + let data = await requestMusicApi('search', params); + if (Array.isArray(data) && data.length === 0) { + const fallbackSource: MusicSource = source === 'netease' ? 'kuwo' : 'netease'; + data = await requestMusicApi('search', { ...params, source: fallbackSource }); + } + return NextResponse.json(Array.isArray(data) ? data : []); + } + + if (requestType === 'lyric') { + const lyricData = await resolveLyricWithFallback(source, id, name); + return NextResponse.json(lyricData); + } + + if (requestType === 'stream') { + const audioUrl = await resolveAudioUrlWithFallback(source, id, name, br); + if (!audioUrl) { + return errorResponse('TRACK_UNAVAILABLE', '全网暂无可用的音频播放路径', 404); + } + return NextResponse.redirect(audioUrl, { status: 302 }); + } + + if (requestType === 'playlist') { + if (source === 'tencent') { + const dataPayload = { + req_0: { + module: 'music.srfDissInfo.aiDissInfo', + method: 'uniform_get_Dissinfo', + param: { disstid: Number(id) || id, enc_host_uin: '' }, + }, + }; + const qqUrl = `https://u.y.qq.com/cgi-bin/musicu.fcg?g_tk=5381&format=json&data=${encodeURIComponent(JSON.stringify(dataPayload))}`; + const response = await fetch(qqUrl, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + Referer: 'https://y.qq.com/', + }, + signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) throw new Error(`QQ音乐接口响应失败 (${response.status})`); + const json = await response.json(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const songlist = json?.req_0?.data?.songlist || []; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const items = songlist.map((song: any) => ({ + id: song.mid || String(song.id), + name: song.name || song.title || '未知曲目', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + artist: Array.isArray(song.singer) ? song.singer.map((s: any) => s.name) : (song.singer?.name || '未知歌手'), + album: song.album?.name || 'QQ音乐歌单', + pic_id: song.album?.mid ? `https://y.gtimg.cn/music/photo_new/T002R300x300M000${song.album.mid}.jpg` : (song.mid || String(song.id)), + url_id: song.name, + lyric_id: song.mid || String(song.id), + source: 'tencent', + })); + return NextResponse.json(items); + } + + if (source === 'kugou') { + const kgUrl = `https://mobilecdnbj.kugou.com/api/v3/special/song?specialid=${encodeURIComponent(id)}&page=1&pagesize=100`; + const response = await fetch(kgUrl, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + }, + signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) throw new Error(`酷狗音乐接口响应失败 (${response.status})`); + const json = await response.json(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const songlist = json?.data?.info || []; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const items = songlist.map((item: any) => { + const parts = (item.filename || '').split(' - '); + const artist = parts.length > 1 ? parts[0].trim() : '未知歌手'; + const name = parts.length > 1 ? parts.slice(1).join(' - ').trim() : (item.filename || '未知曲目'); + return { + id: item.hash || String(item.audio_id), + name, + artist, + album: '酷狗歌单', + pic_id: item.hash, + url_id: name, + lyric_id: item.hash, + source: 'kugou', + }; + }); + return NextResponse.json(items); + } + + if (source === 'netease') { + try { + const neteaseUrl = `https://music.163.com/api/v1/playlist/detail?id=${encodeURIComponent(id)}`; + const response = await fetch(neteaseUrl, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + Referer: 'https://music.163.com/', + }, + signal: AbortSignal.timeout(10_000), + }); + if (response.ok) { + const json = await response.json(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const playlistData = json?.playlist || json?.result; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const trackIds = (playlistData?.trackIds || []).map((t: any) => t.id).filter(Boolean); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let rawTracks: any[] = []; + + if (trackIds.length > 0) { + const chunkSize = 500; + for (let i = 0; i < Math.min(trackIds.length, 1000); i += chunkSize) { + const chunkIds = trackIds.slice(i, i + chunkSize); + const cParam = JSON.stringify(chunkIds.map((tid: number | string) => ({ id: tid }))); + const detailUrl = `https://music.163.com/api/v3/song/detail?c=${encodeURIComponent(cParam)}`; + const detailRes = await fetch(detailUrl, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + Referer: 'https://music.163.com/', + }, + signal: AbortSignal.timeout(10_000), + }); + if (detailRes.ok) { + const detailJson = await detailRes.json(); + if (Array.isArray(detailJson?.songs)) { + rawTracks.push(...detailJson.songs); + } + } + } + } + + if (rawTracks.length === 0) { + rawTracks = playlistData?.tracks || []; + } + + if (Array.isArray(rawTracks) && rawTracks.length > 0) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const items = rawTracks.map((track: any) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const artistList = track.ar || track.artists || []; + const artist = Array.isArray(artistList) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ? artistList.map((a: any) => a.name).join(' / ') + : (artistList.name || '未知歌手'); + const album = track.al?.name || track.album?.name || '网易云歌单'; + const picId = track.al?.picUrl || track.album?.picUrl || track.al?.pic_str || track.al?.pic || track.album?.picId || String(track.id); + + return { + id: String(track.id), + name: track.name || '未知曲目', + artist, + album, + pic_id: String(picId), + url_id: String(track.id), + lyric_id: String(track.id), + source: 'netease', + }; + }); + return NextResponse.json(items); + } + } + } catch { + // fallback to requestMusicApi + } + } + + const data = await requestMusicApi('playlist', params); + return NextResponse.json(Array.isArray(data) ? data : []); + } + + const data = await requestMusicApi(requestType, params); + if (requestType === 'url' && !(data as { url?: string })?.url) { + const audioUrl = await resolveAudioUrlWithFallback(source, id, name, br); + if (audioUrl) { + return NextResponse.json({ url: audioUrl }); + } + return errorResponse('TRACK_UNAVAILABLE', '全网暂无可用的音频播放路径', 404); + } + return NextResponse.json(data); + } catch (error) { + const message = error instanceof Error + ? (error.name === 'TimeoutError' ? '音乐服务响应超时' : error.message) + : '音乐服务暂时不可用'; + return errorResponse('UPSTREAM_UNAVAILABLE', message, 502); + } +} diff --git a/src/app/globals.css b/src/app/globals.css index 7c03091..efbeef9 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -388,6 +388,8 @@ html.lenis, html.lenis body { transition here so the scroll-scrubbed cross-dissolve is not double-eased. */ } + + .footer-peekers-floating-image { position: relative; z-index: 1; @@ -580,4 +582,17 @@ nextjs-portal, #__next-prerender-indicator { display: none !important; } +/* 黑胶唱片 360 度平滑旋转动画 */ +@keyframes spin-linear { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} + +.animate-spin-slow { + animation: spin-linear 20s linear infinite; +} diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 914d3d4..f7ea657 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -3,13 +3,13 @@ import { Inter, Cormorant_Garamond, Playfair_Display, Space_Grotesk, Space_Mono, import "./globals.css"; import Navbar from "@/components/Navbar"; import Footer from "@/components/Footer"; -import FloatingFooterPeekers from "@/components/ui/FloatingFooterPeekers"; import SmoothScroll from "@/components/ui/SmoothScroll"; import StyleConsole from "@/components/ui/StyleConsole"; import BackToTop from "@/components/ui/BackToTop"; -import TapeStation from "@/components/ui/TapeStation"; +import ArchivePlayer from "@/components/ui/ArchivePlayer"; import ThemeApplier from "@/components/ui/ThemeApplier"; -import { fetchPublicConfigForServer } from "@/api/config"; +import { getPublicConfigSnapshot } from "@/api/config"; +import { SysConfigProvider } from "@/hooks/useSysConfig"; const inter = Inter({ variable: "--font-inter", @@ -65,21 +65,13 @@ const maShanZheng = Ma_Shan_Zheng({ export async function generateMetadata(): Promise { let title = "春风不解别离 | 个人生活档案馆"; let faviconUrl = "/icon.png"; - try { - const data = await fetchPublicConfigForServer({ next: { revalidate: 10 } }); - if (data.code === 200 && Array.isArray(data.data)) { - const titleItem = data.data.find((c: any) => c.configKey === "site.title.default"); - if (titleItem?.configValue) { - title = titleItem.configValue; - } - const favItem = data.data.find((c: any) => c.configKey === "site.favicon.url"); - if (favItem?.configValue) { - faviconUrl = favItem.configValue; - } + const configs = await getPublicConfigSnapshot(); + const titleItem = configs.find((config) => config.configKey === "site.title.default"); + if (titleItem?.configValue) title = titleItem.configValue; + const faviconItem = configs.find((config) => config.configKey === "site.favicon.url"); + if (faviconItem?.configValue) { + faviconUrl = faviconItem.configValue; } - } catch (e) { - console.warn("Failed to fetch root metadata:", e); - } return { title, @@ -90,17 +82,20 @@ export async function generateMetadata(): Promise { }; } -export default function RootLayout({ +export default async function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { + const configs = await getPublicConfigSnapshot(); + return ( + {/* 1. 全局底色层 (z-0) */}
@@ -129,17 +124,15 @@ export default function RootLayout({
- {/* 5. 全站底部趴窗装饰,接近 footer 时停靠到 footer 顶部 */} - - {/* 6. 悬浮的视觉控制中心 */} {/* 7. 全局回到顶部按钮 */} - {/* 8. 治愈系磁带播放器 */} - + {/* 8. 沉浸式音乐播放器 */} + +
); diff --git a/src/app/letter/page.tsx b/src/app/letter/page.tsx index fa1ed0a..3c89559 100644 --- a/src/app/letter/page.tsx +++ b/src/app/letter/page.tsx @@ -37,7 +37,6 @@ export default function LetterPage() { content: item.content || "", images: item.images || "" })); - console.log("[岁月信箱] 动态加载的未来信札列表:", list); setLetters(list); } } catch (err) { diff --git a/src/app/page.tsx b/src/app/page.tsx index d9aeb40..e92bbb5 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -3,7 +3,8 @@ import { galleryData } from "@/data/gallery"; import { writingData, Post } from "@/data/writing"; import { getBlogsList } from "@/api/blogs"; import { getGalleryList } from "@/api/gallery"; -import { getPublicConfig } from "@/api/config"; +import { getPublicConfigSnapshot } from "@/api/config"; +import { reportUnexpectedFallback } from "@/lib/fallback-log"; async function getFeaturedPosts(): Promise { try { @@ -23,7 +24,7 @@ async function getFeaturedPosts(): Promise { })).slice(0, 3); } } catch (err) { - console.warn("Home page: API unavailable, using local writingData static fallback.", err); + reportUnexpectedFallback("home-posts", "首页文章使用本地数据", err); } return writingData.slice(0, 3); } @@ -48,33 +49,23 @@ async function getFeaturedPhotos(): Promise { })).slice(0, 4); } } catch (err) { - console.warn("Home page gallery: API unavailable, using local galleryData static fallback.", err); + reportUnexpectedFallback("home-gallery", "首页相册使用本地数据", err); } return galleryData.slice(0, 4); } async function getPublicConfigs(): Promise> { - try { - const res = await getPublicConfig(); - const data = res.data; - if (data && data.code === 200 && Array.isArray(data.data)) { - const configMap: Record = {}; - data.data.forEach((item: any) => { - configMap[item.configKey] = item.configValue; - }); - return configMap; - } - } catch (err) { - console.warn("Home page configs: API unavailable, using empty config fallback.", err); - } - return {}; + const configs = await getPublicConfigSnapshot(); + return Object.fromEntries(configs.map((item) => [item.configKey, item.configValue])); } export default async function HomePage() { - const featuredPosts = await getFeaturedPosts(); - const featuredPhotos = await getFeaturedPhotos(); - const configs = await getPublicConfigs(); + const [featuredPosts, featuredPhotos, configs] = await Promise.all([ + getFeaturedPosts(), + getFeaturedPhotos(), + getPublicConfigs(), + ]); return (
- {heroBgUrl ? ( + {heroBgUrl && !mediaFailed ? ( heroBgUrl.match(/\.(mp4|webm|ogg|mov|m4v)($|\?)/i) ? (