twitter.js 18 KB

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