twitter.js 16 KB

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