info.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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(`请求url:${url}`)
  52. console.log(`请求data:${data}`)
  53. console.log(`请求method:${method}`)
  54. console.log(`请求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(`解析baseUrl: ${baseJsUrl}`);
  90. const cacheKey = `js:${baseJsUrl}`;
  91. if (cache[cacheKey]) {
  92. console.log(`从缓存中获取JSSignatureFunction: ${baseJsUrl}`);
  93. return cache[cacheKey];
  94. }
  95. const headers = {
  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. }
  98. const baseContent = await request('GET', baseJsUrl, null, headers, platform);
  99. const decipher = getDecipherFunction(baseContent);
  100. if (decipher) {
  101. cache[cacheKey] = decipher;
  102. }
  103. return decipher;
  104. }
  105. getUrlFromSignature = async (signatureCipher, baseJsUrl, platform) => {
  106. const decipher = await extractJSSignatureFunction(baseJsUrl, platform);
  107. const searchParams = {}
  108. for (const item of signatureCipher.split("&")) {
  109. const [key, value] = item.split('=');
  110. searchParams[decodeURIComponent(key)] = decodeURIComponent(value);
  111. }
  112. const [url, signature, sp] = [searchParams["url"], searchParams["s"], searchParams["sp"]];
  113. console.log(signatureCipher, url, signature, sp);
  114. return `${url}&${sp}=${decipher(signature)}`;
  115. }
  116. detail = async (url, platform) => {
  117. try {
  118. let html = await request('GET', url, null, {
  119. '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'
  120. }, platform);
  121. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  122. let match = html.match(regex);
  123. if (!match || !match.length) {
  124. console.log("解释失败: 无法找到json");
  125. throw new Error('JSON not found.');
  126. }
  127. const ytInitialPlayerResponse = JSON.parse(match[1]);
  128. console.log(ytInitialPlayerResponse);
  129. const originVideoDetails = ytInitialPlayerResponse["videoDetails"];
  130. console.log(`videoDetails: ${JSON.stringify(originVideoDetails)}`);
  131. const thumbnails = []
  132. for (const item of originVideoDetails["thumbnail"]["thumbnails"]) {
  133. thumbnails.push({
  134. "url": item["url"],
  135. "width": item["width"] + "",
  136. "height": item["height"] + ""
  137. })
  138. }
  139. const baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  140. const formats = [];
  141. try {
  142. let regex = /ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;/
  143. let match = html.match(regex);
  144. if (match != null && match.length === 2) {
  145. const masterYtConfig = JSON.parse(match[1]);
  146. const apiKey = masterYtConfig['INNERTUBE_API_KEY'] || 'AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39'
  147. const data = {
  148. "context": {
  149. "client": {
  150. "clientName": "ANDROID",
  151. "clientVersion": "19.09.37",
  152. "androidSdkVersion": 30,
  153. "userAgent": "com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip",
  154. }
  155. },
  156. 'videoId': url.replace('https://www.youtube.com/watch?v=', ''),
  157. "playbackContext": {
  158. "contentPlaybackContext": {
  159. "html5Preference": "HTML5_PREF_WANTS"
  160. }
  161. },
  162. "params": "CgIIAQ==",
  163. "contentCheckOk": true,
  164. "racyCheckOk": true
  165. }
  166. const apiUrl = `https://www.youtube.com/youtubei/v1/player?key=${apiKey}&prettyPrint=false`;
  167. let res = await request('POST', apiUrl, JSON.stringify(data), {
  168. 'X-YouTube-Client-Name': '5',
  169. 'X-YouTube-Client-Version': '19.09.3',
  170. 'User-Agent': 'com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  171. 'Content-Type': 'application/json'
  172. }, platform);
  173. console.log(`api结果: ${res}`);
  174. res = JSON.parse(res);
  175. console.log(res);
  176. for (let format of [].concat(res["streamingData"]["formats"]).concat(res["streamingData"]["adaptiveFormats"])) {
  177. if (format) {
  178. console.log(`current format: ${JSON.stringify(format)}`);
  179. if (!format["url"]) {
  180. format["url"] = await getUrlFromSignature(format["signatureCipher"], baseJsUrl, platform);
  181. }
  182. if (format["url"]) {
  183. const {vcodec, acodec} = parseCodecs(format)
  184. if (vcodec && acodec) {
  185. formats.push({
  186. "width": format["width"] + "",
  187. "height": format["height"] + "",
  188. "type": format["mimeType"],
  189. "quality": format["quality"],
  190. "itag": format["itag"],
  191. "fps": format["fps"] + "",
  192. "bitrate": format["bitrate"] + "",
  193. "url": format["url"],
  194. "ext": "mp4",
  195. "vcodec": vcodec,
  196. "acodec": acodec,
  197. "vbr": "0",
  198. "abr": "0",
  199. "container": "mp4_dash"
  200. })
  201. }
  202. }
  203. }
  204. }
  205. }
  206. } catch (e) {
  207. console.log(`无法从api中解析format,并且报错了: ${e}`);
  208. }
  209. if (formats.length === 0) {
  210. for (let format of [].concat(ytInitialPlayerResponse["streamingData"]["formats"]).concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
  211. console.log(`current format: ${JSON.stringify(format)}`);
  212. if (format) {
  213. if (!format["url"]) {
  214. format["url"] = await getUrlFromSignature(format["signatureCipher"], baseJsUrl, platform);
  215. }
  216. if (format["url"]) {
  217. const {vcodec, acodec} = parseCodecs(format)
  218. if (vcodec && acodec) {
  219. formats.push({
  220. "width": format["width"] + "",
  221. "height": format["height"] + "",
  222. "type": format["mimeType"],
  223. "quality": format["quality"],
  224. "itag": format["itag"],
  225. "fps": format["fps"] + "",
  226. "bitrate": format["bitrate"] + "",
  227. "url": format["url"],
  228. "ext": "mp4",
  229. "vcodec": vcodec,
  230. "acodec": acodec,
  231. "vbr": "0",
  232. "abr": "0",
  233. "container": "mp4_dash"
  234. })
  235. }
  236. }
  237. }
  238. }
  239. }
  240. match = html.match(/var ytInitialData\s*=\s*({.*?});/);
  241. const recommendInfo = [];
  242. if (match && match.length === 2) {
  243. const ytInitialData = JSON.parse(match[1]);
  244. for (const item of ytInitialData["contents"]?.["twoColumnWatchNextResults"]?.["secondaryResults"]?.["secondaryResults"]?.["results"] || []) {
  245. if (item["compactVideoRenderer"]) {
  246. const recommendVideo = item["compactVideoRenderer"];
  247. console.log(`推荐视频: ${JSON.stringify(recommendVideo)}`);
  248. if (recommendVideo["videoId"]) {
  249. recommendInfo.push({
  250. "type": "gridVideoRenderer",
  251. "videoId": recommendVideo["videoId"],
  252. "title": recommendVideo["title"]?.["simpleText"],
  253. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  254. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  255. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  256. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  257. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  258. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  259. })
  260. }
  261. }
  262. }
  263. } else {
  264. console.log(`解析失败,无法找到 ytInitialData,无法获取推荐视频`);
  265. }
  266. const videoDetails = {
  267. "isLiveContent": originVideoDetails["isLiveContent"],
  268. "title": originVideoDetails["title"],
  269. "thumbnails": thumbnails,
  270. "description": originVideoDetails["shortDescription"],
  271. "lengthSeconds": originVideoDetails["lengthSeconds"],
  272. "viewCount": originVideoDetails["viewCount"],
  273. "keywords": originVideoDetails["keywords"],
  274. "author": originVideoDetails["author"],
  275. "channelID": originVideoDetails["channelId"],
  276. "recommendInfo": recommendInfo,
  277. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  278. "videoId": originVideoDetails["videoId"]
  279. }
  280. const ret = {
  281. "code": 200,
  282. "msg": "",
  283. "data": {
  284. "videoDetails": videoDetails,
  285. "streamingData": {
  286. "formats": formats.reverse()
  287. }
  288. },
  289. "id": "MusicDetailViewModel_detail_url"
  290. }
  291. console.log(`解析结果: ${JSON.stringify(ret)}`);
  292. return ret;
  293. } catch (e) {
  294. const ret = {
  295. "code": -1,
  296. "msg": e.toString()
  297. }
  298. console.log(`解析失败: ${JSON.stringify(ret)}`);
  299. console.log(e);
  300. return ret;
  301. }
  302. }
  303. search = async (keyword, next, platform) => {
  304. try {
  305. console.log(`接受到搜索请求 keyword: ${keyword}`);
  306. console.log(`接收到搜索请求 next: ${next}`);
  307. if (next) {
  308. const nextObject = JSON.parse(next);
  309. const key = nextObject["key"];
  310. const body = {
  311. context: {
  312. client: {
  313. clientName: "WEB",
  314. clientVersion: "2.20240506.01.00",
  315. },
  316. },
  317. continuation: nextObject["continuation"]
  318. };
  319. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, platform);
  320. res = JSON.parse(res);
  321. const videos = [];
  322. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  323. const video = item["videoRenderer"];
  324. console.log(`搜索结果: ${JSON.stringify(video)}`);
  325. if (video && video["videoId"]) {
  326. videos.push({
  327. "type": "videoWithContextRenderer",
  328. "data": {
  329. "videoId": video["videoId"],
  330. "title": video["title"]?.["runs"]?.[0]?.["text"],
  331. "thumbnails": video["thumbnail"]?.["thumbnails"],
  332. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  333. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  334. "viewCountText": video["viewCountText"]?.["simpleText"],
  335. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  336. "lengthText": video["lengthText"]?.["simpleText"]
  337. }
  338. });
  339. }
  340. }
  341. const ret = {
  342. "code": 200,
  343. "msg": "",
  344. "data": {
  345. "data": videos,
  346. "next": JSON.stringify({
  347. "key": nextObject["key"],
  348. "continuation": res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][1]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"],
  349. }),
  350. },
  351. "id": "MusicSearchResultViewModel_search_result"
  352. }
  353. console.log(`携带next搜索结果成功: ${JSON.stringify(ret)}`);
  354. return ret;
  355. } else {
  356. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  357. const html = await request('GET', url, null, {}, platform);
  358. let regex = /var ytInitialData\s*=\s*({.*?});/;
  359. let match = html.match(regex);
  360. if (!match || !match.length) {
  361. console.log("搜索失败:无法找到ytInitialData");
  362. throw new Error('JSON not found.');
  363. }
  364. const ytInitialDataResp = JSON.parse(match[1]);
  365. const videos = [];
  366. for (const item of ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"]) {
  367. if (item["videoRenderer"]) {
  368. const video = item["videoRenderer"];
  369. console.log(`搜索结果: ${JSON.stringify(video)}`);
  370. if (video && video["videoId"]) {
  371. videos.push({
  372. "type": "videoWithContextRenderer",
  373. "data": {
  374. "videoId": video["videoId"],
  375. "title": video["title"]?.["runs"]?.[0]?.["text"],
  376. "thumbnails": video["thumbnail"]?.["thumbnails"],
  377. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  378. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  379. "viewCountText": video["viewCountText"]?.["simpleText"],
  380. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  381. "lengthText": video["lengthText"]?.["simpleText"]
  382. }
  383. });
  384. }
  385. }
  386. }
  387. let next = {};
  388. if (html.split("innertubeApiKey").length > 0) {
  389. next["key"] = html
  390. .split("innertubeApiKey")[1]
  391. .trim()
  392. .split(",")[0]
  393. .split('"')[2];
  394. }
  395. next["continuation"] = ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][1]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"]
  396. const ret = {
  397. "code": 200,
  398. "msg": "",
  399. "data": {
  400. "data": videos,
  401. "next": JSON.stringify(next),
  402. },
  403. "id": "MusicSearchResultViewModel_search_result"
  404. }
  405. console.log(`未携带next搜索结果成功: ${JSON.stringify(ret)}`);
  406. return ret;
  407. }
  408. } catch (e) {
  409. const ret = {
  410. "code": -1,
  411. "msg": e.toString()
  412. }
  413. console.log(`搜索失败: ${JSON.stringify(ret)}`);
  414. return ret;
  415. }
  416. }