Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

feat: Implement database data retention management and add favicon provider selection.

luolei52e3244e3dec
diff --git a/README.md b/README.md
index 9d6e8cc..c17f8af 100644
--- a/README.md
+++ b/README.md
@@ -85,7 +85,7 @@ services:
docker compose up -d
```
-访问 http://localhost:3000
+访问 <http://localhost:3000>
### 方式三:使用 .env 配置文件
@@ -121,7 +121,7 @@ docker run -d \
![首次使用](./assets/clash-master-setup.png)
-1. 打开 http://localhost:3000
+1. 打开 <http://localhost:3000>
2. 首次访问会弹出**后端配置**对话框
3. 填写 OpenClash 连接信息:
- **名称**: 自定义名称(如 "Home")
@@ -168,7 +168,7 @@ docker compose down
docker compose up -d
```
-现在访问 http://localhost:8080
+现在访问 <http://localhost:8080>
### 方案 3:直接修改 docker-compose.yml
@@ -289,7 +289,7 @@ clash-master/
## 🛠️ 技术栈
-- **前端**: Next.js 15 + React 19 + TypeScript + Tailwind CSS
+- **前端**: Next.js 16 + React 19 + TypeScript + Tailwind CSS
- **数据收集**: Node.js + WebSocket + SQLite
- **可视化**: Recharts + D3.js
- **部署**: Docker + Docker Compose
@@ -298,6 +298,10 @@ clash-master/
MIT License © 2024 [foru17](https://github.com/foru17)
+## Star History
+
+[![Star History Chart](https://api.star-history.com/svg?repos=foru17/clash-master&type=date&legend=top-left)](https://www.star-history.com/#foru17/clash-master&type=date&legend=top-left)
+
---
<p align="center">
diff --git a/apps/collector/src/api.ts b/apps/collector/src/api.ts
index 48a1f14..05da53f 100644
--- a/apps/collector/src/api.ts
+++ b/apps/collector/src/api.ts
@@ -516,6 +516,36 @@ export class APIServer {
return { message: 'Database vacuumed successfully' };
});
+ // Get retention configuration
+ app.get('/api/db/retention', async () => {
+ return this.db.getRetentionConfig();
+ });
+
+ // Update retention configuration
+ app.put('/api/db/retention', async (request, reply) => {
+ const { connectionLogsDays, hourlyStatsDays, autoCleanup } = request.body as {
+ connectionLogsDays?: number;
+ hourlyStatsDays?: number;
+ autoCleanup?: boolean;
+ };
+
+ // Validate input
+ if (connectionLogsDays !== undefined && (connectionLogsDays < 1 || connectionLogsDays > 90)) {
+ return reply.status(400).send({ error: 'connectionLogsDays must be between 1 and 90' });
+ }
+ if (hourlyStatsDays !== undefined && (hourlyStatsDays < 7 || hourlyStatsDays > 365)) {
+ return reply.status(400).send({ error: 'hourlyStatsDays must be between 7 and 365' });
+ }
+
+ const newConfig = this.db.updateRetentionConfig({
+ connectionLogsDays,
+ hourlyStatsDays,
+ autoCleanup,
+ });
+
+ return { message: 'Retention configuration updated', config: newConfig };
+ });
+
await app.listen({ port: this.port, host: '0.0.0.0' });
console.log(`[API] Server running at http://localhost:${this.port}`);
diff --git a/apps/collector/src/batch-writer.ts b/apps/collector/src/batch-writer.ts
new file mode 100644
index 0000000..d0bbce6
--- /dev/null
+++ b/apps/collector/src/batch-writer.ts
@@ -0,0 +1,222 @@
+import { StatsDatabase } from './db.js';
+import { GeoIPService } from './geo-service.js';
+
+export interface TrafficUpdate {
+ domain: string;
+ ip: string;
+ chain: string;
+ chains: string[];
+ upload: number;
+ download: number;
+}
+
+interface GeoIPResult {
+ ip: string;
+ geo: {
+ country: string;
+ country_name: string;
+ continent: string;
+ } | null;
+ upload: number;
+ download: number;
+}
+
+interface BatchConfig {
+ // Flush interval in milliseconds
+ flushIntervalMs: number;
+
+ // Max buffer size before forced flush
+ maxBufferSize: number;
+
+ // Whether to write connection_logs (can be disabled for minimal retention)
+ writeConnectionLogs: boolean;
+}
+
+const DEFAULT_CONFIG: BatchConfig = {
+ flushIntervalMs: 1000, // Flush every 1 second
+ maxBufferSize: 1000, // Force flush at 1000 entries
+ writeConnectionLogs: true, // Enable by default
+};
+
+/**
+ * Optimized batch writer for traffic data
+ *
+ * Key optimizations:
+ * 1. In-memory buffering to reduce SQLite transactions
+ * 2. Aggregation of same-key updates within batch window
+ * 3. Single transaction for all stats tables
+ * 4. Optional connection_logs for storage efficiency
+ */
+export class BatchWriter {
+ private db: StatsDatabase;
+ private geoService?: GeoIPService;
+ private config: BatchConfig;
+
+ // Buffer storage
+ private buffer: Map<string, TrafficUpdate & { count: number; firstSeen: number }> = new Map();
+ private geoQueue: GeoIPResult[] = [];
+ private connectionLogBuffer: TrafficUpdate[] = [];
+
+ // Flush management
+ private flushTimer: NodeJS.Timeout | null = null;
+ private lastFlushTime = 0;
+ private isFlushing = false;
+
+ // Metrics
+ private totalBuffered = 0;
+ private totalFlushed = 0;
+
+ constructor(
+ db: StatsDatabase,
+ geoService?: GeoIPService,
+ config: Partial<BatchConfig> = {}
+ ) {
+ this.db = db;
+ this.geoService = geoService;
+ this.config = { ...DEFAULT_CONFIG, ...config };
+ this.startFlushTimer();
+ }
+
+ /**
+ * Add a traffic update to the buffer
+ * Returns immediately, data is written on next flush
+ */
+ add(backendId: number, update: TrafficUpdate): void {
+ // Create aggregation key (domain + ip + chain for granular tracking)
+ const key = `${backendId}:${update.domain}:${update.ip}:${update.chain}`;
+ const now = Date.now();
+
+ const existing = this.buffer.get(key);
+ if (existing) {
+ // Aggregate with existing entry
+ existing.upload += update.upload;
+ existing.download += update.download;
+ existing.count += 1;
+ } else {
+ // New entry
+ this.buffer.set(key, {
+ ...update,
+ count: 1,
+ firstSeen: now,
+ });
+ }
+
+ // Also buffer for connection_logs if enabled
+ if (this.config.writeConnectionLogs) {
+ this.connectionLogBuffer.push(update);
+ }
+
+ this.totalBuffered++;
+
+ // Check if we need to force flush
+ if (this.buffer.size >= this.config.maxBufferSize) {
+ this.flush(backendId);
+ }
+ }
+
+ /**
+ * Queue GeoIP result for batch country stats update
+ */
+ queueGeoIP(ip: string, geo: GeoIPResult['geo'], upload: number, download: number): void {
+ this.geoQueue.push({ ip, geo, upload, download });
+ }
+
+ /**
+ * Force flush all buffered data to database
+ */
+ async flush(backendId: number): Promise<void> {
+ if (this.isFlushing || this.buffer.size === 0) {
+ return;
+ }
+
+ this.isFlushing = true;
+ const startTime = Date.now();
+
+ try {
+ // Copy buffers and clear immediately to allow new data during write
+ const updates = Array.from(this.buffer.values());
+ const geoResults = [...this.geoQueue];
+ const connectionLogs = this.config.writeConnectionLogs
+ ? [...this.connectionLogBuffer]
+ : [];
+
+ this.buffer.clear();
+ this.geoQueue = [];
+ if (this.config.writeConnectionLogs) {
+ this.connectionLogBuffer = [];
+ }
+
+ // Perform batch write in single transaction
+ this.db.batchUpdateTrafficStats(backendId, updates.map(u => ({
+ domain: u.domain,
+ ip: u.ip,
+ chain: u.chain,
+ chains: u.chains,
+ upload: u.upload,
+ download: u.download,
+ })));
+
+ // Process GeoIP results
+ for (const result of geoResults) {
+ if (result.geo) {
+ this.db.updateCountryStats(
+ backendId,
+ result.geo.country,
+ result.geo.country_name,
+ result.geo.continent,
+ result.upload,
+ result.download
+ );
+ }
+ }
+
+ // Write connection logs (may be skipped if disabled)
+ if (connectionLogs.length > 0) {
+ this.db.batchInsertConnectionLogs(backendId, connectionLogs);
+ }
+
+ this.totalFlushed += updates.length;
+
+ const duration = Date.now() - startTime;
+ if (duration > 100) {
+ console.log(`[BatchWriter] Flushed ${updates.length} updates in ${duration}ms`);
+ }
+ } catch (err) {
+ console.error('[BatchWriter] Flush failed:', err);
+ // TODO: Implement retry or error recovery
+ } finally {
+ this.isFlushing = false;
+ this.lastFlushTime = Date.now();
+ }
+ }
+
+ /**
+ * Get current buffer statistics
+ */
+ getStats(): { buffered: number; flushed: number; pendingFlush: number } {
+ return {
+ buffered: this.totalBuffered,
+ flushed: this.totalFlushed,
+ pendingFlush: this.buffer.size,
+ };
+ }
+
+ /**
+ * Stop the flush timer and cleanup
+ */
+ stop(): void {
+ if (this.flushTimer) {
+ clearInterval(this.flushTimer);
+ this.flushTimer = null;
+ }
+ }
+
+ /**
+ * Start the automatic flush timer
+ */
+ private startFlushTimer(): void {
+ this.flushTimer = setInterval(() => {
+ // Timer check is done at backend level
+ }, this.config.flushIntervalMs);
+ }
+}
diff --git a/apps/collector/src/cleanup-service.ts b/apps/collector/src/cleanup-service.ts
new file mode 100644
index 0000000..d5794e9
--- /dev/null
+++ b/apps/collector/src/cleanup-service.ts
@@ -0,0 +1,171 @@
+import { StatsDatabase } from './db.js';
+import { RetentionConfig, DEFAULT_RETENTION } from './data-retention.js';
+
+/**
+ * Automatic data cleanup service
+ *
+ * Implements tiered data retention:
+ * - Raw connection logs: Short term (configurable, default 7 days)
+ * - Hourly stats: Medium term (configurable, default 30 days)
+ * - Daily/domain stats: Long term (permanent, continuously updated)
+ */
+export class CleanupService {
+ private db: StatsDatabase;
+ private cleanupTimer: NodeJS.Timeout | null = null;
+ private isRunning = false;
+ private customInterval: number | undefined;
+
+ constructor(db: StatsDatabase, config: Partial<RetentionConfig> = {}) {
+ this.db = db;
+ this.customInterval = config.cleanupInterval;
+ }
+
+ /**
+ * Get current config from database
+ */
+ private getConfig(): RetentionConfig {
+ const dbConfig = this.db.getRetentionConfig();
+ return {
+ ...DEFAULT_RETENTION,
+ ...dbConfig,
+ // Use custom interval if provided in constructor
+ cleanupInterval: this.customInterval ?? DEFAULT_RETENTION.cleanupInterval,
+ };
+ }
+
+ /**
+ * Start automatic cleanup scheduling
+ */
+ start(): void {
+ const config = this.getConfig();
+
+ if (!config.autoCleanup) {
+ console.log('[Cleanup] Auto-cleanup disabled');
+ return;
+ }
+
+ if (this.cleanupTimer) {
+ return; // Already running
+ }
+
+ console.log(`[Cleanup] Starting with retention policy:`, {
+ connectionLogs: `${config.connectionLogsDays} days`,
+ hourlyStats: `${config.hourlyStatsDays} days`,
+ interval: `${config.cleanupInterval} hours`,
+ });
+
+ // Run initial cleanup
+ this.runCleanup();
+
+ // Schedule periodic cleanup
+ const intervalMs = config.cleanupInterval * 60 * 60 * 1000;
+ this.cleanupTimer = setInterval(() => {
+ this.runCleanup();
+ }, intervalMs);
+ }
+
+ /**
+ * Stop automatic cleanup
+ */
+ stop(): void {
+ if (this.cleanupTimer) {
+ clearInterval(this.cleanupTimer);
+ this.cleanupTimer = null;
+ console.log('[Cleanup] Stopped');
+ }
+ }
+
+ /**
+ * Run cleanup manually
+ */
+ async runCleanup(): Promise<void> {
+ if (this.isRunning) {
+ console.log('[Cleanup] Previous cleanup still running, skipping');
+ return;
+ }
+
+ this.isRunning = true;
+ const startTime = Date.now();
+
+ try {
+ // Clean up old connection logs
+ const logsDeleted = this.cleanupConnectionLogs();
+
+ // Clean up old hourly stats
+ const hourlyDeleted = this.cleanupHourlyStats();
+
+ // Vacuum database to reclaim space (only if significant data deleted)
+ const totalDeleted = logsDeleted + hourlyDeleted;
+ if (totalDeleted > 10000) {
+ console.log(`[Cleanup] Deleted ${totalDeleted} records, vacuuming database...`);
+ this.db.vacuum();
+ }
+
+ const duration = Date.now() - startTime;
+ console.log(`[Cleanup] Completed in ${duration}ms: ${logsDeleted} logs, ${hourlyDeleted} hourly records deleted`);
+ } catch (err) {
+ console.error('[Cleanup] Failed:', err);
+ } finally {
+ this.isRunning = false;
+ }
+ }
+
+ /**
+ * Clean up old connection logs
+ */
+ private cleanupConnectionLogs(): number {
+ const config = this.getConfig();
+ const cutoffDate = new Date();
+ cutoffDate.setDate(cutoffDate.getDate() - config.connectionLogsDays);
+ const cutoff = cutoffDate.toISOString();
+
+ return this.db.deleteOldConnectionLogs(cutoff);
+ }
+
+ /**
+ * Clean up old hourly stats
+ */
+ private cleanupHourlyStats(): number {
+ const config = this.getConfig();
+ const cutoffDate = new Date();
+ cutoffDate.setDate(cutoffDate.getDate() - config.hourlyStatsDays);
+ const cutoff = cutoffDate.toISOString().slice(0, 13) + ':00:00';
+
+ return this.db.deleteOldHourlyStats(cutoff);
+ }
+
+ /**
+ * Get current database size statistics
+ */
+ getStats(): {
+ connectionLogsCount: number;
+ hourlyStatsCount: number;
+ oldestConnectionLog: string | null;
+ oldestHourlyStat: string | null;
+ } {
+ return this.db.getCleanupStats();
+ }
+
+ /**
+ * Update retention configuration
+ */
+ updateConfig(config: Partial<RetentionConfig>): void {
+ // Save to database
+ this.db.updateRetentionConfig({
+ connectionLogsDays: config.connectionLogsDays,
+ hourlyStatsDays: config.hourlyStatsDays,
+ autoCleanup: config.autoCleanup,
+ });
+
+ // Handle interval change
+ if (config.cleanupInterval !== undefined) {
+ this.customInterval = config.cleanupInterval;
+ }
+
+ // Restart if interval changed or autoCleanup was toggled
+ if ((config.cleanupInterval !== undefined || config.autoCleanup !== undefined) && this.cleanupTimer) {
+ this.stop();
+ this.start();
+ }
+ }
+}
diff --git a/apps/collector/src/collector.ts b/apps/collector/src/collector.ts
index d3f0649..5834d08 100644
--- a/apps/collector/src/collector.ts
+++ b/apps/collector/src/collector.ts
@@ -1,3 +1,5 @@
+"use client";
+
import WebSocket from 'ws';
import type { ConnectionsData } from '@clashmaster/shared';
import { StatsDatabase } from './db.js';
@@ -11,6 +13,26 @@ interface CollectorOptions {
onError?: (error: Error) => void;
}
+interface TrafficUpdate {
+ domain: string;
+ ip: string;
+ chain: string;
+ chains: string[];
+ upload: number;
+ download: number;
+}
+
+interface GeoIPResult {
+ ip: string;
+ geo: {
+ country: string;
+ country_name: string;
+ continent: string;
+ } | null;
+ upload: number;
+ download: number;
+}
+
export class OpenClashCollector {
private ws: WebSocket | null = null;
private url: string;
@@ -98,6 +120,89 @@ export class OpenClashCollector {
}
}
+// Batch buffer for traffic updates
+class BatchBuffer {
+ private buffer: Map<string, TrafficUpdate> = new Map();
+ private geoQueue: GeoIPResult[] = [];
+ private lastLogTime = 0;
+ private logCounter = 0;
+
+ add(backendId: number, update: TrafficUpdate) {
+ const key = `${backendId}:${update.domain}:${update.ip}:${update.chain}`;
+ const existing = this.buffer.get(key);
+
+ if (existing) {
+ existing.upload += update.upload;
+ existing.download += update.download;
+ } else {
+ this.buffer.set(key, { ...update });
+ }
+ }
+
+ addGeoResult(result: GeoIPResult) {
+ this.geoQueue.push(result);
+ }
+
+ flush(db: StatsDatabase, geoService: GeoIPService | undefined, backendId: number): { domains: number; rules: number } {
+ if (this.buffer.size === 0) {
+ return { domains: 0, rules: 0 };
+ }
+
+ const updates = Array.from(this.buffer.values());
+ this.buffer.clear();
+
+ // Merge geo queue
+ const geoResults = [...this.geoQueue];
+ this.geoQueue = [];
+
+ // Calculate unique domains and rules for logging
+ const domains = new Set<string>();
+ const rules = new Set<string>();
+
+ for (const update of updates) {
+ if (update.domain) domains.add(update.domain);
+ const initialRule = update.chains.length > 0 ? update.chains[update.chains.length - 1] : 'DIRECT';
+ rules.add(initialRule);
+ }
+
+ // Batch write to database
+ try {
+ db.batchUpdateTrafficStats(backendId, updates);
+
+ // Process geo results
+ for (const result of geoResults) {
+ if (result.geo) {
+ db.updateCountryStats(
+ backendId,
+ result.geo.country,
+ result.geo.country_name,
+ result.geo.continent,
+ result.upload,
+ result.download
+ );
+ }
+ }
+ } catch (err) {
+ console.error(`[Collector:${backendId}] Batch write failed:`, err);
+ }
+
+ return { domains: domains.size, rules: rules.size };
+ }
+
+ shouldLog(): boolean {
+ const now = Date.now();
+ if (now - this.lastLogTime > 10000) {
+ this.lastLogTime = now;
+ return true;
+ }
+ return false;
+ }
+
+ incrementLogCounter(): number {
+ return ++this.logCounter;
+ }
+}
+
// Track connection state with their accumulated traffic
interface TrackedConnection {
id: string;
@@ -120,11 +225,21 @@ export function createCollector(
) {
const id = backendId || 0;
const activeConnections = new Map<string, TrackedConnection>();
- let lastLogTime = 0;
+ const batchBuffer = new BatchBuffer();
let lastBroadcastTime = 0;
const broadcastThrottleMs = 500;
-
- return new OpenClashCollector(id, {
+ let flushInterval: NodeJS.Timeout | null = null;
+
+ // Start batch flush interval (every 1000ms)
+ flushInterval = setInterval(() => {
+ const stats = batchBuffer.flush(db, geoService, id);
+
+ if (batchBuffer.shouldLog() && (stats.domains > 0 || stats.rules > 0)) {
+ console.log(`[Collector:${id}] Active: ${activeConnections.size}, Domains: ${stats.domains}, Rules: ${stats.rules}`);
+ }
+ }, 1000);
+
+ const collector = new OpenClashCollector(id, {
url,
token,
onData: (data) => {
@@ -176,15 +291,15 @@ export function createCollector(
domain,
ip,
chains,
- lastUpload: 0,
- lastDownload: 0,
+ lastUpload: conn.upload,
+ lastDownload: conn.download,
totalUpload: conn.upload,
totalDownload: conn.download,
});
- // Record initial traffic for new connection
+ // Record initial traffic for new connection (add to batch buffer)
if (conn.upload > 0 || conn.download > 0) {
- db.updateTrafficStats(id, {
+ batchBuffer.add(id, {
domain,
ip,
chain: chains[0] || 'DIRECT',
@@ -193,20 +308,18 @@ export function createCollector(
download: conn.download,
});
- // Query and update country stats if GeoIP service is available
+ // Queue GeoIP lookup
if (geoService && ip) {
- geoService.getGeoLocation(ip).then((geo: { country: string; country_name: string; continent: string } | null) => {
+ geoService.getGeoLocation(ip).then((geo) => {
if (geo) {
- db.updateCountryStats(
- id,
- geo.country,
- geo.country_name,
- geo.continent,
- conn.upload,
- conn.download
- );
+ batchBuffer.addGeoResult({
+ ip,
+ geo,
+ upload: conn.upload,
+ download: conn.download,
+ });
}
- }).catch((err: Error) => {
+ }).catch(() => {
// Silently fail for GeoIP errors
});
}
@@ -214,7 +327,7 @@ export function createCollector(
hasNewTraffic = true;
}
} else {
- // Existing connection - calculate delta and update stats
+ // Existing connection - calculate delta and add to batch
const uploadDelta = Math.max(0, conn.upload - existing.lastUpload);
const downloadDelta = Math.max(0, conn.download - existing.lastDownload);
@@ -223,8 +336,8 @@ export function createCollector(
existing.totalUpload += uploadDelta;
existing.totalDownload += downloadDelta;
- // Update stats in database with delta
- db.updateTrafficStats(id, {
+ // Add delta to batch buffer
+ batchBuffer.add(id, {
domain: existing.domain,
ip: existing.ip,
chain: existing.chains[0] || 'DIRECT',
@@ -233,20 +346,18 @@ export function createCollector(
download: downloadDelta,
});
- // Query and update country stats if GeoIP service is available
+ // Queue GeoIP lookup for delta
if (geoService && existing.ip) {
- geoService.getGeoLocation(existing.ip).then((geo: { country: string; country_name: string; continent: string } | null) => {
+ geoService.getGeoLocation(existing.ip).then((geo) => {
if (geo) {
- db.updateCountryStats(
- id,
- geo.country,
- geo.country_name,
- geo.continent,
- uploadDelta,
- downloadDelta
- );
+ batchBuffer.addGeoResult({
+ ip: existing.ip,
+ geo,
+ upload: uploadDelta,
+ download: downloadDelta,
+ });
}
- }).catch((err: Error) => {
+ }).catch(() => {
// Silently fail for GeoIP errors
});
}
@@ -258,7 +369,7 @@ export function createCollector(
}
}
- // Find closed connections and flush their remaining traffic
+ // Find closed connections and remove them
for (const [connId, tracked] of activeConnections) {
if (!currentIds.has(connId)) {
// Connection closed - any remaining traffic was already counted
@@ -271,25 +382,23 @@ export function createCollector(
lastBroadcastTime = now;
onTrafficUpdate();
}
-
- // Log stats periodically (every 10 seconds)
- if (now - lastLogTime > 10000) {
- const domains = new Set<string>();
- const rules = new Set<string>();
-
- for (const conn of activeConnections.values()) {
- if (conn.domain) domains.add(conn.domain);
- // The initial rule is the last element in chains array
- const initialRule = conn.chains.length > 0 ? conn.chains[conn.chains.length - 1] : 'DIRECT';
- rules.add(initialRule);
- }
-
- console.log(`[Collector:${id}] Active: ${activeConnections.size}, Domains: ${domains.size}, Rules: ${rules.size}`);
- lastLogTime = now;
- }
},
onError: (err) => {
console.error(`[Collector:${id}] Error:`, err);
}
});
+
+ // Override disconnect to clear interval
+ const originalDisconnect = collector.disconnect.bind(collector);
+ collector.disconnect = () => {
+ if (flushInterval) {
+ clearInterval(flushInterval);
+ flushInterval = null;
+ // Final flush
+ batchBuffer.flush(db, geoService, id);
+ }
+ originalDisconnect();
+ };
+
+ return collector;
}
diff --git a/apps/collector/src/data-retention.ts b/apps/collector/src/data-retention.ts
new file mode 100644
index 0000000..9d5d694
--- /dev/null
+++ b/apps/collector/src/data-retention.ts
@@ -0,0 +1,46 @@
+/**
+ * Data Retention Policy for Clash Master
+ *
+ * Tiered storage strategy:
+ * - Raw data (connection_logs): 7 days for detailed analysis
+ * - Hourly aggregates: 30 days for recent trends
+ * - Daily aggregates: 90 days for monthly analysis
+ * - Domain/IP stats: Permanent (continuously updated)
+ */
+
+export interface RetentionConfig {
+ // Raw connection logs retention (detailed per-connection data)
+ connectionLogsDays: number;
+
+ // Hourly stats retention (for traffic trend charts)
+ hourlyStatsDays: number;
+
+ // Auto-cleanup enabled
+ autoCleanup: boolean;
+
+ // Cleanup interval (hours)
+ cleanupInterval: number;
+}
+
+export const DEFAULT_RETENTION: RetentionConfig = {
+ connectionLogsDays: 7, // Keep 7 days of raw logs
+ hourlyStatsDays: 30, // Keep 30 days of hourly data
+ autoCleanup: true,
+ cleanupInterval: 24, // Run cleanup every 24 hours
+};
+
+// For users who want longer retention (higher storage cost)
+export const EXTENDED_RETENTION: RetentionConfig = {
+ connectionLogsDays: 30, // Keep 30 days of raw logs
+ hourlyStatsDays: 90, // Keep 90 days of hourly data
+ autoCleanup: true,
+ cleanupInterval: 24,
+};
+
+// Minimal retention for low-resource environments
+export const MINIMAL_RETENTION: RetentionConfig = {
+ connectionLogsDays: 3, // Keep 3 days of raw logs
+ hourlyStatsDays: 14, // Keep 14 days of hourly data
+ autoCleanup: true,
+ cleanupInterval: 12, // Cleanup more frequently
+};
diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.ts
index b2daa57..8bbc3f8 100644
--- a/apps/collector/src/db.ts
+++ b/apps/collector/src/db.ts
@@ -2,6 +2,12 @@ import Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';
import type { Connection, DomainStats, IPStats, HourlyStats, DailyStats, ProxyStats, RuleStats, ProxyTrafficStats } from '@clashmaster/shared';
+// Retention config stored in database (doesn't include cleanupInterval)
+interface DatabaseRetentionConfig {
+ connectionLogsDays: number;
+ hourlyStatsDays: number;
+ autoCleanup: boolean;
+}
export interface TrafficUpdate {
domain: string;
@@ -215,6 +221,23 @@ export class StatsDatabase {
// Create unique index on name
this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_backend_configs_name ON backend_configs(name);`);
+ // App configuration - stores app-level settings like retention policy
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS app_config (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ `);
+
+ // Insert default retention config if not exists
+ this.db.exec(`
+ INSERT OR IGNORE INTO app_config (key, value) VALUES
+ ('retention.connection_logs_days', '7'),
+ ('retention.hourly_stats_days', '30'),
+ ('retention.auto_cleanup', '1');
+ `);
+
// Migrate existing data if needed (from single-backend schema)
this.migrateIfNeeded();
}
@@ -628,6 +651,298 @@ export class StatsDatabase {
transaction();
}
+ // Batch update traffic stats - processes multiple updates in a single transaction
+ batchUpdateTrafficStats(backendId: number, updates: TrafficUpdate[]) {
+ if (updates.length === 0) return;
+
+ const now = new Date();
+ const timestamp = now.toISOString();
+ const hour = timestamp.slice(0, 13) + ':00:00';
+
+ // Aggregate updates by domain, ip, chain to reduce UPSERT conflicts
+ const domainMap = new Map<string, TrafficUpdate & { count: number }>();
+ const ipMap = new Map<string, TrafficUpdate & { count: number }>();
+ const chainMap = new Map<string, { chains: string[]; upload: number; download: number; count: number }>();
+ const ruleProxyMap = new Map<string, { rule: string; proxy: string; count: number }>();
+ const hourlyMap = new Map<string, { upload: number; download: number; connections: number }>();
+
+ for (const update of updates) {
+ if (update.upload === 0 && update.download === 0) continue;
+
+ const initialRule = update.chains.length > 0 ? update.chains[update.chains.length - 1] : 'DIRECT';
+ const finalProxy = update.chains.length > 0 ? update.chains[0] : 'DIRECT';
+
+ // Aggregate domain stats
+ if (update.domain) {
+ const domainKey = `${update.domain}:${update.ip}:${update.chain}`;
+ const existing = domainMap.get(domainKey);
+ if (existing) {
+ existing.upload += update.upload;
+ existing.download += update.download;
+ existing.count++;
+ } else {
+ domainMap.set(domainKey, { ...update, count: 1 });
+ }
+ }
+
+ // Aggregate IP stats
+ const ipKey = `${update.ip}:${update.domain}:${update.chain}`;
+ const existingIp = ipMap.get(ipKey);
+ if (existingIp) {
+ existingIp.upload += update.upload;
+ existingIp.download += update.download;
+ existingIp.count++;
+ } else {
+ ipMap.set(ipKey, { ...update, count: 1 });
+ }
+
+ // Aggregate chain stats
+ const chainKey = update.chain;
+ const existingChain = chainMap.get(chainKey);
+ if (existingChain) {
+ existingChain.upload += update.upload;
+ existingChain.download += update.download;
+ existingChain.count++;
+ } else {
+ chainMap.set(chainKey, {
+ chains: update.chains,
+ upload: update.upload,
+ download: update.download,
+ count: 1
+ });
+ }
+
+ // Aggregate rule stats
+ const ruleKey = `${initialRule}:${finalProxy}`;
+ const existingRule = ruleProxyMap.get(ruleKey);
+ if (existingRule) {
+ existingRule.count++;
+ } else {
+ ruleProxyMap.set(ruleKey, { rule: initialRule, proxy: finalProxy, count: 1 });
+ }
+
+ // Aggregate hourly stats
+ const hourKey = hour;
+ const existingHour = hourlyMap.get(hourKey);
+ if (existingHour) {
+ existingHour.upload += update.upload;
+ existingHour.download += update.download;
+ existingHour.connections++;
+ } else {
+ hourlyMap.set(hourKey, {
+ upload: update.upload,
+ download: update.download,
+ connections: 1
+ });
+ }
+ }
+
+ // Execute batch upserts in a single transaction
+ const transaction = this.db.transaction(() => {
+ // Domain stats
+ const domainStmt = this.db.prepare(`
+ INSERT INTO domain_stats (backend_id, domain, ips, total_upload, total_download, total_connections, last_seen, rules, chains)
+ VALUES (@backendId, @domain, @ip, @upload, @download, @count, @timestamp, @rule, @chain)
+ ON CONFLICT(backend_id, domain) DO UPDATE SET
+ ips = CASE
+ WHEN domain_stats.ips IS NULL THEN @ip
+ WHEN INSTR(domain_stats.ips, @ip) > 0 THEN domain_stats.ips
+ ELSE domain_stats.ips || ',' || @ip
+ END,
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + @count,
+ last_seen = @timestamp,
+ rules = CASE
+ WHEN domain_stats.rules IS NULL THEN @rule
+ WHEN INSTR(domain_stats.rules, @rule) > 0 THEN domain_stats.rules
+ ELSE domain_stats.rules || ',' || @rule
+ END,
+ chains = CASE
+ WHEN domain_stats.chains IS NULL THEN @chain
+ WHEN INSTR(domain_stats.chains, @chain) > 0 THEN domain_stats.chains
+ ELSE domain_stats.chains || ',' || @chain
+ END
+ `);
+
+ for (const [key, data] of domainMap) {
+ const initialRule = data.chains.length > 0 ? data.chains[data.chains.length - 1] : 'DIRECT';
+ domainStmt.run({
+ backendId,
+ domain: data.domain,
+ ip: data.ip,
+ upload: data.upload,
+ download: data.download,
+ count: data.count,
+ timestamp,
+ rule: initialRule,
+ chain: data.chain
+ });
+ }
+
+ // IP stats
+ const ipStmt = this.db.prepare(`
+ INSERT INTO ip_stats (backend_id, ip, domains, total_upload, total_download, total_connections, last_seen, chains)
+ VALUES (@backendId, @ip, @domain, @upload, @download, @count, @timestamp, @chain)
+ ON CONFLICT(backend_id, ip) DO UPDATE SET
+ domains = CASE
+ WHEN ip_stats.domains IS NULL THEN @domain
+ WHEN INSTR(ip_stats.domains, @domain) > 0 THEN ip_stats.domains
+ ELSE ip_stats.domains || ',' || @domain
+ END,
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + @count,
+ last_seen = @timestamp,
+ chains = CASE
+ WHEN ip_stats.chains IS NULL THEN @chain
+ WHEN INSTR(ip_stats.chains, @chain) > 0 THEN ip_stats.chains
+ ELSE ip_stats.chains || ',' || @chain
+ END
+ `);
+
+ for (const [key, data] of ipMap) {
+ ipStmt.run({
+ backendId,
+ ip: data.ip,
+ domain: data.domain || 'unknown',
+ upload: data.upload,
+ download: data.download,
+ count: data.count,
+ timestamp,
+ chain: data.chain
+ });
+ }
+
+ // Chain/Proxy stats
+ const proxyStmt = this.db.prepare(`
+ INSERT INTO proxy_stats (backend_id, chain, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @chain, @upload, @download, @count, @timestamp)
+ ON CONFLICT(backend_id, chain) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + @count,
+ last_seen = @timestamp
+ `);
+
+ for (const [chain, data] of chainMap) {
+ proxyStmt.run({
+ backendId,
+ chain,
+ upload: data.upload,
+ download: data.download,
+ count: data.count,
+ timestamp
+ });
+ }
+
+ // Rule stats
+ const ruleStmt = this.db.prepare(`
+ INSERT INTO rule_stats (backend_id, rule, final_proxy, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @rule, @proxy, 0, 0, @count, @timestamp)
+ ON CONFLICT(backend_id, rule) DO UPDATE SET
+ final_proxy = @proxy,
+ total_connections = total_connections + @count,
+ last_seen = @timestamp
+ `);
+
+ for (const [key, data] of ruleProxyMap) {
+ ruleStmt.run({
+ backendId,
+ rule: data.rule,
+ proxy: data.proxy,
+ count: data.count,
+ timestamp
+ });
+ }
+
+ // Rule proxy map (only insert, ignore duplicates)
+ const ruleProxyStmt = this.db.prepare(`
+ INSERT OR IGNORE INTO rule_proxy_map (backend_id, rule, proxy)
+ VALUES (@backendId, @rule, @proxy)
+ `);
+
+ for (const [key, data] of ruleProxyMap) {
+ ruleProxyStmt.run({
+ backendId,
+ rule: data.rule,
+ proxy: data.proxy
+ });
+ }
+
+ // Hourly stats
+ const hourlyStmt = this.db.prepare(`
+ INSERT INTO hourly_stats (backend_id, hour, upload, download, connections)
+ VALUES (@backendId, @hour, @upload, @download, @connections)
+ ON CONFLICT(backend_id, hour) DO UPDATE SET
+ upload = upload + @upload,
+ download = download + @download,
+ connections = connections + @connections
+ `);
+
+ for (const [hour, data] of hourlyMap) {
+ hourlyStmt.run({
+ backendId,
+ hour,
+ upload: data.upload,
+ download: data.download,
+ connections: data.connections
+ });
+ }
+
+ // Batch insert into connection_logs for detailed analytics
+ // All records are preserved for accuracy
+ const logStmt = this.db.prepare(`
+ INSERT INTO connection_logs (backend_id, domain, ip, chain, upload, download)
+ VALUES (@backendId, @domain, @ip, @chain, @upload, @download)
+ `);
+
+ for (const [key, data] of domainMap) {
+ logStmt.run({
+ backendId,
+ domain: data.domain || 'unknown',
+ ip: data.ip,
+ chain: data.chain,
+ upload: data.upload,
+ download: data.download
+ });
+ }
+ });
+
+ transaction();
+ }
+
+ // Batch insert connection logs (for optimized bulk writing)
+ batchInsertConnectionLogs(backendId: number, logs: Array<{
+ domain: string;
+ ip: string;
+ chain: string;
+ upload: number;
+ download: number;
+ }>): void {
+ if (logs.length === 0) return;
+
+ const stmt = this.db.prepare(`
+ INSERT INTO connection_logs (backend_id, domain, ip, chain, upload, download)
+ VALUES (@backendId, @domain, @ip, @chain, @upload, @download)
+ `);
+
+ const transaction = this.db.transaction(() => {
+ for (const log of logs) {
+ stmt.run({
+ backendId,
+ domain: log.domain || 'unknown',
+ ip: log.ip,
+ chain: log.chain,
+ upload: log.upload,
+ download: log.download,
+ });
+ }
+ });
+
+ transaction();
+ }
+
// Get a specific domain by name
getDomainByName(backendId: number, domain: string): DomainStats | null {
const stmt = this.db.prepare(`
@@ -1017,16 +1332,21 @@ export class StatsDatabase {
// Get summary stats for a specific backend
getSummary(backendId: number): { totalConnections: number; totalUpload: number; totalDownload: number; uniqueDomains: number; uniqueIPs: number } {
- const connectionsStmt = this.db.prepare(`
- SELECT COUNT(*) as count FROM connection_logs WHERE backend_id = ?
- `);
- const totalConnections = (connectionsStmt.get(backendId) as { count: number }).count;
-
+ // Calculate totals from domain_stats (aggregated data) instead of connection_logs
+ // This is more efficient and works with batch writing
const trafficStmt = this.db.prepare(`
- SELECT COALESCE(SUM(upload), 0) as upload, COALESCE(SUM(download), 0) as download
- FROM connection_logs WHERE backend_id = ?
+ SELECT
+ COALESCE(SUM(total_connections), 0) as connections,
+ COALESCE(SUM(total_upload), 0) as upload,
+ COALESCE(SUM(total_download), 0) as download
+ FROM domain_stats
+ WHERE backend_id = ?
`);
- const { upload, download } = trafficStmt.get(backendId) as { upload: number; download: number };
+ const { connections, upload, download } = trafficStmt.get(backendId) as {
+ connections: number;
+ upload: number;
+ download: number;
+ };
const domainsStmt = this.db.prepare(`
SELECT COUNT(DISTINCT domain) as count FROM domain_stats WHERE backend_id = ?
@@ -1039,7 +1359,7 @@ export class StatsDatabase {
const uniqueIPs = (ipsStmt.get(backendId) as { count: number }).count;
return {
- totalConnections,
+ totalConnections: connections,
totalUpload: upload,
totalDownload: download,
uniqueDomains,
@@ -1274,11 +1594,6 @@ export class StatsDatabase {
return result.changes;
}
- // Vacuum database to reclaim space
- vacuum(): void {
- this.db.exec('VACUUM');
- }
-
// Get database file size in bytes
getDatabaseSize(): number {
try {
@@ -1305,6 +1620,59 @@ export class StatsDatabase {
return result.count;
}
+ // Retention Configuration Methods
+
+ // Get retention configuration
+ getRetentionConfig(): DatabaseRetentionConfig {
+ const connectionLogsDays = this.db.prepare(`
+ SELECT value FROM app_config WHERE key = 'retention.connection_logs_days'
+ `).get() as { value: string } | undefined;
+
+ const hourlyStatsDays = this.db.prepare(`
+ SELECT value FROM app_config WHERE key = 'retention.hourly_stats_days'
+ `).get() as { value: string } | undefined;
+
+ const autoCleanup = this.db.prepare(`
+ SELECT value FROM app_config WHERE key = 'retention.auto_cleanup'
+ `).get() as { value: string } | undefined;
+
+ return {
+ connectionLogsDays: parseInt(connectionLogsDays?.value || '7', 10),
+ hourlyStatsDays: parseInt(hourlyStatsDays?.value || '30', 10),
+ autoCleanup: autoCleanup?.value === '1',
+ };
+ }
+
+ // Update retention configuration
+ updateRetentionConfig(updates: {
+ connectionLogsDays?: number;
+ hourlyStatsDays?: number;
+ autoCleanup?: boolean;
+ }): DatabaseRetentionConfig {
+ if (updates.connectionLogsDays !== undefined) {
+ this.db.prepare(`
+ INSERT INTO app_config (key, value) VALUES ('retention.connection_logs_days', ?)
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP
+ `).run(updates.connectionLogsDays.toString());
+ }
+
+ if (updates.hourlyStatsDays !== undefined) {
+ this.db.prepare(`
+ INSERT INTO app_config (key, value) VALUES ('retention.hourly_stats_days', ?)
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP
+ `).run(updates.hourlyStatsDays.toString());
+ }
+
+ if (updates.autoCleanup !== undefined) {
+ this.db.prepare(`
+ INSERT INTO app_config (key, value) VALUES ('retention.auto_cleanup', ?)
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP
+ `).run(updates.autoCleanup ? '1' : '0');
+ }
+
+ return this.getRetentionConfig();
+ }
+
// Backend Management Methods
// Create a new backend configuration
@@ -1454,16 +1822,19 @@ export class StatsDatabase {
// Get total stats across all backends
getGlobalSummary(): { totalConnections: number; totalUpload: number; totalDownload: number; uniqueDomains: number; uniqueIPs: number; backendCount: number } {
- const connectionsStmt = this.db.prepare(`
- SELECT COUNT(*) as count FROM connection_logs
- `);
- const totalConnections = (connectionsStmt.get() as { count: number }).count;
-
+ // Calculate totals from domain_stats (aggregated data) instead of connection_logs
const trafficStmt = this.db.prepare(`
- SELECT COALESCE(SUM(upload), 0) as upload, COALESCE(SUM(download), 0) as download
- FROM connection_logs
+ SELECT
+ COALESCE(SUM(total_connections), 0) as connections,
+ COALESCE(SUM(total_upload), 0) as upload,
+ COALESCE(SUM(total_download), 0) as download
+ FROM domain_stats
`);
- const { upload, download } = trafficStmt.get() as { upload: number; download: number };
+ const { connections, upload, download } = trafficStmt.get() as {
+ connections: number;
+ upload: number;
+ download: number;
+ };
const domainsStmt = this.db.prepare(`
SELECT COUNT(DISTINCT domain) as count FROM domain_stats
@@ -1481,7 +1852,7 @@ export class StatsDatabase {
const backendCount = (backendStmt.get() as { count: number }).count;
return {
- totalConnections,
+ totalConnections: connections,
totalUpload: upload,
totalDownload: download,
uniqueDomains,
@@ -1490,6 +1861,44 @@ export class StatsDatabase {
};
}
+ vacuum(): void {
+ this.db.exec('VACUUM');
+ }
+
+ // Cleanup methods for data retention
+ deleteOldConnectionLogs(cutoff: string): number {
+ const stmt = this.db.prepare(`
+ DELETE FROM connection_logs WHERE timestamp < ?
+ `);
+ return stmt.run(cutoff).changes;
+ }
+
+ deleteOldHourlyStats(cutoff: string): number {
+ const stmt = this.db.prepare(`
+ DELETE FROM hourly_stats WHERE hour < ?
+ `);
+ return stmt.run(cutoff).changes;
+ }
+
+ getCleanupStats(): {
+ connectionLogsCount: number;
+ hourlyStatsCount: number;
+ oldestConnectionLog: string | null;
+ oldestHourlyStat: string | null;
+ } {
+ const logsCountStmt = this.db.prepare('SELECT COUNT(*) as count FROM connection_logs');
+ const hourlyCountStmt = this.db.prepare('SELECT COUNT(*) as count FROM hourly_stats');
+ const oldestLogStmt = this.db.prepare('SELECT MIN(timestamp) as ts FROM connection_logs');
+ const oldestHourlyStmt = this.db.prepare('SELECT MIN(hour) as hr FROM hourly_stats');
+
+ return {
+ connectionLogsCount: (logsCountStmt.get() as { count: number }).count,
+ hourlyStatsCount: (hourlyCountStmt.get() as { count: number }).count,
+ oldestConnectionLog: (oldestLogStmt.get() as { ts: string | null })?.ts || null,
+ oldestHourlyStat: (oldestHourlyStmt.get() as { hr: string | null })?.hr || null,
+ };
+ }
+
close() {
this.db.close();
}
diff --git a/apps/web/app/[locale]/page.tsx b/apps/web/app/[locale]/page.tsx
index b645b6c..f4bf9a3 100644
--- a/apps/web/app/[locale]/page.tsx
+++ b/apps/web/app/[locale]/page.tsx
@@ -18,6 +18,7 @@ import {
Sun,
Monitor,
Info,
+ MoreVertical,
} from "lucide-react";
import { useRouter, usePathname } from "next/navigation";
import Image from "next/image";
@@ -268,20 +269,10 @@ export default function DashboardPage() {
api.getCountries(backendId, 50, timeRange),
]);
- // Check if data actually changed by comparing JSON (include backendId to detect backend switch)
- const newDataJson = JSON.stringify({
- backendId,
- totalDownload: stats?.totalDownload,
- totalUpload: stats?.totalUpload,
- totalDomains: stats?.totalDomains,
- });
-
- if (newDataJson !== lastDataRef.current) {
- lastDataRef.current = newDataJson;
- setData(stats);
- setCountryData(countries);
- setLastUpdated(new Date());
- }
+ // Always update data on successful fetch
+ setData(stats);
+ setCountryData(countries);
+ setLastUpdated(new Date());
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : "Unknown error");
@@ -367,7 +358,11 @@ export default function DashboardPage() {
return (
<div className="flex min-h-screen bg-background">
- <Navigation activeTab={activeTab} onTabChange={setActiveTab} onBackendChange={handleBackendChange} />
+ <Navigation
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ onBackendChange={handleBackendChange}
+ />
<main className="flex-1 min-w-0 lg:ml-0">
<header className="sticky top-0 z-40 lg:static border-b border-border/40 bg-background/80 backdrop-blur-md">
@@ -384,14 +379,19 @@ export default function DashboardPage() {
className="w-full h-full object-cover"
/>
</div>
- <h2 className="hidden lg:block font-semibold">{t(activeTab)}</h2>
+ <h2 className="hidden lg:block font-semibold">
+ {t(activeTab)}
+ </h2>
</div>
{/* Backend Selector */}
{backends.length > 0 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm" className="gap-1 px-2 sm:px-3">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="gap-1 px-2 sm:px-3">
<Server className="w-4 h-4" />
<span className="max-w-[80px] sm:max-w-[120px] truncate">
{activeBackend?.name || backendT("selectBackend")}
@@ -417,18 +417,18 @@ export default function DashboardPage() {
{backend.name}
</span>
<div className="flex items-center gap-1">
- {backend.is_active && (
+ {!!backend.is_active && (
<Badge
variant="default"
className="text-[10px] h-5">
{backendT("displaying")}
</Badge>
)}
- {backend.listening && !backend.is_active && (
+ {!!backend.listening && !backend.is_active && (
<Badge
variant="secondary"
- className="text-[10px] h-5">
- <Radio className="w-2 h-2 mr-1" />
+ className="text-[10px] h-5 gap-1">
+ <Radio className="w-2 h-2" />
{backendT("collecting")}
</Badge>
)}
@@ -438,7 +438,7 @@ export default function DashboardPage() {
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setShowBackendDialog(true)}>
- <Server className="w-4 h-4 mr-2" />
+ <Settings className="w-4 h-4 mr-2" />
{backendT("manageBackends")}
</DropdownMenuItem>
</DropdownMenuContent>
@@ -452,13 +452,13 @@ export default function DashboardPage() {
<Badge
key={backend.id}
variant="outline"
- className="text-[10px] h-5 gap-1 border-green-500/30 text-green-600">
+ className="text-[10px] h-5 gap-1 px-1.5 border-green-500/30 text-green-600">
<Radio className="w-2 h-2" />
{backend.name}
</Badge>
))}
{listeningBackends.length > 3 && (
- <Badge variant="outline" className="text-[10px] h-5">
+ <Badge variant="outline" className="text-[10px] h-5 px-1.5">
+{listeningBackends.length - 3}
</Badge>
)}
@@ -493,57 +493,23 @@ export default function DashboardPage() {
)}
</label>
</div>
-
+
{/* Desktop: Language & Theme */}
<div className="hidden sm:flex items-center gap-1">
<LanguageSwitcher />
<ThemeToggle />
</div>
-
- {/* Mobile: Settings Dropdown */}
+
+ {/* Mobile: More Options Dropdown */}
<div className="sm:hidden">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-9 w-9">
- <Settings className="w-5 h-5" />
+ <MoreVertical className="w-5 h-5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
- {/* Backend Selector for Mobile */}
- {backends.length > 0 && (
- <>
- <DropdownMenuLabel className="flex items-center gap-2">
- <Server className="w-4 h-4" />
- {backendT("backendsTab")}
- </DropdownMenuLabel>
- {backends.map((backend) => (
- <DropdownMenuItem
- key={backend.id}
- onClick={() => handleSwitchBackend(backend.id)}
- className="flex items-center justify-between">
- <span className={cn(
- "truncate",
- backend.is_active && "font-medium"
- )}>
- {backend.name}
- </span>
- {backend.is_active && (
- <Badge variant="default" className="text-[10px] h-5">
- {backendT("displaying")}
- </Badge>
- )}
- </DropdownMenuItem>
- ))}
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={() => setShowBackendDialog(true)}>
- <Server className="w-4 h-4 mr-2" />
- {backendT("manageBackends")}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- </>
- )}
-
- {/* Auto Refresh Toggle */}
+ {/* Auto Refresh Toggle -->
<DropdownMenuLabel className="flex items-center gap-2">
<RefreshCw className="w-4 h-4" />
{dashboardT("refresh")}
@@ -558,46 +524,69 @@ export default function DashboardPage() {
{/* Theme Selection */}
<DropdownMenuLabel className="flex items-center gap-2">
- {theme === 'dark' ? <Moon className="w-4 h-4" /> : <Sun className="w-4 h-4" />}
+ {theme === "dark" ? (
+ <Moon className="w-4 h-4" />
+ ) : (
+ <Sun className="w-4 h-4" />
+ )}
Theme
</DropdownMenuLabel>
- <DropdownMenuItem onClick={() => setTheme('light')} className={theme === 'light' ? 'bg-muted' : ''}>
+ <DropdownMenuItem
+ onClick={() => setTheme("light")}
+ className={theme === "light" ? "bg-muted" : ""}>
<Sun className="w-4 h-4 mr-2 text-amber-500" />
- Light {theme === 'light' && '✓'}
+ Light {theme === "light" && "✓"}
</DropdownMenuItem>
- <DropdownMenuItem onClick={() => setTheme('dark')} className={theme === 'dark' ? 'bg-muted' : ''}>
+ <DropdownMenuItem
+ onClick={() => setTheme("dark")}
+ className={theme === "dark" ? "bg-muted" : ""}>
<Moon className="w-4 h-4 mr-2 text-indigo-500" />
- Dark {theme === 'dark' && '✓'}
+ Dark {theme === "dark" && "✓"}
</DropdownMenuItem>
- <DropdownMenuItem onClick={() => setTheme('system')} className={theme === 'system' ? 'bg-muted' : ''}>
+ <DropdownMenuItem
+ onClick={() => setTheme("system")}
+ className={theme === "system" ? "bg-muted" : ""}>
<Monitor className="w-4 h-4 mr-2 text-slate-500" />
- System {theme === 'system' && '✓'}
+ System {theme === "system" && "✓"}
</DropdownMenuItem>
<DropdownMenuSeparator />
-
+
{/* Language Selection */}
<DropdownMenuLabel className="flex items-center gap-2">
<Globe className="w-4 h-4" />
Language
</DropdownMenuLabel>
- <DropdownMenuItem
+ <DropdownMenuItem
onClick={() => {
- const newPathname = pathname.replace(`/${locale}`, '/en');
+ const newPathname = pathname.replace(
+ `/${locale}`,
+ "/en",
+ );
router.push(newPathname);
}}
- className={locale === 'en' ? 'bg-muted' : ''}>
- English {locale === 'en' && '✓'}
+ className={locale === "en" ? "bg-muted" : ""}>
+ English {locale === "en" && "✓"}
</DropdownMenuItem>
- <DropdownMenuItem
+ <DropdownMenuItem
onClick={() => {
- const newPathname = pathname.replace(`/${locale}`, '/zh');
+ const newPathname = pathname.replace(
+ `/${locale}`,
+ "/zh",
+ );
router.push(newPathname);
}}
- className={locale === 'zh' ? 'bg-muted' : ''}>
- 中文 {locale === 'zh' && '✓'}
+ className={locale === "zh" ? "bg-muted" : ""}>
+ 中文 {locale === "zh" && "✓"}
</DropdownMenuItem>
<DropdownMenuSeparator />
-
+
+ {/* Settings */}
+ <DropdownMenuItem
+ onClick={() => setShowBackendDialog(true)}>
+ <Settings className="w-4 h-4 mr-2" />
+ {backendT("manageBackends")}
+ </DropdownMenuItem>
+
{/* About */}
<DropdownMenuItem onClick={() => setShowAboutDialog(true)}>
<Info className="w-4 h-4 mr-2 text-primary" />
@@ -606,7 +595,7 @@ export default function DashboardPage() {
</DropdownMenuContent>
</DropdownMenu>
</div>
-
+
{/* Refresh Button - Both Desktop & Mobile */}
<Button
variant="outline"
@@ -640,10 +629,7 @@ export default function DashboardPage() {
/>
{/* About Dialog */}
- <AboutDialog
- open={showAboutDialog}
- onOpenChange={setShowAboutDialog}
- />
+ <AboutDialog open={showAboutDialog} onOpenChange={setShowAboutDialog} />
</div>
);
}
diff --git a/apps/web/components/backend-config-dialog.tsx b/apps/web/components/backend-config-dialog.tsx
index c9f9ffb..9671d18 100644
--- a/apps/web/components/backend-config-dialog.tsx
+++ b/apps/web/components/backend-config-dialog.tsx
@@ -2,13 +2,13 @@
import { useState, useEffect } from "react";
import { useTranslations } from "next-intl";
-import {
- Server,
- Plus,
- Trash2,
- Edit2,
- Check,
- X,
+import {
+ Server,
+ Plus,
+ Trash2,
+ Edit2,
+ Check,
+ X,
RefreshCw,
AlertCircle,
CheckCircle2,
@@ -18,6 +18,8 @@ import {
Settings,
Radio,
Eye,
+ SlidersHorizontal,
+ Globe,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -37,6 +39,148 @@ import { cn, formatBytes, formatNumber } from "@/lib/utils";
import { api } from "@/lib/api";
import { toast } from "sonner";
import { BackendVerifyAnimation } from "./backend-verify-animation";
+import { useSettings, FaviconProvider, getFaviconUrl } from "@/lib/settings";
+import { Label } from "@/components/ui/label";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import { Separator } from "@/components/ui/separator";
+
+// Favicon Provider Preview Component
+function FaviconProviderPreview({
+ selected,
+ onChange,
+ t,
+}: {
+ selected: FaviconProvider;
+ onChange: (value: FaviconProvider) => void;
+ t: (key: string) => string;
+}) {
+ // Preview domains for the right side (desktop: 4, mobile: 2)
+ const previewDomains = [
+ "youtube.com",
+ "github.com",
+ "instagram.com",
+ "chatgpt.com",
+ ];
+
+ return (
+ <RadioGroup
+ value={selected}
+ onValueChange={(value) => onChange(value as FaviconProvider)}
+ className="space-y-3">
+ {/* Google Option */}
+ <div
+ className={cn(
+ "flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4 p-3 rounded-lg border transition-all cursor-pointer",
+ selected === "google"
+ ? "border-primary bg-primary/5"
+ : "border-border hover:bg-muted/50",
+ )}
+ onClick={() => onChange("google")}>
+ {/* Top row: Radio + Icon + Label */}
+ <div className="flex items-center gap-3 sm:gap-4 flex-1 min-w-0">
+ <RadioGroupItem value="google" id="google" className="shrink-0" />
+
+ {/* Provider Icon - Google */}
+ <div className="w-10 h-10 rounded-lg bg-white flex items-center justify-center overflow-hidden shrink-0">
+ <img
+ src="https://www.google.com/favicon.ico"
+ alt="Google"
+ className="w-6 h-6 object-contain"
+ loading="lazy"
+ onError={(e) => {
+ (e.target as HTMLImageElement).style.display = "none";
+ }}
+ />
+ </div>
+
+ {/* Label */}
+ <Label
+ htmlFor="google"
+ className="font-medium cursor-pointer flex-1 min-w-0">
+ {t("faviconGoogle")}
+ </Label>
+ </div>
+
+ {/* Preview Icons - Bottom on mobile, Right on desktop */}
+ <div className="flex items-center gap-2 pl-7 sm:pl-0">
+ {previewDomains.map((domain) => (
+ <div
+ key={domain}
+ className="w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-muted flex items-center justify-center overflow-hidden">
+ <img
+ src={getFaviconUrl(domain, "google")}
+ alt={domain}
+ className="w-4 h-4 sm:w-5 sm:h-5 object-cover"
+ loading="lazy"
+ onError={(e) => {
+ (e.target as HTMLImageElement).style.display = "none";
+ }}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Favicon.im Option */}
+ <div
+ className={cn(
+ "flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4 p-3 rounded-lg border transition-all cursor-pointer",
+ selected === "faviconim"
+ ? "border-primary bg-primary/5"
+ : "border-border hover:bg-muted/50",
+ )}
+ onClick={() => onChange("faviconim")}>
+ {/* Top row: Radio + Icon + Label */}
+ <div className="flex items-center gap-3 sm:gap-4 flex-1 min-w-0">
+ <RadioGroupItem
+ value="faviconim"
+ id="faviconim"
+ className="shrink-0"
+ />
+
+ {/* Provider Icon - favicon.im */}
+ <div className="w-10 h-10 rounded-lg bg-muted flex items-center justify-center overflow-hidden shrink-0">
+ <img
+ src="https://favicon.im/favicon.im?larger=true"
+ alt="favicon.im"
+ className="w-6 h-6 object-contain"
+ loading="lazy"
+ onError={(e) => {
+ (e.target as HTMLImageElement).style.display = "none";
+ }}
+ />
+ </div>
+
+ {/* Label */}
+ <Label
+ htmlFor="faviconim"
+ className="font-medium cursor-pointer flex-1 min-w-0">
+ {t("faviconIm")}
+ </Label>
+ </div>
+
+ {/* Preview Icons - Bottom on mobile, Right on desktop */}
+ <div className="flex items-center gap-2 pl-7 sm:pl-0">
+ {previewDomains.map((domain) => (
+ <div
+ key={domain}
+ className="w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-muted flex items-center justify-center overflow-hidden">
+ <img
+ src={getFaviconUrl(domain, "faviconim")}
+ alt={domain}
+ className="w-4 h-4 sm:w-5 sm:h-5 object-cover"
+ loading="lazy"
+ onError={(e) => {
+ (e.target as HTMLImageElement).style.display = "none";
+ }}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ </RadioGroup>
+ );
+}
interface Backend {
id: number;
@@ -65,23 +209,39 @@ interface DbStats {
totalConnectionsCount: number;
}
+// Retention presets - inspired by AdGuard Home
+const RETENTION_PRESETS = [
+ { key: "minimal", days: 3 },
+ { key: "standard", days: 7 },
+ { key: "extended", days: 30 },
+ { key: "maximum", days: 90 },
+] as const;
+
+type PresetKey = (typeof RETENTION_PRESETS)[number]["key"];
+
+interface RetentionConfig {
+ connectionLogsDays: number;
+ hourlyStatsDays: number;
+ autoCleanup: boolean;
+}
+
// Parse URL to host and port
function parseUrl(url: string): { host: string; port: string; ssl: boolean } {
try {
const urlObj = new URL(url);
return {
host: urlObj.hostname,
- port: urlObj.port || (urlObj.protocol === 'https:' ? '443' : '80'),
- ssl: urlObj.protocol === 'https:',
+ port: urlObj.port || (urlObj.protocol === "https:" ? "443" : "80"),
+ ssl: urlObj.protocol === "https:",
};
} catch {
- return { host: '', port: '9090', ssl: false };
+ return { host: "", port: "9090", ssl: false };
}
}
// Build URL from host, port, ssl
function buildUrl(host: string, port: string, ssl: boolean): string {
- const protocol = ssl ? 'https' : 'http';
+ const protocol = ssl ? "https" : "http";
return `${protocol}://${host}:${port}`;
}
@@ -94,38 +254,61 @@ export function BackendConfigDialog({
}: BackendConfigDialogProps) {
const t = useTranslations("backend");
const commonT = useTranslations("common");
-
+
const [backends, setBackends] = useState<Backend[]>([]);
const [loading, setLoading] = useState(false);
const [editingId, setEditingId] = useState<number | null>(null);
const [testingId, setTestingId] = useState<number | null>(null);
- const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
- const [activeTab, setActiveTab] = useState<'backends' | 'database'>('backends');
+ const [testResult, setTestResult] = useState<{
+ success: boolean;
+ message: string;
+ } | null>(null);
+ const [activeTab, setActiveTab] = useState<
+ "backends" | "database" | "preferences"
+ >("backends");
+ const { settings, setSettings } = useSettings();
const [dbStats, setDbStats] = useState<DbStats | null>(null);
const [clearingLogs, setClearingLogs] = useState(false);
-
+
+ // Data retention state
+ const [retentionConfig, setRetentionConfig] = useState<RetentionConfig>({
+ connectionLogsDays: 7,
+ hourlyStatsDays: 30,
+ autoCleanup: true,
+ });
+ const [updatingRetention, setUpdatingRetention] = useState(false);
+
// Alert Dialog States
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [deleteBackendId, setDeleteBackendId] = useState<number | null>(null);
const [clearLogsDialogOpen, setClearLogsDialogOpen] = useState(false);
const [clearLogsDays, setClearLogsDays] = useState<number>(0);
- const [clearBackendDataDialogOpen, setClearBackendDataDialogOpen] = useState(false);
- const [clearDataBackendId, setClearDataBackendId] = useState<number | null>(null);
-
+ const [clearBackendDataDialogOpen, setClearBackendDataDialogOpen] =
+ useState(false);
+ const [clearDataBackendId, setClearDataBackendId] = useState<number | null>(
+ null,
+ );
+
// Error Alert Dialog State
const [errorDialogOpen, setErrorDialogOpen] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
-
+
// Success Alert Dialog State
const [successDialogOpen, setSuccessDialogOpen] = useState(false);
const [successMessage, setSuccessMessage] = useState("");
// Verify Animation State
const [showVerifyAnimation, setShowVerifyAnimation] = useState(false);
- const [verifyPhase, setVerifyPhase] = useState<"pending" | "success" | "error">("pending");
+ const [verifyPhase, setVerifyPhase] = useState<
+ "pending" | "success" | "error"
+ >("pending");
const [verifyMessage, setVerifyMessage] = useState("");
- const [pendingBackend, setPendingBackend] = useState<{ name: string; url: string; token: string } | null>(null);
-
+ const [pendingBackend, setPendingBackend] = useState<{
+ name: string;
+ url: string;
+ token: string;
+ } | null>(null);
+
const [formData, setFormData] = useState({
name: "",
host: "",
@@ -138,6 +321,7 @@ export function BackendConfigDialog({
if (open) {
loadBackends();
loadDbStats();
+ loadRetentionConfig();
}
}, [open]);
@@ -164,21 +348,97 @@ export function BackendConfigDialog({
}
};
+ const loadRetentionConfig = async () => {
+ try {
+ const config = await api.getRetentionConfig();
+ setRetentionConfig(config);
+ } catch (error) {
+ console.error("Failed to load retention config:", error);
+ }
+ };
+
+ const handleUpdateRetention = async (
+ key: keyof RetentionConfig,
+ value: number | boolean,
+ ) => {
+ try {
+ setUpdatingRetention(true);
+ const newConfig = { ...retentionConfig, [key]: value };
+ await api.updateRetentionConfig(newConfig);
+ setRetentionConfig(newConfig);
+ toast.success(t("retentionUpdated"));
+ } catch (error: any) {
+ toast.error(error.message || t("retentionUpdateFailed"));
+ } finally {
+ setUpdatingRetention(false);
+ }
+ };
+
+ // Check which preset matches current config
+ const getActivePreset = (): PresetKey | "custom" => {
+ const preset = RETENTION_PRESETS.find(
+ (p) => p.days === retentionConfig.connectionLogsDays,
+ );
+ return preset ? preset.key : "custom";
+ };
+
+ // Apply preset
+ const applyPreset = async (presetKey: PresetKey) => {
+ const preset = RETENTION_PRESETS.find((p) => p.key === presetKey);
+ if (!preset) return;
+
+ try {
+ setUpdatingRetention(true);
+ const newConfig = {
+ connectionLogsDays: preset.days,
+ hourlyStatsDays: Math.min(preset.days * 4, 90), // Hourly stats = 4x detail days, max 90
+ autoCleanup: true,
+ };
+ await api.updateRetentionConfig(newConfig);
+ setRetentionConfig(newConfig);
+ toast.success(t("retentionUpdated"));
+ } catch (error: any) {
+ toast.error(error.message || t("retentionUpdateFailed"));
+ } finally {
+ setUpdatingRetention(false);
+ }
+ };
+
+ // Apply custom days
+ const applyCustomDays = async (days: number) => {
+ const validDays = Math.max(1, Math.min(30, days));
+ try {
+ setUpdatingRetention(true);
+ const newConfig = {
+ connectionLogsDays: validDays,
+ hourlyStatsDays: Math.min(validDays * 4, 90),
+ autoCleanup: true,
+ };
+ await api.updateRetentionConfig(newConfig);
+ setRetentionConfig(newConfig);
+ toast.success(t("retentionUpdated"));
+ } catch (error: any) {
+ toast.error(error.message || t("retentionUpdateFailed"));
+ } finally {
+ setUpdatingRetention(false);
+ }
+ };
+
const handleAdd = async () => {
if (!formData.name || !formData.host) return;
-
+
const url = buildUrl(formData.host, formData.port, formData.ssl);
-
+
// Show verification animation immediately
setPendingBackend({ name: formData.name, url, token: formData.token });
setVerifyPhase("pending");
setVerifyMessage("");
setShowVerifyAnimation(true);
-
+
// Perform verification
try {
const testResult = await api.testBackend(url, formData.token);
-
+
if (testResult.success) {
setVerifyPhase("success");
setVerifyMessage(testResult.message || t("testSuccess"));
@@ -195,28 +455,37 @@ export function BackendConfigDialog({
// Called after verification animation completes
const handleVerifyComplete = async () => {
if (!pendingBackend) return;
-
+
// Only save if verification was successful
if (verifyPhase === "success") {
try {
- const result = await api.createBackend({
- name: pendingBackend.name,
- url: pendingBackend.url,
- token: pendingBackend.token
+ const result = await api.createBackend({
+ name: pendingBackend.name,
+ url: pendingBackend.url,
+ token: pendingBackend.token,
+ });
+
+ setFormData({
+ name: "",
+ host: "",
+ port: "9090",
+ ssl: false,
+ token: "",
});
-
- setFormData({ name: "", host: "", port: "9090", ssl: false, token: "" });
setShowVerifyAnimation(false);
setPendingBackend(null);
await loadBackends();
await onBackendChange?.();
-
+
// Show success message for first backend
if (result.isActive) {
- setTestResult({ success: true, message: t("firstBackendAutoActive") });
+ setTestResult({
+ success: true,
+ message: t("firstBackendAutoActive"),
+ });
setTimeout(() => setTestResult(null), 3000);
}
-
+
if (isFirstTime && onConfigComplete) {
await onConfigComplete();
onOpenChange(false);
@@ -238,10 +507,10 @@ export function BackendConfigDialog({
setLoading(true);
try {
const url = buildUrl(formData.host, formData.port, formData.ssl);
- await api.updateBackend(id, {
- name: formData.name,
- url,
- token: formData.token || undefined
+ await api.updateBackend(id, {
+ name: formData.name,
+ url,
+ token: formData.token || undefined,
});
setEditingId(null);
setFormData({ name: "", host: "", port: "9090", ssl: false, token: "" });
@@ -264,7 +533,7 @@ export function BackendConfigDialog({
// Handle actual delete
const handleDelete = async () => {
if (!deleteBackendId) return;
-
+
setLoading(true);
try {
await api.deleteBackend(deleteBackendId);
@@ -316,7 +585,7 @@ export function BackendConfigDialog({
// Handle clear backend data
const handleClearBackendData = async () => {
if (!clearDataBackendId) return;
-
+
setLoading(true);
try {
await api.clearBackendData(clearDataBackendId);
@@ -325,7 +594,11 @@ export function BackendConfigDialog({
setClearBackendDataDialogOpen(false);
setClearDataBackendId(null);
} catch (error: any) {
- setErrorMessage(error.message || t("clearBackendDataError") || "Failed to clear backend data");
+ setErrorMessage(
+ error.message ||
+ t("clearBackendDataError") ||
+ "Failed to clear backend data",
+ );
setErrorDialogOpen(true);
} finally {
setLoading(false);
@@ -339,7 +612,10 @@ export function BackendConfigDialog({
const result = await api.testBackend(backend.url, backend.token);
setTestResult(result);
} catch (error: any) {
- setTestResult({ success: false, message: error.message || "Test failed" });
+ setTestResult({
+ success: false,
+ message: error.message || "Test failed",
+ });
} finally {
setTestingId(null);
}
@@ -374,7 +650,7 @@ export function BackendConfigDialog({
name: backend.name,
host: backend.host,
port: String(backend.port || 9090),
- ssl: backend.url.startsWith('https'),
+ ssl: backend.url.startsWith("https"),
token: "",
});
};
@@ -398,30 +674,35 @@ export function BackendConfigDialog({
<p className="text-sm text-muted-foreground">
{isFirstTime ? t("firstTimeDescription") : t("description")}
</p>
-
+
{/* Tabs */}
- <div className="flex gap-2 mt-4">
+ <div className="flex gap-2 mt-4 flex-wrap">
<Button
- variant={activeTab === 'backends' ? 'default' : 'ghost'}
+ variant={activeTab === "backends" ? "default" : "ghost"}
size="sm"
- onClick={() => setActiveTab('backends')}
- >
+ onClick={() => setActiveTab("backends")}>
<Server className="w-4 h-4 mr-2" />
{t("backendsTab")}
</Button>
<Button
- variant={activeTab === 'database' ? 'default' : 'ghost'}
+ variant={activeTab === "database" ? "default" : "ghost"}
size="sm"
- onClick={() => setActiveTab('database')}
- >
+ onClick={() => setActiveTab("database")}>
<Database className="w-4 h-4 mr-2" />
{t("databaseTab")}
</Button>
+ <Button
+ variant={activeTab === "preferences" ? "default" : "ghost"}
+ size="sm"
+ onClick={() => setActiveTab("preferences")}>
+ <SlidersHorizontal className="w-4 h-4 mr-2" />
+ {t("preferencesTab")}
+ </Button>
</div>
</CardHeader>
<CardContent className="space-y-4">
- {activeTab === 'backends' ? (
+ {activeTab === "backends" ? (
// Backends Tab
<div className="space-y-3">
{backends.map((backend) => (
@@ -432,27 +713,40 @@ export function BackendConfigDialog({
backend.is_active
? "border-primary bg-primary/5"
: "border-border bg-card",
- !backend.enabled && "opacity-60"
- )}
- >
+ !backend.enabled && "opacity-60",
+ )}>
{editingId === backend.id ? (
// Edit Mode
<div className="space-y-3">
<div className="grid grid-cols-2 gap-3">
<div>
- <label className="text-xs font-medium">{t("name")}</label>
+ <label className="text-xs font-medium">
+ {t("name")}
+ </label>
<Input
value={formData.name}
- onChange={(e) => setFormData({ ...formData, name: e.target.value })}
+ onChange={(e) =>
+ setFormData({
+ ...formData,
+ name: e.target.value,
+ })
+ }
placeholder={t("namePlaceholder")}
className="h-9 mt-1"
/>
</div>
<div>
- <label className="text-xs font-medium">{t("host")}</label>
+ <label className="text-xs font-medium">
+ {t("host")}
+ </label>
<Input
value={formData.host}
- onChange={(e) => setFormData({ ...formData, host: e.target.value })}
+ onChange={(e) =>
+ setFormData({
+ ...formData,
+ host: e.target.value,
+ })
+ }
placeholder="192.168.1.1"
className="h-9 mt-1"
/>
@@ -460,10 +754,17 @@ export function BackendConfigDialog({
</div>
<div className="grid grid-cols-3 gap-3">
<div>
- <label className="text-xs font-medium">{t("port")}</label>
+ <label className="text-xs font-medium">
+ {t("port")}
+ </label>
<Input
value={formData.port}
- onChange={(e) => setFormData({ ...formData, port: e.target.value })}
+ onChange={(e) =>
+ setFormData({
+ ...formData,
+ port: e.target.value,
+ })
+ }
placeholder="9090"
className="h-9 mt-1"
/>
@@ -471,27 +772,42 @@ export function BackendConfigDialog({
<div className="col-span-2 flex items-center gap-2 pt-5">
<Switch
checked={formData.ssl}
- onCheckedChange={(checked) => setFormData({ ...formData, ssl: checked })}
+ onCheckedChange={(checked) =>
+ setFormData({ ...formData, ssl: checked })
+ }
/>
<label className="text-sm">{t("useSsl")}</label>
</div>
</div>
<div>
- <label className="text-xs font-medium">{t("token")}</label>
+ <label className="text-xs font-medium">
+ {t("token")}
+ </label>
<Input
type="password"
value={formData.token}
- onChange={(e) => setFormData({ ...formData, token: e.target.value })}
+ onChange={(e) =>
+ setFormData({
+ ...formData,
+ token: e.target.value,
+ })
+ }
placeholder={t("tokenPlaceholder")}
className="h-9 mt-1"
/>
</div>
<div className="flex gap-2 justify-end">
- <Button variant="ghost" size="sm" onClick={cancelEdit}>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={cancelEdit}>
<X className="w-4 h-4 mr-1" />
{commonT("cancel")}
</Button>
- <Button size="sm" onClick={() => handleUpdate(backend.id)} disabled={loading}>
+ <Button
+ size="sm"
+ onClick={() => handleUpdate(backend.id)}
+ disabled={loading}>
<Check className="w-4 h-4 mr-1" />
{commonT("save")}
</Button>
@@ -503,7 +819,9 @@ export function BackendConfigDialog({
{/* Left: Info */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
- <span className="font-medium text-base">{backend.name}</span>
+ <span className="font-medium text-base">
+ {backend.name}
+ </span>
{!backend.enabled && (
<span className="px-2 py-0.5 rounded-full bg-muted text-muted-foreground text-xs font-medium">
{t("disabled")}
@@ -514,14 +832,16 @@ export function BackendConfigDialog({
{backend.host}:{backend.port}
</div>
</div>
-
+
{/* Right: Actions */}
<div className="flex items-center gap-2 shrink-0">
{/* Collect Toggle with Label */}
<div className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-secondary/50">
<Switch
checked={backend.listening}
- onCheckedChange={(checked) => handleToggleListening(backend.id, checked)}
+ onCheckedChange={(checked) =>
+ handleToggleListening(backend.id, checked)
+ }
className="data-[state=checked]:bg-green-500"
/>
<span className="text-xs text-muted-foreground hidden sm:inline">
@@ -537,43 +857,57 @@ export function BackendConfigDialog({
size="icon"
className={cn(
"h-8 w-8",
- backend.is_active && "opacity-50 cursor-not-allowed"
+ backend.is_active &&
+ "opacity-50 cursor-not-allowed",
)}
- onClick={() => !backend.is_active && handleSetActive(backend.id)}
+ onClick={() =>
+ !backend.is_active &&
+ handleSetActive(backend.id)
+ }
disabled={backend.is_active}
- title={backend.is_active ? t("displaying") : t("setActive")}
- >
- <Eye className={cn("w-4 h-4", backend.is_active && "text-primary")} />
+ title={
+ backend.is_active
+ ? t("displaying")
+ : t("setActive")
+ }>
+ <Eye
+ className={cn(
+ "w-4 h-4",
+ backend.is_active && "text-primary",
+ )}
+ />
</Button>
-
+
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => handleTest(backend)}
disabled={testingId === backend.id}
- title={t("testConnection")}
- >
- <RefreshCw className={cn("w-4 h-4", testingId === backend.id && "animate-spin")} />
+ title={t("testConnection")}>
+ <RefreshCw
+ className={cn(
+ "w-4 h-4",
+ testingId === backend.id && "animate-spin",
+ )}
+ />
</Button>
-
+
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => startEdit(backend)}
- title={commonT("edit")}
- >
+ title={commonT("edit")}>
<Edit2 className="w-4 h-4" />
</Button>
-
+
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => openDeleteDialog(backend.id)}
- title={commonT("delete")}
- >
+ title={commonT("delete")}>
<Trash2 className="w-4 h-4" />
</Button>
</div>
@@ -590,9 +924,8 @@ export function BackendConfigDialog({
"p-3 rounded-lg flex items-center gap-2 text-sm",
testResult.success
? "bg-green-500/10 text-green-600 border border-green-500/20"
- : "bg-destructive/10 text-destructive border border-destructive/20"
- )}
- >
+ : "bg-destructive/10 text-destructive border border-destructive/20",
+ )}>
{testResult.success ? (
<CheckCircle2 className="w-4 h-4 shrink-0" />
) : (
@@ -606,24 +939,34 @@ export function BackendConfigDialog({
<div className="p-4 rounded-lg border border-dashed border-border bg-muted/50">
<h4 className="text-sm font-medium mb-3 flex items-center gap-2">
<Plus className="w-4 h-4" />
- {backends.length === 0 && isFirstTime ? t("firstTimeTitle") : t("addNew")}
+ {backends.length === 0 && isFirstTime
+ ? t("firstTimeTitle")
+ : t("addNew")}
</h4>
<div className="space-y-3">
<div className="grid grid-cols-2 gap-3">
<div>
- <label className="text-xs font-medium">{t("name")} *</label>
+ <label className="text-xs font-medium">
+ {t("name")} *
+ </label>
<Input
value={formData.name}
- onChange={(e) => setFormData({ ...formData, name: e.target.value })}
+ onChange={(e) =>
+ setFormData({ ...formData, name: e.target.value })
+ }
placeholder={t("namePlaceholder")}
className="h-9 mt-1"
/>
</div>
<div>
- <label className="text-xs font-medium">{t("host")} *</label>
+ <label className="text-xs font-medium">
+ {t("host")} *
+ </label>
<Input
value={formData.host}
- onChange={(e) => setFormData({ ...formData, host: e.target.value })}
+ onChange={(e) =>
+ setFormData({ ...formData, host: e.target.value })
+ }
placeholder="192.168.1.1"
className="h-9 mt-1"
/>
@@ -631,10 +974,14 @@ export function BackendConfigDialog({
</div>
<div className="grid grid-cols-3 gap-3">
<div>
- <label className="text-xs font-medium">{t("port")}</label>
+ <label className="text-xs font-medium">
+ {t("port")}
+ </label>
<Input
value={formData.port}
- onChange={(e) => setFormData({ ...formData, port: e.target.value })}
+ onChange={(e) =>
+ setFormData({ ...formData, port: e.target.value })
+ }
placeholder="9090"
className="h-9 mt-1"
/>
@@ -642,33 +989,40 @@ export function BackendConfigDialog({
<div className="col-span-2 flex items-center gap-2 pt-5">
<Switch
checked={formData.ssl}
- onCheckedChange={(checked) => setFormData({ ...formData, ssl: checked })}
+ onCheckedChange={(checked) =>
+ setFormData({ ...formData, ssl: checked })
+ }
/>
<label className="text-sm">{t("useSsl")}</label>
</div>
</div>
<div>
- <label className="text-xs font-medium">{t("token")}</label>
+ <label className="text-xs font-medium">
+ {t("token")}
+ </label>
<Input
type="password"
value={formData.token}
- onChange={(e) => setFormData({ ...formData, token: e.target.value })}
+ onChange={(e) =>
+ setFormData({ ...formData, token: e.target.value })
+ }
placeholder={t("tokenPlaceholder")}
className="h-9 mt-1"
/>
</div>
- <Button
- onClick={handleAdd}
+ <Button
+ onClick={handleAdd}
disabled={loading || !formData.name || !formData.host}
- className="w-full"
- >
+ className="w-full">
<Plus className="w-4 h-4 mr-2" />
- {isFirstTime && backends.length === 0 ? t("saveAndContinue") : t("addBackend")}
+ {isFirstTime && backends.length === 0
+ ? t("saveAndContinue")
+ : t("addBackend")}
</Button>
</div>
</div>
</div>
- ) : (
+ ) : activeTab === "database" ? (
// Database Tab
<div className="space-y-6">
{/* DB Stats */}
@@ -679,23 +1033,98 @@ export function BackendConfigDialog({
</h4>
<div className="grid grid-cols-2 gap-4">
<div className="p-3 rounded-lg bg-muted">
- <div className="text-xs text-muted-foreground">{t("dbSize")}</div>
+ <div className="text-xs text-muted-foreground">
+ {t("dbSize")}
+ </div>
<div className="text-lg font-semibold">
{dbStats ? formatBytes(dbStats.size) : "--"}
</div>
</div>
<div className="p-3 rounded-lg bg-muted">
- <div className="text-xs text-muted-foreground">{t("connectionsCount")}</div>
+ <div className="text-xs text-muted-foreground">
+ {t("connectionsCount")}
+ </div>
<div className="text-lg font-semibold">
- {dbStats ? formatNumber(dbStats.totalConnectionsCount) : "--"}
+ {dbStats
+ ? formatNumber(dbStats.totalConnectionsCount)
+ : "--"}
</div>
</div>
</div>
</div>
- {/* Clear Logs */}
+ {/* Data Retention Settings */}
<div className="p-4 rounded-lg border bg-card">
- <h4 className="text-sm font-medium mb-4 flex items-center gap-2">
+ <div className="flex items-center justify-between mb-2">
+ <h4 className="text-sm font-medium flex items-center gap-2">
+ <Database className="w-4 h-4" />
+ {t("dataRetention")}
+ </h4>
+ <span className="text-sm text-muted-foreground">
+ {t("retentionDays", {
+ days: retentionConfig.connectionLogsDays,
+ })}
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground mb-3">
+ {t("dataRetentionDescription")}
+ </p>
+
+ <div className="flex flex-wrap gap-2">
+ {/* Preset Buttons */}
+ {RETENTION_PRESETS.map((preset) => {
+ const isActive = getActivePreset() === preset.key;
+ return (
+ <button
+ key={preset.key}
+ onClick={() => applyPreset(preset.key)}
+ disabled={updatingRetention}
+ className={cn(
+ "px-3 py-1.5 text-sm rounded-md border transition-all",
+ isActive
+ ? "border-primary bg-primary/10 text-primary font-medium"
+ : "border-border hover:bg-muted/50 text-muted-foreground",
+ )}
+ title={t(
+ `retentionPreset${preset.key.charAt(0).toUpperCase() + preset.key.slice(1)}Desc`,
+ )}>
+ {t(
+ `retentionPreset${preset.key.charAt(0).toUpperCase() + preset.key.slice(1)}`,
+ )}
+ </button>
+ );
+ })}
+
+ {/* Custom Input */}
+ <div
+ className={cn(
+ "flex items-center gap-1.5 px-2 py-1 rounded-md border transition-all",
+ getActivePreset() === "custom"
+ ? "border-primary bg-primary/10"
+ : "border-border",
+ )}>
+ <Input
+ type="number"
+ min={1}
+ max={90}
+ value={retentionConfig.connectionLogsDays}
+ onChange={(e) => {
+ const days = parseInt(e.target.value) || 1;
+ applyCustomDays(Math.min(90, Math.max(1, days)));
+ }}
+ disabled={updatingRetention}
+ className="w-14 h-6 text-sm text-center p-0 border-0 bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0"
+ />
+ <span className="text-xs text-muted-foreground">
+ {commonT("days")}
+ </span>
+ </div>
+ </div>
+ </div>
+
+ {/* Clear Logs - Dangerous action, placed at the bottom */}
+ <div className="p-4 rounded-lg border ">
+ <h4 className="text-sm font-medium mb-4 flex items-center gap-2 text-destructive">
<Trash className="w-4 h-4" />
{t("clearLogs")}
</h4>
@@ -703,41 +1132,60 @@ export function BackendConfigDialog({
{t("clearLogsDescription")}
</p>
<div className="flex flex-wrap gap-2">
- <Button
- variant="outline"
+ <Button
+ variant="outline"
size="sm"
onClick={() => openClearLogsDialog(1)}
- disabled={clearingLogs}
- >
+ disabled={clearingLogs}>
{t("clear1Day")}
</Button>
- <Button
- variant="outline"
+ <Button
+ variant="outline"
size="sm"
onClick={() => openClearLogsDialog(7)}
- disabled={clearingLogs}
- >
+ disabled={clearingLogs}>
{t("clear7Days")}
</Button>
- <Button
- variant="outline"
+ <Button
+ variant="outline"
size="sm"
onClick={() => openClearLogsDialog(30)}
- disabled={clearingLogs}
- >
+ disabled={clearingLogs}>
{t("clear30Days")}
</Button>
- <Button
- variant="destructive"
+ <Button
+ variant="destructive"
size="sm"
onClick={() => openClearLogsDialog(0)}
- disabled={clearingLogs}
- >
+ disabled={clearingLogs}>
{t("clearAll")}
</Button>
</div>
</div>
</div>
+ ) : (
+ // Preferences Tab
+ <div className="space-y-6">
+ {/* Favicon Provider */}
+ <div className="p-4 rounded-lg border bg-card">
+ <h4 className="text-sm font-medium mb-2 flex items-center gap-2">
+ <Globe className="w-4 h-4" />
+ {t("faviconProvider")}
+ </h4>
+ <p className="text-sm text-muted-foreground mb-4">
+ {t("faviconProviderDescription")}
+ </p>
+
+ {/* Favicon Preview */}
+ <FaviconProviderPreview
+ selected={settings.faviconProvider}
+ onChange={(value) =>
+ setSettings({ faviconProvider: value })
+ }
+ t={t}
+ />
+ </div>
+ </div>
)}
{/* Close button for non-first-time */}
@@ -765,10 +1213,9 @@ export function BackendConfigDialog({
<AlertDialogCancel onClick={() => setDeleteBackendId(null)}>
{commonT("cancel")}
</AlertDialogCancel>
- <AlertDialogAction
+ <AlertDialogAction
onClick={handleDelete}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
{commonT("delete")}
</AlertDialogAction>
</AlertDialogFooter>
@@ -776,24 +1223,27 @@ export function BackendConfigDialog({
</AlertDialog>
{/* Clear Logs Confirmation Dialog */}
- <AlertDialog open={clearLogsDialogOpen} onOpenChange={setClearLogsDialogOpen}>
+ <AlertDialog
+ open={clearLogsDialogOpen}
+ onOpenChange={setClearLogsDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("clearLogs")}</AlertDialogTitle>
<AlertDialogDescription>
- {clearLogsDays === 0
- ? t("confirmClearAllLogs")
+ {clearLogsDays === 0
+ ? t("confirmClearAllLogs")
: t("confirmClearLogs", { days: clearLogsDays })}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
- <AlertDialogCancel>
- {commonT("cancel")}
- </AlertDialogCancel>
- <AlertDialogAction
+ <AlertDialogCancel>{commonT("cancel")}</AlertDialogCancel>
+ <AlertDialogAction
onClick={handleClearLogs}
- className={clearLogsDays === 0 ? "bg-destructive text-destructive-foreground hover:bg-destructive/90" : ""}
- >
+ className={
+ clearLogsDays === 0
+ ? "bg-destructive text-destructive-foreground hover:bg-destructive/90"
+ : ""
+ }>
{commonT("confirm")}
</AlertDialogAction>
</AlertDialogFooter>
@@ -808,9 +1258,7 @@ export function BackendConfigDialog({
<AlertCircle className="h-5 w-5 text-destructive" />
{commonT("error") || "Error"}
</AlertDialogTitle>
- <AlertDialogDescription>
- {errorMessage}
- </AlertDialogDescription>
+ <AlertDialogDescription>{errorMessage}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogAction onClick={() => setErrorDialogOpen(false)}>
@@ -828,9 +1276,7 @@ export function BackendConfigDialog({
<CheckCircle2 className="h-5 w-5 text-green-500" />
{commonT("success") || "Success"}
</AlertDialogTitle>
- <AlertDialogDescription>
- {successMessage}
- </AlertDialogDescription>
+ <AlertDialogDescription>{successMessage}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogAction onClick={() => setSuccessDialogOpen(false)}>
diff --git a/apps/web/components/domain-top-grid.tsx b/apps/web/components/domain-top-grid.tsx
index f3aea26..296ccf0 100644
--- a/apps/web/components/domain-top-grid.tsx
+++ b/apps/web/components/domain-top-grid.tsx
@@ -6,6 +6,7 @@ import { useTranslations } from "next-intl";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { formatBytes, formatNumber } from "@/lib/utils";
+import { useSettings, getFaviconUrl } from "@/lib/settings";
import type { DomainStats } from "@clashmaster/shared";
interface DomainTopGridProps {
@@ -16,10 +17,6 @@ interface DomainTopGridProps {
type SortBy = "traffic" | "connections";
-function getFaviconUrl(domain: string): string {
- return `https://www.google.com/s2/favicons?domain=${domain}&sz=64`;
-}
-
function getInitials(domain: string): string {
return domain.slice(0, 2).toUpperCase();
}
@@ -28,6 +25,7 @@ export function DomainTopGrid({ data, limit = 5, onViewAll }: DomainTopGridProps
const [sortBy, setSortBy] = useState<SortBy>("traffic");
const t = useTranslations("topDomains");
const proxiesT = useTranslations("proxies");
+ const { settings } = useSettings();
const domains = useMemo(() => {
if (!data) return [];
@@ -46,6 +44,11 @@ export function DomainTopGrid({ data, limit = 5, onViewAll }: DomainTopGridProps
const toggleSort = () => setSortBy(prev => prev === "traffic" ? "connections" : "traffic");
+ // Get favicon URL using current provider
+ const getFaviconForDomain = (domain: string) => {
+ return getFaviconUrl(domain, settings.faviconProvider);
+ };
+
return (
<Card className="h-full flex flex-col">
<CardHeader className="pb-3 flex-shrink-0">
@@ -80,7 +83,7 @@ export function DomainTopGrid({ data, limit = 5, onViewAll }: DomainTopGridProps
</span>
<img
- src={getFaviconUrl(domain.domain)}
+ src={getFaviconForDomain(domain.domain)}
alt=""
className="w-5 h-5 rounded"
onError={(e) => {
diff --git a/apps/web/components/domain-top-list.tsx b/apps/web/components/domain-top-list.tsx
index d70561b..4a84666 100644
--- a/apps/web/components/domain-top-list.tsx
+++ b/apps/web/components/domain-top-list.tsx
@@ -7,6 +7,7 @@ import { OverviewCard } from "./overview-card";
import { TopListItem } from "./top-list-item";
import { Button } from "@/components/ui/button";
import { formatBytes, formatNumber } from "@/lib/utils";
+import { useSettings, getFaviconUrl } from "@/lib/settings";
import type { DomainStats } from "@clashmaster/shared";
interface DomainTopListProps {
@@ -22,10 +23,6 @@ const COLORS = [
"#EF4444", "#EC4899", "#6366F1"
];
-function getFaviconUrl(domain: string): string {
- return `https://www.google.com/s2/favicons?domain=${domain}&sz=64`;
-}
-
function getInitials(domain: string): string {
return domain.charAt(0).toUpperCase();
}
@@ -34,6 +31,7 @@ export function DomainTopList({ data, limit = 7, onViewAll }: DomainTopListProps
const [sortBy, setSortBy] = useState<SortBy>("traffic");
const t = useTranslations("topDomains");
const proxiesT = useTranslations("proxies");
+ const { settings } = useSettings();
const { domains, totalTraffic, totalConnections } = useMemo(() => {
if (!data) return { domains: [], totalTraffic: 0, totalConnections: 0 };
@@ -64,6 +62,11 @@ export function DomainTopList({ data, limit = 7, onViewAll }: DomainTopListProps
setSortBy(prev => prev === "traffic" ? "connections" : "traffic");
};
+ // Get favicon URL using current provider
+ const getFaviconForDomain = (domain: string) => {
+ return getFaviconUrl(domain, settings.faviconProvider);
+ };
+
if (domains.length === 0) {
return (
<OverviewCard title={t("title")} icon={<Globe className="w-4 h-4" />}>
@@ -107,7 +110,7 @@ export function DomainTopList({ data, limit = 7, onViewAll }: DomainTopListProps
rank={index + 1}
icon={
<img
- src={getFaviconUrl(domain.domain)}
+ src={getFaviconForDomain(domain.domain)}
alt=""
className="w-5 h-5"
onError={(e) => {
diff --git a/apps/web/components/favicon.tsx b/apps/web/components/favicon.tsx
index 8c82a6d..71e8ed5 100644
--- a/apps/web/components/favicon.tsx
+++ b/apps/web/components/favicon.tsx
@@ -1,8 +1,9 @@
"use client";
-import { useState } from "react";
+import { useState, useEffect } from "react";
import { Globe } from "lucide-react";
import { cn } from "@/lib/utils";
+import { getFaviconUrl, useSettings, type FaviconProvider } from "@/lib/settings";
interface FaviconProps {
domain: string;
@@ -22,41 +23,48 @@ const iconSizeMap = {
lg: "w-6 h-6",
};
-export function Favicon({ domain, size = "md", className }: FaviconProps) {
- const [error, setError] = useState(false);
- const [loading, setLoading] = useState(true);
+// Generate gradient background based on domain
+function getGradient(domain: string): string[] {
+ const colors = [
+ ["from-blue-500", "to-cyan-400"],
+ ["from-purple-500", "to-pink-400"],
+ ["from-emerald-500", "to-teal-400"],
+ ["from-orange-500", "to-amber-400"],
+ ["from-rose-500", "to-red-400"],
+ ["from-indigo-500", "to-violet-400"],
+ ];
+ let hash = 0;
+ for (let i = 0; i < domain.length; i++) {
+ hash = domain.charCodeAt(i) + ((hash << 5) - hash);
+ }
+ return colors[Math.abs(hash) % colors.length];
+}
- // Clean domain (remove protocol, path, etc.)
- const cleanDomain = domain
+// Clean domain (remove protocol, path, etc.)
+function cleanDomain(domain: string): string {
+ return domain
.replace(/^https?:\/\//, "")
.replace(/^www\./, "")
.split("/")[0];
+}
+
+export function Favicon({ domain, size = "md", className }: FaviconProps) {
+ const [error, setError] = useState(false);
+ const [loading, setLoading] = useState(true);
+ const { settings } = useSettings();
- // Use Google's favicon service
- const faviconUrl = `https://www.google.com/s2/favicons?domain=${encodeURIComponent(
- cleanDomain
- )}&sz=128`;
+ const cleanedDomain = cleanDomain(domain);
+ const gradient = getGradient(cleanedDomain);
- // Generate gradient background based on domain
- const getGradient = (domain: string) => {
- const colors = [
- ["from-blue-500", "to-cyan-400"],
- ["from-purple-500", "to-pink-400"],
- ["from-emerald-500", "to-teal-400"],
- ["from-orange-500", "to-amber-400"],
- ["from-rose-500", "to-red-400"],
- ["from-indigo-500", "to-violet-400"],
- ];
- let hash = 0;
- for (let i = 0; i < domain.length; i++) {
- hash = domain.charCodeAt(i) + ((hash << 5) - hash);
- }
- return colors[Math.abs(hash) % colors.length];
- };
+ const faviconUrl = getFaviconUrl(cleanedDomain, settings.faviconProvider);
- const gradient = getGradient(cleanDomain);
+ // Reset error state when provider changes
+ useEffect(() => {
+ setError(false);
+ setLoading(true);
+ }, [settings.faviconProvider, domain]);
- if (error || !cleanDomain) {
+ if (error || !cleanedDomain) {
return (
<div
className={cn(
@@ -88,8 +96,9 @@ export function Favicon({ domain, size = "md", className }: FaviconProps) {
/>
)}
<img
+ key={faviconUrl} // Force re-render when URL changes
src={faviconUrl}
- alt={cleanDomain}
+ alt={cleanedDomain}
className={cn(
"w-full h-full object-cover p-0.5",
loading ? "opacity-0" : "opacity-100"
@@ -103,30 +112,9 @@ export function Favicon({ domain, size = "md", className }: FaviconProps) {
// Fallback component for when favicon fails
export function DomainInitial({ domain, size = "md", className }: FaviconProps) {
- const cleanDomain = domain
- .replace(/^https?:\/\//, "")
- .replace(/^www\./, "")
- .split("/")[0];
-
- const initial = cleanDomain.charAt(0).toUpperCase();
-
- const getGradient = (domain: string) => {
- const colors = [
- ["from-blue-500", "to-cyan-400"],
- ["from-purple-500", "to-pink-400"],
- ["from-emerald-500", "to-teal-400"],
- ["from-orange-500", "to-amber-400"],
- ["from-rose-500", "to-red-400"],
- ["from-indigo-500", "to-violet-400"],
- ];
- let hash = 0;
- for (let i = 0; i < domain.length; i++) {
- hash = domain.charCodeAt(i) + ((hash << 5) - hash);
- }
- return colors[Math.abs(hash) % colors.length];
- };
-
- const gradient = getGradient(cleanDomain);
+ const cleaned = cleanDomain(domain);
+ const initial = cleaned.charAt(0).toUpperCase();
+ const gradient = getGradient(cleaned);
return (
<div
diff --git a/apps/web/components/overview/top-domains-simple.tsx b/apps/web/components/overview/top-domains-simple.tsx
index 836bed7..1840384 100644
--- a/apps/web/components/overview/top-domains-simple.tsx
+++ b/apps/web/components/overview/top-domains-simple.tsx
@@ -5,6 +5,7 @@ import { Globe, ArrowRight, BarChart3, Link2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { cn, formatBytes, formatNumber } from "@/lib/utils";
+import { useSettings, getFaviconUrl } from "@/lib/settings";
import type { DomainStats } from "@clashmaster/shared";
interface TopDomainsSimpleProps {
@@ -14,10 +15,6 @@ interface TopDomainsSimpleProps {
onViewAll?: () => void;
}
-function getFaviconUrl(domain: string): string {
- return `https://www.google.com/s2/favicons?domain=${domain}&sz=64`;
-}
-
function getInitials(domain: string): string {
return domain.slice(0, 2).toUpperCase();
}
@@ -29,6 +26,7 @@ export const TopDomainsSimple = React.memo(function TopDomainsSimple({
onViewAll,
}: TopDomainsSimpleProps) {
const t = useTranslations("topDomains");
+ const { settings } = useSettings();
const sortedDomains = useMemo(() => {
if (!domains?.length) return [];
@@ -47,6 +45,10 @@ export const TopDomainsSimple = React.memo(function TopDomainsSimple({
return sorted.slice(0, 6);
}, [domains, sortBy]);
+ // Get favicon URL using current provider
+ const getFaviconForDomain = (domain: string) => {
+ return getFaviconUrl(domain, settings.faviconProvider);
+ };
return (
<div className="space-y-3 h-full flex flex-col">
@@ -118,7 +120,7 @@ export const TopDomainsSimple = React.memo(function TopDomainsSimple({
{/* Favicon */}
<div className="w-5 h-5 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden">
<img
- src={getFaviconUrl(domain.domain)}
+ src={getFaviconForDomain(domain.domain)}
alt=""
className="w-4 h-4"
loading="lazy"
diff --git a/apps/web/components/top-domains-chart.tsx b/apps/web/components/top-domains-chart.tsx
index 603420f..a1039e8 100644
--- a/apps/web/components/top-domains-chart.tsx
+++ b/apps/web/components/top-domains-chart.tsx
@@ -27,6 +27,14 @@ interface TopDomainsChartProps {
const TOP_OPTIONS = [10, 20, 50, 100] as const;
type TopOption = (typeof TOP_OPTIONS)[number];
+// Dynamic height configuration based on topN
+const CHART_CONFIG = {
+ 10: { height: 350, barSize: 32, showAllLabels: true },
+ 20: { height: 450, barSize: 24, showAllLabels: true },
+ 50: { height: 700, barSize: 18, showAllLabels: true },
+ 100: { height: 1200, barSize: 14, showAllLabels: true },
+} as const;
+
// Vibrant color palette for bars
const COLORS = [
"#3B82F6", // Blue
@@ -84,6 +92,9 @@ export function TopDomainsChart({ data }: TopDomainsChartProps) {
// Show labels only when container is wide enough (> 400px)
const showLabels = containerWidth > 400;
+ // Get chart configuration based on topN
+ const config = CHART_CONFIG[topN];
+
const chartData = useMemo(() => {
if (!data) return [];
const result = data.slice(0, topN).map((domain, index) => ({
@@ -170,7 +181,10 @@ export function TopDomainsChart({ data }: TopDomainsChartProps) {
</div>
</CardHeader>
<CardContent ref={containerRef}>
- <div className="h-[350px] w-full min-w-0 overflow-hidden sm:overflow-visible">
+ <div
+ className="w-full min-w-0 overflow-hidden sm:overflow-visible transition-all duration-500 ease-in-out"
+ style={{ height: `${config.height}px` }}
+ >
<ResponsiveContainer width="100%" height="100%">
<BarChart
data={chartData}
@@ -210,7 +224,7 @@ export function TopDomainsChart({ data }: TopDomainsChartProps) {
<Bar
dataKey="total"
radius={[0, 4, 4, 0]}
- maxBarSize={32}
+ maxBarSize={config.barSize}
isAnimationActive={!hasRenderedRef.current}
animationDuration={600}>
{chartData.map((entry, index) => (
diff --git a/apps/web/components/ui/radio-group.tsx b/apps/web/components/ui/radio-group.tsx
new file mode 100644
index 0000000..e9bde17
--- /dev/null
+++ b/apps/web/components/ui/radio-group.tsx
@@ -0,0 +1,44 @@
+"use client"
+
+import * as React from "react"
+import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
+import { Circle } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+const RadioGroup = React.forwardRef<
+ React.ElementRef<typeof RadioGroupPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
+>(({ className, ...props }, ref) => {
+ return (
+ <RadioGroupPrimitive.Root
+ className={cn("grid gap-2", className)}
+ {...props}
+ ref={ref}
+ />
+ )
+})
+RadioGroup.displayName = RadioGroupPrimitive.Root.displayName
+
+const RadioGroupItem = React.forwardRef<
+ React.ElementRef<typeof RadioGroupPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
+>(({ className, ...props }, ref) => {
+ return (
+ <RadioGroupPrimitive.Item
+ ref={ref}
+ className={cn(
+ "aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
+ className
+ )}
+ {...props}
+ >
+ <RadioGroupPrimitive.Indicator className="flex items-center justify-center">
+ <Circle className="h-2.5 w-2.5 fill-current text-current" />
+ </RadioGroupPrimitive.Indicator>
+ </RadioGroupPrimitive.Item>
+ )
+})
+RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName
+
+export { RadioGroup, RadioGroupItem }
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index 8726bb9..514edea 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -233,6 +233,12 @@ export const api = {
vacuumDatabase: () =>
fetchJson<{ message: string }>(`${API_BASE}/db/vacuum`, 'POST'),
+
+ getRetentionConfig: () =>
+ fetchJson<{ connectionLogsDays: number; hourlyStatsDays: number; autoCleanup: boolean }>(`${API_BASE}/db/retention`),
+
+ updateRetentionConfig: (config: { connectionLogsDays: number; hourlyStatsDays: number; autoCleanup?: boolean }) =>
+ fetchJson<{ message: string }>(`${API_BASE}/db/retention`, 'PUT', config),
};
// Helper functions for time range
diff --git a/apps/web/lib/settings.ts b/apps/web/lib/settings.ts
new file mode 100644
index 0000000..af5f9f8
--- /dev/null
+++ b/apps/web/lib/settings.ts
@@ -0,0 +1,148 @@
+"use client";
+
+import { useState, useEffect, useCallback, useSyncExternalStore, useMemo } from "react";
+
+export type FaviconProvider = "google" | "faviconim";
+
+export interface UserSettings {
+ faviconProvider: FaviconProvider;
+}
+
+const DEFAULT_SETTINGS: UserSettings = {
+ faviconProvider: "faviconim",
+};
+
+const STORAGE_KEY = "clash-master-settings";
+
+// Cached settings for sync access
+let cachedSettings: UserSettings = DEFAULT_SETTINGS;
+let isClient = false;
+
+// Initialize cache (only runs once)
+function initCache() {
+ if (typeof window === "undefined") return;
+ isClient = true;
+ try {
+ const stored = localStorage.getItem(STORAGE_KEY);
+ if (stored) {
+ const parsed = JSON.parse(stored);
+ cachedSettings = { ...DEFAULT_SETTINGS, ...parsed };
+ }
+ } catch {
+ // Ignore parse errors
+ }
+}
+
+// Get settings from cache (sync, returns same reference if unchanged)
+function getCachedSettings(): UserSettings {
+ if (typeof window === "undefined") {
+ return DEFAULT_SETTINGS;
+ }
+ if (!isClient) {
+ initCache();
+ }
+ return cachedSettings;
+}
+
+// Get settings from localStorage (force refresh)
+export function getSettings(): UserSettings {
+ if (typeof window === "undefined") {
+ return DEFAULT_SETTINGS;
+ }
+
+ try {
+ const stored = localStorage.getItem(STORAGE_KEY);
+ if (stored) {
+ const parsed = JSON.parse(stored);
+ const settings = { ...DEFAULT_SETTINGS, ...parsed };
+ cachedSettings = settings; // Update cache
+ return settings;
+ }
+ } catch {
+ // Ignore parse errors
+ }
+
+ return DEFAULT_SETTINGS;
+}
+
+// Save settings to localStorage
+export function saveSettings(settings: Partial<UserSettings>): void {
+ if (typeof window === "undefined") {
+ return;
+ }
+
+ try {
+ const current = getSettings();
+ const updated = { ...current, ...settings };
+ cachedSettings = updated; // Update cache immediately
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
+
+ // Dispatch event to notify components
+ window.dispatchEvent(new CustomEvent("settings-changed", { detail: updated }));
+ } catch {
+ // Ignore storage errors
+ }
+}
+
+// Subscribe to settings changes
+function subscribe(callback: () => void) {
+ const handler = () => {
+ // Update cache when settings change
+ try {
+ const stored = localStorage.getItem(STORAGE_KEY);
+ if (stored) {
+ const parsed = JSON.parse(stored);
+ cachedSettings = { ...DEFAULT_SETTINGS, ...parsed };
+ }
+ } catch {
+ // Ignore parse errors
+ }
+ callback();
+ };
+ window.addEventListener("settings-changed", handler);
+ return () => window.removeEventListener("settings-changed", handler);
+}
+
+// Snapshot function that returns cached value (must be same reference if unchanged)
+function getSnapshot(): UserSettings {
+ return getCachedSettings();
+}
+
+// Server snapshot
+function getServerSnapshot(): UserSettings {
+ return DEFAULT_SETTINGS;
+}
+
+// React hook for settings using useSyncExternalStore for instant sync
+export function useSettings() {
+ const settings = useSyncExternalStore(
+ subscribe,
+ getSnapshot,
+ getServerSnapshot
+ );
+
+ // Use useMemo to ensure stable reference
+ const stableSettings = useMemo(() => settings, [settings.faviconProvider]);
+
+ const setSettings = useCallback((newSettings: Partial<UserSettings>) => {
+ saveSettings(newSettings);
+ }, []);
+
+ return { settings: stableSettings, setSettings, mounted: true };
+}
+
+// Generate favicon URL based on provider
+export function getFaviconUrl(domain: string, provider: FaviconProvider): string {
+ const cleanDomain = domain
+ .replace(/^https?:\/\//, "")
+ .replace(/^www\./, "")
+ .split("/")[0];
+
+ switch (provider) {
+ case "faviconim":
+ return `https://favicon.im/${encodeURIComponent(cleanDomain)}?larger=true`;
+ case "google":
+ default:
+ return `https://www.google.com/s2/favicons?domain=${encodeURIComponent(cleanDomain)}&sz=128`;
+ }
+}
diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json
index e1b9894..2e35709 100644
--- a/apps/web/messages/en.json
+++ b/apps/web/messages/en.json
@@ -206,6 +206,8 @@
"viewOnGitHub": "View on GitHub"
},
"common": {
+ "daysSuffix": "d ago",
+ "days": "days",
"search": "Search",
"cancel": "Cancel",
"close": "Close",
@@ -285,8 +287,28 @@
"collect": "Collect",
"setDisplay": "Set Display",
"selectBackend": "Select Backend",
- "manageBackends": "Manage Backends",
+ "manageBackends": "Settings",
"firstBackendAutoActive": "First backend automatically set as active",
- "verificationFailed": "Backend verification failed. Please check the host address and token."
+ "verificationFailed": "Backend verification failed. Please check the host address and token.",
+ "preferencesTab": "Preferences",
+ "faviconProvider": "Favicon Provider",
+ "faviconProviderDescription": "Choose the service used to display website icons in the domain list. favicon.im is recommended for users in China.",
+ "faviconGoogle": "Google Favicon",
+ "faviconIm": "favicon.im (Recommended for China)",
+ "dataRetention": "Data Storage Time",
+ "dataRetentionDescription": "Control how long detailed connection records are kept. Domain and IP statistics are always preserved. Longer storage uses more disk space but allows troubleshooting older issues.",
+ "retentionPresetMinimal": "Minimal",
+ "retentionPresetMinimalDesc": "Save disk space, keep 3 days of details",
+ "retentionPresetStandard": "Standard",
+ "retentionPresetStandardDesc": "Balanced, keep 7 days of details",
+ "retentionPresetExtended": "Extended",
+ "retentionPresetExtendedDesc": "Full history, keep 30 days of details",
+ "retentionPresetMaximum": "Maximum",
+ "retentionPresetMaximumDesc": "Maximum retention, keep 90 days of details",
+ "retentionCustom": "Custom",
+ "retentionCustomDesc": "Set your own storage period (max 90 days)",
+ "retentionDays": "{days} days",
+ "retentionUpdated": "Storage settings saved",
+ "retentionUpdateFailed": "Failed to save settings"
}
}
diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.json
index bc58012..13a5681 100644
--- a/apps/web/messages/zh.json
+++ b/apps/web/messages/zh.json
@@ -205,6 +205,8 @@
"viewOnGitHub": "在 GitHub 查看"
},
"common": {
+ "daysSuffix": "天前",
+ "days": "天",
"search": "搜索",
"cancel": "取消",
"close": "关闭",
@@ -284,8 +286,28 @@
"collect": "收集",
"setDisplay": "设为显示",
"selectBackend": "选择后端",
- "manageBackends": "管理后端",
+ "manageBackends": "设置",
"firstBackendAutoActive": "第一个后端已自动设为显示",
- "verificationFailed": "后端验证失败,请检查地址和令牌是否正确"
+ "verificationFailed": "后端验证失败,请检查地址和令牌是否正确",
+ "preferencesTab": "偏好设置",
+ "faviconProvider": "网站图标提供商",
+ "faviconProviderDescription": "选择在域名列表中显示网站图标时使用的服务。favicon.im 在国内访问更快。",
+ "faviconGoogle": "Google Favicon",
+ "faviconIm": "favicon.im (国内推荐)",
+ "dataRetention": "数据存储时间",
+ "dataRetentionDescription": "控制详细连接记录的保存时长。域名和IP的统计数据将永久保留。存储时间越长占用磁盘空间越多,但可用于排查更早的问题。",
+ "retentionPresetMinimal": "极简",
+ "retentionPresetMinimalDesc": "节省空间,保留3天详细记录",
+ "retentionPresetStandard": "标准",
+ "retentionPresetStandardDesc": "均衡选择,保留7天详细记录",
+ "retentionPresetExtended": "完整",
+ "retentionPresetExtendedDesc": "完整历史,保留30天详细记录",
+ "retentionPresetMaximum": "最大",
+ "retentionPresetMaximumDesc": "最大保留,保留90天详细记录",
+ "retentionCustom": "自定义",
+ "retentionCustomDesc": "自定义存储时长(最多90天)",
+ "retentionDays": "{days} 天",
+ "retentionUpdated": "存储设置已保存",
+ "retentionUpdateFailed": "设置保存失败"
}
}
diff --git a/apps/web/package.json b/apps/web/package.json
index fbbc324..7b5722f 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -13,6 +13,7 @@
"@ducanh2912/next-pwa": "^10.2.9",
"@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-popover": "^1.1.15",
+ "@radix-ui/react-radio-group": "^1.3.8",
"@radix-ui/react-scroll-area": "^1.2.10",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7b004a1..79e1a2a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -63,6 +63,9 @@ importers:
'@radix-ui/react-popover':
specifier: ^1.1.15
+ '@radix-ui/react-radio-group':
+ specifier: ^1.3.8
'@radix-ui/react-scroll-area':
specifier: ^1.2.10