info.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. console.log('bundle2!')
  2. printable = (platform) => {
  3. return platform === "WEB";
  4. }
  5. parseCodecs = (format) => {
  6. const mimeType = format['mimeType']
  7. if (!mimeType) {
  8. return {};
  9. }
  10. const regex = /(?<mimetype>[^/]+\/[^;]+)(?:;\s*codecs="?(?<codecs>[^"]+))?/;
  11. const match = mimeType.match(regex);
  12. if (!match) {
  13. return {};
  14. }
  15. const codecs = match.groups.codecs;
  16. if (!codecs) {
  17. return {};
  18. }
  19. const splitCodecs = codecs.trim().replace(/,$/, '').split(',').map(str => str.trim()).filter(Boolean);
  20. let vcodec = null;
  21. let acodec = null;
  22. for (const fullCodec of splitCodecs) {
  23. const codec = fullCodec.split('.')[0];
  24. if (['avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1', 'av01', 'theora'].includes(codec)) {
  25. if (!vcodec) {
  26. vcodec = fullCodec;
  27. }
  28. } else if (['mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'].includes(codec)) {
  29. if (!acodec) {
  30. acodec = fullCodec;
  31. }
  32. } else {
  33. console.log(`WARNING: Unknown codec ${fullCodec}`);
  34. }
  35. }
  36. if (!vcodec && !acodec) {
  37. if (splitCodecs.length === 2) {
  38. return {
  39. vcodec: splitCodecs[0],
  40. acodec: splitCodecs[1]
  41. };
  42. }
  43. } else {
  44. return {
  45. vcodec: vcodec,
  46. acodec: acodec
  47. };
  48. }
  49. return {};
  50. }
  51. parseSetCookie = (headers) => {
  52. if (!headers) {
  53. return ""
  54. }
  55. const setCookie = headers['Set-Cookie']
  56. if (!setCookie) {
  57. return ""
  58. }
  59. console.log(`setCookie: ${setCookie}`)
  60. let result = 'PREF=hl=en&tz=UTC; SOCS=CAI; GPS=1; ';
  61. const needCookieNames = ['YSC', 'VISITOR_INFO1_LIVE', 'VISITOR_PRIVACY_METADATA'];
  62. for (const i in needCookieNames) {
  63. const cookieName = needCookieNames[i];
  64. const regexp = new RegExp(`${cookieName}=([^;,]+)`)
  65. const match = setCookie.match(regexp)
  66. if (match && match.length === 2) {
  67. const cookieValue = match[1]
  68. if (i != needCookieNames.length - 1) {
  69. result += `${cookieName}=${cookieValue}; `
  70. } else {
  71. result += `${cookieName}=${cookieValue}`
  72. }
  73. }
  74. }
  75. console.log(`current cookie: ${result}`)
  76. return result;
  77. }
  78. request = async (method, url, data = null, headers = {}, platform) => {
  79. if (platform === "WEB") {
  80. url = url.replace("https://www.youtube.com", "http://127.0.0.1");
  81. }
  82. console.log(`request url:${url}`)
  83. console.log(`request data:${data}`)
  84. console.log(`request method:${method}`)
  85. console.log(`request headers:${JSON.stringify((headers))}`)
  86. if (platform === "WEB") {
  87. const res = await fetch(url, {
  88. 'mode': 'cors',
  89. 'method': method,
  90. 'headers': headers,
  91. 'body': data
  92. })
  93. const resData = await res.text()
  94. return Promise.resolve({
  95. 'data': resData,
  96. 'headers': res.headers
  97. });
  98. }
  99. return new Promise((resolve, reject) => {
  100. AF.request(url, method, data, headers, (data, headers, err) => {
  101. if (err) {
  102. reject(err);
  103. } else {
  104. console.log(`response headers: ${headers}`);
  105. resolve({
  106. 'data': data,
  107. 'headers': JSON.parse(headers)
  108. });
  109. }
  110. });
  111. })
  112. }
  113. getStringBetween = (string, needleStart, needleEnd, offsetStart = 0, offsetEnd = 0) => {
  114. const x = string.indexOf(needleStart);
  115. const y = needleEnd ? string.indexOf(needleEnd, x) : string.length;
  116. return string.substring(x + needleStart.length + offsetEnd, y + offsetStart);
  117. }
  118. findFunction = (jsCode, regexp, platform) => {
  119. const match = jsCode.match(regexp)
  120. if (!match && match.length <= 1) {
  121. return null;
  122. }
  123. let result = "";
  124. const dependencyMatches = match[0].match(/([$a-zA-Z0-9]+\.[$a-zA-Z0-9]+)/g)
  125. const existDependencies = [];
  126. if (dependencyMatches && dependencyMatches.length >= 1) {
  127. for (let currentMatch of dependencyMatches) {
  128. const varName = currentMatch.split('.')[0];
  129. if (existDependencies.includes(varName)) {
  130. continue
  131. }
  132. const varNameMatch = jsCode.match(new RegExp(`var \\${varName}={(.|\\n)*?};`), 'ig');
  133. if (varNameMatch && varNameMatch.length >= 1) {
  134. result += varNameMatch[0] + "\n";
  135. }
  136. existDependencies.push(varName);
  137. }
  138. }
  139. result += `\n${match[0]}`;
  140. if (printable(platform)) {
  141. console.log(`decipherFunction result: ` + result);
  142. }
  143. return eval(result);
  144. };
  145. const cache = {};
  146. fetchBaseJSContent = async (baseJsUrl, platform) => {
  147. const cacheKey = `jsContent:${baseJsUrl}`;
  148. if (cache[cacheKey]) {
  149. console.log(`baseContent from cache: ${baseJsUrl}`);
  150. return cache[cacheKey];
  151. }
  152. console.log(`extract baseUrl: ${baseJsUrl}`);
  153. const baseContentResp = await request('GET', baseJsUrl, null, {
  154. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.101 Safari/537.36',
  155. }, platform);
  156. const {data, _} = baseContentResp;
  157. cache[cacheKey] = data;
  158. return data;
  159. }
  160. extractJSSignatureFunction = async (baseJsUrl, platform) => {
  161. const cacheKey = `jsSign:${baseJsUrl}`
  162. if (cache[cacheKey]) {
  163. console.log(`jsSign from cache: ${baseJsUrl}`);
  164. return cache[cacheKey];
  165. }
  166. const baseJsContent = await fetchBaseJSContent(baseJsUrl, platform);
  167. const result = findFunction(baseJsContent, /([a-zA-Z0-9]+)=function\([a-zA-Z0-9]+\)\{a=a\.split\(""\).*};/, platform);
  168. cache[cacheKey] = result
  169. return result
  170. }
  171. extractNJSFunction = async (baseJsUrl, platform) => {
  172. const cacheKey = `jsN:${baseJsUrl}`
  173. if (cache[cacheKey]) {
  174. console.log(`jsN from cache: ${baseJsUrl}`);
  175. return cache[cacheKey];
  176. }
  177. const baseJsContent = await fetchBaseJSContent(baseJsUrl, platform);
  178. const result = findFunction(baseJsContent, /([a-zA-Z0-9]+)=function\([a-zA-Z0-9]+\)\{var b=a\.split\(""\)[\s\S]*?};/, platform);
  179. cache[cacheKey] = result
  180. return result
  181. }
  182. signUrl = async (signatureCipher, baseJsUrl, platform) => {
  183. const searchParams = {}
  184. for (const item of signatureCipher.split('&')) {
  185. const [key, value] = item.split('=');
  186. searchParams[decodeURIComponent(key)] = decodeURIComponent(value);
  187. }
  188. const [url, signature, sp] = [searchParams['url'], searchParams['s'], searchParams['sp']];
  189. const decipher = await extractJSSignatureFunction(baseJsUrl, platform);
  190. if (!decipher) {
  191. return null;
  192. }
  193. if (printable(platform)) {
  194. console.log(`signatureCipher=${signatureCipher}, url=${url}, signature=${signature}, sp=${sp}`)
  195. }
  196. let newUrl = `${url}&${sp}=${decipher(signature)}`;
  197. function replaceUrlParam(url, paramName, paramValue) {
  198. let pattern = new RegExp(`([?&])${paramName}=.*?(&|$)`, 'i');
  199. let newUrl = url.replace(pattern, `$1${paramName}=${paramValue}$2`);
  200. if (newUrl === url && url.indexOf('?') === -1) {
  201. newUrl += `?${paramName}=${paramValue}`;
  202. } else if (newUrl === url) {
  203. newUrl += `&${paramName}=${paramValue}`;
  204. }
  205. return newUrl;
  206. }
  207. for (const item of url.split('&')) {
  208. const [key, value] = item.split('=');
  209. searchParams[decodeURIComponent(key)] = decodeURIComponent(value);
  210. }
  211. const nFunction = await extractNJSFunction(baseJsUrl, platform);
  212. const n = searchParams['n']
  213. if (n && nFunction) {
  214. const newN = nFunction(n);
  215. return replaceUrlParam(newUrl, 'n', newN);
  216. }
  217. return newUrl;
  218. }
  219. detail = async (url, platform) => {
  220. try {
  221. const htmlResp = await request('GET', `${url}&bpctr=9999999999&has_verified=1`, null, {
  222. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
  223. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  224. 'Accept-Language': 'en-us,en;q=0.5',
  225. 'Sec-Fetch-Mode': 'navigate',
  226. 'Accept-Encoding': 'gzip, deflate, br',
  227. 'Cookie': 'PREF=hl=en&tz=UTC; SOCS=CAI'
  228. }, platform);
  229. let {data: html, headers: htmlHeaders} = htmlResp;
  230. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  231. let match = html.match(regex);
  232. if (!match || !match.length) {
  233. console.log('can not found JSON: ytInitialPlayerResponse');
  234. throw new Error('JSON not found: ytInitialPlayerResponse');
  235. }
  236. const ytInitialPlayerResponse = JSON.parse(match[1]);
  237. if (printable(platform)) {
  238. console.log(ytInitialPlayerResponse);
  239. }
  240. const originVideoDetails = ytInitialPlayerResponse['videoDetails'];
  241. const thumbnails = []
  242. for (const item of originVideoDetails['thumbnail']['thumbnails']) {
  243. thumbnails.push({
  244. 'url': item['url'],
  245. 'width': item['width'] + "",
  246. 'height': item['height'] + ""
  247. })
  248. }
  249. let originFormats = [];
  250. // android
  251. try {
  252. const apiKey = 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
  253. const apiUrl = `https://www.youtube.com/youtubei/v1/player?key=${apiKey}`;
  254. const apiResp = await request('POST', apiUrl, JSON.stringify({
  255. "videoId": url.replace('https://www.youtube.com/watch?v=', ''),
  256. "contentCheckOk": true,
  257. "params": "8AEB",
  258. "context": {
  259. "client": {
  260. "clientName": "ANDROID_MUSIC",
  261. "clientVersion": "5.16.51",
  262. "androidSdkVersion": 30
  263. }
  264. },
  265. "racyCheckOk": true
  266. }), {
  267. 'Host': 'www.youtube.com',
  268. 'Connection': 'keep-alive',
  269. 'User-Agent': 'com.google.android.apps.youtube.music/17.31.35 (Linux; U; Android 11) gzip',
  270. 'Accept-Language': 'en-US,en',
  271. 'Cookie': parseSetCookie(htmlHeaders),
  272. 'Content-Type': 'application/json'
  273. }, platform);
  274. let {data: apiData, _} = apiResp;
  275. console.log(`android api result: ${JSON.stringify(apiResp)}`);
  276. const res = JSON.parse(apiData);
  277. const currentFormats = [];
  278. for (const format of [].concat(res["streamingData"]["formats"]).concat(res["streamingData"]["adaptiveFormats"])) {
  279. if (format) {
  280. format["from"] = "android"
  281. currentFormats.push(format);
  282. }
  283. }
  284. originFormats = originFormats.concat(currentFormats);
  285. } catch (e) {
  286. console.log(`can not found format android api error: ${e}`);
  287. }
  288. console.log(`after android api, format size:${originFormats.length}`);
  289. const currentFormats = [];
  290. for (const format of ytInitialPlayerResponse["streamingData"]["formats"].concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
  291. if (format) {
  292. format["from"] = "web"
  293. currentFormats.push(format);
  294. }
  295. }
  296. originFormats = originFormats.concat(currentFormats);
  297. console.log(`after html, format size:${originFormats.length}`);
  298. const baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  299. let formatIds = [];
  300. const formats = [];
  301. for (let format of originFormats) {
  302. if (printable(platform)) {
  303. console.log(format);
  304. }
  305. if (format && formatIds.indexOf(format['itag']) === -1) {
  306. // if (!format["url"]) {
  307. // format["url"] = await signUrl(format["signatureCipher"], baseJsUrl, platform);
  308. // }
  309. if (format["url"]) {
  310. const {vcodec, acodec} = parseCodecs(format)
  311. if (vcodec && acodec) {
  312. const current = {
  313. "width": format["width"] + "",
  314. "height": format["height"] + "",
  315. "type": format["mimeType"],
  316. "quality": format["qualityLabel"],
  317. "itag": format["itag"],
  318. "fps": format["fps"] + "",
  319. "bitrate": format["bitrate"] + "",
  320. "url": format["url"],
  321. "ext": "mp4",
  322. "vcodec": vcodec,
  323. "acodec": acodec,
  324. "vbr": "0",
  325. "abr": "0",
  326. "container": "mp4_dash",
  327. "from": format["from"]
  328. }
  329. if (platform === "WEB") {
  330. current["source"] = format
  331. }
  332. formats.push(current)
  333. formatIds.push(format["itag"]);
  334. }
  335. }
  336. }
  337. }
  338. const ytInitialDataMatch = html.match(/var ytInitialData\s*=\s*({.*?});/);
  339. const recommendInfo = [];
  340. if (ytInitialDataMatch && ytInitialDataMatch.length === 2) {
  341. const ytInitialData = JSON.parse(ytInitialDataMatch[1]);
  342. if (printable(platform)) {
  343. console.log(ytInitialData);
  344. }
  345. for (const item of ytInitialData["contents"]?.["twoColumnWatchNextResults"]?.["secondaryResults"]?.["secondaryResults"]?.["results"] || []) {
  346. if (item["compactVideoRenderer"]) {
  347. const recommendVideo = item["compactVideoRenderer"];
  348. console.log(`recommend video: ${JSON.stringify(recommendVideo)}`);
  349. if (recommendVideo["videoId"]) {
  350. recommendInfo.push({
  351. "type": "gridVideoRenderer",
  352. "videoId": recommendVideo["videoId"],
  353. "title": recommendVideo["title"]?.["simpleText"],
  354. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  355. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  356. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  357. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  358. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  359. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  360. })
  361. }
  362. }
  363. }
  364. }
  365. formats.sort((a, b) => parseInt(a["height"]) - parseInt(b["height"]));
  366. const videoDetails = {
  367. "isLiveContent": originVideoDetails["isLiveContent"],
  368. "title": originVideoDetails["title"],
  369. "thumbnails": thumbnails,
  370. "description": originVideoDetails["shortDescription"],
  371. "lengthSeconds": originVideoDetails["lengthSeconds"],
  372. "viewCount": originVideoDetails["viewCount"],
  373. "keywords": originVideoDetails["keywords"],
  374. "author": originVideoDetails["author"],
  375. "channelID": originVideoDetails["channelId"],
  376. "recommendInfo": recommendInfo,
  377. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  378. "videoId": originVideoDetails["videoId"]
  379. }
  380. const ret = {
  381. "code": 200,
  382. "msg": "",
  383. "data": {
  384. "videoDetails": videoDetails,
  385. "streamingData": {
  386. "formats": formats
  387. }
  388. },
  389. "id": "MusicDetailViewModel_detail_url"
  390. }
  391. console.log(`detail result: ${JSON.stringify(ret)}`);
  392. return ret;
  393. } catch (e) {
  394. const ret = {
  395. "code": -1,
  396. "msg": e.toString()
  397. }
  398. console.log(`detail result error: ${JSON.stringify(ret)}`);
  399. console.log(e);
  400. return ret;
  401. }
  402. }
  403. search = async (keyword, next, platform) => {
  404. try {
  405. console.log(`search keyword: ${keyword}`);
  406. console.log(`search next: ${next}`);
  407. if (next) {
  408. const nextObject = JSON.parse(next);
  409. const key = nextObject["key"];
  410. const body = {
  411. context: {
  412. client: {
  413. clientName: "WEB",
  414. clientVersion: "2.20240506.01.00",
  415. },
  416. },
  417. continuation: nextObject["continuation"]
  418. };
  419. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, platform);
  420. const {data, _} = res;
  421. res = JSON.parse(data);
  422. const videos = [];
  423. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  424. const video = item["videoRenderer"];
  425. if (printable(platform)) {
  426. console.log(video);
  427. }
  428. if (video && video["videoId"]) {
  429. videos.push({
  430. "type": "videoWithContextRenderer",
  431. "data": {
  432. "videoId": video["videoId"],
  433. "title": video["title"]?.["runs"]?.[0]?.["text"],
  434. "thumbnails": video["thumbnail"]?.["thumbnails"],
  435. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  436. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  437. "viewCountText": video["viewCountText"]?.["simpleText"],
  438. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  439. "lengthText": video["lengthText"]?.["simpleText"]
  440. }
  441. });
  442. }
  443. }
  444. const ret = {
  445. "code": 200,
  446. "msg": "",
  447. "data": {
  448. "data": videos,
  449. "next": JSON.stringify({
  450. "key": nextObject["key"],
  451. "continuation": res["onResponseReceivedCommands"]?.[0]?.["appendContinuationItemsAction"]?.["continuationItems"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"],
  452. }),
  453. },
  454. "id": "MusicSearchResultViewModel_search_result"
  455. }
  456. console.log(`[next] search result: ${JSON.stringify(ret)}`);
  457. return ret;
  458. } else {
  459. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  460. const htmlRes = await request('GET', url, null, {}, platform);
  461. const {data: html, _} = htmlRes;
  462. let regex = /var ytInitialData\s*=\s*({.*?});/;
  463. let match = html.match(regex);
  464. if (!match || !match.length) {
  465. console.log("can not found ytInitialData");
  466. throw new Error('JSON not found: ytInitialData');
  467. }
  468. const ytInitialDataResp = JSON.parse(match[1]);
  469. const videos = [];
  470. for (const item of ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"]?.[0]?.["itemSectionRenderer"]?.["contents"]) {
  471. if (item["videoRenderer"]) {
  472. const video = item["videoRenderer"];
  473. if (printable(platform)) {
  474. console.log(video);
  475. }
  476. if (video && video["videoId"]) {
  477. videos.push({
  478. "type": "videoWithContextRenderer",
  479. "data": {
  480. "videoId": video["videoId"],
  481. "title": video["title"]?.["runs"]?.[0]?.["text"],
  482. "thumbnails": video["thumbnail"]?.["thumbnails"],
  483. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  484. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  485. "viewCountText": video["viewCountText"]?.["simpleText"],
  486. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  487. "lengthText": video["lengthText"]?.["simpleText"]
  488. }
  489. });
  490. }
  491. }
  492. }
  493. let next = {};
  494. if (html.split("innertubeApiKey").length > 0) {
  495. next["key"] = html
  496. .split("innertubeApiKey")[1]
  497. .trim()
  498. .split(",")[0]
  499. .split('"')[2];
  500. }
  501. next["continuation"] = ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"]
  502. const ret = {
  503. "code": 200,
  504. "msg": "",
  505. "data": {
  506. "data": videos,
  507. "next": JSON.stringify(next),
  508. },
  509. "id": "MusicSearchResultViewModel_search_result"
  510. }
  511. console.log(`unnext search result: ${JSON.stringify(ret)}`);
  512. return ret;
  513. }
  514. } catch (e) {
  515. const ret = {
  516. "code": -1,
  517. "msg": e.toString()
  518. }
  519. console.log(`search result error: ${JSON.stringify(ret)}`);
  520. return ret;
  521. }
  522. }