20240510202531 15 KB

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