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 support for custom events

Blue Mouse2e8da1b6788d
diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.ts
index dd0212a22..13577877b 100644
--- a/src/analytics/analytics.controller.ts
+++ b/src/analytics/analytics.controller.ts
@@ -3,6 +3,7 @@ import * as _isNumber from 'lodash/isNumber'
import * as _isArray from 'lodash/isArray'
import * as _size from 'lodash/size'
import * as _last from 'lodash/last'
+import * as _countBy from 'lodash/countBy'
import * as dayjs from 'dayjs'
import * as utc from 'dayjs/plugin/utc'
import { v4 as uuidv4 } from 'uuid'
@@ -20,10 +21,11 @@ import { UserType } from '../user/entities/user.entity'
import { Roles } from '../common/decorators/roles.decorator'
import { RolesGuard } from 'src/common/guards/roles.guard'
import { PageviewsDTO } from './dto/pageviews.dto'
+import { EventsDTO } from './dto/events.dto'
import { AnalyticsGET_DTO } from './dto/getData.dto'
import { AppLoggerService } from '../logger/logger.service'
import {
- clickhouse, isValidPID, REDIS_LOG_DATA_CACHE_KEY, redis,
+ clickhouse, isValidPID, REDIS_LOG_DATA_CACHE_KEY, redis, REDIS_LOG_CUSTOM_CACHE_KEY,
} from '../common/constants'
import ct from '../common/countriesTimezones'
@@ -33,9 +35,15 @@ dayjs.extend(utc)
// store them in redis storage and reset every 24 hours
const getSessionKey = (ip: string, ua: string, pid: string, salt: string = '') => hash(`${ua}${ip}${pid}${salt}`).toString('hex')
-const analyticsDTO = (pid: string, ev: string, pg: string, dv: string, br: string, os: string, lc: string, ref: string, so: string, me: string, ca: string, lt: number | string, tz: string, unique: number): Array<string | number> => {
+const getSessionKeyCustom = (ip: string, ua: string, pid: string, ev: string, salt: string = '') => hash(`${ua}${ip}${pid}${ev}${salt}`).toString('hex')
+
+const analyticsDTO = (pid: string, pg: string, dv: string, br: string, os: string, lc: string, ref: string, so: string, me: string, ca: string, lt: number | string, tz: string, unique: number): Array<string | number> => {
const cc = tz === 'NULL' ? 'NULL' : ct.getCountryForTimezone(tz)?.id
- return [uuidv4(), pid, ev, pg, dv, br, os, lc, ref, so, me, ca, lt, cc, unique, dayjs.utc().format('YYYY-MM-DD HH:mm:ss')]
+ return [uuidv4(), pid, pg, dv, br, os, lc, ref, so, me, ca, lt, cc, unique, dayjs.utc().format('YYYY-MM-DD HH:mm:ss')]
+}
+
+const customLogDTO = (pid: string, ev: string): Array<string> => {
+ return [uuidv4(), pid, ev, dayjs.utc().format('YYYY-MM-DD HH:mm:ss')]
}
const getElValue = (el) => {
@@ -67,6 +75,7 @@ export class AnalyticsController {
// TODO: automatic timeBucket detection based on period provided
let query = `SELECT * FROM analytics WHERE pid='${pid}'`
+ let queryCustoms = `SELECT ev FROM customEV WHERE pid='${pid}'`
if (!_isEmpty(from) && !_isEmpty(to)) {
throw new NotImplementedException('Filtering by from/to params is currently not available')
@@ -77,20 +86,29 @@ export class AnalyticsController {
if (dayjs.utc(to).isAfter(dayjs.utc(), 'second')) {
groupTo = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
query += `AND created BETWEEN ${from} AND ${groupTo}`
+ queryCustoms += `AND created BETWEEN ${from} AND ${groupTo}`
} else {
query += `AND created BETWEEN ${from} AND ${to}`
+ queryCustoms += `AND created BETWEEN ${from} AND ${to}`
}
} else if (!_isEmpty(period)) {
groupFrom = dayjs.utc().subtract(parseInt(period), _last(period)).format('YYYY-MM-DD HH:mm:ss')
groupTo = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
query += `AND created BETWEEN '${groupFrom}' AND '${groupTo}'`
+ queryCustoms += `AND created BETWEEN '${groupFrom}' AND '${groupTo}'`
} else {
throw new BadRequestException('The timeframe (either from/to pair or period) to be provided')
}
const response = await clickhouse.query(query).toPromise()
const result = await this.analyticsService.groupByTimeBucket(response, timeBucket, groupFrom, groupTo)
- return result
+
+ const customs = await clickhouse.query(queryCustoms).toPromise()
+
+ return {
+ ...result,
+ customs: _countBy(customs, 'ev'),
+ }
}
@Get('/birdseye')
@@ -122,6 +140,39 @@ export class AnalyticsController {
return this.analyticsService.getSummary(pids, 'w', true)
}
+ // Log custom event
+ @Post('/custom')
+ async logCustom(@Body() eventsDTO: EventsDTO, @Headers() headers): Promise<any> {
+ this.logger.log({ eventsDTO, headers }, 'POST /log/custom')
+
+ const { 'user-agent': userAgent, origin } = headers
+ await this.analyticsService.validate(eventsDTO, origin)
+
+ const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || ''
+
+ if (eventsDTO.unique) {
+ const sessionHash = getSessionKeyCustom(ip, userAgent, eventsDTO.pid, eventsDTO.ev)
+ const unique = await this.analyticsService.isUnique(sessionHash)
+
+ if (!unique) {
+ return
+ }
+ }
+
+ const dto = customLogDTO(eventsDTO.pid, eventsDTO.ev)
+
+ // todo: fix: may be vulnerable to sql injection attack
+ const values = `(${dto.map(getElValue).join(',')})`
+ try {
+ await redis.rpush(REDIS_LOG_CUSTOM_CACHE_KEY, values)
+ return
+ } catch (e) {
+ this.logger.error(e)
+ throw new InternalServerErrorException('Error occured while saving the custom event')
+ }
+ }
+
+ // Log pageview event
@Post('/')
async log(@Body() logDTO: PageviewsDTO, @Headers() headers): Promise<any> {
this.logger.log({ logDTO, headers }, 'POST /log')
@@ -142,9 +193,9 @@ export class AnalyticsController {
const dv = ua.device.type || 'desktop'
const br = ua.browser.name
const os = ua.os.name
- dto = analyticsDTO(logDTO.pid, logDTO.ev, logDTO.pg, dv, br, os, logDTO.lc, logDTO.ref, logDTO.so, logDTO.me, logDTO.ca, logDTO.lt, logDTO.tz, 1)
+ dto = analyticsDTO(logDTO.pid, logDTO.pg, dv, br, os, logDTO.lc, logDTO.ref, logDTO.so, logDTO.me, logDTO.ca, logDTO.lt, logDTO.tz, 1)
} else {
- dto = analyticsDTO(logDTO.pid, logDTO.ev, 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 0)
+ dto = analyticsDTO(logDTO.pid, 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 0)
}
// todo: fix: may be vulnerable to sql injection attack
diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.ts
index fd565967d..ee84ade72 100644
--- a/src/analytics/analytics.service.ts
+++ b/src/analytics/analytics.service.ts
@@ -21,7 +21,9 @@ import {
} from '../common/constants'
import { Analytics } from './entities/analytics.entity'
import { PageviewsDTO } from './dto/pageviews.dto'
+import { EventsDTO } from './dto/events.dto'
import { ProjectService } from '../project/project.service'
+import { Project } from '../project/entity/project.entity'
import { TimeBucketType } from './dto/getData.dto'
dayjs.extend(utc)
@@ -62,13 +64,7 @@ export class AnalyticsService {
return this.analyticsRepository.find({ where })
}
- async validate(logDTO: PageviewsDTO, origin: string): Promise<string | null> {
- if (_isEmpty(logDTO)) throw new BadRequestException('The request cannot be empty')
- const { pid } = logDTO
-
- if (_isEmpty(pid)) throw new BadRequestException('The Project ID (pid) has to be provided')
- if (!isValidPID(pid)) throw new BadRequestException('The provided Project ID (pid) is incorrect')
-
+ async getRedisProject(pid: string): Promise<Project | null> {
const pidKey = getRedisProjectKey(pid)
let project = await redis.get(pidKey)
if (_isEmpty(project)) {
@@ -83,8 +79,11 @@ export class AnalyticsService {
}
}
- if (!project.active) throw new BadRequestException('Incoming analytics is disabled for this project')
+ return project
+ }
+ // Returns amount of existing events starting from month
+ async getRedisCount(pid: string): Promise<number | null> {
const countKey = getRedisProjectCountKey(pid)
let count = await redis.get(countKey)
if (_isEmpty(count)) {
@@ -95,7 +94,7 @@ export class AnalyticsService {
const pageviews = result[0]['count()']
count = pageviews
-
+
await redis.set(countKey, `${pageviews}`, 'EX', redisProjectCountCacheTimeout)
} else {
try {
@@ -105,13 +104,11 @@ export class AnalyticsService {
throw new InternalServerErrorException('Error while processing project')
}
}
+
+ return count
+ }
- const maxCount = ACCOUNT_PLANS[project.admin.planCode].monthlyUsageLimit || 0
-
- if (count >= maxCount) {
- throw new ForbiddenException('You have exceeded the available monthly request limit for your account. Please upgrade your account plan if you need more requests.')
- }
-
+ checkOrigin(project: Project, origin: string): void {
if (!_isEmpty(project.origins) && !_isEmpty(origin)) {
if (origin === 'null') {
if (!_includes(project.origins, 'null')) {
@@ -124,6 +121,32 @@ export class AnalyticsService {
}
}
}
+ }
+
+ // TODO: Remove unnecessary checks (because some of them are already checked in the DTO)
+ async validate(logDTO: PageviewsDTO | EventsDTO, origin: string): Promise<string | null> {
+ if (_isEmpty(logDTO)) throw new BadRequestException('The request cannot be empty')
+ const { pid } = logDTO
+
+ if (_isEmpty(pid)) throw new BadRequestException('The Project ID (pid) has to be provided')
+ if (!isValidPID(pid)) throw new BadRequestException('The provided Project ID (pid) is incorrect')
+
+ if (logDTO instanceof EventsDTO && !_isEmpty(logDTO.ev) && _size(logDTO.ev) > 64) {
+ throw new BadRequestException('An incorrect event name (ev) is provided')
+ }
+
+ const project = await this.getRedisProject(pid)
+
+ if (!project.active) throw new BadRequestException('Incoming analytics is disabled for this project')
+
+ const count = await this.getRedisCount(pid)
+ const maxCount = ACCOUNT_PLANS[project.admin.planCode].monthlyUsageLimit || 0
+
+ if (count >= maxCount) {
+ throw new ForbiddenException('You have exceeded the available monthly request limit for your account. Please upgrade your account plan if you need more requests.')
+ }
+
+ this.checkOrigin(project, origin)
return null
}
diff --git a/src/analytics/dto/events.dto.ts b/src/analytics/dto/events.dto.ts
index 2791878af..026443cb3 100644
--- a/src/analytics/dto/events.dto.ts
+++ b/src/analytics/dto/events.dto.ts
@@ -5,24 +5,21 @@ export class EventsDTO {
@ApiProperty({
example: 'aUn1quEid-3',
required: true,
- description: 'The project ID'
+ description: 'The project ID',
})
@IsNotEmpty()
pid: string
@ApiProperty({
example: 'user-subscribed',
- description: 'Event type'
+ description: 'Event name',
+ maxLength: 64,
})
+ @IsNotEmpty()
ev: string
- // Tracking metrics
@ApiProperty({
- example: {
- ref: 'duckduckgo',
- plan: 'gold+',
- },
- description: 'Custom parameters related to the event'
+ description: 'If true, only 1 event with the same ID will be saved per user session',
})
- params: object
-}
\ No newline at end of file
+ unique: object
+}
diff --git a/src/analytics/dto/pageviews.dto.ts b/src/analytics/dto/pageviews.dto.ts
index 23f10c2a3..637f846dd 100644
--- a/src/analytics/dto/pageviews.dto.ts
+++ b/src/analytics/dto/pageviews.dto.ts
@@ -10,12 +10,6 @@ export class PageviewsDTO {
@IsNotEmpty()
pid: string
- @ApiProperty({
- example: 'pageviews',
- description: 'Event type'
- })
- ev: string
-
// Tracking metrics
@ApiProperty({
example: 'Europe/Kiev',
diff --git a/src/analytics/entities/analytics.entity.ts b/src/analytics/entities/analytics.entity.ts
index 45882a0a5..0e0c9116c 100644
--- a/src/analytics/entities/analytics.entity.ts
+++ b/src/analytics/entities/analytics.entity.ts
@@ -3,10 +3,6 @@ import { ApiProperty } from '@nestjs/swagger'
import { Project } from '../../project/entity/project.entity'
-enum EventType {
- PAGEVIEWS = 'pageviews',
-}
-
@Entity()
export class Analytics {
@PrimaryGeneratedColumn('uuid')
@@ -19,13 +15,6 @@ export class Analytics {
// @ManyToOne(() => Project, proj => proj.id)
// pid: Project
- @Column({
- type: 'enum',
- enum: EventType,
- default: EventType.PAGEVIEWS,
- })
- ev: string
-
@Column('varchar', {
length: 64,
nullable: true,
diff --git a/src/common/constants.ts b/src/common/constants.ts
index 530a35221..3e188daa0 100644
--- a/src/common/constants.ts
+++ b/src/common/constants.ts
@@ -62,6 +62,8 @@ const getRedisProjectCountKey = (pid: string) => `pid_c_${pid}`
const REDIS_LOG_DATA_CACHE_KEY = 'log_cache'
+const REDIS_LOG_CUSTOM_CACHE_KEY = 'log_custom_cache'
+
// 3600 sec -> 1 hour
const redisProjectCacheTimeout = 3600
@@ -77,5 +79,5 @@ const GDPR_EXPORT_TIMEFRAME = 14
export {
clickhouse, JWT_LIFE_TIME, HISTORY_LIFE_TIME_DAYS, redis, isValidPID, getRedisProjectKey,
redisProjectCacheTimeout, getPercentageChange, UNIQUE_SESSION_LIFE_TIME, REDIS_LOG_DATA_CACHE_KEY,
- GDPR_EXPORT_TIMEFRAME, getRedisProjectCountKey, redisProjectCountCacheTimeout,
+ GDPR_EXPORT_TIMEFRAME, getRedisProjectCountKey, redisProjectCountCacheTimeout, REDIS_LOG_CUSTOM_CACHE_KEY,
}
diff --git a/src/task-manager/task-manager.service.ts b/src/task-manager/task-manager.service.ts
index 0fd8d67e3..5294ebaa6 100644
--- a/src/task-manager/task-manager.service.ts
+++ b/src/task-manager/task-manager.service.ts
@@ -14,7 +14,9 @@ import { UserService } from '../user/user.service'
import { LetterTemplate } from '../mailer/letter'
import { AnalyticsService } from '../analytics/analytics.service'
import { ReportFrequency } from '../user/entities/user.entity'
-import { clickhouse, REDIS_LOG_DATA_CACHE_KEY, redis } from '../common/constants'
+import {
+ clickhouse, redis, REDIS_LOG_DATA_CACHE_KEY, REDIS_LOG_CUSTOM_CACHE_KEY,
+} from '../common/constants'
dayjs.extend(utc)
@@ -28,13 +30,28 @@ export class TaskManagerService {
) {}
@Cron(CronExpression.EVERY_MINUTE)
- async someTask(): Promise<void> {
+ async saveLogData(): Promise<void> {
const data = await redis.lrange(REDIS_LOG_DATA_CACHE_KEY, 0, -1)
+ const customData = await redis.lrange(REDIS_LOG_CUSTOM_CACHE_KEY, 0, -1)
if (!_isEmpty(data)) {
await redis.del(REDIS_LOG_DATA_CACHE_KEY)
const query = `INSERT INTO analytics (*) VALUES ${_join(data, ',')}`
- await clickhouse.query(query).toPromise()
+ try {
+ await clickhouse.query(query).toPromise()
+ } catch (e) {
+ console.error(`[CRON WORKER] Error whilst saving log data: ${e}`)
+ }
+ }
+
+ if (!_isEmpty(customData)) {
+ await redis.del(REDIS_LOG_CUSTOM_CACHE_KEY)
+ const query = `INSERT INTO customEV (*) VALUES ${_join(customData, ',')}`
+ try {
+ await clickhouse.query(query).toPromise()
+ } catch (e) {
+ console.error(`[CRON WORKER] Error whilst saving log data: ${e}`)
+ }
}
}