PUGE 2 hónapja
szülő
commit
656696a5e1
10 módosított fájl, 29 hozzáadás és 597 törlés
  1. 0 214
      back/background.js
  2. 0 111
      back/insert.js
  3. 0 60
      back/options.js
  4. 0 202
      back/popup.js
  5. 0 2
      background.html
  6. 5 4
      content-script.js
  7. 0 0
      insert-auto.js
  8. 22 0
      insert-popup.js
  9. 1 3
      js/popup.js
  10. 1 1
      manifest.json

+ 0 - 214
back/background.js

@@ -1,214 +0,0 @@
-var userInfo = {}
-
-var tempData = null
-var openList = {}
-if (localStorage.getItem('owoOpenList')) {
-  openList = JSON.parse(localStorage.getItem('owoOpenList'))
-}
-
-function saveOpenList () {
-  localStorage.setItem('owoOpenList', JSON.stringify(openList))
-}
-
-function reloadUser (callBack) {
-  chrome.storage.sync.get('userInfo', function(data) {
-    // alert(data)
-    userInfoTemp = data.userInfo
-    if (!userInfoTemp) return
-    username = userInfoTemp.username
-    password = userInfoTemp.password
-    if (username && password) {
-      fetch(`http://user.lamp.run/login`, {
-        method: 'POST',
-        headers: {
-          "Content-Type": "application/json"
-        },
-        body: JSON.stringify({
-          type: "assist",
-          username: username,
-          password: password
-        })
-      }).then((response) => {return response.json();}).then((res) => {
-        if (res.err === 0) {
-          userInfo = res.data
-          if (callBack) callBack()
-        }
-      })
-    }
-  })
-  
-}
-reloadUser()
-
-// 对数据进行处理
-function clearData (data) {
-  let returnData = []
-  data.forEach(element => {
-    if (openList[element.id] || element.type == 'autoRun') {
-      returnData.push(element)
-    }
-  })
-  return returnData
-}
-
-function reGetData (url, callBack) {
-  const nowTime = Date.parse(new Date())
-  const serverUrl = 'https://assist.lamp.run/assistAll'
-  fetch(`${serverUrl}?username=` + (userInfo.username || ''), {
-    method: 'POST',
-    body: JSON.stringify({
-      "edition": 7,
-      "url": url
-    }),
-    redirect: 'follow'
-  }).then(data => data.json()).then(dataTemp => {
-    
-    tempData = {
-      time: nowTime,
-      data: dataTemp
-    }
-    if (callBack) callBack(dataTemp)
-  })
-}
-
-// 监听消息
-chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
-  // console.log(message)
-  switch (message.name) {
-    case 'getData':
-      const nowTime = Date.parse(new Date())
-      // 缓存
-      if (tempData && (tempData.time + 60 * 60 * 1000) > nowTime) {
-        // console.log('使用缓存返回!', tempData)
-        sendResponse(clearData(tempData.data))
-      } else {
-        reGetData(message.url, (dataTemp) => {
-          sendResponse(clearData(dataTemp))
-        })
-      }
-      break;
-    case 'clear':
-      tempData = null
-      fetch(`https://assist.lamp.run/blockList`).then(data => data.json()).then(dataTemp => {
-        blockListTemp = dataTemp
-        chrome.storage.sync.set({userInfo: {}})
-        userInfo = {}
-        lanjie(dataTemp)
-        sendResponse()
-      })
-    case 'reloadUser':
-      setTimeout(() => {
-        reloadUser(() => {
-          reGetData('')
-        })
-      }, 100);
-    default:
-      break;
-  }
-  return true
-})
-
-
-var blockListTemp = null
-
-if (blockListTemp != null) {
-  lanjie(blockListTemp)
-} else {
-  fetch(`https://assist.lamp.run/blockList`).then(data => data.json()).then(dataTemp => {
-    blockListTemp = dataTemp
-    lanjie(dataTemp)
-  })
-}
-
-
-function lanjie (blockList) {
-  // 拦截请求
-  chrome.webRequest.onBeforeRequest.addListener(
-    function(details) {
-      
-      for (const key in blockList) {
-        if (details.url.includes(key) || new RegExp(key).test(details.url) || details.url == key) {
-          console.log(`拦截请求:${details.url}`)
-          console.log(`替换请求:${blockList[key]}`)
-          return {
-            redirectUrl: blockList[key]
-          }
-        }
-      }
-      return {
-        cancel: false
-      };
-    },
-    {urls: ["<all_urls>"]},
-    ["blocking"]
-  )
-}
-
-chrome.runtime.onMessageExternal.addListener(
-  function(request, sender, sendResponse) {
-    console.log(request)
-    switch (request.name) {
-      case 'sendMessage':
-        var myHeaders = new Headers();
-        myHeaders.append("Content-Type", "application/json");
-
-        var raw = JSON.stringify({
-          "first": {
-            "value": "插件提示",
-            "color": "#173177"
-          },
-          "keyword1": {
-            "value": request.keyword1,
-            "color": "#173177"
-          },
-          "keyword2": {
-            "value": request.keyword1,
-            "color": "#173177"
-          },
-          "keyword3": {
-            "value": (new Date()).toLocaleString(),
-            "color": "#173177"
-          },
-          "remark": {
-            "value": request.remark,
-            "color": "#173177"
-          }
-        });
-
-        var requestOptions = {
-          method: 'POST',
-          headers: myHeaders,
-          body: raw,
-          redirect: 'follow'
-        };
-
-        fetch(`https://message.lamp.run/workWeixin?type=${request.type}&template=EvpHwEBpG2rkLHYMtIH2ADww9JCQwEaWlTAqyoPF6xQ`, requestOptions)
-          .then(response => response.text())
-          .then(result => console.log(result))
-          .catch(error => console.log('error', error));
-      case 'notifications':
-        chrome.notifications.create(null, {
-          type: 'basic',
-          iconUrl: 'img/48.png',
-          title: request.title,
-          message: request.message
-        });
-      case 'playMusic':
-        let musicUrl = request.url ? request.url : 'https://cunchu.site/work/assist/lingyin.wav'
-        new Audio(musicUrl).play()
-        default:
-          break;
-    }
-    sendResponse('ok')
-  }
-);
-
-
-// function logResponse(responseDetails) {
-//   console.log(responseDetails);
-// }
-
-// chrome.webRequest.onCompleted.addListener(
-//   logResponse,
-//   {urls: ["<all_urls>"]}
-// );

+ 0 - 111
back/insert.js

@@ -1,111 +0,0 @@
-
-// let tempData = localStorage.getItem('tempData')
-// if (tempData) {
-//   tempData = JSON.parse(tempData)
-// }
-
-
-function addScr (data) {
-  if (!document.body) {
-    setTimeout(() => {
-      // console.info('尝试重新加载:' + data)
-      addScr (data)
-    }, 100);
-    return
-  }
-  var script = document.createElement("script");
-  script.type = "text/javascript";
-  script.charset = "UTF-8";
-  script.innerHTML = data;
-  document.body.appendChild(script)
-}
-
-function loadJS( url, callback ){
-  var script = document.createElement('script'),
-      fn = callback || function(){};
-  script.type = 'text/javascript';
-  //IE
-  if(script.readyState){
-      script.onreadystatechange = function(){
-          if( script.readyState == 'loaded' || script.readyState == 'complete' ){
-              script.onreadystatechange = null;
-              fn();
-          }
-      };
-  }else{
-      //其他浏览器
-      script.onload = function(){
-          fn();
-      };
-  }
-  script.src = url;
-  script.onerror = function() {
-    console.error(`脚本: ${url} 加载失败,正在重试!`)
-    setTimeout(() => {
-        loadJS(url, callback)
-    }, 1000);
-  }
-  document.getElementsByTagName('head')[0].appendChild(script);
-}
-
-function loadCSS (url) {
-  var headObj = document.getElementsByTagName('head')[0];
-  var cssObj = document.createElement('link');
-  cssObj.rel = 'stylesheet';
-  cssObj.href = url;
-  headObj.appendChild(cssObj);
-}
-
-// 判断是否有永久的加载数据
-
-if (localStorage.getItem('owoLoadData')) {
-  const element = JSON.parse(localStorage.getItem('owoLoadData'))
-  let urlStr = window.location.href
-  if (new RegExp(element.url).test(urlStr)) {
-    setTimeout(() => {
-      if (element.script) {
-        element.script.forEach(element => {
-          loadJS(element)
-        });
-      }
-      if (element.style) {
-        element.style.forEach(element => {
-          loadCSS(element)
-        });
-      }
-      setTimeout(() => {
-        if (element.data) addScr(element.data)
-      }, 0);
-    }, element.delay || 0);
-    
-  }
-} else {
-  // 尝试网络加载
-  chrome.runtime.sendMessage({name:"getData", url: window.location.href},function(dataTemp){
-    // console.log(dataTemp)
-    if (!dataTemp) return
-    let urlStr = window.location.href
-    dataTemp.forEach(element => {
-      if (new RegExp(element.url).test(urlStr)) {
-        setTimeout(() => {
-          if (element.script) {
-            JSON.parse(element.script).forEach(element => {
-              loadJS(element)
-            });
-          }
-          if (element.style) {
-            JSON.parse(element.style).forEach(element => {
-              loadCSS(element)
-            });
-          }
-          setTimeout(() => {
-            if (element.data) addScr(element.data)
-          }, 0);
-        }, element.delay || 0);
-        
-        return
-      }
-    })
-  })
-}
-

+ 0 - 60
back/options.js

@@ -1,60 +0,0 @@
-//在popup.js 中调用 backgourd.js 中的变量和方法,很重要
-var bg = chrome.extension.getBackgroundPage();
-
-function login (username, password) {
-  fetch(`http://user.lamp.run/login`, {
-    method: 'POST',
-    headers: {
-      "Content-Type": "application/json"
-    },
-    body: JSON.stringify({
-      type: "assist",
-      username: username,
-      password: password
-    })
-  }).then((response) => {return response.json();}).then((res) => {
-    if (res.err === 0) {
-      bg.userInfo = res.data
-      chrome.storage.sync.set({userInfo: {username, password, session: bg.userInfo.session}})
-      chrome.runtime.sendMessage({name:"reloadUser"},function() {})
-      document.querySelector('.login-box').style.display = 'none'
-      fetch(`https://assist.lamp.run/getList?username=${username}&session=${bg.userInfo.session}`).then((response) => {return response.json();}).then((res) => {
-
-        document.querySelector('#selectTable').style.display = 'block'
-        setTimeout(() => {
-          document.querySelectorAll('table input').forEach(element => {
-            element.onchange = function (e) {
-              const itemId = e.target.getAttribute("key")
-              bg.openList[itemId] = !bg.openList[itemId]
-              bg.saveOpenList()
-            }
-          });
-        }, 0);
-      })
-    } else {
-      alert(res.message)
-    }
-  })
-}
-chrome.storage.sync.get('userInfo', function(data) {
-  console.log(data)
-  const userInfo = data.userInfo
-  if (userInfo && userInfo.username && userInfo.password && userInfo.session) {
-    login(userInfo.username, userInfo.password)
-  }
-})
-// 登录按钮点击
-document.getElementsByClassName('login-button')[0].onclick = function () {
-	const username = document.getElementById('username').value
-  const password = document.getElementById('password').value
-  if (!username || !password) {
-    chrome.notifications.create(null, {
-      type: 'basic',
-      iconUrl: 'img/48.png',
-      title: '运行方案',
-      message: '用户名或密码不能为空!'
-    })
-    return
-  }
-	login(username, password)
-}

+ 0 - 202
back/popup.js

@@ -1,202 +0,0 @@
-//在popup.js 中调用 backgourd.js 中的变量和方法,很重要
-var bg = chrome.extension.getBackgroundPage();
-// bg.count = bg.count+1;
-// console.log(bg)
-const serverUrl = 'https://assist.lamp.run/assist'
-
-function owoReplaceAll(str, s1, s2) {
-  while (str.indexOf(s1) >= 0) {
-    str = str.replace(s1, s2)
-  }
-  return str
-}
-
-let userInfo = {}
-
-const getSchemeData = new Promise((resolve, reject) => {
-  getCurrentTabId((tabInfo) => {
-    setTimeout(() => {
-        const myHeaders = new Headers();
-        myHeaders.append("Content-Type", "application/json");
-        fetch(`${serverUrl}?route=search&username=${userInfo.username || 'nologin'}`, {
-            method: 'POST',
-            headers: myHeaders,
-            body: JSON.stringify({
-              "edition": 7,
-              "url": tabInfo.url
-            }),
-            redirect: 'follow'
-          }).then(data => data.json()).then(dataTemp => {
-            dataTemp.tabInfo = tabInfo
-            resolve(dataTemp)
-          })
-    }, 100);
-    
-  })
-})
-
-
-
-// 获取当前选项卡ID
-function getCurrentTabId(callback) {
-	chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
-		if(callback) callback(tabs.length ? tabs[0]: null);
-	})
-}
-
-// 登录按钮登录
-document.getElementsByClassName('userInfo')[0].onclick = function () {
-  if (!userInfo || !userInfo.username || !userInfo.password || !userInfo.session) {
-    // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
-    window.open(chrome.extension.getURL('options.html'), "_blank")
-  } else {
-    chrome.storage.sync.set({userInfo: {}})
-    chrome.runtime.sendMessage({name:"reloadUser"},function() {})
-    location.reload();
-  }
-}
-
-document.getElementsByClassName('clearTemp')[0].onclick = function () {
-  chrome.runtime.sendMessage({name:"clear"},function() {
-    alert('缓存清除成功!')
-  })
-}
-
-let dataCopy = null
-
-function load() {
-  chrome.storage.sync.get('userInfo', function(data) {
-    // alert(data)
-    userInfo = data.userInfo
-    if (!userInfo) {
-      userInfo = {}
-    }
-    if (userInfo && userInfo.username && userInfo.password && userInfo.session) {
-      document.querySelector('.userInfo').innerHTML = `${userInfo.username}`
-    }
-    // alert("页面加载完成!"); 
-    // 获取是否有脚本
-    getSchemeData.then((dataTemp) => {
-    //   console.log(dataTemp)
-      const scriptBox = document.getElementsByClassName('script-box')[0]
-      const data = dataTemp['data']
-      if (dataTemp.err !== 0 || data.length == 0) {
-        scriptBox.classList.add('no-scheme')
-        scriptBox.classList.remove('scheme')
-      } else {
-        dataCopy = data
-        let buttonHtml = ''
-        let ind = 0
-        data.forEach(element => {
-          buttonHtml += `<button data-ind="${ind}">${element.name}</button>`
-          ind++
-        });
-        document.querySelector('.button-box').innerHTML = buttonHtml
-        scriptBox.classList.add('scheme')
-        setTimeout(() => {
-          const buttonList = document.getElementsByTagName('button')
-          for (const key in buttonList) {
-            if (Object.hasOwnProperty.call(buttonList, key)) {
-              const element = buttonList[key];
-              element.onclick = function () {
-                
-                let index = this.getAttribute("data-ind")
-                index = parseInt(index)
-                let dataTempCopy = dataCopy[index]
-                switch (dataTempCopy.type) {
-                  case 'run': {
-                    chrome.notifications.create(null, {
-                      type: 'basic',
-                      iconUrl: 'img/48.png',
-                      title: dataTempCopy.name,
-                      message: '远程方案已载入并运行!'
-                    })
-                    // console.log(unescape(dataTemp.data))
-                    function decodeOwo (value) {
-                      value = owoReplaceAll(value, "'", 'owovar1')
-                      value = owoReplaceAll(value,  "`", 'owovar2')
-                      value = owoReplaceAll(value, '"', 'owovar3')
-                      value = owoReplaceAll(value, '$', 'owovar4')
-                      return value
-                    }
-                    if (dataTempCopy.data) {
-                      let execTwmp = `
-                      function owoReplaceAll(str, s1, s2) {
-                        while (str.indexOf(s1) >= 0) {
-                          str = str.replace(s1, s2)
-                        }
-                        return str
-                      }
-                      function clearOwo (value) {
-                        value = owoReplaceAll(value, 'owovar1', "'")
-                        value = owoReplaceAll(value, 'owovar2', "\`")
-                        value = owoReplaceAll(value, 'owovar3', '"')
-                        value = owoReplaceAll(value, 'owovar4', '$')
-                        return value
-                      }
-                      var script = document.createElement("script");
-                      script.type = "text/javascript";
-                      script.charset = "UTF-8";
-                      script.innerHTML = clearOwo(\`${decodeOwo(dataTempCopy.data)}\`);
-                      document.body.appendChild(script)
-                      `
-                      chrome.tabs.executeScript(dataTemp.tabInfo.id, {code: execTwmp})
-                    }
-                    if (dataTempCopy.style || dataTempCopy.script) {
-                      dataTempCopy.style = dataTempCopy.style || '[]'
-                      dataTempCopy.script = dataTempCopy.script || '[]'
-                      let temp = `
-                      function loadScript(url, callback) {
-                        var script = document.createElement("script")
-                        script.type = "text/javascript";
-                        if (script.readyState) { //IE
-                            script.onreadystatechange = function () {
-                                if (script.readyState == "loaded" || script.readyState == "complete") {
-                                    script.onreadystatechange = null;
-                                    if (callback) callback();
-                                }
-                            };
-                        } else { //Others
-                            script.onload = function () {
-                                if (callback) callback();
-                            };
-                        }
-                        script.src = url;
-                        var head = document.head || document.getElementsByTagName('head')[0];
-                        head.appendChild(script);
-                    }
-                    
-                    function loadCSS (url) {
-                        var link = document.createElement("link");
-                        link.rel = "stylesheet";
-                        link.type = "text/css";
-                    
-                        link.href = url;
-                    
-                        document.getElementsByTagName("head")[0].appendChild(link);
-                    }
-                    ${dataTempCopy.style}.forEach(element => {
-                      loadCSS(element)
-                    });
-                    ${dataTempCopy.script}.forEach(element => {
-                      loadScript(element)
-                    });
-                      `
-                      chrome.tabs.executeScript(dataTemp.tabInfo.id, {code: unescape(temp)})
-                    }
-                    break
-                  }
-                }
-              }
-            }
-          }
-        }, 0);
-      }
-    })
-  })
-}
-load();
-
-// document.getElementsByClassName('.no-script')[0].addEventListener("click", function(){
-//   load()
-// })

+ 0 - 2
background.html

@@ -6,8 +6,6 @@
   <body>
     1
     <script>
-      console.log('sdsd')
-      chrome.tabs.executeScript(tabId, {code: 'document.body.style.backgroundColor="red"'});
     </script>
   </body>
 </html>

+ 5 - 4
content-script.js

@@ -1,4 +1,4 @@
-function assistLoad() {
+function assistLoad(itemId) {
     // 页面为加载完毕就不断等待
     if (!document.body) {
         setTimeout(() => {
@@ -30,7 +30,8 @@ function assistLoad() {
     document.body.appendChild(newDiv);
     // 创建 iframe 并插入页面
     const iframe = document.createElement('iframe');
-    iframe.src = 'https://demos.run/assist/index.html'; // 注意:必须同源或对方允许跨源
+    
+    iframe.src = itemId ? `https://demos.run/assist/index-${itemId}.html` : 'https://demos.run/assist/index.html'; 
     iframe.style.cssText = `width: 300px;height: 400px;border: none;`
     setTimeout(() => {
         window.assistBox.appendChild(iframe);
@@ -105,12 +106,12 @@ function assistLoad() {
                 sendCallBack(event.data.callBackID, returnList)
                 break;
             case "fetch":
-                fetch(event.data.value.url, event.data.value)
+                fetch(event.data.value.url, event.data.value.options)
                 .then((response) => response.text())
                 .then((result) => {
                     console.log(result)
                     if (event.data.callBackID) {
-                    sendCallBack(event.data.callBackID, response)
+                    sendCallBack(event.data.callBackID, result)
                     }
                 })
                 .catch((error) => console.error(error));

+ 0 - 0
insert.js → insert-auto.js


+ 22 - 0
insert-popup.js

@@ -0,0 +1,22 @@
+const requestOptions = {
+  method: "POST",
+  headers: {
+    "Content-Type": "application/json"
+  },
+  body: JSON.stringify({
+    "url": location.href,
+    "edition": 1
+  }),
+  redirect: "follow"
+};
+
+fetch("https://assist.lamp.run/assist?route=run", requestOptions)
+  .then((response) => response.json())
+  .then((result) => {
+    console.log(result)
+    if (result["data"] && result["data"][0]) {
+      assistLoad(result["data"][0]["id"])
+    }
+  })
+  .catch((error) => console.error(error));
+

+ 1 - 3
js/popup.js

@@ -113,9 +113,7 @@ function load() {
                     })
                     chrome.scripting.executeScript({
                         target: { tabId: tabData.tabInfo.id },
-                        func: () => {
-                          assistLoad()
-                        }
+                        files: ['insert-popup.js']
                     });
                     break
                   }

+ 1 - 1
manifest.json

@@ -19,7 +19,7 @@
 	"content_scripts": [
 		{
 			"matches": ["<all_urls>"],
-			"js": ["insert.js", "content-script.js"],
+			"js": ["insert-auto.js", "content-script.js"],
 			"all_frames": true,
 			"run_at": "document_start"
 		}