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!

some improvements

Blue Mouse5990aa8fcb41
diff --git a/apps/production/src/common/utils.ts b/apps/production/src/common/utils.ts
index 12b622129..b958bd076 100644
--- a/apps/production/src/common/utils.ts
+++ b/apps/production/src/common/utils.ts
@@ -3,6 +3,8 @@ import { hash } from 'blake3'
import * as randomstring from 'randomstring'
import * as _sample from 'lodash/sample'
import * as _toNumber from 'lodash/toNumber'
+import * as _replace from 'lodash/replace'
+import * as _find from 'lodash/find'
import * as _round from 'lodash/round'
import { redis, isDevelopment } from './constants'
@@ -39,6 +41,21 @@ const getRandomTip = (language = 'en'): string => {
return _sample(marketingTips[language])
}
+const rx = /\.0+$|(\.[0-9]*[1-9])0+$/
+
+const formatterLookup = [
+ { value: 1, symbol: '' },
+ { value: 1e3, symbol: 'k' },
+ { value: 1e6, symbol: 'M' },
+ { value: 1e9, symbol: 'B' },
+]
+
+const nFormatter = (num: any, digits = 1) => {
+ const item = _find(formatterLookup.slice().reverse(), ({ value }) => Math.abs(num) >= value)
+
+ return item ? _replace((num / item.value).toFixed(digits), rx, '$1') + item.symbol : '0'
+}
+
// 'action' is used as a salt to differ rate limiting routes
const checkRateLimit = async (
ip: string,
@@ -115,4 +132,5 @@ export {
calculateRelativePercentage,
millisecondsToSeconds,
generateRandomString,
+ nFormatter,
}
diff --git a/apps/production/src/project/project.controller.ts b/apps/production/src/project/project.controller.ts
index 62486a2d2..f2445b1e8 100644
--- a/apps/production/src/project/project.controller.ts
+++ b/apps/production/src/project/project.controller.ts
@@ -1221,12 +1221,13 @@ export class ProjectController {
@HttpCode(200)
@Header('Content-Type', 'image/png')
// 1 day cache
- // @Header('Cache-Control', 'immutable, no-transform, s-max-age=86400, max-age=86400')
+ @Header('Cache-Control', 'immutable, no-transform, s-max-age=86400, max-age=86400')
@ApiResponse({ status: 200 })
async getOgImage(
@Param('id') id: string,
@Res() res: Response,
): Promise<any> {
+ // TODO: Cache the generated image in the filesystem (or CDN) for 1 day and return it instead of generating it again
this.logger.log({ id }, 'GET /project/ogimage/:id')
if (!isValidPID(id)) {
@@ -1238,27 +1239,22 @@ export class ProjectController {
const project = await this.projectService.findOne(id)
if (_isEmpty(project)) {
- throw new NotFoundException()
+ // TODO: Return default image
+ throw new NotFoundException('Project not found.')
}
- console.log(project)
-
- // if (!project.public) {
- // throw new ForbiddenException()
- // }
+ if (!project.public) {
+ // TODO: Return default image
+ throw new ForbiddenException()
+ }
- // project.name
- const image = await this.projectService.getOgImage('My Awesome Project')
+ const image = await this.projectService.getOgImage(project.id, project.name)
res.end(image)
- // return image
}
@Get('/ogimage/:id/html')
@HttpCode(200)
- // @Header('Content-Type', 'image/png')
- // 1 day cache
- // @Header('Cache-Control', 'immutable, no-transform, s-max-age=86400, max-age=86400')
@ApiResponse({ status: 200 })
async getOgHTML(
@Param('id') id: string,
@@ -1266,6 +1262,10 @@ export class ProjectController {
): Promise<any> {
this.logger.log({ id }, 'GET /project/ogimage/:id')
+ if (!isDevelopment) {
+ throw new ForbiddenException('This route is only available in dev mode')
+ }
+
if (!isValidPID(id)) {
throw new BadRequestException(
'The provided Project ID (pid) is incorrect',
@@ -1275,11 +1275,9 @@ export class ProjectController {
const project = await this.projectService.findOne(id)
if (_isEmpty(project)) {
- throw new NotFoundException()
+ throw new NotFoundException('Project not found')
}
- console.log(project)
-
const html = this.projectService.getOgHTML('My Awesome Project')
res.send(html)
diff --git a/apps/production/src/project/project.service.ts b/apps/production/src/project/project.service.ts
index d8bb080c2..b38ab6b4b 100644
--- a/apps/production/src/project/project.service.ts
+++ b/apps/production/src/project/project.service.ts
@@ -55,6 +55,7 @@ import { ProjectSubscriber } from './entity'
import { AddSubscriberType } from './types'
import { GetSubscribersQueriesDto, UpdateSubscriberBodyDto } from './dto'
import { ReportFrequency } from './enums'
+import { nFormatter } from '../common/utils'
dayjs.extend(utc)
@@ -249,11 +250,9 @@ const getCompiledStyles = (name: string): string => {
})
}
-const getCompiledHTML = (name: string, compiledStyles: string) => {
+const getCompiledHTML = (title: string, desc: string, styles: string) => {
return handlebars.compile(previewHTML)({
- title: name,
- desc: '8k visitors in the last month',
- styles: compiledStyles,
+ title, desc, styles,
})
}
@@ -925,15 +924,32 @@ export class ProjectService {
})
}
- getOgHTML(name: string) {
+ getOgHTML(name: string, desc = '8k visitors in the last month') {
const styles = getCompiledStyles(name)
- const html = getCompiledHTML(name, styles)
+ const html = getCompiledHTML(name, desc, styles)
return html
}
- async getOgImage(name: string) {
- const html = this.getOgHTML(name)
+ async getOgImage(pid: string, name: string) {
+ const from = dayjs
+ .utc()
+ .subtract(1, 'month')
+ .startOf('month')
+ .format('YYYY-MM-DD 00:00:00')
+ const to = dayjs
+ .utc()
+ .subtract(1, 'month')
+ .endOf('month')
+ .format('YYYY-MM-DD 23:59:59')
+
+ const formatted = nFormatter(
+ await this.countVisitorsFromTo(pid, from, to),
+ 0,
+ )
+ const desc = `${formatted} visitors in the last month`
+
+ const html = this.getOgHTML(name, desc)
const browser = await puppeteer.launch({
headless: 'new',
@@ -976,4 +992,23 @@ export class ProjectService {
return image
}
+
+ async countVisitorsFromTo(
+ pid: string,
+ from: string,
+ to: string,
+ ): Promise<number> {
+ const query = 'SELECT count() FROM analytics WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String} AND unique=\'1\''
+ const params = { pid, from, to }
+ let count = 0
+
+ try {
+ const result = await clickhouse.query(query, { params }).toPromise()
+ count = result[0]['count()']
+ } catch (reason) {
+ console.error('[ERROR](project service -> countVisitorsFromTo) Error while counting visitors', reason)
+ }
+
+ return count
+ }
}