Ben 11 月之前
父節點
當前提交
e01acc07a2
共有 2 個文件被更改,包括 74 次插入74 次删除
  1. 56 56
      js/info.js
  2. 18 18
      js/test.js

+ 56 - 56
js/info.js

@@ -50,25 +50,66 @@ parseCodecs = (format) => {
     return {};
 }
 
+request = async (method, url, data = null, headers = {}, local) => {
+    if (local) {
+        url = url.replace("https://www.youtube.com", "http://127.0.0.1");
+    }
+    console.log(`请求url:${url}`)
+    console.log(`请求data:${data}`)
+    console.log(`请求method:${method}`)
+    console.log(`请求headers:${JSON.stringify((headers))}`)
+    if (local) {
+        return fetch(url, {
+            "method": method,
+            "headers": headers,
+            "body": data,
+        }).then(res => res.text())
+    }
+    return new Promise((resolve, reject) => {
+        AF.request(url, method, data, headers, (data, err) => {
+            if (err) {
+                console.log(`请求失败: ${err}`)
+                reject(err);
+            } else {
+                resolve(data);
+            }
+        });
+    })
+}
+
 getStringBetween = (string, needleStart, needleEnd, offsetStart = 0, offsetEnd = 0) => {
     const x = string.indexOf(needleStart);
     const y = needleEnd ? string.indexOf(needleEnd, x) : string.length;
     return string.substring(x + needleStart.length + offsetEnd, y + offsetStart);
 }
 
-var cache = {}
+getDecipherFunction = (string) => {
+    const js = string.replace("var _yt_player={}", "");
+    const top = getStringBetween(js, `a=a.split("")`, "};", 1, -28);
+    const beginningOfFunction =
+        "var " + getStringBetween(top, `a=a.split("")`, "(", 10, 1).split(".")[0] + "=";
+    const side = getStringBetween(js, beginningOfFunction, "};", 2, -beginningOfFunction.length);
+    console.log(`side: ${side}`);
+    console.log(`top: ${top}`);
+    return eval(side + top);
+};
+
+const cache = {};
 extractJSSignatureFunction = async (baseJsUrl, local) => {
     console.log(`解析baseUrl: ${baseJsUrl}`);
-    if (cache[baseJsUrl]) {
+    const cacheKey = `js:${baseJsUrl}`;
+    if (cache[cacheKey]) {
         console.log(`从缓存中获取JSSignatureFunction: ${baseJsUrl}`);
-        return cache[baseJsUrl];
+        return cache[cacheKey];
     }
     const headers = {
         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.101 Safari/537.36',
     }
     const baseContent = await request('GET', baseJsUrl, null, headers, local);
     const decipher = getDecipherFunction(baseContent);
-    cache[baseJsUrl] = decipher;
+    if (decipher) {
+        cache[cacheKey] = decipher;
+    }
     return decipher;
 }
 
@@ -84,43 +125,6 @@ getUrlFromSignature = async (signatureCipher, baseJsUrl, local) => {
     return `${url}&${sp}=${decipher(signature)}`;
 }
 
-getDecipherFunction = (string) => {
-    const js = string.replace("var _yt_player={}", "");
-    const top = getStringBetween(js, `a=a.split("")`, "};", 1, -28);
-    const beginningOfFunction =
-        "var " + getStringBetween(top, `a=a.split("")`, "(", 10, 1).split(".")[0] + "=";
-    const side = getStringBetween(js, beginningOfFunction, "};", 2, -beginningOfFunction.length);
-    console.log(side + top);
-    return eval(side + top);
-};
-
-request = async (method, url, data = null, headers = {}, local) => {
-    if (local) {
-        url = url.replace("https://www.youtube.com", "http://127.0.0.1");
-    }
-    console.log(`请求url:${url}`)
-    console.log(`请求data:${data}`)
-    console.log(`请求method:${method}`)
-    console.log(`请求headers:${JSON.stringify((headers))}`)
-    if (local) {
-        return fetch(url, {
-            "method": method,
-            "headers": headers,
-            "body": data,
-        }).then(res => res.text())
-    }
-    return new Promise((resolve, reject) => {
-        AF.request(url, method, data, headers, (data, err) => {
-            if (err) {
-                console.log(`请求失败: ${err}`)
-                reject(err);
-            } else {
-                resolve(data);
-            }
-        });
-    })
-}
-
 detail = async (url, local) => {
     try {
         console.log(`接受到解析请求: ${url}`);
@@ -136,8 +140,8 @@ detail = async (url, local) => {
             throw new Error('JSON not found.');
         }
         const ytInitialPlayerResponse = JSON.parse(match[1]);
-        console.log(`ytInitialPlayerResponse: ${JSON.stringify(ytInitialPlayerResponse)}`)
         const originVideoDetails = ytInitialPlayerResponse["videoDetails"];
+        console.log(`videoDetails: ${JSON.stringify(originVideoDetails)}`);
         const thumbnails = []
         for (const item of originVideoDetails["thumbnail"]["thumbnails"]) {
             thumbnails.push({
@@ -147,12 +151,10 @@ detail = async (url, local) => {
             })
         }
 
-        let baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
-        console.log(`解析baseUrl: ${baseJsUrl}`);
-
         const formats = []
+        const baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
         for (let format of [].concat(ytInitialPlayerResponse["streamingData"]["formats"]).concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
-            console.log(`format: ${JSON.stringify(format)}`);
+            console.log(`current format: ${JSON.stringify(format)}`);
             if (!format["url"]) {
                 format["url"] = await getUrlFromSignature(format["signatureCipher"], baseJsUrl, local);
             }
@@ -186,7 +188,6 @@ detail = async (url, local) => {
             throw new Error('JSON not found.');
         }
         const ytInitialData = JSON.parse(match[1]);
-        console.log(`ytInitialData: ${JSON.stringify(ytInitialData)}`);
         const recommendInfo = [];
         for (const item of ytInitialData["contents"]["twoColumnWatchNextResults"]["secondaryResults"]["secondaryResults"]["results"]) {
             if (item["compactVideoRenderer"]) {
@@ -241,14 +242,14 @@ detail = async (url, local) => {
             "msg": e.toString()
         }
         console.log(`解析失败: ${JSON.stringify(ret)}`);
-        return ret
+        return ret;
     }
 }
 
 search = async (keyword, next, local) => {
     try {
-        console.log(`接受到搜索请求: ${keyword}`);
-        console.log(`next: ${next}`);
+        console.log(`接受到搜索请求 keyword: ${keyword}`);
+        console.log(`接收到搜索请求 next: ${next}`);
         if (next) {
             const nextObject = JSON.parse(next);
             const key = nextObject["key"];
@@ -263,10 +264,10 @@ search = async (keyword, next, local) => {
             };
             let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, local);
             res = JSON.parse(res);
-            console.log(`搜索结果res: ${JSON.stringify(res)}`)
             const videos = [];
             for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
                 const video = item["videoRenderer"];
+                console.log(`搜索结果: ${JSON.stringify(video)}`);
                 if (video && video["videoId"]) {
                     videos.push({
                         "type": "videoWithContextRenderer",
@@ -295,7 +296,7 @@ search = async (keyword, next, local) => {
                 },
                 "id": "MusicSearchResultViewModel_search_result"
             }
-            console.log(`搜索结果成功1: ${JSON.stringify(ret)}`);
+            console.log(`携带next搜索结果成功: ${JSON.stringify(ret)}`);
             return ret;
         } else {
             let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
@@ -310,11 +311,11 @@ search = async (keyword, next, local) => {
             }
 
             const ytInitialDataResp = JSON.parse(match[1]);
-            console.log(`ytInitialDataResp: ${JSON.stringify(ytInitialDataResp)}`);
             const videos = [];
             for (const item of ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"]) {
                 if (item["videoRenderer"]) {
                     const video = item["videoRenderer"];
+                    console.log(`搜索结果: ${JSON.stringify(video)}`);
                     if (video && video["videoId"]) {
                         videos.push({
                             "type": "videoWithContextRenderer",
@@ -335,7 +336,6 @@ search = async (keyword, next, local) => {
 
             let next = {};
             if (html.split("innertubeApiKey").length > 0) {
-                // 写入path
                 next["key"] = html
                     .split("innertubeApiKey")[1]
                     .trim()
@@ -353,7 +353,7 @@ search = async (keyword, next, local) => {
                 },
                 "id": "MusicSearchResultViewModel_search_result"
             }
-            console.log(`搜索结果成功2: ${JSON.stringify(ret)}`);
+            console.log(`未携带next搜索结果成功: ${JSON.stringify(ret)}`);
             return ret;
         }
     } catch (e) {
@@ -361,7 +361,7 @@ search = async (keyword, next, local) => {
             "code": -1,
             "msg": e.toString()
         }
-        console.log(`解析失败: ${JSON.stringify(ret)}`);
+        console.log(`搜索失败: ${JSON.stringify(ret)}`);
         return ret;
     }
 }

+ 18 - 18
js/test.js

@@ -15,21 +15,21 @@ detail(url, true)
     .catch(e => {
         console.log(e);
     })
-//
-// search("周 杰伦", null, true)
-//     .then(res => {
-//         console.log(res);
-//
-//         const next = res["data"]["next"];
-//         console.log(next);
-//         search("周 杰伦", next, true)
-//             .then(nextRes => {
-//                 console.log(nextRes);
-//             })
-//             .catch(e => {
-//                 console.log(e);
-//             })
-//     })
-//     .catch(e => {
-//         console.log(e);
-//     })
+
+search("周 杰伦", null, true)
+    .then(res => {
+        console.log(res);
+
+        const next = res["data"]["next"];
+        console.log(next);
+        search("周 杰伦", next, true)
+            .then(nextRes => {
+                console.log(nextRes);
+            })
+            .catch(e => {
+                console.log(e);
+            })
+    })
+    .catch(e => {
+        console.log(e);
+    })