twitter.js 17 KB

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