youtubev1.js 19 KB

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