twitter.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 } from '@/uilts/chromeExtension.js'
  3. import { guid } from '@/uilts/help.js'
  4. import { pageUrl, 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. let cookiesParams = {
  229. name: 'pickup_info',
  230. url: pageUrl
  231. }
  232. getChromeCookie(cookiesParams, (res) => {
  233. let { postNickName, srcContentId } = res;
  234. if (res && postNickName && srcContentId) {
  235. let url = `https://twitter.com/${postNickName}/status/${srcContentId}`
  236. chrome.tabs.create({
  237. url
  238. });
  239. removeChromeCookie(cookiesParams)
  240. } else {
  241. let nftParams = {
  242. name: 'nft_info',
  243. url: pageUrl
  244. }
  245. getChromeCookie(nftParams, (res) => {
  246. let { twitterAccount, nftProjectId } = res;
  247. if (res && twitterAccount && nftProjectId) {
  248. let url = `https://twitter.com/${twitterAccount}`
  249. chrome.tabs.create({
  250. url
  251. });
  252. removeChromeCookie(nftParams)
  253. } else {
  254. let nftGroupParams = {
  255. name: 'nft_group_info',
  256. url: pageUrl
  257. }
  258. getChromeCookie(nftGroupParams, (res) => {
  259. let { twitterAccount } = res;
  260. if (res && twitterAccount) {
  261. // setChromeStorage({ groupTabData: JSON.stringify({
  262. // deTabVal: 'deGroupTab'
  263. // })})
  264. chrome.storage.local.set({
  265. groupTabData: JSON.stringify({
  266. deTabVal: 'deGroupTab'
  267. })
  268. }, (res) => {
  269. let url = `https://twitter.com/${twitterAccount}`
  270. chrome.tabs.create({
  271. url
  272. });
  273. })
  274. removeChromeCookie(nftGroupParams)
  275. } else {
  276. chrome.tabs.create({
  277. url: "https://twitter.com",
  278. });
  279. }
  280. })
  281. }
  282. })
  283. }
  284. })
  285. }
  286. /**
  287. * 在popop重新发送
  288. * @param {*} req
  289. */
  290. export function popupRePublish(req) {
  291. setChromeStorage({
  292. popupShowPublishDialog: JSON.stringify({
  293. ...req.data,
  294. show: true
  295. }),
  296. });
  297. chrome.tabs.create({
  298. url: "https://twitter.com",
  299. });
  300. }
  301. export function setBadgeInfo(params) {
  302. let { text = '', color = '#DF3535' } = params.data || {};
  303. chrome.action.setBadgeText({ text: text });
  304. chrome.action.setBadgeBackgroundColor({ color: color });
  305. }
  306. export function hideBadge() {
  307. chrome.action.setBadgeText({ text: '' });
  308. chrome.action.setBadgeBackgroundColor({ color: [0, 0, 0, 0] });
  309. }
  310. export async function setMessageCount() {
  311. const { accessToken: token = '', uid = '' } = await getChromeStorage('userInfo') || {}
  312. if (token) {
  313. getMessageInfo();
  314. createAlarm();
  315. }
  316. }
  317. function createAlarm() {
  318. let alarmInfo = {
  319. //1分鐘之後開始(該值不能小於1)
  320. delayInMinutes: 1,
  321. //與上方等同的寫法是
  322. // when : Date.now() + n,
  323. //開始後每一分鐘執行一次(該值不能小于1)
  324. periodInMinutes: 1
  325. };
  326. //每次加載就清空定時器
  327. chrome.alarms.clear('denetChromeAlarm');
  328. //創造定時器
  329. chrome.alarms.create('denetChromeAlarm', alarmInfo);
  330. }
  331. export function getMessageInfo() {
  332. fetchAllMessageInfo().then(res => {
  333. if (res.code == 0) {
  334. let { unReadCountTotal = 0 } = res.data;
  335. if (unReadCountTotal > 0) {
  336. let text = unReadCountTotal > 99 ? '99+' : unReadCountTotal + '';
  337. setBadgeInfo({ data: { text } });
  338. } else {
  339. hideBadge();
  340. }
  341. }
  342. })
  343. }
  344. export function readTaskAllMsg({ msgType }, cb) {
  345. fetchReadTaskAllMsg({
  346. msgType // 1:任务红包 2:钱包明细
  347. }).then(res => {
  348. if (res.code == 0) {
  349. cb && cb();
  350. }
  351. });
  352. }
  353. export const onDisconnectHandler = (port) => {
  354. if (port.name === "popup" || port.name === "popup_transactions") {
  355. let msgType = port.name === "popup" ? 1 : 2;
  356. readTaskAllMsg({ msgType }, () => {
  357. getMessageInfo();
  358. })
  359. }
  360. }
  361. export const injectExtensionPopup = (tab) => {
  362. sendActivetabMessage({
  363. actionType: 'BG_INJECT_EXTENSION_POPUP'
  364. });
  365. }
  366. export const setPopupConfig = (activeInfo) => {
  367. chrome.tabs.query({
  368. active: true,
  369. currentWindow: true
  370. }, (tabs) => {
  371. if (tabs.length) {
  372. let { pendingUrl = '', url = '' } = tabs[0];
  373. if (pendingUrl.startsWith('https://twitter.com') || url.startsWith('https://twitter.com')) {
  374. sendActivetabMessage({
  375. actionType: 'BG_SET_POPUP_CONFIG'
  376. });
  377. } else {
  378. chrome.action.setPopup({
  379. popup: 'popup.html',
  380. }, function () {
  381. });
  382. }
  383. // if(pendingUrl.startsWith('chrome://') || url.startsWith('chrome://') || pendingUrl.startsWith('https://chrome.google.com') || url.startsWith('https://chrome.google.com')) {
  384. // chrome.action.setPopup({
  385. // popup: 'popup.html',
  386. // },function() {
  387. // });
  388. // } else {
  389. // chrome.action.setPopup({
  390. // popup: '',
  391. // },function() {
  392. // });
  393. // }
  394. }
  395. })
  396. }
  397. export const getLuckMessage = () => {
  398. // 请求通知接口
  399. fetchGetAllUnReadNotices({})
  400. .then((res) => {
  401. // 向选中的content发送消息
  402. setContentMessage({ actionType: 'BACK_UNREAD_MESSAGE', data: res })
  403. })
  404. }
  405. export const windwoLoadSetPopupPage = (data, sender) => {
  406. let { url = '' } = sender.tab;
  407. if (url.startsWith('chrome://')) {
  408. chrome.action.setPopup({
  409. popup: 'popup.html',
  410. }, function () {
  411. });
  412. } else {
  413. chrome.action.setPopup({
  414. popup: '',
  415. }, function () {
  416. });
  417. }
  418. }
  419. export const setActionPopup = (data) => {
  420. let { popup } = data.data || {};
  421. if (popup) {
  422. chrome.action.getPopup(
  423. {},
  424. function (result) {
  425. if (!result) {
  426. chrome.action.setPopup({
  427. popup,
  428. }, function () {
  429. });
  430. }
  431. });
  432. } else {
  433. chrome.action.setPopup({
  434. popup: '',
  435. }, function () {
  436. });
  437. }
  438. }
  439. export const getTwitterNftPostPre = (params, sender) => {
  440. fetchGetTwitterNftPostPre(params).then((res) => {
  441. if (res.code == 0) {
  442. chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_TWITTER_NFT_POST_PRE', data: res.data }, (res) => { console.log(res) });
  443. }
  444. })
  445. }
  446. export const nftTxtPublish = (params, sender) => {
  447. fetchPublish(params).then((res) => {
  448. if (res.code == 0) {
  449. chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_NFT_PUBLISH_DONE', data: res.data }, (res) => { console.log(res) });
  450. }
  451. })
  452. }