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!

Added ability to connect accounts

Yevhenii Kulisidi88c6f7f81d77
diff --git a/src/task-manager/task-manager.service.ts b/src/task-manager/task-manager.service.ts
index 87a6612c6..8d1a57333 100644
--- a/src/task-manager/task-manager.service.ts
+++ b/src/task-manager/task-manager.service.ts
@@ -71,7 +71,9 @@ export class TaskManagerService {
const query = `INSERT INTO customEV (id, pid, ev, created)`
await clickhouse.query(query, parsed).toPromise()
} catch (e) {
- console.error(`[CRON WORKER] Error whilst saving custom events data: ${e}`)
+ console.error(
+ `[CRON WORKER] Error whilst saving custom events data: ${e}`,
+ )
}
}
@@ -83,7 +85,9 @@ export class TaskManagerService {
try {
await clickhouse.query(query).toPromise()
} catch (e) {
- console.error(`[CRON WORKER] Error whilst saving performance data: ${e}`)
+ console.error(
+ `[CRON WORKER] Error whilst saving performance data: ${e}`,
+ )
}
}
}
@@ -304,7 +308,8 @@ export class TaskManagerService {
const setSdurQuery = `ALTER TABLE analytics UPDATE sdur = sdur + CASE ${_map(
toSave,
- ([key, duration]) => `WHEN sid = '${key.split(':')[1]}' THEN ${duration / 1000}`, // converting to seconds
+ ([key, duration]) =>
+ `WHEN sid = '${key.split(':')[1]}' THEN ${duration / 1000}`, // converting to seconds
).join(' ')} END WHERE sid IN (${_map(
toSave,
([key]) => `'${key.split(':')[1]}'`,
@@ -313,4 +318,20 @@ export class TaskManagerService {
await clickhouse.query(setSdurQuery).toPromise()
}
}
+
+ @Cron(CronExpression.EVERY_10_MINUTES)
+ async checkIsTelegramChatIdConfirmed(): Promise<void> {
+ const users = await this.userService.find({
+ where: {
+ isTelegramChatIdConfirmed: false,
+ },
+ select: ['id', 'telegramChatId'],
+ })
+
+ for (let i = 0; i < _size(users); ++i) {
+ await this.userService.update(users[i].id, {
+ telegramChatId: null,
+ })
+ }
+ }
}
diff --git a/src/tg-integration/tg.module.ts b/src/tg-integration/tg.module.ts
index e308395f7..4f9d43ab6 100644
--- a/src/tg-integration/tg.module.ts
+++ b/src/tg-integration/tg.module.ts
@@ -1,7 +1,9 @@
import { Module } from '@nestjs/common'
+import { UserModule } from 'src/user/user.module'
import { SwetrixUpdate } from './tg.update'
@Module({
+ imports: [UserModule],
providers: [SwetrixUpdate],
})
export class TGModule {}
diff --git a/src/tg-integration/tg.update.ts b/src/tg-integration/tg.update.ts
index 7917a84e7..08469695d 100644
--- a/src/tg-integration/tg.update.ts
+++ b/src/tg-integration/tg.update.ts
@@ -1,9 +1,12 @@
-import { Ctx, Sender, Start, Update } from 'nestjs-telegraf'
+import { Ctx, On, Sender, Start, Update } from 'nestjs-telegraf'
import { SWETRIX_SETTINGS_URL } from 'src/tg-integration/constants'
+import { UserService } from 'src/user/user.service'
import { Context } from 'telegraf'
@Update()
export class SwetrixUpdate {
+ constructor(private readonly userService: UserService) {}
+
@Start()
async start(
@Ctx() ctx: Context,
@@ -21,4 +24,36 @@ export class SwetrixUpdate {
disable_web_page_preview: true,
})
}
+
+ @On('callback_query')
+ async callbackQuery(@Ctx() ctx: Context): Promise<void> {
+ const [action, userId] = ctx.callbackQuery?.['data'].split(':')
+
+ if (action === 'confirmTelegramChatId') {
+ await ctx.telegram.editMessageText(
+ ctx.chat.id,
+ ctx.callbackQuery?.['message'].message_id,
+ undefined,
+ 'βœ… Your Telegram account is connected to your Swetrix account.',
+ )
+
+ await this.userService.update(userId, {
+ telegramChatId: ctx.chat.id,
+ isTelegramChatIdConfirmed: true,
+ })
+ }
+
+ if (action === 'cancelTelegramChatId') {
+ await ctx.telegram.editMessageText(
+ ctx.chat.id,
+ ctx.callbackQuery?.['message'].message_id,
+ undefined,
+ '❌ Your Telegram account is not connected to your Swetrix account.',
+ )
+
+ await this.userService.update(userId, {
+ telegramChatId: null,
+ })
+ }
+ }
}
diff --git a/src/user/dto/admin-update-user.dto.ts b/src/user/dto/admin-update-user.dto.ts
index acca90ad1..e9f047cd9 100644
--- a/src/user/dto/admin-update-user.dto.ts
+++ b/src/user/dto/admin-update-user.dto.ts
@@ -32,4 +32,7 @@ export class AdminUpdateUserProfileDTO {
@ApiProperty({ example: 'Europe/Kiev' })
timezone: string
+
+ @ApiProperty({ example: '1234567890' })
+ telegramChatId: string | null
}
diff --git a/src/user/dto/update-user.dto.ts b/src/user/dto/update-user.dto.ts
index 2130937f8..7b7d43fda 100644
--- a/src/user/dto/update-user.dto.ts
+++ b/src/user/dto/update-user.dto.ts
@@ -14,4 +14,7 @@ export class UpdateUserProfileDTO {
@ApiProperty({ example: 'Europe/Kiev' })
timezone: string
+
+ @ApiProperty({ example: '1234567890' })
+ telegramChatId: string | null
}
diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.ts
index c6437296c..c785e22aa 100644
--- a/src/user/entities/user.entity.ts
+++ b/src/user/entities/user.entity.ts
@@ -192,6 +192,20 @@ export class User {
})
apiKey: string | null
+ @Column({
+ type: 'varchar',
+ unique: true,
+ nullable: true,
+ default: null,
+ })
+ telegramChatId: string | null
+
+ @Column({
+ type: 'boolean',
+ default: false,
+ })
+ isTelegramChatIdConfirmed: boolean
+
@OneToMany(() => ExtensionToUser, extensionToUser => extensionToUser.user)
@JoinTable()
extensions: ExtensionToUser[]
diff --git a/src/user/user.controller.ts b/src/user/user.controller.ts
index b44c7ac8c..bcb12c842 100644
--- a/src/user/user.controller.ts
+++ b/src/user/user.controller.ts
@@ -54,9 +54,13 @@ import { LetterTemplate } from '../mailer/letter'
import { AppLoggerService } from '../logger/logger.service'
import { UserProfileDTO } from './dto/user.dto'
import { checkRateLimit } from '../common/utils'
+import { InjectBot } from 'nestjs-telegraf'
+import { Scenes, Telegraf } from 'telegraf'
dayjs.extend(utc)
+export type TelegrafContext = Scenes.SceneContext
+
@ApiTags('User')
@Controller('user')
@UseGuards(RolesGuard)
@@ -68,6 +72,7 @@ export class UserController {
private readonly actionTokensService: ActionTokensService,
private readonly mailerService: MailerService,
private readonly logger: AppLoggerService,
+ @InjectBot() private bot: Telegraf<TelegrafContext>,
) {}
@Get('/')
@@ -434,6 +439,43 @@ export class UserController {
{ url },
)
}
+
+ if (
+ userDTO.telegramChatId &&
+ user.telegramChatId !== userDTO.telegramChatId
+ ) {
+ const userWithByTelegramChatId = await this.userService.findOneWhere({
+ telegramChatId: userDTO.telegramChatId,
+ })
+
+ if (userWithByTelegramChatId) {
+ throw new BadRequestException(
+ 'User with this telegram chat id already exists',
+ )
+ }
+
+ this.bot.telegram.sendMessage(
+ userDTO.telegramChatId,
+ 'Confirm the connection between your Telegram account and your Swetrix account.',
+ {
+ reply_markup: {
+ inline_keyboard: [
+ [
+ {
+ text: 'βœ… Confirm',
+ callback_data: `confirmTelegramChatId:${user.id}`,
+ },
+ {
+ text: '❌ Cancel',
+ callback_data: `cancelTelegramChatId:${user.id}`,
+ },
+ ],
+ ],
+ },
+ },
+ )
+ }
+
// delete internal properties from userDTO before updating it
// todo: use _pick instead of _omit
const userToUpdate = _omit(userDTO, [
@@ -457,7 +499,10 @@ export class UserController {
'twoFactorAuthenticationSecret',
'isTwoFactorAuthenticationEnabled',
])
- await this.userService.update(id, userToUpdate)
+ await this.userService.update(id, {
+ ...userToUpdate,
+ isTelegramChatIdConfirmed: false,
+ })
const updatedUser = await this.userService.findOneWhere({ id })
return this.userService.omitSensitiveData(updatedUser)