twitter.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. // 获取全局消息数据
  84. setMessageCount()
  85. chrome.cookies.remove(LANDING_PAGE)
  86. }
  87. })
  88. })
  89. }
  90. let discordAuthWindowId = '';
  91. export function saveDiscordAuthWindowId(params) {
  92. let { windowId = '' } = params.data || {};
  93. discordAuthWindowId = windowId;
  94. }
  95. export function discordLoginCode({ code }, sender) {
  96. console.log('sender', sender)
  97. let { windowId, id } = sender.tab || {};
  98. chrome.tabs.remove(id);
  99. // 发送请求
  100. getDiscordUserInfo({
  101. authCode: code,
  102. redirectUrl: discordAuthRedirectUri
  103. }).then(res => {
  104. if (res.code == 0) {
  105. setTimeout(() => {
  106. sendActivetabMessage({
  107. actionType: 'BACK_DISCORD_LOGIN_SUCCESS'
  108. });
  109. })
  110. }
  111. })
  112. // if(windowId) {
  113. // chrome.windows.remove(
  114. // windowId,
  115. // function () {
  116. // }
  117. // )
  118. // }
  119. }
  120. export function twitterShortUrl(sender, url) {
  121. fetchTwitterShortUrl(url).then(res => {
  122. let str_arr = res.match(/denetme.net\/([\s\S]*?)"/) || []
  123. let post_Id = str_arr[1] || ''
  124. if (!post_Id) {
  125. return
  126. }
  127. // 解析
  128. let _obj = {
  129. short_url: url,
  130. post_Id
  131. }
  132. getChromeStorage('cardData', item => {
  133. if (item) {
  134. let has = false
  135. for (let i in item) {
  136. if (item[i].short_url == _obj.short_url) {
  137. item[i].short_url = _obj.short_url
  138. item[i].post_Id = _obj.post_Id
  139. setChromeStorage({ cardData: JSON.stringify(item) })
  140. has = true
  141. break
  142. }
  143. }
  144. if (!has) {
  145. item.push(_obj)
  146. setChromeStorage({ cardData: JSON.stringify(item) })
  147. }
  148. } else {
  149. setChromeStorage({ cardData: JSON.stringify([_obj]) })
  150. }
  151. chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_TWITTER_SHORT_URL' }, (response) => { });
  152. // port.postMessage({
  153. // state: "BACK_TWITTER_SHORT_URL"
  154. // });
  155. })
  156. })
  157. }
  158. // 安装插件后获取mid
  159. export function onInstalledMid() {
  160. getChromeCookie(LANDING_PAGE_MID, (res_arr) => {
  161. // 没有cookie
  162. if (res_arr && res_arr.length) {
  163. setChromeStorage({ mid: JSON.stringify(res_arr[0]) })
  164. } else {
  165. let _params = {
  166. mid: guid()
  167. }
  168. setChromeCookie(LANDING_PAGE, { 'mid': _params.mid })
  169. setChromeStorage({ mid: JSON.stringify(_params) })
  170. }
  171. })
  172. }
  173. export function onInstalledUserSet() {
  174. chrome.action.getUserSettings().then(res => {
  175. setChromeStorage({ userSettings: JSON.stringify({ res }) })
  176. // 无刷新插入js
  177. chrome.tabs.query({}, (tab) => {
  178. for (let i in tab) {
  179. chrome.scripting.executeScript({
  180. target: { tabId: tab[i].id },
  181. files: ['js/content_help.js']
  182. }, () => { })
  183. if (tab[i].url.indexOf('twitter.com') >= 0 || tab[i].url.indexOf('facebook.com') >= 0) {
  184. chrome.scripting.executeScript({
  185. target: { tabId: tab[i].id },
  186. files: ['js/content.js'],
  187. }, () => {
  188. setTimeout(() => {
  189. setChromeStorage({ executeScript: JSON.stringify({ executeScript: 1 }) })
  190. }, 2000);
  191. })
  192. }
  193. }
  194. })
  195. })
  196. }
  197. /**
  198. * 检查是否pined 显示tips
  199. */
  200. export function checkPined() {
  201. chrome.action.getUserSettings(res => {
  202. let { isOnToolbar } = res;
  203. if (!isOnToolbar) {
  204. sendActivetabMessage({
  205. actionType: 'BG_SHOW_PIN_TIPS'
  206. });
  207. }
  208. })
  209. }
  210. function sendActivetabMessage(message = {}) {
  211. chrome.tabs.query({
  212. active: true,
  213. currentWindow: true
  214. }, (tabs) => {
  215. chrome.tabs.sendMessage(tabs[0].id, message, res => {
  216. console.log(res)
  217. })
  218. })
  219. }
  220. /**
  221. * 安装后打开新标签页
  222. */
  223. export function onInstalledCreateTab() {
  224. let cookiesParams = {
  225. name: 'pickup_info',
  226. url: pageUrl
  227. }
  228. getChromeCookie(cookiesParams, (res) => {
  229. let { postNickName, srcContentId } = res;
  230. if (res && postNickName && srcContentId) {
  231. let url = `https://twitter.com/${postNickName}/status/${srcContentId}`
  232. chrome.tabs.create({
  233. url
  234. });
  235. removeChromeCookie(cookiesParams)
  236. } else {
  237. chrome.tabs.create({
  238. url: "https://twitter.com",
  239. });
  240. }
  241. })
  242. }
  243. /**
  244. * 在popop重新发送
  245. * @param {*} req
  246. */
  247. export function popupRePublish(req) {
  248. setChromeStorage({
  249. popupShowPublishDialog: JSON.stringify({
  250. ...req.data,
  251. show: true
  252. }),
  253. });
  254. chrome.tabs.create({
  255. url: "https://twitter.com",
  256. });
  257. }
  258. export function setBadgeInfo(params) {
  259. let { text = '', color = '#DF3535' } = params.data || {};
  260. chrome.action.setBadgeText({ text: text });
  261. chrome.action.setBadgeBackgroundColor({ color: color });
  262. }
  263. export function hideBadge() {
  264. chrome.action.setBadgeText({ text: '' });
  265. chrome.action.setBadgeBackgroundColor({ color: [0, 0, 0, 0] });
  266. }
  267. export async function setMessageCount() {
  268. const { accessToken: token = '', uid = '' } = await getChromeStorage('userInfo') || {}
  269. if (token) {
  270. getMessageInfo();
  271. createAlarm();
  272. }
  273. }
  274. function createAlarm() {
  275. let alarmInfo = {
  276. //1分鐘之後開始(該值不能小於1)
  277. delayInMinutes: 1,
  278. //與上方等同的寫法是
  279. // when : Date.now() + n,
  280. //開始後每一分鐘執行一次(該值不能小于1)
  281. periodInMinutes: 1
  282. };
  283. //每次加載就清空定時器
  284. chrome.alarms.clear('denetChromeAlarm');
  285. //創造定時器
  286. chrome.alarms.create('denetChromeAlarm', alarmInfo);
  287. }
  288. export function getMessageInfo() {
  289. fetchAllMessageInfo().then(res => {
  290. if (res.code == 0) {
  291. let { unReadCountTotal = 0 } = res.data;
  292. if (unReadCountTotal > 0) {
  293. let text = unReadCountTotal > 99 ? '99+' : unReadCountTotal + '';
  294. setBadgeInfo({ data: { text } });
  295. } else {
  296. hideBadge();
  297. }
  298. }
  299. })
  300. }
  301. export function readTaskAllMsg({ msgType }, cb) {
  302. fetchReadTaskAllMsg({
  303. msgType // 1:任务红包 2:钱包明细
  304. }).then(res => {
  305. if (res.code == 0) {
  306. cb && cb();
  307. }
  308. });
  309. }
  310. export const onDisconnectHandler = (port) => {
  311. if (port.name === "popup" || port.name === "popup_transactions") {
  312. let msgType = port.name === "popup" ? 1 : 2;
  313. readTaskAllMsg({ msgType }, () => {
  314. getMessageInfo();
  315. })
  316. }
  317. }
  318. export const injectExtensionPopup = (tab) => {
  319. sendActivetabMessage({
  320. actionType: 'BG_INJECT_EXTENSION_POPUP'
  321. });
  322. }