Kaynağa Gözat

[edit][card bug]

zhangwei 2 yıl önce
ebeveyn
işleme
be7d02fdb2

+ 4 - 2
src/entry/background.js

@@ -17,13 +17,15 @@ chrome.runtime.onConnect.addListener(function (port) {
     port.onMessage.addListener(function (res) {
         switch (res.state) {
             case "CONTENT_SEND_CODE":
-                twitterPinLoginCode(port,res.code);
+                twitterPinLoginCode(port, res.code);
                 break;
             case "CONTENT_TWITTER_LOGIN":
                 twitterPinLoginToken();
                 break;
             case "CONTENT_TWITTER_SHORT_LINK":
-                twitterShortUrl(res.url)
+                res.arr_url.forEach(item => {
+                    twitterShortUrl(item)
+                });
                 break
         }
     });

+ 0 - 1
src/http/request.js

@@ -50,7 +50,6 @@ function checkParams(config) {
     let data = {
       ...config.data
     }
-    console.log('data', data)
     let {pageSource} = data.params || {};
     if(pageSource) {
       delete data.params.pageSource;

+ 28 - 23
src/logic/background/twitter.js

@@ -1,5 +1,5 @@
 import { fetchTtwitterRequestToken, fetchTwitterLogin, fetchTwitterShortUrl } from '@/logic/background/fetch/twitter.js'
-import { LANDING_PAGE, LANDING_PAGE_MID, setChromeStorage, setChromeCookie, getChromeCookie ,getChromeStorage, removeChromeCookie} from '@/uilts/chromeExtension.js'
+import { LANDING_PAGE, LANDING_PAGE_MID, setChromeStorage, setChromeCookie, getChromeCookie, getChromeStorage, removeChromeCookie } from '@/uilts/chromeExtension.js'
 import { guid } from '@/uilts/help.js'
 import { pageUrl } from '@/http/configAPI'
 
@@ -19,7 +19,7 @@ export function twitterPinLoginToken() {
     })
 }
 
-export function twitterPinLoginCode(port,code) {
+export function twitterPinLoginCode(port, code) {
     port.postMessage({
         state: "BACK_TWITTER_LOGIN_SUCCESS",
     });
@@ -61,34 +61,39 @@ export function twitterPinLoginCode(port,code) {
 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) {
+            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
-                // tweet_id
+                short_url: url,
+                post_Id
             }
-            getChromeStorage('sortLink', item => {
+            console.log('123', _obj)
+            getChromeStorage('cardData', item => {
                 if (item) {
+                    let has = false
                     for (let i in item) {
-                        if (item[i].url == _obj.url) {
-                            item[i] = _obj
+                        if (item[i].short_url == _obj.short_url) {
+                            item[i].short_url = _obj.short_url
+                            item[i].post_Id = _obj.post_Id
+                            setChromeStorage({ cardData: JSON.stringify(item) })
+                            has = true
+                            break
                         }
-                        // else{
-                        //     delete item[i].tweet_id
-                        // }
                     }
-                    setChromeStorage({ sortLink: JSON.stringify(item) })
+                    if (!has) {
+                        item.push(_obj)
+                        setChromeStorage({ cardData: JSON.stringify(item) })
+                    }
+
                 } else {
-                    setChromeStorage({ sortLink: JSON.stringify([_obj]) })
+                    setChromeStorage({ cardData: JSON.stringify([_obj]) })
                 }
                 resolve({
-                    post_id: _post_id
+                    post_Id
                 })
             })
         })
@@ -202,12 +207,12 @@ export function popupRePublish(req) {
 }
 
 export function setBadgeInfo() {
-    let {text = '', color = [255, 0, 0, 255]} = req.data || {};
-    chrome.action.setBadgeText({text: text});
-    chrome.action.setBadgeBackgroundColor({color: color });
+    let { text = '', color = [255, 0, 0, 255] } = req.data || {};
+    chrome.action.setBadgeText({ text: text });
+    chrome.action.setBadgeBackgroundColor({ color: color });
 }
 
 export function hideBadge() {
-    chrome.action.setBadgeText({text: ''});
-    chrome.action.setBadgeBackgroundColor({color: [0, 0, 0, 0]});
+    chrome.action.setBadgeText({ text: '' });
+    chrome.action.setBadgeBackgroundColor({ color: [0, 0, 0, 0] });
 }

+ 139 - 0
src/logic/content/ParseCard.js

@@ -0,0 +1,139 @@
+import { getChromeStorage, setChromeStorage } from '@/uilts/chromeExtension.js'
+// 解析卡片类
+class ParseCard {
+    constructor() {
+
+    }
+    parseAllDeNetCard() {
+        let de_net_card = []
+        let a_arr = document.querySelectorAll('a') || []
+        for (let i in a_arr) {
+            if (a_arr[i].innerText == '#DeNet') {
+                de_net_card.push(a_arr[i].closest('article'))
+            }
+        }
+        return de_net_card
+    }
+    parseCardParmas(dom_card) {
+        let tweet_Id = ''
+        let short_url = ''
+        let a_arr = dom_card.querySelectorAll('a') || []
+
+        for (let i in a_arr) {
+            // 获取推特id
+            if (a_arr[i].href && a_arr[i].href.indexOf('/status/') > 0 && !tweet_Id) {
+                tweet_Id = a_arr[i].href.split('/status/')[1] || ''
+            }
+            if (a_arr[i].href && a_arr[i].href.includes('https://t.co') && !short_url) {
+                short_url = a_arr[i].href
+            }
+            if (tweet_Id && short_url) {
+                break
+            }
+        }
+        return { tweet_Id, short_url, dom_card }
+    }
+    hideCard() {
+        if (dom.querySelector('iframe')) {
+            return
+        }
+    }
+    parseAllDeNetCardParmas() {
+        let json_data = []
+        this.parseAllDeNetCard().forEach((item) => {
+            json_data.push(this.parseCardParmas(item))
+        })
+        return json_data
+    }
+    // 获取短链接和渲染卡片数据
+    async getCardParmas(card_json_data) {
+        let sort_link_data = await getChromeStorage('cardData') || []
+        let has_post_Id_card_data = this.getLocalHasPostIdData(sort_link_data, card_json_data)
+        let need_net_short_url = this.filterShortUrl(sort_link_data, card_json_data)
+
+        // 校验存储大小
+        let new_item = this.checkShortUrlArraySize(sort_link_data)
+        if (sort_link_data.length != new_item.length) {
+            setChromeStorage({ cardData: JSON.stringify(new_item) })
+        }
+        return {
+            has_post_Id_card_data,
+            need_net_short_url
+        }
+    }
+    filterShortUrl(sort_link_data, card_json_data) {
+        let has = false
+        let need_net_short_url = []
+
+        card_json_data.forEach((card_item) => {
+            has = false
+            sort_link_data.forEach((local_item) => {
+                if (card_item.short_url == local_item.short_url && local_item.post_Id) {
+                    has = true
+                }
+            })
+            if (!has) {
+                need_net_short_url.push(card_item.short_url)
+            }
+        })
+        // 返回的是没有postid的
+        return need_net_short_url
+    }
+    getLocalHasPostIdData(sort_link_data = [], card_json_data = []) {
+        // 
+        let has_post_Id_card_data = []
+        card_json_data.forEach((item) => {
+            let filter_item = sort_link_data.filter((filter) => {
+                return filter.short_url == item.short_url && filter.post_Id
+            })
+            if (filter_item.length > 0) {
+                item.post_Id = filter_item[0].post_Id
+                has_post_Id_card_data.push(item)
+            }
+        })
+        return has_post_Id_card_data
+    }
+    checkShortUrlArraySize(_array) {
+        if (new Blob(_array).size >= 1024 * 1024) {
+            _array.splice(0, parseInt(_array.length / 2))
+        }
+        return _array
+    }
+
+    createIframe(post_Id, tweet_Id) {
+        let _iframe = document.createElement('iframe')
+        _iframe.id = post_Id
+        _iframe.src = chrome.runtime.getURL('/iframe/red-packet.html') + `?postId=${post_Id}&tweetId=${tweet_Id}`;
+        _iframe.style.cssText = 'border: medium none; width:375px;min-height:500px;'
+        return _iframe
+    }
+    replaceDOMRedPacket({ dom_card, tweet_Id, post_Id }) {
+        if (!dom_card || !dom_card.parentElement) {
+            return
+        }
+
+        let type = 'parnet'
+        let dom = dom_card.querySelector('div[aria-labelledby]')
+        if (dom) {
+            type = 'card'
+        } else {
+            type = 'txt'
+            dom = dom_card.querySelector('div[lang][dir=auto]').parentElement
+        }
+
+        if (type == 'card') {
+            for (let i = 0; i < dom.childNodes.length; i++) {
+                if(dom.children[i].tagName.toLowerCase() != 'iframe' ){
+                    dom.children[i].style.display = 'none'
+                }   
+            }
+            dom.style = 'min-height:500px'
+        } 
+
+        if(dom_card.querySelector('iframe')){
+            return
+        }
+        dom.appendChild(this.createIframe(post_Id, tweet_Id))
+    }
+}
+export default new ParseCard()

+ 56 - 204
src/logic/content/twitter.js

@@ -359,7 +359,7 @@ function _createBtnDom(port) {
         // }, res => {
         //     console.log(res);
         // })
-    
+
         Report.reportLog({
             pageSource: Report.pageSource.mainPage,
             businessType: Report.businessType.buttonClick,
@@ -482,229 +482,74 @@ function bindTwitterArtMethod({ postId, twitterId }) {
         }
     }
 }
+import parseCard from './ParseCard'
 
-function parseDOMRedPacket() {
-    let _dom = null
-    let arr = document.querySelectorAll('a') || []
-    let _type = ''
-    for (let i in arr) {
-        if (arr[i].innerText == '#DeNet') {
-            let _tweetId = ''
-            let _article = arr[i].closest('article')
-            let _txt_area = _article.querySelector('[lang][dir=auto]')
-            let _postId = _txt_area.innerText
-            _postId = _postId.match(/###([\s\S]*?)###/)[1]
-            _dom = _article.querySelector('div[aria-labelledby]')
-            if (_dom) {
-                _type = 'card'
-            } else {
-                _type = 'parnet'
-                _dom = _txt_area
-            }
-            let _a_area = _article.querySelector('a[aria-label]')
-            if (_a_area && _a_area.getAttribute('href')) {
-                _tweetId = _a_area.getAttribute('href').split('/status/')[1] || ''
-                if (bindTwitterArt.needBind) {
-                    bindTwitterArtMethod({ postId: _postId, twitterId: _tweetId });
-                }
-            }
-            replaceDOMRedPacket(_type, _dom, _postId, _tweetId)
-        }
-    }
-}
-function getTwitterIdByDOM(dom) {
-    let _twitter_id = ''
-    for (let i in dom) {
-        if (dom[i].href.indexOf('/status/') > 0) {
-            _twitter_id = dom[i].href.split('/status/')[1] || ''
-            break
-        }
-    }
-    return _twitter_id
-}
-
-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
-            }
-            if (parse_dom.dom && parse_dom.dom.parentElement.querySelector('iframe')) {
-                continue
-            }
-            parse_dom.short_url = getTwitterShortUrl(parse_dom.article)
-            parse_dom.tweetId = getTwitterIdByDOM(parse_dom.article.querySelectorAll('a'))
-            parse_dom.postId = await handleShortUrl(port, parse_dom.short_url)
-
-            // 获取到postId了
-            if (parse_dom.postId && parse_dom.tweetId) {
-                console.log('bindTwitterArt.postId', bindTwitterArt.postId)
-                console.log('parse_dom.postId', parse_dom.postId)
-                // if (bindTwitterArt.needBind) {
-                //     bindTwitterArtMethod({ postId: parse_dom.postId, twitterId: parse_dom.tweetId });
-                // }
-                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)
-            }
-        }
-    }
-}
+// 检测dom改变 
+// 获取短链接 
+// 查看本地是否有postid 
+// 如果有 修改dom 返回 
+// 如果没有 网络请求 
+// 获取postid 
+// 获取twitterid 
+// 检测当前所有dom 如果没有 
 
-// 校验推特短数组大小
-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) {
-    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 > 1000) {
-                    for (let i in sort_link_data) {
-                        if (sort_link_data[i].url == url) {
-                            sort_link_data[i].time = _new_time
-                            break
-                        }
-                    }
-                    setChromeStorage({ sortLink: JSON.stringify(sort_link_data) })
-                    port.postMessage({ state: 'CONTENT_TWITTER_SHORT_LINK', url })
-                }
-            }
-        } 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 })
-        }
-        // 校验存储大小
-        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 })
-    }
-    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;min-height:500px;'
-    return _iframe
-}
-function replaceDOMRedPacket(_type, _dom, postId, tweetId) {
-    if (!_dom || !_dom.parentElement) {
-        return
-    }
-    if (_dom.parentElement.querySelector('iframe')) {
-        return
-    }
-
-    if (_type == 'card') {
-        let _len
-        _len = _dom.childNodes.length
-        for (let i = 0; i < _len; i++) {
-            _dom.children[i].style.display = 'none'
-        }
-        _dom.style = 'min-height:500px'
-        _dom.appendChild(createIframe(postId, tweetId))
-    } else {
-        let _parent = _dom.parentNode
-        _parent.appendChild(createIframe(postId, tweetId))
-    }
-}
 
 let change_time = new Date().getTime()
 function onChangePageMain(port, targetNode) {
     const config = { attributes: false, childList: true, subtree: true };
+    let article = null
     const callback = (mutationsList, observer) => {
-        parseDOMRedPacketByShortUrl(port)
-        setTimeout(() => {
-            parseDOMRedPacketByShortUrl(port)
-        }, 1100)
+        
+        for (let i in mutationsList) {
+            if (mutationsList[i].target && mutationsList[i].target.querySelector('article')) {
+                setIframeRedPacket(port)
+                break
+            }
+        }
+
     }
     const observer = new MutationObserver(callback);
     observer.observe(targetNode, config);
 }
 
+// 1.监听main改变
+// 2.监听卡片是否可见
+// 3.如果可见了 去找
+
 function setIframeRedPacket(port) {
     // let elment = document.documentElement
 
     if (window.location.href.includes('twitter.com)')) {
         return
     }
-    // setInterval(() => {
-    //     parseDOMRedPacketByShortUrl(port)
-    // }, 1000)
-
-
-    let targetNode = null
+    // let new_time = new Date().getTime()
+    // if(new_time - change_time <= 2000){
+    //     return
+    // }
+    // change_time = new_time
+    let stop_time = 0
     let timer = setInterval(() => {
-        targetNode = document.querySelector('main')
-        if (targetNode) {
-            clearInterval(timer)
-            onChangePageMain(port, targetNode)
-        }
-    }, 1000);
+        stop_time++
+        // 获取所有卡片参数
+        let card_json_data = parseCard.parseAllDeNetCardParmas()
+        // 过滤出可以请求的短链接
+        parseCard.getCardParmas(card_json_data).then((res) => {
+            for (let i in res.has_post_Id_card_data) {
+                parseCard.replaceDOMRedPacket(res.has_post_Id_card_data[i])
+            }
+            if (res.need_net_short_url.length > 0) {
+                // 请求短链接
+                port.postMessage({ state: 'CONTENT_TWITTER_SHORT_LINK', arr_url: res.need_net_short_url })
+            }
+            if (card_json_data.length == res.has_post_Id_card_data.length || stop_time >= 5) {
+                clearInterval(timer)
+            }
+        })
+    }, 1000)
 }
 
-export function initExecuteScript(port,changes) {
+export function initExecuteScript(port, changes) {
     if (changes.executeScript) {
         let item = JSON.parse(changes.executeScript.newValue)
         if (item.executeScript) {
@@ -713,14 +558,21 @@ export function initExecuteScript(port,changes) {
     }
 }
 
-
+// 初始化
 export function init(port) {
     if (window.location.href.indexOf('twitter.com') < 0) {
         return
     }
     twitterPinLogin(port);
     renderDom(port);
-    setIframeRedPacket(port);
+    let targetNode = null
+    let timer = setInterval(() => {
+        targetNode = document.querySelector('main')
+        if (targetNode) {
+            clearInterval(timer)
+            onChangePageMain(port, targetNode)
+        }
+    }, 1000);
 
     getChromeStorage("popupShowPublishDialog", (res) => {
         console.log("popupShowPublishDialog", res);

+ 11 - 1
src/manifest.json

@@ -27,7 +27,16 @@
             ]
         }
     ],
-      "host_permissions": [
+    "declarative_net_request": {
+        "rule_resources": [
+            {
+                "id": "ruleset_1",
+                "enabled": true,
+                "path": "/rules/rules_1.json"
+            }
+        ]
+    },
+    "host_permissions": [
         "*://*.twitter.com/*",
         "*://twitter.com/*",
         "*://testh5.denetme.net/*",
@@ -35,6 +44,7 @@
         "*://preh5.denetme.net/*"
     ],
     "permissions": [
+        "declarativeNetRequest",
         "tabs",
         "action",
         "cookies",

+ 4 - 0
vue.config.js

@@ -99,6 +99,10 @@ module.exports = {
           {
             from: path.resolve(`src/manifest.json`),
             to: `${path.resolve('dist')}/manifest.json`
+          },
+          {
+            from: path.resolve(`src/rules`),
+            to: `${path.resolve('dist')}/rules`
           }
         ]
       })