twitter.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. /* eslint-disable */
  2. import { getChromeStorage, setChromeStorage,LANDING_PAGE } from '../uilts/chromeExtension.js'
  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. setTimeout(() => {
  70. _addIframe();
  71. _addDeNetBtn();
  72. _getSliderTwitterBtn();
  73. }, 800)
  74. }
  75. }
  76. /**
  77. * 展示give弹窗
  78. */
  79. export function showGiveDialogHandler(userInfo) {
  80. dom.iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', userInfo }, '*');
  81. }
  82. export function showIframeHandler() {
  83. dom.iframe.style.display = 'block';
  84. }
  85. export function hideIframeHandler() {
  86. dom.iframe.style.display = 'none';
  87. }
  88. /**
  89. * 展示twitter原生发布框
  90. */
  91. export function showTwitterPublishDialogHandler(publishRes) {
  92. dom.tweetBtn.click();
  93. _setPublishContent(publishRes.srcContent);
  94. _publishTweetEvent(publishRes.postId, (twitterArtId) => {
  95. if (twitterArtId) {
  96. getUserInfo((userInfo) => {
  97. if (userInfo) {
  98. srcPublishSuccess({
  99. baseInfo: {
  100. token: userInfo.accessToken
  101. },
  102. params: {
  103. postId: publishRes.postId,
  104. srcContentId: twitterArtId
  105. }
  106. }).then((res) => {
  107. })
  108. }
  109. })
  110. }
  111. });
  112. }
  113. function getUserInfo(cb) {
  114. getChromeStorage('userInfo', (res) => {
  115. cb && cb(res);
  116. })
  117. }
  118. /**
  119. * 监听dialog内点击原生发布按钮事件
  120. * @private
  121. */
  122. function _publishTweetEvent(contentStr, cb) {
  123. setTimeout(() => {
  124. let publishTweetBtn = document.querySelector('div[role="dialog"]').querySelector('div[data-testid="tweetButton"]');
  125. publishTweetBtn.addEventListener('click', function () {
  126. setTimeout(() => {
  127. _getTwitterArtId(contentStr, (twitterArtId) => {
  128. cb && cb(twitterArtId)
  129. });
  130. }, 1500)
  131. });
  132. }, 800)
  133. }
  134. /**
  135. * 在输入推文区插入deNet按钮
  136. * @param parent
  137. * @param dom
  138. * @param isClick
  139. * @private
  140. */
  141. function _addDeNetEditBtn(parent, dom, isClick = false) {
  142. setTimeout(() => {
  143. if (parent) {
  144. parent.parentNode.insertBefore(dom, parent.nextElementSibling);
  145. } else {
  146. setTimeout(() => {
  147. parent = _getScheduleDom(isClick);
  148. parent.parentNode.insertBefore(dom, parent.nextElementSibling);
  149. }, 1000)
  150. }
  151. })
  152. }
  153. /**
  154. * 在dialog插入deNet按钮
  155. * @private
  156. */
  157. function _addDeNetBtnToDialog() {
  158. setTimeout(() => {
  159. let dialogScheduleBtn = _getScheduleDom(true);
  160. _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn2);
  161. }, 800)
  162. }
  163. /**
  164. * 获取左侧twitter按钮
  165. * @private
  166. */
  167. function _getSliderTwitterBtn() {
  168. dom.tweetBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
  169. dom.tweetBtn.addEventListener('click', function () {
  170. // _addDeNetBtnToDialog();
  171. })
  172. }
  173. /**
  174. * 添加deNet按钮
  175. * @private
  176. */
  177. function _addDeNetBtn() {
  178. setTimeout(() => {
  179. let node = document.querySelector('header[role="banner"]').querySelector('.r-1habvwh');
  180. if (node) {
  181. node.appendChild(dom.deBtn);
  182. }
  183. let dialogScheduleBtn = _getScheduleDom(false);
  184. _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn1);
  185. }, 800)
  186. }
  187. /**
  188. * 获取推文输入框内dom,用于插入deNet
  189. * @param isDialogInner
  190. * @returns {Element}
  191. * @private
  192. */
  193. function _getScheduleDom(isDialogInner = false) {
  194. let scheduleBtn;
  195. if (isDialogInner) {
  196. scheduleBtn = document.querySelector('div[role="dialog"]').querySelector('[data-testid="createPollButton"]');
  197. } else {
  198. let toolBar = document.querySelector('div[data-testid="toolBar"]');
  199. if (toolBar) {
  200. scheduleBtn = toolBar.querySelector('div[data-testid="geoButton"]');
  201. }
  202. }
  203. return scheduleBtn;
  204. }
  205. /**
  206. * 插入iframe到页面
  207. * @private
  208. */
  209. function _addIframe() {
  210. // let span = document.createElement('span');
  211. // const shadowRoot = span.attachShadow({mode: 'closed'})
  212. let iframe = document.createElement('iframe');
  213. iframe.src = chrome.runtime.getURL('/iframe/publish.html')
  214. iframe.id = 'iframe-test'
  215. iframe.style.cssText = 'position:fixed;top:0px;right:0;display:block; width:100%;height:100%;z-index:0; border: medium none;display:none';
  216. // shadowRoot.appendChild(iframe);
  217. // document.body.appendChild(span)
  218. dom.iframe = iframe;
  219. document.getElementById('layers').appendChild(iframe)
  220. }
  221. /**
  222. * 获取发布推文id
  223. * @returns {string}
  224. * @private
  225. */
  226. function _getTwitterArtId(contentStr, cb) {
  227. // let firstTwitterArtId = document.querySelector('article[data-testid="tweet"]').querySelector('a[dir="auto"]').getAttribute('href');
  228. // return firstTwitterArtId.split('/status/')[1];
  229. let id = '';
  230. let timer = setInterval(() => {
  231. let artDomList = document.querySelectorAll('article[data-testid="tweet"]');
  232. for (let i = 0; i < artDomList.length; i++) {
  233. let itemChild = artDomList[i].querySelector('.css-1dbjc4n');
  234. if (itemChild && itemChild.querySelector('div[lang="und"]')) {
  235. let innerText = itemChild.querySelector('div[lang="und"]').innerText;
  236. let regex = new RegExp(contentStr);
  237. if (regex.test(innerText)) {
  238. id = itemChild.parentNode.querySelector('a[dir="auto"]').getAttribute('href').split('/status/')[1];
  239. clearInterval(timer);
  240. if (id) {
  241. cb && cb(id);
  242. }
  243. break;
  244. }
  245. }
  246. }
  247. }, 1000);
  248. }
  249. /**
  250. * 点击deNet按钮处理
  251. * @private
  252. */
  253. function _deNetBtnClick(port) {
  254. getUserInfo((res) => {
  255. if (res) {
  256. if (window.location.pathname != '/home') {
  257. if (!dom.homeBtn) {
  258. dom.homeBtn = document.querySelector('a[data-testid="AppTabBar_Home_Link"]');
  259. }
  260. dom.homeBtn.click();
  261. }
  262. showGiveDialogHandler(res);
  263. } else {
  264. dom.deBtn.insertBefore(dom.loadingImg, dom.deBtn.querySelector('span'));
  265. setTimeout(() => {
  266. dom.deBtn.innerHTML = '<span>DeNet<span>';
  267. }, 3000)
  268. port.postMessage({ state: 'CONTENT_TWITTER_LOGIN' })
  269. }
  270. })
  271. }
  272. /**
  273. * 设置发布内容
  274. * @param content
  275. * @private
  276. */
  277. function _setPublishContent(content) {
  278. setTimeout(() => {
  279. document.execCommand("insertText", false, '');
  280. document.execCommand("insertText", false, content);
  281. }, 1300);
  282. }
  283. /**
  284. * 创建deNet按钮 添加到页面
  285. * @returns {{deBtn2: HTMLDivElement, deBtn1: HTMLDivElement, deBtn: HTMLSpanElement}}
  286. * @private
  287. */
  288. function _createBtnDom(port) {
  289. let loadingImg = document.createElement('img');
  290. loadingImg.src = require("../assets/img/icon-btn-loading.png");
  291. loadingImg.style.cssText = 'width:20px;height: 20px;margin-right:3px;-webkit-animation:load 1.1s infinite linear;';
  292. let style = document.createElement('style');
  293. style.innerHTML=" @-webkit-keyframes load{from{ transform: rotate(0deg);} to{transform: rotate(360deg);}}";
  294. document.getElementsByTagName('head').item(0).appendChild(style);
  295. let deBtn = document.createElement('span');
  296. const shadowDiv = document.createElement('div');
  297. deBtn.innerHTML = '<span>DeNet</span>';
  298. deBtn.id = 'de-btn';
  299. deBtn.style.cssText = 'width:220px;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:15px;font-weight:700;border-radius:100px;cursor: pointer;display: flex;align-items: center;justify-content: center;';
  300. const deBtn1 = document.createElement('img');
  301. let src = require("../assets/img/icon-gift-pack.png");
  302. const smallDeBtnStyle = 'width:20px;height: 20px;cursor: pointer;marign-left:4px;margin-right:4px';
  303. deBtn1.id = 'de-btn1';
  304. deBtn1.style.cssText = smallDeBtnStyle;
  305. deBtn1.src = src
  306. const deBtn2 = document.createElement('div');
  307. deBtn2.id = 'de-btn2';
  308. deBtn2.style.cssText = smallDeBtnStyle;
  309. deBtn2.src = "../assets/img/icon-gift-pack.png"
  310. deBtn.addEventListener('click', () => {
  311. _deNetBtnClick(port);
  312. })
  313. deBtn1.addEventListener('click', () => {
  314. _deNetBtnClick(port);
  315. })
  316. deBtn2.addEventListener('click', () => {
  317. _deNetBtnClick(port);
  318. })
  319. dom.deBtn = deBtn;
  320. dom.deBtn1 = deBtn1;
  321. dom.deBtn2 = deBtn2;
  322. dom.loadingImg = loadingImg;
  323. }
  324. /* setInterval(() => {
  325. let toolBar = document.querySelector('div[data-testid="toolBar"]');
  326. let innerDeIcon = document.getElementById('de-icon');
  327. if (toolBar && !innerDeIcon) {
  328. // let dialogScheduleBtn = _getScheduleDom(false);
  329. // _addDeNetEditBtn(dialogScheduleBtn, deBtn1);
  330. }
  331. }, 800) */
  332. function parseDOMRedPacket() {
  333. let _dom = null
  334. // let denet_arr = document.querySelector('article[data-testid=tweet]').querySelectorAll('a')
  335. // let _dom = null
  336. // for (let i in denet_arr) {
  337. // if (denet_arr[i].innerText == '#DeNet') {
  338. // _dom = denet_arr[i].parentNode.parentNode.parentNode.parentNode.children[1]
  339. // // 是否有有红包秘文
  340. // }
  341. // }
  342. // //
  343. // denet_arr = document.querySelector('section').querySelectorAll('a')
  344. // for (let i in denet_arr) {
  345. // if (denet_arr[i].innerText == '#DeNet') {
  346. // _dom = denet_arr[i].parentNode
  347. // // 是否有有红包秘文
  348. // }
  349. // }
  350. // return _dom
  351. let arr = document.querySelectorAll('a') || []
  352. arr.forEach((item) => {
  353. if (item.innerText == '#DeNet') {
  354. if (item.parentNode && item.parentNode.parentNode && item.parentNode.parentNode.innerText.length > 5) {
  355. let _postId = item.parentNode.parentNode.innerText || ''
  356. _postId = _postId.match(/###([\s\S]*?)###/)[1];
  357. let _dom = item.parentNode.parentNode.parentNode.parentNode.parentNode
  358. replaceDOMRedPacket(_dom.children[1], _postId)
  359. }
  360. }
  361. })
  362. }
  363. function replaceDOMRedPacket(_dom, postId) {
  364. if (!_dom || _dom.querySelector('iframe')) {
  365. return
  366. }
  367. _dom.innerHTML = ''
  368. let _iframe = document.createElement('iframe')
  369. _iframe.id = postId
  370. _iframe.src = chrome.runtime.getURL('/iframe/red-packet.html') + '?postId=' + postId;
  371. _iframe.style.cssText = 'border: medium none; width:375px;height:500px;'
  372. _dom.style = 'height:500px'
  373. _dom.appendChild(_iframe)
  374. }
  375. export function setIframeRedPacket() {
  376. // let elment = document.documentElement
  377. // if(window.location.href != 'https://twitter.com/home'){
  378. // return
  379. // }
  380. parseDOMRedPacket()
  381. // let _current_top = 0
  382. setInterval(() => {
  383. parseDOMRedPacket()
  384. }, 1000)
  385. // document.addEventListener('scroll', (e) => {
  386. // if ((elment.scrollTop - _current_top) > 500 || (_current_top - elment.scrollTop) > 500) {
  387. // _current_top = elment.scrollTop
  388. // 1.解析推文
  389. // 2.替换推文
  390. // parseDOMRedPacket()
  391. // }
  392. // })
  393. }