info.js 15 KB

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