twitter.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. import { getChromeStorage, setChromeStorage } from '@/uilts/chromeExtension.js'
  2. import { throttle, getQueryString } from '@/uilts/help'
  3. import { discordAuthRedirectUri } from '@/http/configAPI'
  4. import { reportSrcPublishEvent } from '@/http/publishApi'
  5. import Report from "@/log-center/log"
  6. let dom = {};
  7. function twitterPinLogin() {
  8. if (window.location.href == 'https://api.twitter.com/oauth/authorize') {
  9. let code = document.querySelector('code')
  10. if (code) {
  11. chrome.runtime.sendMessage({ actionType: "CONTENT_SEND_CODE", code: code.innerText }, () => { })
  12. // port.postMessage({ state: 'CONTENT_SEND_CODE', code: code.innerText })
  13. }
  14. }
  15. }
  16. function getDiscordAuthCode() {
  17. if (window.location.href.indexOf(discordAuthRedirectUri) > -1) {
  18. const urlParams = new URLSearchParams(window.location.search);
  19. const code = urlParams.get('code');
  20. if (code) {
  21. chrome.runtime.sendMessage({ actionType: "CONTENT_SEND_DISCORD_AUTH_CODE", code }, () => { })
  22. }
  23. }
  24. };
  25. /**
  26. * 渲染要插入的dom,初始化逻辑
  27. * @param port
  28. */
  29. function renderDom() {
  30. if (window.location.href.indexOf('https://twitter.com') > -1) {
  31. _createBtnDom();
  32. onWindowResize();
  33. checkHasDeBtn();
  34. setTimeout(() => {
  35. _addIframe();
  36. _addDeNetBtn();
  37. _getSliderTwitterBtn();
  38. }, 800)
  39. }
  40. }
  41. /**
  42. * 展示give弹窗
  43. */
  44. export function showGiveDialogHandler(userInfo) {
  45. let iframe = document.getElementById('iframe-content');
  46. if (iframe) {
  47. iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', userInfo }, '*');
  48. } else {
  49. _addIframe();
  50. let iframe = document.getElementById('iframe-content');
  51. iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', userInfo }, '*');
  52. }
  53. }
  54. export function showIframeHandler() {
  55. document.getElementById('iframe-content').style.display = 'block';
  56. }
  57. export function hideIframeHandler() {
  58. document.getElementById('iframe-content').style.display = 'none';
  59. }
  60. /**
  61. * 展示twitter原生发布框
  62. */
  63. export function showTwitterPublishDialogHandler(publishRes) {
  64. dom.tweetBtn.click();
  65. _setPublishContent(publishRes.srcContent);
  66. _publishTweetEvent(publishRes.postId, bindTwitterArtMethod);
  67. }
  68. export function showPinTips() {
  69. getChromeStorage('pinData', (res) => {
  70. if (!res || res.show) {
  71. let domPop = document.getElementById('de-pin-pop');
  72. domPop.style.display = 'block';
  73. }
  74. })
  75. }
  76. function addPinedPop() {
  77. let domPop = document.getElementById('de-pin-pop');
  78. if (domPop) {
  79. return;
  80. }
  81. let popWrapper = document.createElement('div');
  82. 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';
  83. popWrapper.id = 'de-pin-pop'
  84. let img = document.createElement('img');
  85. img.src = require("@/assets/img/img-pined-guide.png");
  86. let contentDom = document.createElement('div');
  87. 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>"
  88. popWrapper.appendChild(img);
  89. popWrapper.appendChild(contentDom);
  90. document.querySelector('body').appendChild(popWrapper);
  91. let deCheck = document.querySelector('#de-check');
  92. let deRemind = document.querySelector('#de-remind');
  93. deCheck.onclick = function (e) {
  94. e && e.stopPropagation && e.stopPropagation();
  95. setChromeStorage({ pinData: JSON.stringify({ show: !this.checked }) })
  96. }
  97. deRemind.onclick = function () {
  98. deCheck.checked = !deCheck.checked;
  99. setChromeStorage({ pinData: JSON.stringify({ show: !deCheck.checked }) })
  100. }
  101. document.querySelector('.de-pin-skip').onclick = function () {
  102. document.querySelector('#de-pin-pop').style.display = 'none';
  103. }
  104. }
  105. function getUserInfo(cb) {
  106. getChromeStorage('userInfo', (res) => {
  107. cb && cb(res);
  108. })
  109. }
  110. // 绑定推文id所需参数
  111. let bindTwitterArt = {
  112. needBind: false,
  113. postId: '',
  114. isBindIng: false
  115. };
  116. /**
  117. * 监听dialog内点击原生发布按钮事件
  118. * @private
  119. */
  120. function _publishTweetEvent(contentStr, cb) {
  121. setTimeout(() => {
  122. let publishTweetBtn;
  123. let dialog = document.querySelector('div[role="dialog"]');
  124. if (dialog) {
  125. publishTweetBtn = dialog.querySelector('div[data-testid="tweetButton"]');
  126. } else {
  127. let domMain = document.querySelector('main[role="main"]');
  128. publishTweetBtn = domMain && domMain.querySelector('div[data-testid="tweetButton"]');
  129. }
  130. publishTweetBtn && publishTweetBtn.addEventListener('click', function () {
  131. bindTwitterArt.needBind = true;
  132. bindTwitterArt.postId = contentStr;
  133. cb && cb()
  134. });
  135. }, 800)
  136. }
  137. /**
  138. * 在输入推文区插入deNet按钮
  139. * @param parent
  140. * @param dom
  141. * @param isClick
  142. * @private
  143. */
  144. function _addDeNetEditBtn(parent, dom, isClick = false) {
  145. setTimeout(() => {
  146. if (parent && parent.parentNode) {
  147. Report.reportLog({
  148. pageSource: Report.pageSource.mainPage,
  149. businessType: Report.businessType.buttonView,
  150. objectType: Report.objectType.buttonSecond
  151. });
  152. parent.parentNode.insertBefore(dom, parent.nextElementSibling);
  153. } else {
  154. setTimeout(() => {
  155. parent = _getScheduleDom(isClick);
  156. if (parent && parent.parentNode) {
  157. Report.reportLog({
  158. pageSource: Report.pageSource.mainPage,
  159. businessType: Report.businessType.buttonView,
  160. objectType: Report.objectType.buttonSecond
  161. });
  162. let innerDeIcon = document.getElementById('de-btn1');
  163. if (!innerDeIcon) {
  164. parent.parentNode.insertBefore(dom, parent.nextElementSibling);
  165. }
  166. }
  167. }, 1000)
  168. }
  169. })
  170. }
  171. /**
  172. * 在dialog插入deNet按钮
  173. * @private
  174. */
  175. // function _addDeNetBtnToDialog() {
  176. // setTimeout(() => {
  177. // let dialogScheduleBtn = _getScheduleDom(true);
  178. // _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn2);
  179. // }, 800)
  180. // }
  181. /**
  182. * 获取左侧twitter按钮
  183. * @private
  184. */
  185. function _getSliderTwitterBtn() {
  186. dom.tweetBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
  187. dom.tweetBtn.addEventListener('click', function () {
  188. // _addDeNetBtnToDialog();
  189. })
  190. }
  191. /**
  192. * 添加deNet按钮
  193. * @private
  194. */
  195. function _addDeNetBtn() {
  196. setTimeout(() => {
  197. let navWidth = document.querySelector('nav[role="navigation"]').offsetWidth;
  198. addSliderNavDeBtn(navWidth < 245);
  199. let innerDeIcon = document.getElementById('de-btn1');
  200. if (!innerDeIcon) {
  201. let dialogScheduleBtn = _getScheduleDom(false);
  202. _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn1);
  203. }
  204. }, 800)
  205. }
  206. /**
  207. * 获取推文输入框内dom,用于插入deNet
  208. * @param isDialogInner
  209. * @returns {Element}
  210. * @private
  211. */
  212. function _getScheduleDom(isDialogInner = false) {
  213. let scheduleBtn;
  214. if (isDialogInner) {
  215. scheduleBtn = document.querySelector('div[role="dialog"]').querySelector('[data-testid="createPollButton"]');
  216. } else {
  217. let toolBar = document.querySelector('div[data-testid="toolBar"]');
  218. if (toolBar) {
  219. scheduleBtn = toolBar.querySelector('div[data-testid="geoButton"]');
  220. }
  221. }
  222. return scheduleBtn;
  223. }
  224. /**
  225. * 插入iframe到页面
  226. * @private
  227. */
  228. function _addIframe() {
  229. // let span = document.createElement('span');
  230. // const shadowRoot = span.attachShadow({mode: 'closed'})
  231. let iframe = document.createElement('iframe');
  232. iframe.src = chrome.runtime.getURL('/iframe/publish.html')
  233. iframe.id = 'iframe-content'
  234. iframe.style.cssText = 'position:fixed;top:0px;right:0;display:block; width:100%;height:100%;z-index:10000; border: medium none;display:none';
  235. // shadowRoot.appendChild(iframe);
  236. // document.body.appendChild(span)
  237. dom.iframe = iframe;
  238. let iframeContent = document.getElementById('iframe-content');
  239. if (!iframeContent) {
  240. document.getElementById('layers').appendChild(iframe);
  241. }
  242. }
  243. /**
  244. * 点击deNet按钮处理
  245. * @private
  246. */
  247. function _deNetBtnClick() {
  248. getUserInfo((res) => {
  249. if (res) {
  250. if (window.location.pathname != '/home') {
  251. if (!dom.homeBtn) {
  252. dom.homeBtn = document.querySelector('a[data-testid="AppTabBar_Home_Link"]');
  253. }
  254. dom.homeBtn.click();
  255. }
  256. showGiveDialogHandler(res);
  257. } else {
  258. let loadIcon = document.getElementById('de-btn-loading');
  259. if (loadIcon) {
  260. return;
  261. }
  262. dom.deBtn.insertBefore(dom.loadingImg, dom.deBtn.querySelector('span'));
  263. setTimeout(() => {
  264. dom.loadingImg.style.transform = 'rotate(1080deg)'
  265. });
  266. setTimeout(() => {
  267. dom.loadingImg.style.transform = 'rotate(0deg)'
  268. dom.deBtn.innerHTML = '<span>DeNet<span>';
  269. }, 2000)
  270. chrome.runtime.sendMessage({ actionType: "CONTENT_TWITTER_LOGIN", data: '1' }, (res) => { console.log(res) })
  271. }
  272. })
  273. }
  274. /**
  275. * 设置发布内容
  276. * @param content
  277. * @private
  278. */
  279. let isSetContent = false;
  280. const _setPublishContent = throttle(function (content) {
  281. if (!isSetContent) {
  282. isSetContent = true;
  283. setTimeout(() => {
  284. document.execCommand("insertText", false, content);
  285. setTimeout(() => {
  286. isSetContent = false;
  287. }, 2000)
  288. }, 1000);
  289. }
  290. }, 800);
  291. /**
  292. * 创建deNet按钮 添加到页面
  293. * @returns {{deBtn2: HTMLDivElement, deBtn1: HTMLDivElement, deBtn: HTMLSpanElement}}
  294. * @private
  295. */
  296. function _createBtnDom() {
  297. let loadingImg = document.createElement('img');
  298. loadingImg.id = 'de-btn-loading'
  299. loadingImg.src = require("@/assets/img/icon-btn-loading.png");
  300. loadingImg.style.cssText = 'width:20px;height: 20px;margin-right:3px;transition-duration: 3s;';
  301. let style = document.createElement('style');
  302. style.innerHTML = "#de-btn:hover{opacity: .9;};@-webkit-keyframes load{from{ transform: rotate(0deg);} to{transform: rotate(360deg);}}";
  303. document.getElementsByTagName('head').item(0).appendChild(style);
  304. // 左侧大屏按钮
  305. let deBtn = document.createElement('span');
  306. // const shadowDiv = document.createElement('div');
  307. deBtn.innerHTML = '<span>DeNet</span>';
  308. deBtn.id = 'de-btn';
  309. 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;';
  310. // 编辑框内按钮
  311. const deBtn1 = document.createElement('img');
  312. let src = require("@/assets/img/icon-gift-pack.png");
  313. const smallDeBtnStyle = 'width:20px;height: 20px;cursor: pointer;padding: 0px 8px';
  314. deBtn1.id = 'de-btn1';
  315. deBtn1.style.cssText = smallDeBtnStyle;
  316. deBtn1.src = src
  317. const deBtn2 = document.createElement('div');
  318. deBtn2.id = 'de-btn2';
  319. deBtn2.style.cssText = smallDeBtnStyle;
  320. deBtn2.src = "@/assets/img/icon-gift-pack.png"
  321. // 小屏按钮
  322. const deBtn3 = document.createElement('img');
  323. deBtn3.id = 'de-btn3'
  324. deBtn3.src = require("@/assets/logo/128.png");
  325. deBtn3.style.cssText = 'width:52px;height: 52px;margin-top:20px;cursor: pointer;';
  326. deBtn.addEventListener('click', () => {
  327. // chrome.runtime.sendMessage({
  328. // actionType: 'CONTENT_SET_BADGE',
  329. // data: {
  330. // text: '2'
  331. // }
  332. // }, res => {
  333. // console.log(res);
  334. // })
  335. Report.reportLog({
  336. pageSource: Report.pageSource.mainPage,
  337. businessType: Report.businessType.buttonClick,
  338. objectType: Report.objectType.buttonMain
  339. });
  340. _deNetBtnClick();
  341. })
  342. deBtn1.addEventListener('click', () => {
  343. Report.reportLog({
  344. pageSource: Report.pageSource.mainPage,
  345. businessType: Report.businessType.buttonClick,
  346. objectType: Report.objectType.buttonSecond
  347. });
  348. _deNetBtnClick();
  349. })
  350. deBtn2.addEventListener('click', () => {
  351. _deNetBtnClick();
  352. })
  353. deBtn3.addEventListener('click', () => {
  354. Report.reportLog({
  355. pageSource: Report.pageSource.mainPage,
  356. businessType: Report.businessType.buttonClick,
  357. objectType: Report.objectType.buttonMain
  358. });
  359. _deNetBtnClick();
  360. })
  361. dom.deBtn = deBtn;
  362. dom.deBtn1 = deBtn1;
  363. dom.deBtn2 = deBtn2;
  364. dom.deBtn3 = deBtn3;
  365. dom.loadingImg = loadingImg;
  366. }
  367. function addSliderNavDeBtn(isSmall = false) {
  368. if (!isSmall) {
  369. let bigDom = document.querySelector('a[href="/compose/tweet"]').parentNode.parentNode;
  370. let deBtn = document.getElementById('de-btn');
  371. if (bigDom && !deBtn) {
  372. bigDom.appendChild(dom.deBtn);
  373. Report.reportLog({
  374. pageSource: Report.pageSource.mainPage,
  375. businessType: Report.businessType.buttonView,
  376. objectType: Report.objectType.buttonMain
  377. });
  378. }
  379. } else {
  380. let smallDom = document.querySelector('a[href="/compose/tweet"]').parentNode.parentNode;
  381. let deBtn3 = document.getElementById('de-btn3');
  382. if (smallDom && !deBtn3) {
  383. smallDom.appendChild(dom.deBtn3);
  384. Report.reportLog({
  385. pageSource: Report.pageSource.mainPage,
  386. businessType: Report.businessType.buttonView,
  387. objectType: Report.objectType.buttonMain
  388. });
  389. }
  390. }
  391. }
  392. function onWindowResize() {
  393. window.onresize = throttle(function () {
  394. try {
  395. if (window.innerWidth < 1273) {
  396. let bigBtn = document.querySelector('#de-btn');
  397. bigBtn && bigBtn.remove();
  398. setTimeout(() => {
  399. addSliderNavDeBtn(true);
  400. })
  401. } else {
  402. let smallBtn = document.querySelector('#de-btn3');
  403. smallBtn && smallBtn.remove();
  404. setTimeout(() => {
  405. addSliderNavDeBtn()
  406. })
  407. }
  408. } catch (e) {
  409. console.log(e)
  410. }
  411. }, 800)
  412. }
  413. function checkHasDeBtn() {
  414. try {
  415. let toolBar = document.querySelector('div[data-testid="toolBar"]');
  416. let innerDeIcon = document.getElementById('de-btn1');
  417. if (toolBar && !innerDeIcon) {
  418. let dialogScheduleBtn = _getScheduleDom(false);
  419. _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn1);
  420. }
  421. } catch (e) {
  422. console.log(e)
  423. }
  424. }
  425. /**
  426. * 点击发推,后端绑定推特id
  427. */
  428. function bindTwitterArtMethod() {
  429. if (!bindTwitterArt.postId) {
  430. return
  431. }
  432. if (bindTwitterArt.needBind && !bindTwitterArt.isBindIng) {
  433. bindTwitterArt.isBindIng = true;
  434. reportSrcPublishEvent({
  435. params: {
  436. postId: bindTwitterArt.postId,
  437. }
  438. }).then((res) => {
  439. if (res.code == 0) {
  440. Report.reportLog({
  441. objectType: Report.objectType.tweetPostBinded
  442. });
  443. bindTwitterArt.needBind = false;
  444. bindTwitterArt.postId = '';
  445. bindTwitterArt.isBindIng = false;
  446. }
  447. })
  448. }
  449. }
  450. import parseCard from './ParseCard'
  451. // 检测dom改变
  452. // 获取短链接
  453. // 查看本地是否有postid
  454. // 如果有 修改dom 返回
  455. // 如果没有 网络请求
  456. // 获取postid
  457. // 获取twitterid
  458. // 检测当前所有dom 如果没有
  459. let queue_num = 1
  460. export const changeQueueNum = (num = 0) => {
  461. queue_num = queue_num + num
  462. if (queue_num > 5) {
  463. queue_num = 5
  464. }
  465. }
  466. let main_observer = null
  467. function onChangePageMain(targetNode) {
  468. try {
  469. const config = { attributes: false, childList: true, subtree: true };
  470. const callback = (mutationsList, observer) => {
  471. changeQueueNum(1)
  472. }
  473. main_observer = new MutationObserver(callback);
  474. main_observer.observe(targetNode, config);
  475. } catch (error) {
  476. main_observer = null
  477. }
  478. }
  479. // 1.监听main改变
  480. // 2.监听卡片是否可见
  481. // 3.如果可见了 去找
  482. function setIframeRedPacket() {
  483. // 获取所有卡片参数
  484. let card_json_data = parseCard.parseAllDeNetCardParmas()
  485. // 过滤出可以请求的短链接
  486. parseCard.getCardParmas(card_json_data).then((res) => {
  487. for (let i in res.has_post_Id_card_data) {
  488. parseCard.replaceDOMRedPacket(res.has_post_Id_card_data[i])
  489. }
  490. if (res.need_net_short_url.length > 0) {
  491. // 请求短链接
  492. chrome.runtime.sendMessage({ actionType: "CONTENT_TWITTER_SHORT_LINK", data: "", arr_url: res.need_net_short_url }, () => { })
  493. }
  494. })
  495. }
  496. // 监听点击发推 按钮绑定事件
  497. // document.addEventListener('click', (e) => {
  498. // try {
  499. // if (e.target.dataset && e.target.dataset.testid && e.target.dataset.testid == 'tweetButton') {
  500. // bindTwitterArtMethod()
  501. // } else if (e.target.closest('div[data-testid=tweetButton]')) {
  502. // bindTwitterArtMethod()
  503. // }
  504. // } catch (error) {
  505. // console.error('error', error)
  506. // }
  507. // })
  508. export function initExecuteScript(changes) {
  509. if (changes.executeScript) {
  510. let item = JSON.parse(changes.executeScript.newValue)
  511. if (item.executeScript) {
  512. init()
  513. }
  514. }
  515. }
  516. const createIframe = ({ url, tweet_Id }, callback) => {
  517. let iframe = document.createElement('iframe')
  518. iframe.id = `tweetId${tweet_Id}`
  519. iframe.src = url
  520. iframe.onload = () => {
  521. callback()
  522. }
  523. }
  524. // 初始化
  525. export function init() {
  526. getDiscordAuthCode();
  527. if (window.location.href.indexOf('twitter.com') < 0) {
  528. return
  529. }
  530. twitterPinLogin();
  531. // 渲染dom
  532. let targetNode = null
  533. let timer = setInterval(() => {
  534. targetNode = document.querySelector('main')
  535. if (targetNode) {
  536. clearInterval(timer)
  537. setInterval(() => {
  538. if (window.location.href.includes('twitter.com)')) {
  539. return
  540. }
  541. if (!main_observer) {
  542. onChangePageMain(targetNode)
  543. changeQueueNum(1)
  544. }
  545. if (queue_num <= 0) {
  546. return
  547. }
  548. setIframeRedPacket()
  549. checkHasDeBtn()
  550. changeQueueNum(-1)
  551. }, 1000)
  552. }
  553. }, 1000);
  554. renderDom();
  555. checkTwitterTaskState()
  556. getChromeStorage("popupShowPublishDialog", (res) => {
  557. console.log("popupShowPublishDialog", res);
  558. if (res && res.show) {
  559. setTimeout(() => {
  560. showTwitterPublishDialogHandler({
  561. srcContent: res.srcContent,
  562. postId: res.postId
  563. });
  564. }, 1500);
  565. chrome.storage.local.remove("popupShowPublishDialog");
  566. }
  567. });
  568. getChromeStorage("userSettings", (res) => {
  569. addPinedPop();
  570. if (res && !res.isOnToolbar) {
  571. setTimeout(() => {
  572. showPinTips();
  573. chrome.storage.local.remove("userSettings");
  574. }, 800);
  575. }
  576. });
  577. }
  578. // 根据推特id找到dom,完成任务
  579. export function findTweetByIdDoTask({ tweet_Id = '', follow_names = [] }, task_type = 'like') {
  580. // 1.根据推特ID寻找推文,获取卡片
  581. // 获取所有卡片参数
  582. let card_json_data = parseCard.parseAllDeNetCardParmas()
  583. let result = card_json_data.filter((item) => { return item.tweet_Id == tweet_Id }) || []
  584. if (result.length < 1) {
  585. return
  586. }
  587. result = result[0]
  588. switch (task_type) {
  589. case 'like':
  590. // https://twitter.com/intent/retweet?tweet_id=1525900221628223491
  591. if (result.dom_card) {
  592. result.dom_card.querySelector('div[data-testid=like]').click()
  593. result.dom_card.querySelector('iframe').contentWindow.postMessage({ actionType: 'CONTENT_DONE_TASK', task_type, }, '*');
  594. }
  595. break;
  596. case 'retweet':
  597. if (result.dom_card) {
  598. result.dom_card.querySelector('div[data-testid=retweet]').click()
  599. result.dom_card.querySelector('div[data-testid=retweetConfirm]').click()
  600. }
  601. break
  602. case 'follow':
  603. follow_names.forEach((item) => {
  604. window.open(`https://twitter.com/intent/follow?screen_name=${item}&tweet_Id=${tweet_Id}`)
  605. })
  606. break
  607. }
  608. }
  609. function clickByDataTestId(e, id, callback) {
  610. if (e.target.dataset && e.target.dataset.testid && e.target.dataset.testid == id) {
  611. callback()
  612. } else if (e.target.closest('div[data-testid=' + id + ']')) {
  613. callback()
  614. }
  615. }
  616. // 校验关注推特状态
  617. export function checkTwitterTaskState() {
  618. let task_type = ''
  619. let url = window.location.href
  620. let tweet_Id
  621. let task_data = {
  622. follow_name: ''
  623. }
  624. // 校验当前链接
  625. if (url.includes('https://twitter.com/intent/retweet')) {
  626. task_type = 'retweet'
  627. } else if (url.includes('https://twitter.com/intent/follow')) {
  628. task_type = 'follow'
  629. task_data.follow_name = getQueryString('screen_name')
  630. } else if (url.includes('https://twitter.com/intent/like')) {
  631. task_type = 'like'
  632. } else {
  633. return
  634. }
  635. tweet_Id = getQueryString('tweet_id')
  636. // let root_status
  637. document.body.addEventListener('click', (e) => {
  638. // 点击 确认
  639. clickByDataTestId(e, 'confirmationSheetConfirm', () => {
  640. chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: true }, () => { })
  641. })
  642. // 点击取消
  643. clickByDataTestId(e, 'confirmationSheetCancel', () => {
  644. chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: false }, () => { })
  645. })
  646. // 点击 蒙层
  647. if (e.target && e.target.nextSibling && e.target.nextSibling.dataset && e.target.nextSibling.dataset.testid == 'confirmationSheetDialog') {
  648. chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: false }, () => { })
  649. }
  650. }, true)
  651. let timer = setInterval(() => {
  652. // 喜欢
  653. if (document.querySelector('div[data-testid=unlike]') && task_type == 'like') {
  654. clearInterval(timer)
  655. chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: true }, () => { })
  656. }
  657. // 转推
  658. if (document.querySelector('div[data-testid=unretweet]') && task_type == 'retweet') {
  659. clearInterval(timer)
  660. chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: true }, () => { })
  661. }
  662. // 关注
  663. if (task_type == 'follow') {
  664. let follow_area = document.querySelector('div[data-testid=placementTracking]')
  665. if (follow_area && follow_area.querySelectorAll('div')) {
  666. follow_area = follow_area.querySelectorAll('div')
  667. clearInterval(timer)
  668. for (let i in follow_area) {
  669. if (follow_area[i] && follow_area[i].dataset && follow_area[i].dataset.testid && follow_area[i].dataset.testid.indexOf('unfollow') > 0) {
  670. chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: true }, () => { })
  671. break
  672. }
  673. }
  674. }
  675. }
  676. }, 1000)
  677. }