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!

implemented telegram integration

Blue Mouse11c919135344
diff --git a/public/locales/en.json b/public/locales/en.json
index 8c2a79cc0..8118befe6 100644
--- a/public/locales/en.json
+++ b/public/locales/en.json
@@ -18,7 +18,8 @@
"acceptInvitationError": "Error occurred while accepting the project invitation",
"acceptInvitation": "The project invitation has been accepted",
"subscriptionUpdated": "Your subscription has been updated",
- "generate2FAError": "Error occurred while generating 2FA code"
+ "generate2FAError": "Error occurred while generating 2FA code",
+ "integrationRemovalError": "Error occurred while removing the integration"
},
"common": {
"features": "Features",
@@ -48,6 +49,9 @@
"isNot": "is not",
"invite": "Invite",
"pending": "Pending",
+ "notConnected": "Not connected",
+ "connected": "Connected",
+ "goBack": "Go back",
"accept": "Accept",
"reject": "Reject",
"delete": "Delete",
@@ -353,7 +357,16 @@
"apiKeyDelete": "Delete your API Key?",
"apiKeyDeleteConf": "Are you sure you want to delete your API key?\nAll API access via this key will be disabled.",
"theme": "Theme",
- "selectTheme": "Select theme"
+ "selectTheme": "Select theme",
+ "integrations": "Integrations",
+ "integrationsDesc": "Integrations can be used to connect your favourite messengers to Swetrix and receive updates such as notifications, reports or alerts directly.",
+ "integrationsList": {
+ "telegram": "Receive notifications directly into a Telegram bot.",
+ "tgHint": "Write a message to <url>{{username}}</url> to get your chat ID. This bot will be used later to send you notifications or alerts."
+ },
+ "addIntegration": "Add integration",
+ "removeIntegration": "Remove integration",
+ "chatID": "Chat ID"
},
"dashboard": {
"newProject": "New project",
diff --git a/src/api/index.js b/src/api/index.js
index 2f8a60948..552f99a7d 100644
--- a/src/api/index.js
+++ b/src/api/index.js
@@ -467,3 +467,14 @@ export const getLiveVisitorsInfo = (pid) =>
? error.response.data
: error.response.data.message
})
+
+export const removeTgIntegration = (tgID) =>
+ api
+ .delete(`user/tg/${tgID}`)
+ .then((response) => response.data)
+ .catch((error) => {
+ debug('%s', error)
+ throw _isEmpty(error.response.data?.message)
+ ? error.response.data
+ : error.response.data.message
+ })
diff --git a/src/pages/UserSettings/UserSettings.container.jsx b/src/pages/UserSettings/UserSettings.container.jsx
index 12a89ac43..7d6a2eca3 100644
--- a/src/pages/UserSettings/UserSettings.container.jsx
+++ b/src/pages/UserSettings/UserSettings.container.jsx
@@ -71,13 +71,18 @@ const mapDispatchToProps = (dispatch) => ({
accountUpdated: (message) => {
dispatch(alertsActions.accountUpdated(message))
},
- updateUserProfileAsync: (data, successMessage) => {
+ updateUserProfileAsync: (data, successMessage, callback = () => {}) => {
dispatch(
authActions.updateUserProfileAsync(
data,
- () => dispatch(
- alertsActions.accountUpdated(successMessage),
- ),
+ (res) => {
+ if (res) {
+ dispatch(
+ alertsActions.accountUpdated(successMessage),
+ )
+ }
+ callback(res)
+ },
),
)
},
diff --git a/src/pages/UserSettings/UserSettings.jsx b/src/pages/UserSettings/UserSettings.jsx
index c7b379a02..4dc565062 100644
--- a/src/pages/UserSettings/UserSettings.jsx
+++ b/src/pages/UserSettings/UserSettings.jsx
@@ -40,6 +40,7 @@ import {
} from 'api'
import ProjectList from './components/ProjectList'
import TwoFA from './components/TwoFA'
+import Integrations from './components/Integrations'
import NoSharedProjects from './components/NoSharedProjects'
dayjs.extend(utc)
@@ -95,7 +96,7 @@ const UserSettings = ({
setValidated(valid)
}
- const onSubmit = (data) => {
+ const onSubmit = (data, callback = () => { }) => {
delete data.repeat
// eslint-disable-next-line no-restricted-syntax
for (const key in data) {
@@ -104,7 +105,7 @@ const UserSettings = ({
}
}
- updateUserProfileAsync(data, t('profileSettings.updated'))
+ updateUserProfileAsync(data, t('profileSettings.updated'), callback)
}
useEffect(() => {
@@ -158,6 +159,17 @@ const UserSettings = ({
}
}
+ const handleIntegrationSave = (data, callback = () => {}) => {
+ setBeenSubmitted(true)
+
+ if (validated) {
+ onSubmit({
+ ...form,
+ ...data,
+ }, callback)
+ }
+ }
+
const handleReportSave = () => {
setBeenSubmitted(true)
@@ -368,6 +380,22 @@ const UserSettings = ({
{t('common.save')}
</Button>
<hr className='mt-5 border-gray-200 dark:border-gray-600' />
+
+ <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.integrations')}
+ <div className='ml-5'>
+ <Beta />
+ </div>
+ </h3>
+ <Integrations
+ user={user}
+ updateUserData={updateUserData}
+ handleIntegrationSave={handleIntegrationSave}
+ genericError={genericError}
+ />
+
+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />
+
<h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
{t('profileSettings.apiKey')}
<div className='ml-5'>
@@ -432,7 +460,6 @@ const UserSettings = ({
{t('profileSettings.2fa')}
</h3>
<TwoFA
- t={t}
user={user}
dontRemember={dontRemember}
updateUserData={updateUserData}
diff --git a/src/pages/UserSettings/components/Integrations.jsx b/src/pages/UserSettings/components/Integrations.jsx
new file mode 100644
index 000000000..3301050ad
--- /dev/null
+++ b/src/pages/UserSettings/components/Integrations.jsx
@@ -0,0 +1,212 @@
+import React, { useState, memo } from 'react'
+import { useTranslation, Trans } from 'react-i18next'
+import _map from 'lodash/map'
+import _isString from 'lodash/isString'
+import {
+ CheckCircleIcon, XCircleIcon, ClockIcon,
+} from '@heroicons/react/24/solid'
+
+import Input from 'ui/Input'
+import Button from 'ui/Button'
+import Telegram from 'ui/icons/Telegram'
+import { removeTgIntegration } from 'api'
+
+const getAvailableIntegrations = t => ([
+ {
+ name: 'Telegram',
+ key: 'telegram',
+ description: t('profileSettings.integrationsList.telegram'),
+ Icon: Telegram,
+ },
+])
+
+const TG_BOT_URL = 'https://t.me/swetrixbot'
+const TG_BOT_USERNAME = '@swetrixbot'
+
+const Integrations = ({
+ user, updateUserData, handleIntegrationSave, genericError,
+}) => {
+ const { t } = useTranslation('common')
+ const available = getAvailableIntegrations(t)
+ const [integrationConfigurating, setIntegrationConfigurating] = useState(null)
+ const [tgChatId, setTgChatId] = useState(null)
+ const [isIntegrationLoading, setIsIntegrationLoading] = useState(false)
+ const [isRemovalLoading, setIsRemovalLoading] = useState(false)
+
+ const setupIntegration = (key) => () => {
+ setIntegrationConfigurating(key)
+ }
+
+ const addIntegration = (key) => () => {
+ if (isIntegrationLoading) {
+ return
+ }
+
+ if (key === 'telegram' && tgChatId) {
+ setIsIntegrationLoading(true)
+ handleIntegrationSave({
+ telegramChatId: tgChatId,
+ }, () => {
+ setIsIntegrationLoading(false)
+ setIntegrationConfigurating(null)
+ })
+ }
+ }
+
+ const getIntegrationStatus = (key) => {
+ if (key === 'telegram') {
+ return {
+ connected: user.telegramChatId,
+ confirmed: user.isTelegramChatIdConfirmed,
+ id: user.telegramChatId,
+ }
+ }
+
+ return {}
+ }
+
+ const removeIntegration = async (key) => {
+ if (isRemovalLoading) {
+ return
+ }
+
+ if (key === 'telegram') {
+ setIsRemovalLoading(true)
+
+ try {
+ await removeTgIntegration(user.telegramChatId)
+ updateUserData({
+ isTelegramChatIdConfirmed: false,
+ telegramChatId: null,
+ })
+ } catch (e) {
+ if (_isString(e)) {
+ genericError(e)
+ } else {
+ genericError(t('apiNotifications.integrationRemovalError'))
+ }
+ console.error(`[ERROR] Failed to remove TG integration: ${e}`)
+ }
+ setIsRemovalLoading(false)
+ }
+ }
+
+ if (integrationConfigurating) {
+ if (integrationConfigurating === 'telegram') {
+ return (
+ <>
+ <Button
+ className='mb-2 mt-2'
+ onClick={() => setIntegrationConfigurating(null)}
+ primary
+ small
+ >
+ {t('common.goBack')}
+ </Button>
+ <p className='text-base max-w-prose text-gray-900 dark:text-gray-50'>
+ <Trans
+ t={t}
+ i18nKey='profileSettings.integrationsList.tgHint'
+ components={{
+ // eslint-disable-next-line jsx-a11y/anchor-has-content
+ url: <a href={TG_BOT_URL} className='hover:underline text-blue-600' target='_blank' rel='noreferrer noopener' />,
+ }}
+ values={{
+ username: TG_BOT_USERNAME,
+ }}
+ />
+ </p>
+ <div className='flex items-center mt-4'>
+ <Input
+ type='text'
+ label={t('profileSettings.chatID')}
+ value={tgChatId}
+ placeholder={t('profileSettings.chatID')}
+ className='sm:col-span-3'
+ onChange={(e) => setTgChatId(e.target.value)}
+ disabled={isIntegrationLoading}
+ />
+ <Button
+ className='ml-2 mt-4'
+ onClick={addIntegration(integrationConfigurating)}
+ loading={isIntegrationLoading}
+ primary
+ large
+ >
+ {t('common.enable')}
+ </Button>
+ </div>
+ </>
+ )
+ }
+
+ return null
+ }
+
+ return (
+ <>
+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.integrationsDesc')}
+ </p>
+ <div className='overflow-hidden bg-white dark:bg-gray-700 mt-2 shadow sm:rounded-md'>
+ <ul className='divide-y divide-gray-200'>
+ {
+ _map(available, ({
+ name, key, description, Icon,
+ }) => {
+ const { connected, confirmed, id } = getIntegrationStatus(key)
+ const status = connected ? (confirmed ? 'connected' : 'pending') : 'notConnected'
+
+ return (
+ <li key={key}>
+ <div className='flex items-center px-4 py-4 sm:px-6'>
+ <div className='flex min-w-0 flex-1 items-center'>
+ <div className='flex-shrink-0'>
+ <Icon className='max-h-12 max-w-12 rounded-full' />
+ </div>
+ <div className='min-w-0 flex-1 px-4 md:grid md:grid-cols-2 md:gap-4'>
+ <div>
+ <p className='text-md font-medium text-gray-800 dark:text-gray-50'>{name}</p>
+ <p className='mt-2 flex items-center text-sm text-gray-500 dark:text-gray-100'>
+ <span>{description}</span>
+ </p>
+ </div>
+ <div>
+ {id && (
+ <p className='text-sm text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.chatID')}
+ {`: ${id}`}
+ </p>
+ )}
+ <p className='mt-2 flex items-center text-sm text-gray-500 dark:text-gray-100'>
+ {status === 'notConnected' && <XCircleIcon className='mr-1.5 h-5 w-5 flex-shrink-0 text-red-400' aria-hidden='true' />}
+ {status === 'pending' && <ClockIcon className='mr-1.5 h-5 w-5 flex-shrink-0 text-yellow-400' aria-hidden='true' />}
+ {status === 'connected' && <CheckCircleIcon className='mr-1.5 h-5 w-5 flex-shrink-0 text-green-400' aria-hidden='true' />}
+ {t(`common.${status}`)}
+ </p>
+ </div>
+ </div>
+ </div>
+ <div>
+ {connected ? (
+ <Button onClick={() => removeIntegration(key)} small danger>
+ {t('profileSettings.removeIntegration')}
+ </Button>
+ ) : (
+ <Button onClick={setupIntegration(key)} small primary>
+ {t('profileSettings.addIntegration')}
+ </Button>
+ )}
+ </div>
+ </div>
+ </li>
+ )
+ })
+ }
+ </ul>
+ </div>
+ </>
+ )
+}
+
+export default memo(Integrations)
diff --git a/src/redux/actions/auth/index.js b/src/redux/actions/auth/index.js
index 36e47df23..bff08f4fa 100644
--- a/src/redux/actions/auth/index.js
+++ b/src/redux/actions/auth/index.js
@@ -108,10 +108,10 @@ export const authActions = {
}
},
- updateUserProfileAsync(data, successfulCallback = () => { }) {
+ updateUserProfileAsync(data, callback = () => { }) {
return {
type: types.UPDATE_USER_PROFILE_ASYNC,
- payload: { data, successfulCallback },
+ payload: { data, callback },
}
},
diff --git a/src/redux/sagas/auth/workers/updateUserProfile.js b/src/redux/sagas/auth/workers/updateUserProfile.js
index b6f3ba4af..aada1db8d 100644
--- a/src/redux/sagas/auth/workers/updateUserProfile.js
+++ b/src/redux/sagas/auth/workers/updateUserProfile.js
@@ -4,15 +4,17 @@ import { authActions } from 'redux/actions/auth'
import { errorsActions } from 'redux/actions/errors'
import { changeUserDetails } from 'api'
-export default function* updateUserProfileWorker({ payload: { data, successfulCallback } }) {
+export default function* updateUserProfileWorker({ payload: { data, callback } }) {
+ let isSuccess = false
try {
const user = yield call(changeUserDetails, data)
yield put(authActions.updateProfileSuccess(user))
- successfulCallback()
+ isSuccess = true
} catch (error) {
yield put(errorsActions.updateProfileFailed(error.message || (typeof error === 'string' ? error : error[0])))
} finally {
yield put(authActions.finishLoading())
+ callback(isSuccess)
}
}