info.js 14 KB

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