youtubev1.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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=AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w`;
  169. const apiResp = await request('POST', apiUrl, JSON.stringify({
  170. "context": {
  171. "client": {
  172. "clientName": "ANDROID",
  173. "clientVersion": "19.09.37",
  174. "androidSdkVersion": 30,
  175. "userAgent": "com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip",
  176. "hl": "en",
  177. "timeZone": "UTC",
  178. "utcOffsetMinutes": 0
  179. }
  180. },
  181. "params": "CgIIAQ==",
  182. "playbackContext": {
  183. "contentPlaybackContext": {
  184. "html5Preference": "HTML5_PREF_WANTS"
  185. }
  186. },
  187. "contentCheckOk": true,
  188. "videoId": url.replace('https://www.youtube.com/watch?v=', '')
  189. }), {
  190. // 'Host': 'www.youtube.com',
  191. // 'Connection': 'keep-alive',
  192. // 'User-Agent': 'com.google.android.apps.youtube.music/17.31.35 (Linux; U; Android 11) gzip',
  193. // 'Accept-Language': 'en-US,en',
  194. // 'Cookie': parseSetCookie(htmlHeaders),
  195. // 'Content-Type': 'application/json'
  196. }, requestId, platform);
  197. let {data: apiData, _} = apiResp;
  198. console.log(`android api result: ${JSON.stringify(apiResp)}`);
  199. const res = JSON.parse(apiData);
  200. const currentFormats = [];
  201. originVideoDetails = res["videoDetails"];
  202. for (const format of [].concat(res["streamingData"]["formats"] || []).concat(res["streamingData"]["adaptiveFormats"] || [])) {
  203. if (format) {
  204. format["from"] = "android"
  205. currentFormats.push(format);
  206. }
  207. }
  208. originFormats = originFormats.concat(currentFormats);
  209. } catch (e) {
  210. console.log(`can not found format android api error: ${e}`);
  211. const ret = {
  212. "code": -1,
  213. "msg": e.toString(),
  214. "requestId": requestId
  215. }
  216. console.log(`detail2 result error: ${JSON.stringify(ret)}`);
  217. return ret;
  218. }
  219. console.log(`after android api, format size:${originFormats.length}`);
  220. let qualities = [];
  221. const formats = [];
  222. for (let format of originFormats) {
  223. if (printable(platform)) {
  224. console.log(format);
  225. }
  226. if (format && qualities.indexOf(format['itag']) === -1) {
  227. if (format["url"]) {
  228. const {vcodec, acodec} = parseCodecs(format)
  229. if (vcodec && acodec) {
  230. const current = {
  231. "width": format["width"] + "",
  232. "height": format["height"] + "",
  233. "type": format["mimeType"],
  234. "quality": format["qualityLabel"],
  235. "itag": format["itag"],
  236. "fps": format["fps"] + "",
  237. "bitrate": format["bitrate"] + "",
  238. "url": format["url"],
  239. "ext": "mp4",
  240. "vcodec": vcodec,
  241. "acodec": acodec,
  242. "vbr": "0",
  243. "abr": "0",
  244. "container": "mp4_dash",
  245. "from": format["from"],
  246. "source": format
  247. }
  248. formats.push(current)
  249. qualities.push(format["qualityLabel"]);
  250. }
  251. }
  252. }
  253. }
  254. for (const item of originVideoDetails['thumbnail']['thumbnails']) {
  255. thumbnails.push({
  256. 'url': item['url'], 'width': item['width'] + "", 'height': item['height'] + ""
  257. })
  258. }
  259. formats.sort((a, b) => parseInt(a["height"]) - parseInt(b["height"]));
  260. const videoDetails = {
  261. "isLiveContent": originVideoDetails["isLiveContent"],
  262. "title": originVideoDetails["title"],
  263. "thumbnails": thumbnails,
  264. "description": originVideoDetails["shortDescription"],
  265. "lengthSeconds": originVideoDetails["lengthSeconds"],
  266. "viewCount": originVideoDetails["viewCount"],
  267. "keywords": originVideoDetails["keywords"],
  268. "author": originVideoDetails["author"],
  269. "channelID": originVideoDetails["channelId"],
  270. "recommendInfo": recommendInfo,
  271. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  272. "videoId": originVideoDetails["videoId"]
  273. }
  274. const ret = {
  275. "code": 200,
  276. "msg": "",
  277. "data": {
  278. "videoDetails": videoDetails,
  279. "streamingData": {
  280. "formats": formats
  281. }
  282. },
  283. "id": "MusicDetailViewModel_detail_url",
  284. "requestId": requestId
  285. }
  286. console.log(`detail result: ${JSON.stringify(ret)}`);
  287. return ret;
  288. } catch (e) {
  289. const ret = {
  290. "code": -1,
  291. "msg": e.toString(),
  292. "requestId": requestId
  293. }
  294. console.log(`detail2 result error: ${JSON.stringify(ret)}`);
  295. console.log(e);
  296. return ret;
  297. }
  298. }
  299. search = async (keyword, next, requestId, platform) => {
  300. try {
  301. console.log(`search keyword: ${keyword}`);
  302. console.log(`search next: ${next}`);
  303. if (next) {
  304. const nextObject = JSON.parse(next);
  305. const key = nextObject["key"];
  306. const body = {
  307. context: {
  308. client: {
  309. clientName: "WEB",
  310. clientVersion: "2.20240506.01.00",
  311. },
  312. },
  313. continuation: nextObject["continuation"]
  314. };
  315. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, requestId, platform);
  316. const {data, _} = res;
  317. res = JSON.parse(data);
  318. const videos = [];
  319. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  320. const video = item["videoRenderer"];
  321. if (printable(platform)) {
  322. console.log(video);
  323. }
  324. if (video && video["videoId"] && video["lengthText"]) {
  325. videos.push({
  326. "type": "videoWithContextRenderer",
  327. "data": {
  328. "videoId": video["videoId"],
  329. "title": video["title"]?.["runs"]?.[0]?.["text"],
  330. "thumbnails": video["thumbnail"]?.["thumbnails"],
  331. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  332. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  333. "viewCountText": video["viewCountText"]?.["simpleText"],
  334. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  335. "lengthText": video["lengthText"]?.["simpleText"]
  336. }
  337. });
  338. }
  339. }
  340. const ret = {
  341. "code": 200,
  342. "msg": "",
  343. "data": {
  344. "data": videos,
  345. "next": JSON.stringify({
  346. "key": nextObject["key"],
  347. "continuation": res["onResponseReceivedCommands"]?.[0]?.["appendContinuationItemsAction"]?.["continuationItems"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"],
  348. }),
  349. },
  350. "id": "MusicSearchResultViewModel_search_result",
  351. "requestId": requestId
  352. }
  353. console.log(`[next] search result: ${JSON.stringify(ret)}`);
  354. return ret;
  355. } else {
  356. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  357. const htmlRes = await request('GET', url, null, {}, requestId, platform);
  358. const {data: html, _} = htmlRes;
  359. let regex = /var ytInitialData\s*=\s*({.*?});/;
  360. let match = html.match(regex);
  361. if (!match || !match.length) {
  362. console.log("can not found ytInitialData");
  363. throw new Error('JSON not found: ytInitialData');
  364. }
  365. const ytInitialDataResp = JSON.parse(match[1]);
  366. if (printable(platform)) {
  367. console.log(ytInitialDataResp);
  368. }
  369. const videos = [];
  370. const contents = ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"] || []
  371. for (const content of contents) {
  372. const currentContents = content["itemSectionRenderer"]?.["contents"]
  373. if (Array.isArray(currentContents)) {
  374. for (const currentContent of currentContents) {
  375. if (currentContent["videoRenderer"]) {
  376. const video = currentContent["videoRenderer"];
  377. if (printable(platform)) {
  378. console.log(video);
  379. }
  380. if (video && video["videoId"] && video["lengthText"]) {
  381. videos.push({
  382. "type": "videoWithContextRenderer",
  383. "data": {
  384. "videoId": video["videoId"],
  385. "title": video["title"]?.["runs"]?.[0]?.["text"],
  386. "thumbnails": video["thumbnail"]?.["thumbnails"],
  387. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  388. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  389. "viewCountText": video["viewCountText"]?.["simpleText"],
  390. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  391. "lengthText": video["lengthText"]?.["simpleText"]
  392. }
  393. });
  394. }
  395. }
  396. }
  397. }
  398. }
  399. let next = {};
  400. if (html.split("innertubeApiKey").length > 0) {
  401. next["key"] = html
  402. .split("innertubeApiKey")[1]
  403. .trim()
  404. .split(",")[0]
  405. .split('"')[2];
  406. }
  407. next["continuation"] = contents[contents.length - 1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"]
  408. const ret = {
  409. "code": 200,
  410. "msg": "",
  411. "data": {
  412. "data": videos,
  413. "next": JSON.stringify(next),
  414. },
  415. "id": "MusicSearchResultViewModel_search_result",
  416. "requestId": requestId
  417. }
  418. console.log(`unnext search result: ${JSON.stringify(ret)}`);
  419. return ret;
  420. }
  421. } catch (e) {
  422. const ret = {
  423. "code": -1,
  424. "msg": e.toString(),
  425. "requestId": requestId
  426. }
  427. console.log(`search result error: ${JSON.stringify(ret)}`);
  428. return ret;
  429. }
  430. }