Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

add redux

Maksim Mrug5a25a3cdbfea
diff --git a/app/redux/constants/index.ts b/app/redux/constants/index.ts
new file mode 100644
index 000000000..56c6ce16e
--- /dev/null
+++ b/app/redux/constants/index.ts
@@ -0,0 +1,543 @@
+const getCustomLabel = (dates: Date[], t: Function): string => {
+ if (dates) {
+ const from = dates[0].toLocaleDateString()
+ const to = dates[1].toLocaleDateString()
+
+ if (from === to) {
+ return from
+ }
+
+ return `${from} - ${to}`
+ }
+
+ return t('project.custom')
+}
+
+export const FORECAST_MAX_MAPPING: {
+ [key: string]: number
+} = {
+ hour: 72,
+ day: 21,
+ month: 12,
+}
+
+export const tbPeriodPairs = (t: Function, tbs?: string[] | null, dates?: Date[]): {
+ label: string
+ period: string
+ tbs: string[]
+ countDays?: number
+ dropdownLabel?: string
+ isCustomDate?: boolean
+}[] => [{
+ label: t('project.today'),
+ period: 'today',
+ tbs: ['hour'],
+}, {
+ label: t('project.yesterday'),
+ period: 'yesterday',
+ tbs: ['hour'],
+}, {
+ label: t('project.last24h'),
+ period: '1d',
+ countDays: 1,
+ tbs: ['hour'],
+}, {
+ label: t('project.lastXDays', { amount: 7 }),
+ period: '7d',
+ tbs: ['hour', 'day'],
+ countDays: 7,
+}, {
+ label: t('project.lastXWeeks', { amount: 4 }),
+ period: '4w',
+ tbs: ['day'],
+ countDays: 28,
+}, {
+ label: t('project.lastXMonths', { amount: 3 }),
+ period: '3M',
+ tbs: ['month'],
+ countDays: 90,
+}, {
+ label: t('project.lastXMonths', { amount: 12 }),
+ period: '12M',
+ tbs: ['month'],
+ countDays: 365,
+}, {
+ label: t('project.lastXMonths', { amount: 24 }),
+ period: '24M',
+ tbs: ['month'],
+}, {
+ label: dates ? getCustomLabel(dates, t) : t('project.custom'),
+ dropdownLabel: t('project.custom'),
+ isCustomDate: true,
+ period: 'custom',
+ tbs: tbs || ['custom'],
+}, {
+ label: t('project.compare'),
+ period: 'compare',
+ tbs: tbs || ['custom'],
+}]
+
+export const filtersPeriodPairs = ['1d', '7d', '4w', '3M', '12M', 'custom', 'compare']
+
+export const tbPeriodPairsCompare = (t: Function, dates?: Date[]): {
+ label: string
+ period: string
+}[] => [{
+ label: t('project.previousPeriod'),
+ period: 'previous',
+}, {
+ label: dates ? getCustomLabel(dates, t) : t('project.custom'),
+ period: 'custom',
+}, {
+ label: t('project.disableCompare'),
+ period: 'disable',
+}]
+
+export const PERIOD_PAIRS_COMPARE: {
+ COMPARE: string
+ PREVIOS: string
+ CUSTOM: string
+ DISABLE: string
+} = {
+ COMPARE: 'compare',
+ PREVIOS: 'previous',
+ CUSTOM: 'custom',
+ DISABLE: 'disable',
+}
+
+interface IStringObject {
+ [key: string]: string
+}
+
+// the order of panels in the project view
+export const TRAFFIC_PANELS_ORDER: string[] = ['cc', 'pg', 'lc', 'br', 'os', 'dv', 'ref', 'so', 'me', 'ca']
+export const PERFORMANCE_PANELS_ORDER: string[] = ['cc', 'pg', 'br', 'dv']
+
+// the maximum amount of months user can go back when picking a date in flat picker (project view)
+export const MAX_MONTHS_IN_PAST: number = 24
+
+export const timeBucketToDays: {
+ lt: number
+ tb: string[]
+}[] = [
+ { lt: 1, tb: ['hour'] }, // 1 days
+ { lt: 7, tb: ['hour', 'day'] }, // 7 days
+ { lt: 28, tb: ['day'] }, // 4 weeks
+ { lt: 366, tb: ['month'] }, // 12 months
+ { lt: 732, tb: ['month'] }, // 24 months
+]
+
+export const tbsFormatMapper: IStringObject = {
+ hour: '%I %p',
+ day: '%d %b',
+ month: '%b %Y',
+}
+
+export const tbsFormatMapperTooltip: IStringObject = {
+ hour: '%d %b %I %p',
+ day: '%d %b',
+ month: '%b %Y',
+}
+
+export const tbsFormatMapperTooltip24h: IStringObject = {
+ hour: '%d %b %H:%M',
+ day: '%d %b',
+ month: '%b %Y',
+}
+
+export const tbsFormatMapper24h: IStringObject = {
+ hour: '%H:%M',
+ day: '%d %b',
+ month: '%b %Y',
+}
+
+export const TimeFormat: IStringObject = {
+ '12-hour': '12-hour',
+ '24-hour': '24-hour',
+}
+
+export const FREE_TIER_KEY: string = 'free'
+
+export const PADDLE_JS_URL = 'https://cdn.paddle.com/paddle/paddle.js'
+export const PADDLE_VENDOR_ID = 139393
+
+// a dedicated variable is needed for paid tier checking
+export const WEEKLY_REPORT_FREQUENCY: string = 'weekly'
+export const reportFrequencies: string[] = [WEEKLY_REPORT_FREQUENCY, 'monthly', 'quarterly', 'never']
+
+export const reportFrequencyForEmailsOptions: {
+ value: string
+ label: string
+}[] = [
+ { value: 'quarterly', label: 'Quarterly' },
+ { value: 'monthly', label: 'Monthly' },
+ { value: 'weekly', label: 'Weekly' },
+ { value: 'never', label: 'Never' },
+]
+
+export const GDPR_EXPORT_TIMEFRAME: number = 14 // days
+
+export const SHOW_BANNER_AT_PERC: number = 85 // show banner when 85% of events in tier are used
+
+export const TITLE_SUFFIX: string = '| Swetrix'
+
+export const LS_THEME_SETTING: string = 'colour-theme'
+export const LS_VIEW_PREFS_SETTING: string = 'proj-view-preferences'
+export const LS_CAPTCHA_VIEW_PREFS_SETTING: string = 'captcha-view-preferences'
+
+export const DEFAULT_TIMEZONE: string = 'Etc/GMT'
+
+export const DONATE_URL: string = 'https://ko-fi.com/andriir'
+export const FIREFOX_ADDON_URL: string = 'https://addons.mozilla.org/en-US/firefox/addon/swetrix/'
+export const CHROME_EXTENSION_URL: string = 'https://chrome.google.com/webstore/detail/swetrix/glbeclfdldjldjonfnpnembfkhphmeld'
+export const HAVE_I_BEEN_PWNED_URL: string = 'https://haveibeenpwned.com/passwords'
+export const LINKEDIN_URL: string = 'https://www.linkedin.com/company/swetrix/'
+export const GITHUB_URL: string = 'https://github.com/Swetrix'
+export const TWITTER_URL: string = 'https://twitter.com/intent/user?screen_name=swetrix'
+export const TWITTER_USERNAME: string = '@swetrix'
+export const DISCORD_URL: string = 'https://discord.gg/tVxGxU3s4B'
+export const STATUSPAGE_URL: string = 'https://stats.uptimerobot.com/33rvmiXXEz'
+export const BLOG_URL: string = 'https://blog.swetrix.com'
+export const UTM_GENERATOR_URL: string = 'https://url.swetrix.com'
+export const LIVE_DEMO_URL: string = '/projects/STEzHcB1rALV'
+export const MARKETPLACE_URL: string = 'https://marketplace.swetrix.com'
+export const DOCS_URL: string = 'https://docs.swetrix.com'
+export const CAPTCHA_URL: string = 'https://captcha.swetrix.com'
+export const DOCS_CAPTCHA_URL: string = `${DOCS_URL}/captcha/introduction`
+export const CDN_URL: string | undefined = process.env.REACT_APP_CDN_URL
+
+// Swetrix vs ...
+export const SWETRIX_VS_GOOGLE: string = 'https://blog.swetrix.com/post/vs-google-analytics/'
+export const SWETRIX_VS_CLOUDFLARE: string = 'https://blog.swetrix.com/post/vs-cloudflare-analytics/'
+export const SWETRIX_VS_SIMPLE_ANALYTICS: string = 'https://blog.swetrix.com/post/vs-simple-analytics/'
+
+export const isDevelopment: boolean = !process.env.NODE_ENV || process.env.NODE_ENV === 'development'
+
+export const SUPPORTED_THEMES: string[] = ['light', 'dark']
+
+export const CONTACT_EMAIL: string = '[email protected]'
+export const SECURITY_EMAIL: string = '[email protected]'
+
+export const isSelfhosted: boolean = Boolean(process.env.REACT_APP_SELFHOSTED)
+
+export const LIVE_VISITORS_UPDATE_INTERVAL: number = 40000
+
+// Functions
+export const getProjectCacheKey = (period: string, timeBucket: string): string => `${period}${timeBucket}`
+export const getProjectCaptchaCacheKey = (period: string, timeBucket: string): string => `${period}${timeBucket}captcha`
+export const getProjectForcastCacheKey = (period: string, timeBucket: string, periodToForecast: string): string => `${period}${timeBucket}${periodToForecast}forecast`
+export const getProjectCacheCustomKey = (from: string, to: string, timeBucket: string): string => `${from}-${to}-${timeBucket}`
+export const getProjectCacheCustomKeyPerf = (from: string, to: string, timeBucket: string): string => `${from}-${to}-${timeBucket}perf`
+export const getUserFlowCacheKey = (pid: string, period: string): string => `${pid}${period}userflow`
+
+// Cookies
+export const GDPR_REQUEST: string = 'gdpr_request'
+export const CONFIRMATION_TIMEOUT: string = 'confirmation_timeout'
+export const LOW_EVENTS_WARNING: string = 'low_events_warning'
+export const TOKEN: string = 'access_token'
+export const REFRESH_TOKEN: string = 'refresh_token'
+
+// LocalStorage
+export const PAGE_FORCE_REFRESHED = 'page-force-refreshed'
+export const PROJECTS_PROTECTED = 'projects_protected'
+
+export const IS_ACTIVE_COMPARE = 'is-active-compare'
+
+// List of languages with translations available
+export const whitelist: string[] = ['en', 'uk', 'pl', 'de', 'sv', 'el', 'ru', 'hi', 'zh']
+export const defaultLanguage: string = 'en'
+export const languages: IStringObject = {
+ en: 'English',
+ uk: 'Українська',
+ pl: 'Polski',
+ de: 'Deutsch',
+ sv: 'Svenska',
+ el: 'Ελληνικά',
+ ru: 'Русский',
+ hi: 'हिन्दी',
+ zh: '中文简体',
+}
+
+export const languageFlag: IStringObject = {
+ en: 'GB',
+ uk: 'UA',
+ pl: 'PL',
+ de: 'DE',
+ sv: 'SE',
+ el: 'GR',
+ ru: 'RU',
+ hi: 'IN',
+ zh: 'CN',
+}
+
+export const paddleLanguageMapping: IStringObject = {
+ zh: 'zh-Hans',
+ uk: 'ru',
+ el: 'en',
+}
+
+// dashboard && projects
+
+export const roles: string[] = ['admin', 'viewer']
+
+export const roleViewer: {
+ name: string
+ role: string
+ description: string
+} = {
+ name: 'Viewer',
+ role: 'viewer',
+ description: 'Can view the project',
+}
+
+export const roleAdmin: {
+ name: string
+ role: string
+ description: string
+} = {
+ name: 'Admin',
+ role: 'admin',
+ description: 'Can manage the project',
+}
+
+export const tabForOwnedProject: string = 'owned'
+export const tabForSharedProject: string = 'shared'
+export const tabForCaptchaProject: string = 'captcha'
+
+interface IDashboardTabs {
+ name: string
+ label: string
+}
+
+export const tabsForDashboard: IDashboardTabs[] = [
+ {
+ name: tabForOwnedProject,
+ label: 'profileSettings.owned',
+ },
+ {
+ name: tabForSharedProject,
+ label: 'profileSettings.shared',
+ },
+ {
+ name: tabForCaptchaProject,
+ label: 'profileSettings.captcha',
+ },
+]
+
+const SELFHOSTED_PROJECT_TABS: IStringObject = {
+ traffic: 'traffic',
+ performance: 'performance',
+}
+
+const PRODUCTION_PROJECT_TABS: IStringObject = {
+ traffic: 'traffic',
+ performance: 'performance',
+ alerts: 'alerts',
+}
+
+export const PROJECT_TABS = isSelfhosted ? SELFHOSTED_PROJECT_TABS : PRODUCTION_PROJECT_TABS
+
+export const DASHBOARD_TABS: IStringObject = {
+ owned: 'owned',
+ shared: 'shared',
+ captcha: 'captcha',
+}
+
+export const QUERY_METRIC: IStringObject = {
+ PAGE_VIEWS: 'page_views',
+ UNIQUE_PAGE_VIEWS: 'unique_page_views',
+ ONLINE_USERS: 'online_users',
+}
+
+export const QUERY_CONDITION: IStringObject = {
+ GREATER_THAN: 'greater_than',
+ GREATER_EQUAL_THAN: 'greater_equal_than',
+ LESS_THAN: 'less_than',
+ LESS_EQUAL_THAN: 'less_equal_than',
+}
+
+export const QUERY_TIME: IStringObject = {
+ LAST_15_MINUTES: 'last_15_minutes',
+ LAST_30_MINUTES: 'last_30_minutes',
+ LAST_1_HOUR: 'last_1_hour',
+ LAST_4_HOURS: 'last_4_hours',
+ LAST_24_HOURS: 'last_24_hours',
+ LAST_48_HOURS: 'last_48_hours',
+}
+
+export const INVITATION_EXPIRES_IN: number = 48 // hours
+export const ENTRIES_PER_PAGE_DASHBOARD: number = 11
+
+export const THEME_TYPE: IStringObject = {
+ classic: 'classic',
+ christmas: 'christmas',
+}
+
+export const DEFAULT_ALERTS_TAKE: number = 100
+
+const EUR = {
+ symbol: '€',
+ code: 'EUR',
+}
+
+const USD = {
+ symbol: '$',
+ code: 'USD',
+}
+
+const GBP = {
+ symbol: '£',
+ code: 'GBP',
+}
+
+type ICurrencies = {
+ [key in 'EUR' | 'USD' | 'GBP']: {
+ symbol: string
+ code: string
+ }
+}
+
+export const CURRENCIES: ICurrencies = {
+ EUR, USD, GBP,
+}
+
+// TODO: Eventually this should be fetched from the API, e.g. GET /config route
+export const PLAN_LIMITS = {
+ free: {
+ monthlyUsageLimit: 5000,
+ maxProjects: 10,
+ maxAlerts: 1,
+ legacy: true,
+ price: {
+ USD: {
+ monthly: 0,
+ yearly: 0,
+ },
+ EUR: {
+ monthly: 0,
+ yearly: 0,
+ },
+ GBP: {
+ monthly: 0,
+ yearly: 0,
+ },
+ },
+ },
+ trial: {
+ monthlyUsageLimit: 100000,
+ maxProjects: 20,
+ maxAlerts: 20,
+ legacy: false,
+ price: {
+ USD: {
+ monthly: 0,
+ yearly: 0,
+ },
+ EUR: {
+ monthly: 0,
+ yearly: 0,
+ },
+ GBP: {
+ monthly: 0,
+ yearly: 0,
+ },
+ },
+ },
+ hobby: {
+ monthlyUsageLimit: 10000,
+ maxProjects: 20,
+ maxAlerts: 10,
+ legacy: false,
+ price: {
+ USD: {
+ monthly: 5,
+ yearly: 50,
+ },
+ EUR: {
+ monthly: 5,
+ yearly: 50,
+ },
+ GBP: {
+ monthly: 4,
+ yearly: 40,
+ },
+ },
+ },
+ freelancer: {
+ monthlyUsageLimit: 100000,
+ maxProjects: 20,
+ maxAlerts: 20,
+ legacy: false,
+ price: {
+ USD: {
+ monthly: 15,
+ yearly: 150,
+ },
+ EUR: {
+ monthly: 15,
+ yearly: 150,
+ },
+ GBP: {
+ monthly: 14,
+ yearly: 140,
+ },
+ },
+ },
+ startup: {
+ monthlyUsageLimit: 1000000,
+ maxProjects: 30,
+ maxAlerts: 50,
+ legacy: false,
+ price: {
+ USD: {
+ monthly: 59,
+ yearly: 590,
+ },
+ EUR: {
+ monthly: 57,
+ yearly: 570,
+ },
+ GBP: {
+ monthly: 49,
+ yearly: 490,
+ },
+ },
+ },
+ enterprise: {
+ monthlyUsageLimit: 5000000,
+ maxProjects: 50,
+ maxAlerts: 100,
+ legacy: false,
+ price: {
+ USD: {
+ monthly: 110,
+ yearly: 1100,
+ },
+ EUR: {
+ monthly: 110,
+ yearly: 1100,
+ },
+ GBP: {
+ monthly: 95,
+ yearly: 950,
+ },
+ },
+ },
+}
+
+export const TRIAL_DAYS: number = 14
+
+export const chartTypes = Object.freeze({
+ line: 'line',
+ bar: 'bar',
+})
+
+export const SSO_ACTIONS = Object.freeze({
+ LINK: 'link',
+ AUTH: 'auth',
+})
+
+export const SSO_PROVIDERS = Object.freeze({
+ GOOGLE: 'google',
+ GITHUB: 'github',
+})
diff --git a/app/redux/models/IAlerts.ts b/app/redux/models/IAlerts.ts
new file mode 100644
index 000000000..cd0374c3c
--- /dev/null
+++ b/app/redux/models/IAlerts.ts
@@ -0,0 +1,14 @@
+import { QUERY_METRIC, QUERY_CONDITION, QUERY_TIME } from '../constants'
+
+export interface IAlerts {
+ id: string
+ name: string
+ active: boolean
+ created: string
+ lastTriggered: string | null
+ queryMetric: keyof typeof QUERY_METRIC
+ queryCondition: keyof typeof QUERY_CONDITION
+ queryValue: number
+ queryTime: keyof typeof QUERY_TIME
+ pid: string
+}
diff --git a/app/redux/models/IAnalytics.ts b/app/redux/models/IAnalytics.ts
new file mode 100644
index 000000000..7429ef710
--- /dev/null
+++ b/app/redux/models/IAnalytics.ts
@@ -0,0 +1,3 @@
+// export interface IAnalytics {
+
+// }
diff --git a/app/redux/models/IAuth.ts b/app/redux/models/IAuth.ts
new file mode 100644
index 000000000..99ebe9b8d
--- /dev/null
+++ b/app/redux/models/IAuth.ts
@@ -0,0 +1,7 @@
+import { IUser } from './IUser'
+
+export interface IAuth {
+ refresh_token: string
+ access_token: string
+ user: IUser
+}
diff --git a/app/redux/models/IMetainfo.ts b/app/redux/models/IMetainfo.ts
new file mode 100644
index 000000000..f79f52a1b
--- /dev/null
+++ b/app/redux/models/IMetainfo.ts
@@ -0,0 +1,5 @@
+export interface IMetainfo {
+ country: string | null
+ symbol: string
+ code: 'USD' | 'EUR' | 'GBP'
+}
diff --git a/app/redux/models/IProject.ts b/app/redux/models/IProject.ts
new file mode 100644
index 000000000..2d96f65b1
--- /dev/null
+++ b/app/redux/models/IProject.ts
@@ -0,0 +1,76 @@
+export interface IOvervallObject {
+ thisWeek?: number
+ lastWeek?: number
+ thisWeekUnique?: number
+ lastWeekUnique?: number
+ percChange?: number
+ total?: number
+ percChangeUnique?: number
+}
+
+export interface IOverall {
+ [key: string]: IOvervallObject
+}
+
+export interface IUserShareProject {
+ email: string
+}
+
+export interface ILiveStats {
+ [key: string]: number
+}
+
+export interface IShareOwnerProject {
+ id: string
+ confirmed: boolean
+ role: string
+ created: string
+ updated: string
+ user: IUserShareProject
+}
+
+export interface IProjectNames {
+ name: string
+ id: string
+ isCaptchaProject: boolean
+}
+
+export interface IProject {
+ id: string
+ name: string
+ origins: string[] | string | null
+ ipBlacklist: string[] | null | string
+ active: boolean
+ public: boolean
+ isAnalyticsProject: boolean
+ isCaptchaProject: boolean
+ isCaptchaEnabled: boolean
+ captchaSecretKey: string | null
+ created: string
+ share?: IShareOwnerProject[]
+ isOwner: boolean
+ overall: IOvervallObject
+ uiHidden: boolean
+ isPublicVisitors?: boolean
+ isPublic?: boolean
+ isTransferring?: boolean
+ isPasswordProtected?: boolean
+ password?: string
+}
+
+export interface ICaptchaProject {
+ id: string
+ name: string
+ origins: string[] | string | null
+ ipBlacklist: string[] | null | string
+ active: boolean
+ public: boolean
+ isAnalyticsProject: boolean
+ isCaptchaProject: boolean
+ isCaptchaEnabled: boolean
+ captchaSecretKey: string | null
+ created: string
+ isOwner: boolean
+ overall: IOvervallObject
+ uiHidden: boolean
+}
diff --git a/app/redux/models/ISharedProject.ts b/app/redux/models/ISharedProject.ts
new file mode 100644
index 000000000..6d9cecd50
--- /dev/null
+++ b/app/redux/models/ISharedProject.ts
@@ -0,0 +1,16 @@
+import { IProject } from './IProject'
+
+export interface IProjectForShared extends IProject {
+ shared?: boolean
+ role?: string
+}
+
+export interface ISharedProject {
+ id: string
+ confirmed: boolean
+ role: string
+ created: string
+ updated: string
+ project: IProjectForShared
+ uiHidden: boolean
+}
diff --git a/app/redux/models/IStats.ts b/app/redux/models/IStats.ts
new file mode 100644
index 000000000..5ca470ba2
--- /dev/null
+++ b/app/redux/models/IStats.ts
@@ -0,0 +1,5 @@
+export interface IStats {
+ users: number
+ projects: number
+ events: number
+}
diff --git a/app/redux/models/ISubscribers.ts b/app/redux/models/ISubscribers.ts
new file mode 100644
index 000000000..d8909a851
--- /dev/null
+++ b/app/redux/models/ISubscribers.ts
@@ -0,0 +1,14 @@
+import { reportFrequencies } from '../constants'
+
+export interface ISubscribers {
+ userId: string
+ projectId: string
+ projectName: string
+ email: string
+ reportFrequency: typeof reportFrequencies[number]
+ origin: string
+ id: string
+ isConfirmed: boolean
+ addedAt: string
+ updatedAt: string
+}
diff --git a/app/redux/models/IUsageinfo.ts b/app/redux/models/IUsageinfo.ts
new file mode 100644
index 000000000..755fa9e16
--- /dev/null
+++ b/app/redux/models/IUsageinfo.ts
@@ -0,0 +1,9 @@
+export interface IUsageInfo {
+ total: number
+ traffic: number
+ customEvents: number
+ captcha: number
+ trafficPerc: number
+ customEventsPerc: number
+ captchaPerc: number
+}
diff --git a/app/redux/models/IUser.ts b/app/redux/models/IUser.ts
new file mode 100644
index 000000000..6944dfdcc
--- /dev/null
+++ b/app/redux/models/IUser.ts
@@ -0,0 +1,39 @@
+import { ISharedProject } from './ISharedProject'
+
+export interface IUser {
+ id: string
+ roles: string[]
+ planCode: string
+ nickname: string
+ email: string
+ isActive: boolean
+ trialEndDate: string
+ reportFrequency: string
+ emailRequests: number
+ created: string
+ updated: string
+ evWarningSentOn: string | null
+ exportedAt: string
+ subID: string | null
+ subUpdateURL: string | null
+ subCancelURL: string | null
+ timezone: string
+ theme: string | null
+ isTwoFactorAuthenticationEnabled: boolean
+ trialReminderSent: boolean
+ billingFrequency: string | null
+ nextBillDate: string | null
+ cancellationEffectiveDate: string | null
+ apiKey: string | null
+ telegramChatId: string | null
+ isTelegramChatIdConfirmed: boolean
+ timeFormat: string
+ sharedProjects: ISharedProject[]
+ registeredWithGoogle: boolean
+ googleId: string | null
+ githubId: number | null
+ registeredWithGithub: boolean
+ maxEventsCount: number
+ tierCurrency: 'USD' | 'EUR' | 'GBP' | null
+ showLiveVisitorsInTitle: boolean
+}
diff --git a/app/redux/models/IUserFlow.ts b/app/redux/models/IUserFlow.ts
new file mode 100644
index 000000000..507f3999b
--- /dev/null
+++ b/app/redux/models/IUserFlow.ts
@@ -0,0 +1,12 @@
+interface UserFlow {
+ nodes: {
+ id: string
+ }[]
+ links: {
+ source: string
+ target: string
+ value: number
+ }[]
+}
+
+export type IUserFlow = UserFlow | null
diff --git a/app/redux/reducers/alerts.ts b/app/redux/reducers/alerts.ts
new file mode 100644
index 000000000..a0f9a0ff6
--- /dev/null
+++ b/app/redux/reducers/alerts.ts
@@ -0,0 +1,41 @@
+/* eslint-disable no-param-reassign */
+import { createSlice, PayloadAction } from '@reduxjs/toolkit'
+
+interface IInitialState {
+ message: null | string
+ type: string
+}
+
+const initialState: IInitialState = {
+ message: null,
+ type: 'info',
+}
+
+const alertsCreate = (state: IInitialState, { payload }: PayloadAction<{ message: string, type?: string }>) => {
+ state.message = payload.message
+ state.type = payload.type || 'info'
+}
+
+const alertsSlice = createSlice({
+ name: 'alerts',
+ initialState,
+ reducers: {
+ accountDeleted: alertsCreate,
+ accountUpdated: alertsCreate,
+ newPassword: alertsCreate,
+ deleteProjectSuccess: alertsCreate,
+ createNewProjectSuccess: alertsCreate,
+ roleUpdated: alertsCreate,
+ inviteUser: alertsCreate,
+ removeUser: alertsCreate,
+ userSharedUpdate: alertsCreate,
+ generateAlerts: alertsCreate,
+ clearAlerts: (state) => {
+ state.message = null
+ state.type = 'info'
+ },
+ },
+})
+
+export const alertsActions = alertsSlice.actions
+export default alertsSlice.reducer
diff --git a/app/redux/reducers/auth.ts b/app/redux/reducers/auth.ts
new file mode 100644
index 000000000..c1253377b
--- /dev/null
+++ b/app/redux/reducers/auth.ts
@@ -0,0 +1,99 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
+/* eslint-disable no-unused-expressions */
+/* eslint-disable no-param-reassign */
+import { createSlice, current, PayloadAction } from '@reduxjs/toolkit'
+import _filter from 'lodash/filter'
+import _map from 'lodash/map'
+import { IUser } from '../models/IUser'
+import { FREE_TIER_KEY, isSelfhosted } from '../constants'
+import { ISharedProject } from '../models/ISharedProject'
+
+interface IAuthState {
+ user: IUser
+ redirectPath: string | null
+ authenticated: boolean
+ loading: boolean
+ dontRemember: boolean
+ isPaidTierUsed: boolean
+}
+
+const initialState: IAuthState = {
+ user: {} as IUser,
+ redirectPath: null,
+ authenticated: false,
+ loading: true,
+ dontRemember: false,
+ // if the app is selfhosted, we assume that the user is using a paid tier so there won't be any restrictions or advertising of it
+ isPaidTierUsed: isSelfhosted,
+}
+
+const authSlice = createSlice({
+ name: 'auth',
+ initialState,
+ reducers: {
+ finishLoading: (state) => {
+ state.loading = false
+ },
+ loginSuccessful: (state, { payload }: PayloadAction<IUser>) => {
+ state.user = payload
+ state.authenticated = true
+ state.isPaidTierUsed = isSelfhosted || (payload?.planCode && payload.planCode !== FREE_TIER_KEY) as boolean
+ },
+ emailVerifySuccessful: (state) => {
+ state.user = { ...state.user, isActive: true }
+ },
+ signupUpSuccessful: (state, { payload }: PayloadAction<IUser>) => {
+ state.user = payload
+ state.authenticated = true
+ state.isPaidTierUsed = isSelfhosted || (payload?.planCode && payload.planCode !== FREE_TIER_KEY) as boolean
+ },
+ updateUserProfileSuccess: (state, { payload }: PayloadAction<IUser>) => {
+ state.user = payload
+ },
+ partiallyOverwriteUser: (state, { payload }: PayloadAction<Partial<IUser>>) => {
+ state.user = { ...state.user, ...payload }
+ },
+ logout: (state) => {
+ state.user = {} as IUser
+ state.authenticated = false
+ state.isPaidTierUsed = isSelfhosted
+ },
+ savePath: (state, { payload }: PayloadAction<string>) => {
+ state.redirectPath = payload
+ },
+ deleteAccountSuccess: (state) => {
+ state.user = {} as IUser
+ state.authenticated = false
+ state.isPaidTierUsed = isSelfhosted
+ },
+ deleteShareProject: (state, { payload }: PayloadAction<string>) => {
+ const projects = _filter(state.user?.sharedProjects, (item) => item.id !== payload)
+ state.user = { ...state.user, sharedProjects: projects }
+ },
+ setUserShareData: (state, { payload }: PayloadAction<{ data: Partial<ISharedProject>, id: string }>) => {
+ const projects = _map(current(state.user?.sharedProjects), (item) => {
+ if (item.id === payload.id) {
+ return { ...item, ...payload.data }
+ }
+ return item
+ })
+ state.user = { ...state.user, sharedProjects: projects }
+ },
+ setDontRemember: (state, { payload }: PayloadAction<boolean>) => {
+ state.dontRemember = payload
+ },
+ updateUserData: (state, { payload }: PayloadAction<IUser>) => {
+ state.user = { ...state.user, ...payload }
+ },
+ setApiKey: (state, { payload }: PayloadAction<string>) => {
+ state.user = { ...state.user, apiKey: payload }
+ },
+ setUser: (state, { payload }: PayloadAction<IUser>) => {
+ state.user = { ...state.user, ...payload }
+ },
+ },
+})
+
+export const authActions = authSlice.actions
+
+export default authSlice.reducer
diff --git a/app/redux/reducers/errors.ts b/app/redux/reducers/errors.ts
new file mode 100644
index 000000000..58ce4ecce
--- /dev/null
+++ b/app/redux/reducers/errors.ts
@@ -0,0 +1,39 @@
+/* eslint-disable no-param-reassign */
+import { createSlice, PayloadAction } from '@reduxjs/toolkit'
+
+interface IInitialState {
+ error: null | string
+}
+
+const initialState: IInitialState = {
+ error: null,
+}
+
+const errorsCreate = (state: IInitialState, { payload }: PayloadAction<{ message: string }>) => {
+ state.error = payload.message
+}
+
+const errorsSlice = createSlice({
+ name: 'alerts',
+ initialState,
+ reducers: {
+ genericError: errorsCreate,
+ setError: errorsCreate,
+ loginFailed: errorsCreate,
+ signUpFailed: errorsCreate,
+ updateUserProfileFailed: errorsCreate,
+ createNewPasswordFailed: errorsCreate,
+ deleteAccountFailed: errorsCreate,
+ createNewProjectFailed: errorsCreate,
+ updateProjectFailed: errorsCreate,
+ deleteProjectFailed: errorsCreate,
+ gdprExportFailed: errorsCreate,
+ sharedProjectFailed: errorsCreate,
+ clearErrors: (state) => {
+ state.error = null
+ },
+ },
+})
+
+export const errorsActions = errorsSlice.actions
+export default errorsSlice.reducer
diff --git a/app/redux/reducers/ui/alerts.ts b/app/redux/reducers/ui/alerts.ts
new file mode 100644
index 000000000..5596ffa0b
--- /dev/null
+++ b/app/redux/reducers/ui/alerts.ts
@@ -0,0 +1,37 @@
+import { createSlice, PayloadAction } from '@reduxjs/toolkit'
+import { IAlerts } from 'redux/models/IAlerts'
+
+interface IInitialState {
+ alerts: IAlerts[]
+ total: number
+ pageTotal: number
+ loading: boolean
+}
+
+const initialState: IInitialState = {
+ alerts: [],
+ total: 0,
+ pageTotal: 0,
+ loading: false,
+}
+
+const alertsSlice = createSlice({
+ name: 'alerts',
+ initialState,
+ reducers: {
+ setProjectAlerts(state, action: PayloadAction<IAlerts[]>) {
+ state.alerts = action.payload
+ },
+ setProjectAlertsTotal(state, { payload }: PayloadAction<{ total: number, pageTotal?: number }>) {
+ state.total = payload.total
+ state.pageTotal = payload.pageTotal || state.pageTotal
+ },
+ setProjectAlertsLoading(state, { payload }: PayloadAction<boolean>) {
+ state.loading = payload
+ },
+ },
+})
+
+export const alertsActions = alertsSlice.actions
+
+export default alertsSlice.reducer
diff --git a/app/redux/reducers/ui/cache.ts b/app/redux/reducers/ui/cache.ts
new file mode 100644
index 000000000..19993a915
--- /dev/null
+++ b/app/redux/reducers/ui/cache.ts
@@ -0,0 +1,221 @@
+import { createSlice, PayloadAction } from '@reduxjs/toolkit'
+import _filter from 'lodash/filter'
+import _isEmpty from 'lodash/isEmpty'
+import { getItem, removeItem, setItem } from 'utils/localstorage'
+import {
+ getProjectCacheKey, LS_VIEW_PREFS_SETTING, LS_CAPTCHA_VIEW_PREFS_SETTING, getProjectCaptchaCacheKey, getUserFlowCacheKey,
+} from 'redux/constants'
+import { IUserFlow } from 'redux/models/IUserFlow'
+
+export const getInitialViewPrefs = (LS_VIEW: string) => {
+ if (typeof window !== 'undefined' && window.localStorage) {
+ const storedPrefs = getItem(LS_VIEW)
+ try {
+ return storedPrefs
+ } catch (e) {
+ removeItem(LS_VIEW)
+ }
+ }
+
+ return {}
+}
+
+interface IInitialState {
+ analytics: any
+ analyticsPerf: any
+ captchaAnalytics: any
+ captchaProjectsViewPrefs: any
+ customEventsPrefs: any
+ projectViewPrefs: {
+ [key: string]: {
+ period: string
+ timeBucket: string
+ rangeDate?: Date[]
+ },
+ } | null
+ userFlowAscending: {
+ [key: string]: IUserFlow
+ }
+ userFlowDescending: {
+ [key: string]: IUserFlow
+ }
+}
+
+const initialState: IInitialState = {
+ analytics: {},
+ analyticsPerf: {},
+ captchaAnalytics: {},
+ captchaProjectsViewPrefs: getInitialViewPrefs(LS_CAPTCHA_VIEW_PREFS_SETTING) || {},
+ projectViewPrefs: getInitialViewPrefs(LS_VIEW_PREFS_SETTING),
+ customEventsPrefs: {},
+ userFlowAscending: {},
+ userFlowDescending: {},
+}
+
+const cacheSlice = createSlice({
+ name: 'cache',
+ initialState,
+ reducers: {
+ setProjectCache(state, { payload }: PayloadAction<{ pid: string, key: string, data: any }>) {
+ state.analytics = {
+ ...state.analytics,
+ [payload.pid]: {
+ ...state.analytics[payload.pid],
+ [payload.key]: payload.data,
+ },
+ }
+ },
+ setCaptchaProjectCache(state, { payload }: PayloadAction<{ pid: string, key: string, data: any }>) {
+ state.captchaAnalytics = {
+ ...state.captchaAnalytics,
+ [payload.pid]: {
+ ...state.captchaAnalytics[payload.pid],
+ [payload.key]: payload.data,
+ },
+ }
+ },
+ deleteProjectCache(state, { payload }: PayloadAction<{ pid?: string, period?: string, timeBucket?: string }>) {
+ const {
+ pid, period, timeBucket,
+ } = payload
+ let key: string
+
+ if (period && timeBucket) {
+ key = getProjectCacheKey(period, timeBucket)
+ }
+
+ if (_isEmpty(period) || _isEmpty(timeBucket)) {
+ if (_isEmpty(pid)) {
+ state.analytics = {}
+ }
+ state.analytics = _filter(state.analytics, (project) => project !== pid)
+ }
+ if (pid) {
+ state.analytics = {
+ ...state.analytics,
+ [pid]: _filter(state.analytics[pid], (ckey) => ckey !== key),
+ }
+ }
+ },
+ deleteCaptchaProjectCache(state, { payload }: PayloadAction<{ pid: string, period?: string, timeBucket?: string }>) {
+ const { pid, period, timeBucket } = payload
+ let key: string
+
+ if (period && timeBucket) {
+ key = getProjectCaptchaCacheKey(period, timeBucket)
+ }
+
+ if (_isEmpty(period) || _isEmpty(timeBucket)) {
+ if (_isEmpty(pid)) {
+ state.captchaAnalytics = {}
+ }
+ state.captchaAnalytics = _filter(state.captchaAnalytics, (project) => project !== pid)
+ }
+ state.captchaAnalytics = {
+ ...state.captchaAnalytics,
+ [pid]: _filter(state.captchaAnalytics[pid], (ckey) => ckey !== key),
+ }
+ },
+ setProjectViewPrefs(state, { payload }: PayloadAction<{ pid: string, period: string, timeBucket: string, rangeDate?: Date[] }>) {
+ const {
+ pid, period, timeBucket, rangeDate,
+ } = payload
+ const viewPrefs = rangeDate ? {
+ period, timeBucket, rangeDate,
+ } : {
+ period, timeBucket,
+ }
+ const storedPrefs = getItem(LS_VIEW_PREFS_SETTING) as {
+ [key: string]: {
+ period: string
+ timeBucket: string
+ rangeDate?: Date[]
+ },
+ }
+ if (typeof storedPrefs === 'object' && storedPrefs !== null) {
+ storedPrefs[pid] = viewPrefs
+ setItem(LS_VIEW_PREFS_SETTING, JSON.stringify(storedPrefs))
+ } else {
+ setItem(LS_VIEW_PREFS_SETTING, JSON.stringify({ [pid]: viewPrefs }))
+ }
+ state.projectViewPrefs = {
+ ...state.projectViewPrefs,
+ [pid]: viewPrefs,
+ }
+ },
+ setCaptchaProjectViewPrefs(state, { payload }: PayloadAction<{ pid: string, period: string, timeBucket: string, rangeDate?: Date[] | null }>) {
+ const {
+ pid, period, timeBucket, rangeDate,
+ } = payload
+ const viewPrefs = rangeDate ? {
+ period, timeBucket, rangeDate,
+ } : {
+ period, timeBucket,
+ }
+ const storedPrefs = getItem(LS_CAPTCHA_VIEW_PREFS_SETTING) as {
+ [key: string]: {
+ period: string
+ timeBucket: string
+ rangeDate?: Date[]
+ },
+ }
+ if (typeof storedPrefs === 'object' && storedPrefs !== null) {
+ storedPrefs[pid] = viewPrefs
+ setItem(LS_CAPTCHA_VIEW_PREFS_SETTING, JSON.stringify(storedPrefs))
+ } else {
+ setItem(LS_CAPTCHA_VIEW_PREFS_SETTING, JSON.stringify({ [pid]: viewPrefs }))
+ }
+ state.captchaProjectsViewPrefs = {
+ ...state.captchaProjectsViewPrefs,
+ [pid]: viewPrefs,
+ }
+ },
+ setProjectCachePerf(state, { payload }: PayloadAction<{ pid: string, key: string, data: any }>) {
+ state.analyticsPerf = {
+ ...state.analyticsPerf,
+ [payload.pid]: {
+ ...state.analyticsPerf[payload.pid],
+ [payload.key]: payload.data,
+ },
+ }
+ },
+ setProjectForecastCache(state, { payload }: PayloadAction<{ pid: string, key: string, data: any }>) {
+ state.analytics = {
+ ...state.analytics,
+ [payload.pid]: {
+ ...state.analytics[payload.pid],
+ [payload.key]: payload.data,
+ },
+ }
+ },
+ setCustomEventsPrefs(state, { payload }: PayloadAction<{ pid: string, data: any }>) {
+ state.customEventsPrefs = {
+ ...state.customEventsPrefs,
+ [payload.pid]: {
+ ...state.customEventsPrefs[payload.pid],
+ ...payload.data,
+ },
+ }
+ },
+ setUserFlowAscending(state, { payload }: PayloadAction<{ pid: string, period: string, data: IUserFlow }>) {
+ const key = getUserFlowCacheKey(payload.pid, payload.period)
+
+ state.userFlowAscending = {
+ ...state.userFlowAscending,
+ [key]: payload.data,
+ }
+ },
+ setUserFlowDescending(state, { payload }: PayloadAction<{ pid: string, period: string, data: IUserFlow }>) {
+ const key = getUserFlowCacheKey(payload.pid, payload.period)
+
+ state.userFlowDescending = {
+ ...state.userFlowDescending,
+ [key]: payload.data,
+ }
+ },
+ },
+})
+
+export const cacheActions = cacheSlice.actions
+
+export default cacheSlice.reducer
diff --git a/app/redux/reducers/ui/index.ts b/app/redux/reducers/ui/index.ts
new file mode 100644
index 000000000..e3ff264fd
--- /dev/null
+++ b/app/redux/reducers/ui/index.ts
@@ -0,0 +1,15 @@
+import { alertsActions } from './alerts'
+import { cacheActions } from './cache'
+import { miscActions } from './misc'
+import { projectsActions } from './projects'
+import { themeActions } from './theme'
+
+const UIActions = {
+ ...alertsActions,
+ ...cacheActions,
+ ...miscActions,
+ ...projectsActions,
+ ...themeActions,
+}
+
+export default UIActions
diff --git a/app/redux/reducers/ui/misc.ts b/app/redux/reducers/ui/misc.ts
new file mode 100644
index 000000000..6361dd7a3
--- /dev/null
+++ b/app/redux/reducers/ui/misc.ts
@@ -0,0 +1,85 @@
+import { createSlice, PayloadAction } from '@reduxjs/toolkit'
+import { LOW_EVENTS_WARNING } from 'redux/constants'
+import { setCookie } from 'utils/cookie'
+import { secondsTillNextMonth } from 'utils/generic'
+import { IStats } from 'redux/models/IStats'
+import { IMetainfo } from 'redux/models/IMetainfo'
+import { IUsageInfo } from 'redux/models/IUsageinfo'
+
+interface IInitialState {
+ stats: IStats
+ metainfo: IMetainfo
+ usageinfo: IUsageInfo
+ usageinfoLoaded: boolean
+ paddleLoaded: boolean
+ paddle: any
+ showNoEventsLeftBanner: boolean
+ lastBlogPost: any
+ extensions: any[]
+}
+
+const initialState: IInitialState = {
+ stats: {
+ users: 0,
+ projects: 0,
+ events: 0,
+ },
+ metainfo: {
+ country: null,
+ symbol: '$',
+ code: 'USD',
+ },
+ usageinfo: {
+ total: 0,
+ traffic: 0,
+ customEvents: 0,
+ captcha: 0,
+ trafficPerc: 0,
+ customEventsPerc: 0,
+ captchaPerc: 0,
+ },
+ usageinfoLoaded: false,
+ paddleLoaded: false,
+ paddle: {},
+ showNoEventsLeftBanner: false,
+ lastBlogPost: null,
+ extensions: [],
+}
+
+const miscSlice = createSlice({
+ name: 'misc',
+ initialState,
+ reducers: {
+ setGeneralStats(state, { payload }: PayloadAction<IStats>) {
+ state.stats = payload
+ },
+ setPaddleLastEvent(state, { payload }: PayloadAction<any>) {
+ state.paddle = { ...state.paddle, lastEvent: payload }
+ },
+ setShowNoEventsLeftBanner(state, { payload }: PayloadAction<boolean>) {
+ if (!payload) {
+ const maxAge = secondsTillNextMonth() + 86400
+ setCookie(LOW_EVENTS_WARNING, 1, maxAge)
+ }
+
+ state.showNoEventsLeftBanner = payload
+ },
+ setExtensions(state, { payload }: PayloadAction<any[]>) {
+ state.extensions = payload
+ },
+ setMetainfo(state, { payload }: PayloadAction<IMetainfo>) {
+ state.metainfo = payload
+ },
+ setUsageinfo(state, { payload }: PayloadAction<IUsageInfo>) {
+ state.usageinfoLoaded = true
+ state.usageinfo = payload
+ },
+ setLastBlogPost(state, { payload }: PayloadAction<any>) {
+ state.lastBlogPost = payload
+ },
+ },
+})
+
+export const miscActions = miscSlice.actions
+
+export default miscSlice.reducer
diff --git a/app/redux/reducers/ui/projects.ts b/app/redux/reducers/ui/projects.ts
new file mode 100644
index 000000000..f72dc003f
--- /dev/null
+++ b/app/redux/reducers/ui/projects.ts
@@ -0,0 +1,227 @@
+import { createSlice, current, PayloadAction } from '@reduxjs/toolkit'
+import _filter from 'lodash/filter'
+import _findIndex from 'lodash/findIndex'
+import _map from 'lodash/map'
+import { tabForOwnedProject, PROJECT_TABS, PROJECTS_PROTECTED } from 'redux/constants'
+import { setItem, getItem } from 'utils/localstorage'
+import { IProject, ICaptchaProject, ILiveStats } from 'redux/models/IProject'
+import { ISharedProject } from 'redux/models/ISharedProject'
+import { IAlerts } from 'redux/models/IAlerts'
+
+interface IInitialState {
+ projects: IProject[]
+ sharedProjects: ISharedProject[]
+ captchaProjects: ICaptchaProject[]
+ isLoading: boolean
+ isLoadingShared: boolean
+ isLoadingCaptcha: boolean
+ error: null | string
+ totalMonthlyEvents: number | null
+ total: number
+ sharedTotal: number
+ captchaTotal: number
+ dashboardPaginationPage: number
+ dashboardPaginationPageShared: number
+ dashboardPaginationPageCaptcha: number
+ dashboardTabs: string
+ projectTab: string
+ alerts: IAlerts[]
+ subscribers: any[]
+ liveStats: ILiveStats
+ password: {
+ [key: string]: string
+ }
+}
+
+const initialState: IInitialState = {
+ projects: [],
+ sharedProjects: [],
+ captchaProjects: [],
+ isLoading: true,
+ isLoadingShared: true,
+ isLoadingCaptcha: true,
+ error: null,
+ totalMonthlyEvents: null,
+ total: 0,
+ sharedTotal: 0,
+ captchaTotal: 0,
+ dashboardPaginationPage: 1,
+ dashboardPaginationPageShared: 1,
+ dashboardPaginationPageCaptcha: 1,
+ dashboardTabs: getItem('dashboardTabs') as string || tabForOwnedProject,
+ projectTab: PROJECT_TABS.traffic,
+ alerts: [],
+ subscribers: [],
+ liveStats: {},
+ password: getItem(PROJECTS_PROTECTED) || {},
+}
+
+const projectsSlice = createSlice({
+ name: 'projects',
+ initialState,
+ reducers: {
+ setProjects(state, { payload }: PayloadAction<{
+ projects: Partial<IProject | ISharedProject>[]
+ shared?: boolean
+ }>) {
+ if (payload.shared) {
+ state.isLoadingShared = false
+ state.sharedProjects = payload.projects as ISharedProject[]
+ } else {
+ state.isLoading = false
+ state.projects = payload.projects as IProject[]
+ }
+ },
+ setCaptchaProjects(state, { payload }: PayloadAction<ICaptchaProject[]>) {
+ state.isLoadingCaptcha = false
+ state.captchaProjects = payload
+ },
+ setDashboardPaginationPage(state, { payload }: PayloadAction<number>) {
+ state.dashboardPaginationPage = payload
+ },
+ setDashboardPaginationPageShared(state, { payload }: PayloadAction<number>) {
+ state.dashboardPaginationPageShared = payload
+ },
+ setDashboardPaginationPageCaptcha(state, { payload }: PayloadAction<number>) {
+ state.dashboardPaginationPageCaptcha = payload
+ },
+ setTotalMonthlyEvents(state, { payload }: PayloadAction<number>) {
+ state.totalMonthlyEvents = payload
+ },
+ setTotal(state, { payload }: PayloadAction<{ total: number, shared?: boolean }>) {
+ if (payload.shared) {
+ state.sharedTotal = payload.total
+ } else {
+ state.total = payload.total
+ }
+ },
+ setCaptchaTotal(state, { payload }: PayloadAction<number>) {
+ state.captchaTotal = payload
+ },
+ setCaptchaLoading(state, { payload }: PayloadAction<boolean>) {
+ state.isLoadingCaptcha = payload
+ },
+ removeCaptchaProject(state, { payload }: PayloadAction<string>) {
+ state.captchaProjects = _filter(state.captchaProjects, (project) => project.id !== payload)
+ },
+ setLiveStats(state, { payload }: PayloadAction<{ data: any}>) {
+ const { data } = payload
+
+ state.liveStats = {
+ ...state.liveStats,
+ ...data,
+ }
+ },
+ setLiveStatsProject(state, { payload }: PayloadAction<{ id: string, count: number }>) {
+ const { id, count } = payload
+
+ state.liveStats = {
+ ...state.liveStats,
+ [id]: count,
+ }
+ },
+ setPublicProject(state, { payload }: PayloadAction<{ project: Partial<IProject | ISharedProject>, shared?: boolean }>) {
+ const { project, shared = false } = payload
+
+ if (shared) {
+ state.sharedProjects = _findIndex(current(state.sharedProjects), (el) => el.id === project.id) >= 0
+ ? state.sharedProjects
+ : [
+ ...state.sharedProjects,
+ {
+ ...project as ISharedProject,
+ uiHidden: true,
+ },
+ ]
+ } else {
+ state.projects = _findIndex(current(state.projects), (el) => el.id === project.id) >= 0
+ ? state.projects
+ : [
+ ...state.projects,
+ {
+ ...project as IProject,
+ uiHidden: true,
+ },
+ ]
+ }
+ },
+ setProjectsShareData(state, { payload }: PayloadAction<{ data: Partial<IProject> | Partial<ISharedProject>, id: string, shared?: boolean }>) {
+ const { data, id, shared = false } = payload
+
+ if (shared) {
+ state.sharedProjects = _map(current(state.sharedProjects), (res) => {
+ if (res.project && res.project.id === id) {
+ return {
+ ...res,
+ ...data,
+ }
+ }
+ return res
+ })
+ } else {
+ state.projects = _map(current(state.projects), (res) => {
+ if (res.id === id) {
+ return {
+ ...res,
+ ...data,
+ }
+ }
+ return res
+ })
+ }
+ },
+ setProjectsError(state, { payload }: PayloadAction<string>) {
+ state.error = payload
+ },
+ removeProject(state, { payload }: PayloadAction<{ pid: string, shared: boolean }>) {
+ const { pid, shared = false } = payload
+
+ if (shared) {
+ state.sharedProjects = _filter(state.sharedProjects, (project) => project.id !== pid)
+ state.sharedTotal -= 1
+ } else {
+ state.projects = _filter(state.projects, (project) => project.id !== pid)
+ state.total -= 1
+ }
+ },
+ setProjectsLoading(state, { payload }: PayloadAction<{ isLoading: boolean, shared?: boolean }>) {
+ const { isLoading, shared = false } = payload
+
+ if (shared) {
+ state.isLoadingShared = isLoading
+ } else {
+ state.isLoading = isLoading
+ }
+ },
+ setDashboardTabs(state, { payload }: PayloadAction<string>) {
+ state.dashboardTabs = payload
+ setItem('dashboardTabs', payload)
+ },
+ setProjectTab(state, { payload }: PayloadAction<string>) {
+ state.projectTab = payload
+ },
+ setProjectProtectedPassword: (state, { payload }: PayloadAction<{ id: string, password: string }>) => {
+ const { id, password } = payload
+
+ state.password = {
+ ...state.password,
+ [id]: password,
+ }
+ setItem(PROJECTS_PROTECTED, JSON.stringify(state.password))
+ },
+ reset(state) {
+ state.projects = []
+ state.sharedProjects = []
+ state.captchaProjects = []
+ state.total = 0
+ state.sharedTotal = 0
+ state.captchaTotal = 0
+ state.alerts = []
+ state.subscribers = []
+ },
+ },
+})
+
+export const projectsActions = projectsSlice.actions
+
+export default projectsSlice.reducer
diff --git a/app/redux/reducers/ui/theme.ts b/app/redux/reducers/ui/theme.ts
new file mode 100644
index 000000000..b3d786dea
--- /dev/null
+++ b/app/redux/reducers/ui/theme.ts
@@ -0,0 +1,66 @@
+import { createSlice, PayloadAction } from '@reduxjs/toolkit'
+import _includes from 'lodash/includes'
+import { LS_THEME_SETTING, SUPPORTED_THEMES, THEME_TYPE } from 'redux/constants'
+
+const setThemeToDOM = (theme: string) => {
+ const root = window.document.documentElement
+ const isDark = theme === 'dark'
+
+ root.classList.remove(isDark ? 'light' : 'dark')
+ root.classList.add(theme)
+}
+
+const setTheme = (theme: string): string => {
+ setThemeToDOM(theme)
+ localStorage.setItem(LS_THEME_SETTING, theme)
+ return theme
+}
+
+const getInitialTheme = (): 'light' | 'dark' => {
+ if (typeof window !== 'undefined' && window.localStorage) {
+ const lsTheme: any = window.localStorage.getItem(LS_THEME_SETTING)
+ if (_includes(SUPPORTED_THEMES, lsTheme)) {
+ setThemeToDOM(lsTheme)
+ return lsTheme
+ }
+
+ const userMedia = window.matchMedia('(prefers-color-scheme: dark)')
+ if (userMedia.matches) {
+ setThemeToDOM('dark')
+ return 'dark'
+ }
+ }
+
+ setThemeToDOM('light')
+ return 'light' // light theme as the default
+}
+
+interface IInitialState {
+ theme: 'light' | 'dark'
+ type: string
+}
+
+const getInitialState = (): IInitialState => {
+ return {
+ theme: getInitialTheme(),
+ type: THEME_TYPE.classic,
+ }
+}
+
+const themeSlice = createSlice({
+ name: 'theme',
+ initialState: getInitialState(),
+ reducers: {
+ setTheme(state, { payload }: PayloadAction<'light' | 'dark'>) {
+ setTheme(payload)
+ state.theme = payload
+ },
+ setThemeType(state, { payload }: PayloadAction<string>) {
+ state.type = payload
+ },
+ },
+})
+
+export const themeActions = themeSlice.actions
+
+export default themeSlice.reducer
diff --git a/app/redux/sagas/actions/index.ts b/app/redux/sagas/actions/index.ts
new file mode 100644
index 000000000..f4899a09b
--- /dev/null
+++ b/app/redux/sagas/actions/index.ts
@@ -0,0 +1,161 @@
+/* eslint-disable no-unused-vars */
+import types from 'redux/sagas/actions/types'
+import { getRefreshToken, removeRefreshToken } from 'utils/refreshToken'
+import { logoutApi } from 'api'
+import { removeAccessToken } from 'utils/accessToken'
+import { removeItem } from 'utils/localstorage'
+import { LS_VIEW_PREFS_SETTING, LS_CAPTCHA_VIEW_PREFS_SETTING } from 'redux/constants'
+import { IUser } from '../../models/IUser'
+
+const loadProjects = (take?: number, skip?: number) => ({
+ type: types.LOAD_PROJECTS,
+ payload: { take, skip },
+})
+
+const loadMetainfo = () => ({
+ type: types.LOAD_METAINFO,
+})
+
+const loadUsageinfo = () => ({
+ type: types.LOAD_USAGEINFO,
+})
+
+const loadSharedProjects = (take?: number, skip?: number) => ({
+ type: types.LOAD_SHARED_PROJECTS,
+ payload: { take, skip },
+})
+
+const loadProjectsCaptcha = (take?: number, skip?: number) => ({
+ type: types.LOAD_PROJECTS,
+ payload: { take, skip, isCaptcha: true },
+})
+
+const loadExtensions = () => ({
+ type: types.LOAD_EXTENSIONS,
+})
+
+const loadProjectAlerts = (take?: number, skip?: number) => ({
+ type: types.LOAD_PROJECT_ALERTS,
+ payload: { take, skip },
+})
+
+const loginAsync = (credentials: {
+ email: string,
+ password: string,
+ dontRemember: boolean,
+}, callback = () => { }) => ({
+ type: types.LOGIN_ASYNC,
+ payload: {
+ credentials, callback,
+ },
+})
+
+// currently only google is supported, in future we should provide a variable specifying the provider
+const authSSO = (provider: string, dontRemember: boolean, t: (key: string) => string = () => '', callback: (res: any) => void = () => { }) => ({
+ type: types.AUTH_SSO,
+ payload: {
+ dontRemember, callback, t, provider,
+ },
+})
+
+// currently only google is supported, in future we should provide a variable specifying the provider
+const linkSSO = (t: (key: string) => string = () => '', callback: (res: any) => void = () => { }, provider = 'google') => ({
+ type: types.LINK_SSO,
+ payload: {
+ callback, t, provider,
+ },
+})
+
+// currently only google is supported, in future we should provide a variable specifying the provider
+const unlinkSSO = (t: (key: string) => string = () => '', callback: (res: any) => void = () => { }, provider = 'google') => ({
+ type: types.UNLINK_SSO,
+ payload: {
+ callback, t, provider,
+ },
+})
+
+const signupAsync = (data: {
+ email: string,
+ password: string,
+}, t?: (string: string) => {}, callback = (res: any) => { }) => ({
+ type: types.SIGNUP_ASYNC,
+ payload: {
+ data, callback, t,
+ },
+})
+
+const emailVerifyAsync = (data: {
+ id: string,
+}, successfulCallback?: () => void, errorCallback?: (e: string) => void) => ({
+ type: types.EMAIL_VERIFY_ASYNC,
+ payload: { data, successfulCallback, errorCallback },
+})
+
+const updateUserProfileAsync = (data: Partial<IUser>, callback = (item: any) => { }) => ({
+ type: types.UPDATE_USER_PROFILE_ASYNC,
+ payload: { data, callback },
+})
+
+const deleteAccountAsync = (errorCallback?: (e: string) => {}, successCallback?: (str?: string) => void, t?: (str: string) => {}) => {
+ const refreshToken = getRefreshToken()
+ logoutApi(refreshToken)
+
+ return {
+ type: types.DELETE_ACCOUNT_ASYNC,
+ payload: {
+ errorCallback, successCallback, t,
+ },
+ }
+}
+
+const shareVerifyAsync = (data: {
+ id: string,
+ path: string
+}, successfulCallback?: () => void, errorCallback?: (error: string) => void) => ({
+ type: types.SHARE_VERIFY_ASYNC,
+ payload: { data, successfulCallback, errorCallback },
+})
+
+const logout = (basedOn401Error: boolean) => {
+ const refreshToken = getRefreshToken()
+ logoutApi(refreshToken)
+ removeAccessToken()
+ removeRefreshToken()
+ removeItem(LS_VIEW_PREFS_SETTING)
+ removeItem(LS_CAPTCHA_VIEW_PREFS_SETTING)
+
+ return {
+ type: types.LOGOUT,
+ payload: { basedOn401Error },
+ }
+}
+
+const updateShowLiveVisitorsInTitle = (show: boolean, callback: (isSuccess: boolean) => void) => ({
+ type: types.UPDATE_SHOW_LIVE_VISITORS_IN_TITLE,
+ payload: {
+ show, callback,
+ },
+})
+
+const sagaActions = {
+ loadProjects,
+ loadSharedProjects,
+ loadProjectsCaptcha,
+ loadExtensions,
+ loadProjectAlerts,
+ loginAsync,
+ authSSO,
+ signupAsync,
+ emailVerifyAsync,
+ updateUserProfileAsync,
+ deleteAccountAsync,
+ logout,
+ shareVerifyAsync,
+ linkSSO,
+ unlinkSSO,
+ loadMetainfo,
+ loadUsageinfo,
+ updateShowLiveVisitorsInTitle,
+}
+
+export default sagaActions
diff --git a/app/redux/sagas/actions/types.ts b/app/redux/sagas/actions/types.ts
new file mode 100644
index 000000000..d0844c159
--- /dev/null
+++ b/app/redux/sagas/actions/types.ts
@@ -0,0 +1,21 @@
+const sagaTypes = Object.freeze({
+ LOAD_EXTENSIONS: 'LOAD_EXTENSIONS',
+ LOAD_PROJECTS: 'LOAD_PROJECTS',
+ LOAD_METAINFO: 'LOAD_METAINFO',
+ LOAD_USAGEINFO: 'LOAD_USAGEINFO',
+ LOAD_SHARED_PROJECTS: 'LOAD_SHARED_PROJECTS',
+ LOAD_PROJECT_ALERTS: 'LOAD_PROJECT_ALERTS',
+ LOGIN_ASYNC: 'LOGIN_ASYNC',
+ SIGNUP_ASYNC: 'SIGNUP_ASYNC',
+ EMAIL_VERIFY_ASYNC: 'EMAIL_VERIFY_ASYNC',
+ UPDATE_USER_PROFILE_ASYNC: 'UPDATE_USER_PROFILE_ASYNC',
+ UPDATE_SHOW_LIVE_VISITORS_IN_TITLE: 'UPDATE_SHOW_LIVE_VISITORS_IN_TITLE',
+ DELETE_ACCOUNT_ASYNC: 'DELETE_ACCOUNT_ASYNC',
+ SHARE_VERIFY_ASYNC: 'SHARE_VERIFY_ASYNC',
+ LOGOUT: 'LOGOUT',
+ AUTH_SSO: 'AUTH_SSO',
+ LINK_SSO: 'LINK_SSO',
+ UNLINK_SSO: 'UNLINK_SSO',
+})
+
+export default sagaTypes
diff --git a/app/redux/sagas/auth/watchers/index.ts b/app/redux/sagas/auth/watchers/index.ts
new file mode 100644
index 000000000..4694e9794
--- /dev/null
+++ b/app/redux/sagas/auth/watchers/index.ts
@@ -0,0 +1,71 @@
+import { takeLatest, all, call } from 'redux-saga/effects'
+import signIn from '../workers/signin'
+import signUp from '../workers/signup'
+import logout from '../workers/logout'
+import verifyEmail from '../workers/verifyEmail'
+import updateUserProfile from '../workers/updateUserProfile'
+import deleteUserAccount from '../workers/deleteUserAccount'
+import ssoAuth from '../workers/sso_auth'
+import ssoLink from '../workers/sso_link'
+import ssoUnlink from '../workers/sso_unlink'
+import updateShowLiveVisitorsInTitle from '../workers/update_show_live_visitors_in_title'
+import sagaTypes from '../../actions/types'
+
+function* watchLogin() {
+ // @ts-ignore
+ yield takeLatest(sagaTypes.LOGIN_ASYNC, signIn)
+}
+
+function* watchVerifyEmail() {
+ // @ts-ignore
+ yield takeLatest(sagaTypes.EMAIL_VERIFY_ASYNC, verifyEmail)
+}
+
+function* watchSignup() {
+ // @ts-ignore
+ yield takeLatest(sagaTypes.SIGNUP_ASYNC, signUp)
+}
+
+function* watchLogout() {
+ // @ts-ignore
+ yield takeLatest(sagaTypes.LOGOUT, logout)
+}
+
+function* watchUpdateUserProfile() {
+ // @ts-ignore
+ yield takeLatest(sagaTypes.UPDATE_USER_PROFILE_ASYNC, updateUserProfile)
+}
+
+function* watchDeleteUserProfile() {
+ // @ts-ignore
+ yield takeLatest(sagaTypes.DELETE_ACCOUNT_ASYNC, deleteUserAccount)
+}
+
+function* watchAuthSSO() {
+ // @ts-ignore
+ yield takeLatest(sagaTypes.AUTH_SSO, ssoAuth)
+}
+
+function* watchLinkSSO() {
+ // @ts-ignore
+ yield takeLatest(sagaTypes.LINK_SSO, ssoLink)
+}
+
+function* watchUnlinkSSO() {
+ // @ts-ignore
+ yield takeLatest(sagaTypes.UNLINK_SSO, ssoUnlink)
+}
+
+function* watchUpdateShowLiveVisitorsInTitle() {
+ // @ts-ignore
+ yield takeLatest(sagaTypes.UPDATE_SHOW_LIVE_VISITORS_IN_TITLE, updateShowLiveVisitorsInTitle)
+}
+
+export default function* watchAuth() {
+ yield all([
+ call(watchLogin), call(watchSignup), call(watchVerifyEmail),
+ call(watchUpdateUserProfile), call(watchDeleteUserProfile),
+ call(watchLogout), call(watchAuthSSO), call(watchLinkSSO),
+ call(watchUnlinkSSO), call(watchUpdateShowLiveVisitorsInTitle),
+ ])
+}
diff --git a/app/redux/sagas/auth/workers/deleteUserAccount.ts b/app/redux/sagas/auth/workers/deleteUserAccount.ts
new file mode 100644
index 000000000..ed6f9224e
--- /dev/null
+++ b/app/redux/sagas/auth/workers/deleteUserAccount.ts
@@ -0,0 +1,37 @@
+import { call, put } from 'redux-saga/effects'
+
+import { authActions } from 'redux/reducers/auth'
+import { alertsActions } from 'redux/reducers/alerts'
+import { deleteUser } from 'api'
+
+export default function* deleteUserAccountWorker({ payload: { errorCallback, successCallback, t } }: {
+ payload: {
+ errorCallback: (error: any) => void,
+ successCallback: () => void,
+ t: (key: string) => string,
+ },
+}) {
+ try {
+ yield call(deleteUser)
+ yield call(successCallback)
+ yield put(authActions.deleteAccountSuccess())
+ yield put(alertsActions.accountDeleted({
+ message: t('apiNotifications.accountDeleted'),
+ type: 'success',
+ }))
+ } catch (error) {
+ let message
+
+ try {
+ // @ts-ignore
+ message = JSON.parse(error.message).message || 'somethingWentWrong'
+ } catch (e) {
+ message = 'somethingWentWrong'
+ }
+
+ // @ts-ignore
+ errorCallback(t([`apiNotifications.${message}`, 'apiNotifications.somethingWentWrong']))
+ } finally {
+ yield put(authActions.finishLoading())
+ }
+}
diff --git a/app/redux/sagas/auth/workers/logout.ts b/app/redux/sagas/auth/workers/logout.ts
new file mode 100644
index 000000000..41875fdcb
--- /dev/null
+++ b/app/redux/sagas/auth/workers/logout.ts
@@ -0,0 +1,19 @@
+import { call, put } from 'redux-saga/effects'
+import Debug from 'debug'
+
+import UIActions from 'redux/reducers/ui'
+import { getGeneralStats } from 'api'
+import { IStats } from '../../../models/IStats'
+
+const debug = Debug('swetrix:rx:s:logout')
+
+export default function* logoutWorker({ payload: { basedOn401Error } }: { payload: { basedOn401Error: boolean } }) {
+ try {
+ if (!basedOn401Error) {
+ const stats: IStats = yield call(getGeneralStats)
+ yield put(UIActions.setGeneralStats(stats))
+ }
+ } catch (e) {
+ debug('Error while getting general stats data: %s', e)
+ }
+}
diff --git a/app/redux/sagas/auth/workers/signin.ts b/app/redux/sagas/auth/workers/signin.ts
new file mode 100644
index 000000000..39e73a8b1
--- /dev/null
+++ b/app/redux/sagas/auth/workers/signin.ts
@@ -0,0 +1,57 @@
+import { call, put } from 'redux-saga/effects'
+import { authActions } from 'redux/reducers/auth'
+import { errorsActions } from 'redux/reducers/errors'
+import _isObject from 'lodash/isPlainObject'
+import _omit from 'lodash/omit'
+
+import UIActions from 'redux/reducers/ui'
+import { setAccessToken } from 'utils/accessToken'
+import { login } from 'api'
+import { setRefreshToken } from 'utils/refreshToken'
+import sagaActions from '../../actions/index'
+
+export default function* singinWorker({ payload: { credentials, callback } }: {
+ payload: {
+ credentials: {
+ email: string,
+ password: string,
+ dontRemember: boolean,
+ },
+ callback: (isSuccess: boolean, isTwoFactorAuthenticationEnabled: boolean) => void,
+ },
+}) {
+ try {
+ const { dontRemember } = credentials
+ const {
+ user, accessToken, refreshToken,
+ } = yield call(login, _omit(credentials, ['dontRemember']))
+
+ yield put(authActions.setDontRemember(dontRemember))
+
+ if (user.isTwoFactorAuthenticationEnabled) {
+ yield call(setAccessToken, accessToken, true)
+ yield call(setRefreshToken, refreshToken, true)
+ yield put(authActions.updateUserData(user))
+ callback(false, true)
+ return
+ }
+
+ yield put(authActions.loginSuccessful(user))
+ yield call(setAccessToken, accessToken, dontRemember)
+ yield call(setRefreshToken, refreshToken)
+ yield put(UIActions.setThemeType(user.theme))
+ yield put(sagaActions.loadProjects())
+ yield put(sagaActions.loadSharedProjects())
+ yield put(sagaActions.loadProjectAlerts())
+ callback(true, false)
+ } catch (error) {
+ // @ts-ignore
+ const err = _isObject(error) ? error.message : error
+ yield put(errorsActions.loginFailed({
+ message: err || 'apiNotifications.somethingWentWrong',
+ }))
+ callback(false, false)
+ } finally {
+ yield put(authActions.finishLoading())
+ }
+}
diff --git a/app/redux/sagas/auth/workers/signup.ts b/app/redux/sagas/auth/workers/signup.ts
new file mode 100644
index 000000000..55b64fd98
--- /dev/null
+++ b/app/redux/sagas/auth/workers/signup.ts
@@ -0,0 +1,48 @@
+import { call, put } from 'redux-saga/effects'
+import { authActions } from 'redux/reducers/auth'
+import { errorsActions } from 'redux/reducers/errors'
+import _omit from 'lodash/omit'
+
+import { setAccessToken } from 'utils/accessToken'
+import { signup } from 'api'
+import { setRefreshToken } from 'utils/refreshToken'
+import sagaActions from '../../actions'
+
+export default function* signupWorder({ payload: { data: rawData, callback } }: {
+ payload: {
+ data: {
+ email: string,
+ password: string
+ repeat: string
+ dontRemember: boolean
+ },
+ callback: (isSuccess: boolean) => void
+ }
+}) {
+ try {
+ const { repeat, ...data } = rawData
+ const { dontRemember } = data
+ const {
+ user, accessToken, refreshToken, // theme,
+ // @ts-ignore
+ } = yield call(signup, _omit(data, ['dontRemember']))
+
+ yield put(authActions.signupUpSuccessful(user))
+ yield call(setAccessToken, accessToken, dontRemember)
+ yield call(setRefreshToken, refreshToken)
+ yield put(authActions.setDontRemember(dontRemember))
+ // yield put(UIActions.setThemeType(response.theme))
+ yield put(sagaActions.loadProjects())
+ yield put(sagaActions.loadSharedProjects())
+ yield put(sagaActions.loadProjectAlerts())
+ callback(true)
+ } catch (error: unknown) {
+ // @ts-ignore
+ const message = error.message || (typeof error === 'string' ? error : error[0])
+ // @ts-ignore
+ yield put(errorsActions.signupFailed(message || 'apiNotifications.somethingWentWrong'))
+ callback(false)
+ } finally {
+ yield put(authActions.finishLoading())
+ }
+}
diff --git a/app/redux/sagas/auth/workers/sso_auth.ts b/app/redux/sagas/auth/workers/sso_auth.ts
new file mode 100644
index 000000000..031676fc2
--- /dev/null
+++ b/app/redux/sagas/auth/workers/sso_auth.ts
@@ -0,0 +1,96 @@
+import { call, put, delay } from 'redux-saga/effects'
+
+import { authActions } from 'redux/reducers/auth'
+import { errorsActions } from 'redux/reducers/errors'
+import { setAccessToken } from 'utils/accessToken'
+import {
+ getJWTBySSOHash, generateSSOAuthURL,
+} from 'api'
+import { setRefreshToken } from 'utils/refreshToken'
+import { openBrowserWindow } from 'utils/generic'
+import sagaActions from '../../actions/index'
+
+const AUTH_WINDOW_WIDTH = 600
+const AUTH_WINDOW_HEIGHT = 800
+
+const HASH_CHECK_FREQUENCY = 1000 // 1 second
+
+interface ISSOAuth {
+ payload: {
+ callback: (isSuccess: boolean, is2FA: boolean) => void
+ dontRemember: boolean
+ t: (key: string) => string
+ provider: string
+ }
+}
+
+export default function* ssoAuth({
+ payload: {
+ callback, dontRemember, t, provider,
+ },
+}: ISSOAuth) {
+ const authWindow = openBrowserWindow('', AUTH_WINDOW_WIDTH, AUTH_WINDOW_HEIGHT)
+
+ if (!authWindow) {
+ yield put(errorsActions.loginFailed({
+ message: t('apiNotifications.socialisationAuthGenericError'),
+ }))
+ callback(false, false)
+ return
+ }
+
+ try {
+ const {
+ uuid, auth_url: authUrl, expires_in: expiresIn,
+ } = yield call(generateSSOAuthURL, provider)
+
+ // Set the URL of the authentification browser window
+ authWindow.location = authUrl
+
+ // Closing the authorisation window after the session expires
+ setTimeout(authWindow.close, expiresIn)
+
+ while (true) {
+ yield delay(HASH_CHECK_FREQUENCY)
+
+ try {
+ const {
+ accessToken, refreshToken, user,
+ } = yield call(getJWTBySSOHash, uuid, provider)
+ authWindow.close()
+
+ yield put(authActions.setDontRemember(dontRemember))
+
+ if (user.isTwoFactorAuthenticationEnabled) {
+ yield call(setAccessToken, accessToken, true)
+ yield call(setRefreshToken, refreshToken)
+ yield put(authActions.updateUserData(user))
+ callback(false, true)
+ return
+ }
+
+ yield put(authActions.loginSuccessful(user))
+ yield call(setAccessToken, accessToken, dontRemember)
+ yield call(setRefreshToken, refreshToken)
+ // yield put(UIActions.setThemeType(user.theme))
+ yield put(sagaActions.loadProjects())
+ yield put(sagaActions.loadSharedProjects())
+ yield put(sagaActions.loadProjectAlerts())
+ yield put(authActions.finishLoading())
+ callback(true, false)
+ return
+ } catch (reason) {
+ // Authentication is not finished yet
+ }
+ if (authWindow.closed) {
+ callback(false, false)
+ return
+ }
+ }
+ } catch (reason) {
+ yield put(errorsActions.loginFailed({
+ message: t('apiNotifications.socialisationAuthGenericError'),
+ }))
+ callback(false, false)
+ }
+}
diff --git a/app/redux/sagas/auth/workers/sso_link.ts b/app/redux/sagas/auth/workers/sso_link.ts
new file mode 100644
index 000000000..e7def5607
--- /dev/null
+++ b/app/redux/sagas/auth/workers/sso_link.ts
@@ -0,0 +1,78 @@
+import { call, put, delay } from 'redux-saga/effects'
+
+import { authActions } from 'redux/reducers/auth'
+import { errorsActions } from 'redux/reducers/errors'
+import { alertsActions } from 'redux/reducers/alerts'
+import {
+ linkBySSOHash, generateSSOAuthURL, authMe,
+} from 'api'
+import { openBrowserWindow } from 'utils/generic'
+
+const AUTH_WINDOW_WIDTH = 600
+const AUTH_WINDOW_HEIGHT = 800
+
+const HASH_CHECK_FREQUENCY = 1000 // 1 second
+
+export interface ISSOLink {
+ payload: {
+ callback: (isSuccess: boolean) => void
+ t: (key: string) => string
+ provider: string
+ }
+}
+
+export default function* ssoLink({ payload: { callback, t, provider } }: ISSOLink) {
+ const authWindow = openBrowserWindow('', AUTH_WINDOW_WIDTH, AUTH_WINDOW_HEIGHT)
+
+ if (!authWindow) {
+ yield put(errorsActions.loginFailed({
+ message: t('apiNotifications.socialisationGenericError'),
+ }))
+ callback(false)
+ return
+ }
+
+ try {
+ const {
+ uuid, auth_url: authUrl, expires_in: expiresIn,
+ } = yield call(generateSSOAuthURL, provider)
+
+ // Set the URL of the authentification browser window
+ authWindow.location = authUrl
+
+ // Closing the authorisation window after the session expires
+ setTimeout(authWindow.close, expiresIn)
+
+ while (true) {
+ yield delay(HASH_CHECK_FREQUENCY)
+
+ try {
+ yield call(linkBySSOHash, uuid, provider)
+ authWindow.close()
+
+ // @ts-ignore
+ const user = yield call(authMe)
+ yield put(authActions.loginSuccessful(user))
+
+ yield put(alertsActions.generateAlerts({
+ message: t('apiNotifications.socialAccountLinked'),
+ type: 'success',
+ }))
+
+ callback(true)
+ return
+ } catch (reason) {
+ // Authentication is not finished yet
+ }
+ if (authWindow.closed) {
+ callback(false)
+ return
+ }
+ }
+ } catch (reason) {
+ yield put(errorsActions.loginFailed({
+ message: t('apiNotifications.socialisationGenericError'),
+ }))
+ callback(false)
+ }
+}
diff --git a/app/redux/sagas/auth/workers/sso_unlink.ts b/app/redux/sagas/auth/workers/sso_unlink.ts
new file mode 100644
index 000000000..8e4c8f030
--- /dev/null
+++ b/app/redux/sagas/auth/workers/sso_unlink.ts
@@ -0,0 +1,45 @@
+import { call, put } from 'redux-saga/effects'
+import _values from 'lodash/values'
+import _includes from 'lodash/includes'
+
+import { authActions } from 'redux/reducers/auth'
+import { errorsActions } from 'redux/reducers/errors'
+import { alertsActions } from 'redux/reducers/alerts'
+import {
+ unlinkSSO, authMe,
+} from 'api'
+import { SSO_PROVIDERS } from 'redux/constants'
+
+export interface ISSOUnlink {
+ payload: {
+ provider: string
+ t: (key: string) => string
+ callback: (isSuccess: boolean) => void
+ }
+}
+
+export default function* ssoUnlink({ payload: { provider, t, callback } }: ISSOUnlink) {
+ if (!_includes(_values(SSO_PROVIDERS), provider)) {
+ callback(false)
+ return
+ }
+
+ try {
+ yield call(unlinkSSO, provider)
+
+ // @ts-ignore
+ const user = yield call(authMe)
+ yield put(authActions.loginSuccessful(user))
+
+ yield put(alertsActions.generateAlerts({
+ message: t('apiNotifications.socialAccountUninked'),
+ type: 'success',
+ }))
+ callback(true)
+ } catch (reason) {
+ yield put(errorsActions.loginFailed({
+ message: t('apiNotifications.socialisationUnlinkGenericError'),
+ }))
+ callback(false)
+ }
+}
diff --git a/app/redux/sagas/auth/workers/updateUserProfile.ts b/app/redux/sagas/auth/workers/updateUserProfile.ts
new file mode 100644
index 000000000..303d1f3b2
--- /dev/null
+++ b/app/redux/sagas/auth/workers/updateUserProfile.ts
@@ -0,0 +1,30 @@
+import { call, put } from 'redux-saga/effects'
+
+import { authActions } from 'redux/reducers/auth'
+import { errorsActions } from 'redux/reducers/errors'
+import { changeUserDetails } from 'api'
+import { IUser } from '../../../models/IUser'
+
+export default function* updateUserProfileWorker({ payload: { data, callback } }: {
+ payload: {
+ data: IUser
+ callback: (isSuccess: boolean) => void
+ }
+}) {
+ let isSuccess = false
+ try {
+ const user: IUser = yield call(changeUserDetails, data)
+
+ yield put(authActions.updateUserProfileSuccess(user))
+ isSuccess = true
+ } catch (e: unknown) {
+ const error = e as { message: string } | string[] | string
+ yield put(errorsActions.updateUserProfileFailed({
+ // @ts-ignore
+ message: error?.message || (typeof error === 'string' ? error : error[0]),
+ }))
+ } finally {
+ yield put(authActions.finishLoading())
+ callback(isSuccess)
+ }
+}
diff --git a/app/redux/sagas/auth/workers/update_show_live_visitors_in_title.ts b/app/redux/sagas/auth/workers/update_show_live_visitors_in_title.ts
new file mode 100644
index 000000000..7d27ca0cf
--- /dev/null
+++ b/app/redux/sagas/auth/workers/update_show_live_visitors_in_title.ts
@@ -0,0 +1,32 @@
+import { call, put } from 'redux-saga/effects'
+
+import { authActions } from 'redux/reducers/auth'
+import { errorsActions } from 'redux/reducers/errors'
+import { setShowLiveVisitorsInTitle } from 'api'
+import { IUser } from '../../../models/IUser'
+
+interface IPayload {
+ show: boolean
+ callback: (isSuccess: boolean) => void
+}
+
+export default function* updateShowLiveVisitorsInTitle({ payload: { show, callback } }: {
+ payload: IPayload
+}) {
+ let isSuccess = false
+
+ try {
+ const user: Partial<IUser> = yield call(setShowLiveVisitorsInTitle, show)
+
+ yield put(authActions.partiallyOverwriteUser(user))
+ isSuccess = true
+ } catch (e: unknown) {
+ const error = e as { message: string } | string[] | string
+ yield put(errorsActions.updateUserProfileFailed({
+ // @ts-ignore
+ message: error?.message || (typeof error === 'string' ? error : error[0]),
+ }))
+ } finally {
+ callback(isSuccess)
+ }
+}
diff --git a/app/redux/sagas/auth/workers/verifyEmail.ts b/app/redux/sagas/auth/workers/verifyEmail.ts
new file mode 100644
index 000000000..706a1d2b7
--- /dev/null
+++ b/app/redux/sagas/auth/workers/verifyEmail.ts
@@ -0,0 +1,25 @@
+import { call, put } from 'redux-saga/effects'
+
+import { authActions } from 'redux/reducers/auth'
+import { verifyEmail } from 'api'
+
+export default function* verifyEmailWorker({ payload: { data, successfulCallback, errorCallback } }: {
+ payload: {
+ data: {
+ id: string,
+ },
+ successfulCallback: () => void,
+ errorCallback: (error: any) => void,
+ },
+}) {
+ try {
+ // @ts-ignore
+ yield call(verifyEmail, data)
+ yield put(authActions.emailVerifySuccessful())
+ successfulCallback()
+ } catch (error) {
+ errorCallback(error)
+ } finally {
+ yield put(authActions.finishLoading())
+ }
+}
diff --git a/app/redux/sagas/index.ts b/app/redux/sagas/index.ts
new file mode 100644
index 000000000..b5d975cf0
--- /dev/null
+++ b/app/redux/sagas/index.ts
@@ -0,0 +1,8 @@
+import { fork } from 'redux-saga/effects'
+import watchAuth from './auth/watchers'
+import mainUISaga from './ui'
+
+export default function* rootSaga() {
+ yield fork(watchAuth)
+ yield fork(mainUISaga)
+}
diff --git a/app/redux/sagas/ui/index.ts b/app/redux/sagas/ui/index.ts
new file mode 100644
index 000000000..8e530ebbd
--- /dev/null
+++ b/app/redux/sagas/ui/index.ts
@@ -0,0 +1,39 @@
+import { takeEvery, fork, takeLatest } from 'redux-saga/effects'
+import sagaTypes from '../actions/types'
+
+import loadProjects from './load_projects'
+import initialise from './initialise'
+import liveVisitors from './worker_live_visitors'
+import generalStats from './worker_general_stats'
+import isEventsAvailable from './worker_is_events_available'
+import shareVerify from './share_verify'
+import loadExtensions from './load_extensions'
+import loadMetainfo from './load_metainfo'
+import loadUsageinfo from './load_usageinfo'
+import logout from './logout'
+import loadSharedProjects from './load_shared_projects'
+import loadProjectAlerts from './load_alerts'
+
+function* mainUISaga() {
+ yield fork(initialise)
+ yield fork(liveVisitors)
+ yield fork(isEventsAvailable)
+ yield fork(generalStats)
+ // @ts-ignore
+ yield takeEvery(sagaTypes.LOAD_PROJECTS, loadProjects)
+ // @is-ignore
+ yield takeEvery(sagaTypes.LOAD_METAINFO, loadMetainfo)
+ // @is-ignore
+ yield takeEvery(sagaTypes.LOAD_USAGEINFO, loadUsageinfo)
+ // @ts-ignore
+ yield takeEvery(sagaTypes.LOAD_SHARED_PROJECTS, loadSharedProjects)
+ yield takeEvery(sagaTypes.LOAD_EXTENSIONS, loadExtensions)
+ // @ts-ignore
+ yield takeEvery(sagaTypes.LOGOUT, logout)
+ // @ts-ignore
+ yield takeLatest(sagaTypes.SHARE_VERIFY_ASYNC, shareVerify)
+ // @ts-ignore
+ yield takeLatest(sagaTypes.LOAD_PROJECT_ALERTS, loadProjectAlerts)
+}
+
+export default mainUISaga
diff --git a/app/redux/sagas/ui/initialise.ts b/app/redux/sagas/ui/initialise.ts
new file mode 100644
index 000000000..640731d76
--- /dev/null
+++ b/app/redux/sagas/ui/initialise.ts
@@ -0,0 +1,38 @@
+import { put, call } from 'redux-saga/effects'
+import Debug from 'debug'
+
+import { getAccessToken } from 'utils/accessToken'
+import { getRefreshToken } from 'utils/refreshToken'
+import { getLastPost } from 'api/blog'
+import UIActions from 'redux/reducers/ui'
+import { isSelfhosted } from 'redux/constants'
+import sagaActions from '../actions'
+
+const debug = Debug('swetrix:rx:s:initialise')
+
+export default function* initialise() {
+ try {
+ const token: string = yield call(getAccessToken)
+ const refreshToken: string = yield call(getRefreshToken)
+
+ if (token && refreshToken) {
+ yield put(sagaActions.loadProjects())
+ yield put(sagaActions.loadSharedProjects())
+ yield put(sagaActions.loadProjectsCaptcha())
+ yield put(sagaActions.loadExtensions())
+ yield put(sagaActions.loadProjectAlerts())
+ }
+
+ if (!isSelfhosted) {
+ yield put(sagaActions.loadMetainfo())
+
+ const lastBlogPost: {
+ title: string,
+ url_path: string,
+ } = yield call(getLastPost)
+ yield put(UIActions.setLastBlogPost(lastBlogPost))
+ }
+ } catch (e) {
+ debug('An error occured whilst initialising: %s', e)
+ }
+}
diff --git a/app/redux/sagas/ui/load_alerts.ts b/app/redux/sagas/ui/load_alerts.ts
new file mode 100644
index 000000000..81e3a4390
--- /dev/null
+++ b/app/redux/sagas/ui/load_alerts.ts
@@ -0,0 +1,36 @@
+import { put, call } from 'redux-saga/effects'
+import Debug from 'debug'
+import _isString from 'lodash/isString'
+import UIActions from 'redux/reducers/ui'
+import { errorsActions } from 'redux/reducers/errors'
+import { DEFAULT_ALERTS_TAKE, isSelfhosted } from 'redux/constants'
+import { getAlerts } from 'api'
+
+const debug = Debug('swetrix:rx:s:load-extensions')
+
+export default function* loadProjectAlerts({ payload: { take = DEFAULT_ALERTS_TAKE, skip = 0 } }) {
+ if (isSelfhosted) {
+ return
+ }
+
+ try {
+ yield put(UIActions.setProjectAlertsLoading(true))
+ const { results, total, page_total: pageTotal } = yield call(getAlerts, take, skip)
+
+ yield put(UIActions.setProjectAlerts(results))
+ yield put(UIActions.setProjectAlertsTotal({
+ total,
+ pageTotal,
+ }))
+ } catch (e: unknown) {
+ const { message } = e as { message: string }
+ if (_isString(message)) {
+ yield put(errorsActions.setError({
+ message,
+ }))
+ }
+ debug('failed to load extensions: %s', message)
+ } finally {
+ yield put(UIActions.setProjectAlertsLoading(false))
+ }
+}
diff --git a/app/redux/sagas/ui/load_extensions.ts b/app/redux/sagas/ui/load_extensions.ts
new file mode 100644
index 000000000..f119aeaf6
--- /dev/null
+++ b/app/redux/sagas/ui/load_extensions.ts
@@ -0,0 +1,28 @@
+import { put, call } from 'redux-saga/effects'
+import Debug from 'debug'
+
+import UIActions from 'redux/reducers/ui'
+import { isSelfhosted } from 'redux/constants'
+import {
+ getInstalledExtensions,
+} from '../../../api'
+
+const debug = Debug('swetrix:rx:s:load-extensions')
+
+export default function* loadExtensions() {
+ if (isSelfhosted) {
+ return
+ }
+
+ try {
+ const { extensions } = yield call(getInstalledExtensions)
+
+ yield put(UIActions.setExtensions(extensions))
+ } catch (e: unknown) {
+ const { message } = e as { message: string }
+ // if (_isString(message)) {
+ // yield put(UIActions.setProjectsError(message))
+ // }
+ debug('failed to load extensions: %s', message)
+ }
+}
diff --git a/app/redux/sagas/ui/load_metainfo.ts b/app/redux/sagas/ui/load_metainfo.ts
new file mode 100644
index 000000000..8ca0ac711
--- /dev/null
+++ b/app/redux/sagas/ui/load_metainfo.ts
@@ -0,0 +1,29 @@
+import { put, call } from 'redux-saga/effects'
+import Debug from 'debug'
+
+import UIActions from 'redux/reducers/ui'
+import { isSelfhosted } from 'redux/constants'
+import { IMetainfo } from 'redux/models/IMetainfo'
+import {
+ getPaymentMetainfo,
+} from '../../../api'
+
+const debug = Debug('swetrix:rx:s:metainfo')
+
+export default function* loadMetainfo() {
+ if (isSelfhosted) {
+ return
+ }
+
+ try {
+ const metainfo: IMetainfo = yield call(getPaymentMetainfo)
+
+ yield put(UIActions.setMetainfo(metainfo))
+ } catch (e: unknown) {
+ const { message } = e as { message: string }
+ // if (_isString(message)) {
+ // yield put(UIActions.setProjectsError(message))
+ // }
+ debug('failed to load metainfo: %s', message)
+ }
+}
diff --git a/app/redux/sagas/ui/load_projects.ts b/app/redux/sagas/ui/load_projects.ts
new file mode 100644
index 000000000..a69bfe42e
--- /dev/null
+++ b/app/redux/sagas/ui/load_projects.ts
@@ -0,0 +1,79 @@
+import { put, call } from 'redux-saga/effects'
+import _map from 'lodash/map'
+import _isString from 'lodash/isString'
+import Debug from 'debug'
+
+import UIActions from 'redux/reducers/ui'
+
+import { ENTRIES_PER_PAGE_DASHBOARD } from 'redux/constants'
+import { IOverall } from 'redux/models/IProject'
+import {
+ getProjects, getOverallStats, getLiveVisitors, getOverallStatsCaptcha,
+} from '../../../api'
+
+const debug = Debug('swetrix:rx:s:load-projects')
+
+export default function* loadProjects({ payload: { take = ENTRIES_PER_PAGE_DASHBOARD, skip = 0, isCaptcha = false } }) {
+ try {
+ if (isCaptcha) {
+ yield put(UIActions.setCaptchaLoading(true))
+ } else {
+ yield put(UIActions.setProjectsLoading({
+ isLoading: true,
+ shared: false,
+ }))
+ }
+
+ let {
+ // eslint-disable-next-line prefer-const, camelcase
+ results, totalMonthlyEvents, total,
+ } = yield call(getProjects, take, skip, isCaptcha)
+
+ const pids = _map(results, result => result.id)
+
+ let overall: IOverall
+
+ if (isCaptcha) {
+ try {
+ overall = yield call(getOverallStatsCaptcha, pids)
+ } catch (e) {
+ debug('failed to overall stats: %s', e)
+ }
+ } else {
+ try {
+ overall = yield call(getOverallStats, pids)
+ } catch (e) {
+ debug('failed to overall stats: %s', e)
+ }
+ }
+
+ results = _map(results, res => ({
+ ...res,
+ overall: overall?.[res.id],
+ }))
+
+ if (isCaptcha) {
+ yield put(UIActions.setCaptchaProjects(results))
+ yield put(UIActions.setCaptchaTotal(total))
+ } else {
+ yield put(UIActions.setProjects({
+ projects: results,
+ }))
+ yield put(UIActions.setTotalMonthlyEvents(totalMonthlyEvents))
+ yield put(UIActions.setTotal({
+ total,
+ }))
+ }
+
+ const liveStats: any[] = yield call(getLiveVisitors, pids)
+ yield put(UIActions.setLiveStats({
+ data: liveStats,
+ }))
+ } catch (e: unknown) {
+ const { message } = e as { message: string }
+ if (_isString(message)) {
+ yield put(UIActions.setProjectsError(message))
+ }
+ debug('failed to load projects: %s', message)
+ }
+}
diff --git a/app/redux/sagas/ui/load_shared_projects.ts b/app/redux/sagas/ui/load_shared_projects.ts
new file mode 100644
index 000000000..ec4434c39
--- /dev/null
+++ b/app/redux/sagas/ui/load_shared_projects.ts
@@ -0,0 +1,83 @@
+import { put, call } from 'redux-saga/effects'
+import _map from 'lodash/map'
+import _isString from 'lodash/isString'
+import Debug from 'debug'
+
+import UIActions from 'redux/reducers/ui'
+
+import { ENTRIES_PER_PAGE_DASHBOARD, isSelfhosted } from 'redux/constants'
+import { IOverall } from 'redux/models/IProject'
+import {
+ getSharedProjects, getOverallStats, getLiveVisitors,
+} from '../../../api'
+
+const debug = Debug('swetrix:rx:s:load-projects')
+
+export default function* loadSharedProjects({ payload: { take = ENTRIES_PER_PAGE_DASHBOARD, skip = 0 } }) {
+ if (isSelfhosted) {
+ return
+ }
+
+ try {
+ yield put(UIActions.setProjectsLoading({
+ isLoading: true,
+ shared: true,
+ }))
+
+ let {
+ // eslint-disable-next-line prefer-const
+ results, total,
+ } = yield call(getSharedProjects, take, skip)
+
+ if (total === 0) {
+ return
+ }
+
+ const projectsWithShared = _map(results, (result) => {
+ return {
+ ...result,
+ project: {
+ ...result.project,
+ shared: true,
+ },
+ }
+ })
+ const pids = _map(projectsWithShared, ({ project }) => project.id)
+
+ let overall: IOverall
+
+ try {
+ overall = yield call(getOverallStats, pids)
+ } catch (e) {
+ debug('failed to overall stats: %s', e)
+ }
+
+ results = _map(projectsWithShared, res => ({
+ ...res,
+ project: {
+ ...res.project,
+ overall: overall?.[res.project.id],
+ },
+ }))
+
+ yield put(UIActions.setProjects({
+ projects: results,
+ shared: true,
+ }))
+ yield put(UIActions.setTotal({
+ total,
+ shared: true,
+ }))
+
+ const liveStats: any[] = yield call(getLiveVisitors, pids)
+ yield put(UIActions.setLiveStats({
+ data: liveStats,
+ }))
+ } catch (e: unknown) {
+ const { message } = e as { message: string }
+ if (_isString(message)) {
+ yield put(UIActions.setProjectsError(message))
+ }
+ debug('failed to load shared projects: %s', message)
+ }
+}
diff --git a/app/redux/sagas/ui/load_usageinfo.ts b/app/redux/sagas/ui/load_usageinfo.ts
new file mode 100644
index 000000000..c697c7100
--- /dev/null
+++ b/app/redux/sagas/ui/load_usageinfo.ts
@@ -0,0 +1,35 @@
+import { put, call, select } from 'redux-saga/effects'
+import Debug from 'debug'
+
+import UIActions from 'redux/reducers/ui'
+import { isSelfhosted } from 'redux/constants'
+import { IUsageInfo } from 'redux/models/IUsageinfo'
+import {
+ getUsageInfo,
+} from '../../../api'
+
+const debug = Debug('swetrix:rx:s:usageinfo')
+
+export default function* loadUsageinfo() {
+ if (isSelfhosted) {
+ return
+ }
+
+ const isUsageinfoLoaded: boolean = yield select(state => state.ui.misc.usageinfoLoaded)
+
+ if (isUsageinfoLoaded) {
+ return
+ }
+
+ try {
+ const info: IUsageInfo = yield call(getUsageInfo)
+
+ yield put(UIActions.setUsageinfo(info))
+ } catch (e: unknown) {
+ const { message } = e as { message: string }
+ // if (_isString(message)) {
+ // yield put(UIActions.setProjectsError(message))
+ // }
+ debug('failed to load usageinfo: %s', message)
+ }
+}
diff --git a/app/redux/sagas/ui/logout.ts b/app/redux/sagas/ui/logout.ts
new file mode 100644
index 000000000..f5f108179
--- /dev/null
+++ b/app/redux/sagas/ui/logout.ts
@@ -0,0 +1,7 @@
+import { put } from 'redux-saga/effects'
+
+import UIActions from 'redux/reducers/ui'
+
+export default function* logout() {
+ yield put(UIActions.reset())
+}
diff --git a/app/redux/sagas/ui/share_verify.ts b/app/redux/sagas/ui/share_verify.ts
new file mode 100644
index 000000000..66bb9deae
--- /dev/null
+++ b/app/redux/sagas/ui/share_verify.ts
@@ -0,0 +1,25 @@
+import { call, put } from 'redux-saga/effects'
+
+import { verifyShare } from 'api'
+import sagaActions from '../actions'
+
+export default function* shareVerify({ payload: { data, successfulCallback, errorCallback } }: {
+ payload: {
+ data: {
+ path: string,
+ id: string,
+ },
+ successfulCallback: () => void,
+ errorCallback: (error: any) => void,
+ },
+}) {
+ try {
+ // @ts-ignore
+ yield call(verifyShare, data)
+ yield put(sagaActions.loadProjects())
+ yield put(sagaActions.loadSharedProjects())
+ successfulCallback()
+ } catch (error) {
+ errorCallback(error)
+ }
+}
diff --git a/app/redux/sagas/ui/worker_general_stats.ts b/app/redux/sagas/ui/worker_general_stats.ts
new file mode 100644
index 000000000..c653f9879
--- /dev/null
+++ b/app/redux/sagas/ui/worker_general_stats.ts
@@ -0,0 +1,32 @@
+import {
+ put, call, delay,
+} from 'redux-saga/effects'
+import Debug from 'debug'
+
+import { getGeneralStats } from 'api'
+import UIActions from 'redux/reducers/ui'
+import { isSelfhosted } from 'redux/constants'
+import { IStats } from 'redux/models/IStats'
+
+const debug = Debug('swetrix:rx:s:general-stats')
+
+const RETRY_INTERVAL = 10000 // 10 seconds
+
+export default function* generalStats() {
+ if (isSelfhosted) {
+ return
+ }
+
+ while (true) {
+ try {
+ const stats: IStats = yield call(getGeneralStats)
+
+ yield put(UIActions.setGeneralStats(stats))
+ return
+ } catch (e) {
+ debug('Error while getting general stats data: %s', e)
+ }
+
+ yield delay(RETRY_INTERVAL)
+ }
+}
diff --git a/app/redux/sagas/ui/worker_is_events_available.ts b/app/redux/sagas/ui/worker_is_events_available.ts
new file mode 100644
index 000000000..4cd48741c
--- /dev/null
+++ b/app/redux/sagas/ui/worker_is_events_available.ts
@@ -0,0 +1,51 @@
+import { put, delay, select } from 'redux-saga/effects'
+import _isNull from 'lodash/isNull'
+
+import UIActions from 'redux/reducers/ui'
+import { SHOW_BANNER_AT_PERC, LOW_EVENTS_WARNING } from 'redux/constants'
+import { getCookie } from 'utils/cookie'
+
+const NOT_AUTHED_INTERVAL = 1000 // 1 second
+const NO_DATA_YET = 1000 // 1 second
+const DATA_REQUEST_ATTEMPTS = 20
+
+export default function* checkEventsAvailable() {
+ const lowEvents = getCookie(LOW_EVENTS_WARNING)
+
+ if (lowEvents) {
+ return
+ }
+
+ let dataRequests = 0
+
+ while (true) {
+ if (dataRequests > DATA_REQUEST_ATTEMPTS) {
+ return
+ }
+
+ const isAuthenticated: boolean = yield select(state => state.auth.authenticated)
+
+ if (!isAuthenticated) {
+ yield delay(NOT_AUTHED_INTERVAL)
+ continue
+ }
+
+ const totalMonthlyEvents: number | null = yield select(state => state.ui.projects.totalMonthlyEvents)
+
+ if (_isNull(totalMonthlyEvents)) {
+ dataRequests++
+ yield delay(NO_DATA_YET)
+ continue
+ }
+
+ const maxEventsCount: number = yield select(state => state.auth.user.maxEventsCount)
+
+ const eventsUsedPercentage = (totalMonthlyEvents * 100) / maxEventsCount
+
+ if (eventsUsedPercentage >= SHOW_BANNER_AT_PERC) {
+ yield put(UIActions.setShowNoEventsLeftBanner(true))
+ }
+
+ return
+ }
+}
diff --git a/app/redux/sagas/ui/worker_live_visitors.ts b/app/redux/sagas/ui/worker_live_visitors.ts
new file mode 100644
index 000000000..d39c5e415
--- /dev/null
+++ b/app/redux/sagas/ui/worker_live_visitors.ts
@@ -0,0 +1,56 @@
+import {
+ put, call, delay, select,
+} from 'redux-saga/effects'
+import _map from 'lodash/map'
+import _filter from 'lodash/filter'
+import _isEmpty from 'lodash/isEmpty'
+
+import { getLiveVisitors } from 'api'
+import UIActions from 'redux/reducers/ui'
+import { LIVE_VISITORS_UPDATE_INTERVAL, tabForSharedProject } from 'redux/constants'
+import { ISharedProject } from '../../models/ISharedProject'
+import { IProject } from '../../models/IProject'
+
+export default function* liveVisitors() {
+ while (true) {
+ yield delay(LIVE_VISITORS_UPDATE_INTERVAL)
+ const tab: string = yield select(state => state.ui.projects.dashboardTabs)
+
+ if (tabForSharedProject === tab) {
+ const sharedProjects: ISharedProject[] = yield select(state => state.ui.projects.sharedProjects)
+
+ if (_isEmpty(sharedProjects)) {
+ continue
+ }
+
+ const pids = _map(_filter(sharedProjects, ({ project }) => !project?.uiHidden), item => (item?.project?.id ? item.project.id : ''))
+
+ if (_isEmpty(pids)) {
+ continue
+ }
+
+ const liveStats: any[] = yield call(getLiveVisitors, pids)
+
+ yield put(UIActions.setLiveStats({
+ data: liveStats,
+ }))
+ } else {
+ const projects: IProject[] = yield select(state => state.ui.projects.projects)
+ if (_isEmpty(projects)) {
+ continue
+ }
+
+ const pids = _map(_filter(projects, ({ uiHidden }) => !uiHidden), project => project.id)
+
+ if (_isEmpty(pids)) {
+ continue
+ }
+
+ const liveStats: any[] = yield call(getLiveVisitors, pids)
+
+ yield put(UIActions.setLiveStats({
+ data: liveStats,
+ }))
+ }
+ }
+}
diff --git a/app/redux/store/index.ts b/app/redux/store/index.ts
new file mode 100644
index 000000000..f48661bac
--- /dev/null
+++ b/app/redux/store/index.ts
@@ -0,0 +1,40 @@
+import { combineReducers, configureStore } from '@reduxjs/toolkit'
+import createSagaMiddleware from 'redux-saga'
+import { useDispatch } from 'react-redux'
+import rootSaga from '../sagas'
+import authSlice from '../reducers/auth'
+import errorsSlice from '../reducers/errors'
+import alertsSlice from '../reducers/alerts'
+import miscSlice from '../reducers/ui/misc'
+import projectsSlice from '../reducers/ui/projects'
+import alertsProjectsSlice from '../reducers/ui/alerts'
+import themeSlice from '../reducers/ui/theme'
+import cacheSlice from '../reducers/ui/cache'
+
+const rootReducer = combineReducers({
+ auth: authSlice,
+ errors: errorsSlice,
+ alerts: alertsSlice,
+ ui: combineReducers({
+ misc: miscSlice,
+ projects: projectsSlice,
+ alerts: alertsProjectsSlice,
+ theme: themeSlice,
+ cache: cacheSlice,
+ }),
+})
+
+const sagaMiddleware = createSagaMiddleware()
+
+export const store = configureStore({
+ reducer: rootReducer,
+ middleware: [sagaMiddleware],
+ devTools: true,
+})
+
+sagaMiddleware.run(rootSaga)
+
+export type RootState = ReturnType<typeof rootReducer>
+export type AppDispatch = typeof store.dispatch
+export const useAppDispatch: () => AppDispatch = useDispatch
+export type StateType = ReturnType<typeof store.getState>
diff --git a/package.json b/package.json
index e5a7b09ff..b72df5766 100644
--- a/package.json
+++ b/package.json
@@ -51,11 +51,14 @@
"react-i18next": "^12.3.1",
"react-outside-click-handler": "^1.3.0",
"react-qr-code": "^2.0.11",
+ "react-redux": "^8.0.5",
"react-router-hash-link": "^2.4.3",
"react-select": "^5.7.2",
"react-snowfall": "^1.2.1",
"react-timezone-select": "^2.1.1",
"react-type-animation": "^3.0.1",
+ "redux": "^4.2.1",
+ "redux-saga": "^1.2.3",
"remix-i18next": "^5.1.1",
"spacetime": "^7.4.3",
"swetrix": "^2.2.1",