Создан компонет счетчика сайта
This commit is contained in:
parent
54b92c3015
commit
95c7b64d4c
11 changed files with 425 additions and 31 deletions
111
frontend/src/pages/api/visitors.ts
Normal file
111
frontend/src/pages/api/visitors.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import type { APIRoute } from 'astro';
|
||||
import crypto from 'crypto';
|
||||
|
||||
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090';
|
||||
|
||||
function getClientIp(request: Request): string {
|
||||
const forwarded = request.headers.get('x-forwarded-for');
|
||||
if (forwarded) {
|
||||
return forwarded.split(',')[0].trim();
|
||||
}
|
||||
const realIp = request.headers.get('x-real-ip');
|
||||
if (realIp) {
|
||||
return realIp;
|
||||
}
|
||||
const host = request.headers.get('host') || 'localhost';
|
||||
return host.includes('localhost') || host.includes('127.0.0.1') ? 'localhost' : 'unknown';
|
||||
}
|
||||
|
||||
function generateVisitorHash(ip: string, userAgent: string): string {
|
||||
return crypto.createHash('sha256').update(ip + userAgent).digest('hex').slice(0, 32);
|
||||
}
|
||||
|
||||
async function pbRequest(method: string, path: string, body?: object) {
|
||||
const url = `${POCKETBASE_URL}${path}`;
|
||||
const options: RequestInit = {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Origin': 'http://127.0.0.1:4321',
|
||||
},
|
||||
};
|
||||
if (body) options.body = JSON.stringify(body);
|
||||
|
||||
const res = await fetch(url, options);
|
||||
if (!res.ok) {
|
||||
const err = await res.text();
|
||||
throw new Error(`PB ${method} ${path}: ${res.status} - ${err}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
function jsonResponse(data: object, status = 200): Response {
|
||||
return new Response(JSON.stringify(data), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }
|
||||
});
|
||||
}
|
||||
|
||||
export const GET: APIRoute = async ({ request }) => {
|
||||
try {
|
||||
const ip = getClientIp(request);
|
||||
const userAgent = request.headers.get('user-agent') || 'unknown';
|
||||
const visitorHash = generateVisitorHash(ip, userAgent);
|
||||
|
||||
const now = new Date();
|
||||
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
const yesterdayStr = yesterday.toISOString().split('T')[0] + ' 00:00:00.000Z';
|
||||
|
||||
// Проверяем был ли посетитель за последние 24 часа
|
||||
const filterLast24h = `visitor_hash="${visitorHash}" && created >= "${yesterdayStr}"`;
|
||||
|
||||
let existingVisitor;
|
||||
try {
|
||||
const res = await pbRequest('GET', `/api/collections/site_visitors/records?filter=${encodeURIComponent(filterLast24h)}&perPage=1`);
|
||||
existingVisitor = { totalItems: res.totalItems || 0 };
|
||||
} catch {
|
||||
existingVisitor = { totalItems: 0 };
|
||||
}
|
||||
|
||||
let isNewVisitor = false;
|
||||
|
||||
// Создаём запись только если НЕ было посещения за последние 24ч
|
||||
if (existingVisitor.totalItems === 0) {
|
||||
isNewVisitor = true;
|
||||
try {
|
||||
await pbRequest('POST', '/api/collections/site_visitors/records', {
|
||||
visitor_hash: visitorHash,
|
||||
ip: ip,
|
||||
user_agent: userAgent,
|
||||
});
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
// Получаем статистику за сегодня
|
||||
const filterToday = `created >= "${yesterdayStr}"`;
|
||||
let todayCount = 0;
|
||||
let totalCount = 0;
|
||||
|
||||
try {
|
||||
const resToday = await pbRequest('GET', `/api/collections/site_visitors/records?filter=${encodeURIComponent(filterToday)}&perPage=1`);
|
||||
todayCount = resToday.totalItems || 0;
|
||||
} catch {
|
||||
todayCount = 0;
|
||||
}
|
||||
|
||||
try {
|
||||
const resTotal = await pbRequest('GET', '/api/collections/site_visitors/records?perPage=1');
|
||||
totalCount = resTotal.totalItems || 0;
|
||||
} catch {
|
||||
totalCount = 0;
|
||||
}
|
||||
|
||||
return jsonResponse({ todayVisitors: todayCount, totalVisitors: totalCount, isNewVisitor }, 200);
|
||||
|
||||
} catch (error) {
|
||||
console.error('[Visitors] Error:', error);
|
||||
return jsonResponse({ error: 'Внутренняя ошибка сервера' }, 500);
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue