twitter.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. import { getChromeStorage, setChromeStorage, LANDING_PAGE } from '@/uilts/chromeExtension.js'
  2. import { throttle } from '@/uilts/help'
  3. import { getTtwitterRequestToken, twitterLogin } from '../server/twitter.js'
  4. import { srcPublishSuccess } from '@/http/publishApi'
  5. let dom = {};
  6. export function contentTwitterPinLogin(port) {
  7. if (window.location.href == 'https://api.twitter.com/oauth/authorize') {
  8. let code = document.querySelector('code')
  9. if (code) {
  10. port.postMessage({ state: 'CONTENT_SEND_CODE', code: code.innerText })
  11. }
  12. }
  13. }
  14. let authToken = ''
  15. export function backTwitterPinLoginToken() {
  16. // 1.判断是否登陆了
  17. getChromeStorage('userInfo', (res) => {
  18. // 没有登陆
  19. if (!res) {
  20. getTtwitterRequestToken().then((res) => {
  21. authToken = res.data.authToken
  22. chrome.tabs.create({
  23. url: `https://api.twitter.com/oauth/authorize?oauth_token=${res.data.authToken}`
  24. })
  25. })
  26. }
  27. })
  28. }
  29. export function backTwitterPinLoginCode(code) {
  30. // 关闭code页面
  31. chrome.tabs.query({}, (tab) => {
  32. for (let i in tab) {
  33. console.log(tab[i])
  34. if (tab[i].url == 'https://api.twitter.com/oauth/authorize') {
  35. chrome.tabs.remove(tab[i].id)
  36. }
  37. }
  38. })
  39. chrome.cookies.getAll(LANDING_PAGE, (e = []) => {
  40. let _str = '[]'
  41. if (e.length > 0) {
  42. _str = e[0].value
  43. }
  44. let _arr = JSON.parse(decodeURIComponent(_str))
  45. let receivedIds = []
  46. if (_arr.length > 0) {
  47. for (let i in _arr) {
  48. receivedIds.push(_arr[i].receivedId)
  49. }
  50. }
  51. // 发送请求
  52. // token,code
  53. twitterLogin(authToken, code, receivedIds).then(res => {
  54. if (res.code == 0) {
  55. setChromeStorage({ userInfo: JSON.stringify(res.data) })
  56. chrome.cookies.remove(LANDING_PAGE)
  57. }
  58. })
  59. }
  60. )
  61. }
  62. /**
  63. * 渲染要插入的dom,初始化逻辑
  64. * @param port
  65. */
  66. export function renderDom(port) {
  67. if (window.location.href.indexOf('https://twitter.com') > -1) {
  68. _createBtnDom(port);
  69. onWindowResize();
  70. checkHasDeBtn();
  71. setTimeout(() => {
  72. _addIframe();
  73. _addDeNetBtn();
  74. _getSliderTwitterBtn();
  75. }, 800)
  76. }
  77. }
  78. /**
  79. * 展示give弹窗
  80. */
  81. export function showGiveDialogHandler(userInfo) {
  82. let iframe = document.getElementById('iframe-content');
  83. if (iframe) {
  84. iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', userInfo }, '*');
  85. } else {
  86. _addIframe();
  87. let iframe = document.getElementById('iframe-content');
  88. iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', userInfo }, '*');
  89. }
  90. }
  91. export function showIframeHandler() {
  92. document.getElementById('iframe-content').style.display = 'block';
  93. }
  94. export function hideIframeHandler() {
  95. document.getElementById('iframe-content').style.display = 'none';
  96. }
  97. /**
  98. * 展示twitter原生发布框
  99. */
  100. export function showTwitterPublishDialogHandler(publishRes) {
  101. dom.tweetBtn.click();
  102. _setPublishContent(publishRes.srcContent);
  103. _publishTweetEvent(publishRes.postId);
  104. }
  105. export function showPinTips() {
  106. getChromeStorage('pinData', (res) => {
  107. if (!res || res.show) {
  108. let domPop = document.getElementById('de-pin-pop');
  109. domPop.style.display = 'block';
  110. }
  111. })
  112. }
  113. export function addPinedPop() {
  114. let domPop = document.getElementById('de-pin-pop');
  115. if (domPop) {
  116. return;
  117. }
  118. let popWrapper = document.createElement('div');
  119. 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';
  120. popWrapper.id = 'de-pin-pop'
  121. let img = document.createElement('img');
  122. img.src = require("@/assets/img/img-pined-guide.png");
  123. let contentDom = document.createElement('div');
  124. contentDom.innerHTML = "<div style='font-weight: 500;font-size: 18px;margin-top: 20px;margin-bottom: 20px'>📌 Pin an Extension is more convenient to open😄</div><div style='display: flex; align-items: center; justify-content: space-between;'><div style='display: flex; align-items: center; font-size: 14px; color: #899099; cursor: pointer;' id='de-remind'><input id='de-check' type='checkbox'/> Don't remind</div><div class='de-pin-skip' style='font-weight: 500; font-size: 16px; color: #1D9BF0;cursor: pointer;'>Skip</div></div>"
  125. let arrow = document.createElement('div');
  126. arrow.style.cssText = 'position: absolute;height: 15px;width: 15px;top: -8px;right: 80px;border-left: 0.5px solid rgb(145, 145, 145);border-top: 0.5px solid rgb(145, 145, 145);background: rgb(255, 255, 255);transform: rotate(45deg);';
  127. popWrapper.appendChild(arrow);
  128. popWrapper.appendChild(img);
  129. popWrapper.appendChild(contentDom);
  130. document.querySelector('body').appendChild(popWrapper);
  131. let deCheck = document.querySelector('#de-check');
  132. let deRemind = document.querySelector('#de-remind');
  133. deCheck.onclick = function (e) {
  134. e && e.stopPropagation && e.stopPropagation();
  135. setChromeStorage({ pinData: JSON.stringify({ show: !this.checked }) })
  136. }
  137. deRemind.onclick = function () {
  138. deCheck.checked = !deCheck.checked;
  139. setChromeStorage({ pinData: JSON.stringify({ show: !deCheck.checked }) })
  140. }
  141. document.querySelector('.de-pin-skip').onclick = function () {
  142. document.querySelector('#de-pin-pop').style.display = 'none';
  143. }
  144. }
  145. function getUserInfo(cb) {
  146. getChromeStorage('userInfo', (res) => {
  147. cb && cb(res);
  148. })
  149. }
  150. // 绑定推文id所需参数
  151. let bindTwitterArt = {
  152. needBind: false,
  153. postId: '',
  154. isBindIng: false
  155. };
  156. /**
  157. * 监听dialog内点击原生发布按钮事件
  158. * @private
  159. */
  160. function _publishTweetEvent(contentStr, cb) {
  161. setTimeout(() => {
  162. let publishTweetBtn = document.querySelector('div[role="dialog"]').querySelector('div[data-testid="tweetButton"]');
  163. publishTweetBtn.addEventListener('click', function () {
  164. bindTwitterArt.needBind = true;
  165. bindTwitterArt.postId = contentStr;
  166. cb && cb()
  167. });
  168. }, 800)
  169. }
  170. /**
  171. * 在输入推文区插入deNet按钮
  172. * @param parent
  173. * @param dom
  174. * @param isClick
  175. * @private
  176. */
  177. function _addDeNetEditBtn(parent, dom, isClick = false) {
  178. setTimeout(() => {
  179. if (parent && parent.parentNode) {
  180. parent.parentNode.insertBefore(dom, parent.nextElementSibling);
  181. } else {
  182. setTimeout(() => {
  183. parent = _getScheduleDom(isClick);
  184. parent && parent.parentNode && parent.parentNode.insertBefore(dom, parent.nextElementSibling);
  185. }, 1000)
  186. }
  187. })
  188. }
  189. /**
  190. * 在dialog插入deNet按钮
  191. * @private
  192. */
  193. // function _addDeNetBtnToDialog() {
  194. // setTimeout(() => {
  195. // let dialogScheduleBtn = _getScheduleDom(true);
  196. // _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn2);
  197. // }, 800)
  198. // }
  199. /**
  200. * 获取左侧twitter按钮
  201. * @private
  202. */
  203. function _getSliderTwitterBtn() {
  204. dom.tweetBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
  205. dom.tweetBtn.addEventListener('click', function () {
  206. // _addDeNetBtnToDialog();
  207. })
  208. }
  209. /**
  210. * 添加deNet按钮
  211. * @private
  212. */
  213. function _addDeNetBtn() {
  214. setTimeout(() => {
  215. let navWidth = document.querySelector('nav[role="navigation"]').offsetWidth;
  216. addSliderNavDeBtn(navWidth < 245);
  217. let innerDeIcon = document.getElementById('de-btn1');
  218. if (!innerDeIcon) {
  219. let dialogScheduleBtn = _getScheduleDom(false);
  220. _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn1);
  221. }
  222. }, 800)
  223. }
  224. /**
  225. * 获取推文输入框内dom,用于插入deNet
  226. * @param isDialogInner
  227. * @returns {Element}
  228. * @private
  229. */
  230. function _getScheduleDom(isDialogInner = false) {
  231. let scheduleBtn;
  232. if (isDialogInner) {
  233. scheduleBtn = document.querySelector('div[role="dialog"]').querySelector('[data-testid="createPollButton"]');
  234. } else {
  235. let toolBar = document.querySelector('div[data-testid="toolBar"]');
  236. if (toolBar) {
  237. scheduleBtn = toolBar.querySelector('div[data-testid="geoButton"]');
  238. }
  239. }
  240. return scheduleBtn;
  241. }
  242. /**
  243. * 插入iframe到页面
  244. * @private
  245. */
  246. function _addIframe() {
  247. // let span = document.createElement('span');
  248. // const shadowRoot = span.attachShadow({mode: 'closed'})
  249. let iframe = document.createElement('iframe');
  250. iframe.src = chrome.runtime.getURL('/iframe/publish.html')
  251. iframe.id = 'iframe-content'
  252. iframe.style.cssText = 'position:fixed;top:0px;right:0;display:block; width:100%;height:100%;z-index:0; border: medium none;display:none';
  253. // shadowRoot.appendChild(iframe);
  254. // document.body.appendChild(span)
  255. dom.iframe = iframe;
  256. let iframeContent = document.getElementById('iframe-content');
  257. if (!iframeContent) {
  258. document.getElementById('layers').appendChild(iframe);
  259. }
  260. }
  261. /**
  262. * 获取发布推文id
  263. * @returns {string}
  264. * @private
  265. */
  266. /** function _getTwitterArtId(contentStr, cb) {
  267. let id = '';
  268. let timer = setInterval(() => {
  269. let arr = document.querySelectorAll('a') || [];
  270. for (let i = 0; i < arr.length; i++) {
  271. let item = arr[i];
  272. if (item.innerText == '#DeNet') {
  273. if (item.parentNode && item.parentNode.parentNode && item.parentNode.parentNode.innerText.length > 5) {
  274. let _postId = item.parentNode.parentNode.innerText || ''
  275. let _dom = item.parentNode.parentNode.parentNode.parentNode.parentNode
  276. let regex = new RegExp(contentStr);
  277. if (regex.test(_postId)) {
  278. id = _dom.children[0].querySelector('a[dir="auto"]').getAttribute('href').split('/status/')[1];
  279. clearInterval(timer);
  280. if (id) {
  281. cb && cb(id);
  282. }
  283. break;
  284. }
  285. }
  286. }
  287. }
  288. }, 1000);
  289. }
  290. */
  291. /**
  292. * 点击deNet按钮处理
  293. * @private
  294. */
  295. function _deNetBtnClick(port) {
  296. getUserInfo((res) => {
  297. if (res) {
  298. if (window.location.pathname != '/home') {
  299. if (!dom.homeBtn) {
  300. dom.homeBtn = document.querySelector('a[data-testid="AppTabBar_Home_Link"]');
  301. }
  302. dom.homeBtn.click();
  303. }
  304. showGiveDialogHandler(res);
  305. } else {
  306. let loadIcon = document.getElementById('de-btn-loading');
  307. if (loadIcon) {
  308. return;
  309. }
  310. dom.deBtn.insertBefore(dom.loadingImg, dom.deBtn.querySelector('span'));
  311. setTimeout(() => {
  312. dom.loadingImg.style.transform = 'rotate(1080deg)'
  313. });
  314. setTimeout(() => {
  315. dom.loadingImg.style.transform = 'rotate(0deg)'
  316. dom.deBtn.innerHTML = '<span>DeNet<span>';
  317. }, 3000)
  318. port.postMessage({ state: 'CONTENT_TWITTER_LOGIN' })
  319. }
  320. })
  321. }
  322. /**
  323. * 设置发布内容
  324. * @param content
  325. * @private
  326. */
  327. let isSetContent = false;
  328. function _setPublishContent(content) {
  329. if (!isSetContent) {
  330. isSetContent = true;
  331. setTimeout(() => {
  332. document.execCommand("insertText", false, content);
  333. setTimeout(() => {
  334. isSetContent = false;
  335. }, 2000)
  336. }, 1000);
  337. }
  338. }
  339. /**
  340. * 创建deNet按钮 添加到页面
  341. * @returns {{deBtn2: HTMLDivElement, deBtn1: HTMLDivElement, deBtn: HTMLSpanElement}}
  342. * @private
  343. */
  344. function _createBtnDom(port) {
  345. let loadingImg = document.createElement('img');
  346. loadingImg.id = 'de-btn-loading'
  347. loadingImg.src = require("@/assets/img/icon-btn-loading.png");
  348. loadingImg.style.cssText = 'width:20px;height: 20px;margin-right:3px;transition-duration: 3s;';
  349. let style = document.createElement('style');
  350. style.innerHTML = "#de-btn:hover{opacity: .9;};@-webkit-keyframes load{from{ transform: rotate(0deg);} to{transform: rotate(360deg);}}";
  351. document.getElementsByTagName('head').item(0).appendChild(style);
  352. let deBtn = document.createElement('span');
  353. // const shadowDiv = document.createElement('div');
  354. deBtn.innerHTML = '<span>DeNet</span>';
  355. deBtn.id = 'de-btn';
  356. 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;';
  357. const deBtn1 = document.createElement('img');
  358. let src = require("@/assets/img/icon-gift-pack.png");
  359. const smallDeBtnStyle = 'width:20px;height: 20px;cursor: pointer;marign-left:4px;margin-right:4px';
  360. deBtn1.id = 'de-btn1';
  361. deBtn1.style.cssText = smallDeBtnStyle;
  362. deBtn1.src = src
  363. const deBtn2 = document.createElement('div');
  364. deBtn2.id = 'de-btn2';
  365. deBtn2.style.cssText = smallDeBtnStyle;
  366. deBtn2.src = "@/assets/img/icon-gift-pack.png"
  367. const deBtn3 = document.createElement('img');
  368. deBtn3.id = 'de-btn3'
  369. deBtn3.src = require("@/assets/logo/128.png");
  370. deBtn3.style.cssText = 'width:52px;height: 52px;margin-top:20px;cursor: pointer;';
  371. deBtn.addEventListener('click', () => {
  372. _deNetBtnClick(port);
  373. })
  374. deBtn1.addEventListener('click', () => {
  375. _deNetBtnClick(port);
  376. })
  377. deBtn2.addEventListener('click', () => {
  378. _deNetBtnClick(port);
  379. })
  380. deBtn3.addEventListener('click', () => {
  381. _deNetBtnClick(port);
  382. })
  383. dom.deBtn = deBtn;
  384. dom.deBtn1 = deBtn1;
  385. dom.deBtn2 = deBtn2;
  386. dom.deBtn3 = deBtn3;
  387. dom.loadingImg = loadingImg;
  388. }
  389. function addSliderNavDeBtn(isSmall = false) {
  390. if (!isSmall) {
  391. let bigDom = document.querySelector('h1[role]').parentNode.parentNode;
  392. let deBtn = document.getElementById('de-btn');
  393. if (bigDom && !deBtn) {
  394. bigDom.appendChild(dom.deBtn);
  395. }
  396. } else {
  397. let smallDom = document.querySelector('h1[role]').parentNode.parentNode;
  398. let deBtn3 = document.getElementById('de-btn3');
  399. if (smallDom && !deBtn3) {
  400. smallDom.appendChild(dom.deBtn3);
  401. }
  402. }
  403. }
  404. function onWindowResize() {
  405. window.onresize = throttle(function () {
  406. try {
  407. if (window.innerWidth < 1273) {
  408. let bigBtn = document.querySelector('#de-btn');
  409. bigBtn && bigBtn.remove();
  410. setTimeout(() => {
  411. addSliderNavDeBtn(true);
  412. })
  413. } else {
  414. let smallBtn = document.querySelector('#de-btn3');
  415. smallBtn && smallBtn.remove();
  416. setTimeout(() => {
  417. addSliderNavDeBtn()
  418. })
  419. }
  420. } catch (e) {
  421. console.log(e)
  422. }
  423. }, 800)
  424. }
  425. function checkHasDeBtn() {
  426. setInterval(() => {
  427. try {
  428. let toolBar = document.querySelector('div[data-testid="toolBar"]');
  429. let innerDeIcon = document.getElementById('de-btn1');
  430. if (toolBar && !innerDeIcon) {
  431. let dialogScheduleBtn = _getScheduleDom(false);
  432. _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn1);
  433. }
  434. } catch (e) {
  435. console.log(e)
  436. }
  437. }, 1000)
  438. }
  439. /**
  440. * 根据postID绑定推文id
  441. */
  442. function bindTwitterArtMethod({ postId, twitterId }) {
  443. let regex = new RegExp(bindTwitterArt.postId);
  444. if (regex.test(postId)) {
  445. if (twitterId && bindTwitterArt.needBind && !bindTwitterArt.isBindIng) {
  446. bindTwitterArt.isBindIng = true;
  447. srcPublishSuccess({
  448. params: {
  449. postId: postId,
  450. srcContentId: twitterId
  451. }
  452. }).then((res) => {
  453. if (res.code == 0) {
  454. bindTwitterArt.needBind = false;
  455. bindTwitterArt.postId = '';
  456. bindTwitterArt.isBindIng = false;
  457. }
  458. })
  459. }
  460. }
  461. }
  462. function parseDOMRedPacket() {
  463. let _dom = null
  464. let arr = document.querySelectorAll('a') || []
  465. let _type = ''
  466. for (let i in arr) {
  467. if (arr[i].innerText == '#DeNet') {
  468. let _tweetId = ''
  469. let _article = arr[i].closest('article')
  470. let _txt_area = _article.querySelector('[lang][dir=auto]')
  471. let _postId = _txt_area.innerText
  472. _postId = _postId.match(/###([\s\S]*?)###/)[1]
  473. _dom = _article.querySelector('div[aria-labelledby]')
  474. if (_dom) {
  475. _type = 'card'
  476. } else {
  477. _type = 'parnet'
  478. _dom = _txt_area
  479. }
  480. let _a_area = _article.querySelector('a[aria-label]')
  481. if (_a_area && _a_area.getAttribute('href')) {
  482. _tweetId = _a_area.getAttribute('href').split('/status/')[1] || ''
  483. if (bindTwitterArt.needBind) {
  484. bindTwitterArtMethod({ postId: _postId, twitterId: _tweetId });
  485. }
  486. }
  487. replaceDOMRedPacket(_type, _dom, _postId, _tweetId)
  488. }
  489. }
  490. }
  491. function createIframe(postId, tweetId) {
  492. let _iframe = document.createElement('iframe')
  493. _iframe.id = postId
  494. _iframe.src = chrome.runtime.getURL('/iframe/red-packet.html') + `?postId=${postId}&tweetId=${tweetId}`;
  495. _iframe.style.cssText = 'border: medium none; width:375px;height:500px;'
  496. return _iframe
  497. }
  498. function replaceDOMRedPacket(_type, _dom, postId, tweetId) {
  499. if (!_dom || !_dom.parentElement) {
  500. return
  501. }
  502. if (_type == 'card' && !_dom.querySelector('iframe') && _dom.closest('article').querySelector('iframe')) {
  503. _dom.style.display = 'none'
  504. return
  505. }
  506. if (_dom.parentElement.querySelector('iframe')) {
  507. return
  508. }
  509. if (_type == 'card') {
  510. let _len
  511. _len = _dom.childNodes.length
  512. for (let i = 0; i < _len; i++) {
  513. _dom.children[i].style.display = 'none'
  514. }
  515. _dom.style = 'height:500px'
  516. _dom.appendChild(createIframe(postId, tweetId))
  517. } else {
  518. let _parent = _dom.parentNode
  519. _parent.appendChild(createIframe(postId, tweetId))
  520. }
  521. }
  522. export function setIframeRedPacket() {
  523. // let elment = document.documentElement
  524. if (window.location.href.includes('https://twitter.com)')) {
  525. return
  526. }
  527. // const observer = new MutationObserver(callback);
  528. parseDOMRedPacket()
  529. // let _current_top = 0
  530. setInterval(() => {
  531. parseDOMRedPacket()
  532. }, 1000)
  533. }