info.js 13 KB

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