| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579 | import { getChromeStorage, setChromeStorage, LANDING_PAGE } from '../uilts/chromeExtension.js'import { throttle } from '../uilts/help'import { getTtwitterRequestToken, twitterLogin } from '../server/twitter.js'import { srcPublishSuccess } from '../http/publishApi'let dom = {};export function contentTwitterPinLogin(port) {    if (window.location.href == 'https://api.twitter.com/oauth/authorize') {        let code = document.querySelector('code')        if (code) {            port.postMessage({ state: 'CONTENT_SEND_CODE', code: code.innerText })        }    }}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)            }        })    }    )}/** * 渲染要插入的dom,初始化逻辑 * @param port */export function renderDom(port) {    if (window.location.href.indexOf('https://twitter.com') > -1) {        _createBtnDom(port);        onWindowResize();        checkHasDeBtn();        setTimeout(() => {            _addIframe();            _addDeNetBtn();            _getSliderTwitterBtn();        }, 800)    }}/** * 展示give弹窗 */export function showGiveDialogHandler(userInfo) {    let iframe = document.getElementById('iframe-content');    if (iframe) {        iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', userInfo }, '*');    } else {        _addIframe();        let iframe = document.getElementById('iframe-content');        iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', userInfo }, '*');    }}export function showIframeHandler() {    document.getElementById('iframe-content').style.display = 'block';}export function hideIframeHandler() {    document.getElementById('iframe-content').style.display = 'none';}/** * 展示twitter原生发布框 */export function showTwitterPublishDialogHandler(publishRes) {    dom.tweetBtn.click();    _setPublishContent(publishRes.srcContent);    _publishTweetEvent(publishRes.postId);}export function showPinTips() {    getChromeStorage('pinData', (res) => {        if (!res || res.show) {            let domPop = document.getElementById('de-pin-pop');            domPop.style.display = 'block';        }    })}export function addPinedPop() {    let domPop = document.getElementById('de-pin-pop');    if(domPop) {        return;    }    let popWrapper = document.createElement('div');    popWrapper.style.cssText = 'position: fixed; height: 400px;width: 300px;top: 12px;right: 20px;border-radius: 12px;border: 0.5px solid #919191;box-sizing: border-box;padding: 20px;background: #fff;display:none';    popWrapper.id = 'de-pin-pop'    let img = document.createElement('img');    img.src = require("../assets/img/img-pined-guide.png");    let contentDom = document.createElement('div');    contentDom.innerHTML = "<div style='font-weight: 500;font-size: 18px;margin-top: 20px;margin-bottom: 20px'>📌 Pin an Extension is more convenient to open😄</div><div style='display: flex; align-items: center; justify-content: space-between;'><div style='display: flex; align-items: center; font-size: 14px; color: #899099; cursor: pointer;'><input id='de-check' type='checkbox'/> Don't remind</div><div class='de-pin-skip' style='font-weight: 500; font-size: 16px; color: #389AFF;cursor: pointer;'>Skip</div></div>"    let arrow = document.createElement('div');    arrow.style.cssText = 'position: absolute;height: 15px;width: 15px;top: -8px;right: 80px;border-left: 0.5px solid rgb(145, 145, 145);border-top: 0.5px solid rgb(145, 145, 145);background: rgb(255, 255, 255);transform: rotate(45deg);';    popWrapper.appendChild(arrow);    popWrapper.appendChild(img);    popWrapper.appendChild(contentDom);    document.querySelector('body').appendChild(popWrapper);    document.querySelector('#de-check').onclick = function() {        setChromeStorage({ pinData: JSON.stringify({show: !this.checked}) })    }    document.querySelector('.de-pin-skip').onclick = function() {        document.querySelector('#de-pin-pop').style.display = 'none';    }}function getUserInfo(cb) {    getChromeStorage('userInfo', (res) => {        cb && cb(res);    })}// 绑定推文id所需参数let bindTwitterArt = {    needBind: false,    postId: '',    isBindIng: false};/** * 监听dialog内点击原生发布按钮事件 * @private */function _publishTweetEvent(contentStr, cb) {    setTimeout(() => {        let publishTweetBtn = document.querySelector('div[role="dialog"]').querySelector('div[data-testid="tweetButton"]');        publishTweetBtn.addEventListener('click', function () {            bindTwitterArt.needBind = true;            bindTwitterArt.postId = contentStr;            isSetContent = false;            // setTimeout(() => {            //     _getTwitterArtId(contentStr, (twitterArtId) => {            cb && cb()            //     });            // }, 1500)        });    }, 800)}/** * 在输入推文区插入deNet按钮 * @param parent * @param dom * @param isClick * @private */function _addDeNetEditBtn(parent, dom, isClick = false) {    setTimeout(() => {        if (parent && parent.parentNode) {            parent.parentNode.insertBefore(dom, parent.nextElementSibling);        } else {            setTimeout(() => {                parent = _getScheduleDom(isClick);                parent && parent.parentNode && parent.parentNode.insertBefore(dom, parent.nextElementSibling);            }, 1000)        }    })}/** * 在dialog插入deNet按钮 * @private */// function _addDeNetBtnToDialog() {//     setTimeout(() => {//         let dialogScheduleBtn = _getScheduleDom(true);//         _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn2);//     }, 800)// }/** * 获取左侧twitter按钮 * @private */function _getSliderTwitterBtn() {    dom.tweetBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');    dom.tweetBtn.addEventListener('click', function () {        // _addDeNetBtnToDialog();    })}/** * 添加deNet按钮 * @private */function _addDeNetBtn() {    setTimeout(() => {        let navWidth = document.querySelector('nav[role="navigation"]').offsetWidth;        addSliderNavDeBtn(navWidth < 245);        let innerDeIcon = document.getElementById('de-btn1');        if (!innerDeIcon) {            let dialogScheduleBtn = _getScheduleDom(false);            _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn1);        }    }, 800)}/** * 获取推文输入框内dom,用于插入deNet * @param isDialogInner * @returns {Element} * @private */function _getScheduleDom(isDialogInner = false) {    let scheduleBtn;    if (isDialogInner) {        scheduleBtn = document.querySelector('div[role="dialog"]').querySelector('[data-testid="createPollButton"]');    } else {        let toolBar = document.querySelector('div[data-testid="toolBar"]');        if (toolBar) {            scheduleBtn = toolBar.querySelector('div[data-testid="geoButton"]');        }    }    return scheduleBtn;}/** * 插入iframe到页面 * @private */function _addIframe() {    // let span = document.createElement('span');    // const shadowRoot = span.attachShadow({mode: 'closed'})    let iframe = document.createElement('iframe');    iframe.src = chrome.runtime.getURL('/iframe/publish.html')    iframe.id = 'iframe-content'    iframe.style.cssText = 'position:fixed;top:0px;right:0;display:block; width:100%;height:100%;z-index:0; border: medium none;display:none';    // shadowRoot.appendChild(iframe);    // document.body.appendChild(span)    dom.iframe = iframe;    let iframeContent = document.getElementById('iframe-content');    if(!iframeContent) {        document.getElementById('layers').appendChild(iframe);    }}/** * 获取发布推文id * @returns {string} * @private *//** function _getTwitterArtId(contentStr, cb) {    let id = '';    let timer = setInterval(() => {        let arr = document.querySelectorAll('a') || [];        for (let i = 0; i < arr.length; i++) {            let item = arr[i];            if (item.innerText == '#DeNet') {                if (item.parentNode && item.parentNode.parentNode && item.parentNode.parentNode.innerText.length > 5) {                    let _postId = item.parentNode.parentNode.innerText || ''                    let _dom = item.parentNode.parentNode.parentNode.parentNode.parentNode                    let regex = new RegExp(contentStr);                    if (regex.test(_postId)) {                        id = _dom.children[0].querySelector('a[dir="auto"]').getAttribute('href').split('/status/')[1];                        clearInterval(timer);                        if (id) {                            cb && cb(id);                        }                        break;                    }                }            }        }    }, 1000);}*//** * 点击deNet按钮处理 * @private */function _deNetBtnClick(port) {    getUserInfo((res) => {        if (res) {            if (window.location.pathname != '/home') {                if (!dom.homeBtn) {                    dom.homeBtn = document.querySelector('a[data-testid="AppTabBar_Home_Link"]');                }                dom.homeBtn.click();            }            showGiveDialogHandler(res);        } else {            let loadIcon = document.getElementById('de-btn-loading');            if (loadIcon) {                return;            }            dom.deBtn.insertBefore(dom.loadingImg, dom.deBtn.querySelector('span'));            setTimeout(() => {                dom.deBtn.innerHTML = '<span>DeNet<span>';            }, 3000)            port.postMessage({ state: 'CONTENT_TWITTER_LOGIN' })        }    })}/** * 设置发布内容 * @param content * @private */let isSetContent = false;function _setPublishContent(content) {    setTimeout(() => {        // document.execCommand('selectAll')        // document.execCommand("Delete","false",null);        if(!isSetContent) {            isSetContent = true;            document.execCommand("insertText", false, content);        }            }, 1000);}/** * 创建deNet按钮 添加到页面 * @returns {{deBtn2: HTMLDivElement, deBtn1: HTMLDivElement, deBtn: HTMLSpanElement}} * @private */function _createBtnDom(port) {    let loadingImg = document.createElement('img');    loadingImg.id = 'de-btn-loading'    loadingImg.src = require("../assets/img/icon-btn-loading.png");    loadingImg.style.cssText = 'width:20px;height: 20px;margin-right:3px;-webkit-animation:load 1.1s infinite linear;';    let style = document.createElement('style');    style.innerHTML = "#de-btn:hover{opacity: .9;};@-webkit-keyframes load{from{ transform: rotate(0deg);} to{transform: rotate(360deg);}}";    document.getElementsByTagName('head').item(0).appendChild(style);    let deBtn = document.createElement('span');    // const shadowDiv = document.createElement('div');    deBtn.innerHTML = '<span>DeNet</span>';    deBtn.id = 'de-btn';    deBtn.style.cssText = 'width:90%;height: 52px;text-align:center;line-height:52px;margin-bottom: 4px;margin-top: 4px;background: linear-gradient(274.8deg, #FF9900 -3.69%, #BD00FF 69.71%, #00F0FF 122.65%);color:#fff;font-size:17px;font-weight:700;border-radius:100px;cursor: pointer;display: flex;align-items: center;justify-content: center;';    const deBtn1 = document.createElement('img');    let src = require("../assets/img/icon-gift-pack.png");    const smallDeBtnStyle = 'width:20px;height: 20px;cursor: pointer;marign-left:4px;margin-right:4px';    deBtn1.id = 'de-btn1';    deBtn1.style.cssText = smallDeBtnStyle;    deBtn1.src = src    const deBtn2 = document.createElement('div');    deBtn2.id = 'de-btn2';    deBtn2.style.cssText = smallDeBtnStyle;    deBtn2.src = "../assets/img/icon-gift-pack.png"    const deBtn3 = document.createElement('img');    deBtn3.id = 'de-btn3'    deBtn3.src = require("../assets/img/icon-slider-de-net-btn.png");    deBtn3.style.cssText = 'width:52px;height: 52px;margin-top:20px;cursor: pointer;';    deBtn.addEventListener('click', () => {        _deNetBtnClick(port);    })    deBtn1.addEventListener('click', () => {        _deNetBtnClick(port);    })    deBtn2.addEventListener('click', () => {        _deNetBtnClick(port);    })    deBtn3.addEventListener('click', () => {        _deNetBtnClick(port);    })    dom.deBtn = deBtn;    dom.deBtn1 = deBtn1;    dom.deBtn2 = deBtn2;    dom.deBtn3 = deBtn3;    dom.loadingImg = loadingImg;}function addSliderNavDeBtn(isSmall = false) {    if (!isSmall) {        let bigDom = document.querySelector('h1[role]').parentNode.parentNode;        let deBtn = document.getElementById('de-btn');        if (bigDom && !deBtn) {            bigDom.appendChild(dom.deBtn);        }    } else {        let smallDom = document.querySelector('h1[role]').parentNode.parentNode;        let deBtn3 = document.getElementById('de-btn3');        if (smallDom && !deBtn3) {            smallDom.appendChild(dom.deBtn3);        }    }}function onWindowResize() {    window.onresize = throttle(function () {        try {            if (window.innerWidth < 1273) {                let bigBtn = document.querySelector('#de-btn');                bigBtn && bigBtn.remove();                setTimeout(() => {                    addSliderNavDeBtn(true);                })            } else {                let smallBtn = document.querySelector('#de-btn3');                smallBtn && smallBtn.remove();                setTimeout(() => {                    addSliderNavDeBtn()                })            }        } catch (e) {            console.log(e)        }    }, 800)}function checkHasDeBtn() {    setInterval(() => {        try {            let toolBar = document.querySelector('div[data-testid="toolBar"]');            let innerDeIcon = document.getElementById('de-btn1');            if (toolBar && !innerDeIcon) {                let dialogScheduleBtn = _getScheduleDom(false);                _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn1);            }        } catch (e) {            console.log(e)        }    }, 1000)}/** * 根据postID绑定推文id */ function bindTwitterArtMethod({postId, twitterId}) {    let regex = new RegExp(bindTwitterArt.postId);    if (regex.test(postId)) {        if (twitterId && bindTwitterArt.needBind && !bindTwitterArt.isBindIng) {            bindTwitterArt.isBindIng = true;            srcPublishSuccess({                params: {                       postId: postId,                    srcContentId: twitterId                }            }).then((res) => {                if(res.code == 0) {                    bindTwitterArt.needBind = false;                    bindTwitterArt.postId = '';                    bindTwitterArt.isBindIng = false;                }            })        }    }}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]')            let _postId = _txt_area.innerText            _postId = _postId.match(/###([\s\S]*?)###/)[1]            _dom = _article.querySelector('[aria-labelledby]')            if (_dom) {                _type = 'card'            } else {                _type = 'parnet'                _dom = _txt_area.parentNode.parentNode            }            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 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;'    return _iframe}function replaceDOMRedPacket(_type, _dom, postId, tweetId) {    if (!_dom || _dom.querySelector('iframe')) {        return    }    let _len    if (_type == 'card') {        _len = _dom.childNodes.length        for (let i = 0; i < _len; i++) {            _dom.children[i].style.display = 'none'        }        _dom.style = 'height:500px'        _dom.appendChild(createIframe(postId,tweetId))    } else {        _dom.insertBefore(createIframe(postId,tweetId), _dom.children[1])    }}export function setIframeRedPacket() {    // let elment = document.documentElement    if (window.location.href.includes('https://twitter.com)')) {        return    }    // const observer = new MutationObserver(callback);    parseDOMRedPacket()    // let _current_top = 0    setInterval(() => {        parseDOMRedPacket()    }, 1000)    // document.addEventListener('scroll', (e) => {    // if ((elment.scrollTop - _current_top) > 500 || (_current_top - elment.scrollTop) > 500) {    // _current_top = elment.scrollTop    // 1.解析推文    // 2.替换推文    // parseDOMRedPacket()    // }    // })}
 |