youtube.bak.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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:80/");
  81. url = url.replace("https://music.youtube.com/", "http://127.0.0.1:80/");
  82. }
  83. console.log(`request url:${url}`)
  84. console.log(`request data:${data}`)
  85. console.log(`request method:${method}`)
  86. console.log(`request headers:${JSON.stringify((headers))}`)
  87. if (platform === "WEB") {
  88. const res = await fetch(url, {
  89. 'mode': 'cors',
  90. 'method': method,
  91. 'headers': headers,
  92. 'body': data
  93. })
  94. const resData = await res.text()
  95. return Promise.resolve({
  96. 'data': resData,
  97. 'headers': res.headers
  98. });
  99. }
  100. return new Promise((resolve, reject) => {
  101. AF.request(url, method, data, headers, (data, headers, err) => {
  102. if (err) {
  103. reject(err);
  104. } else {
  105. console.log(`response headers: ${headers}`);
  106. resolve({
  107. 'data': data,
  108. 'headers': JSON.parse(headers)
  109. });
  110. }
  111. });
  112. })
  113. }
  114. findFunction = (jsCode, regexp, platform) => {
  115. const match = jsCode.match(regexp)
  116. if (!match && match.length <= 1) {
  117. return null;
  118. }
  119. let result = "";
  120. const dependencyMatches = match[0].match(/([$a-zA-Z0-9]+\.[$a-zA-Z0-9]+)/g)
  121. const existDependencies = [];
  122. if (dependencyMatches && dependencyMatches.length >= 1) {
  123. for (let currentMatch of dependencyMatches) {
  124. const varName = currentMatch.split('.')[0];
  125. if (existDependencies.includes(varName)) {
  126. continue
  127. }
  128. if (!/^[$A-Z|a-z]{2,}$/.test(varName)) {
  129. continue
  130. }
  131. let reg = "var (\$)?" + varName + "={(.|\\n)*?};"
  132. const varNameMatch = jsCode.match(new RegExp(reg), '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(`findFunction 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]+\)\{try{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 apiUrl = `https://music.youtube.com/youtubei/v1/player?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8`;
  253. const apiResp = await request('POST', apiUrl, JSON.stringify({
  254. "context": {
  255. "client": {
  256. "clientName": "ANDROID",
  257. "hl": "en",
  258. "clientVersion": "18.49.37",
  259. "gl": "US"
  260. }
  261. },
  262. "videoId": url.replace('https://www.youtube.com/watch?v=', ''),
  263. "params": "CgIQBg"
  264. }), {
  265. 'Host': 'www.youtube.com',
  266. 'Connection': 'keep-alive',
  267. 'User-Agent': 'com.google.android.apps.youtube.music/17.31.35 (Linux; U; Android 11) gzip',
  268. 'Accept-Language': 'en-US,en',
  269. 'Cookie': parseSetCookie(htmlHeaders),
  270. 'Content-Type': 'application/json'
  271. }, platform);
  272. let {data: apiData, _} = apiResp;
  273. console.log(`android api result: ${JSON.stringify(apiResp)}`);
  274. const res = JSON.parse(apiData);
  275. const currentFormats = [];
  276. for (const format of [].concat(res["streamingData"]["formats"]).concat(res["streamingData"]["adaptiveFormats"])) {
  277. if (format) {
  278. format["from"] = "android"
  279. currentFormats.push(format);
  280. }
  281. }
  282. originFormats = originFormats.concat(currentFormats);
  283. } catch (e) {
  284. console.log(`can not found format android api error: ${e}`);
  285. }
  286. console.log(`after android api, format size:${originFormats.length}`);
  287. // web
  288. const currentFormats = [];
  289. for (const format of ytInitialPlayerResponse["streamingData"]["formats"].concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
  290. if (format) {
  291. format["from"] = "web"
  292. currentFormats.push(format);
  293. }
  294. }
  295. originFormats = originFormats.concat(currentFormats);
  296. console.log(`after html, format size:${originFormats.length}`);
  297. const baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  298. let audioUrl = ""
  299. for (let format of originFormats) {
  300. if (!format["url"]) {
  301. format["url"] = await signUrl(format["signatureCipher"], baseJsUrl, platform);
  302. }
  303. if (format["url"]) {
  304. const {vcodec, acodec} = parseCodecs(format)
  305. if (!vcodec && acodec) {
  306. audioUrl = format["url"]
  307. break
  308. }
  309. }
  310. }
  311. let formatIds = [];
  312. const formats = [];
  313. for (let format of originFormats) {
  314. if (printable(platform)) {
  315. console.log(format);
  316. }
  317. if (format && formatIds.indexOf(format['itag']) === -1) {
  318. if (!format["url"]) {
  319. format["url"] = await signUrl(format["signatureCipher"], baseJsUrl, platform);
  320. }
  321. if (format["url"]) {
  322. const {vcodec, acodec} = parseCodecs(format)
  323. if (vcodec && acodec) {
  324. const current = {
  325. "width": format["width"] + "",
  326. "height": format["height"] + "",
  327. "type": format["mimeType"],
  328. "quality": format["qualityLabel"],
  329. "itag": format["itag"],
  330. "fps": format["fps"] + "",
  331. "bitrate": format["bitrate"] + "",
  332. "url": format["url"],
  333. "ext": "mp4",
  334. "vcodec": vcodec,
  335. "acodec": acodec,
  336. "vbr": "0",
  337. "abr": "0",
  338. "container": "mp4_dash",
  339. "from": format["from"],
  340. "audioUrl": audioUrl
  341. }
  342. if (platform === "WEB") {
  343. current["source"] = format
  344. }
  345. formats.push(current)
  346. formatIds.push(format["itag"]);
  347. }
  348. }
  349. }
  350. }
  351. const ytInitialDataMatch = html.match(/var ytInitialData\s*=\s*({.*?});/);
  352. const recommendInfo = [];
  353. if (ytInitialDataMatch && ytInitialDataMatch.length === 2) {
  354. const ytInitialData = JSON.parse(ytInitialDataMatch[1]);
  355. if (printable(platform)) {
  356. console.log(ytInitialData);
  357. }
  358. for (const item of ytInitialData["contents"]?.["twoColumnWatchNextResults"]?.["secondaryResults"]?.["secondaryResults"]?.["results"] || []) {
  359. if (item["compactVideoRenderer"]) {
  360. const recommendVideo = item["compactVideoRenderer"];
  361. console.log(`recommend video: ${JSON.stringify(recommendVideo)}`);
  362. if (recommendVideo["videoId"]) {
  363. recommendInfo.push({
  364. "type": "gridVideoRenderer",
  365. "videoId": recommendVideo["videoId"],
  366. "title": recommendVideo["title"]?.["simpleText"],
  367. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  368. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  369. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  370. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  371. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  372. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  373. })
  374. }
  375. }
  376. }
  377. }
  378. formats.sort((a, b) => parseInt(a["height"]) - parseInt(b["height"]));
  379. const videoDetails = {
  380. "isLiveContent": originVideoDetails["isLiveContent"],
  381. "title": originVideoDetails["title"],
  382. "thumbnails": thumbnails,
  383. "description": originVideoDetails["shortDescription"],
  384. "lengthSeconds": originVideoDetails["lengthSeconds"],
  385. "viewCount": originVideoDetails["viewCount"],
  386. "keywords": originVideoDetails["keywords"],
  387. "author": originVideoDetails["author"],
  388. "channelID": originVideoDetails["channelId"],
  389. "recommendInfo": recommendInfo,
  390. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  391. "videoId": originVideoDetails["videoId"]
  392. }
  393. const ret = {
  394. "code": 200,
  395. "msg": "",
  396. "data": {
  397. "videoDetails": videoDetails,
  398. "streamingData": {
  399. "formats": formats
  400. }
  401. },
  402. "id": "MusicDetailViewModel_detail_url"
  403. }
  404. console.log(`detail result: ${JSON.stringify(ret)}`);
  405. return ret;
  406. } catch (e) {
  407. const ret = {
  408. "code": -1,
  409. "msg": e.toString()
  410. }
  411. console.log(`detail2 result error: ${JSON.stringify(ret)}`);
  412. console.log(e);
  413. return ret;
  414. }
  415. }
  416. search = async (keyword, next, platform) => {
  417. try {
  418. console.log(`search keyword: ${keyword}`);
  419. console.log(`search next: ${next}`);
  420. if (next) {
  421. const nextObject = JSON.parse(next);
  422. const key = nextObject["key"];
  423. const body = {
  424. context: {
  425. client: {
  426. clientName: "WEB",
  427. clientVersion: "2.20240506.01.00",
  428. },
  429. },
  430. continuation: nextObject["continuation"]
  431. };
  432. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, platform);
  433. const {data, _} = res;
  434. res = JSON.parse(data);
  435. const videos = [];
  436. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  437. const video = item["videoRenderer"];
  438. if (printable(platform)) {
  439. console.log(video);
  440. }
  441. if (video && video["videoId"] && video["lengthText"]) {
  442. videos.push({
  443. "type": "videoWithContextRenderer",
  444. "data": {
  445. "videoId": video["videoId"],
  446. "title": video["title"]?.["runs"]?.[0]?.["text"],
  447. "thumbnails": video["thumbnail"]?.["thumbnails"],
  448. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  449. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  450. "viewCountText": video["viewCountText"]?.["simpleText"],
  451. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  452. "lengthText": video["lengthText"]?.["simpleText"]
  453. }
  454. });
  455. }
  456. }
  457. const ret = {
  458. "code": 200,
  459. "msg": "",
  460. "data": {
  461. "data": videos,
  462. "next": JSON.stringify({
  463. "key": nextObject["key"],
  464. "continuation": res["onResponseReceivedCommands"]?.[0]?.["appendContinuationItemsAction"]?.["continuationItems"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"],
  465. }),
  466. },
  467. "id": "MusicSearchResultViewModel_search_result"
  468. }
  469. console.log(`[next] search result: ${JSON.stringify(ret)}`);
  470. return ret;
  471. } else {
  472. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  473. const htmlRes = await request('GET', url, null, {}, platform);
  474. const {data: html, _} = htmlRes;
  475. let regex = /var ytInitialData\s*=\s*({.*?});/;
  476. let match = html.match(regex);
  477. if (!match || !match.length) {
  478. console.log("can not found ytInitialData");
  479. throw new Error('JSON not found: ytInitialData');
  480. }
  481. const ytInitialDataResp = JSON.parse(match[1]);
  482. if (printable(platform)) {
  483. console.log(ytInitialDataResp);
  484. }
  485. const videos = [];
  486. const contents = ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"] || []
  487. for (const content of contents) {
  488. const currentContents = content["itemSectionRenderer"]?.["contents"]
  489. if (Array.isArray(currentContents)) {
  490. for (const currentContent of currentContents) {
  491. if (currentContent["videoRenderer"]) {
  492. const video = currentContent["videoRenderer"];
  493. if (printable(platform)) {
  494. console.log(video);
  495. }
  496. if (video && video["videoId"] && video["lengthText"]) {
  497. videos.push({
  498. "type": "videoWithContextRenderer",
  499. "data": {
  500. "videoId": video["videoId"],
  501. "title": video["title"]?.["runs"]?.[0]?.["text"],
  502. "thumbnails": video["thumbnail"]?.["thumbnails"],
  503. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  504. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  505. "viewCountText": video["viewCountText"]?.["simpleText"],
  506. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  507. "lengthText": video["lengthText"]?.["simpleText"]
  508. }
  509. });
  510. }
  511. }
  512. }
  513. }
  514. }
  515. let next = {};
  516. if (html.split("innertubeApiKey").length > 0) {
  517. next["key"] = html
  518. .split("innertubeApiKey")[1]
  519. .trim()
  520. .split(",")[0]
  521. .split('"')[2];
  522. }
  523. next["continuation"] = contents[contents.length - 1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"]
  524. const ret = {
  525. "code": 200,
  526. "msg": "",
  527. "data": {
  528. "data": videos,
  529. "next": JSON.stringify(next),
  530. },
  531. "id": "MusicSearchResultViewModel_search_result"
  532. }
  533. console.log(`unnext search result: ${JSON.stringify(ret)}`);
  534. return ret;
  535. }
  536. } catch (e) {
  537. const ret = {
  538. "code": -1,
  539. "msg": e.toString()
  540. }
  541. console.log(`search result error: ${JSON.stringify(ret)}`);
  542. return ret;
  543. }
  544. }