import { getChromeStorage, setChromeStorage } from '@/uilts/chromeExtension.js'
import { throttle, getQueryString, getCookie, nextTick } from '@/uilts/help'
import { discordAuthRedirectUri } from '@/http/configAPI'
import { reportSrcPublishEvent } from '@/http/publishApi'
import Report from "@/log-center/log"
import { fetchAddFinishEvent } from '@/logic/background/fetch/facebook';
let dom = {};
function twitterPinLogin() {
if (window.location.href == 'https://api.twitter.com/oauth/authorize') {
let code = document.querySelector('code')
if (code) {
chrome.runtime.sendMessage({ actionType: "CONTENT_SEND_CODE", code: code.innerText }, () => { })
// port.postMessage({ state: 'CONTENT_SEND_CODE', code: code.innerText })
}
}
}
function getDiscordAuthCode() {
if (window.location.href.indexOf(discordAuthRedirectUri) > -1) {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
if (code) {
chrome.runtime.sendMessage({ actionType: "CONTENT_SEND_DISCORD_AUTH_CODE", code }, () => { })
}
}
};
/**
* 渲染要插入的dom,初始化逻辑
* @param port
*/
function renderDom() {
if (window.location.href.indexOf('https://twitter.com') > -1) {
_createBtnDom();
onWindowResize();
checkHasDeBtn();
setTimeout(() => {
_addIframe();
_addDeNetBtn();
_getSliderTwitterBtn();
}, 800)
}
}
/**
* 展示give弹窗
*/
export function showGiveDialogHandler(userInfo) {
let iframe = document.getElementById('iframe-content');
if (iframe) {
iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', userInfo }, '*');
} else {
_addIframe();
let iframe = document.getElementById('iframe-content');
iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', userInfo }, '*');
}
}
export function showIframeHandler() {
document.getElementById('iframe-content').style.display = 'block';
}
export function hideIframeHandler() {
document.getElementById('iframe-content').style.display = 'none';
}
/**
* 展示twitter原生发布框
*/
let tweetPublishStore = {
showPublishDialog: false
}
export function showTwitterPublishDialogHandler(publishRes) {
let bigBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
if (bigBtn) {
bigBtn.click();
tweetPublishStore.showPublishDialog = true;
} else {
let smallBtn = document.querySelector('a[href="/compose/tweet"]')
smallBtn && smallBtn.click();
tweetPublishStore.showPublishDialog = true;
}
setChromeStorage({ publishData: JSON.stringify(publishRes) })
addPublishTipsIframe({
srcContent: publishRes.copyContent
})
_setPublishContent(publishRes.srcContent);
_publishTweetEvent(publishRes, bindTwitterArtMethod);
}
export function twitterPublishHandler(res) {
let bigBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
if (bigBtn) {
bigBtn.click();
} else {
let smallBtn = document.querySelector('a[href="/compose/tweet"]')
smallBtn && smallBtn.click();
}
nextTick(() => {
document.execCommand('selectAll');
}, 100).then(() => {
_setPublishContent(res.srcContent, 500);
})
}
export function showPinTips() {
hidePopupPage();
hideNoticeBindTweet();
getChromeStorage('pinData', (res) => {
if (!res || res.show) {
let domPop = document.getElementById('de-pin-pop');
domPop.style.display = 'block';
}
})
}
export function hidePinTips() {
let pop = document.querySelector('#de-pin-pop');
if (pop) {
pop.style.display = 'none';
}
}
function addPinedPop() {
let domPop = document.getElementById('de-pin-pop');
if (domPop) {
return;
}
let popWrapper = document.createElement('div');
popWrapper.style.cssText = 'position: fixed; height: 400px;width: 300px;top: 12px;right: 20px;border-radius: 12px;border: 0.5px solid #919191;box-sizing: border-box;padding: 20px;background: #fff;display:none';
popWrapper.id = 'de-pin-pop'
let img = document.createElement('img');
img.src = require("@/assets/img/img-pined-guide.png");
img.width = 253;
let contentDom = document.createElement('div');
contentDom.innerHTML = "
📌 Pin an Extension is more convenient to open😄
"
popWrapper.appendChild(img);
popWrapper.appendChild(contentDom);
document.querySelector('body').appendChild(popWrapper);
let deCheck = document.querySelector('#de-check');
let deRemind = document.querySelector('#de-remind');
deCheck.onclick = function (e) {
e && e.stopPropagation && e.stopPropagation();
setChromeStorage({ pinData: JSON.stringify({ show: !this.checked }) })
}
deRemind.onclick = function () {
deCheck.checked = !deCheck.checked;
setChromeStorage({ pinData: JSON.stringify({ show: !deCheck.checked }) })
}
document.querySelector('.de-pin-skip').onclick = function () {
document.querySelector('#de-pin-pop').style.display = 'none';
}
}
function getUserInfo(cb) {
getChromeStorage('userInfo', (res) => {
cb && cb(res);
})
}
// 绑定推文id所需参数
let bindTwitterArt = {
needBind: false,
postId: '',
isBindIng: false
};
/**
* 监听dialog内点击原生发布按钮事件
* @private
*/
function _publishTweetEvent(params, cb) {
setTimeout(() => {
let publishTweetBtn;
let dialog = document.querySelector('div[role="dialog"]');
if (dialog) {
publishTweetBtn = dialog.querySelector('div[data-testid="tweetButton"]');
onClosePublishDialogHandle(dialog, params)
} else {
let domMain = document.querySelector('main[role="main"]');
publishTweetBtn = domMain && domMain.querySelector('div[data-testid="tweetButton"]');
}
publishTweetBtn && publishTweetBtn.addEventListener('click', function () {
bindTwitterArt.needBind = true;
bindTwitterArt.postId = params.postId;
tweetPublishStore.showPublishDialog = false;
// checkIsShowReSend(dialog, params);
cb && cb()
});
}, 800)
}
function onClosePublishDialogHandle(dom, params) {
dom.querySelector('div[role="group"]').addEventListener('click', function () {
setTimeout(() => {
let parent = document.querySelector('div[data-testid="confirmationSheetDialog"]');
if (parent) {
let btnArr = parent.querySelectorAll('div[role=button]')
for (let i = 0; i < btnArr.length; i++) {
let btn = btnArr[i];
btn.addEventListener('click', function () {
tweetPublishStore.showPublishDialog = false;
let taskLuckdropId = JSON.parse(params.postBizData).taskLuckdropId;
noticeBindTweet({ postId: params.postId, taskLuckdropId });
})
}
} else {
setTimeout(() => {
let dialog = document.querySelector('div[role="dialog"]');
if (!dialog) {
tweetPublishStore.showPublishDialog = false;
}
}, 800)
}
}, 1000)
})
}
function checkIsShowReSend(dom, params) {
let str = dom.querySelector('div[data-contents="true"]').innerHTML;
if (str.indexOf(params.postId) < 0) {
let taskLuckdropId = JSON.parse(params.postBizData).taskLuckdropId;
noticeBindTweet({ postId: params.postId, taskLuckdropId });
}
}
/**
* 在输入推文区插入deNet按钮
* @param parent
* @param dom
* @param isClick
* @private
*/
function _addDeNetEditBtn(parent, dom, isClick = false) {
setTimeout(() => {
if (parent && parent.parentNode) {
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonView,
objectType: Report.objectType.buttonSecond
});
parent.parentNode.insertBefore(dom, parent.nextElementSibling);
} else {
setTimeout(() => {
parent = _getScheduleDom(isClick);
if (parent && parent.parentNode) {
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonView,
objectType: Report.objectType.buttonSecond
});
let innerDeIcon = document.getElementById('de-btn1');
if (!innerDeIcon) {
parent.parentNode.insertBefore(dom, parent.nextElementSibling);
}
}
}, 1000)
}
})
}
/**
* 在dialog插入deNet按钮
* @private
*/
// function _addDeNetBtnToDialog() {
// setTimeout(() => {
// let dialogScheduleBtn = _getScheduleDom(true);
// _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn2);
// }, 800)
// }
/**
* 获取左侧twitter按钮
* @private
*/
function _getSliderTwitterBtn() {
dom.tweetBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
dom.tweetBtn.addEventListener('click', function () {
// _addDeNetBtnToDialog();
})
}
/**
* 添加deNet按钮
* @private
*/
function _addDeNetBtn() {
setTimeout(() => {
let navWidth = document.querySelector('nav[role="navigation"]').offsetWidth;
addSliderNavDeBtn(navWidth < 245);
let innerDeIcon = document.getElementById('de-btn1');
if (!innerDeIcon) {
let dialogScheduleBtn = _getScheduleDom(false);
_addDeNetEditBtn(dialogScheduleBtn, dom.deBtn1);
}
}, 800)
}
/**
* 获取推文输入框内dom,用于插入deNet
* @param isDialogInner
* @returns {Element}
* @private
*/
function _getScheduleDom(isDialogInner = false) {
let scheduleBtn;
if (isDialogInner) {
scheduleBtn = document.querySelector('div[role="dialog"]').querySelector('[data-testid="createPollButton"]');
} else {
let toolBar = document.querySelector('div[data-testid="toolBar"]');
if (toolBar) {
scheduleBtn = toolBar.querySelector('div[data-testid="geoButton"]');
}
}
return scheduleBtn;
}
/**
* 插入iframe到页面
* @private
*/
function _addIframe() {
// let span = document.createElement('span');
// const shadowRoot = span.attachShadow({mode: 'closed'})
let iframe = document.createElement('iframe');
iframe.src = chrome.runtime.getURL('/iframe/publish.html')
iframe.id = 'iframe-content'
iframe.style.cssText = 'position:fixed;top:0px;right:0;display:block; width:100%;height:100%;z-index:10000; border: medium none;display:none';
// shadowRoot.appendChild(iframe);
// document.body.appendChild(span)
dom.iframe = iframe;
let iframeContent = document.getElementById('iframe-content');
if (!iframeContent) {
document.querySelector('body').appendChild(iframe);
}
}
function addPublishTipsIframe(params = {}) {
let { time = 1000 } = params;
setTimeout(() => {
let dialog = document.querySelector('div[role="dialog"]').querySelector('div[role="dialog"]')
if (dialog) {
let right = dialog.offsetLeft - 15 - 266;
let iframe = document.createElement('iframe');
iframe.id = 'de-publish-tips'
iframe.src = chrome.runtime.getURL('/iframe/publish-tips.html');
iframe.style.cssText = `border: medium none; width:270px;height:500px;position: fixed; right: ${right}px; top: 5%;z-index: -1`
let iframeContent = document.getElementById('de-publish-tips');
if (!iframeContent) {
dialog.appendChild(iframe)
}
}
}, time)
}
export function noticeBindTweet(params) {
hidePinTips();
hidePopupPage();
let iframe = document.createElement('iframe');
iframe.id = 'de-notice-bind-tweet';
iframe.src = chrome.runtime.getURL('/iframe/bind-tweet.html') + `?params=${JSON.stringify(params)}`;
iframe.style.cssText = `border: medium none; width:400px;min-height:313px;position: fixed; right: 16px; top: 16px;`
let iframeContent = document.getElementById('de-notice-bind-tweet');
if (!iframeContent) {
document.querySelector('body').appendChild(iframe)
}
}
export function hideNoticeBindTweet() {
let iframeContent = document.getElementById('de-notice-bind-tweet');
if (iframeContent) {
document.querySelector('body').removeChild(iframeContent)
}
}
/**
* 点击deNet按钮处理
* @private
*/
function _deNetBtnClick() {
getUserInfo((res) => {
if (res) {
if (window.location.pathname != '/home') {
if (!dom.homeBtn) {
dom.homeBtn = document.querySelector('a[data-testid="AppTabBar_Home_Link"]');
}
dom.homeBtn.click();
}
showGiveDialogHandler(res);
} else {
let loadIcon = document.getElementById('de-btn-loading');
if (loadIcon) {
return;
}
dom.deBtn.insertBefore(dom.loadingImg, dom.deBtn.querySelector('span'));
setTimeout(() => {
dom.loadingImg.style.transform = 'rotate(1080deg)'
});
setTimeout(() => {
dom.loadingImg.style.transform = 'rotate(0deg)'
dom.deBtn.innerHTML = 'DeNet';
}, 2000)
chrome.runtime.sendMessage({ actionType: "CONTENT_TWITTER_LOGIN", data: '1' }, (res) => { console.log(res) })
}
})
}
/**
* 设置发布内容
* @param content
* @private
*/
let isSetContent = false;
const _setPublishContent = throttle(function (content, time = 1000) {
if (!isSetContent) {
isSetContent = true;
let inputEle = document.querySelector('div[contenteditable="true"]');
if (inputEle) {
inputEle.focus();
}
setTimeout(() => {
document.execCommand("insertText", false, content);
setTimeout(() => {
isSetContent = false;
}, 2000)
}, time);
}
}, 800);
/**
* 创建deNet按钮 添加到页面
* @returns {{deBtn2: HTMLDivElement, deBtn1: HTMLDivElement, deBtn: HTMLSpanElement}}
* @private
*/
function _createBtnDom() {
let loadingImg = document.createElement('img');
loadingImg.id = 'de-btn-loading'
loadingImg.src = require("@/assets/img/icon-btn-loading.png");
loadingImg.style.cssText = 'width:20px;height: 20px;margin-right:3px;transition-duration: 3s;';
let style = document.createElement('style');
style.innerHTML = "#de-btn:hover{opacity: .9;};@-webkit-keyframes load{from{ transform: rotate(0deg);} to{transform: rotate(360deg);}}";
document.getElementsByTagName('head').item(0).appendChild(style);
// 左侧大屏按钮
let deBtn = document.createElement('span');
// const shadowDiv = document.createElement('div');
deBtn.innerHTML = 'DeNet';
deBtn.id = 'de-btn';
deBtn.style.cssText = 'width:90%;height: 52px;text-align:center;line-height:52px;margin-bottom: 4px;margin-top: 4px;background: linear-gradient(274.8deg, #FF9900 -3.69%, #BD00FF 69.71%, #00F0FF 122.65%);color:#fff;font-size:17px;font-weight:700;border-radius:100px;cursor: pointer;display: flex;align-items: center;justify-content: center;';
// 编辑框内按钮
const deBtn1 = document.createElement('img');
let src = require("@/assets/img/icon-gift-pack.png");
const smallDeBtnStyle = 'width:20px;height: 20px;cursor: pointer;padding: 0px 8px';
deBtn1.id = 'de-btn1';
deBtn1.style.cssText = smallDeBtnStyle;
deBtn1.src = src
const deBtn2 = document.createElement('div');
deBtn2.id = 'de-btn2';
deBtn2.style.cssText = smallDeBtnStyle;
deBtn2.src = "@/assets/img/icon-gift-pack.png"
// 小屏按钮
const deBtn3 = document.createElement('img');
deBtn3.id = 'de-btn3'
deBtn3.src = require("@/assets/logo/128.png");
deBtn3.style.cssText = 'width:52px;height: 52px;margin-top:20px;cursor: pointer;';
deBtn.addEventListener('click', () => {
// chrome.runtime.sendMessage({
// actionType: 'CONTENT_SET_BADGE',
// data: {
// text: '2'
// }
// }, res => {
// console.log(res);
// })
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.buttonMain
});
_deNetBtnClick();
})
deBtn1.addEventListener('click', () => {
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.buttonSecond
});
_deNetBtnClick();
})
deBtn2.addEventListener('click', () => {
_deNetBtnClick();
})
deBtn3.addEventListener('click', () => {
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.buttonMain
});
_deNetBtnClick();
})
dom.deBtn = deBtn;
dom.deBtn1 = deBtn1;
dom.deBtn2 = deBtn2;
dom.deBtn3 = deBtn3;
dom.loadingImg = loadingImg;
}
function addSliderNavDeBtn(isSmall = false) {
if (!isSmall) {
let bigDom = document.querySelector('a[href="/compose/tweet"]').parentNode.parentNode;
let deBtn = document.getElementById('de-btn');
if (bigDom && !deBtn) {
bigDom.appendChild(dom.deBtn);
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonView,
objectType: Report.objectType.buttonMain
});
}
} else {
let smallDom = document.querySelector('a[href="/compose/tweet"]').parentNode.parentNode;
let deBtn3 = document.getElementById('de-btn3');
if (smallDom && !deBtn3) {
smallDom.appendChild(dom.deBtn3);
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonView,
objectType: Report.objectType.buttonMain
});
}
}
}
function onWindowResize() {
window.onresize = throttle(function () {
try {
if (tweetPublishStore.showPublishDialog) {
let dialog = document.querySelector('div[role="dialog"]');
let dePublishTips = document.getElementById('de-publish-tips');
if (dialog && !dePublishTips) {
addPublishTipsIframe({ time: 0 });
} else if (dialog && dePublishTips) {
let dialogContent = dialog.querySelector('div[role=dialog]')
if (dialogContent) {
let right = dialogContent.offsetLeft - 15 - 266;
dePublishTips.style.right = right + 'px';
}
}
}
if (window.innerWidth < 1273) {
let bigBtn = document.querySelector('#de-btn');
bigBtn && bigBtn.remove();
setTimeout(() => {
addSliderNavDeBtn(true);
})
} else {
let smallBtn = document.querySelector('#de-btn3');
smallBtn && smallBtn.remove();
setTimeout(() => {
addSliderNavDeBtn()
})
}
} catch (e) {
console.log(e)
}
}, 800)
}
function checkHasDeBtn() {
try {
let toolBar = document.querySelector('div[data-testid="toolBar"]');
let innerDeIcon = document.getElementById('de-btn1');
if (toolBar && !innerDeIcon) {
let dialogScheduleBtn = _getScheduleDom(false);
_addDeNetEditBtn(dialogScheduleBtn, dom.deBtn1);
}
} catch (e) {
console.log(e)
}
}
/**
* 点击发推,后端绑定推特id
*/
function bindTwitterArtMethod() {
if (!bindTwitterArt.postId) {
return
}
if (bindTwitterArt.needBind && !bindTwitterArt.isBindIng) {
bindTwitterArt.isBindIng = true;
reportSrcPublishEvent({
params: {
postId: bindTwitterArt.postId,
}
}).then((res) => {
if (res.code == 0) {
Report.reportLog({
objectType: Report.objectType.tweetPostBinded
});
bindTwitterArt.needBind = false;
bindTwitterArt.postId = '';
bindTwitterArt.isBindIng = false;
}
})
}
}
import parseCard from './ParseCard'
// 检测dom改变
// 获取短链接
// 查看本地是否有postid
// 如果有 修改dom 返回
// 如果没有 网络请求
// 获取postid
// 获取twitterid
// 检测当前所有dom 如果没有
let queue_num = 1
export const changeQueueNum = (num = 0) => {
queue_num = queue_num + num
if (queue_num > 5) {
queue_num = 5
}
}
let main_observer = null
function onChangePageMain(targetNode) {
try {
const config = { attributes: false, childList: true, subtree: true };
const callback = (mutationsList, observer) => {
changeQueueNum(1)
}
main_observer = new MutationObserver(callback);
main_observer.observe(targetNode, config);
} catch (error) {
main_observer = null
}
}
// 1.监听main改变
// 2.监听卡片是否可见
// 3.如果可见了 去找
function setIframeRedPacket(type = 'twitter') {
// 获取所有卡片参数
let card_json_data
switch (type) {
case 'facebook':
card_json_data = parseCard.parseFacebookCardParmas()
for (let i in card_json_data) {
parseCard.replaceFacebookPacket(card_json_data[i])
}
break;
default:
card_json_data = parseCard.parseAllDeNetCardParmas()
// 过滤出可以请求的短链接
parseCard.getCardParmas(card_json_data).then((res) => {
for (let i in res.has_post_Id_card_data) {
let item = res.has_post_Id_card_data[i];
if (item && item.post_Id && item.post_Id.indexOf('nft/') >= 0) {
parseCard.replaceNftDomRedPacket(item)
} else {
parseCard.replaceDOMRedPacket(item)
}
}
if (res.need_net_short_url.length > 0) {
// 请求短链接
chrome.runtime.sendMessage({ actionType: "CONTENT_TWITTER_SHORT_LINK", data: "", arr_url: res.need_net_short_url }, () => { })
}
})
break;
}
}
// 监听点击发推 按钮绑定事件
// document.addEventListener('click', (e) => {
// try {
// if (e.target.dataset && e.target.dataset.testid && e.target.dataset.testid == 'tweetButton') {
// bindTwitterArtMethod()
// } else if (e.target.closest('div[data-testid=tweetButton]')) {
// bindTwitterArtMethod()
// }
// } catch (error) {
// console.error('error', error)
// }
// })
export function initExecuteScript(changes) {
if (changes.executeScript) {
let item = JSON.parse(changes.executeScript.newValue)
if (item.executeScript) {
init()
}
}
}
const createNFTIframe = ({ url, id }, callback) => {
let iframe = document.createElement('iframe')
iframe.id = id
iframe.src = url
iframe.style.cssText = 'border:medium none; width:100%; height:100%; z-index:100; position: fixed; top:0;left:0; display:none;';
iframe.onload = () => {
callback && callback()
}
document.body.appendChild(iframe);
}
function initParseCard() {
let timer = setInterval(() => {
let inTwitter = window.location.href.includes('twitter.com');
let inTwitterNode = document.querySelector('main');
let inFacebook = window.location.href.includes('facebook.com');
let inFacebookNode = document.querySelector('#facebook');
if (inTwitter && inTwitterNode) {
clearInterval(timer)
setInterval(() => {
if (!main_observer) {
onChangePageMain(inTwitterNode)
changeQueueNum(1)
}
if (queue_num <= 0) {
return
}
setIframeRedPacket()
checkHasDeBtn()
checkHasSliderDeBtn();
changeQueueNum(-1)
showNFTCard()
}, 1000)
} else if (inFacebook && inFacebookNode) {
clearInterval(timer)
setInterval(() => {
if (!main_observer) {
onChangePageMain(inFacebookNode)
changeQueueNum(1)
}
if (queue_num <= 0) {
return
}
setIframeRedPacket('facebook')
changeQueueNum(-1)
}, 1000)
}
}, 1000);
}
let inited = false
// 初始化
export function init() {
if (inited) {
return
}
inited = true
console.log('init')
getDiscordAuthCode();
let where = window.location.href.indexOf('twitter.com') < 0 && window.location.href.indexOf('facebook.com') < 0;
if (where) {
return
}
twitterPinLogin();
// 渲染dom
initParseCard()
showNFTCard()
renderDom();
checkTwitterTaskState();
onBodyClick();
initBuyNFT()
getChromeStorage("popupShowPublishDialog", (res) => {
console.log("popupShowPublishDialog", res);
if (res && res.show) {
setTimeout(() => {
showTwitterPublishDialogHandler({
srcContent: res.srcContent,
postId: res.postId,
copyContent: res.copyContent || ''
});
}, 1500);
chrome.storage.local.remove("popupShowPublishDialog");
}
});
getChromeStorage("userSettings", (res) => {
setTimeout(() => {
addPinedPop();
if (res && !res.isOnToolbar) {
setTimeout(() => {
showPinTips();
chrome.storage.local.remove("userSettings");
}, 800);
}
}, 800);
});
}
function checkHasSliderDeBtn() {
let deBtn = document.getElementById('de-btn');
let deBtn3 = document.getElementById('de-btn3');
if (!deBtn && !deBtn3) {
addSliderNavDeBtn();
}
}
export function facebookReplyTweet(params) {
if (window.location.origin.indexOf('twitter.com')) {
const urlParams = new URLSearchParams(window.location.search);
const actionType = urlParams.get('actionType');
let deReplyParams = urlParams.get('deReplyParams') || '{}';
deReplyParams = JSON.parse(deReplyParams);
if (actionType == 'denetFacebookToTwitterReply') {
if (params.postId == deReplyParams.postId) {
let iframe = document.getElementById(params.postId);
iframe.contentWindow.postMessage({ actionType: 'CONTENT_RED_PACKET_FACEBOOK_REPLY', data: deReplyParams }, '*');
}
}
}
}
export function replyHandle(params) {
let iframe = window.parent.document.getElementById(params.postId);
let replyBtn = iframe.parentNode.parentNode.querySelector('div[data-testid="reply"]') ||
iframe.parentNode.parentNode.parentNode.querySelector('div[data-testid="reply"]');
if (replyBtn) {
replyBtn.click();
}
onReplyDialogOpen(params, iframe);
// 详情页推文底部评论处理
let pathNameArr = window.location.pathname.split('/');
if (pathNameArr.length >= 2 && pathNameArr[pathNameArr.length - 2] == 'status') {
let tweetReply = document.querySelector('div[data-testid="tweetButtonInline"]');
if (tweetReply) {
tweetReply.addEventListener('click', function () {
// 详情页回复按钮点击
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.replyClickByDetailPage
});
let eleList = tweetReply.parentNode.parentNode.parentNode.parentNode.parentNode.querySelectorAll('span[data-text="true"]');
reportReplyResult(eleList, params, () => {
// iframe.contentWindow.postMessage({ actionType: 'CONTENT_RED_PACKET_REPLY_RASK_FINSH', data: {} }, '*');
chrome.runtime.sendMessage({ actionType: "CONTENT_RED_PACKET_REPLY_RASK_FINSH", data: { postId: params.postId } }, () => { })
});
})
}
}
}
export function onTweetReplyClick(params) {
let iframe = window.parent.document.getElementById(params.postId);
let replyBtn = iframe.parentNode.parentNode.querySelector('div[data-testid="reply"]') ||
iframe.parentNode.parentNode.parentNode.querySelector('div[data-testid="reply"]');
if (replyBtn) {
replyBtn.addEventListener('click', () => {
onReplyDialogOpen(params, iframe);
})
}
}
function onReplyDialogOpen(params, iframe) {
setTimeout(() => {
let dialog = document.querySelector('div[role="dialog"]');
let replyBtn;
if (dialog) {
let dialogContent = dialog.querySelector('div[role="dialog"]');
replyBtn = dialog.querySelector('div[data-testid="toolBar"]').querySelector('div[data-testid="tweetButton"]');
if (dialogContent) {
let width = dialogContent.offsetWidth;
let ele = document.createElement('div');
ele.innerText = 'Tag 3 friends to complete the task';
ele.style.cssText = `width: ${width}px; height: 38px; color: #fff; font-weight: 600;
font-size: 16px; display: flex; align-items: center; justify-content: center; background: #1D9BF0;
opacity: 0.8; position: absolute; top: 18px; left: 50%; transform: translateX(-50%); z-index: 1000`;
dialogContent.style.top = '80px';
dialogContent.parentNode.appendChild(ele);
}
} else {
dialog = document.querySelector('main[role="main"]');
if (dialog) {
replyBtn = dialog.querySelector('div[data-testid="tweetButton"]');
}
}
if (dialog && replyBtn) {
replyBtn.addEventListener('click', function () {
// 推文页回复按钮点击
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.replyClickByTwitterList
});
let eleList = dialog.querySelector('div[contenteditable="true"]').querySelectorAll('span[data-text="true"]');
reportReplyResult(eleList, params, () => {
// 上報完成
// iframe.contentWindow.postMessage({ actionType: 'CONTENT_RED_PACKET_REPLY_RASK_FINSH', data: {} }, '*');
chrome.runtime.sendMessage({ actionType: "CONTENT_RED_PACKET_REPLY_RASK_FINSH", data: { postId: params.postId } }, () => { })
})
});
}
}, 1000);
}
const reportReplyResult = throttle(function (eleList, params, cb) {
//未过滤的回复文本
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.replyInputTextGet
}, {
replyStr: eleList
});
if (eleList && eleList.length) {
let atList = [];
for (let i = 0; i < eleList.length; i++) {
let item = eleList[i];
// 是否有中文
let reg = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g;
if (item && item.innerText.startsWith('@') && !reg.test(item.innerText)) {
atList.push(item.innerText);
}
}
// 去重过滤文本
atList = Array.from(new Set(atList));
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.replyFilterTextGet
}, {
replyStr: atList
});
if (atList.length >= 3) {
//真实上报
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.replyReport
}, {
replyStr: atList
});
fetchAddFinishEvent({
eventType: params.type,
luckdropId: params.taskLuckdropId
}).then(res => {
if (res.code == 0) {
cb && cb();
}
})
}
}
}, 800);
// 根据推特id找到dom,完成任务
export function findTweetByIdDoTask({ tweet_Id = '', follow_names = [] }, task_type = 'like') {
// 1.根据推特ID寻找推文,获取卡片
// 获取所有卡片参数
let card_json_data = parseCard.parseAllDeNetCardParmas()
let result = card_json_data.filter((item) => { return item.tweet_Id == tweet_Id }) || []
if (result.length < 1) {
return
}
result = result[0]
switch (task_type) {
case 'like':
// https://twitter.com/intent/retweet?tweet_id=1525900221628223491
if (result.dom_card) {
result.dom_card.querySelector('div[data-testid=like]').click()
result.dom_card.querySelector('iframe').contentWindow.postMessage({ actionType: 'CONTENT_DONE_TASK', task_type, }, '*');
}
break;
case 'retweet':
if (result.dom_card) {
result.dom_card.querySelector('div[data-testid=retweet]').click()
result.dom_card.querySelector('div[data-testid=retweetConfirm]').click()
}
break
case 'follow':
follow_names.forEach((item) => {
window.open(`https://twitter.com/intent/follow?screen_name=${item}&tweet_Id=${tweet_Id}`)
})
break
}
}
function clickByDataTestId(e, id, callback) {
if (e.target.dataset && e.target.dataset.testid && e.target.dataset.testid == id) {
callback()
} else if (e.target.closest('div[data-testid=' + id + ']')) {
callback()
}
}
// 校验关注推特状态
export function checkTwitterTaskState() {
let task_type = ''
let url = window.location.href
let tweet_Id
let task_data = {
follow_name: ''
}
// 校验当前链接
if (url.includes('https://twitter.com/intent/retweet')) {
task_type = 'retweet'
} else if (url.includes('https://twitter.com/intent/follow')) {
task_type = 'follow'
task_data.follow_name = getQueryString('screen_name')
} else if (url.includes('https://twitter.com/intent/like')) {
task_type = 'like'
} else {
return
}
tweet_Id = getQueryString('tweet_id')
// let root_status
document.body.addEventListener('click', (e) => {
// 点击 确认
clickByDataTestId(e, 'confirmationSheetConfirm', () => {
chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: true }, () => { })
})
// 点击取消
clickByDataTestId(e, 'confirmationSheetCancel', () => {
chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: false }, () => { })
})
// 点击 蒙层
if (e.target && e.target.nextSibling && e.target.nextSibling.dataset && e.target.nextSibling.dataset.testid == 'confirmationSheetDialog') {
chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: false }, () => { })
}
}, true)
let timer = setInterval(() => {
// 喜欢
if (document.querySelector('div[data-testid=unlike]') && task_type == 'like') {
clearInterval(timer)
chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: true }, () => { })
}
// 转推
if (document.querySelector('div[data-testid=unretweet]') && task_type == 'retweet') {
clearInterval(timer)
chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: true }, () => { })
}
// 关注
if (task_type == 'follow') {
let follow_area = document.querySelector('div[data-testid=placementTracking]')
if (follow_area && follow_area.querySelectorAll('div')) {
follow_area = follow_area.querySelectorAll('div')
clearInterval(timer)
for (let i in follow_area) {
if (follow_area[i] && follow_area[i].dataset && follow_area[i].dataset.testid && follow_area[i].dataset.testid.indexOf('unfollow') > 0) {
chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: true }, () => { })
break
}
}
}
}
}, 1000)
}
export function getTweetAuthorByDom(params) {
let iframe = document.getElementById(params.postId);
if (!iframe) {
return;
}
let fullNameDom;
let pathNameArr = window.location.pathname.split('/');
if (pathNameArr.length >= 2 && pathNameArr[pathNameArr.length - 2] == 'status') {
fullNameDom = iframe.parentNode.parentNode.parentNode.parentNode.querySelector('a[role=link]');
} else {
fullNameDom = iframe.parentNode.parentNode.parentNode.querySelector('a[role=link]');
}
if (fullNameDom) {
let arr = fullNameDom.href.split('/');
if (arr.length) {
let fullName = arr[arr.length - 1];
if (fullName) {
iframe.contentWindow.postMessage({ actionType: 'CONTENT_RED_PACKET_GET_TWEET_AUTHOR', data: { fullName } }, '*');
}
}
}
}
export function doTaskTwitterAPI({ task_data, task_type }) {
switch (task_type) {
case 'like':
TwitterLikeAPI(task_data.tweet_Id)
break
case 'retweet':
TwitterRetweetAPI(task_data.tweet_Id)
break
case 'follow':
task_data.follow_data.forEach((item) => {
if (item.name && item.twitterUserId) {
TwitterFollowAPI(item, task_data.tweet_Id)
}
})
break
}
}
const TwitterFollowAPI = (item, tweet_Id) => {
fetch("https://twitter.com/i/api/1.1/friendships/create.json", {
"headers": {
"authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
"content-type": "application/x-www-form-urlencoded",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\", \"Google Chrome\";v=\"102\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"macOS\"",
"x-csrf-token": getCookie('ct0'),
"x-twitter-active-user": "yes",
"x-twitter-auth-type": "OAuth2Session",
"x-twitter-client-language": "zh-cn"
},
"referrer": "https://twitter.com/home",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": "include_profile_interstitial_type=1&include_blocking=1&include_blocked_by=1&include_followed_by=1&include_want_retweets=1&include_mute_edge=1&include_can_dm=1&include_can_media_tag=1&include_ext_has_nft_avatar=1&skip_status=1&user_id=" + item.twitterUserId + "",
"method": "POST",
"mode": "cors",
"credentials": "include"
}).then(() => {
let task_data = {
follow_name: item.name
}
chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'follow', task_data, task_done: true }, () => { })
}).catch(() => {
chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'follow', task_data, task_done: false }, () => { })
})
}
const TwitterRetweetAPI = (tweet_Id) => {
fetch("https://twitter.com/i/api/graphql/ojPdsZsimiJrUGLR1sjUtA/CreateRetweet", {
"headers": {
"accept": "*/*",
"accept-language": "zh,en;q=0.9,zh-CN;q=0.8",
"authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
"content-type": "application/json",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\", \"Google Chrome\";v=\"102\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"macOS\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-csrf-token": getCookie('ct0'),
"x-twitter-active-user": "yes",
"x-twitter-auth-type": "OAuth2Session",
"x-twitter-client-language": "zh-cn"
},
"referrer": "https://twitter.com/home",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": "{\"variables\":{\"tweet_id\":\"" + tweet_Id + "\",\"dark_request\":false},\"queryId\":\"ojPdsZsimiJrUGLR1sjUtA\"}",
"method": "POST",
"mode": "cors",
"credentials": "include"
}).then(() => {
chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'retweet', task_data: '', task_done: true }, () => { })
}).catch(() => {
chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'retweet', task_data: '', task_done: false }, () => { })
})
}
const TwitterLikeAPI = (tweet_Id) => {
fetch("https://twitter.com/i/api/graphql/lI07N6Otwv1PhnEgXILM7A/FavoriteTweet", {
"headers": {
"accept": "*/*",
"accept-language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
"authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
"content-type": "application/json",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"101\", \"Google Chrome\";v=\"101\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-csrf-token": getCookie('ct0'),
"x-twitter-active-user": "yes",
"x-twitter-auth-type": "OAuth2Session",
"x-twitter-client-language": "en"
},
"referrer": "https://twitter.com/home",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": "{\"variables\":{\"tweet_id\":\"" + tweet_Id + "\"},\"queryId\":\"lI07N6Otwv1PhnEgXILM7A\"}",
"method": "POST",
"mode": "cors",
"credentials": "include"
}).then(() => {
chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'like', task_data: '', task_done: true }, () => { })
}).catch(() => {
chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'like', task_data: '', task_done: false }, () => { })
})
}
export const hideBuyNFT = () => {
let iframe = document.querySelector('#nftProjectId')
iframe.style.display = 'none'
iframe.src = ''
}
export const showBuyNFT = ({ nft_project_Id }) => {
if (!nft_project_Id) {
return
}
let iframe = document.querySelector('#nftProjectId')
iframe.style.display = 'block'
iframe.src = chrome.runtime.getURL(`/iframe/buy-nft.html?nftProjectId=${nft_project_Id}`)
}
const initBuyNFT = () => {
let url = chrome.runtime.getURL(`/iframe/buy-nft.html`)
let id = `nftProjectId`
createNFTIframe({ url, id })
}
export const showNFTCard = () => {
let urlInfo = new URL(window.location.href)
let isTwitter = urlInfo.hostname === 'twitter.com'
let userElem = document.querySelector('div[data-testid="UserName"]');
let sideElem = document.querySelector('div[data-testid="sidebarColumn"]')
let tabIndex = sideElem && sideElem.querySelector('div[tabindex="0"]');
let isAppend = document.querySelector('div[id="de-nft-node"]');
let where = isTwitter && userElem && tabIndex;
if (where) {
let iframe = document.createElement('iframe');
iframe.src = chrome.runtime.getURL(`/iframe/nft-card.html`)
iframe.style.cssText = 'border:medium none; width:100%; height:297px;';
let nftElement = document.createElement('div');
nftElement.id = 'de-nft-node';
nftElement.innerHTML = `
${iframe.outerHTML}
`;
if (tabIndex && tabIndex.firstChild && tabIndex.firstChild.childNodes && !isAppend) {
tabIndex.firstChild.insertBefore(nftElement, tabIndex.firstChild.childNodes[2]);
}
}
}
export const showNFTSale = () => {
document.querySelector('div[id="de-nft-node"]').style.display = 'block';
}
export const appendPopupPage = (params) => {
let { path = '' } = params;
let iframe = document.createElement('iframe');
iframe.id = 'de-popup-page';
iframe.src = chrome.runtime.getURL('/iframe/popup-page.html') + `#${path}`;
iframe.style.cssText = `border: medium none; width: 375px;
height: 600px;position: fixed; right: 16px; top: 16px;background: #FFFFFF;border: 0.5px solid #919191;box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.2);box-sizing: border-box;z-index: 1000;`
let iframeContent = document.getElementById('de-extension-popup');
if (!iframeContent) {
document.querySelector('body').appendChild(iframe);
}
}
export const showPopupPage = (params) => {
let { path = '' } = params;
hidePinTips();
hideNoticeBindTweet();
appendPopupPage({ path });
}
export const hidePopupPage = () => {
let iframe = document.getElementById('de-popup-page');
if (iframe) {
document.querySelector('body').removeChild(iframe);
}
}
const onBodyClick = () => {
document.querySelector('body').addEventListener('click', function () {
hidePopupPage();
})
}