twitter.js 16 KB

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