info.js 13 KB

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