youtubev1.js 18 KB

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