Browse Source

Merge branch 'master' of https://git.yishihui.com/DeNet/de-net

zhangwei 2 năm trước cách đây
mục cha
commit
2c23c21dd0

+ 24 - 17
src/entry/background.js

@@ -53,7 +53,7 @@ chrome.runtime.onUpdateAvailable.addListener(() => {
         Report.reportLog({
             objectType: Report.objectType.background_function_try,
             funcName: 'onUpdateAvailable'
-        });
+        })
         chrome.runtime.reload()
     } catch (error) {
         Report.reportLog({
@@ -115,30 +115,37 @@ function thenInstalledMethod() {
     } catch (error) {
         Report.reportLog({
             objectType: Report.objectType.background_function_catch,
-            funcName: 'onInstalledMethod',
+            funcName: 'thenInstalledMethod',
             errMsg: error.message
-        });
+        })
     }
 }
 function onInstalledMethod() {
-    // 版本更新判断
-    getChromeStorage('baseInfo', (info) => {
-        if (!info || !info.appVersionCode) {
-            setChromeStorage({ baseInfo: JSON.stringify({ appVersionCode }) })
-            thenInstalledMethod()
-        } else if (appVersionCode != info.appVersionCode) {
-            setChromeStorage({ baseInfo: JSON.stringify({ appVersionCode }) }, () => {
-                chrome.runtime.reload()
-            })
-        } else {
-            thenInstalledMethod()
-        }
-    })
+    try {
+        // 版本更新判断
+        getChromeStorage('baseInfo', (info) => {
+            if (!info || !info.appVersionCode) {
+                setChromeStorage({ baseInfo: JSON.stringify({ appVersionCode }) })
+                thenInstalledMethod()
+            } else if (appVersionCode != info.appVersionCode) {
+                setChromeStorage({ baseInfo: JSON.stringify({ appVersionCode }) }, () => {
+                    chrome.runtime.reload()
+                })
+            } else {
+                thenInstalledMethod()
+            }
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'onInstalledMethod',
+            errMsg: error.message
+        })
+    }
 }
 
 function onMessageMethod(req, sender, sendResponse) {
     try {
-
         if (req) {
             switch (req.actionType) {
                 case "POPUP_LOGIN":

+ 70 - 65
src/http/fetch.js

@@ -1,72 +1,77 @@
 import { appVersionCode, baseAPIUrl } from '@/http/configAPI.js'
 import { getChromeStorage } from '@/uilts/chromeExtension.js'
 
-export async function commonFetch({ url = '', method = 'POST' , params = {}, baseInfo = {}}) {
-
-    let storage_mid = await getChromeStorage('mid') || ''
-    const { mid } = storage_mid || {}
-    if (!baseInfo.token || !baseInfo.uid) {
-        const { accessToken: token = '', uid = '' } = await getChromeStorage('userInfo') || {}
-        baseInfo.token = token
-        baseInfo.uid = uid
-    }
-    baseInfo.mid = mid
-    baseInfo.appVersionCode = appVersionCode
-    baseInfo.machineCode = mid
-    baseInfo.appType = 1
-    baseInfo.loginUid = baseInfo.uid
-
-    return new Promise(function (resolve, reject) {
-        let _url = baseAPIUrl + url
-        if(url.includes('http')){
-            _url = url
+export async function commonFetch({ url = '', method = 'POST', params = {}, baseInfo = {} }) {
+    try {
+        let storage_mid = await getChromeStorage('mid') || ''
+        const { mid } = storage_mid || {}
+        if (!baseInfo.token || !baseInfo.uid) {
+            const { accessToken: token = '', uid = '' } = await getChromeStorage('userInfo') || {}
+            baseInfo.token = token
+            baseInfo.uid = uid
         }
-        let bodyObj = {
-            "baseInfo": baseInfo,
-            "params": params
-        };
-        fetch(_url, {
-            method: method, // or 'PUT'
-            cache: 'no-cache',
-            headers: {
-                'Content-Type': 'application/json',
-            },
-            body: JSON.stringify(bodyObj),
-        })
-            .then(response => response.json())
-            .then(data => {
-                switch (data.code.toString()) {
-                    // twitter授权失效
-                    case '1003':
-                        chrome.storage.local.remove("userInfo");
-                        chrome.runtime.sendMessage(
-                            { actionType: "POPUP_LOGIN", data: "" },
-                            (response) => {
-                                console.log("res", response);
-                            }
-                        )
-                        break;
-                    // 登陆token失效
-                    case '-107':
-                        chrome.storage.local.remove("userInfo");
-                        chrome.runtime.sendMessage(
-                            { actionType: "POPUP_LOGIN", data: "" },
-                            (response) => {
-                                console.log("res", response);
-                            }
-                        )
-                        break;
-                }
+        baseInfo.mid = mid
+        baseInfo.appVersionCode = appVersionCode
+        baseInfo.machineCode = mid
+        baseInfo.appType = 1
+        baseInfo.loginUid = baseInfo.uid
 
-                resolve(data);
+        return new Promise(function (resolve, reject) {
+            let _url = baseAPIUrl + url
+            if (url.includes('http')) {
+                _url = url
+            }
+            let bodyObj = {
+                "baseInfo": baseInfo,
+                "params": params
+            };
+            fetch(_url, {
+                method: method, // or 'PUT'
+                cache: 'no-cache',
+                headers: {
+                    'Content-Type': 'application/json',
+                },
+                body: JSON.stringify(bodyObj),
             })
-            .catch((error) => {
-                if(!error) {
-                    error = {}
-                }
-                reject({url: _url, 
-                        error: { message: error.message, stack: error.stack }, 
-                        requestParams: bodyObj });
-            });
-    })
+                .then(response => response.json())
+                .then(data => {
+                    switch (data.code.toString()) {
+                        // twitter授权失效
+                        case '1003':
+                            chrome.storage.local.remove("userInfo");
+                            chrome.runtime.sendMessage(
+                                { actionType: "POPUP_LOGIN", data: "" },
+                                (response) => {
+                                    console.log("res", response);
+                                }
+                            )
+                            break;
+                        // 登陆token失效
+                        case '-107':
+                            chrome.storage.local.remove("userInfo");
+                            chrome.runtime.sendMessage(
+                                { actionType: "POPUP_LOGIN", data: "" },
+                                (response) => {
+                                    console.log("res", response);
+                                }
+                            )
+                            break;
+                    }
+
+                    resolve(data);
+                })
+                .catch((error) => {
+                    if (!error) {
+                        error = {}
+                    }
+                    reject({
+                        url: _url,
+                        error: { message: error.message, stack: error.stack },
+                        requestParams: bodyObj
+                    });
+                });
+        })
+    } catch (error) {
+        console.log('error', error)
+    }
 }

+ 8 - 0
src/http/nft.js

@@ -79,4 +79,12 @@ export function transferRequest(params) {
         method: 'post',
         data: params
     })
+}
+
+export function redeemNft(params) {
+    return service({
+        url: `/nft/project/redeemNft`,
+        method: 'post',
+        data: params
+    })
 }

+ 4 - 4
src/log-center/autoLog/click.js

@@ -8,11 +8,11 @@ let clickDataMap = new Map();
 
 const clickHandle = (e) => { 
     const target = getTargetElementWhenClick(e);
-    const logData = clickDataMap.get(target?.denetClickLogkey);
-    return logData && reportLog({
+    const { extParams, ...eventData } = clickDataMap.get(target?.denetClickLogkey);
+    return eventData && reportLog({
         businessType: Report.businessType.buttonClick,
-        ...logData
-    })
+        ...eventData
+    }, extParams)
 }
 
 const clickLog =  {

+ 4 - 4
src/log-center/autoLog/show.js

@@ -39,11 +39,11 @@ class ShowLogObserver {
     }
 
     report(el) { 
-        const logData = this.showLogMap.get(el?.target?.denetShowLogkey);
-        return logData && reportLog({
+        const { extParams, ...eventData } = this.showLogMap.get(el?.target?.denetShowLogkey);
+        return eventData && reportLog({
             businessType: Report.businessType.pageView,
-            ...logData
-        })
+            ...eventData
+        }, extParams)
     }
 }
 

+ 2 - 0
src/log-center/logEnum.js

@@ -55,6 +55,7 @@ export const objectType = {
     // create Nft
     create_nfts_button: 'create-nfts-button',
     confirm_transfer_button: 'confirm-transfer-button',
+    redeem_button: 'redeem-button',
 }
 
 export const pageSource = {
@@ -71,6 +72,7 @@ export const pageSource = {
     denetTopupSelector: "denet-topup-selector",
     denetMorePage: "denet-more-page",
     denetSelector: "denet-selector",
+    nftShopPage: "nft-shop-page",
     denetNftTransferPage: "denet-nft-transfer-page",
     // 待开红包页
     pending_page: 'pending-page',

+ 33 - 16
src/logic/background/denet.js

@@ -1,25 +1,42 @@
 import { getChromeStorage } from '@/uilts/chromeExtension.js'
 import { payAchNoticeUrl } from '@/http/configAPI'
+import Report from "@/log-center/log"
 
 export const closeAchPayNoticeHandler = async () => {
-    let res = await getCurrentTab();
-    if(res.url.startsWith(payAchNoticeUrl)) {
-        chrome.tabs.remove(
-            res.id, () => {
-                getChromeStorage('achPayInfo', (result) => {
-                    let {tab} = result || {};
-                    chrome.storage.local.remove("achPayInfo");
-                    if(tab) {
-                        chrome.tabs.highlight({ windowId: tab.windowId, tabs: tab.index })
-                    }
-                })
-            }
-        )
+    try{
+        let res = await getCurrentTab();
+        if(res.url.startsWith(payAchNoticeUrl)) {
+            chrome.tabs.remove(
+                res.id, () => {
+                    getChromeStorage('achPayInfo', (result) => {
+                        let {tab} = result || {};
+                        chrome.storage.local.remove("achPayInfo");
+                        if(tab) {
+                            chrome.tabs.highlight({ windowId: tab.windowId, tabs: tab.index })
+                        }
+                    })
+                }
+            )
+        }
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'closeAchPayNoticeHandler',
+            errMsg: error.message
+        })
     }
 }
 
 const getCurrentTab = async () => {
-    let queryOptions = { active: true, lastFocusedWindow: true };
-    let [tab] = await chrome.tabs.query(queryOptions);
-    return tab || {};
+    try{
+        let queryOptions = { active: true, lastFocusedWindow: true };
+        let [tab] = await chrome.tabs.query(queryOptions);
+        return tab || {};
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'getCurrentTab',
+            errMsg: error.message
+        })
+    }
 }

+ 40 - 23
src/logic/background/facebook.js

@@ -1,36 +1,53 @@
 import { fetchAddFinishEvent } from '@/logic/background/fetch/facebook'
+import Report from "@/log-center/log"
 
 /**
  * facebook分享成功逻辑
  */
 export function facebookShareSuccess(params, sender) {
-    let {data} = params;
-    let {id} = sender.tab || {};
-    chrome.tabs.remove(id);
+    try{
+        let {data} = params;
+        let {id} = sender.tab || {};
+        chrome.tabs.remove(id);
 
-    fetchAddFinishEvent({
-        eventType: data.type,
-        luckdropId: data.taskLuckdropId
-    }).then(res => {
-        if (res.code == 0) {
-            setTimeout(() => {
-                sendActivetabMessage({
-                    actionType: 'BG_FACEBOOK_SHARE_SUCCESS',
-                    data: data
-                });
-            })
-        }
-    })
+        fetchAddFinishEvent({
+            eventType: data.type,
+            luckdropId: data.taskLuckdropId
+        }).then(res => {
+            if (res.code == 0) {
+                setTimeout(() => {
+                    sendActivetabMessage({
+                        actionType: 'BG_FACEBOOK_SHARE_SUCCESS',
+                        data: data
+                    });
+                })
+            }
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'facebookShareSuccess',
+            errMsg: error.message
+        })
+    }
 }
 
 
 function sendActivetabMessage(message = {}) {
-    chrome.tabs.query({
-        active: true,
-        currentWindow: true
-    }, (tabs) => {
-        chrome.tabs.sendMessage(tabs[0].id, message, res => {
-            console.log(res)
+    try{
+        chrome.tabs.query({
+            active: true,
+            currentWindow: true
+        }, (tabs) => {
+            chrome.tabs.sendMessage(tabs[0].id, message, res => {
+                console.log(res)
+            })
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'sendActivetabMessage',
+            errMsg: error.message
         })
-    })
+    }
 }

+ 17 - 8
src/logic/background/fetch/twitter.js

@@ -1,5 +1,6 @@
 import { commonFetch } from '@/http/fetch.js'
 import { getChromeStorage } from '@/uilts/chromeExtension.js'
+import Report from "@/log-center/log"
 export async function fetchTtwitterRequestToken() {
     return commonFetch({
         url: '/user/twitterRequestToken',
@@ -23,14 +24,22 @@ export async function fetchTwitterLogin(oauthToken, consumerKey, oauthVerifier,
 }
 // 请求推特短链接
 export async function fetchTwitterShortUrl(url) {
-    return new Promise(function (resolve, reject) {
-        fetch(url) // 返回一个Promise对象 
-            .then((res) => {
-                return res.text() // res.text()是一个Promise对象
-            }).then((res) => {
-                resolve(res.toString());
-            })
-    })
+    try {
+        return new Promise(function (resolve, reject) {
+            fetch(url) // 返回一个Promise对象 
+                .then((res) => {
+                    return res.text() // res.text()是一个Promise对象
+                }).then((res) => {
+                    resolve(res.toString());
+                })
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_try,
+            funcName: 'fetchTwitterShortUrl',
+            errMsg: error.message
+        })
+    }
 }
 
 

+ 60 - 27
src/logic/background/help.js

@@ -1,45 +1,78 @@
 import { commonFetch } from '@/http/fetch'
+import Report from "@/log-center/log"
 
 // 每4分钟调用一次,保持background一直有效
 export function PingPong() {
-    chrome.tabs.query({}, (tabs = []) => {
-        if (tabs.length) {
-            let tab = tabs.filter((item) => { return item.active == true })
-            if (tab.length) {
-                chrome.tabs.sendMessage(tab[0].id, { actionType: 'BACK_PING' }, () => { });
+    try {
+        chrome.tabs.query({}, (tabs = []) => {
+            if (tabs.length) {
+                let tab = tabs.filter((item) => { return item.active == true })
+                if (tab.length) {
+                    chrome.tabs.sendMessage(tab[0].id, { actionType: 'BACK_PING' }, () => { });
+                }
             }
-        }
-    })
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'PingPong',
+            errMsg: error.message
+        })
+    }
 }
 
 export function httpNetWork(funcName, data, sender) {
-    return commonFetch(data)
-        .then((response) => {
-            chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_HTTP_RESPONSE', data: response, funcName });
-        })
-        .catch(() => {
-            chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_HTTP_RESPONSE', data: null, funcName });
+    try {
+        return commonFetch(data)
+            .then((response) => {
+                chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_HTTP_RESPONSE', data: response, funcName });
+            })
+            .catch(() => {
+                chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_HTTP_RESPONSE', data: null, funcName });
+            })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'httpNetWork',
+            errMsg: error.message
         })
+    }
 }
 
 // 向content 发送消息
 export const setContentMessage = (obj) => {
-    chrome.tabs.query({}, (tabs = []) => {
-        if (tabs.length) {
-            tabs = tabs.filter((item) => { return item.active && item.selected && item.highlighted }) || []
-            tabs.forEach((item) => {
-                chrome.tabs.sendMessage(item.id, obj);
-            })
-        }
-    })
+    try {
+        chrome.tabs.query({}, (tabs = []) => {
+            if (tabs.length) {
+                tabs = tabs.filter((item) => { return item.active && item.selected && item.highlighted }) || []
+                tabs.forEach((item) => {
+                    chrome.tabs.sendMessage(item.id, obj);
+                })
+            }
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'setContentMessage',
+            errMsg: error.message
+        })
+    }
 }
 
 export const httpContentToBack = (req, sender) => {
-    commonFetch(req.data)
-        .then((response) => {
-            chrome.tabs.sendMessage(sender.tab.id, { actionType: 'HTTP_BACK_TO_CONTENT', data: response, callback_id: req.callback_id });
-        })
-        .catch(() => {
-            chrome.tabs.sendMessage(sender.tab.id, { actionType: 'HTTP_BACK_TO_CONTENT', data: null, callback_id: req.callback_id });
+    try {
+        commonFetch(req.data)
+            .then((response) => {
+                chrome.tabs.sendMessage(sender.tab.id, { actionType: 'HTTP_BACK_TO_CONTENT', data: response, callback_id: req.callback_id });
+            })
+            .catch(() => {
+                chrome.tabs.sendMessage(sender.tab.id, { actionType: 'HTTP_BACK_TO_CONTENT', data: null, callback_id: req.callback_id });
+            })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'httpContentToBack',
+            errMsg: error.message
         })
+    }
 }

+ 444 - 320
src/logic/background/twitter.js

@@ -9,52 +9,66 @@ let consumerKey = ''
 let tab_flag = true
 
 const 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
+    try {
+        let item
+        chrome.tabs.query({}, (tab) => {
+            for (let i in tab) {
+                if (tab[i].url.indexOf(url) >= 0) {
+                    item = tab[i]
+                    break
+                }
             }
-        }
-        callback(item)
-    })
+            callback(item)
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'isHasTabByUrl',
+            errMsg: error.message
+        })
+    }
 }
 
 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 })
-                        }
-                    })
+    try {
+        // 1.判断是否登陆了
+        getChromeStorage('userInfo', (res) => {
+            // 没有登陆
+            if (!res) {
+                if (tab_flag == false) {
+                    return
                 }
-            }).catch(() => {
-                tab_flag = true
-            })
-        }
-    })
+                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
+                })
+            }
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'twitterPinLoginToken',
+            errMsg: error.message
+        })
+    }
 }
 
 export function twitterPinLoginCode(sender, code) {
-    // actionType:{}
-
     // port.postMessage({
     //     state: "BACK_TWITTER_LOGIN_SUCCESS",
     // });
@@ -67,39 +81,45 @@ export function twitterPinLoginCode(sender, code) {
     //         }
     //     }
     // })
-    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)
+    try {
+        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
             }
-        }
-        // 发送请求
-        // token,code
-        fetchTwitterLogin(authToken, consumerKey, code, receivedIds).then(res => {
-            if (res.code == 0) {
-                setChromeStorage({ userInfo: JSON.stringify(res.data) })
-                setChromeCookie(WEBSITE_USER_INFO, res.data)
+            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) })
+                    setChromeCookie(WEBSITE_USER_INFO, res.data)
 
-                sendActivetabMessage({
-                    actionType: 'BG_LOGIN_SET_USERINFO_CB'
-                });
+                    sendActivetabMessage({
+                        actionType: 'BG_LOGIN_SET_USERINFO_CB'
+                    });
 
-                // 获取全局消息数据
-                setMessageCount()
-                chrome.cookies.remove(LANDING_PAGE)
-            }
+                    // 获取全局消息数据
+                    setMessageCount()
+                    chrome.cookies.remove(LANDING_PAGE)
+                }
+            })
         })
-    })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'twitterPinLoginCode',
+            errMsg: error.message
+        })
+    }
 }
 
 let discordAuthWindowId = '';
@@ -109,23 +129,31 @@ export function saveDiscordAuthWindowId(params) {
 }
 
 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'
-                });
-            })
-        }
-    })
+    try {
+        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'
+                    });
+                })
+            }
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'discordLoginCode',
+            errMsg: error.message
+        })
+    }
 
     // if(windowId) {
     //     chrome.windows.remove(
@@ -138,86 +166,110 @@ export function discordLoginCode({ code }, sender) {
 }
 
 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
+    try {
+        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) })
-                        has = true
-                        break
                     }
-                }
-                if (!has) {
-                    item.push(_obj)
-                    setChromeStorage({ cardData: JSON.stringify(item) })
-                }
 
-            } else {
-                setChromeStorage({ cardData: JSON.stringify([_obj]) })
-            }
+                } 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"
-            // });
+                chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_TWITTER_SHORT_URL' }, (response) => { });
+                // port.postMessage({
+                //     state: "BACK_TWITTER_SHORT_URL"
+                // });
+            })
         })
-    })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'twitterShortUrl',
+            errMsg: error.message
+        })
+    }
 }
 
 
 // 安装插件后获取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()
+    try {
+        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) })
             }
-            setChromeCookie(LANDING_PAGE, { 'mid': _params.mid })
-            setChromeStorage({ mid: JSON.stringify(_params) })
-        }
-    })
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'onInstalledMid',
+            errMsg: error.message
+        })
+    }
 }
 
 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) {
+    try {
+        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.js'],
-                    }, () => {
-                        setTimeout(() => {
-                            setChromeStorage({ executeScript: JSON.stringify({ executeScript: 1 }) })
-                        }, 2000);
-                    })
+                        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);
+                        })
+                    }
                 }
-            }
+            })
         })
-    })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'onInstalledUserSet',
+            errMsg: error.message
+        })
+    }
 }
 
 /**
@@ -235,14 +287,22 @@ export function checkPined() {
 }
 
 function sendActivetabMessage(message = {}) {
-    chrome.tabs.query({
-        active: true,
-        currentWindow: true
-    }, (tabs) => {
-        chrome.tabs.sendMessage(tabs[0].id, message, res => {
-            console.log(res)
+    try {
+        chrome.tabs.query({
+            active: true,
+            currentWindow: true
+        }, (tabs) => {
+            chrome.tabs.sendMessage(tabs[0].id, message, res => {
+                console.log(res)
+            })
         })
-    })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'sendActivetabMessage',
+            errMsg: error.message
+        });
+    }
 }
 
 
@@ -251,94 +311,106 @@ function sendActivetabMessage(message = {}) {
  */
 
 export function onInstalledCreateTab() {
-    getChromeCookie(LANDING_PAGE_JUMP_INFO, (res = {}) => {
-        setTimeout(() => {
-            // 安装成功埋点
-            Report.reportLog({
-                objectType: Report.objectType.chrome_extension_installed,
-                funcName: 'onInstalledCreateTab',
-                postId: res?.postId || ''
-            })
-        }, 5000)
-        let url = 'https://twitter.com/search?q=%23denet'
-        // jump_info
-        if (!res || !res.jump_type) {
-            chrome.tabs.create({
-                url
-            });
-            return
-        }
-        let created_detail = false
-        switch (String(res.jump_type)) {
-            // 普通红包
-            case 'red_packet':
-                if (res && res.postNickName && res.srcContentId) {
-                    created_detail = true
-                    url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
-                    chrome.tabs.create({
-                        url
-                    });
-                }
-                break
-            // 抽奖红包
-            case 'luck_draw':
-                if (res && res.postNickName && res.srcContentId) {
-                    created_detail = true
-                    url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
-                    chrome.tabs.create({
-                        url
-                    });
-                }
-                break
-            // NFT
-            case 'nft_info':
-                if (res && res.twitterAccount && res.nftProjectId) {
-                    created_detail = true
-                    url = `https://twitter.com/${res.twitterAccount}`
-                    chrome.tabs.create({
-                        url
-                    });
+    try {
+        getChromeCookie(LANDING_PAGE_JUMP_INFO, (res = {}) => {
+            setTimeout(() => {
+                if (!res) {
+                    res = {}
                 }
-                break
-            // NFT 组
-            case 'nft_group_info':
-                if (res && res.twitterAccount) {
-                    created_detail = true
-                    // setChromeStorage({ groupTabData: JSON.stringify({
-                    //     deTabVal: 'deGroupTab'
-                    // })})
-                    chrome.storage.local.set({
-                        groupTabData: JSON.stringify({
-                            deTabVal: 'deGroupTab'
-                        })
-                    }, (response) => {
+                // 安装成功埋点
+                Report.reportLog({
+                    objectType: Report.objectType.chrome_extension_installed,
+                    funcName: 'onInstalledCreateTab',
+                    postId: res.postId || ''
+                })
+            }, 5000)
+            let url = 'https://twitter.com/search?q=%23denet'
+            // jump_info
+            if (!res || !res.jump_type) {
+                chrome.tabs.create({
+                    url
+                });
+                return
+            }
+            let created_detail = false
+            switch (String(res.jump_type)) {
+                // 普通红包
+                case 'red_packet':
+                    if (res && res.postNickName && res.srcContentId) {
+                        created_detail = true
+                        url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
+                        chrome.tabs.create({
+                            url
+                        });
+                    }
+                    break
+                // 抽奖红包
+                case 'luck_draw':
+                    if (res && res.postNickName && res.srcContentId) {
+                        created_detail = true
+                        url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
+                        chrome.tabs.create({
+                            url
+                        });
+                    }
+                    break
+                // NFT
+                case 'nft_info':
+                    if (res && res.twitterAccount && res.nftProjectId) {
+                        created_detail = true
                         url = `https://twitter.com/${res.twitterAccount}`
                         chrome.tabs.create({
                             url
                         });
-                    })
-                }
-                break
-            // toolbox
-            case 'tool_box':
-                if (res && res.postNickName && res.srcContentId) {
-                    created_detail = true
-                    url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
-                    chrome.tabs.create({
-                        url
-                    });
-                }
-                break
-        }
+                    }
+                    break
+                // NFT 组
+                case 'nft_group_info':
+                    if (res && res.twitterAccount) {
+                        created_detail = true
+                        // setChromeStorage({ groupTabData: JSON.stringify({
+                        //     deTabVal: 'deGroupTab'
+                        // })})
+                        chrome.storage.local.set({
+                            groupTabData: JSON.stringify({
+                                deTabVal: 'deGroupTab'
+                            })
+                        }, (response) => {
+                            url = `https://twitter.com/${res.twitterAccount}`
+                            chrome.tabs.create({
+                                url
+                            });
+                        })
+                    }
+                    break
+                // toolbox
+                case 'tool_box':
+                    if (res && res.postNickName && res.srcContentId) {
+                        created_detail = true
+                        url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
+                        chrome.tabs.create({
+                            url
+                        });
+                    }
+                    break
+            }
 
-        if (created_detail == false) {
-            chrome.tabs.create({
-                url
-            });
-        }
+            if (created_detail == false) {
+                chrome.tabs.create({
+                    url
+                });
+            }
 
-        removeChromeCookie(LANDING_PAGE_JUMP_INFO)
-    })
+            removeChromeCookie(LANDING_PAGE_JUMP_INFO)
+
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'onInstalledCreateTab',
+            errMsg: error.message
+        })
+    }
 }
 
 /**
@@ -377,100 +449,144 @@ export async function setMessageCount() {
 }
 
 function createAlarm() {
-    let alarmInfo = {
-        //1分鐘之後開始(該值不能小於1) 
-        delayInMinutes: 1,
-        //與上方等同的寫法是 
-        // when : Date.now() + n,
-        //開始後每一分鐘執行一次(該值不能小于1) 
-        periodInMinutes: 1
-    };
-
-    //每次加載就清空定時器
-    chrome.alarms.clear('denetChromeAlarm');
-    //創造定時器
-    chrome.alarms.create('denetChromeAlarm', alarmInfo);
+    try {
+        let alarmInfo = {
+            //1分鐘之後開始(該值不能小於1) 
+            delayInMinutes: 1,
+            //與上方等同的寫法是 
+            // when : Date.now() + n,
+            //開始後每一分鐘執行一次(該值不能小于1) 
+            periodInMinutes: 1
+        };
+
+        //每次加載就清空定時器
+        chrome.alarms.clear('denetChromeAlarm');
+        //創造定時器
+        chrome.alarms.create('denetChromeAlarm', alarmInfo);
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'createAlarm',
+            errMsg: error.message
+        });
+    }
 }
 
 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();
+    try {
+        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();
+                }
             }
-        }
-    })
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'getMessageInfo',
+            errMsg: error.message
+        })
+    }
 }
 
 export function readTaskAllMsg({ msgType }, cb) {
-    fetchReadTaskAllMsg({
-        msgType // 1:任务红包 2:钱包明细
-    }).then(res => {
-        if (res.code == 0) {
-            cb && cb();
-        }
-    });
+    try {
+        fetchReadTaskAllMsg({
+            msgType // 1:任务红包 2:钱包明细
+        }).then(res => {
+            if (res.code == 0) {
+                cb && cb();
+            }
+        });
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'readTaskAllMsg',
+            errMsg: error.message
+        })
+    }
 }
 
 export const onDisconnectHandler = (port) => {
-    if (port.name === "popup" || port.name === "popup_transactions") {
-        let msgType = port.name === "popup" ? 1 : 2;
-        readTaskAllMsg({ msgType }, () => {
-            getMessageInfo();
+    try {
+        if (port.name === "popup" || port.name === "popup_transactions") {
+            let msgType = port.name === "popup" ? 1 : 2;
+            readTaskAllMsg({ msgType }, () => {
+                getMessageInfo();
+            })
+        }
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'onDisconnectHandler',
+            errMsg: error.message
         })
     }
 }
 
 export const injectExtensionPopup = (tab) => {
-    sendActivetabMessage({
-        actionType: 'BG_INJECT_EXTENSION_POPUP'
-    });
+    try {
+        sendActivetabMessage({
+            actionType: 'BG_INJECT_EXTENSION_POPUP'
+        });
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'injectExtensionPopup',
+            errMsg: error.message
+        })
+    }
 }
 
 export const setPopupConfig = (activeInfo) => {
-    chrome.tabs.query({
-        active: true,
-        currentWindow: true
-    }, (tabs) => {
-        if (tabs.length) {
-            let { pendingUrl = '', url = '' } = tabs[0];
-            if (pendingUrl.startsWith('https://twitter.com') || url.startsWith('https://twitter.com')) {
-                sendActivetabMessage({
-                    actionType: 'BG_SET_POPUP_CONFIG'
-                });
-            } else {
-                chrome.action.setPopup({
-                    popup: 'popup.html',
-                }, function () {
-                });
+    try {
+        chrome.tabs.query({
+            active: true,
+            currentWindow: true
+        }, (tabs) => {
+            if (tabs.length) {
+                let { pendingUrl = '', url = '' } = tabs[0];
+                if (pendingUrl.startsWith('https://twitter.com') || url.startsWith('https://twitter.com')) {
+                    sendActivetabMessage({
+                        actionType: 'BG_SET_POPUP_CONFIG'
+                    });
+                } else {
+                    chrome.action.setPopup({
+                        popup: 'popup.html',
+                    }, function () {
+                    });
+                }
             }
-
-            // if(pendingUrl.startsWith('chrome://') || url.startsWith('chrome://') || pendingUrl.startsWith('https://chrome.google.com') || url.startsWith('https://chrome.google.com')) {
-            //     chrome.action.setPopup({
-            //         popup: 'popup.html',
-            //     },function() {
-            //     });
-            // } else {
-            //     chrome.action.setPopup({
-            //         popup: '',
-            //     },function() {
-            //     });
-            // }
-        }
-    })
+        })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'setPopupConfig',
+            errMsg: error.message
+        })
+    }
 }
 
 export const getSysMessage = () => {
-    // 请求通知接口
-    fetchGetAllUnReadNotices({})
-        .then((res) => {
-            // 向选中的content发送消息
-            setContentMessage({ actionType: 'BACK_UNREAD_MESSAGE', data: res })
+    try {
+        // 请求通知接口
+        fetchGetAllUnReadNotices({})
+            .then((res) => {
+                // 向选中的content发送消息
+                setContentMessage({ actionType: 'BACK_UNREAD_MESSAGE', data: res })
+            })
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'getSysMessage',
+            errMsg: error.message
         })
+    }
 }
 
 export const windwoLoadSetPopupPage = (data, sender) => {
@@ -489,22 +605,30 @@ export const windwoLoadSetPopupPage = (data, sender) => {
 }
 
 export const setActionPopup = (data) => {
-    let { popup } = data.data || {};
-    if (popup) {
-        chrome.action.getPopup(
-            {},
-            function (result) {
-                if (!result) {
-                    chrome.action.setPopup({
-                        popup,
-                    }, function () {
-                    });
-                }
+    try {
+        let { popup } = data.data || {};
+        if (popup) {
+            chrome.action.getPopup(
+                {},
+                function (result) {
+                    if (!result) {
+                        chrome.action.setPopup({
+                            popup,
+                        }, function () {
+                        });
+                    }
+                });
+        } else {
+            chrome.action.setPopup({
+                popup: '',
+            }, function () {
             });
-    } else {
-        chrome.action.setPopup({
-            popup: '',
-        }, function () {
+        }
+    } catch (error) {
+        Report.reportLog({
+            objectType: Report.objectType.background_function_catch,
+            funcName: 'setActionPopup',
+            errMsg: error.message
         });
     }
 }

+ 2 - 2
src/manifest.json

@@ -2,8 +2,8 @@
     "manifest_version": 3,
     "name": "DeNet",
     "description": "Growing more twitter followers with Denet",
-    "version": "1.1.6",
-    "denet_app_version_code": "17",
+    "version": "1.1.6.1",
+    "denet_app_version_code": "18",
     "background": {
         "service_worker": "/js/background.js"
     },

+ 54 - 42
src/uilts/chromeExtension.js

@@ -29,33 +29,37 @@ export function setChromeStorage(params, callback) {
             chrome.storage.local.set(params)
         }
     } catch (error) {
-        console.error(error)
+        console.error('catch', error)
     }
 }
 
 export function getChromeStorage(key = '', callback) {
-    let params = {}
-    params[key] = ''
+    try {
+        let params = {}
+        params[key] = ''
+
+        if (!callback) {
+            return new Promise((resolve) => {
+                chrome.storage.local.get(params, (item) => {
+                    if (item[key]) {
+                        resolve(JSON.parse(item[key]))
+                    } else {
+                        resolve(null)
+                    }
+                });
+            })
+        }
 
-    if (!callback) {
-        return new Promise((resolve) => {
-            chrome.storage.local.get(params, (item) => {
-                if (item[key]) {
-                    resolve(JSON.parse(item[key]))
-                } else {
-                    resolve(null)
-                }
-            });
-        })
+        chrome.storage.local.get(params, (item) => {
+            if (item[key]) {
+                callback(JSON.parse(item[key]))
+            } else {
+                callback(null)
+            }
+        });
+    } catch (error) {
+        console.error('catch', error)
     }
-
-    chrome.storage.local.get(params, (item) => {
-        if (item[key]) {
-            callback(JSON.parse(item[key]))
-        } else {
-            callback(null)
-        }
-    });
 }
 
 // export function chromeSendMessage() {
@@ -69,12 +73,16 @@ export function setChromeCookie({
     name,
     url
 }, value_obj) {
-    chrome.cookies.set({
-        expirationDate: new Date().getTime() / 10,
-        name: name,
-        url: url,
-        value: encodeURIComponent(JSON.stringify(value_obj)) || ''
-    })
+    try {
+        chrome.cookies.set({
+            expirationDate: new Date().getTime() / 10,
+            name: name,
+            url: url,
+            value: encodeURIComponent(JSON.stringify(value_obj)) || ''
+        })
+    } catch (error) {
+        console.error('catch', error)
+    }
 }
 
 export function getChromeCookie({ name = '', url = '' }, callback) {
@@ -109,22 +117,26 @@ export function sendChromeTabMessage(params, callback) {
 }
 
 export function checkIsLogin(callback) {
-    return new Promise((resolve) => {
-        getChromeStorage('userInfo', (_userInfo) => {
-            if (!_userInfo) {
-                chrome.runtime.sendMessage(
-                    { actionType: "POPUP_LOGIN", data: "" },
-                    (response) => {
-                        console.log("res", response);
-                    }
-                )
-                callback && callback()
-                resolve(_userInfo)
-            } else {
-                resolve(_userInfo)
-            }
+    try {
+        return new Promise((resolve) => {
+            getChromeStorage('userInfo', (_userInfo) => {
+                if (!_userInfo) {
+                    chrome.runtime.sendMessage(
+                        { actionType: "POPUP_LOGIN", data: "" },
+                        (response) => {
+                            console.log("res", response);
+                        }
+                    )
+                    callback && callback()
+                    resolve(_userInfo)
+                } else {
+                    resolve(_userInfo)
+                }
+            })
         })
-    })
+    } catch (error) {
+        console.error('catch', error)
+    }
 }
 
 let callback_arr = []

+ 4 - 4
src/uilts/help.js

@@ -54,7 +54,7 @@ export function throttle(fn, thresh) {
 }
 
 export function setStorage(key, value) {
-  return localStorage.setItem(key, JSON.stringify(value));
+  return localStorage.setItem(key, JSON.stringify(value) || '');
 }
 
 export function getStorage(key) {
@@ -101,10 +101,10 @@ export function getBit(value) {
   }
 }
 
-export function getTargetElementWhenClick(e) { 
+export function getTargetElementWhenClick(e) {
   const { target, path } = e;
   let result = null;
-  if (Array.isArray(path) && path.length > 0) { 
+  if (Array.isArray(path) && path.length > 0) {
     result = path.find((item) => item.denetClickLogkey)
   }
   return result
@@ -241,7 +241,7 @@ export function checkURL(URL) {
 
 let $_data = []
 export function $(key, cache = true) {
-  if (!key || typeof(key) != 'string') {
+  if (!key || typeof (key) != 'string') {
     return null
   }
   // 不使用缓存

+ 263 - 3
src/view/iframe/buy-nft/buy/home.vue

@@ -19,7 +19,15 @@
                 <div class="limit" v-if="showDesc">Buy Limit: {{ state.data.userBuyCount || 0 }}/{{ state.data.perUserBuyLimit || 0 }}</div>
             </div>
             <div class="btn-area">
-                <template v-for="item in state.data.salePlans.splice(0, 2).reverse()">
+                <!-- 兑换码 -->
+                <template v-if="(state.data.perUserBuyLimit - state.data.userBuyCount) >= 1 && (state.data.itemTotalCount - state.data.itemSoldCount) >= 1">
+                    <div class="redeem" @click="showRedeemLayer">Redeem</div>
+                </template>
+                <template v-else>
+                    <div class="redeem grey">Redeem</div>
+                </template>
+
+                <template v-for="item in state.data.salePlans.slice(0, 2).reverse()">
                     <div class="buy1" @click="clickJump(item)" v-if="item.itemCount == 1 && (state.data.perUserBuyLimit - state.data.userBuyCount) >= 1
                     && (state.data.itemTotalCount - state.data.itemSoldCount) >= 1">
                         <template v-if="(item.price.length + item.currencyInfo.tokenSymbol.length) > 30">
@@ -77,16 +85,43 @@
             </div>
         </div>
     </div>
+
+    <!-- 兑换码弹出层 -->
+    <template v-if="showRedeem">
+        <div class="redeemLayer">
+            <div class="header">
+                <img :src="require('@/assets/svg/icon-close.svg')" @click="hideRedeemLayer" />
+            </div>
+            <div class="footer">
+                <div class="tips">Enter Redemption Code</div>
+                <div class="input"><input ref="refInput" type="text" v-model="redeemStr" /></div>
+                <div class="confirm">
+                    <button class="btn" @click="redeemPost" v-if="redeemNext">Confirm</button>
+                    <button class="btn grey" v-else>Confirm</button>
+                </div>
+            </div>
+        </div>
+        <div class="redeemMask"></div>
+    </template>
 </template>
 <script setup>
 import { useRouter } from 'vue-router'
-import { onMounted, reactive, inject, ref } from "vue";
-import { getNftMysteryBoxSaleInfo } from "@/http/nft";
+import { ElMessage } from 'element-plus'
+import { onMounted, reactive, inject, ref, nextTick, watchEffect } from "vue";
+import { getNftMysteryBoxSaleInfo, redeemNft } from "@/http/nft";
 import BtnLoading from '../components/btn-loading.vue'
+import Report from "@/log-center/log"
 import { getQueryString } from "@/uilts/help";
+import { sendChromeTabMessage } from '@/uilts/chromeExtension.js';
 let pay_info = inject('pay_info');
 let router = useRouter()
 let showDesc = ref(true)
+let showRedeem = ref(false)
+let redeemNext = ref(false)
+let redeemStr = ref('')
+let refInput = ref('')
+let groupId = ref('')
+let projectId = ref('')
 let dialogStyle = reactive({
     height: '800'
 })
@@ -131,6 +166,115 @@ const setDialogStyle = () => {
     }
 }
 
+const redeemPost = () => {
+    let params = {
+        redeemCode: redeemStr.value
+    }
+    if (projectId.value) {
+        params['nftProjectId'] = projectId.value
+    }
+    if (groupId.value) {
+        params['nftGroupId'] = groupId.value
+    }
+
+    // disabled btn
+    redeemNext.value = false
+
+    redeemNft({ params }).then(res => {
+        let { code, data } = res;
+        if (code == 0 && data) {
+            pay_info.buy_items = data
+            sendChromeTabMessage({ actionType: "FINISH_GROUP_BANNNER" }, () => { })
+            router.push({ path: '/open_box' });
+            // report
+            Report.reportLog({
+                pageSource: Report.pageSource.nftShopPage,
+                businessType: Report.businessType.buttonClick,
+                objectType: Report.objectType.redeem_button,
+                nftProjectId: projectId.value,
+            }, {
+                result: 'success'
+            })
+        } else {
+            let msg = ''
+            switch (res.code.toString()) {
+                case '5001':
+                    msg = 'nft project not exist'
+                    break;
+                case '5002':
+                    msg = 'nft project not available'
+                    break
+                case '5101':
+                    msg = 'nft sale plan not exist'
+                    break
+                case '5102':
+                    msg = 'nft sold out'
+                    break
+                case '5103':
+                    msg = 'Purchase limit reached'
+                    break
+                case '5104':
+                case '5105':
+                case '5106':
+                    msg = 'Invalid redemption code'
+                    break;
+                default:
+                    msg = 'Invalid redemption code, please try again'
+                    console.log(res.msg)
+            }
+            ElMessage({
+                message: msg,
+                type: 'warning'
+            })
+            redeemNext.value = true;
+            // report
+            Report.reportLog({
+                pageSource: Report.pageSource.nftShopPage,
+                businessType: Report.businessType.buttonClick,
+                objectType: Report.objectType.redeem_button,
+                nftProjectId: projectId.value,
+            }, {
+                result: 'fail'
+            })
+        }
+    }).catch(() => {
+        ElMessage({
+            message: 'Invalid redemption code, please try again',
+            type: 'warning'
+        })
+        redeemNext.value = true;
+    })
+}
+
+const showRedeemLayer = () => {
+    showRedeem.value = true;
+    nextTick(() => {
+        refInput.value.focus()
+    })
+    // report
+    Report.reportLog({
+        pageSource: Report.pageSource.nftShopPage,
+        businessType: Report.businessType.buttonClick,
+        objectType: Report.objectType.redeem_button,
+        nftProjectId: projectId.value,
+    })
+}
+
+const hideRedeemLayer = () => {
+    showRedeem.value = false;
+    redeemStr.value = '';
+}
+
+watchEffect(() => {
+    let len = 16
+    let str = redeemStr.value.replace(/[^a-zA-Z0-9]/g, '')
+        str = str.toUpperCase();
+        str = str.slice(0, len);
+    // set
+    redeemStr.value = str;
+    redeemNext.value = str !== '' && str.length === len;
+})
+
 onMounted(() => {
     setDialogStyle();
 
@@ -142,6 +286,11 @@ onMounted(() => {
     if (!nft_project_Id) {
         return
     }
+
+    // 作用域外用
+    groupId.value = nft_group_Id
+    projectId.value = nft_project_Id
+
     getNftMysteryBoxSaleInfo({
         params: {
             nftProjectId: nft_project_Id
@@ -151,6 +300,7 @@ onMounted(() => {
             state.data = res.data
             pay_info.home = res.data
             let { perUserBuyLimit, itemTotalCount } = res.data;
+            // 不限购
             if (perUserBuyLimit && itemTotalCount && perUserBuyLimit >= itemTotalCount) {
                 showDesc.value = false;
             }
@@ -160,6 +310,13 @@ onMounted(() => {
     }).catch(() => {
 
     })
+
+    // report
+    Report.reportLog({
+        pageSource: Report.pageSource.nftShopPage,
+        businessType: Report.businessType.pageView,
+        nftProjectId: nft_project_Id
+    })
 })
 </script>
 
@@ -323,7 +480,110 @@ onMounted(() => {
                 background: #CDCDCD;
                 cursor: not-allowed;
             }
+
+            .redeem {
+                border: 1px solid #1D9BF0;
+                background: rgba(29, 155, 240, 0.01);
+                border-radius: 100px;
+                color: #1D9BF0;
+                min-width: 110px;
+                display: flex;
+                justify-content: center;
+                align-items: center;
+                font-weight: 700;
+                font-size: 16px;
+                cursor: pointer;
+                margin-right: 12px;
+                box-sizing: border-box;
+                &.grey {
+                    background: #CDCDCD;
+                    cursor: not-allowed;
+                    color: #fff;
+                    border: unset;
+                }
+            }
+        }
+    }
+}
+
+.redeemLayer {
+    position: absolute;
+    z-index: 25;
+    top: 50%;
+    left: 50%;
+    width: 630px;
+    height: 270px;
+    border-radius: 20px;
+    background: #FFFFFF;
+    transform: translate(-50%, -50%);
+    .header {
+        display: flex;
+        align-items: center;
+        height: 48px;
+        box-shadow: 0px 0.5px 0px #D1D9DD;
+        img {
+            width: 24px;
+            height: 24px;
+            margin-left: 14px;
+            cursor: pointer;
+        }
+    }
+    .footer {
+        padding: 20px;
+        .tips {
+            font-size: 16px;
+            font-weight: 500;
+            line-height: 19px;
+            letter-spacing: 0.3px;
+            margin-bottom: 18px;
+        }
+        .input {
+            display: flex;
+            align-items: center;
+            justify-content: center;
+            height: 49px;
+            border-radius: 100px;
+            background: #FFFFFF;
+            border: 1px solid #DDDDDD;
+            input {
+                width: calc(100% - 40px);
+                border: 0;
+                outline: 0;
+                font-size: 16px;
+                font-weight: 500;
+                line-height: 19px;
+            }
+        }
+        .confirm {
+            margin-top: 45px;
+            text-align: right;
+            .btn {
+                border: 0;
+                width: 170px;
+                height: 51px;
+                cursor: pointer;
+                color: #FFFFFF;
+                font-size: 16px;
+                font-weight: 700;
+                border-radius: 100px;
+                background: #1D9BF0;
+                &.grey {
+                    background: #CDCDCD;
+                    cursor: not-allowed;
+                    color: #fff;
+                    border: unset;
+                }
+            }
         }
     }
 }
+.redeemMask {
+    position: absolute;
+    z-index: 24;
+    top: 0;
+    left: 0;
+    width: 100%;
+    height: 100%;
+    background-color: rgba($color: #000000, $alpha: .7);
+}
 </style>

+ 1 - 2
src/view/iframe/publish/tool-box/child/preview.vue

@@ -197,8 +197,7 @@ const publishHandler = () => {
     if (loadingHide) {
         return;
     }
-
-    if ((!appId || appId && !props.previewData.linkImagePath) && !props.screenshotWebsiteData.url) {
+    if ((!appId || appId && !props.previewData.linkImagePath) && (!props.screenshotWebsiteData.url || props.screenshotWebsiteData.status)) {
         loadingHide = message.loading('loading...', 0);
         return;
     }