Files
music_quiz/apps/server/src/collector/ytmusic.ts
EJClaw cec9f8bdc9 3단계 노래 DB: 곡 스키마(장르·기준별 단계·가사·후보), 노라보세·스타맵 가져오기, 유튜브 원곡 찾기(쿠키 노래 검색 + 로그인 없는 Topic 대체), 관리자 노래·수집 화면
- 노라보세: 8,572곡(멜론 ID·연도·최고순위·장르·5단계 난이도·가사), 500 나는 묶음은 반씩 나눠 재요청, 원본 캐시로 재실행 안전
- 스타맵 803곡: 같은 곡은 합치고(363) 새 곡 440, 맵 제작자 연도(올해)는 버림
- 유튜브: 제목·가수·길이 점수로 확정/후보, 퍼가기 금지 영상 제외, 검색 방식별로 시도 기록
- 관리자: 노래 검색·장르·연도·난이도·유튜브 상태·출처 필터, 편집 패널(미리듣기·후보 선택·하이라이트·별칭·숨김), 수집 기록
- 테스트 32개, e2e에 노래 편집 단계 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 20:31:43 +09:00

150 lines
6.6 KiB
TypeScript

/**
* YouTube Music "노래" search with the user's cookie (docs/08 §1, docs/12 쿠키 — song search only).
* Same approach as music_bot_v2: WEB_REMIX client + SAPISIDHASH.
*/
export interface YtmSong {
videoId: string;
title: string;
artists: string;
album: string | null;
durationSec: number | null;
/** Only set by the plain YouTube fallback: true when the channel is an official "… - Topic" art-track channel. */
topic?: boolean;
}
export class CookieError extends Error {}
const ORIGIN = 'https://music.youtube.com';
/** "Songs" filter of the search tab. */
const SONGS_PARAMS = 'EgWKAQIIAWoKEAoQCRADEAQQBQ%3D%3D';
export function parseDuration(s: string): number | null {
const m = /^(?:(\d+):)?(\d{1,2}):(\d{2})$/.exec(s.trim());
if (!m) return null;
return Number(m[1] ?? 0) * 3600 + Number(m[2]) * 60 + Number(m[3]);
}
/** Pulls song rows out of a search response (musicResponsiveListItemRenderer). */
export function parseSearch(json: unknown): YtmSong[] {
const out: YtmSong[] = [];
const walk = (v: unknown) => {
if (!v || typeof v !== 'object') return;
if (Array.isArray(v)) return v.forEach(walk);
const r = (v as Record<string, any>).musicResponsiveListItemRenderer;
if (r) {
const videoId = r.playlistItemData?.videoId ?? r.overlay?.musicItemThumbnailOverlayRenderer?.content?.musicPlayButtonRenderer?.playNavigationEndpoint?.watchEndpoint?.videoId;
const cols: string[] = (r.flexColumns ?? []).map((c: any) => (c.musicResponsiveListItemFlexColumnRenderer?.text?.runs ?? []).map((x: any) => x.text).join(''));
if (videoId && cols[0]) {
// second column: "아티스트 • 앨범 • 3:15" (songs filter)
const parts = (cols[1] ?? '').split(' • ');
const last = parts[parts.length - 1] ?? '';
const dur = parseDuration(last);
out.push({ videoId, title: cols[0], artists: parts[0] ?? '', album: parts.length >= 3 ? parts[1]! : null, durationSec: dur });
}
return;
}
for (const x of Object.values(v)) walk(x);
};
walk(json);
return out;
}
export class YtMusic {
constructor(
private cookie: string,
private fetchImpl: typeof fetch = fetch,
) {}
static async fromFile(path: string): Promise<YtMusic> {
const cookie = (await Bun.file(path).text()).trim();
if (!/(?:^|; )SAPISID=/.test(cookie)) throw new CookieError('쿠키에 SAPISID가 없어요.');
return new YtMusic(cookie);
}
async searchSongs(query: string): Promise<YtmSong[]> {
const sapisid = /(?:^|; )SAPISID=([^;]+)/.exec(this.cookie)![1]!;
const ts = Math.floor(Date.now() / 1000);
const hash = new Bun.CryptoHasher('sha1').update(`${ts} ${sapisid} ${ORIGIN}`).digest('hex');
const res = await this.fetchImpl(`${ORIGIN}/youtubei/v1/search?prettyPrint=false`, {
method: 'POST',
headers: {
'content-type': 'application/json',
cookie: this.cookie,
origin: ORIGIN,
'x-origin': ORIGIN,
authorization: `SAPISIDHASH ${ts}_${hash}`,
'x-goog-authuser': '0',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36',
},
body: JSON.stringify({ context: { client: { clientName: 'WEB_REMIX', clientVersion: '1.20251015.01.00', hl: 'ko', gl: 'KR' } }, query, params: decodeURIComponent(SONGS_PARAMS) }),
signal: AbortSignal.timeout(15_000),
});
if (res.status === 401 || res.status === 403) throw new CookieError(`유튜브 뮤직 인증 실패(${res.status}) — 쿠키 갱신 필요`);
if (res.status === 429) throw new Error('rate limited (429)');
if (!res.ok) throw new Error(`ytmusic search ${res.status}`);
const json: any = await res.json();
const loggedIn = JSON.stringify(json?.responseContext?.serviceTrackingParams ?? []).includes('"logged_in","value":"1"');
if (!loggedIn) throw new CookieError('유튜브 뮤직 로그인이 풀렸어요 — 쿠키 갱신 필요');
return parseSearch(json);
}
}
/**
* Fallback without login (docs/08 매칭 순서 2): plain YouTube search "{artist} {title} topic", parsed from videoRenderer.
* Weaker than the 노래 tab, so non-Topic results are marked and scored down (score.ts).
*/
export function parseWebSearch(json: unknown): YtmSong[] {
const out: YtmSong[] = [];
const walk = (v: unknown) => {
if (!v || typeof v !== 'object') return;
if (Array.isArray(v)) return v.forEach(walk);
const r = (v as Record<string, any>).videoRenderer;
if (r?.videoId) {
const channel: string = r.ownerText?.runs?.[0]?.text ?? '';
const topic = / - Topic$/.test(channel);
out.push({
videoId: r.videoId,
title: (r.title?.runs ?? []).map((x: any) => x.text).join(''),
artists: topic ? channel.replace(/ - Topic$/, '') : channel,
album: null,
durationSec: r.lengthText?.simpleText ? parseDuration(r.lengthText.simpleText) : null,
topic,
});
return;
}
for (const x of Object.values(v)) walk(x);
};
walk(json);
return out;
}
export class YtWeb {
constructor(private fetchImpl: typeof fetch = fetch) {}
async searchSongs(query: string): Promise<YtmSong[]> {
const res = await this.fetchImpl('https://www.youtube.com/youtubei/v1/search?prettyPrint=false', {
method: 'POST',
headers: { 'content-type': 'application/json', 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36' },
body: JSON.stringify({ context: { client: { clientName: 'WEB', clientVersion: '2.20251015.01.00', hl: 'ko', gl: 'KR' } }, query: `${query} topic` }),
signal: AbortSignal.timeout(15_000),
});
if (res.status === 429) throw new Error('rate limited (429)');
if (!res.ok) throw new Error(`youtube search ${res.status}`);
return parseWebSearch(await res.json());
}
}
/** YouTube Music with the cookie when it is still logged in, else the plain YouTube fallback. */
export async function pickSearcher(cookiePath: string, log: (s: string) => void, requireCookie = false): Promise<{ searchSongs: (q: string) => Promise<YtmSong[]>; kind: 'ytmusic' | 'youtube' }> {
try {
const ytm = await YtMusic.fromFile(cookiePath);
await ytm.searchSongs('아이유 좋은 날');
return { searchSongs: (q) => ytm.searchSongs(q), kind: 'ytmusic' };
} catch (e) {
if (!(e instanceof CookieError) || requireCookie) throw e;
log(`유튜브 뮤직 쿠키를 쓸 수 없어요(${e.message}) → 일반 유튜브 검색(Topic 채널 우선)으로 대신 찾습니다`);
const web = new YtWeb();
return { searchSongs: (q) => web.searchSongs(q), kind: 'youtube' };
}
}