youtubev2.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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', '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.log(`WARNING: Unknown codec ${fullCodec}`);
  30. }
  31. }
  32. if (!vcodec && !acodec) {
  33. if (splitCodecs.length === 2) {
  34. return {
  35. vcodec: splitCodecs[0], acodec: splitCodecs[1]
  36. };
  37. }
  38. } else {
  39. return {
  40. vcodec: vcodec, acodec: acodec
  41. };
  42. }
  43. return {};
  44. }
  45. parseSetCookie = (headers) => {
  46. if (!headers) {
  47. return ""
  48. }
  49. const setCookie = headers['Set-Cookie']
  50. if (!setCookie) {
  51. return ""
  52. }
  53. console.log(`setCookie: ${setCookie}`)
  54. let result = 'PREF=hl=en&tz=UTC; SOCS=CAI; GPS=1; ';
  55. const needCookieNames = ['YSC', 'VISITOR_INFO1_LIVE', 'VISITOR_PRIVACY_METADATA'];
  56. for (const i in needCookieNames) {
  57. const cookieName = needCookieNames[i];
  58. const regexp = new RegExp(`${cookieName}=([^;,]+)`)
  59. const match = setCookie.match(regexp)
  60. if (match && match.length === 2) {
  61. const cookieValue = match[1]
  62. if (i !== needCookieNames.length - 1) {
  63. result += `${cookieName}=${cookieValue}; `
  64. } else {
  65. result += `${cookieName}=${cookieValue}`
  66. }
  67. }
  68. }
  69. console.log(`current cookie: ${result}`)
  70. return result;
  71. }
  72. request = async (method, url, data = null, headers = {}, requestId, platform) => {
  73. if (platform === "WEB") {
  74. url = url.replace("https://www.youtube.com/", "http://16.162.163.175:80/");
  75. url = url.replace("https://music.youtube.com/", "http://16.162.163.175:80/");
  76. }
  77. console.log(`request url:${url}`)
  78. console.log(`request data:${data}`)
  79. console.log(`request method:${method}`)
  80. console.log(`request headers:${JSON.stringify((headers))}`)
  81. if (platform === "WEB") {
  82. const res = await fetch(url, {
  83. 'mode': 'cors', 'method': method, 'headers': headers, 'body': data
  84. })
  85. const resData = await res.text()
  86. return Promise.resolve({
  87. 'data': resData, 'headers': res.headers
  88. });
  89. }
  90. return new Promise((resolve, reject) => {
  91. AF.request(url, method, data, headers, requestId, (data, headers, err) => {
  92. if (err) {
  93. reject(err);
  94. } else {
  95. console.log(`response headers: ${headers}`);
  96. resolve({
  97. 'data': data, 'headers': JSON.parse(headers)
  98. });
  99. }
  100. });
  101. })
  102. }
  103. detail = async (url, requestId, platform) => {
  104. try {
  105. const htmlResp = await request('GET', `${url}&bpctr=9999999999&has_verified=1`, null, {
  106. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
  107. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  108. 'Accept-Language': 'en-us,en;q=0.5',
  109. 'Sec-Fetch-Mode': 'navigate',
  110. 'Accept-Encoding': 'gzip, deflate, br',
  111. 'Cookie': 'PREF=hl=en&tz=UTC; SOCS=CAI'
  112. }, requestId, platform);
  113. let {data: html, headers: htmlHeaders} = htmlResp;
  114. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  115. let match = html.match(regex);
  116. if (!match || !match.length) {
  117. console.log('can not found JSON: ytInitialPlayerResponse');
  118. throw new Error('JSON not found: ytInitialPlayerResponse');
  119. }
  120. const ytInitialPlayerResponse = JSON.parse(match[1]);
  121. console.log(ytInitialPlayerResponse);
  122. const originVideoDetails = ytInitialPlayerResponse['videoDetails'];
  123. const thumbnails = []
  124. for (const item of originVideoDetails['thumbnail']['thumbnails']) {
  125. thumbnails.push({
  126. 'url': item['url'], 'width': item['width'] + "", 'height': item['height'] + ""
  127. })
  128. }
  129. let originFormats = [];
  130. // android
  131. try {
  132. const apiUrl = `https://music.youtube.com/youtubei/v1/player?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8`;
  133. const apiResp = await request('POST', apiUrl, JSON.stringify({
  134. "context": {
  135. "client": {
  136. "clientName": "ANDROID", "hl": "en", "clientVersion": "18.49.37", "gl": "US"
  137. }
  138. }, "videoId": url.replace('https://www.youtube.com/watch?v=', ''), "params": "CgIQBg"
  139. }), {
  140. 'Host': 'www.youtube.com',
  141. 'Connection': 'keep-alive',
  142. 'User-Agent': 'com.google.android.apps.youtube.music/17.31.35 (Linux; U; Android 11) gzip',
  143. 'Accept-Language': 'en-US,en',
  144. 'Cookie': parseSetCookie(htmlHeaders),
  145. 'Content-Type': 'application/json'
  146. }, requestId, platform);
  147. let {data: apiData, _} = apiResp;
  148. console.log(`android api result: ${JSON.stringify(apiResp)}`);
  149. const res = JSON.parse(apiData);
  150. const currentFormats = [];
  151. for (const format of [].concat(res["streamingData"]["formats"] || []).concat(res["streamingData"]["adaptiveFormats"] || [])) {
  152. if (format) {
  153. format["from"] = "android"
  154. currentFormats.push(format);
  155. }
  156. }
  157. originFormats = originFormats.concat(currentFormats);
  158. } catch (e) {
  159. console.log(`can not found format android api error: ${e}`);
  160. const ret = {
  161. "code": -1, "msg": e.toString()
  162. }
  163. console.log(`detail2 result error: ${JSON.stringify(ret)}`);
  164. return ret;
  165. }
  166. console.log(`after android api, format size:${originFormats.length}`);
  167. let audioUrl = ""
  168. for (let format of originFormats) {
  169. if (format["url"]) {
  170. const {vcodec, acodec} = parseCodecs(format)
  171. if (!vcodec && acodec) {
  172. audioUrl = format["url"]
  173. break
  174. }
  175. }
  176. }
  177. const formats = [];
  178. const qualities = [];
  179. for (let format of originFormats) {
  180. console.log(format);
  181. if (format["height"] && parseInt(format["height"]) > 720) {
  182. continue
  183. }
  184. if (format && qualities.indexOf(format['qualityLabel']) === -1) {
  185. if (format["url"]) {
  186. const {vcodec, acodec} = parseCodecs(format)
  187. if (vcodec && acodec) {
  188. const current = {
  189. "width": format["width"] + "",
  190. "height": format["height"] + "",
  191. "type": format["mimeType"],
  192. "quality": format["qualityLabel"],
  193. "itag": format["itag"],
  194. "fps": format["fps"] + "",
  195. "bitrate": format["bitrate"] + "",
  196. "url": format["url"],
  197. "ext": "mp4",
  198. "vcodec": vcodec,
  199. "acodec": acodec,
  200. "vbr": "0",
  201. "abr": "0",
  202. "container": "mp4_dash",
  203. "from": format["from"],
  204. "audioUrl": audioUrl
  205. }
  206. if (platform === "WEB") {
  207. current["source"] = format
  208. }
  209. formats.push(current)
  210. qualities.push(format["qualityLabel"]);
  211. } else if (vcodec && !acodec) {
  212. const current = {
  213. "width": format["width"] + "",
  214. "height": format["height"] + "",
  215. "type": format["mimeType"],
  216. "quality": format["qualityLabel"],
  217. "itag": format["itag"],
  218. "fps": format["fps"] + "",
  219. "bitrate": format["bitrate"] + "",
  220. "videoUrl": format["url"],
  221. "ext": "mp4",
  222. "vcodec": vcodec,
  223. "acodec": acodec,
  224. "vbr": "0",
  225. "abr": "0",
  226. "container": "mp4_dash",
  227. "from": format["from"],
  228. "audioUrl": audioUrl
  229. }
  230. if (platform === "WEB") {
  231. current["source"] = format
  232. }
  233. formats.push(current)
  234. qualities.push(format["qualityLabel"]);
  235. }
  236. }
  237. }
  238. }
  239. const ytInitialDataMatch = html.match(/var ytInitialData\s*=\s*({.*?});/);
  240. const recommendInfo = [];
  241. if (ytInitialDataMatch && ytInitialDataMatch.length === 2) {
  242. const ytInitialData = JSON.parse(ytInitialDataMatch[1]);
  243. console.log(ytInitialData);
  244. for (const item of ytInitialData["contents"]?.["twoColumnWatchNextResults"]?.["secondaryResults"]?.["secondaryResults"]?.["results"] || []) {
  245. if (item["compactVideoRenderer"]) {
  246. const recommendVideo = item["compactVideoRenderer"];
  247. console.log(`recommend video: ${JSON.stringify(recommendVideo)}`);
  248. if (recommendVideo["videoId"]) {
  249. recommendInfo.push({
  250. "type": "gridVideoRenderer",
  251. "videoId": recommendVideo["videoId"],
  252. "title": recommendVideo["title"]?.["simpleText"],
  253. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  254. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  255. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  256. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  257. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  258. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  259. })
  260. }
  261. }
  262. }
  263. }
  264. formats.sort((a, b) => parseInt(a["height"]) - parseInt(b["height"]));
  265. const videoDetails = {
  266. "isLiveContent": originVideoDetails["isLiveContent"],
  267. "title": originVideoDetails["title"],
  268. "thumbnails": thumbnails,
  269. "description": originVideoDetails["shortDescription"],
  270. "lengthSeconds": originVideoDetails["lengthSeconds"],
  271. "viewCount": originVideoDetails["viewCount"],
  272. "keywords": originVideoDetails["keywords"],
  273. "author": originVideoDetails["author"],
  274. "channelID": originVideoDetails["channelId"],
  275. "recommendInfo": recommendInfo,
  276. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  277. "videoId": originVideoDetails["videoId"]
  278. }
  279. const ret = {
  280. "code": 200, "msg": "", "requestId": requestId, "data": {
  281. "videoDetails": videoDetails, "streamingData": {
  282. "formats": formats
  283. }
  284. }, "id": "MusicDetailViewModel_detail_url"
  285. }
  286. console.log(`detail result: ${JSON.stringify(ret)}`);
  287. return ret;
  288. } catch (e) {
  289. const ret = {
  290. "code": -1, "msg": e.toString(), "requestId": requestId,
  291. }
  292. console.log(`detail2 result error: ${JSON.stringify(ret)}`);
  293. console.log(e);
  294. return ret;
  295. }
  296. }
  297. search = async (keyword, next, requestId, platform) => {
  298. try {
  299. console.log(`search keyword: ${keyword}`);
  300. console.log(`search next: ${next}`);
  301. if (next) {
  302. const nextObject = JSON.parse(next);
  303. const key = nextObject["key"];
  304. const body = {
  305. context: {
  306. client: {
  307. clientName: "WEB", clientVersion: "2.20240506.01.00",
  308. },
  309. }, continuation: nextObject["continuation"]
  310. };
  311. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, requestId, platform);
  312. const {data, _} = res;
  313. res = JSON.parse(data);
  314. const videos = [];
  315. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  316. const video = item["videoRenderer"];
  317. console.log(video);
  318. if (video && video["videoId"] && video["lengthText"]) {
  319. videos.push({
  320. "type": "videoWithContextRenderer", "data": {
  321. "videoId": video["videoId"],
  322. "title": video["title"]?.["runs"]?.[0]?.["text"],
  323. "thumbnails": video["thumbnail"]?.["thumbnails"],
  324. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  325. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  326. "viewCountText": video["viewCountText"]?.["simpleText"],
  327. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  328. "lengthText": video["lengthText"]?.["simpleText"]
  329. }
  330. });
  331. }
  332. }
  333. const ret = {
  334. "code": 200, "msg": "", "requestId": requestId, "data": {
  335. "data": videos, "next": JSON.stringify({
  336. "key": nextObject["key"],
  337. "continuation": res["onResponseReceivedCommands"]?.[0]?.["appendContinuationItemsAction"]?.["continuationItems"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"],
  338. }),
  339. }, "id": "MusicSearchResultViewModel_search_result"
  340. }
  341. console.log(`[next] search result: ${JSON.stringify(ret)}`);
  342. return ret;
  343. } else {
  344. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  345. const htmlRes = await request('GET', url, null, {}, requestId, platform);
  346. const {data: html, _} = htmlRes;
  347. let regex = /var ytInitialData\s*=\s*({.*?});/;
  348. let match = html.match(regex);
  349. if (!match || !match.length) {
  350. console.log("can not found ytInitialData");
  351. throw new Error('JSON not found: ytInitialData');
  352. }
  353. const ytInitialDataResp = JSON.parse(match[1]);
  354. console.log(ytInitialDataResp);
  355. const videos = [];
  356. const contents = ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"] || []
  357. for (const content of contents) {
  358. const currentContents = content["itemSectionRenderer"]?.["contents"]
  359. if (Array.isArray(currentContents)) {
  360. for (const currentContent of currentContents) {
  361. if (currentContent["videoRenderer"]) {
  362. const video = currentContent["videoRenderer"];
  363. console.log(video);
  364. if (video && video["videoId"] && video["lengthText"]) {
  365. videos.push({
  366. "type": "videoWithContextRenderer", "data": {
  367. "videoId": video["videoId"],
  368. "title": video["title"]?.["runs"]?.[0]?.["text"],
  369. "thumbnails": video["thumbnail"]?.["thumbnails"],
  370. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  371. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  372. "viewCountText": video["viewCountText"]?.["simpleText"],
  373. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  374. "lengthText": video["lengthText"]?.["simpleText"]
  375. }
  376. });
  377. }
  378. }
  379. }
  380. }
  381. }
  382. let next = {};
  383. if (html.split("innertubeApiKey").length > 0) {
  384. next["key"] = html
  385. .split("innertubeApiKey")[1]
  386. .trim()
  387. .split(",")[0]
  388. .split('"')[2];
  389. }
  390. next["continuation"] = contents[contents.length - 1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"]
  391. const ret = {
  392. "code": 200, "msg": "", "requestId": requestId, "data": {
  393. "data": videos, "next": JSON.stringify(next),
  394. }, "id": "MusicSearchResultViewModel_search_result"
  395. }
  396. console.log(`unnext search result: ${JSON.stringify(ret)}`);
  397. return ret;
  398. }
  399. } catch (e) {
  400. const ret = {
  401. "code": -1, "msg": e.toString(), "requestId": requestId,
  402. }
  403. console.log(`search result error: ${JSON.stringify(ret)}`);
  404. return ret;
  405. }
  406. }