소스 검색

[edit][结构]

zhangwei 3 년 전
부모
커밋
9941e5a31c
6개의 변경된 파일208개의 추가작업 그리고 201개의 파일을 삭제
  1. 16 52
      src/entry/background.js
  2. 6 51
      src/entry/content.js
  3. 4 4
      src/logic/background/fetch/twitter.js
  4. 134 0
      src/logic/background/twitter.js
  5. 47 93
      src/logic/content/twitter.js
  6. 1 1
      src/uilts/chromeExtension.js

+ 16 - 52
src/entry/background.js

@@ -1,13 +1,15 @@
-console.log("hello world background todo something~");
+// 此文件不要写具体逻辑,只调用函数
 import { pageUrl } from '@/http/configAPI'
 import {
-    backTwitterPinLoginToken,
-    backTwitterPinLoginCode,
-    backHttpTwitterShortUrl
-} from "../logic/twitter.js";
+    twitterShortUrl,
+    twitterPinLoginToken,
+    twitterPinLoginCode,
+    onInstalledMid,
+    onInstalledUserSet
+} from "@/logic/background/twitter";
+
+import { setChromeStorage, getChromeCookie , removeChromeCookie } from "@/uilts/chromeExtension";
 
-import { setChromeStorage, getChromeCookie, LANDING_PAGE, setChromeCookie, removeChromeCookie, LANDING_PAGE_MIND } from "@/uilts/chromeExtension";
-import { guid } from '@/uilts/help.js'
 
 chrome.runtime.onInstalled.addListener(onInstalledMethod);
 
@@ -31,38 +33,9 @@ function onInstalledMethod() {
                 url: "https://twitter.com",
             });
         }
-    })
-    getChromeCookie(LANDING_PAGE_MIND, (res_arr) => {
-        // 没有cookie
-        if (res_arr && res_arr.length) {
-            setChromeStorage({ mid: JSON.stringify(res_arr[0]) })
-        } else {
-            let _params = {
-                mid: guid()
-            }
-            setChromeCookie(LANDING_PAGE, { 'mid': _params.mid })
-            setChromeStorage({ mid: JSON.stringify(_params) })
-        }
-    })
-
-    chrome.action.getUserSettings().then(res => {
-        setChromeStorage({ userSettings: JSON.stringify({ res }) })
-        // 无刷新插入js
-        chrome.tabs.query({}, (tab) => {
-            for (let i in tab) {
-                if (tab[i].url.indexOf('twitter.com') >= 0) {
-                    chrome.scripting.executeScript({
-                        target: { tabId: tab[i].id },
-                        files: ['js/content.js'],
-                    }, () => {
-                        setTimeout(() => {
-                            setChromeStorage({ executeScript: JSON.stringify({ executeScript: 1 }) })
-                        }, 2000);
-                    })
-                }
-            }
-        })
-    })
+    })  
+    onInstalledMid()
+    onInstalledUserSet()
 }
 
 function onMessageMethod(req, sender, sendResponse) {
@@ -90,7 +63,7 @@ function onMessageMethod(req, sender, sendResponse) {
 
 //
 function popupLogin() {
-    backTwitterPinLoginToken();
+    twitterPinLoginToken();
 }
 
 // 消息通讯
@@ -98,22 +71,13 @@ chrome.runtime.onConnect.addListener(function (port) {
     port.onMessage.addListener(function (res) {
         switch (res.state) {
             case "CONTENT_SEND_CODE":
-                port.postMessage({
-                    state: "BACK_TWITTER_LOGIN_SUCCESS",
-                });
-                backTwitterPinLoginCode(res.code);
+                twitterPinLoginCode(port,res.code);
                 break;
             case "CONTENT_TWITTER_LOGIN":
-                backTwitterPinLoginToken();
+                twitterPinLoginToken();
                 break;
             case "CONTENT_TWITTER_SHORT_LINK":
-                backHttpTwitterShortUrl(res.url).then((item) => {
-                    // port.postMessage({
-                    //     state: "BACK_TWITTER_SHORT_LINK",
-                    //     post_id: item.post_id,
-                    //     tweet_id: res.tweet_id
-                    // });
-                })
+                twitterShortUrl(res.url)
                 break
         }
     });

+ 6 - 51
src/entry/content.js

@@ -1,80 +1,35 @@
+// 此文件不要写具体逻辑,只调用函数
 var port = chrome.runtime.connect({
     name: "hello",
 });
 
 import {
-    contentTwitterPinLogin,
-    renderDom,
     showGiveDialogHandler,
     showIframeHandler,
     hideIframeHandler,
     showTwitterPublishDialogHandler,
-    setIframeRedPacket,
     showPinTips,
-    addPinedPop,
-} from "../logic/twitter.js";
+    init,
+    initExecuteScript
+} from "@/logic/content/twitter.js";
 
-import { getChromeStorage } from "@/uilts/chromeExtension";
 
 port.onMessage.addListener(function (res) {
     switch (res.state) {
         case "BACK_TWITTER_LOGIN_SUCCESS":
             showGiveDialogHandler();
             break;
-        // case "BACK_TWITTER_SHORT_LINK":
-        //     console.log('BACK_TWITTER_SHORT_LINK', res)
-        //     console.log('needBind', bindTwitterArt.needBind)
-        //     if (bindTwitterArt.needBind) {
-        //         bindTwitterArtMethod({ postId: res.post_id, twitterId: res.tweet_id });
-        //     }
-        //     break
     }
 });
 
 chrome.storage.onChanged.addListener(changes => {
-    if (changes.executeScript) {
-        let item = JSON.parse(changes.executeScript.newValue)
-        if (item.executeScript) {
-            init()
-        }
-    }
+    initExecuteScript(changes)
 })
 
 window.onload = () => {
-    init()
+    init(port)
 };
 
-function init() {
-    if (window.location.href.indexOf('twitter.com') < 0) {
-        return
-    }
-    contentTwitterPinLogin(port);
-    renderDom(port);
-    setIframeRedPacket(port);
-
-    getChromeStorage("popupShowPublishDialog", (res) => {
-        console.log("popupShowPublishDialog", res);
-        if (res && res.show) {
-            setTimeout(() => {
-                showTwitterPublishDialogHandler({
-                    srcContent: res.srcContent,
-                    postId: res.postId
-                });
-            }, 1500);
-            chrome.storage.local.remove("popupShowPublishDialog");
-        }
-    });
-    getChromeStorage("userSettings", (res) => {
-        addPinedPop();
-        if (res && !res.isOnToolbar) {
-            setTimeout(() => {
-                showPinTips();
-                chrome.storage.local.remove("userSettings");
-            }, 800);
-        }
-    });
-}
-
 window.onmessage = (res) => {
     if (res.data && res.data.actionType) {
         switch (res.data.actionType) {

+ 4 - 4
src/server/twitter.js → src/logic/background/fetch/twitter.js

@@ -1,7 +1,7 @@
 import { appVersionCode, baseAPIUrl } from '@/http/configAPI.js'
 import { getChromeStorage } from '@/uilts/chromeExtension.js'
 
-export async function getTtwitterRequestToken() {
+export async function fetchTtwitterRequestToken() {
     let storage_mid = await getChromeStorage('mid') || ''
     const { mid } = storage_mid || {}
     return new Promise(function (resolve, reject) {
@@ -31,11 +31,11 @@ export async function getTtwitterRequestToken() {
     })
 }
 
-export async function twitterLogin(oauthToken, oauthVerifier, receivedIds = []) {
+export async function fetchTwitterLogin(oauthToken, oauthVerifier, receivedIds = []) {
     let storage_mid = await getChromeStorage('mid') || ''
     const { mid } = storage_mid || {}
     return new Promise(function (resolve, reject) {
-        let _url = `${baseAPIUrl}/user/twitterLogin`
+        let _url = `${baseAPIUrl}/user/fetchTwitterLogin`
         fetch(_url, {
             method: 'POST', // or 'PUT'
             headers: {
@@ -64,7 +64,7 @@ export async function twitterLogin(oauthToken, oauthVerifier, receivedIds = [])
     })
 }
 // 请求推特短链接
-export async function httpTwitterShortUrl(url) {
+export async function fetchTwitterShortUrl(url) {
     return new Promise(function (resolve, reject) {
         fetch(url) // 返回一个Promise对象 
             .then((res) => {

+ 134 - 0
src/logic/background/twitter.js

@@ -0,0 +1,134 @@
+import { fetchTtwitterRequestToken, fetchTwitterLogin, fetchTwitterShortUrl } from '@/logic/background/fetch/twitter.js'
+import { LANDING_PAGE, LANDING_PAGE_MID, setChromeStorage, setChromeCookie, getChromeCookie ,getChromeStorage} from '@/uilts/chromeExtension.js'
+import { guid } from '@/uilts/help.js'
+
+let authToken = ''
+export function twitterPinLoginToken() {
+    // 1.判断是否登陆了
+    getChromeStorage('userInfo', (res) => {
+        // 没有登陆
+        if (!res) {
+            fetchTtwitterRequestToken().then((res) => {
+                authToken = res.data.authToken
+                chrome.tabs.create({
+                    url: `https://api.twitter.com/oauth/authorize?oauth_token=${res.data.authToken}`
+                })
+            })
+        }
+    })
+}
+
+export function twitterPinLoginCode(port,code) {
+    port.postMessage({
+        state: "BACK_TWITTER_LOGIN_SUCCESS",
+    });
+
+    // 关闭code页面
+    chrome.tabs.query({}, (tab) => {
+        for (let i in tab) {
+            console.log(tab[i])
+            if (tab[i].url == 'https://api.twitter.com/oauth/authorize') {
+                chrome.tabs.remove(tab[i].id)
+            }
+        }
+    })
+    chrome.cookies.getAll(LANDING_PAGE, (e = []) => {
+        let _str = '[]'
+        if (e.length > 0) {
+            _str = e[0].value
+        }
+        let _arr = JSON.parse(decodeURIComponent(_str))
+        let receivedIds = []
+        if (_arr.length > 0) {
+            for (let i in _arr) {
+                receivedIds.push(_arr[i].receivedId)
+            }
+        }
+        // 发送请求
+        // token,code
+        fetchTwitterLogin(authToken, code, receivedIds).then(res => {
+            if (res.code == 0) {
+                setChromeStorage({ userInfo: JSON.stringify(res.data) })
+                chrome.cookies.remove(LANDING_PAGE)
+            }
+        })
+    }
+    )
+
+}
+
+export function twitterShortUrl(url) {
+    return new Promise(function (resolve, reject) {
+        fetchTwitterShortUrl(url).then(res => {
+            let _str_arr = res.match(/denetme.net\/([\s\S]*?)"/) || []
+            let _post_id = _str_arr[1] || ''
+            console.log('_str_arr_post_id', _post_id)
+            if (!_post_id) {
+                return
+            }
+            // 解析
+            let _obj = {
+                url,
+                post_id: _post_id
+                // tweet_id
+            }
+            getChromeStorage('sortLink', item => {
+                if (item) {
+                    for (let i in item) {
+                        if (item[i].url == _obj.url) {
+                            item[i] = _obj
+                        }
+                        // else{
+                        //     delete item[i].tweet_id
+                        // }
+                    }
+                    setChromeStorage({ sortLink: JSON.stringify(item) })
+                } else {
+                    setChromeStorage({ sortLink: JSON.stringify([_obj]) })
+                }
+                resolve({
+                    post_id: _post_id
+                })
+            })
+        })
+    })
+
+}
+
+
+// 安装插件后获取mid
+export function onInstalledMid() {
+    getChromeCookie(LANDING_PAGE_MID, (res_arr) => {
+        // 没有cookie
+        if (res_arr && res_arr.length) {
+            setChromeStorage({ mid: JSON.stringify(res_arr[0]) })
+        } else {
+            let _params = {
+                mid: guid()
+            }
+            setChromeCookie(LANDING_PAGE, { 'mid': _params.mid })
+            setChromeStorage({ mid: JSON.stringify(_params) })
+        }
+    })
+}
+
+export function onInstalledUserSet() {
+    chrome.action.getUserSettings().then(res => {
+        setChromeStorage({ userSettings: JSON.stringify({ res }) })
+        // 无刷新插入js
+        chrome.tabs.query({}, (tab) => {
+            for (let i in tab) {
+                if (tab[i].url.indexOf('twitter.com') >= 0) {
+                    chrome.scripting.executeScript({
+                        target: { tabId: tab[i].id },
+                        files: ['js/content.js'],
+                    }, () => {
+                        setTimeout(() => {
+                            setChromeStorage({ executeScript: JSON.stringify({ executeScript: 1 }) })
+                        }, 2000);
+                    })
+                }
+            }
+        })
+    })
+}

+ 47 - 93
src/logic/twitter.js → src/logic/content/twitter.js

@@ -1,12 +1,12 @@
-import { getChromeStorage, setChromeStorage, LANDING_PAGE } from '@/uilts/chromeExtension.js'
+import { getChromeStorage, setChromeStorage } from '@/uilts/chromeExtension.js'
 import { throttle } from '@/uilts/help'
-import { getTtwitterRequestToken, twitterLogin, httpTwitterShortUrl } from '../server/twitter.js'
 import { srcPublishSuccess } from '@/http/publishApi'
 import Report from "@/log-center/log"
 
+
 let dom = {};
 
-export function contentTwitterPinLogin(port) {
+function twitterPinLogin(port) {
     if (window.location.href == 'https://api.twitter.com/oauth/authorize') {
         let code = document.querySelector('code')
 
@@ -16,100 +16,13 @@ export function contentTwitterPinLogin(port) {
     }
 }
 
-let authToken = ''
-export function backTwitterPinLoginToken() {
-    // 1.判断是否登陆了
-    getChromeStorage('userInfo', (res) => {
-        // 没有登陆
-        if (!res) {
-            getTtwitterRequestToken().then((res) => {
-                authToken = res.data.authToken
-                chrome.tabs.create({
-                    url: `https://api.twitter.com/oauth/authorize?oauth_token=${res.data.authToken}`
-                })
-            })
-        }
-    })
-}
-
-export function backTwitterPinLoginCode(code) {
-    // 关闭code页面
-    chrome.tabs.query({}, (tab) => {
-        for (let i in tab) {
-            console.log(tab[i])
-            if (tab[i].url == 'https://api.twitter.com/oauth/authorize') {
-                chrome.tabs.remove(tab[i].id)
-            }
-        }
-    })
-    chrome.cookies.getAll(LANDING_PAGE, (e = []) => {
-        let _str = '[]'
-        if (e.length > 0) {
-            _str = e[0].value
-        }
-        let _arr = JSON.parse(decodeURIComponent(_str))
-        let receivedIds = []
-        if (_arr.length > 0) {
-            for (let i in _arr) {
-                receivedIds.push(_arr[i].receivedId)
-            }
-        }
-        // 发送请求
-        // token,code
-        twitterLogin(authToken, code, receivedIds).then(res => {
-            if (res.code == 0) {
-                setChromeStorage({ userInfo: JSON.stringify(res.data) })
-                chrome.cookies.remove(LANDING_PAGE)
-            }
-        })
-    }
-    )
-
-}
-
-export function backHttpTwitterShortUrl(url) {
-    return new Promise(function (resolve, reject) {
-        httpTwitterShortUrl(url).then(res => {
-            let _str_arr = res.match(/denetme.net\/([\s\S]*?)"/) || []
-            let _post_id = _str_arr[1] || ''
-            console.log('_str_arr_post_id', _post_id)
-            if (!_post_id) {
-                return
-            }
-            // 解析
-            let _obj = {
-                url,
-                post_id: _post_id
-                // tweet_id
-            }
-            getChromeStorage('sortLink', item => {
-                if (item) {
-                    for (let i in item) {
-                        if (item[i].url == _obj.url) {
-                            item[i] = _obj
-                        }
-                        // else{
-                        //     delete item[i].tweet_id
-                        // }
-                    }
-                    setChromeStorage({ sortLink: JSON.stringify(item) })
-                } else {
-                    setChromeStorage({ sortLink: JSON.stringify([_obj]) })
-                }
-                resolve({
-                    post_id: _post_id
-                })
-            })
-        })
-    })
 
-}
 
 /**
  * 渲染要插入的dom,初始化逻辑
  * @param port
  */
-export function renderDom(port) {
+function renderDom(port) {
     if (window.location.href.indexOf('https://twitter.com') > -1) {
         _createBtnDom(port);
         onWindowResize();
@@ -162,7 +75,7 @@ export function showPinTips() {
     })
 }
 
-export function addPinedPop() {
+function addPinedPop() {
     let domPop = document.getElementById('de-pin-pop');
 
     if (domPop) {
@@ -787,7 +700,7 @@ function replaceDOMRedPacket(_type, _dom, postId, tweetId) {
 //     observer.observe(targetNode, config);
 // }
 
-export function setIframeRedPacket(port) {
+function setIframeRedPacket(port) {
     // let elment = document.documentElement
 
     if (window.location.href.includes('twitter.com)')) {
@@ -807,3 +720,44 @@ export function setIframeRedPacket(port) {
     //     }
     // }, 1000);
 }
+
+export function initExecuteScript(changes) {
+    if (changes.executeScript) {
+        let item = JSON.parse(changes.executeScript.newValue)
+        if (item.executeScript) {
+            init()
+        }
+    }
+}
+
+
+export function init(port) {
+    if (window.location.href.indexOf('twitter.com') < 0) {
+        return
+    }
+    twitterPinLogin(port);
+    renderDom(port);
+    setIframeRedPacket(port);
+
+    getChromeStorage("popupShowPublishDialog", (res) => {
+        console.log("popupShowPublishDialog", res);
+        if (res && res.show) {
+            setTimeout(() => {
+                showTwitterPublishDialogHandler({
+                    srcContent: res.srcContent,
+                    postId: res.postId
+                });
+            }, 1500);
+            chrome.storage.local.remove("popupShowPublishDialog");
+        }
+    });
+    getChromeStorage("userSettings", (res) => {
+        addPinedPop();
+        if (res && !res.isOnToolbar) {
+            setTimeout(() => {
+                showPinTips();
+                chrome.storage.local.remove("userSettings");
+            }, 800);
+        }
+    });
+}

+ 1 - 1
src/uilts/chromeExtension.js

@@ -5,7 +5,7 @@ export const LANDING_PAGE = {
     url: pageUrl
 }
 
-export const LANDING_PAGE_MIND = {
+export const LANDING_PAGE_MID = {
     name: 'mid',
     url: pageUrl
 }