opt: упростить счетчики - одна запись в БД вместо тысяч
- site_stats: 1 запись с полями today/total вместо site_visitors - posts: today_views + last_reset вместо post_views коллекции - Удалены старые коллекции site_visitors и post_views
This commit is contained in:
parent
62a6453a1a
commit
e7700a3391
6 changed files with 65 additions and 622 deletions
|
|
@ -28,20 +28,10 @@ const { today = 0, total = 0 } = Astro.props;
|
|||
const valueEls = root.querySelectorAll('.counter-value');
|
||||
if (valueEls.length < 2) return;
|
||||
|
||||
const todayStr = new Date().toDateString();
|
||||
const lastVisit = localStorage.getItem('site_visited');
|
||||
|
||||
// Если уже посещали сегодня - помечаем как повторный визит
|
||||
const isRepeat = lastVisit === todayStr;
|
||||
const apiUrl = isRepeat ? '/api/visitors?repeat=true' : '/api/visitors';
|
||||
|
||||
fetch(apiUrl).then(r => r.json()).then(d => {
|
||||
if (typeof d.todayVisitors === 'number') {
|
||||
if (d.isNewVisitor) {
|
||||
localStorage.setItem('site_visited', todayStr);
|
||||
}
|
||||
if (valueEls[0]) valueEls[0].textContent = d.todayVisitors + ' сегодня';
|
||||
if (valueEls[1]) valueEls[1].textContent = d.totalVisitors + ' всего';
|
||||
fetch('/api/visitors').then(r => r.json()).then(d => {
|
||||
if (typeof d.today === 'number') {
|
||||
if (valueEls[0]) valueEls[0].textContent = d.today + ' сегодня';
|
||||
if (valueEls[1]) valueEls[1].textContent = d.total + ' всего';
|
||||
}
|
||||
}).catch(() => {});
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -320,22 +320,17 @@ const {
|
|||
|
||||
// 5. СЧЁТЧИК ПРОСМОТРОВ
|
||||
const viewsEl = document.querySelector('.meta-views') as HTMLElement & { dataset: { postId: string } };
|
||||
console.log('[Views] Element found:', viewsEl, 'postId:', viewsEl?.dataset?.postId);
|
||||
if (viewsEl?.dataset?.postId) {
|
||||
const postId = viewsEl.dataset.postId;
|
||||
console.log('[Views] Fetching for post:', postId);
|
||||
|
||||
fetch(`/api/increment-views?postId=${postId}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
console.log('[Views] Response:', data);
|
||||
if (data.views !== undefined) {
|
||||
viewsEl.textContent = formatViews(data.views);
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('[Views] Error:', err);
|
||||
});
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
function formatViews(n: number): string {
|
||||
|
|
|
|||
|
|
@ -1,44 +1,8 @@
|
|||
import type { APIRoute } from 'astro';
|
||||
import crypto from 'crypto';
|
||||
|
||||
const PB_POCKETBASE_URL = import.meta.env.PB_POCKETBASE_URL || 'http://127.0.0.1:8090';
|
||||
|
||||
const POCKETBASE_ID_REGEX = /^[a-z0-9]{15}$/;
|
||||
|
||||
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;
|
||||
}
|
||||
// Для localhost использовать заголовок Host или default
|
||||
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 = `${PB_POCKETBASE_URL}${path}`;
|
||||
const options: RequestInit = {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
};
|
||||
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,
|
||||
|
|
@ -46,7 +10,7 @@ function jsonResponse(data: object, status = 200): Response {
|
|||
});
|
||||
}
|
||||
|
||||
export const GET: APIRoute = async ({ request, url }) => {
|
||||
export const GET: APIRoute = async ({ url }) => {
|
||||
try {
|
||||
const postId = url.searchParams.get('postId');
|
||||
|
||||
|
|
@ -54,59 +18,43 @@ export const GET: APIRoute = async ({ request, url }) => {
|
|||
return jsonResponse({ error: 'Некорректный postId' }, 400);
|
||||
}
|
||||
|
||||
// Получаем пост
|
||||
let post;
|
||||
try {
|
||||
post = await pbRequest('GET', `/api/collections/posts/records/${postId}`);
|
||||
post = await fetch(`${PB_POCKETBASE_URL}/api/collections/posts/records/${postId}`, {
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}).then(r => r.json());
|
||||
} catch {
|
||||
return jsonResponse({ error: 'Пост не найден' }, 404);
|
||||
}
|
||||
|
||||
const ip = getClientIp(request);
|
||||
const userAgent = request.headers.get('user-agent') || 'unknown';
|
||||
const visitorHash = generateVisitorHash(ip, userAgent);
|
||||
if (!post || !post.id) {
|
||||
return jsonResponse({ error: 'Пост не найден' }, 404);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
const yesterdayStr = yesterday.toISOString();
|
||||
const todayStr = now.toISOString().split('T')[0];
|
||||
|
||||
let existingViews;
|
||||
try {
|
||||
const res = await pbRequest('GET', `/api/collections/post_views/records?filter=(post="${postId}")&&(visitor_hash="${visitorHash}")&&(created>="${yesterdayStr}")&perPage=1`);
|
||||
existingViews = { totalItems: res.totalItems || 0 };
|
||||
} catch {
|
||||
existingViews = { totalItems: 0 };
|
||||
let { views = 0, today_views = 0, last_reset = '' } = post;
|
||||
|
||||
// Если новый день - сбрасываем today_views
|
||||
if (last_reset !== todayStr) {
|
||||
today_views = 0;
|
||||
last_reset = todayStr;
|
||||
}
|
||||
|
||||
let isNewView = false;
|
||||
// Инкремент
|
||||
views++;
|
||||
today_views++;
|
||||
|
||||
if (existingViews.totalItems === 0) {
|
||||
isNewView = true;
|
||||
// Обновляем пост
|
||||
await fetch(`${PB_POCKETBASE_URL}/api/collections/posts/records/${postId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ views, today_views, last_reset })
|
||||
});
|
||||
|
||||
try {
|
||||
await pbRequest('POST', '/api/collections/post_views/records', {
|
||||
post: postId,
|
||||
visitor_hash: visitorHash,
|
||||
ip: ip,
|
||||
user_agent: userAgent,
|
||||
});
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
let totalViews = post.views || 0;
|
||||
|
||||
if (isNewView) {
|
||||
totalViews += 1;
|
||||
|
||||
try {
|
||||
await pbRequest('PATCH', `/api/collections/posts/records/${postId}`, { views: totalViews });
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
return jsonResponse({ views: totalViews, isNewView }, 200);
|
||||
return jsonResponse({ views, today_views }, 200);
|
||||
|
||||
} catch (error) {
|
||||
console.error('[Increment Views] Error:', error);
|
||||
|
|
|
|||
|
|
@ -1,49 +1,7 @@
|
|||
import type { APIRoute } from 'astro';
|
||||
import crypto from 'crypto';
|
||||
|
||||
const PB_POCKETBASE_URL = import.meta.env.PB_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 {
|
||||
// Упрощаем - используем только IP (без порта) для стабильности
|
||||
const stableIP = ip.split(':').pop() || ip;
|
||||
// Используем только первые 2 слова из userAgent (браузер + платформа)
|
||||
const uaParts = userAgent.split(' ');
|
||||
const stableUA = uaParts.slice(0, 2).join(' ');
|
||||
return crypto.createHash('sha256').update(stableIP + stableUA).digest('hex').slice(0, 32);
|
||||
}
|
||||
|
||||
async function pbRequest(method: string, path: string, body?: object) {
|
||||
const url = `${PB_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,
|
||||
|
|
@ -53,73 +11,54 @@ function jsonResponse(data: object, status = 200): Response {
|
|||
|
||||
export const GET: APIRoute = async ({ request }) => {
|
||||
try {
|
||||
const url = new URL(request.url);
|
||||
const isRepeatVisit = url.searchParams.get('repeat') === 'true';
|
||||
|
||||
const ip = getClientIp(request);
|
||||
const userAgent = request.headers.get('user-agent') || 'unknown';
|
||||
const visitorHash = generateVisitorHash(ip, userAgent);
|
||||
|
||||
const now = new Date();
|
||||
// Начало текущего дня по UTC (00:00 UTC)
|
||||
const todayStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), 0, 0, 0, 0));
|
||||
// PocketBase использует формат YYYY-MM-DD HH:MM:SS
|
||||
const todayStartStr = todayStart.toISOString().replace('T', ' ').replace('Z', '');
|
||||
const todayStr = now.toISOString().split('T')[0];
|
||||
|
||||
// Проверяем был ли посетитель сегодня (с 00:00 UTC)
|
||||
const filterTodayVisitor = `visitor_hash="${visitorHash}" && created >= "${todayStartStr}"`;
|
||||
// Получаем текущую запись stats
|
||||
const res = await fetch(`${PB_POCKETBASE_URL}/api/collections/site_stats/records?perPage=1`, {
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
|
||||
let existingVisitor;
|
||||
try {
|
||||
const res = await pbRequest('GET', `/api/collections/site_visitors/records?filter=${encodeURIComponent(filterTodayVisitor)}&perPage=1`);
|
||||
existingVisitor = { totalItems: res.totalItems || 0 };
|
||||
} catch {
|
||||
existingVisitor = { totalItems: 0 };
|
||||
if (!res.ok) {
|
||||
return jsonResponse({ today: 0, total: 0 }, 200);
|
||||
}
|
||||
|
||||
let isNewVisitor = false;
|
||||
const data = await res.json();
|
||||
const stats = data.items?.[0];
|
||||
|
||||
// Если это повторный визит по данным клиента - не создаём запись
|
||||
if (isRepeatVisit) {
|
||||
isNewVisitor = false;
|
||||
}
|
||||
// Создаём запись только если НЕ было посещения сегодня
|
||||
else 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
|
||||
}
|
||||
if (!stats) {
|
||||
// Нет записи - создаём первую
|
||||
await fetch(`${PB_POCKETBASE_URL}/api/collections/site_stats/records`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ today: 1, total: 1, last_reset: todayStr })
|
||||
});
|
||||
return jsonResponse({ today: 1, total: 1 }, 200);
|
||||
}
|
||||
|
||||
// Получаем статистику за сегодня (с 00:00 UTC)
|
||||
const filterToday = `created >= "${todayStartStr}"`;
|
||||
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;
|
||||
let { today = 0, total = 0, last_reset = '' } = stats;
|
||||
|
||||
// Если новый день - сбрасываем today
|
||||
if (last_reset !== todayStr) {
|
||||
today = 0;
|
||||
last_reset = todayStr;
|
||||
}
|
||||
|
||||
try {
|
||||
const resTotal = await pbRequest('GET', '/api/collections/site_visitors/records?perPage=1');
|
||||
totalCount = resTotal.totalItems || 0;
|
||||
} catch {
|
||||
totalCount = 0;
|
||||
}
|
||||
// Инкремент
|
||||
today++;
|
||||
total++;
|
||||
|
||||
return jsonResponse({ todayVisitors: todayCount, totalVisitors: totalCount, isNewVisitor }, 200);
|
||||
// Обновляем в БД
|
||||
await fetch(`${PB_POCKETBASE_URL}/api/collections/site_stats/records/${stats.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ today, total, last_reset })
|
||||
});
|
||||
|
||||
return jsonResponse({ today, total }, 200);
|
||||
|
||||
} catch (error) {
|
||||
console.error('[Visitors] Error:', error);
|
||||
return jsonResponse({ error: 'Внутренняя ошибка сервера' }, 500);
|
||||
return jsonResponse({ today: 0, total: 0 }, 200);
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue