twitter.js 13 KB

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