π 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Other features of the Telegram bot were implemented
Yevhenii Kulisidi6138d829709a
diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.tsindex e4e89dc18..f63682f5b 100644--- a/src/analytics/analytics.service.ts+++ b/src/analytics/analytics.service.ts@@ -1298,4 +1298,13 @@ export class AnalyticsService {},})}++ async getOnlineCountByProjectId(projectId: string) {+ // @ts-ignore+ return redis.countKeysByPattern(`hb:${projectId}:*`)+ }++ async getStatsByProjectId(projectId: string) {+ return this.getSummaryStats([projectId], 'analytics', 'w', 1)+ }}diff --git a/src/app.module.ts b/src/app.module.tsindex 1b3cdf854..7f3fcbdd5 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -2,7 +2,6 @@ import { Module } from '@nestjs/common'import { TypeOrmModule } from '@nestjs/typeorm'import { ConfigModule } from '@nestjs/config'import { ScheduleModule } from '@nestjs/schedule'-import { TelegrafModule } from 'nestjs-telegraf'import { NestjsFormDataModule } from 'nestjs-form-data'import { I18nModule } from 'nestjs-i18n'@@ -15,13 +14,12 @@ import { TwoFactorAuthModule } from './twoFactorAuth/twoFactorAuth.module'import { TaskManagerModule } from './task-manager/task-manager.module'import { WebhookModule } from './webhook/webhook.module'import { PingModule } from './ping/ping.module'-// import { TGModule } from './tg-integration/tg.module'import { MarketplaceModule } from './marketplace/marketplace.module'import { AlertModule } from './alert/alert.module'import { getI18nConfig } from './configs'import { AuthModule } from './auth/auth.module'import { CaptchaModule } from './captcha/captcha.module'-import { isDevelopment, isTgTokenPresent } from './common/constants'+import { isDevelopment } from './common/constants'import { IntegrationsModule } from './integrations/integrations.module'const modules = [@@ -53,21 +51,12 @@ const modules = [AnalyticsModule,WebhookModule,PingModule,- // TGModule,MarketplaceModule,AlertModule,AuthModule,CaptchaModule,]-if (isTgTokenPresent) {- modules.push(- TelegrafModule.forRoot({- token: process.env.TG_BOT_TOKEN,- }),- )-}-@Module({imports: [...modules,diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.tsindex 85b92eda0..617ee46cc 100644--- a/src/auth/auth.module.ts+++ b/src/auth/auth.module.ts@@ -5,6 +5,7 @@ import { ActionTokensModule } from 'src/action-tokens/action-tokens.module'import { MailerModule } from 'src/mailer/mailer.module'import { UserModule } from 'src/user/user.module'import { ProjectModule } from 'src/project/project.module'+import { TelegramService } from 'src/integrations/telegram/telegram.service'import { AuthController } from './auth.controller'import { AuthService } from './auth.service'import {@@ -29,6 +30,7 @@ import {JwtAccessTokenStrategy,JwtRefreshTokenStrategy,ApiKeyStrategy,+ TelegramService,],exports: [AuthService],})diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex 893f23772..c49135cca 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -12,8 +12,6 @@ import { getCountry } from 'countries-and-timezones'import { Auth } from 'googleapis'import { createHash } from 'crypto'import * as dayjs from 'dayjs'-import { InjectBot } from 'nestjs-telegraf'-import { Telegraf } from 'telegraf'import { UAParser } from 'ua-parser-js'import * as _pick from 'lodash/pick'import * as _split from 'lodash/split'@@ -33,7 +31,6 @@ import {User,TRIAL_DURATION,} from 'src/user/entities/user.entity'-import { TelegrafContext } from 'src/user/user.controller'import { UserService } from 'src/user/user.service'import { ProjectService } from 'src/project/project.service'import {@@ -42,6 +39,7 @@ import {PRODUCTION_ORIGIN,isDevelopment,} from 'src/common/constants'+import { TelegramService } from 'src/integrations/telegram/telegram.service'import { SSOProviders } from './dtos/sso-generate.dto'import { UserGoogleDTO } from '../user/dto/user-google.dto'import { UserGithubDTO } from '../user/dto/user-github.dto'@@ -68,13 +66,13 @@ export class AuthService {githubOAuthClientSecret: stringconstructor(- @InjectBot() private readonly telegramBot: Telegraf<TelegrafContext>,private readonly userService: UserService,private readonly actionTokensService: ActionTokensService,private readonly configService: ConfigService,private readonly mailerService: MailerService,private readonly jwtService: JwtService,private readonly projectService: ProjectService,+ private readonly telegramService: TelegramService,) {this.oauth2Client = new Auth.OAuth2Client(this.configService.get('GOOGLE_OAUTH2_CLIENT_ID'),@@ -186,6 +184,14 @@ export class AuthService {return user}+ if (user && user.isTelegramChatIdConfirmed) {+ await this.telegramService.sendMessage(+ Number(user.telegramChatId),+ 'β οΈ *Someone has tried to login to their account with an incorrect password.*',+ { parse_mode: 'Markdown' },+ )+ }+return null}@@ -220,12 +226,6 @@ export class AuthService {return}- const chat = await this.checkTelegramChatId(user.telegramChatId)-- if (!chat) {- return- }-const headersInfo = await this.getHeadersInfo(headers)const loginDate = dayjs().utc().format('YYYY-MM-DD HH:mm:ss')const message =@@ -237,9 +237,15 @@ export class AuthService {`*IP:* ${ip}\n` +`*Date:* ${loginDate} (UTC)\n\n` +'If it was not you, please change your password immediately.'- await this.telegramBot.telegram.sendMessage(user.telegramChatId, message, {- parse_mode: 'Markdown',- })+ if (user && user.isTelegramChatIdConfirmed) {+ await this.telegramService.sendMessage(+ Number(user.telegramChatId),+ message,+ {+ parse_mode: 'Markdown',+ },+ )+ }}private async getHeadersInfo(headers: unknown) {@@ -266,11 +272,6 @@ export class AuthService {}}- public async checkTelegramChatId(chatId: string): Promise<boolean> {- const chat = (await this.telegramBot.telegram.getChat(chatId)).id- return Boolean(chat)- }-public async checkVerificationToken(token: string,): Promise<ActionToken | null> {diff --git a/src/common/decorators/update-type.decorator.ts b/src/common/decorators/update-type.decorator.tsdeleted file mode 100644index 9b877b861..000000000--- a/src/common/decorators/update-type.decorator.ts+++ /dev/null@@ -1,7 +0,0 @@-import { createParamDecorator, ExecutionContext } from '@nestjs/common'-import { TelegrafExecutionContext } from 'nestjs-telegraf'--export const UpdateType = createParamDecorator(- (_, ctx: ExecutionContext) =>- TelegrafExecutionContext.create(ctx).getContext().updateType,-)diff --git a/src/common/interfaces/context.interface.ts b/src/common/interfaces/context.interface.tsdeleted file mode 100644index aaa3405a8..000000000--- a/src/common/interfaces/context.interface.ts+++ /dev/null@@ -1,4 +0,0 @@-import { Scenes } from 'telegraf'--// eslint-disable-next-line @typescript-eslint/no-empty-interface-export interface Context extends Scenes.SceneContext {}diff --git a/src/integrations/telegram/scene/projects.scene.ts b/src/integrations/telegram/scene/projects.scene.tsindex e0812734c..a76c8342d 100644--- a/src/integrations/telegram/scene/projects.scene.ts+++ b/src/integrations/telegram/scene/projects.scene.ts@@ -1,21 +1,112 @@-import { Ctx, Hears, Scene, SceneEnter } from 'nestjs-telegraf'+import { Ctx, Hears, On, Scene, SceneEnter } from 'nestjs-telegraf'import { Markup } from 'telegraf'+import * as dayjs from 'dayjs'+import * as utc from 'dayjs/plugin/utc'+import * as timezone from 'dayjs/plugin/timezone'+import { ProjectService } from 'src/project/project.service'+import { UserService } from 'src/user/user.service'+import { AnalyticsService } from 'src/analytics/analytics.service'import { Context } from '../interface/context.interface'import { START_SCENE_ID } from './start.scene'+dayjs.extend(utc)+dayjs.extend(timezone)+export const PROJECTS_SCENE_ID = 'projects'@Scene(PROJECTS_SCENE_ID)export class ProjectsScene {+ constructor(+ private readonly userService: UserService,+ private readonly projectService: ProjectService,+ private readonly analyticsService: AnalyticsService,+ ) {}+@SceneEnter()async onSceneEnter(@Ctx() context: Context) {+ const user = await this.userService.getUserByTelegramId(context.from.id)++ if (!user) {+ await context.scene.enter(START_SCENE_ID)+ return+ }++ const projects = await this.projectService.getProjectsByUserId(user.id)++ if (projects.length === 0) {+ await context.reply(+ 'You have no projects yet.',+ Markup.keyboard([['π Back']])+ .oneTime()+ .resize(),+ )+ return+ }+await context.reply(- '...',- Markup.keyboard([['π Back']])- .oneTime()- .resize(),+ 'Projects',+ Markup.keyboard([+ ...projects.map(project => [project.name]),+ ['π Back'],+ ]).resize(),)}+ @On('text')+ async onText(@Ctx() context: Context & { message: { text: string } }) {+ if (context.message.text === 'π Back') {+ await context.scene.enter(START_SCENE_ID)+ return+ }++ const user = await this.userService.getUserByTelegramId(context.from.id)++ if (!user) {+ await context.scene.enter(START_SCENE_ID)+ return+ }++ const project = await this.projectService.getProjectByNameAndUserId(+ context.message.text,+ user.id,+ )++ if (!project) {+ await context.reply('Project not found.')+ await context.scene.reenter()+ }++ const onlineCount = await this.analyticsService.getOnlineCountByProjectId(+ project.id,+ )+ const stats = await this.analyticsService.getStatsByProjectId(project.id)++ const text =+ `π *${project.name}*` ++ `\n\n` ++ `*Information*` ++ `\n` ++ `ID: \`${project.id}\`` ++ `\n` ++ `Active: \`${project.active ? 'yes' : 'no'}\`` ++ `\n` ++ `Public: \`${project.public ? 'yes' : 'no'}\`` ++ `\n` ++ `Created: \`${dayjs+ .utc(project.created)+ .tz(user.timezone)+ .format('YYYY-MM-DD HH:mm:ss')}\`` ++ `\n\n` ++ `*Analytics (last 7 days)*` ++ `\n` ++ `Online users: \`${onlineCount}\`` ++ `\n` ++ `Page views: \`${stats[project.id].thisWeek}\`` ++ `\n` ++ `Unique page views: \`${stats[project.id].thisWeekUnique}\``++ await context.replyWithMarkdown(text)+ }+@Hears('π Back')async onBack(@Ctx() context: Context) {await context.scene.enter(START_SCENE_ID)diff --git a/src/integrations/telegram/scene/settings.scene.ts b/src/integrations/telegram/scene/settings.scene.tsindex 1cc82e8ab..849b9feaa 100644--- a/src/integrations/telegram/scene/settings.scene.ts+++ b/src/integrations/telegram/scene/settings.scene.ts@@ -10,7 +10,7 @@ export class SettingsScene {@SceneEnter()async onSceneEnter(@Ctx() context: Context) {await context.reply(- '...',+ 'Settings',Markup.keyboard(['π Unlink account', 'π Back']).oneTime().resize(),)}diff --git a/src/integrations/telegram/scene/unlink-account.scene.ts b/src/integrations/telegram/scene/unlink-account.scene.tsindex 6d26ca54d..f81e5fec5 100644--- a/src/integrations/telegram/scene/unlink-account.scene.ts+++ b/src/integrations/telegram/scene/unlink-account.scene.ts@@ -2,14 +2,17 @@ import { Ctx, Hears, Scene, SceneEnter } from 'nestjs-telegraf'import { Markup } from 'telegraf'import { Context } from '../interface/context.interface'import { START_SCENE_ID } from './start.scene'+import { TelegramService } from '../telegram.service'export const UNLINK_ACCOUNT_SCENE_ID = 'unlink-account'@Scene(UNLINK_ACCOUNT_SCENE_ID)export class UnlinkAccountScene {+ constructor(private readonly telegramService: TelegramService) {}+@SceneEnter()async onSceneEnter(@Ctx() context: Context) {await context.reply(- '...',+ 'Are you sure you want to unlink your account?',Markup.keyboard([['β Yes', 'β No']]).oneTime().resize(),@@ -18,13 +21,14 @@ export class UnlinkAccountScene {@Hears('β Yes')async onYes(@Ctx() context: Context) {- await context.reply('...')+ await this.telegramService.confirmUnlinkAccount(context.from.id)+ await context.reply('Your account has been unlinked successfully.')await context.scene.enter(START_SCENE_ID)}@Hears('β No')async onNo(@Ctx() context: Context) {- await context.reply('...')+ await context.reply('Your account has not been unlinked.')await context.scene.enter(START_SCENE_ID)}}diff --git a/src/integrations/telegram/telegram.module.ts b/src/integrations/telegram/telegram.module.tsindex 46df5b7c0..deabc1b25 100644--- a/src/integrations/telegram/telegram.module.ts+++ b/src/integrations/telegram/telegram.module.ts@@ -3,6 +3,8 @@ import { ConfigService } from '@nestjs/config'import { TelegrafModule } from 'nestjs-telegraf'import { session } from 'telegraf'import { UserModule } from 'src/user/user.module'+import { ProjectModule } from 'src/project/project.module'+import { AnalyticsModule } from 'src/analytics/analytics.module'import { TelegramController } from './telegram.controller'import { TelegramUpdate } from './telegram.update'import { StartScene } from './scene/start.scene'@@ -37,6 +39,8 @@ import { TelegramService } from './telegram.service'}),}),UserModule,+ ProjectModule,+ AnalyticsModule,],controllers: [TelegramController],providers: [@@ -47,5 +51,6 @@ import { TelegramService } from './telegram.service'UnlinkAccountScene,TelegramService,],+ exports: [TelegramService],})export class TelegramModule {}diff --git a/src/integrations/telegram/telegram.service.ts b/src/integrations/telegram/telegram.service.tsindex 406075e85..0b85f0d51 100644--- a/src/integrations/telegram/telegram.service.ts+++ b/src/integrations/telegram/telegram.service.ts@@ -1,10 +1,17 @@import { Injectable } from '@nestjs/common'+import { ConfigService } from '@nestjs/config'+import { InjectBot } from 'nestjs-telegraf'+import { Markup, Telegraf } from 'telegraf'import { UserService } from 'src/user/user.service'-import { Markup } from 'telegraf'+import { Context } from './interface/context.interface'@Injectable()export class TelegramService {- constructor(private readonly userService: UserService) {}+ constructor(+ @InjectBot() private readonly bot: Telegraf<Context>,+ private readonly userService: UserService,+ private readonly configService: ConfigService,+ ) {}async getStartMessage(telgramId: number) {const user = await this.userService.getUserByTelegramId(telgramId)@@ -24,7 +31,10 @@ export class TelegramService {'To do this, go to your <a href="https://swetrix.com/settings">Swetrix account settings</a> and enter this ID in the Telegram field.' +'\n\n' +'After that, you can use the bot to manage your projects.'- extra = { disable_web_page_preview: true }+ extra = {+ disable_web_page_preview: true,+ reply_markup: { remove_keyboard: true },+ }}if (user) {@@ -38,4 +48,51 @@ export class TelegramService {return { text, extra }}++ async sendMessage(chatId: number, text: string, extra?: unknown) {+ if (+ this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&+ this.configService.get<string>('ENABLE_TELEGRAM_INTEGRATION') !== 'true'+ ) {+ return+ }++ const chat = await this.bot.telegram.getChat(chatId)+ if (!chat) return+ await this.bot.telegram.sendMessage(chatId, text, extra)+ }++ async confirmLinkAccount(userId: string, chatId: number) {+ if (+ this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&+ this.configService.get<string>('ENABLE_TELEGRAM_INTEGRATION') !== 'true'+ ) {+ return+ }++ await this.userService.updateUserTelegramId(userId, chatId, true)+ }++ async cancelLinkAccount(userId: string) {+ if (+ this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&+ this.configService.get<string>('ENABLE_TELEGRAM_INTEGRATION') !== 'true'+ ) {+ return+ }++ await this.userService.updateUserTelegramId(userId, null)+ }++ async confirmUnlinkAccount(chatId: number) {+ if (+ this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&+ this.configService.get<string>('ENABLE_TELEGRAM_INTEGRATION') !== 'true'+ ) {+ return+ }++ const user = await this.userService.getUserByTelegramId(chatId)+ await this.userService.updateUserTelegramId(user.id, null)+ }}diff --git a/src/integrations/telegram/telegram.update.ts b/src/integrations/telegram/telegram.update.tsindex 47952c27b..61118b3e5 100644--- a/src/integrations/telegram/telegram.update.ts+++ b/src/integrations/telegram/telegram.update.ts@@ -1,11 +1,33 @@-import { Ctx, Start, Update } from 'nestjs-telegraf'+import { Action, Ctx, Start, Update } from 'nestjs-telegraf'+import { TelegramService } from './telegram.service'import { Context } from './interface/context.interface'import { START_SCENE_ID } from './scene/start.scene'@Update()export class TelegramUpdate {+ constructor(private readonly telegramService: TelegramService) {}+@Start()async onStart(@Ctx() context: Context) {await context.scene.enter(START_SCENE_ID)}++ @Action(/link-account:confirm:(.+)/)+ async onLinkAccountConfirm(@Ctx() context: Context & { match: unknown }) {+ await context.answerCbQuery()+ await this.telegramService.confirmLinkAccount(+ context.match[1] as string,+ context.from.id,+ )+ await context.editMessageText('Your account has been linked successfully.')+ await context.scene.enter(START_SCENE_ID)+ }++ @Action(/link-account:cancel:(.+)/)+ async onLinkAccountCancel(@Ctx() context: Context & { match: unknown }) {+ await context.answerCbQuery()+ await this.telegramService.cancelLinkAccount(context.match[1] as string)+ await context.editMessageText('Your account has not been linked.')+ await context.scene.leave()+ }}diff --git a/src/project/project.service.ts b/src/project/project.service.tsindex e64094b20..8f825af6d 100644--- a/src/project/project.service.ts+++ b/src/project/project.service.ts@@ -692,4 +692,16 @@ export class ProjectService {)await this.actionTokens.deleteActionToken(token)}++ async getProjectsByUserId(userId: string) {+ return this.projectsRepository.find({+ where: { admin: { id: userId } },+ })+ }++ async getProjectByNameAndUserId(name: string, userId: string) {+ return this.projectsRepository.findOne({+ where: { name, admin: { id: userId } },+ })+ }}diff --git a/src/task-manager/task-manager.module.ts b/src/task-manager/task-manager.module.tsindex 8f1785a8a..3b9f0fbd1 100644--- a/src/task-manager/task-manager.module.ts+++ b/src/task-manager/task-manager.module.ts@@ -1,6 +1,7 @@import { Module, forwardRef } from '@nestjs/common'import { AlertModule } from 'src/alert/alert.module'import { ExtensionsModule } from 'src/marketplace/extensions/extensions.module'+import { TelegramService } from 'src/integrations/telegram/telegram.service'import { TaskManagerService } from './task-manager.service'import { MailerModule } from '../mailer/mailer.module'import { UserModule } from '../user/user.module'@@ -20,7 +21,7 @@ import { AppLoggerModule } from '../logger/logger.module'ExtensionsModule,AppLoggerModule,],- providers: [TaskManagerService],+ providers: [TaskManagerService, TelegramService],exports: [TaskManagerService],})export class TaskManagerModule {}diff --git a/src/task-manager/task-manager.service.ts b/src/task-manager/task-manager.service.tsindex 78d9e3be6..9d6076544 100644--- a/src/task-manager/task-manager.service.ts+++ b/src/task-manager/task-manager.service.ts@@ -13,13 +13,11 @@ import * as _now from 'lodash/now'import * as _find from 'lodash/find'import { AlertService } from 'src/alert/alert.service'-import { InjectBot } from 'nestjs-telegraf'-import { TelegrafContext } from 'src/user/user.controller'-import { Telegraf } from 'telegraf'import { QueryCondition, QueryMetric, QueryTime } from 'src/alert/dto/alert.dto'import { ExtensionsService } from 'src/marketplace/extensions/extensions.service'import { Extension } from 'src/marketplace/extensions/entities/extension.entity'import { ReportFrequency } from 'src/project/enums'+import { TelegramService } from 'src/integrations/telegram/telegram.service'import { MailerService } from '../mailer/mailer.service'import { UserService } from '../user/user.service'import { ProjectService } from '../project/project.service'@@ -91,9 +89,9 @@ export class TaskManagerService {private readonly projectService: ProjectService,private readonly actionTokensService: ActionTokensService,private readonly alertService: AlertService,- @InjectBot() private bot: Telegraf<TelegrafContext>,private readonly extensionsService: ExtensionsService,private readonly logger: AppLoggerService,+ private readonly telegramService: TelegramService,) {}@Cron(CronExpression.EVERY_MINUTE)@@ -784,14 +782,15 @@ export class TaskManagerService {await this.alertService.update(alert.id, {lastTriggered: new Date(),})-- this.bot.telegram.sendMessage(- project.admin.telegramChatId,- `π Alert *${alert.name}* got triggered!\nYour project *${project.name}* has *${online}* online users right now!`,- {- parse_mode: 'Markdown',- },- )+ if (project.admin && project.admin.isTelegramChatIdConfirmed) {+ this.telegramService.sendMessage(+ Number(project.admin.telegramChatId),+ `π Alert *${alert.name}* got triggered!\nYour project *${project.name}* has *${online}* online users right now!`,+ {+ parse_mode: 'Markdown',+ },+ )+ }}})@@ -862,9 +861,15 @@ export class TaskManagerService {alert.queryTime,)}!`- this.bot.telegram.sendMessage(project.admin.telegramChatId, text, {- parse_mode: 'Markdown',- })+ if (project.admin && project.admin.isTelegramChatIdConfirmed) {+ this.telegramService.sendMessage(+ Number(project.admin.telegramChatId),+ text,+ {+ parse_mode: 'Markdown',+ },+ )+ }}})diff --git a/src/tg-integration/constants.ts b/src/tg-integration/constants.tsdeleted file mode 100644index 157847b1f..000000000--- a/src/tg-integration/constants.ts+++ /dev/null@@ -1 +0,0 @@-export const SWETRIX_SETTINGS_URL = 'https://swetrix.com/settings'diff --git a/src/tg-integration/tg.module.ts b/src/tg-integration/tg.module.tsdeleted file mode 100644index a0a8bc589..000000000--- a/src/tg-integration/tg.module.ts+++ /dev/null@@ -1,12 +0,0 @@-import { Module } from '@nestjs/common'-import { AnalyticsModule } from 'src/analytics/analytics.module'-import { ProjectModule } from 'src/project/project.module'-import { UserModule } from 'src/user/user.module'-import { AlertModule } from 'src/alert/alert.module'-import { SwetrixUpdate } from './tg.update'--@Module({- imports: [UserModule, ProjectModule, AnalyticsModule, AlertModule],- providers: [SwetrixUpdate],-})-export class TGModule {}diff --git a/src/tg-integration/tg.update.ts b/src/tg-integration/tg.update.tsdeleted file mode 100644index b86453bf9..000000000--- a/src/tg-integration/tg.update.ts+++ /dev/null@@ -1,304 +0,0 @@-import { Ctx, Hears, On, Sender, Start, Update } from 'nestjs-telegraf'-import { ProjectService } from 'src/project/project.service'-import { SWETRIX_SETTINGS_URL } from 'src/tg-integration/constants'-import { UserService } from 'src/user/user.service'-import { Context, Markup } from 'telegraf'-import * as _map from 'lodash/map'-import * as _isEmpty from 'lodash/isEmpty'-import * as dayjs from 'dayjs'-import * as utc from 'dayjs/plugin/utc'-import * as timezone from 'dayjs/plugin/timezone'-import { AnalyticsService } from 'src/analytics/analytics.service'-import { AlertService } from 'src/alert/alert.service'--dayjs.extend(utc)-dayjs.extend(timezone)--@Update()-export class SwetrixUpdate {- constructor(- private readonly userService: UserService,- private readonly projectService: ProjectService,- private readonly analyticsService: AnalyticsService,- private readonly alertService: AlertService,- ) {}-- @Start()- async start(- @Ctx() ctx: Context,- @Sender('first_name') firstName: string,- @Sender('id') chatId: string,- ): Promise<void> {- const user = await this.userService.findOneWhere({ telegramChatId: chatId })- const text =- `Hello, *${firstName}*!` +- '\n' +- `Your chat ID is \`${chatId}\`` +- '\n\n' +- `Use this chat ID to connect your Telegram account to your Swetrix account on ${SWETRIX_SETTINGS_URL}.`- await ctx.reply(text, {- parse_mode: 'Markdown',- disable_web_page_preview: true,- ...(user && {- reply_markup: {- keyboard: [[{ text: 'Projects' }, { text: 'Settings' }]],- resize_keyboard: true,- },- }),- })- }-- @On('callback_query')- async callbackQuery(- @Ctx() ctx: Context,- @Sender('id') chatId: string,- ): Promise<void> {- // TODO: REMOVE THE TS IGNORE AND INVESTIGATE THIS ISSUE- // @ts-ignore- const [action, entityId] = ctx.callbackQuery.data.split(':') // eslint-disable-line-- if (action === 'unlinkTelegramAccount') {- await ctx.editMessageText(- 'β οΈ Are you sure you want to unlink your Telegram account from your Swetrix account?',- Markup.inlineKeyboard([- Markup.button.callback('β Yes', 'unlinkTelegramAccountConfirm'),- Markup.button.callback('β No', 'unlinkTelegramAccountCancel'),- ]),- )- }-- if (action === 'unlinkTelegramAccountConfirm') {- const user = await this.userService.findOneWhere({- telegramChatId: chatId,- })-- if (!user) {- await ctx.telegram.editMessageText(- ctx.chat.id,- ctx.callbackQuery?.message.message_id,- undefined,- 'β Your Telegram account is not connected to your Swetrix account.',- )- return- }-- await this.userService.update(user.id, {- telegramChatId: null,- isTelegramChatIdConfirmed: false,- })-- await ctx.telegram.editMessageText(- ctx.chat.id,- ctx.callbackQuery?.message.message_id,- undefined,- 'β Your Telegram account is unlinked from your Swetrix account.',- )- }-- if (action === 'unlinkTelegramAccountCancel') {- await ctx.telegram.editMessageText(- ctx.chat.id,- ctx.callbackQuery?.message.message_id,- undefined,- 'β Canceled unlinking of this Telegram account from your Swetrix account.',- )- }-- if (action === 'confirmTelegramChatId') {- await ctx.telegram.deleteMessage(- ctx.chat.id,- ctx.callbackQuery?.message.message_id,- )- await ctx.telegram.sendMessage(- ctx.chat.id,- 'β Your Telegram account is connected to your Swetrix account.',- {- reply_markup: {- keyboard: [[{ text: 'Projects' }, { text: 'Settings' }]],- resize_keyboard: true,- },- },- )-- await this.userService.update(entityId, {- 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(entityId, {- telegramChatId: null,- })- }-- if (action === 'project') {- const project = await this.projectService.findOne(entityId)-- if (!project) {- return- }-- const user = await this.userService.findOneWhere({- telegramChatId: chatId,- })-- if (!user) {- return- }-- const alerts = await this.alertService.findWhere({- project: project.id,- })-- const online = await this.analyticsService.getOnlineUserCount(project.id)-- const stats = await this.analyticsService.getSummary([project.id], 'w')- let alertsString = ''-- if (_isEmpty(alerts)) {- alertsString = 'β Not set'- } else {- alertsString = _map(alerts, alert => {- return `*${alert.name}*: ${alert.type} -> ${alert.value}`- }).join('\n')- }-- const text =- `π *${project.name}*` +- `\n\n` +- `*Information*` +- `\n` +- `ID: \`${project.id}\`` +- `\n` +- `Active: \`${project.active ? 'yes' : 'no'}\`` +- `\n` +- `Public: \`${project.public ? 'yes' : 'no'}\`` +- `\n` +- `Created: \`${dayjs- .utc(project.created)- .tz(user.timezone)- .format('YYYY-MM-DD HH:mm:ss')}\`` +- `\n\n` +- `*Analytics (last 7 days)*` +- `\n` +- `Online users: \`${online}\`` +- `\n` +- `Page views: \`${stats[project.id].thisWeek}\`` +- `\n` +- `Unique page views: \`${stats[project.id].thisWeekUnique}\`` +- `\n\n` +- `*Alerts*` +- `\n${alertsString}`- await ctx.editMessageText(text, {- parse_mode: 'Markdown',- reply_markup: {- inline_keyboard: [- [- {- text: 'β¬ οΈ Back',- callback_data: 'projects',- },- ],- ],- },- })- }-- if (action === 'projects') {- const user = await this.userService.findOneWhere({- telegramChatId: chatId,- })-- if (!user) {- return- }-- const projects = await this.projectService.findWhere({ admin: user.id })-- if (_isEmpty(projects)) {- await ctx.reply('You have no projects yet.')- return- }-- const keyboard = _map(projects, project => [- {- text: project.name,- callback_data: `project:${project.id}`,- },- ])-- await ctx.editMessageText('Your projects:', {- reply_markup: {- inline_keyboard: keyboard,- },- })- }- }-- @Hears('Projects')- async projects(- @Sender('id') chatId: string,- @Ctx() ctx: Context,- ): Promise<void> {- const user = await this.userService.findOneWhere({ telegramChatId: chatId })-- if (!user) {- return- }-- const projects = await this.projectService.findWhere({ admin: user.id })-- if (_isEmpty(projects)) {- await ctx.reply('You have no projects yet.')- return- }-- const keyboard = _map(projects, project => [- {- text: project.name,- callback_data: `project:${project.id}`,- },- ])-- await ctx.reply('Your projects:', {- reply_markup: {- inline_keyboard: keyboard,- resize_keyboard: true,- },- })- }-- @Hears('Settings')- async settings(- @Sender('id') chatId: string,- @Ctx() ctx: Context,- ): Promise<void> {- const user = await this.userService.findOneWhere({ telegramChatId: chatId })-- if (!user) {- return- }-- await ctx.reply('Extra settings:', {- reply_markup: {- inline_keyboard: [- [- {- text: 'Unlink Telegram account',- callback_data: 'unlinkTelegramAccount',- },- ],- ],- resize_keyboard: true,- },- })- }-}diff --git a/src/user/user.controller.ts b/src/user/user.controller.tsindex 096391771..b7d0ae3fe 100644--- a/src/user/user.controller.ts+++ b/src/user/user.controller.ts@@ -29,9 +29,9 @@ import * as _isString from 'lodash/isString'import * as _omit from 'lodash/omit'import { v4 as uuidv4 } from 'uuid'-import { InjectBot } from 'nestjs-telegraf'-import { Scenes, Telegraf } from 'telegraf'import { JwtAccessTokenGuard } from 'src/auth/guards'+import { TelegramService } from 'src/integrations/telegram/telegram.service'+import { Markup } from 'telegraf'import { UserService } from './user.service'import { ProjectService, deleteProjectRedis } from '../project/project.service'import {@@ -68,8 +68,6 @@ import { checkRateLimit } from '../common/utils'dayjs.extend(utc)-export type TelegrafContext = Scenes.SceneContext-const UNPAID_PLANS = [PlanCode.free, PlanCode.trial, PlanCode.none]@ApiTags('User')@@ -83,7 +81,7 @@ export class UserController {private readonly actionTokensService: ActionTokensService,private readonly mailerService: MailerService,private readonly logger: AppLoggerService,- @InjectBot() private bot: Telegraf<TelegrafContext>,+ private readonly telegramService: TelegramService,) {}@Get('/me')@@ -524,25 +522,18 @@ export class UserController {isTelegramChatIdConfirmed: false,})- 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}`,- },- ],- ],- },- },+ this.telegramService.sendMessage(+ Number(userDTO.telegramChatId),+ 'Please confirm your Telegram chat ID',+ Markup.inlineKeyboard([+ [+ Markup.button.callback(+ 'β Confirm',+ `link-account:confirm:${id}`,+ ),+ Markup.button.callback('β Cancel', `link-account:cancel:${id}`),+ ],+ ]),)}diff --git a/src/user/user.module.ts b/src/user/user.module.tsindex ff350d50d..b51dc7f33 100644--- a/src/user/user.module.ts+++ b/src/user/user.module.ts@@ -1,6 +1,7 @@import { Module, forwardRef } from '@nestjs/common'import { TypeOrmModule } from '@nestjs/typeorm'+import { TelegramService } from 'src/integrations/telegram/telegram.service'import { UserController } from './user.controller'import { UserService } from './user.service'import { User } from './entities/user.entity'@@ -20,7 +21,7 @@ import { RefreshToken } from './entities/refresh-token.entity'AppLoggerModule,ProjectModule,],- providers: [UserService],+ providers: [UserService, TelegramService],exports: [UserService],controllers: [UserController],})diff --git a/src/user/user.service.ts b/src/user/user.service.tsindex b9ade1602..695b0e42e 100644--- a/src/user/user.service.ts+++ b/src/user/user.service.ts@@ -224,4 +224,15 @@ export class UserService {where: { telegramChatId: telegramId },})}++ async updateUserTelegramId(+ userId: string,+ telegramId: number | null,+ isTelegramChatIdConfirmed = false,+ ) {+ await this.usersRepository.update(userId, {+ telegramChatId: String(telegramId),+ isTelegramChatIdConfirmed,+ })+ }}