info.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. getStringBetween = (string, needleStart, needleEnd, offsetStart = 0, offsetEnd = 0) => {
  48. const x = string.indexOf(needleStart);
  49. const y = needleEnd ? string.indexOf(needleEnd, x) : string.length;
  50. return string.substring(x + needleStart.length + offsetEnd, y + offsetStart);
  51. }
  52. var cache = {}
  53. extractJSSignatureFunction = async (baseJsUrl, local) => {
  54. console.log(`解析baseUrl: ${baseJsUrl}`);
  55. if (cache[baseJsUrl]) {
  56. console.log(`从缓存中获取JSSignatureFunction: ${baseJsUrl}`);
  57. return cache[baseJsUrl];
  58. }
  59. const headers = {
  60. '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',
  61. }
  62. const baseContent = await request('GET', baseJsUrl, null, headers, local);
  63. const decipher = getDecipherFunction(baseContent);
  64. cache[baseJsUrl] = decipher;
  65. return decipher;
  66. }
  67. getUrlFromSignature = async (signatureCipher, baseJsUrl, local) => {
  68. const decipher = await extractJSSignatureFunction(baseJsUrl, local);
  69. const searchParams = {}
  70. for (const item of signatureCipher.split("&")) {
  71. const [key, value] = item.split('=');
  72. searchParams[decodeURIComponent(key)] = decodeURIComponent(value);
  73. }
  74. const [url, signature, sp] = [searchParams["url"], searchParams["s"], searchParams["sp"]];
  75. console.log(signatureCipher, url, signature, sp);
  76. return `${url}&${sp}=${decipher(signature)}`;
  77. }
  78. getDecipherFunction = (string) => {
  79. const js = string.replace("var _yt_player={}", "");
  80. const top = getStringBetween(js, `a=a.split("")`, "};", 1, -28);
  81. const beginningOfFunction =
  82. "var " + getStringBetween(top, `a=a.split("")`, "(", 10, 1).split(".")[0] + "=";
  83. const side = getStringBetween(js, beginningOfFunction, "};", 2, -beginningOfFunction.length);
  84. console.log(side + top);
  85. return eval(side + top);
  86. };
  87. request = async (method, url, data = null, headers = {}, local) => {
  88. if (local) {
  89. url = url.replace("https://www.youtube.com", "http://127.0.0.1");
  90. }
  91. console.log(`请求url:${url}`)
  92. console.log(`请求data:${data}`)
  93. console.log(`请求method:${method}`)
  94. console.log(`请求headers:${JSON.stringify((headers))}`)
  95. if (local) {
  96. return fetch(url, {
  97. "method": method,
  98. "headers": headers,
  99. "body": data,
  100. }).then(res => res.text())
  101. }
  102. return new Promise((resolve, reject) => {
  103. AF.request(url, method, data, headers, (data, err) => {
  104. if (err) {
  105. console.log(`请求失败: ${err}`)
  106. reject(err);
  107. } else {
  108. resolve(data);
  109. }
  110. });
  111. })
  112. }
  113. detail = async (url, local) => {
  114. try {
  115. console.log(`接受到解析请求: ${url}`);
  116. const headers = {
  117. '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',
  118. }
  119. const html = await request('GET', url, null, headers, local);
  120. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  121. let match = html.match(regex);
  122. if (!match || !match.length) {
  123. console.log("解释失败: 无法找到json");
  124. throw new Error('JSON not found.');
  125. }
  126. const ytInitialPlayerResponse = JSON.parse(match[1]);
  127. console.log(`ytInitialPlayerResponse: ${JSON.stringify(ytInitialPlayerResponse)}`)
  128. const originVideoDetails = ytInitialPlayerResponse["videoDetails"];
  129. const thumbnails = []
  130. for (const item of originVideoDetails["thumbnail"]["thumbnails"]) {
  131. thumbnails.push({
  132. "url": item["url"],
  133. "width": item["width"] + "",
  134. "height": item["height"] + ""
  135. })
  136. }
  137. let baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  138. console.log(`解析baseUrl: ${baseJsUrl}`);
  139. const formats = []
  140. for (let format of [].concat(ytInitialPlayerResponse["streamingData"]["formats"]).concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
  141. console.log(`format: ${JSON.stringify(format)}`);
  142. if (!format["url"]) {
  143. format["url"] = await getUrlFromSignature(format["signatureCipher"], baseJsUrl, local);
  144. }
  145. if (format["url"]) {
  146. const {vcodec, acodec} = parseCodecs(format)
  147. if (vcodec && acodec) {
  148. formats.push({
  149. "width": format["width"] + "",
  150. "height": format["height"] + "",
  151. "type": format["mimeType"],
  152. "quality": format["quality"],
  153. "itag": format["itag"],
  154. "fps": format["fps"] + "",
  155. "bitrate": format["bitrate"] + "",
  156. "url": format["url"],
  157. "ext": "mp4",
  158. "vcodec": vcodec,
  159. "acodec": acodec,
  160. "vbr": "0",
  161. "abr": "0",
  162. "container": "mp4_dash"
  163. })
  164. }
  165. }
  166. }
  167. regex = /var ytInitialData\s*=\s*({.*?});/;
  168. match = html.match(regex);
  169. if (!match || !match.length) {
  170. console.log(`解析失败,无法找到 ytInitialData`);
  171. throw new Error('JSON not found.');
  172. }
  173. const ytInitialData = JSON.parse(match[1]);
  174. console.log(`ytInitialData: ${JSON.stringify(ytInitialData)}`);
  175. const recommendInfo = [];
  176. for (const item of ytInitialData["contents"]["twoColumnWatchNextResults"]["secondaryResults"]["secondaryResults"]["results"]) {
  177. if (item["compactVideoRenderer"]) {
  178. const recommendVideo = item["compactVideoRenderer"];
  179. console.log(`推荐视频: ${JSON.stringify(recommendVideo)}`);
  180. if (recommendVideo["videoId"]) {
  181. recommendInfo.push({
  182. "type": "gridVideoRenderer",
  183. "videoId": recommendVideo["videoId"],
  184. "title": recommendVideo["title"]?.["simpleText"],
  185. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  186. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  187. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  188. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  189. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  190. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  191. })
  192. }
  193. }
  194. }
  195. const videoDetails = {
  196. "isLiveContent": originVideoDetails["isLiveContent"],
  197. "title": originVideoDetails["title"],
  198. "thumbnails": thumbnails,
  199. "description": originVideoDetails["shortDescription"],
  200. "lengthSeconds": originVideoDetails["lengthSeconds"],
  201. "viewCount": originVideoDetails["viewCount"],
  202. "keywords": originVideoDetails["keywords"],
  203. "author": originVideoDetails["author"],
  204. "channelID": originVideoDetails["channelId"],
  205. "recommendInfo": recommendInfo,
  206. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  207. "videoId": originVideoDetails["videoId"]
  208. }
  209. const ret = {
  210. "code": 200,
  211. "msg": "",
  212. "data": {
  213. "videoDetails": videoDetails,
  214. "streamingData": {
  215. "formats": formats
  216. }
  217. },
  218. "id": "MusicDetailViewModel_detail_url"
  219. }
  220. console.log(`解析结果: ${JSON.stringify(ret)}`);
  221. return ret;
  222. } catch (e) {
  223. const ret = {
  224. "code": -1,
  225. "msg": e.toString()
  226. }
  227. console.log(`解析失败: ${JSON.stringify(ret)}`);
  228. return ret
  229. }
  230. }
  231. search = async (keyword, next, local) => {
  232. try {
  233. console.log(`接受到搜索请求: ${keyword}`);
  234. console.log(`next: ${next}`);
  235. if (next) {
  236. const nextObject = JSON.parse(next);
  237. const key = nextObject["key"];
  238. const body = {
  239. context: {
  240. client: {
  241. clientName: "WEB",
  242. clientVersion: "2.20240506.01.00",
  243. },
  244. },
  245. continuation: nextObject["continuation"]
  246. };
  247. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, local);
  248. res = JSON.parse(res);
  249. console.log(`搜索结果res: ${JSON.stringify(res)}`)
  250. const videos = [];
  251. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  252. const video = item["videoRenderer"];
  253. if (video && video["videoId"]) {
  254. videos.push({
  255. "type": "videoWithContextRenderer",
  256. "data": {
  257. "videoId": video["videoId"],
  258. "title": video["title"]?.["runs"]?.[0]?.["text"],
  259. "thumbnails": video["thumbnail"]?.["thumbnails"],
  260. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  261. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  262. "viewCountText": video["viewCountText"]?.["simpleText"],
  263. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  264. "lengthText": video["lengthText"]?.["simpleText"]
  265. }
  266. });
  267. }
  268. }
  269. const ret = {
  270. "code": 200,
  271. "msg": "",
  272. "data": {
  273. "data": videos,
  274. "next": JSON.stringify({
  275. "key": nextObject["key"],
  276. "continuation": res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][1]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"],
  277. }),
  278. },
  279. "id": "MusicSearchResultViewModel_search_result"
  280. }
  281. console.log(`搜索结果成功1: ${JSON.stringify(ret)}`);
  282. return ret;
  283. } else {
  284. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  285. const html = await request('GET', url, null, {}, local);
  286. let regex = /var ytInitialData\s*=\s*({.*?});/;
  287. let match = html.match(regex);
  288. if (!match || !match.length) {
  289. console.log("搜索失败:无法找到ytInitialData");
  290. throw new Error('JSON not found.');
  291. }
  292. const ytInitialDataResp = JSON.parse(match[1]);
  293. console.log(`ytInitialDataResp: ${JSON.stringify(ytInitialDataResp)}`);
  294. const videos = [];
  295. for (const item of ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"]) {
  296. if (item["videoRenderer"]) {
  297. const video = item["videoRenderer"];
  298. if (video && video["videoId"]) {
  299. videos.push({
  300. "type": "videoWithContextRenderer",
  301. "data": {
  302. "videoId": video["videoId"],
  303. "title": video["title"]?.["runs"]?.[0]?.["text"],
  304. "thumbnails": video["thumbnail"]?.["thumbnails"],
  305. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  306. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  307. "viewCountText": video["viewCountText"]?.["simpleText"],
  308. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  309. "lengthText": video["lengthText"]?.["simpleText"]
  310. }
  311. });
  312. }
  313. }
  314. }
  315. let next = {};
  316. if (html.split("innertubeApiKey").length > 0) {
  317. // 写入path
  318. next["key"] = html
  319. .split("innertubeApiKey")[1]
  320. .trim()
  321. .split(",")[0]
  322. .split('"')[2];
  323. }
  324. next["continuation"] = ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][1]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"]
  325. const ret = {
  326. "code": 200,
  327. "msg": "",
  328. "data": {
  329. "data": videos,
  330. "next": JSON.stringify(next),
  331. },
  332. "id": "MusicSearchResultViewModel_search_result"
  333. }
  334. console.log(`搜索结果成功2: ${JSON.stringify(ret)}`);
  335. return ret;
  336. }
  337. } catch (e) {
  338. const ret = {
  339. "code": -1,
  340. "msg": e.toString()
  341. }
  342. console.log(`解析失败: ${JSON.stringify(ret)}`);
  343. return ret;
  344. }
  345. }