info.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. parseCodecs = (format) => {
  2. const mimeType = format["mimeType"]
  3. if (!mimeType) {
  4. return {};
  5. }
  6. const regex = /(?<mimetype>[^/]+\/[^;]+)(?:;\s*codecs="?(?<codecs>[^"]+))?/;
  7. const match = mimeType.match(regex);
  8. if (!match) {
  9. return {};
  10. }
  11. const codecs = match.groups.codecs;
  12. if (!codecs) {
  13. return {};
  14. }
  15. const splitCodecs = codecs.trim().replace(/,$/, '').split(',').map(str => str.trim()).filter(Boolean);
  16. let vcodec = null;
  17. let acodec = null;
  18. for (const fullCodec of splitCodecs) {
  19. const codec = fullCodec.split('.')[0];
  20. if (['avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1', 'av01', 'theora'].includes(codec)) {
  21. if (!vcodec) {
  22. vcodec = fullCodec;
  23. }
  24. } else if (['mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'].includes(codec)) {
  25. if (!acodec) {
  26. acodec = fullCodec;
  27. }
  28. } else {
  29. console.warn(`WARNING: Unknown codec ${fullCodec}`);
  30. }
  31. }
  32. if (!vcodec && !acodec) {
  33. if (splitCodecs.length === 2) {
  34. return {
  35. vcodec: splitCodecs[0],
  36. acodec: splitCodecs[1]
  37. };
  38. }
  39. } else {
  40. return {
  41. vcodec: vcodec,
  42. acodec: acodec
  43. };
  44. }
  45. return {};
  46. }
  47. request = async (method, url, data = null, headers = {}, platform) => {
  48. if (platform === "WEB") {
  49. url = url.replace("https://www.youtube.com", "http://127.0.0.1");
  50. }
  51. console.log(`request url:${url}`)
  52. console.log(`request data:${data}`)
  53. console.log(`request method:${method}`)
  54. console.log(`request headers:${JSON.stringify((headers))}`)
  55. if (platform === "WEB") {
  56. return fetch(url, {
  57. "method": method,
  58. "headers": headers,
  59. "body": data
  60. }).then(res => res.text())
  61. }
  62. return new Promise((resolve, reject) => {
  63. AF.request(url, method, data, headers, (data, err) => {
  64. if (err) {
  65. reject(err);
  66. } else {
  67. resolve(data);
  68. }
  69. });
  70. })
  71. }
  72. getStringBetween = (string, needleStart, needleEnd, offsetStart = 0, offsetEnd = 0) => {
  73. const x = string.indexOf(needleStart);
  74. const y = needleEnd ? string.indexOf(needleEnd, x) : string.length;
  75. return string.substring(x + needleStart.length + offsetEnd, y + offsetStart);
  76. }
  77. getDecipherFunction = (string) => {
  78. const js = string.replace("var _yt_player={}", "");
  79. const top = getStringBetween(js, `a=a.split("")`, "};", 1, -28);
  80. const beginningOfFunction =
  81. "var " + getStringBetween(top, `a=a.split("")`, "(", 10, 1).split(".")[0] + "=";
  82. const side = getStringBetween(js, beginningOfFunction, "};", 2, -beginningOfFunction.length);
  83. console.log(`side: ${side}`);
  84. console.log(`top: ${top}`);
  85. return eval(side + top);
  86. };
  87. const cache = {};
  88. extractJSSignatureFunction = async (baseJsUrl, platform) => {
  89. console.log(`extract baseUrl: ${baseJsUrl}`);
  90. const cacheKey = `js:${baseJsUrl}`;
  91. if (cache[cacheKey]) {
  92. console.log(`from cache JSSignatureFunction: ${baseJsUrl}`);
  93. return cache[cacheKey];
  94. }
  95. const baseContent = await request('GET', baseJsUrl, null, {
  96. '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',
  97. }, platform);
  98. const decipher = getDecipherFunction(baseContent);
  99. if (decipher) {
  100. cache[cacheKey] = decipher;
  101. }
  102. return decipher;
  103. }
  104. getUrlFromSignature = async (signatureCipher, baseJsUrl, platform) => {
  105. const decipher = await extractJSSignatureFunction(baseJsUrl, platform);
  106. const searchParams = {}
  107. for (const item of signatureCipher.split("&")) {
  108. const [key, value] = item.split('=');
  109. searchParams[decodeURIComponent(key)] = decodeURIComponent(value);
  110. }
  111. const [url, signature, sp] = [searchParams["url"], searchParams["s"], searchParams["sp"]];
  112. console.log(signatureCipher, url, signature, sp);
  113. return `${url}&${sp}=${decipher(signature)}`;
  114. }
  115. detail = async (url, platform) => {
  116. try {
  117. let html = await request('GET', url, null, {
  118. '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'
  119. }, platform);
  120. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  121. let match = html.match(regex);
  122. if (!match || !match.length) {
  123. console.log("can not found JSON: ytInitialPlayerResponse");
  124. throw new Error('JSON not found: ytInitialPlayerResponse');
  125. }
  126. const ytInitialPlayerResponse = JSON.parse(match[1]);
  127. console.log(ytInitialPlayerResponse);
  128. const originVideoDetails = ytInitialPlayerResponse["videoDetails"];
  129. console.log(`videoDetails: ${JSON.stringify(originVideoDetails)}`);
  130. const thumbnails = []
  131. for (const item of originVideoDetails["thumbnail"]["thumbnails"]) {
  132. thumbnails.push({
  133. "url": item["url"],
  134. "width": item["width"] + "",
  135. "height": item["height"] + ""
  136. })
  137. }
  138. let originFormats = [];
  139. // android
  140. try {
  141. const apiKey = 'AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39'
  142. const data = {
  143. "context": {
  144. "client": {
  145. "clientName": "ANDROID",
  146. "clientVersion": "19.09.37",
  147. "androidSdkVersion": 30,
  148. "userAgent": "com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip",
  149. }
  150. },
  151. 'videoId': url.replace('https://www.youtube.com/watch?v=', ''),
  152. "playbackContext": {
  153. "contentPlaybackContext": {
  154. "html5Preference": "HTML5_PREF_WANTS"
  155. }
  156. },
  157. "params": "CgIIAQ==",
  158. "contentCheckOk": true,
  159. "racyCheckOk": true
  160. }
  161. const apiUrl = `https://www.youtube.com/youtubei/v1/player?key=${apiKey}&prettyPrint=false`;
  162. let apiResp = await request('POST', apiUrl, JSON.stringify(data), {
  163. 'X-YouTube-Client-Name': '5',
  164. 'X-YouTube-Client-Version': '19.09.3',
  165. 'User-Agent': 'com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  166. 'Content-Type': 'application/json'
  167. }, platform);
  168. console.log(`android api result: ${JSON.stringify(apiResp)}`);
  169. const res = JSON.parse(apiResp);
  170. originFormats = originFormats.concat([].concat(res["streamingData"]["formats"]).concat(res["streamingData"]["adaptiveFormats"]));
  171. } catch (e) {
  172. console.log(`can not found format android api error: ${e}`);
  173. }
  174. console.log(`after android api, format size:${originFormats.length}`);
  175. // ios
  176. try {
  177. const apiKey = 'AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc'
  178. const data = {
  179. "context": {
  180. "client": {
  181. 'clientName': 'IOS',
  182. 'clientVersion': '19.09.3',
  183. 'deviceModel': 'iPhone14,3',
  184. 'userAgent': 'com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)'
  185. }
  186. },
  187. 'videoId': url.replace('https://www.youtube.com/watch?v=', ''),
  188. "playbackContext": {
  189. "contentPlaybackContext": {
  190. "html5Preference": "HTML5_PREF_WANTS"
  191. }
  192. },
  193. "contentCheckOk": true,
  194. "racyCheckOk": true
  195. }
  196. const apiUrl = `https://www.youtube.com/youtubei/v1/player?key=${apiKey}&prettyPrint=false`;
  197. let apiResp = await request('POST', apiUrl, JSON.stringify(data), {
  198. 'X-YouTube-Client-Name': '5',
  199. 'X-YouTube-Client-Version': '19.09.3',
  200. 'User-Agent': 'com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  201. 'Content-Type': 'application/json'
  202. }, platform);
  203. console.log(`ios api result: ${JSON.stringify(apiResp)}`);
  204. const res = JSON.parse(apiResp);
  205. originFormats = originFormats.concat([].concat(res["streamingData"]["formats"]).concat(res["streamingData"]["adaptiveFormats"]));
  206. } catch (e) {
  207. console.log(`can not found format ios api error: ${e}`);
  208. }
  209. console.log(`after android api, format size:${originFormats.length}`);
  210. originFormats = originFormats.concat(ytInitialPlayerResponse["streamingData"]["formats"]).concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"]);
  211. console.log(`after html, format size:${originFormats.length}`);
  212. const baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  213. let formatIds = [];
  214. const formats = [];
  215. for (let format of originFormats) {
  216. console.log(`current format: ${JSON.stringify(format)}`);
  217. if (format && formatIds.indexOf(format['itag']) === -1) {
  218. if (!format["url"]) {
  219. format["url"] = await getUrlFromSignature(format["signatureCipher"], baseJsUrl, platform);
  220. }
  221. if (format["url"]) {
  222. const {vcodec, acodec} = parseCodecs(format)
  223. if (vcodec && acodec) {
  224. formats.push({
  225. "width": format["width"] + "",
  226. "height": format["height"] + "",
  227. "type": format["mimeType"],
  228. "quality": format["quality"],
  229. "itag": format["itag"],
  230. "fps": format["fps"] + "",
  231. "bitrate": format["bitrate"] + "",
  232. "url": format["url"],
  233. "ext": "mp4",
  234. "vcodec": vcodec,
  235. "acodec": acodec,
  236. "vbr": "0",
  237. "abr": "0",
  238. "container": "mp4_dash"
  239. })
  240. formatIds.push(format["itag"]);
  241. }
  242. }
  243. }
  244. }
  245. const ytInitialDataMatch = html.match(/var ytInitialData\s*=\s*({.*?});/);
  246. const recommendInfo = [];
  247. if (ytInitialDataMatch && ytInitialDataMatch.length === 2) {
  248. const ytInitialData = JSON.parse(ytInitialDataMatch[1]);
  249. console.log(`ytInitialData: ${JSON.stringify(ytInitialData)}`);
  250. for (const item of ytInitialData["contents"]?.["twoColumnWatchNextResults"]?.["secondaryResults"]?.["secondaryResults"]?.["results"] || []) {
  251. if (item["compactVideoRenderer"]) {
  252. const recommendVideo = item["compactVideoRenderer"];
  253. console.log(`recommend video: ${JSON.stringify(recommendVideo)}`);
  254. if (recommendVideo["videoId"]) {
  255. recommendInfo.push({
  256. "type": "gridVideoRenderer",
  257. "videoId": recommendVideo["videoId"],
  258. "title": recommendVideo["title"]?.["simpleText"],
  259. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  260. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  261. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  262. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  263. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  264. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  265. })
  266. }
  267. }
  268. }
  269. }
  270. const videoDetails = {
  271. "isLiveContent": originVideoDetails["isLiveContent"],
  272. "title": originVideoDetails["title"],
  273. "thumbnails": thumbnails,
  274. "description": originVideoDetails["shortDescription"],
  275. "lengthSeconds": originVideoDetails["lengthSeconds"],
  276. "viewCount": originVideoDetails["viewCount"],
  277. "keywords": originVideoDetails["keywords"],
  278. "author": originVideoDetails["author"],
  279. "channelID": originVideoDetails["channelId"],
  280. "recommendInfo": recommendInfo,
  281. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  282. "videoId": originVideoDetails["videoId"]
  283. }
  284. const ret = {
  285. "code": 200,
  286. "msg": "",
  287. "data": {
  288. "videoDetails": videoDetails,
  289. "streamingData": {
  290. "formats": formats.reverse()
  291. }
  292. },
  293. "id": "MusicDetailViewModel_detail_url"
  294. }
  295. console.log(`detail result: ${JSON.stringify(ret)}`);
  296. return ret;
  297. } catch (e) {
  298. const ret = {
  299. "code": -1,
  300. "msg": e.toString()
  301. }
  302. console.log(`detail result error: ${JSON.stringify(ret)}`);
  303. console.log(e);
  304. return ret;
  305. }
  306. }
  307. search = async (keyword, next, platform) => {
  308. try {
  309. console.log(`search keyword: ${keyword}`);
  310. console.log(`search next: ${next}`);
  311. if (next) {
  312. const nextObject = JSON.parse(next);
  313. const key = nextObject["key"];
  314. const body = {
  315. context: {
  316. client: {
  317. clientName: "WEB",
  318. clientVersion: "2.20240506.01.00",
  319. },
  320. },
  321. continuation: nextObject["continuation"]
  322. };
  323. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, platform);
  324. res = JSON.parse(res);
  325. const videos = [];
  326. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  327. const video = item["videoRenderer"];
  328. console.log(`search result video: ${JSON.stringify(video)}`);
  329. if (video && video["videoId"]) {
  330. videos.push({
  331. "type": "videoWithContextRenderer",
  332. "data": {
  333. "videoId": video["videoId"],
  334. "title": video["title"]?.["runs"]?.[0]?.["text"],
  335. "thumbnails": video["thumbnail"]?.["thumbnails"],
  336. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  337. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  338. "viewCountText": video["viewCountText"]?.["simpleText"],
  339. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  340. "lengthText": video["lengthText"]?.["simpleText"]
  341. }
  342. });
  343. }
  344. }
  345. const ret = {
  346. "code": 200,
  347. "msg": "",
  348. "data": {
  349. "data": videos,
  350. "next": JSON.stringify({
  351. "key": nextObject["key"],
  352. "continuation": res["onResponseReceivedCommands"]?.[0]?.["appendContinuationItemsAction"]?.["continuationItems"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"],
  353. }),
  354. },
  355. "id": "MusicSearchResultViewModel_search_result"
  356. }
  357. console.log(`[next] search result: ${JSON.stringify(ret)}`);
  358. return ret;
  359. } else {
  360. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  361. const html = await request('GET', url, null, {}, platform);
  362. let regex = /var ytInitialData\s*=\s*({.*?});/;
  363. let match = html.match(regex);
  364. if (!match || !match.length) {
  365. console.log("can not found ytInitialData");
  366. throw new Error('JSON not found: ytInitialData');
  367. }
  368. const ytInitialDataResp = JSON.parse(match[1]);
  369. const videos = [];
  370. for (const item of ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"]?.[0]?.["itemSectionRenderer"]?.["contents"]) {
  371. if (item["videoRenderer"]) {
  372. const video = item["videoRenderer"];
  373. console.log(`search result video: ${JSON.stringify(video)}`);
  374. if (video && video["videoId"]) {
  375. videos.push({
  376. "type": "videoWithContextRenderer",
  377. "data": {
  378. "videoId": video["videoId"],
  379. "title": video["title"]?.["runs"]?.[0]?.["text"],
  380. "thumbnails": video["thumbnail"]?.["thumbnails"],
  381. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  382. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  383. "viewCountText": video["viewCountText"]?.["simpleText"],
  384. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  385. "lengthText": video["lengthText"]?.["simpleText"]
  386. }
  387. });
  388. }
  389. }
  390. }
  391. let next = {};
  392. if (html.split("innertubeApiKey").length > 0) {
  393. next["key"] = html
  394. .split("innertubeApiKey")[1]
  395. .trim()
  396. .split(",")[0]
  397. .split('"')[2];
  398. }
  399. next["continuation"] = ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"]
  400. const ret = {
  401. "code": 200,
  402. "msg": "",
  403. "data": {
  404. "data": videos,
  405. "next": JSON.stringify(next),
  406. },
  407. "id": "MusicSearchResultViewModel_search_result"
  408. }
  409. console.log(`unnext search result: ${JSON.stringify(ret)}`);
  410. return ret;
  411. }
  412. } catch (e) {
  413. const ret = {
  414. "code": -1,
  415. "msg": e.toString()
  416. }
  417. console.log(`search result error: ${JSON.stringify(ret)}`);
  418. return ret;
  419. }
  420. }