Ben 11 ماه پیش
والد
کامیت
12da9544e4
2فایلهای تغییر یافته به همراه52 افزوده شده و 43 حذف شده
  1. 49 41
      js/info.js
  2. 3 2
      js/main.swift

+ 49 - 41
js/info.js

@@ -1,4 +1,4 @@
-function parseCodecs(format) {
+parseCodecs = (format) => {
     const mimeType = format["mimeType"]
     if (!mimeType) {
         return {};
@@ -50,28 +50,6 @@ function 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");
-    }
-    if (local) {
-        console.log(url);
-        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) {
-                reject(err);
-            }
-            resolve(data);
-        });
-    })
-}
-
 getStringBetween = (string, needleStart, needleEnd, offsetStart = 0, offsetEnd = 0) => {
     const x = string.indexOf(needleStart);
     const y = needleEnd ? string.indexOf(needleEnd, x) : string.length;
@@ -100,27 +78,54 @@ getDecipherFunction = (string) => {
     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:${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);
+        console.log(`接受到解析请求: ${url}`);
         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 html = await request('GET', url, null, headers, local);
 
         let baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
-
-        console.log(baseJsUrl);
+        console.log(`解析baseUrl: ${baseJsUrl}`);
 
         const baseContent = await request('GET', baseJsUrl, null, headers, local);
 
         let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
         let match = html.match(regex);
         if (!match || !match.length) {
+            console.log("解释失败: 无法找到json");
             throw new Error('JSON not found.');
         }
         const ytInitialPlayerResponse = JSON.parse(match[1]);
-        console.log(ytInitialPlayerResponse);
+        console.log(`ytInitialPlayerResponse: ${JSON.stringify(ytInitialPlayerResponse)}`)
         const originVideoDetails = ytInitialPlayerResponse["videoDetails"];
         const thumbnails = []
         for (const item of originVideoDetails["thumbnail"]["thumbnails"]) {
@@ -133,7 +138,7 @@ detail = async (url, local) => {
 
         const formats = []
         for (let format of [].concat(ytInitialPlayerResponse["streamingData"]["formats"]).concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
-            console.log(format);
+            console.log(`format: ${JSON.stringify(format)}`);
             if (!format["url"]) {
                 format["url"] = getUrlFromSignature(format["signatureCipher"], baseContent);
             }
@@ -163,13 +168,11 @@ detail = async (url, local) => {
         regex = /var ytInitialData\s*=\s*({.*?});/;
         match = html.match(regex);
         if (!match || !match.length) {
-            throw new Error('JSON not found.');
-        }
-        if (!match || !match.length) {
+            console.log(`解析失败,无法找到 ytInitialData`);
             throw new Error('JSON not found.');
         }
         const ytInitialData = JSON.parse(match[1]);
-        console.log(ytInitialData);
+        console.log(`ytInitialData: ${JSON.stringify(ytInitialData)}`);
         const recommendInfo = [];
         for (const item of ytInitialData["contents"]["twoColumnWatchNextResults"]["secondaryResults"]["secondaryResults"]["results"]) {
             if (item["compactVideoRenderer"]) {
@@ -216,19 +219,22 @@ detail = async (url, local) => {
             },
             "id": "MusicDetailViewModel_detail_url"
         }
-        console.log(ret);
+        console.log(`解析结果: ${JSON.stringify(ret)}`);
         return ret;
     } catch (e) {
-        console.log(e);
-        return {
+        const ret = {
             "code": -1,
             "msg": e.toString()
         }
+        console.log(`解析失败: ${JSON.stringify(ret)}`);
+        return ret
     }
 }
 
 search = async (keyword, next, local) => {
     try {
+        console.log(`接受到搜索请求: ${keyword}`);
+        console.log(`next: ${next}`);
         if (next) {
             const nextObject = JSON.parse(next);
             const key = nextObject["key"];
@@ -243,7 +249,7 @@ 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);
+            console.log(`搜索结果res: ${JSON.stringify(res)}`)
             const videos = [];
             for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
                 const video = item["videoRenderer"];
@@ -275,7 +281,7 @@ search = async (keyword, next, local) => {
                 },
                 "id": "MusicSearchResultViewModel_search_result"
             }
-            console.log(ret);
+            console.log(`搜索结果成功1: ${JSON.stringify(ret)}`);
             return ret;
         } else {
             let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
@@ -285,11 +291,12 @@ search = async (keyword, next, local) => {
             let regex = /var ytInitialData\s*=\s*({.*?});/;
             let match = html.match(regex);
             if (!match || !match.length) {
+                console.log("搜索失败:无法找到ytInitialData");
                 throw new Error('JSON not found.');
             }
 
             const ytInitialDataResp = JSON.parse(match[1]);
-            console.log(ytInitialDataResp);
+            console.log(`ytInitialDataResp: ${JSON.stringify(ytInitialDataResp)}`);
             const videos = [];
             for (const item of ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"]) {
                 if (item["videoRenderer"]) {
@@ -332,14 +339,15 @@ search = async (keyword, next, local) => {
                 },
                 "id": "MusicSearchResultViewModel_search_result"
             }
-            console.log(ret);
+            console.log(`搜索结果成功2: ${ret}`);
             return ret;
         }
     } catch (e) {
-        console.log(e);
-        return {
+        const ret = {
             "code": -1,
             "msg": e.toString()
         }
+        console.log(`解析失败: ${JSON.stringify(ret)}`);
+        return ret;
     }
 }

+ 3 - 2
js/main.swift

@@ -58,6 +58,7 @@ func createJSContext() -> JSContext {
     // 捕捉JS运行异常
     ctx?.exceptionHandler = { context, exception in
         if let exception = exception {
+            debugPrint(exception)
             print("JS 执行异常: \(exception)")
         }
     }
@@ -129,8 +130,8 @@ if let url = URL(string: "http://hubgit.cn/ben/be-ytb/raw/master/js/info.js") {
         case .success(let jsString):
             print("下载远程JS成功")
             ctx.evaluateScript(jsString)
-            testDetail(url: "https://www.youtube.com/watch?v=7wNb0pHyGuI", ctx: ctx)
-//            testSearch(keyword: "周杰伦", ctx: ctx)
+//            testDetail(url: "https://www.youtube.com/watch?v=7wNb0pHyGuI", ctx: ctx)
+            testSearch(keyword: "周杰伦", ctx: ctx)
         case .failure(let error):
             print("Download Error: \(error)")
         }