twitter.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. import { fetchTtwitterRequestToken, fetchTwitterLogin, fetchTwitterShortUrl, fetchAllMessageInfo, fetchReadTaskAllMsg, getDiscordUserInfo, fetchGetTwitterNftPostPre, fetchPublish, fetchGetAllUnReadNotices } from '@/logic/background/fetch/twitter.js'
  2. import { LANDING_PAGE, WEBSITE_USER_INFO, LANDING_PAGE_MID, setChromeStorage, setChromeCookie, getChromeCookie, getChromeStorage, removeChromeCookie, LANDING_PAGE_JUMP_INFO } from '@/uilts/chromeExtension.js'
  3. import { guid } from '@/uilts/help.js'
  4. import { discordAuthRedirectUri } from '@/http/configAPI'
  5. import { setContentMessage } from '@/logic/background/help.js'
  6. import Report from "@/log-center/log"
  7. let authToken = ''
  8. let consumerKey = ''
  9. let tab_flag = true
  10. const isHasTabByUrl = (url, callback) => {
  11. try {
  12. let item
  13. chrome.tabs.query({}, (tab) => {
  14. for (let i in tab) {
  15. if (tab[i].url.indexOf(url) >= 0) {
  16. item = tab[i]
  17. break
  18. }
  19. }
  20. callback(item)
  21. })
  22. } catch (error) {
  23. Report.reportLog({
  24. objectType: Report.objectType.background_function_catch,
  25. funcName: 'isHasTabByUrl',
  26. errMsg: error.message
  27. })
  28. }
  29. }
  30. export function twitterPinLoginToken() {
  31. try {
  32. // 1.判断是否登陆了
  33. getChromeStorage('userInfo', (res) => {
  34. // 没有登陆
  35. if (!res) {
  36. if (tab_flag == false) {
  37. return
  38. }
  39. tab_flag = false
  40. fetchTtwitterRequestToken().then((res) => {
  41. tab_flag = true
  42. if (res.code == 0) {
  43. authToken = res.data.authToken
  44. consumerKey = res.data.consumerKey
  45. isHasTabByUrl('https://api.twitter.com/oauth/authorize?oauth_token', (tab) => {
  46. if (!tab) {
  47. chrome.tabs.create({
  48. url: `https://api.twitter.com/oauth/authorize?oauth_token=${res.data.authToken}`
  49. })
  50. } else {
  51. chrome.tabs.highlight({ windowId: tab.windowId, tabs: tab.index })
  52. }
  53. })
  54. }
  55. }).catch(() => {
  56. tab_flag = true
  57. })
  58. }
  59. })
  60. } catch (error) {
  61. Report.reportLog({
  62. objectType: Report.objectType.background_function_catch,
  63. funcName: 'twitterPinLoginToken',
  64. errMsg: error.message
  65. })
  66. }
  67. }
  68. export function twitterPinLoginCode(sender, code) {
  69. // port.postMessage({
  70. // state: "BACK_TWITTER_LOGIN_SUCCESS",
  71. // });
  72. // 关闭code页面
  73. // chrome.tabs.query({}, (tab) => {
  74. // for (let i in tab) {
  75. // console.log(tab[i])
  76. // if (tab[i].url == 'https://api.twitter.com/oauth/authorize') {
  77. // chrome.tabs.remove(tab[i].id)
  78. // }
  79. // }
  80. // })
  81. try {
  82. chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_TWITTER_LOGIN_SUCCESS' }, (res) => { console.log(res) });
  83. chrome.tabs.remove(sender.tab.id)
  84. chrome.cookies.getAll(LANDING_PAGE, (e = []) => {
  85. let _str = '[]'
  86. if (e.length > 0) {
  87. _str = e[0].value
  88. }
  89. let _arr = JSON.parse(decodeURIComponent(_str))
  90. let receivedIds = []
  91. if (_arr.length > 0) {
  92. for (let i in _arr) {
  93. receivedIds.push(_arr[i].receivedId)
  94. }
  95. }
  96. // 发送请求
  97. // token,code
  98. fetchTwitterLogin(authToken, consumerKey, code, receivedIds).then(res => {
  99. if (res.code == 0) {
  100. setChromeStorage({ userInfo: JSON.stringify(res.data) })
  101. setChromeCookie(WEBSITE_USER_INFO, res.data)
  102. sendActivetabMessage({
  103. actionType: 'BG_LOGIN_SET_USERINFO_CB'
  104. });
  105. // 获取全局消息数据
  106. setMessageCount()
  107. chrome.cookies.remove(LANDING_PAGE)
  108. }
  109. }).catch((error) => {
  110. console.log('catch', error)
  111. })
  112. })
  113. } catch (error) {
  114. Report.reportLog({
  115. objectType: Report.objectType.background_function_catch,
  116. funcName: 'twitterPinLoginCode',
  117. errMsg: error.message
  118. })
  119. }
  120. }
  121. let discordAuthWindowId = '';
  122. export function saveDiscordAuthWindowId(params) {
  123. let { windowId = '' } = params.data || {};
  124. discordAuthWindowId = windowId;
  125. }
  126. export function discordLoginCode({ code }, sender) {
  127. try {
  128. console.log('sender', sender)
  129. let { windowId, id } = sender.tab || {};
  130. chrome.tabs.remove(id);
  131. // 发送请求
  132. getDiscordUserInfo({
  133. authCode: code,
  134. redirectUrl: discordAuthRedirectUri
  135. }).then(res => {
  136. if (res.code == 0) {
  137. setTimeout(() => {
  138. sendActivetabMessage({
  139. actionType: 'BACK_DISCORD_LOGIN_SUCCESS'
  140. });
  141. })
  142. }
  143. }).catch((error) => {
  144. console.log('catch', error)
  145. })
  146. } catch (error) {
  147. Report.reportLog({
  148. objectType: Report.objectType.background_function_catch,
  149. funcName: 'discordLoginCode',
  150. errMsg: error.message
  151. })
  152. }
  153. // if(windowId) {
  154. // chrome.windows.remove(
  155. // windowId,
  156. // function () {
  157. // }
  158. // )
  159. // }
  160. }
  161. export function twitterShortUrl(sender, url) {
  162. try {
  163. fetchTwitterShortUrl(url).then(res => {
  164. let str_arr = res.match(/denetme.net\/([\s\S]*?)"/) || []
  165. let post_Id = str_arr[1] || ''
  166. if (!post_Id) {
  167. return
  168. }
  169. // 解析
  170. let _obj = {
  171. short_url: url,
  172. post_Id
  173. }
  174. getChromeStorage('cardData', item => {
  175. if (item) {
  176. let has = false
  177. for (let i in item) {
  178. if (item[i].short_url == _obj.short_url) {
  179. item[i].short_url = _obj.short_url
  180. item[i].post_Id = _obj.post_Id
  181. setChromeStorage({ cardData: JSON.stringify(item) })
  182. has = true
  183. break
  184. }
  185. }
  186. if (!has) {
  187. item.push(_obj)
  188. setChromeStorage({ cardData: JSON.stringify(item) })
  189. }
  190. } else {
  191. setChromeStorage({ cardData: JSON.stringify([_obj]) })
  192. }
  193. chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_TWITTER_SHORT_URL' }, (response) => { });
  194. // port.postMessage({
  195. // state: "BACK_TWITTER_SHORT_URL"
  196. // });
  197. })
  198. }).catch((error) => {
  199. console.log('catch', error)
  200. })
  201. } catch (error) {
  202. Report.reportLog({
  203. objectType: Report.objectType.background_function_catch,
  204. funcName: 'twitterShortUrl',
  205. errMsg: error.message
  206. })
  207. }
  208. }
  209. // 安装插件后获取mid
  210. export function onInstalledMid(cb) {
  211. try {
  212. getChromeCookie(LANDING_PAGE_MID, (res_arr) => {
  213. // 没有cookie
  214. if (res_arr && res_arr.length) {
  215. setChromeStorage({ mid: JSON.stringify(res_arr[0]) }, () => {
  216. cb && cb()
  217. })
  218. } else {
  219. let _params = {
  220. mid: guid()
  221. }
  222. setChromeCookie(LANDING_PAGE, { 'mid': _params.mid })
  223. setChromeStorage({ mid: JSON.stringify(_params) }, () => {
  224. cb && cb()
  225. })
  226. }
  227. })
  228. } catch (error) {
  229. cb && cb();
  230. Report.reportLog({
  231. objectType: Report.objectType.background_function_catch,
  232. funcName: 'onInstalledMid',
  233. errMsg: error.message
  234. })
  235. }
  236. }
  237. export function onInstalledUserSet() {
  238. try {
  239. chrome.action.getUserSettings().then(res => {
  240. setChromeStorage({ userSettings: JSON.stringify({ res }) })
  241. // 无刷新插入js
  242. chrome.tabs.query({}, (tabs) => {
  243. for (let i in tabs) {
  244. if (tabs[i].url && tabs[i].url.substr(0, 4).includes('http')) {
  245. chrome.scripting.executeScript({
  246. target: { tabId: tabs[i].id },
  247. files: ['js/content_help.js']
  248. }, () => { })
  249. if (tabs[i].url.indexOf('twitter.com') >= 0 || tabs[i].url.indexOf('facebook.com') >= 0) {
  250. chrome.scripting.executeScript({
  251. target: { tabId: tabs[i].id },
  252. files: ['js/content.js'],
  253. }, () => {
  254. setTimeout(() => {
  255. setChromeStorage({ executeScript: JSON.stringify({ executeScript: 1 }) })
  256. }, 2000);
  257. })
  258. }
  259. }
  260. }
  261. })
  262. }).catch((error) => {
  263. console.log('catch', error)
  264. })
  265. } catch (error) {
  266. Report.reportLog({
  267. objectType: Report.objectType.background_function_catch,
  268. funcName: 'onInstalledUserSet',
  269. errMsg: error.message
  270. })
  271. }
  272. }
  273. /**
  274. * 检查是否pined 显示tips
  275. */
  276. export function checkPined() {
  277. try {
  278. chrome.action.getUserSettings(res => {
  279. let { isOnToolbar } = res;
  280. if (!isOnToolbar) {
  281. sendActivetabMessage({
  282. actionType: 'BG_SHOW_PIN_TIPS'
  283. });
  284. }
  285. })
  286. } catch (error) {
  287. Report.reportLog({
  288. objectType: Report.objectType.background_function_catch,
  289. funcName: 'checkPined',
  290. errMsg: error.message
  291. })
  292. }
  293. }
  294. function sendActivetabMessage(message = {}) {
  295. try {
  296. chrome.tabs.query({
  297. active: true,
  298. currentWindow: true
  299. }, (tabs) => {
  300. if (tabs && tabs.length) {
  301. chrome.tabs.sendMessage(tabs[0].id, message)
  302. }
  303. })
  304. } catch (error) {
  305. Report.reportLog({
  306. objectType: Report.objectType.background_function_catch,
  307. funcName: 'sendActivetabMessage',
  308. errMsg: error.message
  309. });
  310. }
  311. }
  312. /**
  313. * 安装后打开新标签页
  314. */
  315. export function onInstalledCreateTab({ reason }) {
  316. try {
  317. getChromeCookie(LANDING_PAGE_JUMP_INFO, (res = {}) => {
  318. onInstalledMid(() => {
  319. setTimeout(() => {
  320. if (!res) {
  321. res = {}
  322. }
  323. // 安装成功埋点
  324. Report.reportLog({
  325. objectType: Report.objectType.chrome_extension_installed,
  326. funcName: 'onInstalledCreateTab',
  327. postId: res.postId || '',
  328. shareLinkId: res.shareLinkId || '',
  329. 'channel-name': res.channelName,
  330. reason
  331. })
  332. }, 5000)
  333. });
  334. let url = 'https://twitter.com/search?q=%23denet'
  335. // jump_info
  336. if (!res || !res.jump_type) {
  337. chrome.tabs.create({
  338. url
  339. });
  340. return
  341. }
  342. let created_detail = false
  343. switch (String(res.jump_type)) {
  344. // 普通红包
  345. case 'red_packet':
  346. if (res && res.postNickName && res.srcContentId) {
  347. created_detail = true
  348. url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
  349. chrome.tabs.create({
  350. url
  351. });
  352. }
  353. break
  354. // 抽奖红包
  355. case 'luck_draw':
  356. if (res && res.postNickName && res.srcContentId) {
  357. created_detail = true
  358. url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
  359. chrome.tabs.create({
  360. url
  361. });
  362. }
  363. break
  364. // NFT
  365. case 'nft_info':
  366. if (res && res.twitterAccount && res.nftProjectId) {
  367. created_detail = true
  368. url = `https://twitter.com/${res.twitterAccount}`
  369. chrome.tabs.create({
  370. url
  371. });
  372. }
  373. break
  374. // NFT 组
  375. case 'nft_group_info':
  376. if (res && res.twitterAccount) {
  377. created_detail = true
  378. // setChromeStorage({ groupTabData: JSON.stringify({
  379. // deTabVal: 'deGroupTab'
  380. // })})
  381. chrome.storage.local.set({
  382. groupTabData: JSON.stringify({
  383. deTabVal: 'deGroupTab'
  384. })
  385. }, (response) => {
  386. url = `https://twitter.com/${res.twitterAccount}`
  387. chrome.tabs.create({
  388. url
  389. });
  390. })
  391. }
  392. break
  393. // toolbox
  394. case 'tool_box':
  395. if (res && res.postNickName && res.srcContentId) {
  396. created_detail = true
  397. url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
  398. chrome.tabs.create({
  399. url
  400. });
  401. }
  402. break
  403. case 'treasure_info':
  404. if (res && res.postNickName && res.srcContentId) {
  405. created_detail = true
  406. url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
  407. chrome.tabs.create({
  408. url
  409. });
  410. }
  411. break;
  412. }
  413. if (created_detail == false) {
  414. chrome.tabs.create({
  415. url
  416. });
  417. }
  418. removeChromeCookie(LANDING_PAGE_JUMP_INFO)
  419. })
  420. } catch (error) {
  421. Report.reportLog({
  422. objectType: Report.objectType.background_function_catch,
  423. funcName: 'onInstalledCreateTab',
  424. errMsg: error.message
  425. })
  426. }
  427. }
  428. /**
  429. * 在popop重新发送
  430. * @param {*} req
  431. */
  432. export function popupRePublish(req) {
  433. try {
  434. setChromeStorage({
  435. popupShowPublishDialog: JSON.stringify({
  436. ...req.data,
  437. show: true
  438. }),
  439. });
  440. chrome.tabs.create({
  441. url: "https://twitter.com",
  442. });
  443. } catch (error) {
  444. Report.reportLog({
  445. objectType: Report.objectType.background_function_catch,
  446. funcName: 'popupRePublish',
  447. errMsg: error.message
  448. })
  449. }
  450. }
  451. export function setBadgeInfo(params) {
  452. try {
  453. let { text = '', color = '#DF3535' } = params.data || {};
  454. chrome.action.setBadgeText({ text: text });
  455. chrome.action.setBadgeBackgroundColor({ color: color });
  456. } catch (error) {
  457. Report.reportLog({
  458. objectType: Report.objectType.background_function_catch,
  459. funcName: 'setBadgeInfo',
  460. errMsg: error.message
  461. })
  462. }
  463. }
  464. export function hideBadge() {
  465. try {
  466. chrome.action.setBadgeText({ text: '' });
  467. chrome.action.setBadgeBackgroundColor({ color: [0, 0, 0, 0] });
  468. } catch (error) {
  469. Report.reportLog({
  470. objectType: Report.objectType.background_function_catch,
  471. funcName: 'hideBadge',
  472. errMsg: error.message
  473. })
  474. }
  475. }
  476. export async function setMessageCount() {
  477. try {
  478. const { accessToken: token = '', uid = '' } = await getChromeStorage('userInfo') || {}
  479. if (token) {
  480. getMessageInfo();
  481. createAlarm();
  482. }
  483. } catch (error) {
  484. }
  485. }
  486. function createAlarm() {
  487. try {
  488. let alarmInfo = {
  489. //1分鐘之後開始(該值不能小於1)
  490. delayInMinutes: 1,
  491. //與上方等同的寫法是
  492. // when : Date.now() + n,
  493. //開始後每一分鐘執行一次(該值不能小于1)
  494. periodInMinutes: 1
  495. };
  496. //每次加載就清空定時器
  497. chrome.alarms.clear('denetChromeAlarm');
  498. //創造定時器
  499. chrome.alarms.create('denetChromeAlarm', alarmInfo);
  500. } catch (error) {
  501. Report.reportLog({
  502. objectType: Report.objectType.background_function_catch,
  503. funcName: 'createAlarm',
  504. errMsg: error.message
  505. });
  506. }
  507. }
  508. export function getMessageInfo() {
  509. try {
  510. fetchAllMessageInfo().then(res => {
  511. if (res.code == 0) {
  512. let { unReadCountTotal = 0 } = res.data;
  513. if (unReadCountTotal > 0) {
  514. let text = unReadCountTotal > 99 ? '99+' : unReadCountTotal + '';
  515. setBadgeInfo({ data: { text } });
  516. } else {
  517. hideBadge();
  518. }
  519. }
  520. }).catch((error) => {
  521. console.log('catch', error)
  522. })
  523. } catch (error) {
  524. Report.reportLog({
  525. objectType: Report.objectType.background_function_catch,
  526. funcName: 'getMessageInfo',
  527. errMsg: error.message
  528. })
  529. }
  530. }
  531. export function readTaskAllMsg({ msgType }, cb) {
  532. try {
  533. fetchReadTaskAllMsg({
  534. msgType // 1:任务红包 2:钱包明细
  535. }).then(res => {
  536. if (res.code == 0) {
  537. cb && cb();
  538. }
  539. });
  540. } catch (error) {
  541. Report.reportLog({
  542. objectType: Report.objectType.background_function_catch,
  543. funcName: 'readTaskAllMsg',
  544. errMsg: error.message
  545. })
  546. }
  547. }
  548. export const onDisconnectHandler = (port) => {
  549. try {
  550. if (port.name === "popup" || port.name === "popup_transactions") {
  551. let msgType = port.name === "popup" ? 1 : 2;
  552. readTaskAllMsg({ msgType }, () => {
  553. getMessageInfo();
  554. })
  555. }
  556. } catch (error) {
  557. Report.reportLog({
  558. objectType: Report.objectType.background_function_catch,
  559. funcName: 'onDisconnectHandler',
  560. errMsg: error.message
  561. })
  562. }
  563. }
  564. export const injectExtensionPopup = (tab) => {
  565. try {
  566. sendActivetabMessage({
  567. actionType: 'BG_INJECT_EXTENSION_POPUP'
  568. });
  569. } catch (error) {
  570. Report.reportLog({
  571. objectType: Report.objectType.background_function_catch,
  572. funcName: 'injectExtensionPopup',
  573. errMsg: error.message
  574. })
  575. }
  576. }
  577. export const setPopupConfig = (activeInfo) => {
  578. try {
  579. chrome.tabs.query({
  580. active: true,
  581. currentWindow: true
  582. }, (tabs) => {
  583. if (tabs.length) {
  584. let { pendingUrl = '', url = '' } = tabs[0];
  585. if (pendingUrl.startsWith('https://twitter.com') || url.startsWith('https://twitter.com')) {
  586. sendActivetabMessage({
  587. actionType: 'BG_SET_POPUP_CONFIG'
  588. });
  589. } else {
  590. chrome.action.setPopup({
  591. popup: 'popup.html',
  592. }, function () {
  593. });
  594. }
  595. }
  596. })
  597. } catch (error) {
  598. Report.reportLog({
  599. objectType: Report.objectType.background_function_catch,
  600. funcName: 'setPopupConfig',
  601. errMsg: error.message
  602. })
  603. }
  604. }
  605. export const getSysMessage = () => {
  606. try {
  607. // 请求通知接口
  608. fetchGetAllUnReadNotices({})
  609. .then((res) => {
  610. // 向选中的content发送消息
  611. setContentMessage({ actionType: 'BACK_UNREAD_MESSAGE', data: res })
  612. }).catch((error) => {
  613. console.log('catch', error)
  614. })
  615. } catch (error) {
  616. Report.reportLog({
  617. objectType: Report.objectType.background_function_catch,
  618. funcName: 'getSysMessage',
  619. errMsg: error.message
  620. })
  621. }
  622. }
  623. export const windwoLoadSetPopupPage = (data, sender) => {
  624. let { url = '' } = sender.tab;
  625. if (url.startsWith('chrome://')) {
  626. chrome.action.setPopup({
  627. popup: 'popup.html',
  628. }, function () {
  629. });
  630. } else {
  631. chrome.action.setPopup({
  632. popup: '',
  633. }, function () {
  634. });
  635. }
  636. }
  637. export const setActionPopup = (data) => {
  638. try {
  639. let { popup } = data.data || {};
  640. if (popup) {
  641. chrome.action.getPopup(
  642. {},
  643. function (result) {
  644. if (!result) {
  645. chrome.action.setPopup({
  646. popup,
  647. }, function () {
  648. });
  649. }
  650. });
  651. } else {
  652. chrome.action.setPopup({
  653. popup: '',
  654. }, function () {
  655. });
  656. }
  657. } catch (error) {
  658. Report.reportLog({
  659. objectType: Report.objectType.background_function_catch,
  660. funcName: 'setActionPopup',
  661. errMsg: error.message
  662. });
  663. }
  664. }
  665. export const getTwitterNftPostPre = (params, sender) => {
  666. fetchGetTwitterNftPostPre(params).then((res) => {
  667. if (res.code == 0) {
  668. chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_TWITTER_NFT_POST_PRE', data: res.data }, (res) => { console.log(res) });
  669. }
  670. }).catch((error) => {
  671. console.log('catch', error)
  672. })
  673. }
  674. export const nftTxtPublish = (params, sender) => {
  675. fetchPublish(params).then((res) => {
  676. if (res.code == 0) {
  677. chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_NFT_PUBLISH_DONE', data: res.data }, (res) => { console.log(res) });
  678. }
  679. }).catch((error) => {
  680. console.log('catch', error)
  681. })
  682. }
  683. export const checkShowPublishDialog = (params) => {
  684. const twitterUrl = 'https://twitter.com';
  685. createTabShowGiveaway({
  686. url: twitterUrl
  687. })
  688. }
  689. const createTabShowGiveaway = (params) => {
  690. setChromeStorage({
  691. showGiveawayData: JSON.stringify({
  692. show: true
  693. })
  694. });
  695. chrome.tabs.create({
  696. url: params.url,
  697. });
  698. }