import { getChromeStorage, setChromeStorage, LANDING_PAGE } from '@/uilts/chromeExtension.js'
import { throttle } from '@/uilts/help'
import { getTtwitterRequestToken, twitterLogin, httpTwitterShortUrl } from '../server/twitter.js'
import { srcPublishSuccess } from '@/http/publishApi'
import Report from "@/log-center/log"
let dom = {};
export function contentTwitterPinLogin(port) {
if (window.location.href == 'https://api.twitter.com/oauth/authorize') {
let code = document.querySelector('code')
if (code) {
port.postMessage({ state: 'CONTENT_SEND_CODE', code: code.innerText })
}
}
}
let authToken = ''
export function backTwitterPinLoginToken() {
// 1.判断是否登陆了
getChromeStorage('userInfo', (res) => {
// 没有登陆
if (!res) {
getTtwitterRequestToken().then((res) => {
authToken = res.data.authToken
chrome.tabs.create({
url: `https://api.twitter.com/oauth/authorize?oauth_token=${res.data.authToken}`
})
})
}
})
}
export function backTwitterPinLoginCode(code) {
// 关闭code页面
chrome.tabs.query({}, (tab) => {
for (let i in tab) {
console.log(tab[i])
if (tab[i].url == 'https://api.twitter.com/oauth/authorize') {
chrome.tabs.remove(tab[i].id)
}
}
})
chrome.cookies.getAll(LANDING_PAGE, (e = []) => {
let _str = '[]'
if (e.length > 0) {
_str = e[0].value
}
let _arr = JSON.parse(decodeURIComponent(_str))
let receivedIds = []
if (_arr.length > 0) {
for (let i in _arr) {
receivedIds.push(_arr[i].receivedId)
}
}
// 发送请求
// token,code
twitterLogin(authToken, code, receivedIds).then(res => {
if (res.code == 0) {
setChromeStorage({ userInfo: JSON.stringify(res.data) })
chrome.cookies.remove(LANDING_PAGE)
}
})
}
)
}
export function backHttpTwitterShortUrl(url) {
return new Promise(function (resolve, reject) {
httpTwitterShortUrl(url).then(res => {
let _str_arr = res.match(/denetme.net\/([\s\S]*?)"/) || []
let _post_id = _str_arr[1] || ''
console.log('_str_arr_post_id', _post_id)
if (!_post_id) {
return
}
// 解析
let _obj = {
url,
post_id: _post_id
// tweet_id
}
getChromeStorage('sortLink', item => {
if (item) {
for (let i in item) {
if (item[i].url == _obj.url) {
item[i] = _obj
}
// else{
// delete item[i].tweet_id
// }
}
setChromeStorage({ sortLink: JSON.stringify(item) })
} else {
setChromeStorage({ sortLink: JSON.stringify([_obj]) })
}
resolve({
post_id: _post_id
})
})
})
})
}
/**
* 渲染要插入的dom,初始化逻辑
* @param port
*/
export function renderDom(port) {
if (window.location.href.indexOf('https://twitter.com') > -1) {
_createBtnDom(port);
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原生发布框
*/
export function showTwitterPublishDialogHandler(publishRes) {
dom.tweetBtn.click();
_setPublishContent(publishRes.srcContent);
_publishTweetEvent(publishRes.postId);
}
export function showPinTips() {
getChromeStorage('pinData', (res) => {
if (!res || res.show) {
let domPop = document.getElementById('de-pin-pop');
domPop.style.display = 'block';
}
})
}
export 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");
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(contentStr, cb) {
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 () {
bindTwitterArt.needBind = true;
bindTwitterArt.postId = contentStr;
cb && cb()
});
}, 800)
}
/**
* 在输入推文区插入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
});
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:0; border: medium none;display:none';
// shadowRoot.appendChild(iframe);
// document.body.appendChild(span)
dom.iframe = iframe;
let iframeContent = document.getElementById('iframe-content');
if (!iframeContent) {
document.getElementById('layers').appendChild(iframe);
}
}
/**
* 获取发布推文id
* @returns {string}
* @private
*/
/** function _getTwitterArtId(contentStr, cb) {
let id = '';
let timer = setInterval(() => {
let arr = document.querySelectorAll('a') || [];
for (let i = 0; i < arr.length; i++) {
let item = arr[i];
if (item.innerText == '#DeNet') {
if (item.parentNode && item.parentNode.parentNode && item.parentNode.parentNode.innerText.length > 5) {
let _postId = item.parentNode.parentNode.innerText || ''
let _dom = item.parentNode.parentNode.parentNode.parentNode.parentNode
let regex = new RegExp(contentStr);
if (regex.test(_postId)) {
id = _dom.children[0].querySelector('a[dir="auto"]').getAttribute('href').split('/status/')[1];
clearInterval(timer);
if (id) {
cb && cb(id);
}
break;
}
}
}
}
}, 1000);
}
*/
/**
* 点击deNet按钮处理
* @private
*/
function _deNetBtnClick(port) {
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';
}, 3000)
port.postMessage({ state: 'CONTENT_TWITTER_LOGIN' })
}
})
}
/**
* 设置发布内容
* @param content
* @private
*/
let isSetContent = false;
function _setPublishContent(content) {
if (!isSetContent) {
isSetContent = true;
setTimeout(() => {
document.execCommand("insertText", false, content);
setTimeout(() => {
isSetContent = false;
}, 2000)
}, 1000);
}
}
/**
* 创建deNet按钮 添加到页面
* @returns {{deBtn2: HTMLDivElement, deBtn1: HTMLDivElement, deBtn: HTMLSpanElement}}
* @private
*/
function _createBtnDom(port) {
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', () => {
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.buttonMain
});
_deNetBtnClick(port);
})
deBtn1.addEventListener('click', () => {
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.buttonSecond
});
_deNetBtnClick(port);
})
deBtn2.addEventListener('click', () => {
_deNetBtnClick(port);
})
deBtn3.addEventListener('click', () => {
Report.reportLog({
pageSource: Report.pageSource.mainPage,
businessType: Report.businessType.buttonClick,
objectType: Report.objectType.buttonMain
});
_deNetBtnClick(port);
})
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('h1[role]').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('h1[role]').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 (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() {
setInterval(() => {
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)
}
}, 1000)
}
/**
* 根据postID绑定推文id
*/
function bindTwitterArtMethod({ postId, twitterId }) {
let regex = new RegExp(bindTwitterArt.postId);
if (regex.test(postId)) {
if (twitterId && bindTwitterArt.needBind && !bindTwitterArt.isBindIng) {
bindTwitterArt.isBindIng = true;
srcPublishSuccess({
params: {
postId: postId,
srcContentId: twitterId
}
}).then((res) => {
if (res.code == 0) {
Report.reportLog({
objectType: Report.objectType.tweetPostBinded
});
bindTwitterArt.needBind = false;
bindTwitterArt.postId = '';
bindTwitterArt.isBindIng = false;
}
})
}
}
}
function parseDOMRedPacket() {
let _dom = null
let arr = document.querySelectorAll('a') || []
let _type = ''
for (let i in arr) {
if (arr[i].innerText == '#DeNet') {
let _tweetId = ''
let _article = arr[i].closest('article')
let _txt_area = _article.querySelector('[lang][dir=auto]')
let _postId = _txt_area.innerText
_postId = _postId.match(/###([\s\S]*?)###/)[1]
_dom = _article.querySelector('div[aria-labelledby]')
if (_dom) {
_type = 'card'
} else {
_type = 'parnet'
_dom = _txt_area
}
let _a_area = _article.querySelector('a[aria-label]')
if (_a_area && _a_area.getAttribute('href')) {
_tweetId = _a_area.getAttribute('href').split('/status/')[1] || ''
if (bindTwitterArt.needBind) {
bindTwitterArtMethod({ postId: _postId, twitterId: _tweetId });
}
}
replaceDOMRedPacket(_type, _dom, _postId, _tweetId)
}
}
}
let parse_dom = {}
async function parseDOMRedPacketByShortUrl(port) {
// let _new_time = new Date().getTime()
// if ((_new_time - change_time) > 1000) {
// change_time = _new_time
// } else {
// return
// }
// 为了减少声明变量次数
parse_dom.dom = null
parse_dom.txt_area = null
parse_dom.short_url = ''
parse_dom.postId = ''
parse_dom.a_arr = null
parse_dom.type = ''
parse_dom.tweetId = ''
parse_dom.article = null
parse_dom.a_tweetId = null
parse_dom.a_arr = document.querySelectorAll('a') || []
for (let i in parse_dom.a_arr) {
if (parse_dom.a_arr[i].innerText == '#DeNet') {
parse_dom.article = parse_dom.a_arr[i].closest('article')
parse_dom.dom = parse_dom.article.querySelector('div[aria-labelledby]')
if (parse_dom.dom && !parse_dom.dom.querySelector('iframe') && parse_dom.dom.closest('article').querySelector('iframe')) {
parse_dom.dom.style.display = 'none'
continue
}
if (parse_dom.dom && parse_dom.dom.parentElement.querySelector('iframe')) {
continue
}
parse_dom.short_url = getTwitterShortUrl(parse_dom.article)
parse_dom.a_tweetId = parse_dom.article.querySelector('a[aria-label]')
if (parse_dom.a_tweetId && parse_dom.a_tweetId.getAttribute('href')) {
parse_dom.tweetId = parse_dom.a_tweetId.getAttribute('href').split('/status/')[1] || ''
}
parse_dom.postId = await handleShortUrl(port, parse_dom.short_url)
console.log('_postId', parse_dom.postId)
console.log('short_url', parse_dom.short_url)
// 获取到postId了
if (parse_dom.postId) {
console.log('bindTwitterArt.postId', bindTwitterArt.postId)
console.log('parse_dom.postId', parse_dom.postId)
if (bindTwitterArt.needBind) {
bindTwitterArtMethod({ postId: parse_dom.postId, twitterId: parse_dom.tweetId });
}
if (parse_dom.dom) {
parse_dom.type = 'card'
} else {
parse_dom.type = 'parnet'
parse_dom.txt_area = parse_dom.article.querySelector('[lang][dir=auto]')
parse_dom.dom = parse_dom.txt_area
}
replaceDOMRedPacket(parse_dom.type, parse_dom.dom, parse_dom.postId, parse_dom.tweetId)
}
}
}
}
// 校验推特短数组大小
function checkShortUrlArraySize(_array) {
if (new Blob(_array).size >= 1024 * 1024) {
_array.splice(0, parseInt(_array.length / 2))
}
return _array
}
// 获取推特短链接
function getTwitterShortUrl(_article) {
let dom_arr = _article.querySelectorAll('a[href][role]')
let url = ''
for (let i in dom_arr) {
if (dom_arr[i].href.includes('https://t.co')) {
url = dom_arr[i].href
break
}
}
return url
}
// 处理短链接
async function handleShortUrl(port, url) {
let post_id = ''
// 校验本地是否存在
let sort_link_data = await getChromeStorage('sortLink') || ''
if (sort_link_data) {
let _item = sort_link_data.filter((_item) => { return _item.url == url })
// 本地有值
if (_item.length > 0) {
if (_item[0].post_id) {
post_id = _item[0].post_id
} else {
// 防止多次请求,校验timeout时间
let _new_time = new Date().getTime()
if (_new_time - _item[0].time > 5000) {
for (let i in sort_link_data) {
if (sort_link_data[i].url == url) {
sort_link_data[i].time = _new_time
}
}
setChromeStorage({ sortLink: JSON.stringify(sort_link_data) })
port.postMessage({ state: 'CONTENT_TWITTER_SHORT_LINK', url })
}
}
} else {
// 本地没有值
sort_link_data.push({ url, post_id: '', time: new Date().getTime() })
setChromeStorage({ sortLink: JSON.stringify(sort_link_data) })
port.postMessage({ state: 'CONTENT_TWITTER_SHORT_LINK', url })
}
// 校验存储大小
let new_item = checkShortUrlArraySize(sort_link_data)
if (sort_link_data.length != new_item.length) {
setChromeStorage({ sortLink: JSON.stringify(new_item) })
}
} else {
setChromeStorage({ sortLink: JSON.stringify([{ url, post_id: '', time: new Date().getTime() }]) })
port.postMessage({ state: 'CONTENT_TWITTER_SHORT_LINK', url })
}
return post_id
}
function createIframe(postId, tweetId) {
let _iframe = document.createElement('iframe')
_iframe.id = postId
_iframe.src = chrome.runtime.getURL('/iframe/red-packet.html') + `?postId=${postId}&tweetId=${tweetId}`;
_iframe.style.cssText = 'border: medium none; width:375px;min-height:500px;'
return _iframe
}
function replaceDOMRedPacket(_type, _dom, postId, tweetId) {
if (!_dom || !_dom.parentElement) {
return
}
if (_dom.parentElement.querySelector('iframe')) {
return
}
if (_type == 'card') {
let _len
_len = _dom.childNodes.length
for (let i = 0; i < _len; i++) {
_dom.children[i].style.display = 'none'
}
_dom.style = 'min-height:500px'
_dom.appendChild(createIframe(postId, tweetId))
} else {
let _parent = _dom.parentNode
_parent.appendChild(createIframe(postId, tweetId))
}
}
// let change_time = new Date().getTime()
// function onChangePageMain(port, targetNode) {
// const config = { attributes: true, childList: true, subtree: true };
// const callback = (mutationsList, observer) => {
// setTimeout(() => {
// parseDOMRedPacketByShortUrl(port)
// }, 2000)
// }
// const observer = new MutationObserver(callback);
// observer.observe(targetNode, config);
// }
export function setIframeRedPacket(port) {
// let elment = document.documentElement
if (window.location.href.includes('twitter.com)')) {
return
}
setInterval(() => {
parseDOMRedPacketByShortUrl(port)
}, 1000)
// let targetNode = null
// let timer = setInterval(() => {
// targetNode = document.querySelector('main')
// if (targetNode) {
// clearInterval(timer)
// onChangePageMain(port, targetNode)
// }
// }, 1000);
}