| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354 | import { fetchTtwitterRequestToken, fetchTwitterLogin, fetchTwitterShortUrl, fetchAllMessageInfo, fetchReadTaskAllMsg, getDiscordUserInfo } from '@/logic/background/fetch/twitter.js'import { LANDING_PAGE, LANDING_PAGE_MID, setChromeStorage, setChromeCookie, getChromeCookie, getChromeStorage, removeChromeCookie } from '@/uilts/chromeExtension.js'import { guid } from '@/uilts/help.js'import { pageUrl, discordAuthRedirectUri } from '@/http/configAPI'let authToken = ''let consumerKey = ''let tab_flag = trueconst isHasTabByUrl = (url, callback) => {    let item    chrome.tabs.query({}, (tab) => {        for (let i in tab) {            if (tab[i].url.indexOf(url) >= 0) {                item = tab[i]                break            }        }        callback(item)    })}export function twitterPinLoginToken() {    // 1.判断是否登陆了    getChromeStorage('userInfo', (res) => {        // 没有登陆        if (!res) {            if (tab_flag == false) {                return            }            tab_flag = false            fetchTtwitterRequestToken().then((res) => {                tab_flag = true                if (res.code == 0) {                    authToken = res.data.authToken                    consumerKey = res.data.consumerKey                    isHasTabByUrl('https://api.twitter.com/oauth/authorize?oauth_token', (tab) => {                        if (!tab) {                            chrome.tabs.create({                                url: `https://api.twitter.com/oauth/authorize?oauth_token=${res.data.authToken}`                            })                        } else {                            chrome.tabs.highlight({ windowId: tab.windowId, tabs: tab.index })                        }                    })                }            }).catch(() => {                tab_flag = true            })        }    })}export function twitterPinLoginCode(sender, code) {    // actionType:{}    // 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.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_TWITTER_LOGIN_SUCCESS' }, (res) => { console.log(res) });    chrome.tabs.remove(sender.tab.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, consumerKey, code, receivedIds).then(res => {            if (res.code == 0) {                setChromeStorage({ userInfo: JSON.stringify(res.data) })                // 获取全局消息数据                setMessageCount()                chrome.cookies.remove(LANDING_PAGE)            }        })    })}let discordAuthWindowId = '';export function saveDiscordAuthWindowId(params) {    let { windowId = '' } = params.data || {};    discordAuthWindowId = windowId;}export function discordLoginCode({ code }, sender) {    console.log('sender', sender)    let { windowId, id } = sender.tab || {};    chrome.tabs.remove(id);    // 发送请求    getDiscordUserInfo({        authCode: code,        redirectUrl: discordAuthRedirectUri    }).then(res => {        if (res.code == 0) {            setTimeout(() => {                sendActivetabMessage({                    actionType: 'BACK_DISCORD_LOGIN_SUCCESS'                });            })        }    })    // if(windowId) {    //     chrome.windows.remove(    //         windowId,    //         function () {    //         }    //     )    // }}export function twitterShortUrl(sender, url) {    fetchTwitterShortUrl(url).then(res => {        let str_arr = res.match(/denetme.net\/([\s\S]*?)"/) || []        let post_Id = str_arr[1] || ''        if (!post_Id) {            return        }        // 解析        let _obj = {            short_url: url,            post_Id        }        getChromeStorage('cardData', item => {            if (item) {                let has = false                for (let i in item) {                    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                    }                }                if (!has) {                    item.push(_obj)                    setChromeStorage({ cardData: JSON.stringify(item) })                }            } else {                setChromeStorage({ cardData: JSON.stringify([_obj]) })            }            chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_TWITTER_SHORT_URL' }, (response) => { });            // port.postMessage({            //     state: "BACK_TWITTER_SHORT_URL"            // });        })    })}// 安装插件后获取midexport 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) {                chrome.scripting.executeScript({                    target: { tabId: tab[i].id },                    files: ['js/content_help.js']                }, () => { })                if (tab[i].url.indexOf('twitter.com') >= 0 || tab[i].url.indexOf('facebook.com') >= 0) {                    chrome.scripting.executeScript({                        target: { tabId: tab[i].id },                        files: ['js/content.js'],                    }, () => {                        setTimeout(() => {                            setChromeStorage({ executeScript: JSON.stringify({ executeScript: 1 }) })                        }, 2000);                    })                }            }        })    })}/** * 检查是否pined 显示tips */export function checkPined() {    chrome.action.getUserSettings(res => {        let { isOnToolbar } = res;        if (!isOnToolbar) {            sendActivetabMessage({                actionType: 'BG_SHOW_PIN_TIPS'            });        }    })}function sendActivetabMessage(message = {}) {    chrome.tabs.query({        active: true,        currentWindow: true    }, (tabs) => {        chrome.tabs.sendMessage(tabs[0].id, message, res => {            console.log(res)        })    })}/** * 安装后打开新标签页 */export function onInstalledCreateTab() {    let cookiesParams = {        name: 'pickup_info',        url: pageUrl    }    getChromeCookie(cookiesParams, (res) => {        let { postNickName, srcContentId } = res;        if (res && postNickName && srcContentId) {            let url = `https://twitter.com/${postNickName}/status/${srcContentId}`            chrome.tabs.create({                url            });            removeChromeCookie(cookiesParams)        } else {            chrome.tabs.create({                url: "https://twitter.com",            });        }    })}/** * 在popop重新发送 * @param {*} req  */export function popupRePublish(req) {    setChromeStorage({        popupShowPublishDialog: JSON.stringify({            ...req.data,            show: true        }),    });    chrome.tabs.create({        url: "https://twitter.com",    });}export function setBadgeInfo(params) {    let { text = '', color = '#DF3535' } = params.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] });}export async function setMessageCount() {    const { accessToken: token = '', uid = '' } = await getChromeStorage('userInfo') || {}    if (token) {        getMessageInfo();        createAlarm();    }}function createAlarm() {    let alarmInfo = {        //1分鐘之後開始(該值不能小於1)         delayInMinutes: 1,        //與上方等同的寫法是         // when : Date.now() + n,        //開始後每一分鐘執行一次(該值不能小于1)         periodInMinutes: 1    };    //每次加載就清空定時器    chrome.alarms.clear('denetChromeAlarm');    //創造定時器    chrome.alarms.create('denetChromeAlarm', alarmInfo);}export function getMessageInfo() {    fetchAllMessageInfo().then(res => {        if (res.code == 0) {            let { unReadCountTotal = 0 } = res.data;            if (unReadCountTotal > 0) {                let text = unReadCountTotal > 99 ? '99+' : unReadCountTotal + '';                setBadgeInfo({ data: { text } });            } else {                hideBadge();            }        }    })}export function readTaskAllMsg({ msgType }, cb) {    fetchReadTaskAllMsg({        msgType // 1:任务红包 2:钱包明细    }).then(res => {        if (res.code == 0) {            cb && cb();        }    });}export const onDisconnectHandler = (port) => {    if (port.name === "popup" || port.name === "popup_transactions") {        let msgType = port.name === "popup" ? 1 : 2;        readTaskAllMsg({ msgType }, () => {            getMessageInfo();        })    }}export const injectExtensionPopup = (tab) => {    sendActivetabMessage({        actionType: 'BG_INJECT_EXTENSION_POPUP'    });}
 |