twitter.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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 'ntf_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. }
  309. if (created_detail == false) {
  310. chrome.tabs.create({
  311. url
  312. });
  313. }
  314. removeChromeCookie(LANDING_PAGE_JUMP_INFO)
  315. })
  316. }
  317. /**
  318. * 在popop重新发送
  319. * @param {*} req
  320. */
  321. export function popupRePublish(req) {
  322. setChromeStorage({
  323. popupShowPublishDialog: JSON.stringify({
  324. ...req.data,
  325. show: true
  326. }),
  327. });
  328. chrome.tabs.create({
  329. url: "https://twitter.com",
  330. });
  331. }
  332. export function setBadgeInfo(params) {
  333. let { text = '', color = '#DF3535' } = params.data || {};
  334. chrome.action.setBadgeText({ text: text });
  335. chrome.action.setBadgeBackgroundColor({ color: color });
  336. }
  337. export function hideBadge() {
  338. chrome.action.setBadgeText({ text: '' });
  339. chrome.action.setBadgeBackgroundColor({ color: [0, 0, 0, 0] });
  340. }
  341. export async function setMessageCount() {
  342. const { accessToken: token = '', uid = '' } = await getChromeStorage('userInfo') || {}
  343. if (token) {
  344. getMessageInfo();
  345. createAlarm();
  346. }
  347. }
  348. function createAlarm() {
  349. let alarmInfo = {
  350. //1分鐘之後開始(該值不能小於1)
  351. delayInMinutes: 1,
  352. //與上方等同的寫法是
  353. // when : Date.now() + n,
  354. //開始後每一分鐘執行一次(該值不能小于1)
  355. periodInMinutes: 1
  356. };
  357. //每次加載就清空定時器
  358. chrome.alarms.clear('denetChromeAlarm');
  359. //創造定時器
  360. chrome.alarms.create('denetChromeAlarm', alarmInfo);
  361. }
  362. export function getMessageInfo() {
  363. fetchAllMessageInfo().then(res => {
  364. if (res.code == 0) {
  365. let { unReadCountTotal = 0 } = res.data;
  366. if (unReadCountTotal > 0) {
  367. let text = unReadCountTotal > 99 ? '99+' : unReadCountTotal + '';
  368. setBadgeInfo({ data: { text } });
  369. } else {
  370. hideBadge();
  371. }
  372. }
  373. })
  374. }
  375. export function readTaskAllMsg({ msgType }, cb) {
  376. fetchReadTaskAllMsg({
  377. msgType // 1:任务红包 2:钱包明细
  378. }).then(res => {
  379. if (res.code == 0) {
  380. cb && cb();
  381. }
  382. });
  383. }
  384. export const onDisconnectHandler = (port) => {
  385. if (port.name === "popup" || port.name === "popup_transactions") {
  386. let msgType = port.name === "popup" ? 1 : 2;
  387. readTaskAllMsg({ msgType }, () => {
  388. getMessageInfo();
  389. })
  390. }
  391. }
  392. export const injectExtensionPopup = (tab) => {
  393. sendActivetabMessage({
  394. actionType: 'BG_INJECT_EXTENSION_POPUP'
  395. });
  396. }
  397. export const setPopupConfig = (activeInfo) => {
  398. chrome.tabs.query({
  399. active: true,
  400. currentWindow: true
  401. }, (tabs) => {
  402. if (tabs.length) {
  403. let { pendingUrl = '', url = '' } = tabs[0];
  404. if (pendingUrl.startsWith('https://twitter.com') || url.startsWith('https://twitter.com')) {
  405. sendActivetabMessage({
  406. actionType: 'BG_SET_POPUP_CONFIG'
  407. });
  408. } else {
  409. chrome.action.setPopup({
  410. popup: 'popup.html',
  411. }, function () {
  412. });
  413. }
  414. // if(pendingUrl.startsWith('chrome://') || url.startsWith('chrome://') || pendingUrl.startsWith('https://chrome.google.com') || url.startsWith('https://chrome.google.com')) {
  415. // chrome.action.setPopup({
  416. // popup: 'popup.html',
  417. // },function() {
  418. // });
  419. // } else {
  420. // chrome.action.setPopup({
  421. // popup: '',
  422. // },function() {
  423. // });
  424. // }
  425. }
  426. })
  427. }
  428. export const getSysMessage = () => {
  429. // 请求通知接口
  430. fetchGetAllUnReadNotices({})
  431. .then((res) => {
  432. // 向选中的content发送消息
  433. setContentMessage({ actionType: 'BACK_UNREAD_MESSAGE', data: res })
  434. })
  435. }
  436. export const windwoLoadSetPopupPage = (data, sender) => {
  437. let { url = '' } = sender.tab;
  438. if (url.startsWith('chrome://')) {
  439. chrome.action.setPopup({
  440. popup: 'popup.html',
  441. }, function () {
  442. });
  443. } else {
  444. chrome.action.setPopup({
  445. popup: '',
  446. }, function () {
  447. });
  448. }
  449. }
  450. export const setActionPopup = (data) => {
  451. let { popup } = data.data || {};
  452. if (popup) {
  453. chrome.action.getPopup(
  454. {},
  455. function (result) {
  456. if (!result) {
  457. chrome.action.setPopup({
  458. popup,
  459. }, function () {
  460. });
  461. }
  462. });
  463. } else {
  464. chrome.action.setPopup({
  465. popup: '',
  466. }, function () {
  467. });
  468. }
  469. }
  470. export const getTwitterNftPostPre = (params, sender) => {
  471. fetchGetTwitterNftPostPre(params).then((res) => {
  472. if (res.code == 0) {
  473. chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_TWITTER_NFT_POST_PRE', data: res.data }, (res) => { console.log(res) });
  474. }
  475. })
  476. }
  477. export const nftTxtPublish = (params, sender) => {
  478. fetchPublish(params).then((res) => {
  479. if (res.code == 0) {
  480. chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_NFT_PUBLISH_DONE', data: res.data }, (res) => { console.log(res) });
  481. }
  482. })
  483. }
  484. export const checkShowPublishDialog = (params) => {
  485. const twitterUrl = 'https://twitter.com';
  486. createTabShowGiveaway({
  487. url: twitterUrl
  488. })
  489. }
  490. const createTabShowGiveaway = (params) => {
  491. setChromeStorage({
  492. showGiveawayData: JSON.stringify({
  493. show: true
  494. })
  495. });
  496. chrome.tabs.create({
  497. url: params.url,
  498. });
  499. }