twitter.js 10 KB

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