twitter.js 16 KB

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