twitter.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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() {
  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. })
  331. }, 5000)
  332. });
  333. let url = 'https://twitter.com/search?q=%23denet'
  334. // jump_info
  335. if (!res || !res.jump_type) {
  336. chrome.tabs.create({
  337. url
  338. });
  339. return
  340. }
  341. let created_detail = false
  342. switch (String(res.jump_type)) {
  343. // 普通红包
  344. case 'red_packet':
  345. if (res && res.postNickName && res.srcContentId) {
  346. created_detail = true
  347. url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
  348. chrome.tabs.create({
  349. url
  350. });
  351. }
  352. break
  353. // 抽奖红包
  354. case 'luck_draw':
  355. if (res && res.postNickName && res.srcContentId) {
  356. created_detail = true
  357. url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
  358. chrome.tabs.create({
  359. url
  360. });
  361. }
  362. break
  363. // NFT
  364. case 'nft_info':
  365. if (res && res.twitterAccount && res.nftProjectId) {
  366. created_detail = true
  367. url = `https://twitter.com/${res.twitterAccount}`
  368. chrome.tabs.create({
  369. url
  370. });
  371. }
  372. break
  373. // NFT 组
  374. case 'nft_group_info':
  375. if (res && res.twitterAccount) {
  376. created_detail = true
  377. // setChromeStorage({ groupTabData: JSON.stringify({
  378. // deTabVal: 'deGroupTab'
  379. // })})
  380. chrome.storage.local.set({
  381. groupTabData: JSON.stringify({
  382. deTabVal: 'deGroupTab'
  383. })
  384. }, (response) => {
  385. url = `https://twitter.com/${res.twitterAccount}`
  386. chrome.tabs.create({
  387. url
  388. });
  389. })
  390. }
  391. break
  392. // toolbox
  393. case 'tool_box':
  394. if (res && res.postNickName && res.srcContentId) {
  395. created_detail = true
  396. url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
  397. chrome.tabs.create({
  398. url
  399. });
  400. }
  401. break
  402. case 'treasure_info':
  403. if (res && res.postNickName && res.srcContentId) {
  404. created_detail = true
  405. url = `https://twitter.com/${res.postNickName}/status/${res.srcContentId}`
  406. chrome.tabs.create({
  407. url
  408. });
  409. }
  410. break;
  411. }
  412. if (created_detail == false) {
  413. chrome.tabs.create({
  414. url
  415. });
  416. }
  417. removeChromeCookie(LANDING_PAGE_JUMP_INFO)
  418. })
  419. } catch (error) {
  420. Report.reportLog({
  421. objectType: Report.objectType.background_function_catch,
  422. funcName: 'onInstalledCreateTab',
  423. errMsg: error.message
  424. })
  425. }
  426. }
  427. /**
  428. * 在popop重新发送
  429. * @param {*} req
  430. */
  431. export function popupRePublish(req) {
  432. try {
  433. setChromeStorage({
  434. popupShowPublishDialog: JSON.stringify({
  435. ...req.data,
  436. show: true
  437. }),
  438. });
  439. chrome.tabs.create({
  440. url: "https://twitter.com",
  441. });
  442. } catch (error) {
  443. Report.reportLog({
  444. objectType: Report.objectType.background_function_catch,
  445. funcName: 'popupRePublish',
  446. errMsg: error.message
  447. })
  448. }
  449. }
  450. export function setBadgeInfo(params) {
  451. try {
  452. let { text = '', color = '#DF3535' } = params.data || {};
  453. chrome.action.setBadgeText({ text: text });
  454. chrome.action.setBadgeBackgroundColor({ color: color });
  455. } catch (error) {
  456. Report.reportLog({
  457. objectType: Report.objectType.background_function_catch,
  458. funcName: 'setBadgeInfo',
  459. errMsg: error.message
  460. })
  461. }
  462. }
  463. export function hideBadge() {
  464. try {
  465. chrome.action.setBadgeText({ text: '' });
  466. chrome.action.setBadgeBackgroundColor({ color: [0, 0, 0, 0] });
  467. } catch (error) {
  468. Report.reportLog({
  469. objectType: Report.objectType.background_function_catch,
  470. funcName: 'hideBadge',
  471. errMsg: error.message
  472. })
  473. }
  474. }
  475. export async function setMessageCount() {
  476. try {
  477. const { accessToken: token = '', uid = '' } = await getChromeStorage('userInfo') || {}
  478. if (token) {
  479. getMessageInfo();
  480. createAlarm();
  481. }
  482. } catch (error) {
  483. }
  484. }
  485. function createAlarm() {
  486. try {
  487. let alarmInfo = {
  488. //1分鐘之後開始(該值不能小於1)
  489. delayInMinutes: 1,
  490. //與上方等同的寫法是
  491. // when : Date.now() + n,
  492. //開始後每一分鐘執行一次(該值不能小于1)
  493. periodInMinutes: 1
  494. };
  495. //每次加載就清空定時器
  496. chrome.alarms.clear('denetChromeAlarm');
  497. //創造定時器
  498. chrome.alarms.create('denetChromeAlarm', alarmInfo);
  499. } catch (error) {
  500. Report.reportLog({
  501. objectType: Report.objectType.background_function_catch,
  502. funcName: 'createAlarm',
  503. errMsg: error.message
  504. });
  505. }
  506. }
  507. export function getMessageInfo() {
  508. try {
  509. fetchAllMessageInfo().then(res => {
  510. if (res.code == 0) {
  511. let { unReadCountTotal = 0 } = res.data;
  512. if (unReadCountTotal > 0) {
  513. let text = unReadCountTotal > 99 ? '99+' : unReadCountTotal + '';
  514. setBadgeInfo({ data: { text } });
  515. } else {
  516. hideBadge();
  517. }
  518. }
  519. }).catch((error) => {
  520. console.log('catch', error)
  521. })
  522. } catch (error) {
  523. Report.reportLog({
  524. objectType: Report.objectType.background_function_catch,
  525. funcName: 'getMessageInfo',
  526. errMsg: error.message
  527. })
  528. }
  529. }
  530. export function readTaskAllMsg({ msgType }, cb) {
  531. try {
  532. fetchReadTaskAllMsg({
  533. msgType // 1:任务红包 2:钱包明细
  534. }).then(res => {
  535. if (res.code == 0) {
  536. cb && cb();
  537. }
  538. });
  539. } catch (error) {
  540. Report.reportLog({
  541. objectType: Report.objectType.background_function_catch,
  542. funcName: 'readTaskAllMsg',
  543. errMsg: error.message
  544. })
  545. }
  546. }
  547. export const onDisconnectHandler = (port) => {
  548. try {
  549. if (port.name === "popup" || port.name === "popup_transactions") {
  550. let msgType = port.name === "popup" ? 1 : 2;
  551. readTaskAllMsg({ msgType }, () => {
  552. getMessageInfo();
  553. })
  554. }
  555. } catch (error) {
  556. Report.reportLog({
  557. objectType: Report.objectType.background_function_catch,
  558. funcName: 'onDisconnectHandler',
  559. errMsg: error.message
  560. })
  561. }
  562. }
  563. export const injectExtensionPopup = (tab) => {
  564. try {
  565. sendActivetabMessage({
  566. actionType: 'BG_INJECT_EXTENSION_POPUP'
  567. });
  568. } catch (error) {
  569. Report.reportLog({
  570. objectType: Report.objectType.background_function_catch,
  571. funcName: 'injectExtensionPopup',
  572. errMsg: error.message
  573. })
  574. }
  575. }
  576. export const setPopupConfig = (activeInfo) => {
  577. try {
  578. chrome.tabs.query({
  579. active: true,
  580. currentWindow: true
  581. }, (tabs) => {
  582. if (tabs.length) {
  583. let { pendingUrl = '', url = '' } = tabs[0];
  584. if (pendingUrl.startsWith('https://twitter.com') || url.startsWith('https://twitter.com')) {
  585. sendActivetabMessage({
  586. actionType: 'BG_SET_POPUP_CONFIG'
  587. });
  588. } else {
  589. chrome.action.setPopup({
  590. popup: 'popup.html',
  591. }, function () {
  592. });
  593. }
  594. }
  595. })
  596. } catch (error) {
  597. Report.reportLog({
  598. objectType: Report.objectType.background_function_catch,
  599. funcName: 'setPopupConfig',
  600. errMsg: error.message
  601. })
  602. }
  603. }
  604. export const getSysMessage = () => {
  605. try {
  606. // 请求通知接口
  607. fetchGetAllUnReadNotices({})
  608. .then((res) => {
  609. // 向选中的content发送消息
  610. setContentMessage({ actionType: 'BACK_UNREAD_MESSAGE', data: res })
  611. }).catch((error) => {
  612. console.log('catch', error)
  613. })
  614. } catch (error) {
  615. Report.reportLog({
  616. objectType: Report.objectType.background_function_catch,
  617. funcName: 'getSysMessage',
  618. errMsg: error.message
  619. })
  620. }
  621. }
  622. export const windwoLoadSetPopupPage = (data, sender) => {
  623. let { url = '' } = sender.tab;
  624. if (url.startsWith('chrome://')) {
  625. chrome.action.setPopup({
  626. popup: 'popup.html',
  627. }, function () {
  628. });
  629. } else {
  630. chrome.action.setPopup({
  631. popup: '',
  632. }, function () {
  633. });
  634. }
  635. }
  636. export const setActionPopup = (data) => {
  637. try {
  638. let { popup } = data.data || {};
  639. if (popup) {
  640. chrome.action.getPopup(
  641. {},
  642. function (result) {
  643. if (!result) {
  644. chrome.action.setPopup({
  645. popup,
  646. }, function () {
  647. });
  648. }
  649. });
  650. } else {
  651. chrome.action.setPopup({
  652. popup: '',
  653. }, function () {
  654. });
  655. }
  656. } catch (error) {
  657. Report.reportLog({
  658. objectType: Report.objectType.background_function_catch,
  659. funcName: 'setActionPopup',
  660. errMsg: error.message
  661. });
  662. }
  663. }
  664. export const getTwitterNftPostPre = (params, sender) => {
  665. fetchGetTwitterNftPostPre(params).then((res) => {
  666. if (res.code == 0) {
  667. chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_TWITTER_NFT_POST_PRE', data: res.data }, (res) => { console.log(res) });
  668. }
  669. }).catch((error) => {
  670. console.log('catch', error)
  671. })
  672. }
  673. export const nftTxtPublish = (params, sender) => {
  674. fetchPublish(params).then((res) => {
  675. if (res.code == 0) {
  676. chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_NFT_PUBLISH_DONE', data: res.data }, (res) => { console.log(res) });
  677. }
  678. }).catch((error) => {
  679. console.log('catch', error)
  680. })
  681. }
  682. export const checkShowPublishDialog = (params) => {
  683. const twitterUrl = 'https://twitter.com';
  684. createTabShowGiveaway({
  685. url: twitterUrl
  686. })
  687. }
  688. const createTabShowGiveaway = (params) => {
  689. setChromeStorage({
  690. showGiveawayData: JSON.stringify({
  691. show: true
  692. })
  693. });
  694. chrome.tabs.create({
  695. url: params.url,
  696. });
  697. }