이지선다 조회수 자동: 빈 양식에서 조회수 열을 빼고, 올린 뒤 서버가 곡마다 토픽 음원 + MV 조회수를 불러와 더함. 짝은 유튜브 뮤직 노래↔동영상 전환(watch 응답의 counterpart, 쿠키 필요), 조회수는 로그인 없이 player videoDetails.viewCount(안 되면 watch 화면 숫자). quizzes/duel-views.ts가 pending 곡을 한 곡씩 처리(재시작해도 이어서), 쿠키 만료면 남은 곡 모두 이유와 함께 failed. 짝이 없는 곡은 있는 영상 하나만 쓰고 비고 표시. 파일·편집기에 적은 숫자는 그대로 쓰고 다시 불러오기에서 빠짐, 칸을 비우고 저장하면 자동. 편집기: 조회수(토픽·MV)·비고 칸, 불러오는 중 표시와 2초 폴링(저장 안 됨으로 안 잡힘), 조회수 다시 불러오기(전체/곡), 저장 때 편집기의 옛 사본이 서버가 불러온 값을 덮지 않음. 내보내기는 직접 넣은 숫자만 조회수 열에. 파일로 만들기는 조회수 열이 없으면 고른 종류 유지. 014 마이그레이션, 단위·API 테스트, e2e duel 단계, docs 04·10·12
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -78,12 +78,12 @@ export class YtMusic {
|
||||
this.mtime = mtime;
|
||||
}
|
||||
|
||||
async searchSongs(query: string): Promise<YtmSong[]> {
|
||||
private async post(endpoint: 'search' | 'next', body: Record<string, unknown>): Promise<any> {
|
||||
await this.reload();
|
||||
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`, {
|
||||
const res = await this.fetchImpl(`${ORIGIN}/youtubei/v1/${endpoint}?prettyPrint=false`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
@@ -94,17 +94,70 @@ export class YtMusic {
|
||||
'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) }),
|
||||
body: JSON.stringify({ context: { client: { clientName: 'WEB_REMIX', clientVersion: '1.20251015.01.00', hl: 'ko', gl: 'KR' } }, ...body }),
|
||||
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('유튜브 뮤직 로그인이 풀렸어요 — 쿠키 갱신 필요');
|
||||
if (!res.ok) throw new Error(`ytmusic ${endpoint} ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async searchSongs(query: string): Promise<YtmSong[]> {
|
||||
const json = await this.post('search', { query, params: decodeURIComponent(SONGS_PARAMS) });
|
||||
if (!loggedIn(json)) throw new CookieError('유튜브 뮤직 로그인이 풀렸어요 — 쿠키 갱신 필요');
|
||||
return parseSearch(json);
|
||||
}
|
||||
|
||||
/** The 노래 ↔ 동영상 pair of a video (이지선다 조회수 자동): what the video is and the other half, if YouTube Music has one. */
|
||||
async songPair(videoId: string): Promise<SongPair> {
|
||||
const json = await this.post('next', {
|
||||
videoId,
|
||||
playlistId: `RDAMVM${videoId}`,
|
||||
isAudioOnly: true,
|
||||
enablePersistentPlaylistPanel: true,
|
||||
tunerSettingValue: 'AUTOMIX_SETTING_NORMAL',
|
||||
watchEndpointMusicSupportedConfigs: { watchEndpointMusicConfig: { hasPersistentPlaylistPanel: true, musicVideoType: 'MUSIC_VIDEO_TYPE_ATV' } },
|
||||
});
|
||||
const pair = parseSongPair(json, videoId);
|
||||
// signed out, YouTube Music sends the queue without the pairs
|
||||
if (!pair.other && !loggedIn(json)) throw new CookieError('유튜브 뮤직 로그인이 풀렸어요 — 쿠키 갱신 필요');
|
||||
return pair;
|
||||
}
|
||||
}
|
||||
|
||||
const loggedIn = (json: any) => JSON.stringify(json?.responseContext?.serviceTrackingParams ?? []).includes('"logged_in","value":"1"');
|
||||
|
||||
/** ATV = 토픽 (art track, the 노래 side) · OMV = official music video · UGC = other uploads · … */
|
||||
export interface SongPair {
|
||||
type: string | null;
|
||||
other: { videoId: string; type: string | null } | null;
|
||||
}
|
||||
|
||||
const videoType = (r: any): string | null => r?.navigationEndpoint?.watchEndpoint?.watchEndpointMusicSupportedConfigs?.watchEndpointMusicConfig?.musicVideoType ?? null;
|
||||
|
||||
/**
|
||||
* The queue of a watch response: each entry is a playlistPanelVideoRenderer, or for songs that have both halves a
|
||||
* playlistPanelVideoWrapperRenderer with the one asked for (primaryRenderer) and its counterpart. The entry of `videoId`.
|
||||
*/
|
||||
export function parseSongPair(json: unknown, videoId: string): SongPair {
|
||||
const entries: any[] = [];
|
||||
const walk = (v: unknown) => {
|
||||
if (!v || typeof v !== 'object') return;
|
||||
if (Array.isArray(v)) return v.forEach(walk);
|
||||
const o = v as Record<string, any>;
|
||||
if (o.playlistPanelVideoWrapperRenderer || o.playlistPanelVideoRenderer) return void entries.push(o);
|
||||
for (const x of Object.values(o)) walk(x);
|
||||
};
|
||||
walk(json);
|
||||
for (const e of entries) {
|
||||
const w = e.playlistPanelVideoWrapperRenderer;
|
||||
const self = w ? w.primaryRenderer?.playlistPanelVideoRenderer : e.playlistPanelVideoRenderer;
|
||||
if (self?.videoId !== videoId) continue;
|
||||
const c = w?.counterpart?.[0]?.counterpartRenderer?.playlistPanelVideoRenderer;
|
||||
return { type: videoType(self), other: c?.videoId && c.videoId !== videoId ? { videoId: c.videoId, type: videoType(c) } : null };
|
||||
}
|
||||
return { type: null, other: null };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user