twitter.js 18 KB

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