Skip to content

Commit

Permalink
feat(访问数据): 增加 设备分析
Browse files Browse the repository at this point in the history
  • Loading branch information
xjq committed Oct 31, 2022
1 parent f1fea08 commit ba34be4
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 10 deletions.
3 changes: 2 additions & 1 deletion client/src/pages/stats/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ function Component() {
const fetchStat = async () => {
const { list } = await getStat();

const uv = uniqBy(list, (x) => x.ip).length;
const uniqList = uniqBy(list, (x) => x.ip);
const uv = uniqList.length;

const pv = list.length;
setStats({ uv, pv });
Expand Down
1 change: 1 addition & 0 deletions server/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@ module.exports = {
'@typescript-eslint/no-floating-promises': 0,
'@typescript-eslint/restrict-template-expressions': 0,
'@typescript-eslint/prefer-ts-expect-error': 0,
'@typescript-eslint/no-var-requires': 0,
},
};
8 changes: 5 additions & 3 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
"@koa/cors": "^4.0.0",
"@koa/multer": "^3.0.0",
"@prisma/client": "^4.5.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",
"dayjs": "^1.11.6",
"dockerode": "^3.3.4",
"dotenv": "^16.0.3",
Expand All @@ -32,8 +34,7 @@
"reflect-metadata": "^0.1.13",
"routing-controllers": "^0.9.0",
"ts-node": "^10.9.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2"
"ua-parser-js": "^1.0.32"
},
"devDependencies": {
"@types/dockerode": "^3.3.10",
Expand All @@ -54,6 +55,7 @@
"pm2": "^5.2.2",
"prettier": "^2.7.1",
"typescript": "*",
"zx": "^7.1.1"
"zx": "^7.1.1",
"@types/ua-parser-js": "^0.7.36"
}
}
12 changes: 12 additions & 0 deletions server/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion server/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ datasource db {
model stat {
id Int @id @default(autoincrement())
ip String
device String? @default("")
country String? @default("")
province String? @default("")
city String? @default("")
isp String? @default("")
userAgent String? @default("")
createdAt DateTime @default(now())
}
34 changes: 29 additions & 5 deletions server/src/controller/stat.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Get, JsonController, Post } from 'routing-controllers';
import { Get, HeaderParam, JsonController, Post } from 'routing-controllers';
import { redisStore } from '../config/redis';
import { Ip } from '../middleware/decorator/Ip';
import prisma from '../config/prisma';
import IP2Region from 'ip2region';
import dayjs from 'dayjs';
import logger from '../logger';
import uaparser from 'ua-parser-js';

const IP_PREFIX = 'ip_';

Expand All @@ -19,14 +21,30 @@ export class StatController {
dayjs().format('YYYY-MM-DD') + ' 23:59:59'
).toISOString();

const result = await prisma.stat.findMany({
let list = await prisma.stat.findMany({
where: { createdAt: { lte: endTime, gte: startTime } },
orderBy: [
{
createdAt: 'desc',
},
],
});
console.time();
list = list.map((o) => {
if (!o.userAgent) return o;
const ua = uaparser(o.userAgent);
const browser = ua?.browser?.name ?? '未知';
const os = ua?.os?.name ?? '未知';
const device = ua?.device?.model ?? '未知';
const engine = ua?.engine?.name ?? '未知';
return { ...o, browser, os, device, engine };
});
console.timeEnd();

return {
code: 0,
data: {
list: result,
list,
},
};
} catch (error) {
Expand All @@ -40,7 +58,7 @@ export class StatController {
}

@Post('/visit')
async visit(@Ip() ip: string) {
async visit(@Ip() ip: string, @HeaderParam('User-Agent') userAgent: string) {
if (!ip) {
return {
code: 0,
Expand All @@ -49,6 +67,8 @@ export class StatController {
try {
const ipCache = await redisStore.get(IP_PREFIX + ip);

logger.info(`ip: ${ip}, 存在缓存,跳过 visit`);

if (ipCache !== null) {
return {
code: 0,
Expand All @@ -60,7 +80,7 @@ export class StatController {
const { country, city, province, isp } = region ?? {};

await redisStore.set(IP_PREFIX + ip, '1');
await redisStore.expire(IP_PREFIX + ip, 600);
await redisStore.expire(IP_PREFIX + ip, 60);

await prisma.stat.create({
data: {
Expand All @@ -69,15 +89,19 @@ export class StatController {
city,
province,
isp,
userAgent,
},
});
} catch (error) {
logger.info(`visit error, ${JSON.stringify(error)}`);
return {
code: 0,
message: JSON.stringify(error),
};
}

logger.info(`ip: ${ip}, visit`);

return {
code: 0,
message: 'success!',
Expand Down

0 comments on commit ba34be4

Please sign in to comment.