import { getChromeStorage, setChromeStorage } from '@/uilts/chromeExtension.js'
import { throttle, getQueryString, getCookie, nextTick, getQueryStringByUrl, getStorage, setStorage } from '@/uilts/help'
import { discordAuthRedirectUri, iframeHost } from '@/http/configAPI'
import { reportSrcPublishEvent } from '@/http/publishApi'
import Report from "@/log-center/log"
import { fetchAddFinishEvent } from '@/logic/background/fetch/facebook';
import { showNFTGroupIcon, hideNFTGroupList, checkUserJoinGroup, elemAddEventListener, addJoinedGroupList } from '@/logic/content/nft';
import { jumpTwitterDetailByAlert, showEditTweet } from '@/logic/content/help/twitter.js'
import { clearPostContent, setGroupIconStatus } from '@/logic/content/nft.js'
import { toolBox } from '@/logic/content/ToolBox'
import axios from 'axios';
import messageCenter from '@/uilts/messageCenter';
let dom = {};
let tweetAccountBindGroupInfo = {
isBind: false,
groupInfo: null,
isInit: false
}
let systemInfo = {
theme: 'light'
}
let fixProfileTabAutoTimer = null;
let pin_login = false
function twitterPinLogin() {
if (pin_login) {
return
}
if (window.location.href == 'https://api.twitter.com/oauth/authorize') {
let code = document.querySelector('code')
if (code) {
pin_login = true
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(params) {
let iframe = document.getElementById('iframe-content');
if (iframe) {
iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', data: params }, '*');
} else {
_addIframe();
let iframe = document.getElementById('iframe-content');
iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', data: params }, '*');
}
}
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()
// _setPublishContent(publishRes.srcContent);
setDialogPublishContent(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所需参数
export 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) {
// 如果是 Tool box
if (params.postType == 3) {
return;
}
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(params = {}) {
let toolElem = document.querySelector('div[data-testid="toolBar"]');
if (toolElem) {
let innerDeIcon = toolElem.querySelector('#de-btn1');
if (!innerDeIcon) {
toolElem.firstChild.appendChild(createTweetToolbarDenet());
popupShowGiveawayDialog();
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonView,
objectType: Report.objectType.buttonSecond
}, {
type: 0
});
}
let innerToolBoxIcon = toolElem.querySelector('#de-tool-box-btn-01');
if (!innerToolBoxIcon) {
toolElem.firstChild.appendChild(createTweetToolbarToolBox())
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonView,
objectType: Report.objectType.buttonSecond
}, {
type: 1
});
}
} else {
setTimeout(() => {
let toolElem = document.querySelector('div[data-testid="toolBar"]');
if (toolElem) {
let innerDeIcon = toolElem.querySelector('#de-btn1');
if (!innerDeIcon) {
toolElem.firstChild.appendChild(createTweetToolbarDenet());
popupShowGiveawayDialog();
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonView,
objectType: Report.objectType.buttonSecond
}, {
type: 0
});
}
let innerToolBoxIcon = toolElem.querySelector('#de-tool-box-btn-01');
if (!innerToolBoxIcon) {
toolElem.firstChild.appendChild(createTweetToolbarToolBox())
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonView,
objectType: Report.objectType.buttonSecond
}, {
type: 1
});
}
}
}, 1000)
}
}
const popupShowGiveawayDialog = async () => {
let { show = false } = await getChromeStorage('showGiveawayData') || {};
if (show) {
chrome.storage.local.remove("showGiveawayData");
showPublishDialog()
}
}
/**
* 获取左侧twitter按钮
* @private
*/
function _getSliderTwitterBtn() {
dom.tweetBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
dom.tweetBtn && 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');
let innerToolBoxIcon = document.getElementById('de-tool-box-btn-01');
if (!innerDeIcon || !innerToolBoxIcon) {
_addDeNetEditBtn();
}
}, 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-extension://omadcdhfdfhbklafpaddghnjimpfemgh' + ('/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;background: rgba(255,255,255,0);';
// 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'
if (params.type == 'nft') {
iframe.src = 'chrome-extension://omadcdhfdfhbklafpaddghnjimpfemgh' + ('/iframe/publish-tips.html?type="nft"');
} else {
iframe.src = 'chrome-extension://omadcdhfdfhbklafpaddghnjimpfemgh' + ('/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-extension://omadcdhfdfhbklafpaddghnjimpfemgh' + ('/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;border-radius: 20px;`
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(params = {}) {
debugger
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(params);
} else {
let loadIcon = document.getElementById('de-btn-loading');
if (loadIcon) {
return;
}
dom && dom.deBtn && 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;
export 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);
const setDialogPublishContent = throttle(function (content) {
setTimeout(() => {
let inputEle;
let dialog = document.querySelector('div[role="dialog"]');
if (dialog) {
inputEle = dialog.querySelector('div[contenteditable="true"]');
} else {
inputEle = document.querySelector('div[contenteditable="true"]');
}
const dataTransfer = new DataTransfer();
dataTransfer.setData('text', content);
const event = new ClipboardEvent('paste', {
clipboardData: dataTransfer,
bubbles: true
});
if (inputEle) {
inputEle.dispatchEvent(event);
}
}, 300)
}, 600);
/**
* 创建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;';
// 编辑框内按钮
let src = require("@/assets/img/icon-gift-pack.png");
const smallDeBtnStyle = 'width:20px;height: 20px;cursor: pointer;padding: 0px 8px';
const deBtn2 = document.createElement('div');
deBtn2.id = 'de-btn2';
deBtn2.style.cssText = smallDeBtnStyle;
deBtn2.src = src
// 小屏按钮
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', () => {
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.buttonMain
});
_deNetBtnClick({
type: 'SHOW_SELECT'
});
})
deBtn2.addEventListener('click', () => {
_deNetBtnClick();
})
deBtn3.addEventListener('click', () => {
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.buttonMain
});
_deNetBtnClick({
type: 'SHOW_SELECT'
});
})
dom.deBtn = deBtn;
dom.deBtn2 = deBtn2;
dom.deBtn3 = deBtn3;
dom.loadingImg = loadingImg;
}
function createTweetToolbarDenet() {
let src = require("@/assets/img/icon-gift-pack.png");
const smallDeBtnStyle = 'width:20px;height: 20px;cursor: pointer;margin: 0px 8px';
const deBtn1 = document.createElement('img');
deBtn1.id = 'de-btn1';
deBtn1.style.cssText = smallDeBtnStyle;
deBtn1.src = src;
deBtn1.addEventListener('click', () => {
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.buttonSecond
}, {
type: 0
});
_deNetBtnClick();
})
return deBtn1;
}
function createTweetToolbarToolBox() {
let src = require("@/assets/img/icon-tool-box-01.png");
const smallDeBtnStyle = 'width:20px;height: 20px;cursor: pointer;margin: 0px 8px';
const deToolBoxBtn = document.createElement('img');
deToolBoxBtn.id = 'de-tool-box-btn-01';
deToolBoxBtn.style.cssText = smallDeBtnStyle;
deToolBoxBtn.src = src;
deToolBoxBtn.addEventListener('click', () => {
_deNetBtnClick({
type: 'TOOL_BOX'
})
// report
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.buttonSecond
}, {
type: 1
});
})
return deToolBoxBtn;
}
function addSliderNavDeBtn() {
try {
let isSmall = false;
let tweetBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
if (tweetBtn && tweetBtn.querySelector('svg')) {
isSmall = true;
}
if (!isSmall) {
let bigDom = document.querySelector('a[href="/compose/tweet"]').parentNode.parentNode;
let deBtn = document.getElementById('de-btn');
if (bigDom && !deBtn) {
dom && dom.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) {
dom && dom.deBtn3 && smallDom.appendChild(dom.deBtn3);
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonView,
objectType: Report.objectType.buttonMain
});
}
}
} catch (e) {
console.log(e)
}
}
function onWindowResize() {
window.onresize = throttle(function () {
setTabGroupIframeStyle({}, true);
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';
}
}
}
let isSamllBtn = false;
let tweetBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
if (tweetBtn && tweetBtn.querySelector('svg')) {
isSamllBtn = true;
}
if (isSamllBtn) {
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 append = toolBar && !toolBar.querySelector('#de-btn1');
if (append) {
_addDeNetEditBtn();
}
} catch (e) {
console.log(e)
}
}
/**
* 点击发推,后端绑定推特id
*/
export 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'
import { useFavicon } from '_@vueuse_core@8.9.4@@vueuse/core'
// 检测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) {
if (main_observer) {
return
}
changeQueueNum(1)
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 setIframeCard(type = 'twitter') {
// 获取所有卡片参数
let card_json_data
if (type == 'facebook') {
card_json_data = parseCard.parseFacebookCardParmas()
for (let i in card_json_data) {
parseCard.replaceFacebookPacket(card_json_data[i])
}
}
else if (type == 'twitter') {
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 if (item && item.post_Id && item.post_Id.indexOf('nft_group/') >= 0) {
parseCard.replaceNftGroupDomRedPacket(item)
} else if (item && item.post_Id && item.post_Id.indexOf('luckdraw/') >= 0) {
item.post_Id = item.post_Id.split('luckdraw/')[1] || ''
item.page_type = '抽奖'
parseCard.replaceDOMRedPacket(item)
} else if (item && item.post_Id && item.post_Id.indexOf('toolbox/') >= 0) {
item.page_type = 'toolbox'
item.post_Id = item.post_Id.split('toolbox/')[1] || ''
if (item.post_Id) {
parseCard.replaceIframeToolBox(item)
}
} else if (item && item.post_Id && !item.post_Id.includes('/')) {
item.page_type = '红包'
parseCard.replaceDOMRedPacket(item)
// 夺宝链接
} else if (item && item.post_Id && item.post_Id.includes('treasure/')) {
// https://testh5.denetme.net/treasure/{postid}
// https://testh5.denetme.net/treasure/invite/{inviteCode}
// 邀请链接
if (item.post_Id.includes('invite/')) {
item.invite_code = item.post_Id.split('invite/')[1] || ''
item.page_type = '邀请链接'
if (item.invite_code) {
item.post_Id = ''
parseCard.replaceDOMTreasureCard(item)
}
} else {
// 原始链接
item.page_type = '原始链接'
item.post_Id = item.post_Id.split('treasure/')[1] || ''
if (item.post_Id) {
parseCard.replaceDOMTreasureCard(item)
}
}
}
}
if (res.need_net_short_urls.length > 0) {
parseCard.netShortUrl(res.need_net_short_urls, () => {
changeQueueNum(5)
})
}
})
}
}
// 监听点击发推 上报文案
// document.addEventListener('click', (e) => {
// try {
// let inputEle = document.querySelector('div[contenteditable="true"]');
// if (e.target.dataset && e.target.dataset.testid && e.target.dataset.testid == 'tweetButton') {
// // 获取文案上报
// console.log(inputEle.innerText)
// } else if (e.target.closest('div[data-testid=tweetButton]')) {
// console.log(inputEle.innerText)
// }
// } catch (error) {
// console.error('error', error)
// }
// })
export function initExecuteScript(changes) {
if (changes.executeScript) {
let item = JSON.parse(changes.executeScript.newValue)
if (item.executeScript) {
init()
}
}
if (changes.userInfo) {
let item = JSON.parse(changes.userInfo.newValue)
if (item) {
checkUserJoinGroup(() => {
showNFTGroupIcon()
})
}
}
}
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.host.includes('twitter.com');
let inTwitterNode = document.querySelector('main');
let inFacebook = window.location.host.includes('facebook.com');
let inFacebookNode = document.querySelector('#facebook');
if (inTwitter && inTwitterNode) {
clearInterval(timer)
setInterval(() => {
onChangePageMain(inTwitterNode)
checkHasDeBtn()
twitterPinLogin()
showNFTGroupIcon()
if (queue_num <= 0) {
return
}
initGroupTip()
setIframeCard()
checkHasSliderDeBtn();
changeQueueNum(-1)
showNFTCard()
addGroupTab();
addJoinedGroupList();
}, 1000)
} else if (inFacebook && inFacebookNode) {
clearInterval(timer)
setInterval(() => {
onChangePageMain(inTwitterNode)
if (queue_num <= 0) {
return
}
setIframeCard('facebook')
changeQueueNum(-1)
}, 1000)
}
}, 1000);
}
let inited = false
// 初始化
export function init() {
if (inited) {
return
}
inited = true
console.log('init')
// 渲染dom
initParseCard()
twitterPinLogin()
getDiscordAuthCode();
appendPopupPage();
chrome.runtime.sendMessage({
actionType: "CONTENT_SET_POPUP_CONFIG",
data: {
popup: 'popup.html'
}
});
let where = window.location.host.indexOf('twitter.com') < 0 && window.location.host.indexOf('facebook.com') < 0;
if (where) {
return
}
if (window.location.host.includes('twitter.com')) {
// onPageVisbile();
renderDom();
showNFTCard()
showNFTGroupIcon()
addEventAction();
checkUserJoinGroup();
checkTwitterTaskState();
initBuyNFT();
addJoinedGroupList();
getSysTheme();
addGroupTab();
// 预加载全屏 toobbox
toolBox.initFull()
}
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 onPageVisbile() {
document.addEventListener('visibilitychange', function () {
let isHidden = document.hidden;
if (!isHidden) {
depositUSShowPopupPage();
}
});
}
const depositUSShowPopupPage = async () => {
let { form = '', path } = await getChromeStorage('achPayData') || {};
if (form == 'popupPage') {
showPopupPage({ path });
chrome.storage.local.remove("achPayData");
}
}
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, tasks }) {
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
case 'tasks':
tasks.forEach((item) => {
//
switch (String(item.type)) {
// 关注指定用户
case '1':
item.relatedUsers.forEach((item) => {
if (item.name && item.twitterUserId) {
TwitterFollowAPI(item, task_data.tweet_Id)
}
})
break
// 点赞
case '2':
TwitterLikeAPI(task_data.tweet_Id)
break
// 推文发推
case '10':
// 发推
TwitterApiCreateTweet({ text: task_data.tweet_text, tweet_Id: task_data.tweet_Id })
break
}
})
break
}
}
export function showJoinDialog(data) {
let iframe = document.querySelector('#nftProjectId')
iframe.style.display = 'block'
iframe.contentWindow.postMessage({ actionType: 'SHOW_JOIN_DATA', data }, '*');
iframe.src = 'chrome-extension://omadcdhfdfhbklafpaddghnjimpfemgh' + (`/iframe/buy-nft.html#/group?params=${JSON.stringify(data)}&time=${new Date().getTime()}`)
}
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 }, () => { })
})
}
const TwitterApiCreateTweet = ({ text, tweet_Id }) => {
let data = {
queryId: "hC1nuE-2d1NX5LYBuuAvtQ",
features: {
"dont_mention_me_view_api_enabled": true,
"interactive_text_enabled": true,
"responsive_web_uc_gql_enabled": false,
"vibe_api_enabled": true,
"responsive_web_edit_tweet_api_enabled": false,
"standardized_nudges_misinfo": true,
"responsive_web_enhance_cards_enabled": false
},
variables: {
"tweet_text": text,
"media": {
"media_entities": [],
"possibly_sensitive": false
},
"withDownvotePerspective": true,
"withReactionsMetadata": false,
"withReactionsPerspective": false,
"withSuperFollowsTweetFields": true,
"withSuperFollowsUserFields": true,
"semantic_annotation_ids": [],
"dark_request": false
}
};
axios.post(`https://twitter.com/i/api/graphql/hC1nuE-2d1NX5LYBuuAvtQ/CreateTweet`,
data, {
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"
},
}).then(function (response) {
chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'createTweet', task_data: '', task_done: true, response })
}).catch(function (err) {
chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'createTweet', task_data: '', task_done: false })
});
}
export const TwitterApiUserByScreenName = (params) => {
let { screen_name, tweetId = '', objectType = '' } = params;
axios.get(`https://twitter.com/i/api/graphql/mCbpQvZAw6zu_4PvuAUVVQ/UserByScreenName?variables=%7B%22screen_name%22%3A%22${screen_name}%22%2C%22withSafetyModeUserFields%22%3Atrue%2C%22withSuperFollowsUserFields%22%3Atrue%7D`, {
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"
},
}).then(function (response) {
chrome.runtime.sendMessage({ actionType: "CONTENT_API_GET_TWEET_USER_INFO_RES", data: response.data.data || {}, tweetId, objectType }, () => { })
}).catch(function (err) {
chrome.runtime.sendMessage({ actionType: "CONTENT_API_GET_TWEET_USER_INFO_RES", data: {}, tweetId, objectType }, () => { })
});
}
let click_old_time = new Date().getTime()
export const showTwitterPost = (data) => {
let click_new_time = new Date().getTime()
if ((click_new_time - click_old_time) < 3000) {
return
}
click_old_time = click_new_time
showEditTweet(() => {
clearPostContent(() => {
contentGetNftPostPre({
groupId: data.groupId
})
})
})
// addPublishTipsIframe({ type: 'nft' })
setGroupTabStatus();
}
export function publishNFTTweetEvent({ groupId, postId, srcContent }, callback) {
setTimeout(() => {
let publishTweetBtn;
let dialog = document.querySelector('div[role="dialog"]');
if (dialog) {
publishTweetBtn = dialog.querySelector('div[data-testid="tweetButton"]');
} else {
let domMain = document.querySelector('main[role="main"]');
publishTweetBtn = domMain && domMain.querySelector('div[data-testid="tweetButton"]');
}
publishTweetBtn && publishTweetBtn.addEventListener('click', function () {
// 获取文案上报
publishNFTTweetPost({ postId, srcContent, groupId })
// 绑定推文id
bindTwitterArt.needBind = true;
bindTwitterArt.postId = postId;
callback && callback()
jumpTwitterDetailByAlert()
setTimeout(() => {
setGroupTabSelfStyle({
groupColor: 'rgb(83, 100, 113)',
groupFontWeight: '500',
lineDisplay: 'none'
});
sendMessageToGroupBanner({ type: 'arrow' })
}, 2000);
});
}, 800)
}
const sendMessageToGroupBanner = (params) => {
chrome.runtime.sendMessage({
actionType: "SWITCH_GROUP_BANNER_STATUS",
data: params
}, (res) => {
if (!res) {
Report.reportLog({
objectType: Report.objectType.chrome_extension_sendmessage_error
})
}
});
}
export const publishNFTTweetPost = ({ postId, srcContent, groupId }) => {
let inputEle = document.querySelector('div[contenteditable="true"]');
let textContent = inputEle.innerText
srcContent = srcContent.replaceAll('#DNFT', '')
srcContent = srcContent.replaceAll('⬇️', '')
srcContent = srcContent.replaceAll('Join', '')
srcContent = srcContent.replaceAll('Now:', '')
let arr = srcContent.split(' ') || []
arr.forEach((item) => {
if (textContent.includes(item)) {
textContent = textContent.replaceAll(item, '')
}
})
textContent = textContent.replaceAll('#DNFT', '')
textContent = textContent.replaceAll('⬇️', '')
textContent = textContent.replaceAll('Join', '')
textContent = textContent.replaceAll('Now:', '')
textContent = textContent.trim()
let formData = {
groupId,
textContent
}
let params = {
postBizData: JSON.stringify(formData),
postSrc: 1, //1 twitter
postType: 2, //2 nft
postId
}
chrome.runtime.sendMessage({
actionType: "CONTENT_NFT_TXT_PUBLISH",
data: params
});
}
const contentGetNftPostPre = (data) => {
chrome.runtime.sendMessage({
actionType: "CONTENT_GET_TWITTER_NFT_POST_PRE",
data
});
}
let tweet_nft_content = {}
export const setTwitterTextarea = (params, num = 5) => {
if (num <= 0) {
return
}
tweet_nft_content = params
let inputEle = document.querySelector('div[contenteditable="true"]');
if (inputEle) {
inputEle.focus();
setGroupIconStatus();
document.execCommand("insertText", false, '');
setTimeout(() => {
document.execCommand("insertText", false, params.srcContent + ' ');
// 光标定位到起始位置
setTimeout(() => {
inputEle.focus();
let sel = window.getSelection()
let range = document.createRange()
range.setStart(inputEle, 0)
range.setEnd(inputEle, 0)
sel.removeAllRanges()
sel.addRange(range);
}, 0)
publishNFTTweetEvent(params, bindTwitterArtMethod)
}, 1000)
} else {
setTimeout(() => {
num--
setTwitterTextarea(params, num)
}, 500);
}
}
const initGroupTip = () => {
let arr = window.location.pathname.split('/') || []
if (location.pathname == '/compose/tweet') {
return
}
if (!document.querySelector('div[data-testid=UserName]')) {
return
}
if (arr.length >= 2) {
let twitterAccount = arr[1]
let iframe_banner = document.querySelector('#denet_group_banner')
if (iframe_banner) {
if (twitterAccount != getQueryStringByUrl(iframe_banner.src, 'twitterAccount')) {
iframe_banner.style.display = 'none'
// iframe_banner.src = 'chrome-extension://omadcdhfdfhbklafpaddghnjimpfemgh' + (`/iframe/group-card.html?twitterAccount=${twitterAccount}`)
iframe_banner.contentWindow.postMessage({ actionType: 'SHOW_BANNER', twitterAccount }, '*');
}
return
}
try {
let dom = document.querySelector('div[data-testid="ScrollSnap-SwipeableList"]').closest('nav')
let iframe = document.createElement('iframe')
iframe.id = 'denet_group_banner'
iframe.style.cssText = 'border: medium none; display:none; width:100%; height:100px;'
iframe.src = 'chrome-extension://omadcdhfdfhbklafpaddghnjimpfemgh' + (`/iframe/group-card.html?twitterAccount=${twitterAccount}`)
// iframe.contentWindow.postMessage({ actionType: 'SHOW_BANNER', twitterAccount }, '*');
if (dom && !dom.parentNode.children[0].querySelector('iframe')) {
// dom.parentNode.insertBefore(iframe, dom)
dom.parentNode.children[0].appendChild(iframe)
}
} catch (error) {
}
}
}
export const showGroupTip = () => {
let dom_denet_group_banner = document.querySelector('#denet_group_banner')
dom_denet_group_banner.style.display = 'block';
groupBtnStyleChange();
}
export const hideBuyNFT = () => {
let iframe = document.querySelector('#nftProjectId')
iframe.style.display = 'none'
iframe.src = ''
}
export const showBuyNFT = ({ nft_project_Id, post_Id = '' }) => {
if (!nft_project_Id) {
return
}
let iframe = document.querySelector('#nftProjectId')
iframe.style.display = 'block'
iframe.src = 'chrome-extension://omadcdhfdfhbklafpaddghnjimpfemgh' + (`/iframe/buy-nft.html#/?nftProjectId=${nft_project_Id}&postId=${post_Id}`)
}
const initBuyNFT = () => {
let url = ''
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-extension://omadcdhfdfhbklafpaddghnjimpfemgh' + (`/iframe/nft-card.html`)
iframe.style.cssText = 'border:medium none; width:100%; height:290px;';
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 addEventAction = () => {
let urlInfo = new URL(window.location.href)
let isTwitter = urlInfo.hostname === 'twitter.com'
// 页面滚动
if (isTwitter) {
// 首页
if (urlInfo.pathname === '/home') {
window.addEventListener('scroll', () => {
hideNFTGroupList()
})
}
}
}
export const appendPopupPage = (params = {}) => {
let { path = '' } = params;
let iframe = document.createElement('iframe');
iframe.id = 'de-popup-page';
iframe.src = 'chrome-extension://omadcdhfdfhbklafpaddghnjimpfemgh' + ('/iframe/popup-page.html') + `#${path}`;
iframe.style.cssText = `border: medium none; width: 375px !important;
height: 650px;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: 90000;
animation-duration: 0.5s !important;
animation-timing-function: ease-in-out !important;
animation-fill-mode: forwards !important;
transition: all 1s ease 0s !important;right: -385px;transform: translateX(385px);`
let iframeContent = document.getElementById('de-popup-page');
let overlayDom = document.createElement('div');
overlayDom.id = 'de-popup-overlay';
overlayDom.style.cssText = `position: fixed;z-index: 88888;top: 0;
left: 0;width: 100%;height: 100%;opacity: 0;display: none`;
let overlay = document.getElementById('de-popup-overlay');
let body = document.querySelector('body');
if (!iframeContent && body) {
document.querySelector('body').appendChild(iframe);
if (!overlay) {
document.querySelector('body').appendChild(overlayDom);
overlayDom.addEventListener('click', function () {
hidePopupPage();
})
} else {
overlay.addEventListener('click', function () {
hidePopupPage();
})
}
}
}
let showPopupPageFrom = '';
export const showPopupPage = (params = {}) => {
let { path = '', from, showJoinGroupFinish = false } = params;
showPopupPageFrom = from;
hidePinTips();
hideNoticeBindTweet();
let iframe = document.getElementById('de-popup-page');
if (!iframe) {
appendPopupPage();
iframe = document.getElementById('de-popup-page');
}
if (iframe) {
if (path) {
iframe.src = 'chrome-extension://omadcdhfdfhbklafpaddghnjimpfemgh' + ('/iframe/popup-page.html') + `#${path}`;
}
iframe.style.transform = 'translateX(-' + 395 + 'px)';
chrome.runtime.sendMessage({
actionType: "CONTENT_POPUP_PAGE_SHOW",
data: {
path,
showJoinGroupFinish,
}
});
chrome.runtime.sendMessage({
actionType: "CONTENT_SET_POPUP_CONFIG",
data: {
popup: ''
}
});
let overlay = document.getElementById('de-popup-overlay');
overlay.style.display = 'block';
let htmlDom = document.querySelector('html');
if (htmlDom) {
htmlDom.style.overflowY = 'hidden';
}
}
}
export const hidePopupPage = () => {
let iframe = document.getElementById('de-popup-page');
if (iframe) {
iframe.style.transform = 'translateX(' + 385 + 'px)';
let overlay = document.getElementById('de-popup-overlay');
overlay.style.display = 'none';
let htmlDom = document.querySelector('html');
if (htmlDom) {
htmlDom.style.overflowY = 'auto';
}
chrome.runtime.sendMessage({
actionType: "CONTENT_SET_POPUP_CONFIG",
data: {
popup: 'popup.html'
}
});
if (showPopupPageFrom == 'BUY_NFT_FINISH') {
chrome.runtime.sendMessage({
actionType: "CONTENT_GET_PINED",
data: {}
});
showPopupPageFrom = '';
}
}
}
export const tiggerInjectPopupPage = () => {
let iframeContent = document.getElementById('de-popup-page');
if (iframeContent) {
hidePinTips();
hideNoticeBindTweet();
let { transform = '' } = iframeContent.style;
if (transform == 'translateX(385px)' || !transform) {
showPopupPage();
} else {
hidePopupPage();
}
} else {
appendPopupPage();
setTimeout(() => {
let iframe = document.getElementById('de-popup-page');
let { transform = '' } = iframe.style;
if (transform == 'translateX(385px)' || !transform) {
showPopupPage();
} else {
hidePopupPage();
}
}, 300)
}
}
export const setPopupConfByPopupPage = () => {
let iframe = document.getElementById('de-popup-page');
if (iframe) {
let { transform = '' } = iframe.style;
if (transform && transform == 'translateX(-395px)') {
chrome.runtime.sendMessage({
actionType: "CONTENT_SET_POPUP_CONFIG",
data: {
popup: ''
}
});
} else {
chrome.runtime.sendMessage({
actionType: "CONTENT_SET_POPUP_CONFIG",
data: {
popup: 'popup.html'
}
});
}
} else {
chrome.runtime.sendMessage({
actionType: "CONTENT_SET_POPUP_CONFIG",
data: {
popup: 'popup.html'
}
});
}
}
/**
*
* Group Tab List Start
*/
/**
*
* 创建 Group Tab
*/
const createGroupTabNode = () => {
let groupIcon = document.createElement('img');
groupIcon.id = 'de-group-tab-icon'
groupIcon.src = require("@/assets/img/icon-group-tab-item.png");
groupIcon.style.cssText = 'width:20px;height: 20px;margin-right:4px;';
let divNode = document.createElement('div');
divNode.style.cssText = 'display: flex; align-items: center;height: 100%';
divNode.appendChild(groupIcon);
divNode.appendChild(document.createTextNode('Group'));
let lineDom = document.createElement('div');
lineDom.id = 'de-tab-line';
lineDom.style.cssText = `border-radius: 9999px;
position: absolute;
bottom: 0px;
min-width: 56px;
align-self: center;
height: 4px;
background-color: rgb(29, 155, 240);
display: none`;
let groupTab = document.createElement('div');
groupTab.id = 'de-nav-tab-group';
groupTab.style.cssText = `z-index: 1;
position: relative;
display: flex;
min-width: 56px;
-webkit-box-pack: center;
justify-content: center;
-webkit-box-align: center;
align-items: center;
text-align: center;
padding: 0px 16px;
color: rgb(83, 100, 113);
font-weight: 700;
height: 53px;
cursor: pointer;
font: 500 15px / 20px TwitterChirp, -apple-system, "system-ui", "Segoe UI", Roboto, Helvetica, Arial, sans-serif;`;
groupTab.appendChild(divNode);
groupTab.appendChild(lineDom);
return groupTab;
}
const groupBtnStyleChange = () => {
let tab = getGroupTabNode();
if (tab) {
let line = tab.querySelector('#de-tab-line');
if (line) {
let { display } = line.style;
if (display != 'none') {
sendMessageToGroupBanner({ type: 'btn' })
}
}
}
}
const getGroupTabNode = () => {
let tab = document.querySelector('#de-nav-tab-group');
return tab;
}
const addGroupTab = () => {
if (!document.querySelector('div[data-testid=UserName]')) {
return
}
let tabListDom = document.querySelector('div[role="tablist"]');
let groupItemTab = getGroupTabNode();
if (tabListDom && !groupItemTab) {
let groupTab = createGroupTabNode();
tabListDom.appendChild(groupTab);
groupTab.addEventListener('mouseenter', function () {
groupTab.style.background = 'rgba(15, 20, 25, 0.1)'
});
groupTab.addEventListener('mouseleave', function () {
groupTab.style.background = 'none'
});
setTimeout(() => {
let count = 0;
hiddenMaskWeb3Tab(count);
}, 1300)
addGroupTabEventListener();
}
removeTweetTabEvent({
tabListDom
});
addTweetTabEventListener({
tabListDom
});
addTabGroupContent(() => {
checkNeedSelectGroupTab();
});
}
const hiddenMaskWeb3Tab = (count) => {
setTimeout(() => {
count++;
if (count < 6) {
let tab = getMaskWeb3Tab();
if (tab) {
tab.style.display = 'none'
} else {
hiddenMaskWeb3Tab(count);
}
}
}, 1000);
}
/**
* 跳转到个人主页 检查是否需要选中 Group tab
*/
const checkNeedSelectGroupTab = () => {
if (window.location.pathname != '/home' && !document.hidden) {
setTimeout(() => {
getChromeStorage('groupTabData', (res) => {
console.log('groupTabData', res);
if (res && res.deTabVal == 'deGroupTab') {
chrome.storage.local.remove("groupTabData");
setTimeout(() => {
selectGroupTab();
}, 300)
}
})
}, 1300)
}
}
/** 选中 Group tab */
export const selectGroupTab = () => {
let groupTab = getGroupTabNode();
if (groupTab) {
groupTab.click();
}
};
export const groupTipsSelectGroupTab = (params = {}) => {
if (params.type == 'btn') {
let groupTab = getGroupTabNode();
if (groupTab) {
let line = groupTab.querySelector('#de-tab-line');
if (line) {
let { display } = line.style;
if (display == 'none') {
groupTab.click();
}
}
}
} else {
selectGroupTab();
}
}
/**
*
* Group tab点击事件监听
*/
const addGroupTabEventListener = () => {
let groupTab = getGroupTabNode();
groupTab.addEventListener('click', function () {
let bgColor = document.querySelector('body').style.backgroundColor;
let groupColor = systemInfo.theme == 'dark' && bgColor == 'rgb(0, 0, 0)' ? '#fff' : 'rgb(15, 20, 25)';
// let groupColor = systemInfo.theme == 'light' ? 'rgb(15, 20, 25)' : '#fff';
setGroupTabSelfStyle({
groupColor: groupColor,
groupFontWeight: '700',
lineDisplay: 'block'
});
setTweetActiveTabStyle({
color: 'rgb(83, 100, 113)',
display: 'none'
});
setTabContentStyle({
tweetTabContentDisply: 'none',
iframeContentDisplay: 'block'
});
refreshTabGroup();
window.addEventListener('scroll', addPageScrollEvent);
let tipsDom = document.querySelector('#denet_group_banner');
if (tipsDom) {
sendMessageToGroupBanner({ type: 'btn' })
} else {
onShowGroupBanner();
}
})
}
const onShowGroupBanner = () => {
chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
switch (req.actionType) {
case 'IFRAME_SHOW_GROUP_TIP':
sendMessageToGroupBanner({ type: 'btn' })
if (!getGroupTabNode()) {
addGroupTab();
}
break
}
sendResponse && sendResponse()
})
}
const addPageScrollEvent = () => {
let wrapperDom = document.querySelector('html');
let contentDom = document.querySelector('main[role="main"]');
let data = {
wrapperHeight: wrapperDom.offsetHeight,
wrapperScrollTop: wrapperDom.scrollTop,
contentHeight: contentDom.offsetHeight
}
messageCenter.send('de-tab-group-content', 'CONTENT_GROUP_LIST_SCROLL', data)
// chrome.runtime.sendMessage({
// actionType: "CONTENT_GROUP_LIST_SCROLL",
// data: data
// }, () => { });
};
const removeTweetTabEvent = (params) => {
let { tabListDom } = params;
if (tabListDom) {
let tweetTabItem = tabListDom.querySelectorAll('div[role="presentation"]');
if (tweetTabItem.length) {
for (let i = 0; i < tweetTabItem.length; i++) {
let item = tweetTabItem[i];
item.removeEventListener('click', TweetTabEventHandler)
}
}
}
}
/**
*
* twitter tab点击事件监听
*/
const addTweetTabEventListener = (params) => {
let { tabListDom } = params;
let groupItemTab = getGroupTabNode();
if (tabListDom && groupItemTab) {
// 监听twitter tab点击事件
let tweetTabItem = tabListDom.querySelectorAll('div[role="presentation"]');
if (tweetTabItem.length) {
for (let i = 0; i < tweetTabItem.length; i++) {
let item = tweetTabItem[i];
item.addEventListener('click', TweetTabEventHandler)
}
}
}
}
const TweetTabEventHandler = () => {
window.removeEventListener('scroll', addPageScrollEvent);
setGroupTabSelfStyle({
groupColor: 'rgb(83, 100, 113)',
groupFontWeight: '500',
lineDisplay: 'none'
});
setTabContentStyle({
tweetTabContentDisply: 'block',
iframeContentDisplay: 'none'
});
setTweetActiveTabStyle({
color: 'rgb(15, 20, 25)',
display: 'block'
});
sendMessageToGroupBanner({ type: 'arrow' })
};
/**
* 设置 Group Tab 样式
* */
const setGroupTabSelfStyle = (params = {}) => {
let { groupColor, groupFontWeight, lineDisplay } = params;
let groupTab = getGroupTabNode();
if (groupTab) {
groupTab.style.color = groupColor;
groupTab.style.fontWeight = groupFontWeight;
let lineDom = groupTab.querySelector('#de-tab-line');
if (lineDom) {
lineDom.style.display = lineDisplay;
}
}
};
/**
* 切换到 Group tab时 刷新列表
*/
export const refreshTabGroup = () => {
messageCenter.send('de-tab-group-content', 'CONTENT_REFRESH_TAB_GROUP_LIST', {})
// chrome.runtime.sendMessage({
// actionType: "CONTENT_REFRESH_TAB_GROUP_LIST",
// data: {}
// }, () => { });
}
/**
*
* tab选中时设置 激活 的字体样式和选中条
*/
const setTweetActiveTabStyle = (params) => {
let { color, display } = params || {};
let tab = document.querySelector('a[aria-selected="true"]');
if (tab) {
let tweetActiveTab = tab.querySelector('div');
if (tweetActiveTab) {
tweetActiveTab.style.color = color;
let tweetTabLine = tweetActiveTab.querySelector('div');
if (tweetTabLine) {
tweetTabLine.style.display = display;
}
}
}
}
/**
*
* 设置 tab 切换时 tab内容的样式(显示隐藏)
*/
const setTabContentStyle = (params) => {
let { tweetTabContentDisply, iframeContentDisplay } = params;
let tweetTabContent = getTweetTabContent();
if (tweetTabContent) {
if (tweetTabContentDisply == 'block') {
let { visibility } = tweetTabContent.style;
if (visibility == 'hidden') {
tweetTabContent.style.visibility = 'visible';
tweetTabContent.style.height = 'auto';
tweetTabContent.style.overflow = 'auto';
}
} else {
tweetTabContent.style.visibility = 'hidden';
tweetTabContent.style.height = '0px';
tweetTabContent.style.overflow = 'hidden';
tweetTabContent.style.margin = '0';
}
}
let iframeContent = getGroupTabContentNode();
if (!iframeContent) {
addTabGroupContent();
}
setTimeout(() => {
iframeContent = getGroupTabContentNode();
if (iframeContent) {
iframeContent.style.display = iframeContentDisplay;
}
})
};
/**
*
* 获取 twitter tab 下的内容
*/
const getTweetTabContent = () => {
let tweetTabContent = document.querySelector('[data-testid="primaryColumn"] [role="navigation"] + * > div[aria-label]:not([role="progressbar"])') || document.querySelector('div[data-testid="emptyState"]');
return tweetTabContent;
}
/**
* 注入 Group List 内容
*/
const addTabGroupContent = (cb) => {
let params = {
windowLocation: window.location
}
let iframe = document.createElement('iframe');
iframe.id = 'de-tab-group-content';
iframe.src = `${iframeHost}/tab-group` + `?params=${JSON.stringify(params)}`;
iframe.style.cssText = `border: medium none; height: 500px;display: none`
let iframeContent = getGroupTabContentNode();
let tweetTabContent = getTweetTabContent();
if (!iframeContent) {
if (tweetTabContent && tweetTabContent.parentElement) {
tweetTabContent.parentElement.appendChild(iframe);
cb && cb();
}
}
};
const getGroupTabContentNode = () => {
let content = document.getElementById('de-tab-group-content');
return content;
}
const setGroupTabStatus = () => {
let groupTab = getGroupTabNode();
if (groupTab) {
let line = groupTab.querySelector('#de-tab-line');
if (line) {
let { display } = line.style;
if (display != 'none') {
groupTab.click();
}
}
} else {
setTimeout(() => {
addGroupTab();
}, 2000)
}
clearInterval(fixProfileTabAutoTimer);
fixProfileTabAutoSwitch();
};
const fixProfileTabAutoSwitch = () => {
fixProfileTabAutoTimer = setInterval(() => {
let groupTab = getGroupTabNode();
let tweetTab = document.querySelector('a[aria-selected="true"]');
if (groupTab) {
let line = groupTab.querySelector('#de-tab-line');
if (line) {
let { display } = line.style;
if (display != 'none' && tweetTab) {
let groupContent = getGroupTabContentNode();
if (groupContent) {
let tweetTabContent = getTweetTabContent();
let { visibility } = tweetTabContent.style;
let { display } = groupContent.style;
if (display == 'block' && visibility != 'hidden') {
groupTab.click();
}
}
}
}
}
}, 1000)
}
/**
*
* 设置Tab Group Iframe 样式
*/
export const setTabGroupIframeStyle = (params, isReSize = false) => {
if (!isReSize) {
getSysTheme();
}
let iframeContent = getGroupTabContentNode();
if (iframeContent) {
let htmlHeight = document.querySelector('html').offsetHeight;
let primaryColumnHeightn = document.querySelector('div[data-testid="primaryColumn"]').offsetHeight;
let height = primaryColumnHeightn > htmlHeight ? primaryColumnHeightn : htmlHeight;
iframeContent.style.height = height + 'px';
}
}
/**
* mask web3 Tab
*
*/
const getMaskWeb3Tab = () => {
let tab = document.querySelector('div[data-testid="ScrollSnap-nextButtonWrapper"] + span');
return tab;
}
export const pageJumpHandler = (params) => {
let { url } = params
if (url) {
window.open(url)
}
}
export const getTweetProfileNavTop = (params) => {
let top = document.querySelector('div[role="tablist"]').closest('nav').getBoundingClientRect().top;
messageCenter.send({
actionType: "CONTENT_SEND_GROUP_NAV_TOP",
data: {
top,
scrollTop: params.scrollTop
}
})
// chrome.runtime.sendMessage({
// actionType: "CONTENT_SEND_GROUP_NAV_TOP", data: {
// top,
// scrollTop: params.scrollTop
// }
// }, () => { })
}
export const setGroupInfo = (params = {}) => {
tweetAccountBindGroupInfo.groupInfo = params;
let groupTab = getGroupTabNode();
if (!params.nftGroupId) {
let { pathname = '' } = window.location;
if (pathname == "/compose/tweet") {
return;
};
if (groupTab) {
groupTab.style.display = 'none';
} else {
setTimeout(() => {
groupTab = getGroupTabNode();
if (groupTab) {
groupTab.style.display = 'none';
}
}, 800)
}
} else {
if (groupTab) {
let { display } = groupTab.style;
if (display == 'none') {
groupTab.style.display = 'block';
}
}
}
}
const getSysTheme = () => {
const themeMedia = window.matchMedia("(prefers-color-scheme: light)");
if (themeMedia.matches) {
systemInfo.theme = 'light'
} else {
systemInfo.theme = 'dark'
}
sysThemeChange();
themeMedia.addListener(e => {
addGroupTab()
if (e.matches) {
systemInfo.theme = 'light'
} else {
systemInfo.theme = 'dark'
}
sysThemeChange();
});
}
const sysThemeChange = () => {
setTimeout(() => {
let bgColor = document.querySelector('body').style.backgroundColor;
messageCenter.send({
actionType: "CONTENT_SYS_THEME_CHANGE",
data: {
theme: systemInfo.theme,
twitterTheme: bgColor == 'rgb(0, 0, 0)' ? 'dark' : 'light'
}
})
// chrome.runtime.sendMessage({
// actionType: "CONTENT_SYS_THEME_CHANGE", data: {
// theme: systemInfo.theme,
// twitterTheme: bgColor == 'rgb(0, 0, 0)' ? 'dark' : 'light'
// }
// }, () => { })
}, 800)
}
/**
*
* Group Tab List End
*
*/
export const loginSuccessHandle = () => {
// 检查是否漏出group图标
checkUserJoinGroup(() => {
showNFTGroupIcon()
addEventAction()
addJoinedGroupList();
})
}
export const showPublishDialog = () => {
let smallBtn = document.getElementById('de-btn1');
if (smallBtn) {
smallBtn.click();
}
}