youtubev2.js 20 KB

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