twitter.js 18 KB

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