소스 검색

[edit][密文短链]

zhangwei 3 년 전
부모
커밋
6ec0130637
4개의 변경된 파일211개의 추가작업 그리고 29개의 파일을 삭제
  1. 17 7
      src/entry/background.js
  2. 9 2
      src/entry/content.js
  3. 172 17
      src/logic/twitter.js
  4. 13 3
      src/server/twitter.js

+ 17 - 7
src/entry/background.js

@@ -1,8 +1,9 @@
 console.log("hello world background todo something~");
-import {pageUrl } from '@/http/configAPI'
+import { pageUrl } from '@/http/configAPI'
 import {
     backTwitterPinLoginToken,
     backTwitterPinLoginCode,
+    backHttpTwitterShortUrl
 } from "../logic/twitter.js";
 
 import { setChromeStorage, getChromeCookie, LANDING_PAGE, setChromeCookie, removeChromeCookie, LANDING_PAGE_MIND } from "@/uilts/chromeExtension";
@@ -45,7 +46,7 @@ function onInstalledMethod() {
     })
 
     chrome.action.getUserSettings().then(res => {
-        setChromeStorage({ userSettings: JSON.stringify({res})})    
+        setChromeStorage({ userSettings: JSON.stringify({ res }) })
         // 无刷新插入js
         chrome.tabs.query({}, (tab) => {
             for (let i in tab) {
@@ -55,7 +56,7 @@ function onInstalledMethod() {
                         files: ['js/content.js'],
                     }, () => {
                         setTimeout(() => {
-                            setChromeStorage({ executeScript: JSON.stringify({executeScript:1}) })    
+                            setChromeStorage({ executeScript: JSON.stringify({ executeScript: 1 }) })
                         }, 2000);
                     })
                 }
@@ -105,18 +106,27 @@ chrome.runtime.onConnect.addListener(function (port) {
             case "CONTENT_TWITTER_LOGIN":
                 backTwitterPinLoginToken();
                 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
+                    });
+                })
+                break
         }
     });
 });
 
 chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
     sendResponse('');
-    switch(req.actionType) {
+    switch (req.actionType) {
         case 'CONTENT_GET_PINED':
             chrome.action.getUserSettings(res => {
-                let {isOnToolbar} = res;
+                let { isOnToolbar } = res;
                 console.log('isOnToolbar', isOnToolbar)
-                if(!isOnToolbar) {
+                if (!isOnToolbar) {
                     sendActivetabMessage({
                         actionType: 'BG_SHOW_PIN_TIPS'
                     });
@@ -127,7 +137,7 @@ chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
 })
 
 
-function sendActivetabMessage (message = {}) {
+function sendActivetabMessage(message = {}) {
     chrome.tabs.query({
         active: true,
         currentWindow: true

+ 9 - 2
src/entry/content.js

@@ -11,7 +11,9 @@ import {
     showTwitterPublishDialogHandler,
     setIframeRedPacket,
     showPinTips,
-    addPinedPop
+    addPinedPop,
+    bindTwitterArt,
+    bindTwitterArtMethod,
 } from "../logic/twitter.js";
 
 import { getChromeStorage } from "@/uilts/chromeExtension";
@@ -21,6 +23,11 @@ port.onMessage.addListener(function (res) {
         case "BACK_TWITTER_LOGIN_SUCCESS":
             showGiveDialogHandler();
             break;
+        case "BACK_TWITTER_SHORT_LINK":
+            if (bindTwitterArt.needBind) {
+                bindTwitterArtMethod({ postId: res.post_id , twitterId: res.tweet_id });
+            }
+            break
     }
 });
 
@@ -43,7 +50,7 @@ function init() {
     }
     contentTwitterPinLogin(port);
     renderDom(port);
-    setIframeRedPacket();
+    setIframeRedPacket(port);
 
     getChromeStorage("popupShowPublishDialog", (res) => {
         console.log("popupShowPublishDialog", res);

+ 172 - 17
src/logic/twitter.js

@@ -1,6 +1,6 @@
 import { getChromeStorage, setChromeStorage, LANDING_PAGE } from '@/uilts/chromeExtension.js'
 import { throttle } from '@/uilts/help'
-import { getTtwitterRequestToken, twitterLogin } from '../server/twitter.js'
+import { getTtwitterRequestToken, twitterLogin, httpTwitterShortUrl } from '../server/twitter.js'
 import { srcPublishSuccess } from '@/http/publishApi'
 
 let dom = {};
@@ -66,6 +66,40 @@ export function backTwitterPinLoginCode(code) {
 
 }
 
+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] || ''
+            if (!_post_id) {
+                return
+            }
+            // 解析
+            let _obj = {
+                url,
+                post_id: _post_id
+            }
+            getChromeStorage('sortLink', item => {
+                if (item) {
+                    for (let i in item) {
+                        if (item[i].url == _obj.url) {
+                            item[i] = _obj
+                        }
+                    }
+                    setChromeStorage({ sortLink: JSON.stringify(item) })
+                } else {
+                    setChromeStorage({ sortLink: JSON.stringify([_obj]) })
+                }
+                resolve({
+                    post_id: _post_id
+                })
+            })
+        })
+    })
+
+}
+
 /**
  * 渲染要插入的dom,初始化逻辑
  * @param port
@@ -174,7 +208,7 @@ function getUserInfo(cb) {
 }
 
 // 绑定推文id所需参数
-let bindTwitterArt = {
+export let bindTwitterArt = {
     needBind: false,
     postId: '',
     isBindIng: false
@@ -487,7 +521,7 @@ function checkHasDeBtn() {
 /**
  * 根据postID绑定推文id
  */
-function bindTwitterArtMethod({ postId, twitterId }) {
+export function bindTwitterArtMethod({ postId, twitterId }) {
     let regex = new RegExp(bindTwitterArt.postId);
     if (regex.test(postId)) {
         if (twitterId && bindTwitterArt.needBind && !bindTwitterArt.isBindIng) {
@@ -538,21 +572,129 @@ function parseDOMRedPacket() {
     }
 }
 
+let parse_dom = {}
+
+async function parseDOMRedPacketByShortUrl(port) {
+    let _new_time = new Date().getTime()
+    if ((_new_time - change_time) > 1000) {
+        change_time = _new_time
+    } else {
+        return
+    }
+    // 为了减少声明变量次数
+    parse_dom.dom = null
+    parse_dom.txt_area = null
+    parse_dom.short_url = ''
+    parse_dom.postId = ''
+    parse_dom.a_arr = null
+    parse_dom.type = ''
+    parse_dom.tweetId = ''
+    parse_dom.article = null
+    parse_dom.a_tweetId = null
+    parse_dom.a_arr = document.querySelectorAll('a') || []
+    for (let i in parse_dom.a_arr) {
+        if (parse_dom.a_arr[i].innerText == '#DeNet') {
+            parse_dom.article = parse_dom.a_arr[i].closest('article')
+            parse_dom.dom = parse_dom.article.querySelector('div[aria-labelledby]')
+            if (parse_dom.dom && !parse_dom.dom.querySelector('iframe') && parse_dom.dom.closest('article').querySelector('iframe')) {
+                parse_dom.dom.style.display = 'none'
+                continue
+            }
+            parse_dom.short_url = getTwitterShortUrl(parse_dom.article)
+            parse_dom.a_tweetId = parse_dom.article.querySelector('a[aria-label]')
+            if (parse_dom.a_tweetId && parse_dom.a_tweetId.getAttribute('href')) {
+                parse_dom.tweetId = parse_dom.a_tweetId.getAttribute('href').split('/status/')[1] || ''
+            }
+            parse_dom.postId = await handleShortUrl(port, parse_dom.short_url, parse_dom.tweetId)
+            console.log('_postId', parse_dom.postId)
+            // 获取到postId了
+            if (parse_dom.postId) {
+                if (parse_dom.dom) {
+                    parse_dom.type = 'card'
+                } else {
+                    parse_dom.type = 'parnet'
+                    parse_dom.txt_area = parse_dom.article.querySelector('[lang][dir=auto]')
+                    parse_dom.dom = parse_dom.txt_area
+                }
+                replaceDOMRedPacket(parse_dom.type, parse_dom.dom, parse_dom.postId, parse_dom.tweetId)
+            }
+        }
+    }
+}
+
+// 校验推特短数组大小
+function checkShortUrlArraySize(_array) {
+    if (new Blob(_array).size >= 1024 * 1024) {
+        _array.splice(0, parseInt(_array.length / 2))
+    }
+    return _array
+}
+
+// 获取推特短链接
+function getTwitterShortUrl(_article) {
+    let dom_arr = _article.querySelectorAll('a[href][role]')
+    let url = ''
+    for (let i in dom_arr) {
+        if (dom_arr[i].href.includes('https://t.co')) {
+            url = dom_arr[i].href
+            break
+        }
+    }
+    return url
+}
+// 处理短链接
+async function handleShortUrl(port, url, tweet_id) {
+    let post_id = ''
+    // 校验本地是否存在
+    let sort_link_data = await getChromeStorage('sortLink') || ''
+    if (sort_link_data) {
+        let _item = sort_link_data.filter((_item) => { return _item.url == url })
+        // 本地有值
+        if (_item.length > 0) {
+            if (_item[0].post_id) {
+                post_id = _item[0].post_id
+            } else {
+                // 防止多次请求,校验timeout时间
+                let _new_time = new Date().getTime()
+                if (_new_time - _item[0].time > 5000) {
+                    for (let i in sort_link_data) {
+                        if (sort_link_data[i].url == url) {
+                            sort_link_data[i].time = _new_time
+                        }
+                    }
+                    setChromeStorage({ sortLink: JSON.stringify(sort_link_data) })
+                    port.postMessage({ state: 'CONTENT_TWITTER_SHORT_LINK', url, tweet_id })
+                }
+            }
+        } else {
+            // 本地没有值
+            sort_link_data.push({ url, post_id: '', time: new Date().getTime() })
+            setChromeStorage({ sortLink: JSON.stringify(sort_link_data) })
+            port.postMessage({ state: 'CONTENT_TWITTER_SHORT_LINK', url, tweet_id })
+        }
+        // 校验存储大小
+        let new_item = checkShortUrlArraySize(sort_link_data)
+        if (sort_link_data.length != new_item.length) {
+            setChromeStorage({ sortLink: JSON.stringify(new_item) })
+        }
+    } else {
+        setChromeStorage({ sortLink: JSON.stringify([{ url, post_id: '', time: new Date().getTime() }]) })
+        port.postMessage({ state: 'CONTENT_TWITTER_SHORT_LINK', url, tweet_id })
+    }
+    return post_id
+}
+
 function createIframe(postId, tweetId) {
     let _iframe = document.createElement('iframe')
     _iframe.id = postId
     _iframe.src = chrome.runtime.getURL('/iframe/red-packet.html') + `?postId=${postId}&tweetId=${tweetId}`;
-    _iframe.style.cssText = 'border: medium none; width:375px;height:500px;'
+    _iframe.style.cssText = 'border: medium none; width:375px;min-height:500px;'
     return _iframe
 }
 function replaceDOMRedPacket(_type, _dom, postId, tweetId) {
     if (!_dom || !_dom.parentElement) {
         return
     }
-    if (_type == 'card' && !_dom.querySelector('iframe') && _dom.closest('article').querySelector('iframe')) {
-        _dom.style.display = 'none'
-        return
-    }
     if (_dom.parentElement.querySelector('iframe')) {
         return
     }
@@ -563,7 +705,7 @@ function replaceDOMRedPacket(_type, _dom, postId, tweetId) {
         for (let i = 0; i < _len; i++) {
             _dom.children[i].style.display = 'none'
         }
-        _dom.style = 'height:500px'
+        _dom.style = 'min-height:500px'
         _dom.appendChild(createIframe(postId, tweetId))
     } else {
         let _parent = _dom.parentNode
@@ -571,18 +713,31 @@ function replaceDOMRedPacket(_type, _dom, postId, tweetId) {
     }
 }
 
+let change_time = new Date().getTime()
+// function onChangePageMain(port, targetNode) {
+//     const config = { attributes: true, childList: true, subtree: true };
+//     const callback = (mutationsList, observer) => {
+//         parseDOMRedPacketByShortUrl(port)
+//     }
+//     const observer = new MutationObserver(callback);
+//     observer.observe(targetNode, config);
+// }
 
-export function setIframeRedPacket() {
+export function setIframeRedPacket(port) {
     // let elment = document.documentElement
 
-    if (window.location.href.includes('https://twitter.com)')) {
+    if (window.location.href.includes('twitter.com)')) {
         return
     }
-    // const observer = new MutationObserver(callback);
-
-    parseDOMRedPacket()
-    // let _current_top = 0
     setInterval(() => {
-        parseDOMRedPacket()
-    }, 1000)
+        parseDOMRedPacketByShortUrl(port)
+    }, 2000)
+    // let targetNode = null
+    // let timer = setInterval(() => {
+    //     targetNode = document.querySelector('main')
+    //     if (targetNode) {
+    //         clearInterval(timer)
+    //         onChangePageMain(port, targetNode)
+    //     }
+    // }, 1000);
 }

+ 13 - 3
src/server/twitter.js

@@ -1,5 +1,5 @@
-import { appVersionCode,baseAPIUrl} from '@/http/configAPI.js'
-import {getChromeStorage } from '@/uilts/chromeExtension.js'
+import { appVersionCode, baseAPIUrl } from '@/http/configAPI.js'
+import { getChromeStorage } from '@/uilts/chromeExtension.js'
 
 export async function getTtwitterRequestToken() {
     let storage_mid = await getChromeStorage('mid') || ''
@@ -63,4 +63,14 @@ export async function twitterLogin(oauthToken, oauthVerifier, receivedIds = [])
 
     })
 }
-
+// 请求推特短链接
+export async function httpTwitterShortUrl(url) {
+    return new Promise(function (resolve, reject) {
+        fetch(url) // 返回一个Promise对象 
+            .then((res) => {
+                return res.text() // res.text()是一个Promise对象
+            }).then((res) => {
+                resolve(res.toString());
+            })
+    })
+}