Forráskód Böngészése

Merge branch 'test' into dev_220318_test

# Conflicts:
#	src/entry/background.js
#	src/logic/twitter.js
wenliming 3 éve
szülő
commit
6a07c4f72c

+ 14 - 1
src/entry/background.js

@@ -5,7 +5,8 @@ import {
     backTwitterPinLoginCode,
 } from "../logic/twitter.js";
 
-import { setChromeStorage, getChromeCookie } from "../uilts/chromeExtension";
+import { setChromeStorage, getChromeCookie, LANDING_PAGE, setChromeCookie, LANDING_PAGE_MIND } from "../uilts/chromeExtension";
+import { guid } from '../uilts/help.js'
 
 chrome.runtime.onInstalled.addListener(onInstalledMethod);
 
@@ -28,6 +29,18 @@ function onInstalledMethod() {
             backTwitterPinLoginToken();
         }
     })
+    getChromeCookie(LANDING_PAGE_MIND, (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) })
+        }
+    })
 }
 
 function onMessageMethod(req, sender, sendResponse) {

+ 8 - 0
src/http/request.js

@@ -3,6 +3,8 @@ import { getChromeStorage } from '../uilts/chromeExtension.js'
 
 let baseUrl = 'https://denettestapi.piaoquantv.com/denet';
 let userInfo = '';
+let storage_mid = ''
+
 // 创建axios实例
 export const service = axios.create({
   baseURL: baseUrl, // api的base_url
@@ -15,12 +17,14 @@ export const service = axios.create({
 
 function checkParams(config) {
   const { accessToken: token = '' } = userInfo || {};
+  const { mid } = storage_mid || {}
 
   if (config.method === 'get') {
     let { baseInfo = null } = config.params || {};
     if (!baseInfo || !baseInfo.token) {
       config['params']['baseInfo'] = {
         token: token,
+        mid
       }
     }
     let params = {
@@ -34,6 +38,7 @@ function checkParams(config) {
     if (!baseInfo || !baseInfo.token) {
       config['data']['baseInfo'] = {
         token: token,
+        mid
       }
     }
     let data = {
@@ -49,6 +54,9 @@ service.interceptors.request.use(async (config) => {
   if (!userInfo) {
     userInfo = await getChromeStorage('userInfo') || ''
   }
+  if (!storage_mid) {
+    storage_mid = await getChromeStorage('mid') || ''
+  }
   return checkParams(config)
 }, error => {
   // Do something with request error

+ 77 - 68
src/logic/twitter.js

@@ -89,7 +89,7 @@ export function renderDom(port) {
  */
 export function showGiveDialogHandler(userInfo) {
     let iframe = document.getElementById('iframe-content');
-    if(iframe) {
+    if (iframe) {
         iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', userInfo }, '*');
     } else {
         _addIframe();
@@ -112,24 +112,7 @@ export function hideIframeHandler() {
 export function showTwitterPublishDialogHandler(publishRes) {
     dom.tweetBtn.click();
     _setPublishContent(publishRes.srcContent);
-    _publishTweetEvent(publishRes.postId, (twitterArtId) => {
-        if (twitterArtId) {
-            getUserInfo((userInfo) => {
-                if (userInfo) {
-                    srcPublishSuccess({
-                        baseInfo: {
-                            token: userInfo.accessToken
-                        },
-                        params: {
-                            postId: publishRes.postId,
-                            srcContentId: twitterArtId
-                        }
-                    }).then(() => {
-                    })
-                }
-            })
-        }
-    });
+    _publishTweetEvent(publishRes.postId);
 }
 
 function getUserInfo(cb) {
@@ -138,6 +121,12 @@ function getUserInfo(cb) {
     })
 }
 
+// 绑定推文id所需参数
+let bindTwitterArt = {
+    needBind: false,
+    postId: '',
+    isBindIng: false
+};
 /**
  * 监听dialog内点击原生发布按钮事件
  * @private
@@ -146,11 +135,14 @@ function _publishTweetEvent(contentStr, cb) {
     setTimeout(() => {
         let publishTweetBtn = document.querySelector('div[role="dialog"]').querySelector('div[data-testid="tweetButton"]');
         publishTweetBtn.addEventListener('click', function () {
-            setTimeout(() => {
-                _getTwitterArtId(contentStr, (twitterArtId) => {
-                    cb && cb(twitterArtId)
-                });
-            }, 1500)
+            bindTwitterArt.needBind = true;
+            bindTwitterArt.postId = contentStr;
+            isSetContent = false;
+            // setTimeout(() => {
+            //     _getTwitterArtId(contentStr, (twitterArtId) => {
+            cb && cb()
+            //     });
+            // }, 1500)
         });
     }, 800)
 }
@@ -251,7 +243,8 @@ function _addIframe() {
  * @returns {string}
  * @private
  */
-function _getTwitterArtId(contentStr, cb) {
+
+/** function _getTwitterArtId(contentStr, cb) {
     let id = '';
 
     let timer = setInterval(() => {
@@ -276,6 +269,7 @@ function _getTwitterArtId(contentStr, cb) {
         }
     }, 1000);
 }
+*/
 
 /**
  * 点击deNet按钮处理
@@ -293,7 +287,7 @@ function _deNetBtnClick(port) {
             showGiveDialogHandler(res);
         } else {
             let loadIcon = document.getElementById('de-btn-loading');
-            if(loadIcon) {
+            if (loadIcon) {
                 return;
             }
             dom.deBtn.insertBefore(dom.loadingImg, dom.deBtn.querySelector('span'));
@@ -310,11 +304,16 @@ function _deNetBtnClick(port) {
  * @param content
  * @private
  */
+let isSetContent = false;
 function _setPublishContent(content) {
     setTimeout(() => {
         // document.execCommand('selectAll')
-        // document.execCommand("Delete","false",null); 
-        document.execCommand("insertText", false, content);
+        // document.execCommand("Delete","false",null);
+        if(!isSetContent) {
+            isSetContent = true;
+            document.execCommand("insertText", false, content);
+        }
+        
     }, 1000);
 }
 
@@ -375,8 +374,8 @@ function _createBtnDom(port) {
     dom.loadingImg = loadingImg;
 }
 
-function addSliderNavDeBtn (isSmall = false) {
-    if(!isSmall) {
+function addSliderNavDeBtn(isSmall = false) {
+    if (!isSmall) {
         let bigDom = document.querySelector('header[role="banner"]').querySelector('.r-1habvwh');
         if (bigDom) {
             bigDom.appendChild(dom.deBtn);
@@ -389,10 +388,10 @@ function addSliderNavDeBtn (isSmall = false) {
     }
 }
 
-function onWindowResize () {
-    window.onresize = throttle(function() {
+function onWindowResize() {
+    window.onresize = throttle(function () {
         try {
-            if(window.innerWidth < 1270) {
+            if (window.innerWidth < 1270) {
                 let bigBtn = document.querySelector('#de-btn');
                 bigBtn && bigBtn.remove();
                 setTimeout(() => {
@@ -411,7 +410,7 @@ function onWindowResize () {
     }, 800)
 }
 
-function checkHasDeBtn () {
+function checkHasDeBtn() {
     setInterval(() => {
         try {
             let toolBar = document.querySelector('div[data-testid="toolBar"]');
@@ -420,49 +419,57 @@ function checkHasDeBtn () {
                 let dialogScheduleBtn = _getScheduleDom(false);
                 _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn1);
             }
-        } catch(e) {
+        } 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 denet_arr = document.querySelector('article[data-testid=tweet]').querySelectorAll('a')
-    //     let _dom = null
-    //     for (let i in denet_arr) {
-    //         if (denet_arr[i].innerText == '#DeNet') {
-    //             _dom = denet_arr[i].parentNode.parentNode.parentNode.parentNode.children[1]
-    //             // 是否有有红包秘文
-    //         }
-    //     }
-
-    //     // 
-    //     denet_arr = document.querySelector('section').querySelectorAll('a')
-    //     for (let i in denet_arr) {
-    //         if (denet_arr[i].innerText == '#DeNet') {
-    //             _dom = denet_arr[i].parentNode
-    //             // 是否有有红包秘文
-    //         }
-    //     }
-    //     return _dom
+    let _dom = null
     let arr = document.querySelectorAll('a') || []
 
-    arr.forEach((item) => {
-        if (item.innerText == '#DeNet') {
-            if (item.parentNode && item.parentNode.parentNode && item.parentNode.parentNode.innerText.length > 5) {
-                let _postId = item.parentNode.parentNode.innerText || ''
-                _postId = _postId.match(/###([\s\S]*?)###/)[1];
-                let _dom = item.parentNode.parentNode.parentNode.parentNode.parentNode
-                let _tweetId = _dom.children[0].querySelector('a[dir="auto"]').getAttribute('href').split('/status/')[1];
-                replaceDOMRedPacket(_dom.children[1], _postId,_tweetId)
+    for (let i in arr) {
+        if (arr[i].innerText == '#DeNet') {
+            let _article = arr[i].closest('article')
+            let _postId = _article.querySelector('[lang]').innerText
+            _postId = _postId.match(/###([\s\S]*?)###/)[1]
+            _dom = _article.querySelector('[aria-labelledby]')
+            let _tweetId = _article.querySelector('a[aria-label]').getAttribute('href').split('/status/')[1]
+
+            if(bindTwitterArt.needBind) {
+                bindTwitterArtMethod({postId: _postId, twitterId: _tweetId});
             }
-            
+            replaceDOMRedPacket(_dom, _postId, _tweetId)
         }
-    })
+    }
 }
 
-function replaceDOMRedPacket(_dom, postId,tweetId) {
+function replaceDOMRedPacket(_dom, postId, tweetId) {
     if (!_dom || _dom.querySelector('iframe')) {
         return
     }
@@ -483,9 +490,11 @@ function replaceDOMRedPacket(_dom, postId,tweetId) {
 export function setIframeRedPacket() {
     // let elment = document.documentElement
 
-    // if(window.location.href != 'https://twitter.com/home'){
-    //     return
-    // }
+    if(window.location.href.includes('https://twitter.com)')){
+        return
+    }
+    // const observer = new MutationObserver(callback);
+
     parseDOMRedPacket()
     // let _current_top = 0
     setInterval(() => {

+ 11 - 6
src/manifest.development.json

@@ -6,13 +6,18 @@
     "background": {
         "service_worker": "/js/background.js"
     },
+    "icons": {
+        "16": "/logo/16.png",
+        "48": "/logo/48.png",
+        "128": "/logo/128.png"
+    },
     "action": {
-        "default_popup": "popup.html",
-        "default_icon": {           
-            "16": "/logo/16.png",  
-            "48": "/logo/48.png",  
-            "128": "/logo/128.png"   
-          }
+        "default_popup": "popup.html"
+        // "default_icon": {
+        //     "16": "/logo/16.png",
+        //     "48": "/logo/48.png",
+        //     "128": "/logo/128.png"
+        // }
     },
     "content_scripts": [
         {

+ 20 - 11
src/manifest.production.json

@@ -6,8 +6,18 @@
     "background": {
         "service_worker": "/js/background.js"
     },
+    "icons": {
+        "16": "/logo/16.png",
+        "48": "/logo/48.png",
+        "128": "/logo/128.png"
+    },
     "action": {
         "default_popup": "popup.html"
+        // "default_icon": {
+        //     "16": "/logo/16.png",
+        //     "48": "/logo/48.png",
+        //     "128": "/logo/128.png"
+        // }
     },
     "content_scripts": [
         {
@@ -23,8 +33,8 @@
     "host_permissions": [
         "*://*/*",
         "https://de-net-test.piaoquantv.com"
-      ],
-    "permissions":[
+    ],
+    "permissions": [
         "tabs",
         "action",
         "cookies",
@@ -37,14 +47,13 @@
     "options_page": "options.html",
     "web_accessible_resources": [
         {
-          "resources": [
-            "/iframe/publish.html",
-            "/iframe/red-packet.html"
-          ],
-          "matches": [
-            "<all_urls>"
-          ]
+            "resources": [
+                "/iframe/publish.html",
+                "/iframe/red-packet.html"
+            ],
+            "matches": [
+                "<all_urls>"
+            ]
         }
-
     ]
-}
+}

+ 17 - 1
src/uilts/chromeExtension.js

@@ -1,6 +1,11 @@
 export const LANDING_PAGE = {
     name: 'received_log',
-    url: 'https://de-net-test.piaoquantv.com'
+    url: 'http://localhost:3000'
+}
+
+export const LANDING_PAGE_MIND = {
+    name: 'mid',
+    url: 'http://localhost:3000'
 }
 
 export function setChromeStorage(params) {
@@ -32,6 +37,17 @@ export function getChromeStorage(key = '', callback) {
     });
 }
 
+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)) || ''
+    })
+}
 
 export function getChromeCookie({
     name,

+ 37 - 30
src/uilts/help.js

@@ -1,24 +1,24 @@
 export function getQueryString(name) {
-    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i")
-    let r = window.location.search.substr(1).match(reg)
-    if (r != null) {
-        return window.decodeURIComponent(r[2])
-    }
-    return null
- }
+  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i")
+  let r = window.location.search.substr(1).match(reg)
+  if (r != null) {
+    return window.decodeURIComponent(r[2])
+  }
+  return null
+}
 
- export function debounce(fn,delay){
-    let timer; // 定时器
-    return function(...args){ // 形成闭包
-      // args 为函数调用时传的参数。
-      let context = this;
-      timer&&clearTimeout(timer); // 当函数再次执行时,清除定时器,重新开始计时
-      // 利用定时器,让指定函数延迟执行。
-      timer = setTimeout(function(){
-        // 执行传入的指定函数,利用apply更改this绑定和传参
-        fn.apply(context,args);
-      },delay)
-    }
+export function debounce(fn, delay) {
+  let timer; // 定时器
+  return function (...args) { // 形成闭包
+    // args 为函数调用时传的参数。
+    let context = this;
+    timer && clearTimeout(timer); // 当函数再次执行时,清除定时器,重新开始计时
+    // 利用定时器,让指定函数延迟执行。
+    timer = setTimeout(function () {
+      // 执行传入的指定函数,利用apply更改this绑定和传参
+      fn.apply(context, args);
+    }, delay)
+  }
 }
 
 export function throttle(fn, thresh) {
@@ -30,27 +30,34 @@ export function throttle(fn, thresh) {
     var context = this, args = arguments, curr = new Date() - 0
 
     clearTimeout(timeout)//总是干掉事件回调
-    if(curr - start >= threshhold){
+    if (curr - start >= threshhold) {
       fn.apply(context, args) //只执行一部分方法,这些方法是在某个时间段内执行一次
       start = curr
-    }else{
+    } else {
       // 让方法在脱离事件后也能执行一次
-      timeout = setTimeout(function(){
+      timeout = setTimeout(function () {
         fn.apply(context, args)
       }, threshhold);
     }
   }
 }
-  
+
 export function setStorage(key, value) {
-    return localStorage.setItem(key, JSON.stringify(value));
+  return localStorage.setItem(key, JSON.stringify(value));
 }
 
 export function getStorage(key) {
-    const item = localStorage.getItem(key);
-    try {
-        return item ? JSON.parse(item) : '';
-    } catch (e) {
-        return item;
-    }
+  const item = localStorage.getItem(key);
+  try {
+    return item ? JSON.parse(item) : '';
+  } catch (e) {
+    return item;
+  }
+}
+
+export function guid() {
+  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
+    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
+    return v.toString(16);
+  });
 }

+ 47 - 50
src/view/red-packet.vue

@@ -50,7 +50,7 @@
         </div>
       </div>
       <div class="people" @click="clickRoad">
-        <div class="txt">Total ${{ data.detail.amountValue }} USD,{{ data.detail.finishCount || 0 }}/{{
+        <div class="txt">Total ${{ data.detail.amountValue }} USD,{{ data.detail.receiveCount || 0 }}/{{
           data.detail.totalCount || 0
         }} People Got</div>
         <div class="right">
@@ -85,7 +85,7 @@
         </div>
       </div>
       <div class="luck-list-title">
-        <div>{{ data.detail.finishCount || 0 }}/{{ data.detail.totalCount || 0 }} People Got</div>
+        <div>{{ data.detail.receiveCount || 0 }}/{{ data.detail.totalCount || 0 }} People Got</div>
         <div>Total ${{ data.detail.amountValue || '' }} {{ data.detail.amountCurrencyCode || '' }}</div>
       </div>
       <div class="luck-list" @scroll="handleScroll($event)">
@@ -121,7 +121,7 @@
         <img :src="require('../assets/svg/icon-back.svg')" alt @click="clickBack" />
       </div>
       <div class="luck-list-title">
-        <div>{{ data.detail.finishCount || 0 }}/{{ data.detail.totalCount || 0 }} People Got</div>
+        <div>{{ data.detail.receiveCount || 0 }}/{{ data.detail.totalCount || 0 }} People Got</div>
         <div>Total ${{ data.detail.amountValue || 0 }} {{ data.detail.amountCurrencyCode || '' }}</div>
       </div>
       <div class="luck-list" @scroll="handleScroll">
@@ -152,7 +152,7 @@
         <div class="close-title">{{ data.close_title }}</div>
       </div>
       <div class="luck-list-title">
-        <div>{{ data.detail.finishCount || 0 }}/{{ data.detail.totalCount || 0 }} People Got</div>
+        <div>{{ data.detail.receiveCount || 0 }}/{{ data.detail.totalCount || 0 }} People Got</div>
         <div>Total ${{ data.detail.amountValue || 0 }} {{ data.detail.amountCurrencyCode || '' }}</div>
       </div>
       <div class="luck-list" @scroll="handleScroll">
@@ -196,11 +196,10 @@ export default {
 }
 </script>
 <script setup>
-/* eslint-disable */
 import { onMounted, reactive } from "vue";
 import { getPostDetail, getRedPacket, finishRedPacket, oneKeyLike, oneKeyReTweet, oneKeyFollow, getTaskDetail, getReceivedList } from '../http/redPacket.js'
 import { getQueryString } from '../uilts/help.js'
-import { getChromeCookie, concatChromeCookie, getChromeStorage, LANDING_PAGE } from '../uilts/chromeExtension.js'
+import { getChromeStorage } from '../uilts/chromeExtension.js'
 var moment = require('moment');
 
 let data = reactive({
@@ -304,13 +303,20 @@ async function clickRetweetBtn() {
 
 
 function getValidity() {
-  let _d1,_d2
+  let _d1, _d2, _d3, _h, _m, _s
+  if(!data.detail.myReceived.taskEndTimestamp){
+    return
+  }
   let timer = setInterval(() => {
     let _time = new Date().getTime()
-    if (data.detail.endTimestamp - _time > 0) {
-      _d1= moment(data.detail.endTimestamp)
+    _d3 = data.detail.myReceived.taskEndTimestamp - _time
+    if (_d3 > 0) {
+      _d1 = moment(data.detail.myReceived.taskEndTimestamp)
       _d2 = moment(_time)
-      data.detail.validity = moment(_d1.diff(_d2)).format('HH:mm:ss')
+      _h = moment.duration(_d1.diff(_d2)).hours()
+      _m = moment.duration(_d1.diff(_d2)).minutes()
+      _s = moment.duration(_d1.diff(_d2)).seconds()
+      data.detail.validity = `${_h}:${_m}:${_s}`
     } else {
       clearInterval(timer)
     }
@@ -406,21 +412,11 @@ function init() {
               data.close_title = res.msg
             }
           } else {
-            // 判断本地之前是否领取过这个红包
-            getChromeCookie(LANDING_PAGE, (res_arr) => {
-              if (res_arr.length > 0) {
-                let _res = res_arr.filter((item) => { return item.postId == data.postId })[0] || null
-                // 本地领取过红包
-                if (_res) {
-                  data.status = 'opened'
-                  data.money = _res.receiveAmount
-                } else {
-                  data.status = 'not-open'
-                }
-              } else {
-                data.status = 'not-open'
-              }
-            })
+            if (data.detail.myReceived) {
+              data.status = 'opened'
+            } else {
+              data.status = 'not-open'
+            }
           }
           data.detail.taskCondition = JSON.parse(data.detail.taskCondition)
           data.detail.amountValue = showLastTwoPlace(data.detail.amountValue)
@@ -450,7 +446,7 @@ function init() {
         switch (res.data[i].type) {
           case 1:
             data.done.follow = res.data[i].finished
-            data.detail.taskCondition[0].relatedUsers = res.data[i].detail
+            // data.detail.taskCondition[0].relatedUsers = res.data[i].detail
             break
           case 2:
             data.done.like = res.data[i].finished
@@ -474,26 +470,29 @@ onMounted(() => {
 
 // 点击领取
 function clickOpenRedPacket() {
-  getChromeStorage("userInfo", (_res) => {
-    // 1.没有登陆
-    if (!_res) {
-      // 2.查看cookie里是否有  
-      getChromeCookie(LANDING_PAGE, (res_arr) => {
-        // 
-        if (res_arr.length > 0) {
-          let _res = res_arr.filter((item) => { return item.postId == data.postId })[0] || null
-          if (_res) {
-            data.status = 'opened'
-            data.money = _res.receiveAmount
-          }
-        } else {
-          handleRedPacket()
-        }
-      })
-    } else {
-      handleRedPacket()
-    }
-  })
+  // getChromeStorage("userInfo", (_res) => {
+  //   // 1.没有登陆
+  //   if (!_res) {
+  //     // 2.查看cookie里是否有  
+  //     getChromeCookie(LANDING_PAGE, (res_arr) => {
+  //       // 
+  //       // if (res_arr.length > 0) {
+  //       //   let _res = res_arr.filter((item) => { return item.postId == data.postId })[0] || null
+  //       //   if (_res) {
+  //       //     data.status = 'opened'
+  //       //     data.money = _res.receiveAmount
+  //       //   }
+  //       // } else {
+
+  //       // }
+  //       // handleRedPacket()
+  //     })
+  //   } else {
+  //     handleRedPacket()
+  //   }
+  // })
+  handleRedPacket()
+
 }
 
 function handleRedPacket() {
@@ -502,12 +501,10 @@ function handleRedPacket() {
       postId: data.postId
     }
   }).then((res) => {
-
     switch (res.code.toString()) {
       case "0":
         data.status = 'opened'
         data.money = res.data.receiveAmount
-        concatChromeCookie(LANDING_PAGE, { receivedId: res.data.receivedId, postId: data.postId, receiveAmount: res.data.receiveAmount })
         init()
         break
       case "2008":
@@ -527,7 +524,7 @@ chrome.storage.onChanged.addListener(changes => {
 
 // 校验是否封路
 function checkIsLogin() {
-  
+
   return new Promise((resolve) => {
     getChromeStorage('userInfo', (_userInfo) => {
       if (!_userInfo) {
@@ -539,7 +536,7 @@ function checkIsLogin() {
           }
         )
         resolve(_userInfo)
-      }else{
+      } else {
         resolve(_userInfo)
       }
     })