Skip to content

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

feat: Implement detailed rule, domain, and IP statistics with proxy chain tracking and filtering capabilities.

luolei16137a520d75
diff --git a/apps/collector/src/api.ts b/apps/collector/src/api.ts
index 06e3fc7..b123ad2 100644
--- a/apps/collector/src/api.ts
+++ b/apps/collector/src/api.ts
@@ -291,12 +291,23 @@ export class APIServer {
return reply.status(404).send({ error: 'No backend specified or active' });
}
- const { domain } = request.query as { domain?: string };
+ const { domain, sourceIP, sourceChain } = request.query as {
+ domain?: string;
+ sourceIP?: string;
+ sourceChain?: string;
+ };
if (!domain) {
return reply.status(400).send({ error: 'Domain parameter is required' });
}
- return this.db.getDomainProxyStats(backendId, domain, timeRange.start, timeRange.end);
+ return this.db.getDomainProxyStats(
+ backendId,
+ domain,
+ timeRange.start,
+ timeRange.end,
+ sourceIP,
+ sourceChain,
+ );
});
// Get IP details for a specific domain (includes geoIP and traffic)
@@ -312,7 +323,11 @@ export class APIServer {
return reply.status(404).send({ error: 'No backend specified or active' });
}
- const { domain } = request.query as { domain?: string };
+ const { domain, sourceIP, sourceChain } = request.query as {
+ domain?: string;
+ sourceIP?: string;
+ sourceChain?: string;
+ };
if (!domain) {
return reply.status(400).send({ error: 'Domain parameter is required' });
}
@@ -322,6 +337,9 @@ export class APIServer {
domain,
timeRange.start,
timeRange.end,
+ 100,
+ sourceIP,
+ sourceChain,
);
});
@@ -338,12 +356,58 @@ export class APIServer {
return reply.status(404).send({ error: 'No backend specified or active' });
}
- const { ip } = request.query as { ip?: string };
+ const { ip, sourceIP, sourceChain } = request.query as {
+ ip?: string;
+ sourceIP?: string;
+ sourceChain?: string;
+ };
+ if (!ip) {
+ return reply.status(400).send({ error: 'IP parameter is required' });
+ }
+
+ return this.db.getIPProxyStats(
+ backendId,
+ ip,
+ timeRange.start,
+ timeRange.end,
+ sourceIP,
+ sourceChain,
+ );
+ });
+
+ // Get domain details for a specific IP (includes traffic and proxy chains)
+ app.get('/api/stats/ips/domain-details', async (request, reply) => {
+ const backendId = getBackendId(request);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const { ip, sourceIP, sourceChain, limit } = request.query as {
+ ip?: string;
+ sourceIP?: string;
+ sourceChain?: string;
+ limit?: string;
+ };
if (!ip) {
return reply.status(400).send({ error: 'IP parameter is required' });
}
- return this.db.getIPProxyStats(backendId, ip, timeRange.start, timeRange.end);
+ const effectiveLimit = parseLimit(limit, 100, 2000);
+ return this.db.getIPDomainDetails(
+ backendId,
+ ip,
+ timeRange.start,
+ timeRange.end,
+ effectiveLimit,
+ sourceIP,
+ sourceChain,
+ );
});
// Get domains for a specific proxy/chain
@@ -494,6 +558,126 @@ export class APIServer {
);
});
+ // Get per-proxy traffic breakdown for a specific domain under a specific rule
+ app.get('/api/stats/rules/domains/proxy-stats', async (request, reply) => {
+ const backendId = getBackendId(request);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const { rule, domain } = request.query as { rule?: string; domain?: string };
+ if (!rule || !domain) {
+ return reply.status(400).send({ error: 'Rule and domain parameters are required' });
+ }
+
+ return this.db.getRuleDomainProxyStats(
+ backendId,
+ rule,
+ domain,
+ timeRange.start,
+ timeRange.end,
+ );
+ });
+
+ // Get IP details for a specific domain under a specific rule
+ app.get('/api/stats/rules/domains/ip-details', async (request, reply) => {
+ const backendId = getBackendId(request);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const { rule, domain, limit } = request.query as {
+ rule?: string;
+ domain?: string;
+ limit?: string;
+ };
+ if (!rule || !domain) {
+ return reply.status(400).send({ error: 'Rule and domain parameters are required' });
+ }
+ const effectiveLimit = parseLimit(limit, 100, 2000);
+
+ return this.db.getRuleDomainIPDetails(
+ backendId,
+ rule,
+ domain,
+ timeRange.start,
+ timeRange.end,
+ effectiveLimit,
+ );
+ });
+
+ // Get per-proxy traffic breakdown for a specific IP under a specific rule
+ app.get('/api/stats/rules/ips/proxy-stats', async (request, reply) => {
+ const backendId = getBackendId(request);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const { rule, ip } = request.query as { rule?: string; ip?: string };
+ if (!rule || !ip) {
+ return reply.status(400).send({ error: 'Rule and IP parameters are required' });
+ }
+
+ return this.db.getRuleIPProxyStats(
+ backendId,
+ rule,
+ ip,
+ timeRange.start,
+ timeRange.end,
+ );
+ });
+
+ // Get domain details for a specific IP under a specific rule
+ app.get('/api/stats/rules/ips/domain-details', async (request, reply) => {
+ const backendId = getBackendId(request);
+ const timeRange = getTimeRange(request, reply);
+
+ if (timeRange === null) {
+ return;
+ }
+
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+
+ const { rule, ip, limit } = request.query as {
+ rule?: string;
+ ip?: string;
+ limit?: string;
+ };
+ if (!rule || !ip) {
+ return reply.status(400).send({ error: 'Rule and IP parameters are required' });
+ }
+ const effectiveLimit = parseLimit(limit, 100, 2000);
+
+ return this.db.getRuleIPDomainDetails(
+ backendId,
+ rule,
+ ip,
+ timeRange.start,
+ timeRange.end,
+ effectiveLimit,
+ );
+ });
+
// Get rule chain flow for a specific rule
app.get('/api/stats/rules/chain-flow', async (request, reply) => {
const backendId = getBackendId(request);
diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.ts
index 929c42c..22f26fc 100644
--- a/apps/collector/src/db.ts
+++ b/apps/collector/src/db.ts
@@ -777,6 +777,7 @@ export class StatsDatabase {
const ruleName = update.chains.length > 1 ? update.chains[update.chains.length - 1] :
update.rulePayload ? `${update.rule}(${update.rulePayload})` : update.rule;
const finalProxy = update.chains.length > 0 ? update.chains[0] : 'DIRECT';
+ const fullChain = update.chains.join(' > ') || update.chain || 'DIRECT';
const transaction = this.db.transaction(() => {
// Update domain stats with backend_id (skip if domain is unknown)
@@ -814,7 +815,7 @@ export class StatsDatabase {
download: update.download,
timestamp,
rule: ruleName,
- chain: update.chain
+ chain: fullChain
});
}
@@ -843,8 +844,6 @@ export class StatsDatabase {
ELSE ip_stats.rules || ',' || @rule
END
`);
- // Store full chain path (joined with > for clarity)
- const fullChain = update.chains.join(' > ');
ipStmt.run({
backendId,
ip: update.ip,
@@ -868,7 +867,7 @@ export class StatsDatabase {
`);
proxyStmt.run({
backendId,
- chain: update.chain,
+ chain: fullChain,
upload: update.upload,
download: update.download,
timestamp
@@ -1001,7 +1000,7 @@ export class StatsDatabase {
domainProxyStmt.run({
backendId,
domain: domainName,
- chain: update.chain,
+ chain: fullChain,
upload: update.upload,
download: update.download,
timestamp
@@ -1027,7 +1026,7 @@ export class StatsDatabase {
ipProxyStmt.run({
backendId,
ip: update.ip,
- chain: update.chain,
+ chain: fullChain,
upload: update.upload,
download: update.download,
timestamp,
@@ -1080,13 +1079,14 @@ export class StatsDatabase {
const ruleName = update.chains.length > 1 ? update.chains[update.chains.length - 1] :
update.rulePayload ? `${update.rule}(${update.rulePayload})` : update.rule;
const finalProxy = update.chains.length > 0 ? update.chains[0] : 'DIRECT';
+ const fullChain = update.chains.join(' > ') || update.chain || 'DIRECT';
const eventDate = new Date(update.timestampMs ?? now.getTime());
const hourKey = this.toHourKey(eventDate);
const minuteKey = this.toMinuteKey(eventDate);
// Aggregate domain stats
if (update.domain) {
- const domainKey = `${update.domain}:${update.ip}:${update.chain}`;
+ const domainKey = `${update.domain}:${update.ip}:${fullChain}`;
const existing = domainMap.get(domainKey);
if (existing) {
existing.upload += update.upload;
@@ -1098,7 +1098,7 @@ export class StatsDatabase {
}
// Aggregate IP stats
- const ipKey = `${update.ip}:${update.domain}:${update.chain}`;
+ const ipKey = `${update.ip}:${update.domain}:${fullChain}`;
const existingIp = ipMap.get(ipKey);
if (existingIp) {
existingIp.upload += update.upload;
@@ -1109,7 +1109,7 @@ export class StatsDatabase {
}
// Aggregate chain stats
- const chainKey = update.chain;
+ const chainKey = fullChain;
const existingChain = chainMap.get(chainKey);
if (existingChain) {
existingChain.upload += update.upload;
@@ -1199,7 +1199,7 @@ export class StatsDatabase {
const dimDomain = update.domain || '';
const dimIP = update.ip || '';
const dimSourceIP = update.sourceIP || '';
- const dimChain = update.chain || 'DIRECT';
+ const dimChain = fullChain;
const dimKey = `${minuteKey}:${dimDomain}:${dimIP}:${dimSourceIP}:${dimChain}:${ruleName}`;
const existingDim = minuteDimMap.get(dimKey);
if (existingDim) {
@@ -1221,7 +1221,7 @@ export class StatsDatabase {
}
// Aggregate domain_proxy_stats (only when domain exists)
- const proxyChain = update.chain;
+ const proxyChain = fullChain;
if (update.domain) {
const dpKey = `${update.domain}:${proxyChain}`;
const existingDP = domainProxyMap.get(dpKey);
@@ -1783,6 +1783,35 @@ export class StatsDatabase {
return parts[0] || chain;
}
+ private aggregateProxyStatsByFirstHop(rows: ProxyStats[]): ProxyStats[] {
+ const merged = new Map<string, ProxyStats>();
+
+ for (const row of rows) {
+ const hop = this.getChainFirstHop(row.chain || "") || "DIRECT";
+ const existing = merged.get(hop);
+ if (existing) {
+ existing.totalUpload += row.totalUpload;
+ existing.totalDownload += row.totalDownload;
+ existing.totalConnections += row.totalConnections;
+ if (row.lastSeen > existing.lastSeen) {
+ existing.lastSeen = row.lastSeen;
+ }
+ } else {
+ merged.set(hop, {
+ chain: hop,
+ totalUpload: row.totalUpload,
+ totalDownload: row.totalDownload,
+ totalConnections: row.totalConnections,
+ lastSeen: row.lastSeen,
+ });
+ }
+ }
+
+ return Array.from(merged.values()).sort(
+ (a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload),
+ );
+ }
+
private allocateByWeights(total: number, weights: number[]): number[] {
if (weights.length === 0) return [];
const sum = weights.reduce((acc, w) => acc + w, 0);
@@ -1951,6 +1980,71 @@ export class StatsDatabase {
return [rule, ...reversed];
}
+ private uniqueNonEmpty(values: string[]): string[] {
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (const raw of values) {
+ const v = (raw || "").trim();
+ if (!v || seen.has(v)) continue;
+ seen.add(v);
+ out.push(v);
+ }
+ return out;
+ }
+
+ /**
+ * Some range queries aggregate from minute_dim_stats where historical rows may
+ * only contain the final proxy hop in `chain`. This method expands those
+ * short hops to full chains using rule_chain_traffic when possible.
+ */
+ private expandShortChainsForRules(
+ backendId: number,
+ chains: string[],
+ rules: string[],
+ ): string[] {
+ const normalizedChains = this.uniqueNonEmpty(chains);
+ if (normalizedChains.length === 0) return [];
+
+ const shortChains = normalizedChains.filter((c) => !c.includes(">"));
+ if (shortChains.length === 0) return normalizedChains;
+
+ const normalizedRules = this.uniqueNonEmpty(rules);
+ const whereParts: string[] = [];
+ const params: Array<string | number> = [backendId];
+
+ if (normalizedRules.length > 0) {
+ const rulePlaceholders = normalizedRules.map(() => "?").join(", ");
+ whereParts.push(`rule IN (${rulePlaceholders})`);
+ params.push(...normalizedRules);
+ }
+
+ const chainMatchers: string[] = [];
+ for (const chain of shortChains) {
+ chainMatchers.push("(chain = ? OR chain LIKE ?)");
+ params.push(chain, `${chain} > %`);
+ }
+ whereParts.push(`(${chainMatchers.join(" OR ")})`);
+
+ const whereClause = whereParts.length > 0 ? `AND ${whereParts.join(" AND ")}` : "";
+ const stmt = this.db.prepare(`
+ SELECT DISTINCT chain
+ FROM rule_chain_traffic
+ WHERE backend_id = ? ${whereClause}
+ LIMIT 500
+ `);
+
+ const rows = stmt.all(...params) as Array<{ chain: string }>;
+ const expanded = this.uniqueNonEmpty(rows.map((r) => r.chain));
+
+ if (expanded.length === 0) {
+ return normalizedChains;
+ }
+
+ // Prefer expanded full chains, but keep already-full values from input too.
+ const fullInputChains = normalizedChains.filter((c) => c.includes(">"));
+ return this.uniqueNonEmpty([...expanded, ...fullInputChains]);
+ }
+
// Get a specific domain by name
getDomainByName(backendId: number, domain: string): DomainStats | null {
const stmt = this.db.prepare(`
@@ -2016,12 +2110,16 @@ export class StatsDatabase {
chains: string | null;
}>;
- return rows.map(row => ({
- ...row,
- ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
- rules: row.rules ? row.rules.split(',').filter(Boolean) : [],
- chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
- })) as DomainStats[];
+ return rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ rules,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as DomainStats[];
}
const stmt = this.db.prepare(`
@@ -2043,12 +2141,16 @@ export class StatsDatabase {
chains: string | null;
}>;
- return rows.map(row => ({
- ...row,
- ips: row.ips ? row.ips.split(',') : [],
- rules: row.rules ? row.rules.split(',') : [],
- chains: row.chains ? row.chains.split(',') : [],
- })) as DomainStats[];
+ return rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ ips: row.ips ? row.ips.split(',') : [],
+ rules,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as DomainStats[];
}
// Get IP stats for specific IPs (used for domain IP details)
@@ -2113,9 +2215,26 @@ export class StatsDatabase {
start?: string,
end?: string,
limit = 100,
+ sourceIP?: string,
+ sourceChain?: string,
): IPStats[] {
const range = this.parseMinuteRange(start, end);
- if (range) {
+ if (range || sourceIP || sourceChain) {
+ const conditions = ["m.backend_id = ?", "m.domain = ?", "m.ip != ''"];
+ const params: Array<string | number> = [backendId, domain];
+ if (range) {
+ conditions.push("m.minute >= ?", "m.minute <= ?");
+ params.push(range.startMinute, range.endMinute);
+ }
+ if (sourceIP) {
+ conditions.push("m.source_ip = ?");
+ params.push(sourceIP);
+ }
+ if (sourceChain) {
+ conditions.push("(m.chain = ? OR m.chain LIKE ?)");
+ params.push(sourceChain, `${sourceChain} > %`);
+ }
+
const stmt = this.db.prepare(`
SELECT
m.ip,
@@ -2137,42 +2256,42 @@ export class StatsDatabase {
json(i.geoip)
ELSE
NULL
- END as geoIP,
- GROUP_CONCAT(DISTINCT m.chain) as chains
- FROM minute_dim_stats m
+ END as geoIP,
+ GROUP_CONCAT(DISTINCT m.chain) as chains,
+ GROUP_CONCAT(DISTINCT m.rule) as rules
+ FROM minute_dim_stats m
LEFT JOIN ip_stats i ON m.backend_id = i.backend_id AND m.ip = i.ip
LEFT JOIN geoip_cache g ON m.ip = g.ip
- WHERE m.backend_id = ? AND m.minute >= ? AND m.minute <= ? AND m.domain = ? AND m.ip != ''
+ WHERE ${conditions.join(" AND ")}
GROUP BY m.ip
ORDER BY (SUM(m.upload) + SUM(m.download)) DESC
LIMIT ?
`);
- const rows = stmt.all(
- backendId,
- range.startMinute,
- range.endMinute,
- domain,
- limit,
- ) as Array<{
+ const rows = stmt.all(...params, limit) as Array<{
ip: string;
domains: string;
totalUpload: number;
totalDownload: number;
totalConnections: number;
lastSeen: string;
- asn: string | null;
- geoIP: string | null;
- chains: string | null;
- }>;
-
- return rows.map(row => ({
- ...row,
- domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
- geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
- asn: row.asn || undefined,
- chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
- })) as IPStats[];
- }
+ asn: string | null;
+ geoIP: string | null;
+ chains: string | null;
+ rules: string | null;
+ }>;
+
+ return rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
+ geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
+ asn: row.asn || undefined,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as IPStats[];
+ }
const domainData = this.getDomainByName(backendId, domain);
if (!domainData || !domainData.ips || domainData.ips.length === 0) {
@@ -2181,6 +2300,77 @@ export class StatsDatabase {
return this.getIPStatsByIPs(backendId, domainData.ips.slice(0, limit));
}
+ // Get domain details for a specific IP (supports optional time range and sourceIP filter)
+ getIPDomainDetails(
+ backendId: number,
+ ip: string,
+ start?: string,
+ end?: string,
+ limit = 100,
+ sourceIP?: string,
+ sourceChain?: string,
+ ): DomainStats[] {
+ const range = this.parseMinuteRange(start, end);
+ const conditions = ["backend_id = ?", "ip = ?", "domain != ''"];
+ const params: Array<string | number> = [backendId, ip];
+
+ if (range) {
+ conditions.push("minute >= ?", "minute <= ?");
+ params.push(range.startMinute, range.endMinute);
+ }
+ if (sourceIP) {
+ conditions.push("source_ip = ?");
+ params.push(sourceIP);
+ }
+ if (sourceChain) {
+ conditions.push("(chain = ? OR chain LIKE ?)");
+ params.push(sourceChain, `${sourceChain} > %`);
+ }
+
+ const stmt = this.db.prepare(`
+ SELECT
+ domain,
+ GROUP_CONCAT(DISTINCT ip) as ips,
+ SUM(upload) as totalUpload,
+ SUM(download) as totalDownload,
+ SUM(connections) as totalConnections,
+ MAX(minute) as lastSeen,
+ GROUP_CONCAT(DISTINCT CASE WHEN rule != '' THEN rule END) as rules,
+ GROUP_CONCAT(DISTINCT chain) as chains
+ FROM minute_dim_stats
+ WHERE ${conditions.join(" AND ")}
+ GROUP BY domain
+ ORDER BY (SUM(upload) + SUM(download)) DESC
+ LIMIT ?
+ `);
+
+ const rows = stmt.all(...params, limit) as Array<{
+ domain: string;
+ ips: string | null;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ rules: string | null;
+ chains: string | null;
+ }>;
+
+ return rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ domain: row.domain,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ totalUpload: row.totalUpload,
+ totalDownload: row.totalDownload,
+ totalConnections: row.totalConnections,
+ lastSeen: row.lastSeen,
+ rules,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as DomainStats[];
+ }
+
// Get all IP stats for a specific backend
getIPStats(backendId: number, limit = 100, start?: string, end?: string): IPStats[] {
const range = this.parseMinuteRange(start, end);
@@ -2206,9 +2396,10 @@ export class StatsDatabase {
json(i.geoip)
ELSE
NULL
- END as geoIP,
- GROUP_CONCAT(DISTINCT m.chain) as chains
- FROM minute_dim_stats m
+ END as geoIP,
+ GROUP_CONCAT(DISTINCT m.chain) as chains,
+ GROUP_CONCAT(DISTINCT m.rule) as rules
+ FROM minute_dim_stats m
LEFT JOIN ip_stats i ON m.backend_id = i.backend_id AND m.ip = i.ip
LEFT JOIN geoip_cache g ON m.ip = g.ip
WHERE m.backend_id = ? AND m.minute >= ? AND m.minute <= ? AND m.ip != ''
@@ -2228,19 +2419,24 @@ export class StatsDatabase {
totalDownload: number;
totalConnections: number;
lastSeen: string;
- asn: string | null;
- geoIP: string | null;
- chains: string | null;
- }>;
-
- return rows.map(row => ({
- ...row,
- domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
- geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
- asn: row.asn || undefined,
- chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
- })) as IPStats[];
- }
+ asn: string | null;
+ geoIP: string | null;
+ chains: string | null;
+ rules: string | null;
+ }>;
+
+ return rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
+ geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
+ asn: row.asn || undefined,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as IPStats[];
+ }
const stmt = this.db.prepare(`
SELECT
@@ -2696,12 +2892,16 @@ export class StatsDatabase {
rules: string | null;
chains: string | null;
}>;
- return rows.map(row => ({
- ...row,
- ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
- rules: row.rules ? row.rules.split(',').filter(Boolean) : [],
- chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
- })) as DomainStats[];
+ return rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ rules,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as DomainStats[];
}
const stmt = this.db.prepare(`
@@ -2759,7 +2959,8 @@ export class StatsDatabase {
ELSE
NULL
END as geoIP,
- GROUP_CONCAT(DISTINCT m.chain) as chains
+ GROUP_CONCAT(DISTINCT m.chain) as chains,
+ GROUP_CONCAT(DISTINCT m.rule) as rules
FROM minute_dim_stats m
LEFT JOIN ip_stats i ON m.backend_id = i.backend_id AND m.ip = i.ip
LEFT JOIN geoip_cache g ON m.ip = g.ip
@@ -2780,19 +2981,24 @@ export class StatsDatabase {
totalDownload: number;
totalConnections: number;
lastSeen: string;
- domains: string | null;
- asn: string | null;
- geoIP: string | null;
- chains: string | null;
- }>;
- return rows.map(row => ({
- ...row,
- domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
- geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
- asn: row.asn || undefined,
- chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
- })) as IPStats[];
- }
+ domains: string | null;
+ asn: string | null;
+ geoIP: string | null;
+ chains: string | null;
+ rules: string | null;
+ }>;
+ return rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
+ geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
+ asn: row.asn || undefined,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as IPStats[];
+ }
const stmt = this.db.prepare(`
SELECT
@@ -2928,12 +3134,16 @@ export class StatsDatabase {
chains: string | null;
}>;
- const data = rows.map(row => ({
- ...row,
- ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
- rules: row.rules ? row.rules.split(',').filter(Boolean) : [],
- chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
- })) as DomainStats[];
+ const data = rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ rules,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as DomainStats[];
return { data, total };
}
@@ -2969,12 +3179,16 @@ export class StatsDatabase {
chains: string | null;
}>;
- const data = rows.map(row => ({
- ...row,
- ips: row.ips ? row.ips.split(',') : [],
- rules: row.rules ? row.rules.split(',') : [],
- chains: row.chains ? row.chains.split(',') : [],
- })) as DomainStats[];
+ const data = rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ ips: row.ips ? row.ips.split(',') : [],
+ rules,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as DomainStats[];
return { data, total };
}
@@ -3042,6 +3256,7 @@ export class StatsDatabase {
SELECT
ip,
GROUP_CONCAT(DISTINCT CASE WHEN domain != '' THEN domain END) as domains,
+ GROUP_CONCAT(DISTINCT rule) as rules,
SUM(upload) as totalUpload,
SUM(download) as totalDownload,
SUM(connections) as totalConnections,
@@ -3054,6 +3269,7 @@ export class StatsDatabase {
SELECT
agg.ip,
agg.domains,
+ agg.rules,
agg.totalUpload,
agg.totalDownload,
agg.totalConnections,
@@ -3088,6 +3304,7 @@ export class StatsDatabase {
) as Array<{
ip: string;
domains: string;
+ rules: string | null;
totalUpload: number;
totalDownload: number;
totalConnections: number;
@@ -3097,13 +3314,21 @@ export class StatsDatabase {
chains: string | null;
}>;
- const data = rows.map(row => ({
- ...row,
- domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
- geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
- asn: row.asn || undefined,
- chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
- })) as IPStats[];
+ const data = rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ip: row.ip,
+ domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
+ totalUpload: row.totalUpload,
+ totalDownload: row.totalDownload,
+ totalConnections: row.totalConnections,
+ lastSeen: row.lastSeen,
+ geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
+ asn: row.asn || undefined,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as IPStats[];
return { data, total };
}
@@ -3128,6 +3353,7 @@ export class StatsDatabase {
i.total_download as totalDownload,
i.total_connections as totalConnections,
i.last_seen as lastSeen,
+ i.rules,
COALESCE(i.asn, g.asn) as asn,
CASE
WHEN g.country IS NOT NULL THEN
@@ -3156,18 +3382,27 @@ export class StatsDatabase {
totalDownload: number;
totalConnections: number;
lastSeen: string;
+ rules: string | null;
asn: string | null;
geoIP: string | null;
chains: string | null;
}>;
- const data = rows.map(row => ({
- ...row,
- domains: row.domains ? row.domains.split(',') : [],
- geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
- asn: row.asn || undefined,
- chains: row.chains ? row.chains.split(',') : [],
- })) as IPStats[];
+ const data = rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ip: row.ip,
+ domains: row.domains ? row.domains.split(',') : [],
+ totalUpload: row.totalUpload,
+ totalDownload: row.totalDownload,
+ totalConnections: row.totalConnections,
+ lastSeen: row.lastSeen,
+ geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
+ asn: row.asn || undefined,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as IPStats[];
return { data, total };
}
@@ -3188,11 +3423,12 @@ export class StatsDatabase {
GROUP BY chain
ORDER BY (SUM(upload) + SUM(download)) DESC
`);
- return stmt.all(
+ const rows = stmt.all(
backendId,
range.startMinute,
range.endMinute,
) as ProxyStats[];
+ return this.aggregateProxyStatsByFirstHop(rows);
}
const stmt = this.db.prepare(`
@@ -3202,7 +3438,8 @@ export class StatsDatabase {
WHERE backend_id = ?
ORDER BY (total_upload + total_download) DESC
`);
- return stmt.all(backendId) as ProxyStats[];
+ const rows = stmt.all(backendId) as ProxyStats[];
+ return this.aggregateProxyStatsByFirstHop(rows);
}
// Get rule stats for a specific backend
@@ -3440,9 +3677,26 @@ export class StatsDatabase {
domain: string,
start?: string,
end?: string,
+ sourceIP?: string,
+ sourceChain?: string,
): ProxyTrafficStats[] {
const range = this.parseMinuteRange(start, end);
- if (range) {
+ if (range || sourceIP || sourceChain) {
+ const conditions = ["backend_id = ?", "domain = ?"];
+ const params: Array<string | number> = [backendId, domain];
+ if (range) {
+ conditions.push("minute >= ?", "minute <= ?");
+ params.push(range.startMinute, range.endMinute);
+ }
+ if (sourceIP) {
+ conditions.push("source_ip = ?");
+ params.push(sourceIP);
+ }
+ if (sourceChain) {
+ conditions.push("(chain = ? OR chain LIKE ?)");
+ params.push(sourceChain, `${sourceChain} > %`);
+ }
+
const stmt = this.db.prepare(`
SELECT
chain,
@@ -3450,16 +3704,11 @@ export class StatsDatabase {
SUM(download) as totalDownload,
SUM(connections) as totalConnections
FROM minute_dim_stats
- WHERE backend_id = ? AND minute >= ? AND minute <= ? AND domain = ?
+ WHERE ${conditions.join(" AND ")}
GROUP BY chain
ORDER BY (SUM(upload) + SUM(download)) DESC
`);
- return stmt.all(
- backendId,
- range.startMinute,
- range.endMinute,
- domain,
- ) as ProxyTrafficStats[];
+ return stmt.all(...params) as ProxyTrafficStats[];
}
const stmt = this.db.prepare(`
@@ -3480,9 +3729,26 @@ export class StatsDatabase {
ip: string,
start?: string,
end?: string,
+ sourceIP?: string,
+ sourceChain?: string,
): ProxyTrafficStats[] {
const range = this.parseMinuteRange(start, end);
- if (range) {
+ if (range || sourceIP || sourceChain) {
+ const conditions = ["backend_id = ?", "ip = ?"];
+ const params: Array<string | number> = [backendId, ip];
+ if (range) {
+ conditions.push("minute >= ?", "minute <= ?");
+ params.push(range.startMinute, range.endMinute);
+ }
+ if (sourceIP) {
+ conditions.push("source_ip = ?");
+ params.push(sourceIP);
+ }
+ if (sourceChain) {
+ conditions.push("(chain = ? OR chain LIKE ?)");
+ params.push(sourceChain, `${sourceChain} > %`);
+ }
+
const stmt = this.db.prepare(`
SELECT
chain,
@@ -3490,16 +3756,11 @@ export class StatsDatabase {
SUM(download) as totalDownload,
SUM(connections) as totalConnections
FROM minute_dim_stats
- WHERE backend_id = ? AND minute >= ? AND minute <= ? AND ip = ?
+ WHERE ${conditions.join(" AND ")}
GROUP BY chain
ORDER BY (SUM(upload) + SUM(download)) DESC
`);
- return stmt.all(
- backendId,
- range.startMinute,
- range.endMinute,
- ip,
- ) as ProxyTrafficStats[];
+ return stmt.all(...params) as ProxyTrafficStats[];
}
const stmt = this.db.prepare(`
@@ -3533,7 +3794,7 @@ export class StatsDatabase {
MAX(minute) as lastSeen,
GROUP_CONCAT(DISTINCT ip) as ips
FROM minute_dim_stats
- WHERE backend_id = ? AND minute >= ? AND minute <= ? AND chain = ? AND domain != ''
+ WHERE backend_id = ? AND minute >= ? AND minute <= ? AND (chain = ? OR chain LIKE ?) AND domain != ''
GROUP BY domain
ORDER BY (SUM(upload) + SUM(download)) DESC
LIMIT ?
@@ -3543,6 +3804,7 @@ export class StatsDatabase {
range.startMinute,
range.endMinute,
chain,
+ `${chain} > %`,
limit,
) as Array<{
domain: string;
@@ -3571,11 +3833,11 @@ export class StatsDatabase {
ds.ips
FROM domain_proxy_stats dps
LEFT JOIN domain_stats ds ON dps.backend_id = ds.backend_id AND dps.domain = ds.domain
- WHERE dps.backend_id = ? AND dps.chain = ?
+ WHERE dps.backend_id = ? AND (dps.chain = ? OR dps.chain LIKE ?)
ORDER BY (dps.total_upload + dps.total_download) DESC
LIMIT ?
`);
- const rows = stmt.all(backendId, chain, limit) as Array<{
+ const rows = stmt.all(backendId, chain, `${chain} > %`, limit) as Array<{
domain: string;
totalUpload: number;
totalDownload: number;
@@ -3627,7 +3889,7 @@ export class StatsDatabase {
FROM minute_dim_stats m
LEFT JOIN ip_stats i ON m.backend_id = i.backend_id AND m.ip = i.ip
LEFT JOIN geoip_cache g ON m.ip = g.ip
- WHERE m.backend_id = ? AND m.minute >= ? AND m.minute <= ? AND m.chain = ? AND m.ip != ''
+ WHERE m.backend_id = ? AND m.minute >= ? AND m.minute <= ? AND (m.chain = ? OR m.chain LIKE ?) AND m.ip != ''
GROUP BY m.ip
ORDER BY (SUM(m.upload) + SUM(m.download)) DESC
LIMIT ?
@@ -3637,6 +3899,7 @@ export class StatsDatabase {
range.startMinute,
range.endMinute,
chain,
+ `${chain} > %`,
limit,
) as Array<{
ip: string;
@@ -3667,11 +3930,11 @@ export class StatsDatabase {
ips.last_seen as lastSeen,
ips.domains
FROM ip_proxy_stats ips
- WHERE ips.backend_id = ? AND ips.chain = ? AND ips.ip != ''
+ WHERE ips.backend_id = ? AND (ips.chain = ? OR ips.chain LIKE ?) AND ips.ip != ''
ORDER BY (ips.total_upload + ips.total_download) DESC
LIMIT ?
`);
- const rows = stmt.all(backendId, chain, limit) as Array<{
+ const rows = stmt.all(backendId, chain, `${chain} > %`, limit) as Array<{
ip: string;
totalUpload: number;
totalDownload: number;
@@ -3760,16 +4023,19 @@ export class StatsDatabase {
chains: string | null;
}>;
- return rows.map(row => ({
- domain: row.domain,
- totalUpload: row.totalUpload,
- totalDownload: row.totalDownload,
- totalConnections: row.totalConnections,
- lastSeen: row.lastSeen,
- ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
- chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
- rules: [rule],
- })) as DomainStats[];
+ return rows.map(row => {
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ domain: row.domain,
+ totalUpload: row.totalUpload,
+ totalDownload: row.totalDownload,
+ totalConnections: row.totalConnections,
+ lastSeen: row.lastSeen,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ chains: this.expandShortChainsForRules(backendId, chains, [rule]),
+ rules: [rule],
+ };
+ }) as DomainStats[];
}
// Query rule_domain_traffic for accurate all-time per-rule domain traffic
@@ -3806,7 +4072,11 @@ export class StatsDatabase {
totalConnections: row.totalConnections,
lastSeen: row.lastSeen,
ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
- chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
+ chains: this.expandShortChainsForRules(
+ backendId,
+ row.chains ? row.chains.split(',').filter(Boolean) : [],
+ [rule],
+ ),
rules: [rule],
})) as DomainStats[];
}
@@ -3871,17 +4141,20 @@ export class StatsDatabase {
geoIPData: string | null;
}>;
- return rows.map(row => ({
- ip: row.ip,
- totalUpload: row.totalUpload,
- totalDownload: row.totalDownload,
- totalConnections: row.totalConnections,
- lastSeen: row.lastSeen,
- domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
- chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
- asn: row.asn || undefined,
- geoIP: row.geoIPData ? JSON.parse(row.geoIPData).filter(Boolean) : undefined,
- })) as IPStats[];
+ return rows.map(row => {
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ip: row.ip,
+ totalUpload: row.totalUpload,
+ totalDownload: row.totalDownload,
+ totalConnections: row.totalConnections,
+ lastSeen: row.lastSeen,
+ domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
+ chains: this.expandShortChainsForRules(backendId, chains, [rule]),
+ asn: row.asn || undefined,
+ geoIP: row.geoIPData ? JSON.parse(row.geoIPData).filter(Boolean) : undefined,
+ };
+ }) as IPStats[];
}
// Query rule_ip_traffic for accurate all-time per-rule IP traffic
@@ -3933,12 +4206,218 @@ export class StatsDatabase {
totalConnections: row.totalConnections,
lastSeen: row.lastSeen,
domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
- chains: row.chains ? row.chains.split(',').filter(Boolean) : [],
+ chains: this.expandShortChainsForRules(
+ backendId,
+ row.chains ? row.chains.split(',').filter(Boolean) : [],
+ [rule],
+ ),
asn: row.asn || undefined,
geoIP: row.geoIPData ? JSON.parse(row.geoIPData).filter(Boolean) : undefined,
})) as IPStats[];
}
+ // Get per-proxy traffic breakdown for a specific domain under a specific rule
+ getRuleDomainProxyStats(
+ backendId: number,
+ rule: string,
+ domain: string,
+ start?: string,
+ end?: string,
+ ): ProxyTrafficStats[] {
+ const range = this.parseMinuteRange(start, end);
+ if (range) {
+ const stmt = this.db.prepare(`
+ SELECT
+ chain,
+ SUM(upload) as totalUpload,
+ SUM(download) as totalDownload,
+ SUM(connections) as totalConnections
+ FROM minute_dim_stats
+ WHERE backend_id = ? AND minute >= ? AND minute <= ? AND rule = ? AND domain = ?
+ GROUP BY chain
+ ORDER BY (SUM(upload) + SUM(download)) DESC
+ `);
+ return stmt.all(
+ backendId,
+ range.startMinute,
+ range.endMinute,
+ rule,
+ domain,
+ ) as ProxyTrafficStats[];
+ }
+
+ return [];
+ }
+
+ // Get IP details for a specific domain under a specific rule
+ getRuleDomainIPDetails(
+ backendId: number,
+ rule: string,
+ domain: string,
+ start?: string,
+ end?: string,
+ limit = 100,
+ ): IPStats[] {
+ const range = this.parseMinuteRange(start, end);
+ const conditions = ["m.backend_id = ?", "m.rule = ?", "m.domain = ?", "m.ip != ''"];
+ const params: Array<string | number> = [backendId, rule, domain];
+
+ if (range) {
+ conditions.push("m.minute >= ?", "m.minute <= ?");
+ params.push(range.startMinute, range.endMinute);
+ }
+
+ const stmt = this.db.prepare(`
+ SELECT
+ m.ip,
+ GROUP_CONCAT(DISTINCT CASE WHEN m.domain != '' THEN m.domain END) as domains,
+ SUM(m.upload) as totalUpload,
+ SUM(m.download) as totalDownload,
+ SUM(m.connections) as totalConnections,
+ MAX(m.minute) as lastSeen,
+ COALESCE(i.asn, g.asn) as asn,
+ CASE
+ WHEN g.country IS NOT NULL THEN
+ json_array(
+ g.country,
+ COALESCE(g.country_name, g.country),
+ COALESCE(g.city, ''),
+ COALESCE(g.as_name, '')
+ )
+ WHEN i.geoip IS NOT NULL THEN
+ json(i.geoip)
+ ELSE
+ NULL
+ END as geoIP,
+ GROUP_CONCAT(DISTINCT m.chain) as chains
+ FROM minute_dim_stats m
+ LEFT JOIN ip_stats i ON m.backend_id = i.backend_id AND m.ip = i.ip
+ LEFT JOIN geoip_cache g ON m.ip = g.ip
+ WHERE ${conditions.join(" AND ")}
+ GROUP BY m.ip
+ ORDER BY (SUM(m.upload) + SUM(m.download)) DESC
+ LIMIT ?
+ `);
+
+ const rows = stmt.all(...params, limit) as Array<{
+ ip: string;
+ domains: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ asn: string | null;
+ geoIP: string | null;
+ chains: string | null;
+ }>;
+
+ return rows.map(row => {
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ ...row,
+ domains: row.domains ? row.domains.split(',').filter(Boolean) : [],
+ geoIP: row.geoIP ? JSON.parse(row.geoIP).filter(Boolean) : undefined,
+ asn: row.asn || undefined,
+ chains: this.expandShortChainsForRules(backendId, chains, [rule]),
+ };
+ }) as IPStats[];
+ }
+
+ // Get per-proxy traffic breakdown for a specific IP under a specific rule
+ getRuleIPProxyStats(
+ backendId: number,
+ rule: string,
+ ip: string,
+ start?: string,
+ end?: string,
+ ): ProxyTrafficStats[] {
+ const range = this.parseMinuteRange(start, end);
+ if (range) {
+ const stmt = this.db.prepare(`
+ SELECT
+ chain,
+ SUM(upload) as totalUpload,
+ SUM(download) as totalDownload,
+ SUM(connections) as totalConnections
+ FROM minute_dim_stats
+ WHERE backend_id = ? AND minute >= ? AND minute <= ? AND rule = ? AND ip = ?
+ GROUP BY chain
+ ORDER BY (SUM(upload) + SUM(download)) DESC
+ `);
+ return stmt.all(
+ backendId,
+ range.startMinute,
+ range.endMinute,
+ rule,
+ ip,
+ ) as ProxyTrafficStats[];
+ }
+
+ return [];
+ }
+
+ // Get domain details for a specific IP under a specific rule
+ getRuleIPDomainDetails(
+ backendId: number,
+ rule: string,
+ ip: string,
+ start?: string,
+ end?: string,
+ limit = 100,
+ ): DomainStats[] {
+ const range = this.parseMinuteRange(start, end);
+ const conditions = ["backend_id = ?", "rule = ?", "ip = ?", "domain != ''"];
+ const params: Array<string | number> = [backendId, rule, ip];
+
+ if (range) {
+ conditions.push("minute >= ?", "minute <= ?");
+ params.push(range.startMinute, range.endMinute);
+ }
+
+ const stmt = this.db.prepare(`
+ SELECT
+ domain,
+ GROUP_CONCAT(DISTINCT ip) as ips,
+ SUM(upload) as totalUpload,
+ SUM(download) as totalDownload,
+ SUM(connections) as totalConnections,
+ MAX(minute) as lastSeen,
+ GROUP_CONCAT(DISTINCT CASE WHEN rule != '' THEN rule END) as rules,
+ GROUP_CONCAT(DISTINCT chain) as chains
+ FROM minute_dim_stats
+ WHERE ${conditions.join(" AND ")}
+ GROUP BY domain
+ ORDER BY (SUM(upload) + SUM(download)) DESC
+ LIMIT ?
+ `);
+
+ const rows = stmt.all(...params, limit) as Array<{
+ domain: string;
+ ips: string | null;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+ rules: string | null;
+ chains: string | null;
+ }>;
+
+ return rows.map(row => {
+ const rules = row.rules ? row.rules.split(',').filter(Boolean) : [];
+ const chains = row.chains ? row.chains.split(',').filter(Boolean) : [];
+ return {
+ domain: row.domain,
+ ips: row.ips ? row.ips.split(',').filter(Boolean) : [],
+ totalUpload: row.totalUpload,
+ totalDownload: row.totalDownload,
+ totalConnections: row.totalConnections,
+ lastSeen: row.lastSeen,
+ rules,
+ chains: this.expandShortChainsForRules(backendId, chains, rules),
+ };
+ }) as DomainStats[];
+ }
+
// Get rule chain flow for visualization
getRuleChainFlow(
backendId: number,
diff --git a/apps/web/components/domains-table.tsx b/apps/web/components/domains-table.tsx
index 5e69e4d..6b29cad 100644
--- a/apps/web/components/domains-table.tsx
+++ b/apps/web/components/domains-table.tsx
@@ -1,12 +1,13 @@
"use client";
import { useState, useCallback, useEffect, useRef } from "react";
-import { Search, ArrowUpDown, ArrowDown, ArrowUp, ChevronLeft, ChevronRight, Rows3, ChevronDown, ChevronUp, Globe, Server, Waypoints, Loader2 } from "lucide-react";
+import { Search, ArrowUpDown, ArrowDown, ArrowUp, ChevronLeft, ChevronRight, Rows3, ChevronDown, ChevronUp, Server, Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Favicon } from "@/components/favicon";
-import { CountryFlag } from "@/components/country-flag";
+import { DomainExpandedDetails } from "@/components/stats-tables/expanded-details";
+import { ProxyChainBadge } from "@/components/proxy-chain-badge";
import { formatBytes, formatNumber, formatDuration } from "@/lib/utils";
import { cn } from "@/lib/utils";
import type { DomainStats, ProxyTrafficStats, IPStats } from "@clashmaster/shared";
@@ -17,12 +18,6 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip";
interface DomainsTableProps {
activeBackendId?: number;
@@ -35,22 +30,6 @@ type SortOrder = "asc" | "desc";
const PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const;
type PageSize = typeof PAGE_SIZE_OPTIONS[number];
-// Generate gradient based on IP
-const getIPGradient = (ip: string) => {
- const colors = [
- "from-emerald-500 to-teal-400",
- "from-blue-500 to-cyan-400",
- "from-violet-500 to-purple-400",
- "from-orange-500 to-amber-400",
- "from-rose-500 to-pink-400",
- ];
- let hash = 0;
- for (let i = 0; i < ip.length; i++) {
- hash = ip.charCodeAt(i) + ((hash << 5) - hash);
- }
- return colors[Math.abs(hash) % colors.length];
-};
-
export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps) {
const t = useTranslations("domains");
const [data, setData] = useState<DomainStats[]>([]);
@@ -112,15 +91,24 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)
}, [activeBackendId, currentPage, pageSize, sortKey, sortOrder, debouncedSearch, timeRange]);
useEffect(() => {
+ // Backend switch means a different data universe, collapse safely.
setExpandedDomain(null);
setProxyStats({});
setIPDetails({});
- }, [activeBackendId, timeRange]);
+ }, [activeBackendId]);
// Fetch proxy stats when a domain is expanded
- const fetchProxyStats = useCallback(async (domain: string) => {
- if (proxyStats[domain]) return;
- setProxyStatsLoading(domain);
+ const fetchProxyStats = useCallback(async (
+ domain: string,
+ options?: { force?: boolean; background?: boolean },
+ ) => {
+ const force = options?.force ?? false;
+ const background = options?.background ?? false;
+ const hasCached = !!proxyStats[domain];
+ if (!force && hasCached) return;
+ if (!background || !hasCached) {
+ setProxyStatsLoading(domain);
+ }
try {
const stats = await api.getDomainProxyStats(
domain,
@@ -132,14 +120,24 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)
console.error(`Failed to fetch proxy stats for ${domain}:`, err);
setProxyStats(prev => ({ ...prev, [domain]: [] }));
} finally {
- setProxyStatsLoading(null);
+ if (proxyStatsLoading === domain) {
+ setProxyStatsLoading(null);
+ }
}
- }, [proxyStats, activeBackendId, timeRange]);
+ }, [proxyStats, activeBackendId, timeRange, proxyStatsLoading]);
// Fetch IP details when a domain is expanded
- const fetchIPDetails = useCallback(async (domain: string) => {
- if (ipDetails[domain]) return;
- setIPDetailsLoading(domain);
+ const fetchIPDetails = useCallback(async (
+ domain: string,
+ options?: { force?: boolean; background?: boolean },
+ ) => {
+ const force = options?.force ?? false;
+ const background = options?.background ?? false;
+ const hasCached = !!ipDetails[domain];
+ if (!force && hasCached) return;
+ if (!background || !hasCached) {
+ setIPDetailsLoading(domain);
+ }
try {
const details = await api.getDomainIPDetails(
domain,
@@ -151,9 +149,23 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)
console.error(`Failed to fetch IP details for ${domain}:`, err);
setIPDetails(prev => ({ ...prev, [domain]: [] }));
} finally {
- setIPDetailsLoading(null);
+ if (ipDetailsLoading === domain) {
+ setIPDetailsLoading(null);
+ }
}
- }, [ipDetails, activeBackendId, timeRange]);
+ }, [ipDetails, activeBackendId, timeRange, ipDetailsLoading]);
+
+ useEffect(() => {
+ if (!expandedDomain) return;
+ fetchProxyStats(expandedDomain);
+ fetchIPDetails(expandedDomain);
+ }, [expandedDomain, fetchProxyStats, fetchIPDetails]);
+
+ useEffect(() => {
+ if (!expandedDomain) return;
+ fetchProxyStats(expandedDomain, { force: true, background: true });
+ fetchIPDetails(expandedDomain, { force: true, background: true });
+ }, [timeRange?.start, timeRange?.end, expandedDomain, fetchProxyStats, fetchIPDetails]);
const handleSort = (key: SortKey) => {
if (sortKey === key) {
@@ -324,11 +336,6 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)
) : (
data.map((domain, index) => {
const isExpanded = expandedDomain === domain.domain;
- const fullChain = domain.chains && domain.chains.length > 0 ? domain.chains[0] : "";
- const lastProxy = fullChain ? fullChain.split(" > ").pop()?.trim() || fullChain : "";
- const chainTooltip = domain.chains && domain.chains.length > 0
- ? domain.chains.map((chain, idx) => (idx === 0 ? chain : `(${idx + 1}) ${chain}`)).join("\n")
- : "";
return (
<div key={domain.domain} className="group">
@@ -353,35 +360,7 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)
{/* Proxy */}
<div className="col-span-2 flex items-center gap-1.5 min-w-0">
- {domain.chains && domain.chains.length > 0 ? (
- <TooltipProvider delayDuration={300}>
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="inline-flex items-center gap-1.5 min-w-0">
- <span
- className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-[11px] font-medium truncate max-w-[120px]"
- >
- <Waypoints className="h-2.5 w-2.5 shrink-0" />
- {lastProxy}
- </span>
- {domain.chains.length > 1 && (
- <span className="text-[11px] text-muted-foreground shrink-0">
- +{domain.chains.length - 1}
- </span>
- )}
- </span>
- </TooltipTrigger>
- <TooltipContent
- side="top"
- className="max-w-[360px] whitespace-pre-wrap"
- >
- {chainTooltip}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- ) : (
- <span className="text-xs text-muted-foreground">-</span>
- )}
+ <ProxyChainBadge chains={domain.chains} />
</div>
{/* Download */}
@@ -474,31 +453,7 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)
{/* Row 2: Proxy tag - full width, no truncation */}
{domain.chains && domain.chains.length > 0 && (
<div className="flex items-center gap-1.5 mb-2 pl-[30px]">
- <TooltipProvider delayDuration={300}>
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="inline-flex items-center gap-1.5">
- <span
- className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-[11px] font-medium whitespace-nowrap"
- >
- <Waypoints className="h-2.5 w-2.5 shrink-0" />
- {lastProxy}
- </span>
- {domain.chains.length > 1 && (
- <span className="text-[11px] text-muted-foreground shrink-0">
- +{domain.chains.length - 1}
- </span>
- )}
- </span>
- </TooltipTrigger>
- <TooltipContent
- side="top"
- className="max-w-[360px] whitespace-pre-wrap"
- >
- {chainTooltip}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
+ <ProxyChainBadge chains={domain.chains} truncateLabel={false} />
</div>
)}
@@ -514,166 +469,18 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)
{/* Expanded Details: Proxy Traffic + IP List */}
{isExpanded && (
- <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
- <div className="pt-3 grid grid-cols-1 sm:grid-cols-2 gap-4">
- {/* Proxy Traffic Breakdown */}
- <div className="px-1">
- <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
- <Waypoints className="h-3 w-3" />
- {t("proxyTraffic")}
- </p>
- {proxyStatsLoading === domain.domain ? (
- <div className="flex items-center justify-center py-4">
- <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
- </div>
- ) : (proxyStats[domain.domain] && proxyStats[domain.domain].length > 0) ? (
- <div className="space-y-2">
- {proxyStats[domain.domain].map((ps) => {
- const totalTraffic = domain.totalDownload + domain.totalUpload;
- const proxyTraffic = ps.totalDownload + ps.totalUpload;
- const percent = totalTraffic > 0 ? (proxyTraffic / totalTraffic) * 100 : 0;
- const proxyTotal = ps.totalDownload + ps.totalUpload;
- const downloadPercent = proxyTotal > 0 ? (ps.totalDownload / proxyTotal) * 100 : 0;
- const uploadPercent = proxyTotal > 0 ? (ps.totalUpload / proxyTotal) * 100 : 0;
- return (
- <div
- key={ps.chain}
- className="px-3 py-2 rounded-lg bg-card border border-border/50"
- >
- <div className="flex items-center justify-between mb-1.5">
- <span className="inline-flex items-center gap-1.5 text-xs font-medium truncate max-w-[60%]" title={ps.chain}>
- <Waypoints className="h-3 w-3 text-orange-500 shrink-0" />
- {ps.chain}
- </span>
- <span className="text-[11px] text-muted-foreground tabular-nums shrink-0">
- {percent.toFixed(1)}%
- </span>
- </div>
- <div className="w-full h-1.5 rounded-full bg-secondary/80 mb-1.5 overflow-hidden flex">
- {/* Download portion - blue */}
- <div
- className="h-full bg-blue-500 transition-all"
- style={{ width: `${Math.max(percent * (downloadPercent / 100), 0.5)}%` }}
- />
- {/* Upload portion - purple */}
- <div
- className="h-full bg-purple-500 transition-all"
- style={{ width: `${Math.max(percent * (uploadPercent / 100), 0.5)}%` }}
- />
- </div>
- <div className="flex flex-wrap items-center gap-2 sm:gap-3 text-[11px] tabular-nums">
- <span className="text-blue-500">↓ {formatBytes(ps.totalDownload)}</span>
- <span className="text-purple-500">↑ {formatBytes(ps.totalUpload)}</span>
- <span className="text-muted-foreground">{formatNumber(ps.totalConnections)} {t("conn")}</span>
- </div>
- </div>
- );
- })}
- </div>
- ) : (
- <div className="flex flex-wrap gap-1.5">
- {domain.chains.map((chain) => (
- <span
- key={chain}
- className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-xs font-medium max-w-full min-w-0"
- title={chain}
- >
- <Waypoints className="h-3 w-3 shrink-0" />
- <span className="truncate min-w-0">
- {chain}
- </span>
- </span>
- ))}
- </div>
- )}
- </div>
-
- {/* Associated IPs */}
- <div className="px-1">
- <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
- <Globe className="h-3 w-3" />
- {t("associatedIPs")}
- </p>
- {ipDetailsLoading === domain.domain ? (
- <div className="flex items-center justify-center py-4">
- <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
- </div>
- ) : (ipDetails[domain.domain] && ipDetails[domain.domain].length > 0) ? (
- <div className="space-y-2">
- {(() => {
- const totalIPTraffic = ipDetails[domain.domain].reduce((sum, ip) => sum + ip.totalDownload + ip.totalUpload, 0);
- return ipDetails[domain.domain].map((ipStat) => {
- const country = ipStat.geoIP?.[0];
- const location = ipStat.geoIP && ipStat.geoIP.length > 1
- ? ipStat.geoIP[1]
- : ipStat.geoIP?.[0] || null;
- const ipTraffic = ipStat.totalDownload + ipStat.totalUpload;
- const percent = totalIPTraffic > 0 ? (ipTraffic / totalIPTraffic) * 100 : 0;
- const downloadPercent = ipTraffic > 0 ? (ipStat.totalDownload / ipTraffic) * 100 : 0;
- const uploadPercent = ipTraffic > 0 ? (ipStat.totalUpload / ipTraffic) * 100 : 0;
- return (
- <div
- key={ipStat.ip}
- className="px-3 py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
- >
- <div className="flex items-center justify-between mb-1.5">
- <div className="flex items-center gap-1.5">
- <Waypoints className="h-3 w-3 text-orange-500 shrink-0" />
- <code className="text-xs font-mono">{ipStat.ip}</code>
- </div>
- <span className="text-[11px] text-muted-foreground tabular-nums shrink-0">
- {percent.toFixed(1)}%
- </span>
- </div>
- <div className="w-full h-1.5 rounded-full bg-secondary/80 mb-1.5 overflow-hidden flex">
- <div
- className="h-full bg-blue-500 transition-all"
- style={{ width: `${Math.max(percent * (downloadPercent / 100), 0.5)}%` }}
- />
- <div
- className="h-full bg-purple-500 transition-all"
- style={{ width: `${Math.max(percent * (uploadPercent / 100), 0.5)}%` }}
- />
- </div>
- <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-0">
- <div className="flex flex-wrap items-center gap-2 sm:gap-3 text-[11px] tabular-nums">
- <span className="text-blue-500">↓ {formatBytes(ipStat.totalDownload)}</span>
- <span className="text-purple-500">↑ {formatBytes(ipStat.totalUpload)}</span>
- <span className="text-muted-foreground">{formatNumber(ipStat.totalConnections)} conn</span>
- </div>
- {location && (
- <span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground">
- <CountryFlag country={country} className="h-3 w-4" />
- <span>{location}</span>
- </span>
- )}
- </div>
- </div>
- );
- });
- })()}
- </div>
- ) : (
- <div className="flex flex-wrap gap-2">
- {domain.ips.map((ip) => {
- const gradient = getIPGradient(ip);
- return (
- <div
- key={ip}
- className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
- >
- <div className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md bg-gradient-to-br ${gradient} flex items-center justify-center shrink-0`}>
- <Server className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-white" />
- </div>
- <code className="text-xs font-mono break-all">{ip}</code>
- </div>
- );
- })}
- </div>
- )}
- </div>
- </div>
- </div>
+ <DomainExpandedDetails
+ domain={domain}
+ proxyStats={proxyStats[domain.domain]}
+ proxyStatsLoading={proxyStatsLoading === domain.domain}
+ ipDetails={ipDetails[domain.domain]}
+ ipDetailsLoading={ipDetailsLoading === domain.domain}
+ labels={{
+ proxyTraffic: t("proxyTraffic"),
+ associatedIPs: t("associatedIPs"),
+ conn: t("conn"),
+ }}
+ />
)}
</div>
);
diff --git a/apps/web/components/interactive-device-stats.tsx b/apps/web/components/interactive-device-stats.tsx
index d5b4f10..3049860 100644
--- a/apps/web/components/interactive-device-stats.tsx
+++ b/apps/web/components/interactive-device-stats.tsx
@@ -312,10 +312,24 @@ export function InteractiveDeviceStats({
<TabsTrigger value="ips">IP Addresses</TabsTrigger>
</TabsList>
<TabsContent value="domains" className="mt-4">
- <DomainStatsTable domains={deviceDomains} loading={loading} />
+ <DomainStatsTable
+ domains={deviceDomains}
+ loading={loading}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ sourceIP={selectedDevice ?? undefined}
+ richExpand
+ />
</TabsContent>
<TabsContent value="ips" className="mt-4">
- <IPStatsTable ips={deviceIPs} loading={loading} />
+ <IPStatsTable
+ ips={deviceIPs}
+ loading={loading}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ sourceIP={selectedDevice ?? undefined}
+ richExpand
+ />
</TabsContent>
</Tabs>
)}
diff --git a/apps/web/components/interactive-proxy-stats.tsx b/apps/web/components/interactive-proxy-stats.tsx
index 5648109..4e1b4b3 100644
--- a/apps/web/components/interactive-proxy-stats.tsx
+++ b/apps/web/components/interactive-proxy-stats.tsx
@@ -24,10 +24,15 @@ interface InteractiveProxyStatsProps {
}
function normalizeProxyName(name: string): string {
- return name
+ const normalized = name
.trim()
.replace(/^\["?/, "")
.replace(/"?\]$/, "");
+ const parts = normalized
+ .split(">")
+ .map((part) => part.trim())
+ .filter(Boolean);
+ return parts[0] || normalized;
}
function simplifyProxyName(name: string): string {
@@ -345,10 +350,28 @@ export function InteractiveProxyStats({
<TabsTrigger value="ips">IP Addresses</TabsTrigger>
</TabsList>
<TabsContent value="domains" className="mt-4">
- <DomainStatsTable domains={proxyDomains} loading={loading} />
+ <DomainStatsTable
+ domains={proxyDomains}
+ loading={loading}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ sourceChain={selectedProxy}
+ richExpand
+ showProxyColumn={false}
+ showProxyTrafficInExpand={false}
+ />
</TabsContent>
<TabsContent value="ips" className="mt-4">
- <IPStatsTable ips={proxyIPs} loading={loading} />
+ <IPStatsTable
+ ips={proxyIPs}
+ loading={loading}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ sourceChain={selectedProxy}
+ richExpand
+ showProxyColumn={false}
+ showProxyTrafficInExpand={false}
+ />
</TabsContent>
</Tabs>
)}
diff --git a/apps/web/components/interactive-rule-stats.tsx b/apps/web/components/interactive-rule-stats.tsx
index 4d31428..faa61e1 100644
--- a/apps/web/components/interactive-rule-stats.tsx
+++ b/apps/web/components/interactive-rule-stats.tsx
@@ -21,8 +21,10 @@ import { cn } from "@/lib/utils";
import { api, type ClashRulesResponse, type TimeRange } from "@/lib/api";
import { CountryFlag } from "@/components/country-flag";
import { Favicon } from "@/components/favicon";
+import { ProxyChainBadge } from "@/components/proxy-chain-badge";
+import { DomainExpandedDetails, IPExpandedDetails } from "@/components/stats-tables/expanded-details";
import { UnifiedRuleChainFlow } from "@/components/rule-chain-flow";
-import type { RuleStats, DomainStats, IPStats } from "@clashmaster/shared";
+import type { RuleStats, DomainStats, IPStats, ProxyTrafficStats } from "@clashmaster/shared";
interface InteractiveRuleStatsProps {
data: RuleStats[];
@@ -44,22 +46,6 @@ const CHART_COLORS = [
const PAGE_SIZE_OPTIONS = [10, 20, 50] as const;
type PageSize = typeof PAGE_SIZE_OPTIONS[number];
-// Generate gradient based on IP - same as DomainsTable
-const getIPGradient = (ip: string) => {
- const colors = [
- "from-emerald-500 to-teal-400",
- "from-blue-500 to-cyan-400",
- "from-violet-500 to-purple-400",
- "from-orange-500 to-amber-400",
- "from-rose-500 to-pink-400",
- ];
- let hash = 0;
- for (let i = 0; i < ip.length; i++) {
- hash = ip.charCodeAt(i) + ((hash << 5) - hash);
- }
- return colors[Math.abs(hash) % colors.length];
-};
-
// Domain sort keys
type DomainSortKey = "domain" | "totalDownload" | "totalUpload" | "totalConnections";
type SortOrder = "asc" | "desc";
@@ -79,14 +65,6 @@ const ICON_COLORS = [
{ bg: "bg-teal-500", text: "text-white" },
];
-const getDomainColor = (domain: string) => {
- let hash = 0;
- for (let i = 0; i < domain.length; i++) {
- hash = domain.charCodeAt(i) + ((hash << 5) - hash);
- }
- return ICON_COLORS[Math.abs(hash) % ICON_COLORS.length];
-};
-
const getIPColor = (ip: string) => {
let hash = 0;
for (let i = 0; i < ip.length; i++) {
@@ -149,6 +127,14 @@ export function InteractiveRuleStats({
// Expanded states
const [expandedDomain, setExpandedDomain] = useState<string | null>(null);
const [expandedIP, setExpandedIP] = useState<string | null>(null);
+ const [domainProxyStats, setDomainProxyStats] = useState<Record<string, ProxyTrafficStats[]>>({});
+ const [domainProxyStatsLoading, setDomainProxyStatsLoading] = useState<string | null>(null);
+ const [domainIPDetails, setDomainIPDetails] = useState<Record<string, IPStats[]>>({});
+ const [domainIPDetailsLoading, setDomainIPDetailsLoading] = useState<string | null>(null);
+ const [ipProxyStats, setIPProxyStats] = useState<Record<string, ProxyTrafficStats[]>>({});
+ const [ipProxyStatsLoading, setIPProxyStatsLoading] = useState<string | null>(null);
+ const [ipDomainDetails, setIPDomainDetails] = useState<Record<string, DomainStats[]>>({});
+ const [ipDomainDetailsLoading, setIPDomainDetailsLoading] = useState<string | null>(null);
const requestIdRef = useRef(0);
const prevSelectedRuleRef = useRef<string | null>(null);
const prevBackendRef = useRef<number | undefined>(undefined);
@@ -260,13 +246,97 @@ export function InteractiveRuleStats({
// Toggle expand handlers
const toggleExpandDomain = (domain: string) => {
- setExpandedDomain(expandedDomain === domain ? null : domain);
+ const newExpanded = expandedDomain === domain ? null : domain;
+ setExpandedDomain(newExpanded);
+ if (newExpanded) {
+ fetchExpandedDomainDetails(newExpanded);
+ }
};
const toggleExpandIP = (ip: string) => {
- setExpandedIP(expandedIP === ip ? null : ip);
+ const newExpanded = expandedIP === ip ? null : ip;
+ setExpandedIP(newExpanded);
+ if (newExpanded) {
+ fetchExpandedIPDetails(newExpanded);
+ }
};
+ const fetchExpandedDomainDetails = useCallback(async (
+ domain: string,
+ options?: { force?: boolean; background?: boolean },
+ ) => {
+ if (!selectedRule) return;
+ const force = options?.force ?? false;
+ const background = options?.background ?? false;
+ const hasProxyCached = !!domainProxyStats[domain];
+ const hasIPCached = !!domainIPDetails[domain];
+ if (!force && hasProxyCached && hasIPCached) return;
+
+ if (!background || !hasProxyCached) setDomainProxyStatsLoading(domain);
+ if (!background || !hasIPCached) setDomainIPDetailsLoading(domain);
+ try {
+ const [proxyStats, ipDetails] = await Promise.all([
+ api.getRuleDomainProxyStats(selectedRule, domain, activeBackendId, timeRange),
+ api.getRuleDomainIPDetails(selectedRule, domain, activeBackendId, timeRange),
+ ]);
+ setDomainProxyStats((prev) => ({ ...prev, [domain]: proxyStats }));
+ setDomainIPDetails((prev) => ({ ...prev, [domain]: ipDetails }));
+ } catch (err) {
+ console.error(`Failed to fetch rule-domain details for ${domain}:`, err);
+ setDomainProxyStats((prev) => ({ ...prev, [domain]: [] }));
+ setDomainIPDetails((prev) => ({ ...prev, [domain]: [] }));
+ } finally {
+ if (domainProxyStatsLoading === domain) setDomainProxyStatsLoading(null);
+ if (domainIPDetailsLoading === domain) setDomainIPDetailsLoading(null);
+ }
+ }, [
+ selectedRule,
+ domainProxyStats,
+ domainIPDetails,
+ activeBackendId,
+ timeRange,
+ domainProxyStatsLoading,
+ domainIPDetailsLoading,
+ ]);
+
+ const fetchExpandedIPDetails = useCallback(async (
+ ip: string,
+ options?: { force?: boolean; background?: boolean },
+ ) => {
+ if (!selectedRule) return;
+ const force = options?.force ?? false;
+ const background = options?.background ?? false;
+ const hasProxyCached = !!ipProxyStats[ip];
+ const hasDomainCached = !!ipDomainDetails[ip];
+ if (!force && hasProxyCached && hasDomainCached) return;
+
+ if (!background || !hasProxyCached) setIPProxyStatsLoading(ip);
+ if (!background || !hasDomainCached) setIPDomainDetailsLoading(ip);
+ try {
+ const [proxyStats, domainDetails] = await Promise.all([
+ api.getRuleIPProxyStats(selectedRule, ip, activeBackendId, timeRange),
+ api.getRuleIPDomainDetails(selectedRule, ip, activeBackendId, timeRange),
+ ]);
+ setIPProxyStats((prev) => ({ ...prev, [ip]: proxyStats }));
+ setIPDomainDetails((prev) => ({ ...prev, [ip]: domainDetails }));
+ } catch (err) {
+ console.error(`Failed to fetch rule-ip details for ${ip}:`, err);
+ setIPProxyStats((prev) => ({ ...prev, [ip]: [] }));
+ setIPDomainDetails((prev) => ({ ...prev, [ip]: [] }));
+ } finally {
+ if (ipProxyStatsLoading === ip) setIPProxyStatsLoading(null);
+ if (ipDomainDetailsLoading === ip) setIPDomainDetailsLoading(null);
+ }
+ }, [
+ selectedRule,
+ ipProxyStats,
+ ipDomainDetails,
+ activeBackendId,
+ timeRange,
+ ipProxyStatsLoading,
+ ipDomainDetailsLoading,
+ ]);
+
// Sort icon component
const DomainSortIcon = ({ column }: { column: DomainSortKey }) => {
if (domainSortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
@@ -357,6 +427,35 @@ export function InteractiveRuleStats({
}
}, [selectedRule, activeBackendId, timeRange, loadRuleDetails, ruleDomains.length, ruleIPs.length, loading]);
+ useEffect(() => {
+ setExpandedDomain(null);
+ setExpandedIP(null);
+ setDomainProxyStats({});
+ setDomainIPDetails({});
+ setIPProxyStats({});
+ setIPDomainDetails({});
+ setDomainProxyStatsLoading(null);
+ setDomainIPDetailsLoading(null);
+ setIPProxyStatsLoading(null);
+ setIPDomainDetailsLoading(null);
+ }, [selectedRule, activeBackendId]);
+
+ useEffect(() => {
+ if (expandedDomain) {
+ fetchExpandedDomainDetails(expandedDomain, { force: true, background: true });
+ }
+ if (expandedIP) {
+ fetchExpandedIPDetails(expandedIP, { force: true, background: true });
+ }
+ }, [
+ timeRange?.start,
+ timeRange?.end,
+ expandedDomain,
+ expandedIP,
+ fetchExpandedDomainDetails,
+ fetchExpandedIPDetails,
+ ]);
+
const handleRuleClick = useCallback((rule: string) => {
if (selectedRule !== rule) {
setSelectedRule(rule);
@@ -853,12 +952,15 @@ export function InteractiveRuleStats({
{/* Desktop Table Header */}
<div className="hidden sm:grid grid-cols-12 gap-3 px-5 py-3 bg-secondary/30 text-xs font-medium text-muted-foreground uppercase tracking-wider">
<div
- className="col-span-4 flex items-center cursor-pointer hover:text-foreground transition-colors"
+ className="col-span-3 flex items-center cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleDomainSort("domain")}
>
{domainsT("domain")}
<DomainSortIcon column="domain" />
</div>
+ <div className="col-span-2 flex items-center">
+ {domainsT("proxy")}
+ </div>
<div
className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleDomainSort("totalDownload")}
@@ -874,7 +976,7 @@ export function InteractiveRuleStats({
<DomainSortIcon column="totalUpload" />
</div>
<div
- className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
+ className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleDomainSort("totalConnections")}
>
{domainsT("conn")}
@@ -934,13 +1036,18 @@ export function InteractiveRuleStats({
onClick={() => toggleExpandDomain(domain.domain)}
>
{/* Domain with Favicon */}
- <div className="col-span-4 flex items-center gap-3 min-w-0">
+ <div className="col-span-3 flex items-center gap-3 min-w-0">
<Favicon domain={domain.domain} size="sm" className="shrink-0" />
<span className="font-medium text-sm truncate" title={domain.domain}>
{domain.domain}
</span>
</div>
+ {/* Proxy */}
+ <div className="col-span-2 flex items-center gap-1.5 min-w-0">
+ <ProxyChainBadge chains={domain.chains} />
+ </div>
+
{/* Download */}
<div className="col-span-2 text-right tabular-nums text-sm">
<span className="text-blue-500">{formatBytes(domain.totalDownload)}</span>
@@ -952,7 +1059,7 @@ export function InteractiveRuleStats({
</div>
{/* Connections */}
- <div className="col-span-2 flex items-center justify-end">
+ <div className="col-span-1 flex items-center justify-end">
<span className="px-2 py-0.5 rounded-full bg-secondary text-xs font-medium">
{formatNumber(domain.totalConnections)}
</span>
@@ -1019,6 +1126,13 @@ export function InteractiveRuleStats({
</Button>
</div>
+ {/* Proxy row */}
+ {domain.chains && domain.chains.length > 0 && (
+ <div className="flex items-center gap-1.5 mb-2 pl-[30px]">
+ <ProxyChainBadge chains={domain.chains} truncateLabel={false} />
+ </div>
+ )}
+
{/* Bottom: Stats row */}
<div className="flex items-center justify-between text-xs pl-[30px]">
<span className="text-blue-500 tabular-nums">↓ {formatBytes(domain.totalDownload)}</span>
@@ -1029,35 +1143,20 @@ export function InteractiveRuleStats({
</div>
</div>
- {/* Expanded Details: Associated IPs */}
+ {/* Expanded Details: Proxy Traffic + Associated IPs */}
{isExpanded && (
- <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
- <div className="pt-3">
- {/* Associated IPs */}
- <div className="px-1">
- <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
- <Globe className="h-3 w-3" />
- {domainsT("associatedIPs")}
- </p>
- <div className="flex flex-wrap gap-2">
- {domain.ips.map((ip) => {
- const gradient = getIPGradient(ip);
- return (
- <div
- key={ip}
- className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
- >
- <div className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md bg-gradient-to-br ${gradient} flex items-center justify-center shrink-0`}>
- <Server className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-white" />
- </div>
- <code className="text-xs font-mono break-all">{ip}</code>
- </div>
- );
- })}
- </div>
- </div>
- </div>
- </div>
+ <DomainExpandedDetails
+ domain={domain}
+ proxyStats={domainProxyStats[domain.domain]}
+ proxyStatsLoading={domainProxyStatsLoading === domain.domain}
+ ipDetails={domainIPDetails[domain.domain]}
+ ipDetailsLoading={domainIPDetailsLoading === domain.domain}
+ labels={{
+ proxyTraffic: domainsT("proxyTraffic"),
+ associatedIPs: domainsT("associatedIPs"),
+ conn: domainsT("conn"),
+ }}
+ />
)}
</div>
);
@@ -1200,6 +1299,9 @@ export function InteractiveRuleStats({
{ipsT("ipAddress")}
<IPSortIcon column="ip" />
</div>
+ <div className="col-span-2 flex items-center">
+ {ipsT("proxy")}
+ </div>
<div className="col-span-2 flex items-center">
{ipsT("location")}
</div>
@@ -1211,7 +1313,7 @@ export function InteractiveRuleStats({
<IPSortIcon column="totalDownload" />
</div>
<div
- className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
+ className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleIPSort("totalUpload")}
>
{ipsT("upload")}
@@ -1224,7 +1326,7 @@ export function InteractiveRuleStats({
{ipsT("conn")}
<IPSortIcon column="totalConnections" />
</div>
- <div className="col-span-2 flex items-center justify-end">
+ <div className="col-span-1 flex items-center justify-end">
{ipsT("domainCount")}
</div>
</div>
@@ -1286,12 +1388,17 @@ export function InteractiveRuleStats({
<code className="text-sm font-mono truncate">{ip.ip}</code>
</div>
+ {/* Proxy */}
+ <div className="col-span-2 flex items-center gap-1.5 min-w-0">
+ <ProxyChainBadge chains={ip.chains} />
+ </div>
+
{/* Location */}
<div className="col-span-2 flex items-center gap-1.5 min-w-0">
{ip.geoIP && ip.geoIP.length > 0 ? (
<>
<CountryFlag country={ip.geoIP[0]} className="h-3.5 w-5" title={ip.geoIP[1] || ip.geoIP[0]} />
- <span className="text-xs truncate">{ip.geoIP[1] || ip.geoIP[0]}</span>
+ <span className="text-xs whitespace-nowrap">{ip.geoIP[1] || ip.geoIP[0]}</span>
</>
) : (
<span className="text-xs text-muted-foreground">-</span>
@@ -1304,7 +1411,7 @@ export function InteractiveRuleStats({
</div>
{/* Upload */}
- <div className="col-span-2 text-right tabular-nums text-sm">
+ <div className="col-span-1 text-right tabular-nums text-sm">
<span className="text-purple-500">{formatBytes(ip.totalUpload)}</span>
</div>
@@ -1316,7 +1423,7 @@ export function InteractiveRuleStats({
</div>
{/* Domains Count - Clickable */}
- <div className="col-span-2 flex items-center justify-end">
+ <div className="col-span-1 flex items-center justify-end">
<Button
variant="ghost"
size="sm"
@@ -1384,6 +1491,13 @@ export function InteractiveRuleStats({
</Button>
</div>
+ {/* Proxy row */}
+ {ip.chains && ip.chains.length > 0 && (
+ <div className="flex items-center gap-1.5 mb-2 pl-[30px]">
+ <ProxyChainBadge chains={ip.chains} truncateLabel={false} />
+ </div>
+ )}
+
{/* Bottom: Stats row */}
<div className="flex items-center justify-between text-xs pl-[30px]">
<span className="text-blue-500 tabular-nums">↓ {formatBytes(ip.totalDownload)}</span>
@@ -1394,35 +1508,21 @@ export function InteractiveRuleStats({
</div>
</div>
- {/* Expanded Details: Associated Domains */}
+ {/* Expanded Details: Proxy Traffic + Associated Domains */}
{isExpanded && (
- <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
- <div className="pt-3">
- {/* Associated Domains */}
- <div className="px-1">
- <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
- <Link2 className="h-3 w-3" />
- {ipsT("associatedDomains")}
- </p>
- <div className="flex flex-wrap gap-2">
- {ip.domains.map((domain) => {
- const domainColor = getDomainColor(domain);
- return (
- <div
- key={domain}
- className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
- >
- <div className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md ${domainColor.bg} ${domainColor.text} flex items-center justify-center shrink-0`}>
- <Globe className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
- </div>
- <span className="text-xs font-medium truncate max-w-[180px] sm:max-w-[200px]">{domain}</span>
- </div>
- );
- })}
- </div>
- </div>
- </div>
- </div>
+ <IPExpandedDetails
+ ip={ip}
+ proxyStats={ipProxyStats[ip.ip]}
+ proxyStatsLoading={ipProxyStatsLoading === ip.ip}
+ domainDetails={ipDomainDetails[ip.ip]}
+ domainDetailsLoading={ipDomainDetailsLoading === ip.ip}
+ associatedDomainsIcon="link"
+ labels={{
+ proxyTraffic: ipsT("proxyTraffic"),
+ associatedDomains: ipsT("associatedDomains"),
+ conn: ipsT("conn"),
+ }}
+ />
)}
</div>
);
diff --git a/apps/web/components/ips-table.tsx b/apps/web/components/ips-table.tsx
index d011b51..108de58 100644
--- a/apps/web/components/ips-table.tsx
+++ b/apps/web/components/ips-table.tsx
@@ -14,7 +14,6 @@ import {
ChevronDown,
ChevronUp,
Link2,
- Waypoints,
Loader2,
} from "lucide-react";
import { useTranslations } from "next-intl";
@@ -23,7 +22,9 @@ import { Button } from "@/components/ui/button";
import { CountryFlag } from "@/components/country-flag";
import { formatBytes, formatNumber } from "@/lib/utils";
import { cn } from "@/lib/utils";
-import type { IPStats, ProxyTrafficStats } from "@clashmaster/shared";
+import { IPExpandedDetails } from "@/components/stats-tables/expanded-details";
+import { ProxyChainBadge } from "@/components/proxy-chain-badge";
+import type { DomainStats, IPStats, ProxyTrafficStats } from "@clashmaster/shared";
import { api, type TimeRange } from "@/lib/api";
import {
DropdownMenu,
@@ -31,12 +32,6 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip";
interface IPsTableProps {
activeBackendId?: number;
@@ -75,15 +70,6 @@ const getIPColor = (ip: string) => {
return IP_COLORS[Math.abs(hash) % IP_COLORS.length];
};
-// Get color for domain
-const getDomainColor = (domain: string) => {
- let hash = 0;
- for (let i = 0; i < domain.length; i++) {
- hash = domain.charCodeAt(i) + ((hash << 5) - hash);
- }
- return IP_COLORS[Math.abs(hash) % IP_COLORS.length];
-};
-
export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
const t = useTranslations("ips");
const [data, setData] = useState<IPStats[]>([]);
@@ -102,6 +88,12 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(
null,
);
+ const [domainDetails, setDomainDetails] = useState<
+ Record<string, DomainStats[]>
+ >({});
+ const [domainDetailsLoading, setDomainDetailsLoading] = useState<string | null>(
+ null,
+ );
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Debounce search input
@@ -159,15 +151,22 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
]);
useEffect(() => {
+ // Backend switch means a different data universe, collapse safely.
setExpandedIP(null);
setProxyStats({});
- }, [activeBackendId, timeRange]);
+ setDomainDetails({});
+ }, [activeBackendId]);
// Fetch proxy stats when an IP is expanded
const fetchProxyStats = useCallback(
- async (ip: string) => {
- if (proxyStats[ip]) return;
- setProxyStatsLoading(ip);
+ async (ip: string, options?: { force?: boolean; background?: boolean }) => {
+ const force = options?.force ?? false;
+ const background = options?.background ?? false;
+ const hasCached = !!proxyStats[ip];
+ if (!force && hasCached) return;
+ if (!background || !hasCached) {
+ setProxyStatsLoading(ip);
+ }
try {
const stats = await api.getIPProxyStats(ip, activeBackendId, timeRange);
setProxyStats((prev) => ({ ...prev, [ip]: stats }));
@@ -175,12 +174,51 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
console.error(`Failed to fetch proxy stats for ${ip}:`, err);
setProxyStats((prev) => ({ ...prev, [ip]: [] }));
} finally {
- setProxyStatsLoading(null);
+ if (proxyStatsLoading === ip) {
+ setProxyStatsLoading(null);
+ }
}
},
- [proxyStats, activeBackendId, timeRange],
+ [proxyStats, activeBackendId, timeRange, proxyStatsLoading],
);
+ // Fetch domain details (with traffic) when an IP is expanded
+ const fetchDomainDetails = useCallback(
+ async (ip: string, options?: { force?: boolean; background?: boolean }) => {
+ const force = options?.force ?? false;
+ const background = options?.background ?? false;
+ const hasCached = !!domainDetails[ip];
+ if (!force && hasCached) return;
+ if (!background || !hasCached) {
+ setDomainDetailsLoading(ip);
+ }
+ try {
+ const details = await api.getIPDomainDetails(ip, activeBackendId, timeRange);
+ setDomainDetails((prev) => ({ ...prev, [ip]: details }));
+ } catch (err) {
+ console.error(`Failed to fetch domain details for ${ip}:`, err);
+ setDomainDetails((prev) => ({ ...prev, [ip]: [] }));
+ } finally {
+ if (domainDetailsLoading === ip) {
+ setDomainDetailsLoading(null);
+ }
+ }
+ },
+ [domainDetails, activeBackendId, timeRange, domainDetailsLoading],
+ );
+
+ useEffect(() => {
+ if (!expandedIP) return;
+ fetchProxyStats(expandedIP);
+ fetchDomainDetails(expandedIP);
+ }, [expandedIP, fetchProxyStats, fetchDomainDetails]);
+
+ useEffect(() => {
+ if (!expandedIP) return;
+ fetchProxyStats(expandedIP, { force: true, background: true });
+ fetchDomainDetails(expandedIP, { force: true, background: true });
+ }, [timeRange?.start, timeRange?.end, expandedIP, fetchProxyStats, fetchDomainDetails]);
+
const handleSort = (key: SortKey) => {
if (sortKey === key) {
setSortOrder(sortOrder === "asc" ? "desc" : "asc");
@@ -207,6 +245,7 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
setExpandedIP(newExpanded);
if (newExpanded) {
fetchProxyStats(newExpanded);
+ fetchDomainDetails(newExpanded);
}
};
@@ -279,7 +318,7 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
<SortIcon column="ip" />
</div>
<div className="col-span-2 flex items-center">{t("proxy")}</div>
- <div className="col-span-1 flex items-center">{t("location")}</div>
+ <div className="col-span-2 flex items-center">{t("location")}</div>
<div
className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("totalDownload")}>
@@ -298,7 +337,7 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
{t("conn")}
<SortIcon column="totalConnections" />
</div>
- <div className="col-span-2 flex items-center justify-end">
+ <div className="col-span-1 flex items-center justify-end">
{t("domainCount")}
</div>
</div>
@@ -345,19 +384,6 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
data.map((ip, index) => {
const ipColor = getIPColor(ip.ip);
const isExpanded = expandedIP === ip.ip;
- const fullChain =
- ip.chains && ip.chains.length > 0 ? ip.chains[0] : "";
- const lastProxy = fullChain
- ? fullChain.split(" > ").pop()?.trim() || fullChain
- : "";
- const chainTooltip =
- ip.chains && ip.chains.length > 0
- ? ip.chains
- .map((chain, idx) =>
- idx === 0 ? chain : `(${idx + 1}) ${chain}`,
- )
- .join("\n")
- : "";
return (
<div key={ip.ip} className="group">
@@ -384,40 +410,15 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
{/* Proxy */}
<div className="col-span-2 flex items-center gap-1.5 min-w-0">
- {ip.chains && ip.chains.length > 0 ? (
- <TooltipProvider delayDuration={300}>
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="inline-flex items-center gap-1.5 min-w-0">
- <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-[11px] font-medium truncate max-w-[120px]">
- <Waypoints className="h-2.5 w-2.5 shrink-0" />
- {lastProxy}
- </span>
- {ip.chains.length > 1 && (
- <span className="text-[11px] text-muted-foreground shrink-0">
- +{ip.chains.length - 1}
- </span>
- )}
- </span>
- </TooltipTrigger>
- <TooltipContent
- side="top"
- className="max-w-[360px] whitespace-pre-wrap">
- {chainTooltip}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- ) : (
- <span className="text-xs text-muted-foreground">-</span>
- )}
+ <ProxyChainBadge chains={ip.chains} />
</div>
{/* Location */}
- <div className="col-span-1 flex items-center">
+ <div className="col-span-2 flex items-center min-w-0">
{ip.geoIP && ip.geoIP.length > 0 ? (
- <div className="flex items-center gap-1.5">
+ <div className="flex items-center gap-1.5 min-w-0">
<CountryFlag country={ip.geoIP[0]} className="h-3.5 w-5" title={ip.geoIP[1] || ip.geoIP[0]} />
- <span className="text-xs truncate">
+ <span className="text-xs whitespace-nowrap">
{ip.geoIP[1] || ip.geoIP[0]}
</span>
</div>
@@ -448,7 +449,7 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
</div>
{/* Domains Count - Clickable */}
- <div className="col-span-2 flex items-center justify-end">
+ <div className="col-span-1 flex items-center justify-end">
<Button
variant="ghost"
size="sm"
@@ -525,28 +526,7 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
</span>
)}
{ip.chains && ip.chains.length > 0 && (
- <TooltipProvider delayDuration={300}>
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="inline-flex items-center gap-1.5">
- <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-[11px] font-medium whitespace-nowrap">
- <Waypoints className="h-2.5 w-2.5 shrink-0" />
- {lastProxy}
- </span>
- {ip.chains.length > 1 && (
- <span className="text-[11px] text-muted-foreground">
- +{ip.chains.length - 1}
- </span>
- )}
- </span>
- </TooltipTrigger>
- <TooltipContent
- side="top"
- className="max-w-[360px] whitespace-pre-wrap">
- {chainTooltip}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
+ <ProxyChainBadge chains={ip.chains} truncateLabel={false} />
)}
</div>
@@ -566,133 +546,19 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {
{/* Expanded Details: Proxy Traffic + Domains List */}
{isExpanded && (
- <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
- <div className="pt-3 grid grid-cols-1 sm:grid-cols-2 gap-4">
- {/* Proxy Traffic Breakdown */}
- <div className="px-1">
- <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
- <Waypoints className="h-3 w-3" />
- {t("proxyTraffic")}
- </p>
- {proxyStatsLoading === ip.ip ? (
- <div className="flex items-center justify-center py-4">
- <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
- </div>
- ) : proxyStats[ip.ip] &&
- proxyStats[ip.ip].length > 0 ? (
- <div className="space-y-2">
- {proxyStats[ip.ip].map((ps) => {
- const totalTraffic =
- ip.totalDownload + ip.totalUpload;
- const proxyTraffic =
- ps.totalDownload + ps.totalUpload;
- const percent =
- totalTraffic > 0
- ? (proxyTraffic / totalTraffic) * 100
- : 0;
- const proxyTotal =
- ps.totalDownload + ps.totalUpload;
- const downloadPercent =
- proxyTotal > 0
- ? (ps.totalDownload / proxyTotal) * 100
- : 0;
- const uploadPercent =
- proxyTotal > 0
- ? (ps.totalUpload / proxyTotal) * 100
- : 0;
- return (
- <div
- key={ps.chain}
- className="px-3 py-2 rounded-lg bg-card border border-border/50">
- <div className="flex items-center justify-between mb-1.5">
- <span
- className="inline-flex items-center gap-1.5 text-xs font-medium truncate max-w-[60%]"
- title={ps.chain}>
- <Waypoints className="h-3 w-3 text-orange-500 shrink-0" />
- {ps.chain}
- </span>
- <span className="text-[11px] text-muted-foreground tabular-nums shrink-0">
- {percent.toFixed(1)}%
- </span>
- </div>
- <div className="w-full h-1.5 rounded-full bg-secondary/80 mb-1.5 overflow-hidden flex">
- <div
- className="h-full bg-blue-500 transition-all"
- style={{
- width: `${Math.max(percent * (downloadPercent / 100), 0.5)}%`,
- }}
- />
- <div
- className="h-full bg-purple-500 transition-all"
- style={{
- width: `${Math.max(percent * (uploadPercent / 100), 0.5)}%`,
- }}
- />
- </div>
- <div className="flex flex-wrap items-center gap-2 sm:gap-3 text-[11px] tabular-nums">
- <span className="text-blue-500">
- ↓ {formatBytes(ps.totalDownload)}
- </span>
- <span className="text-purple-500">
- ↑ {formatBytes(ps.totalUpload)}
- </span>
- <span className="text-muted-foreground">
- {formatNumber(ps.totalConnections)}{" "}
- {t("conn")}
- </span>
- </div>
- </div>
- );
- })}
- </div>
- ) : ip.chains && ip.chains.length > 0 ? (
- <div className="flex flex-wrap gap-1.5">
- {ip.chains.map((chain) => (
- <span
- key={chain}
- className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-xs font-medium max-w-full min-w-0"
- title={chain}>
- <Waypoints className="h-3 w-3 shrink-0" />
- <span className="truncate min-w-0">
- {chain}
- </span>
- </span>
- ))}
- </div>
- ) : (
- <span className="text-xs text-muted-foreground">
- -
- </span>
- )}
- </div>
-
- {/* Associated Domains */}
- <div className="px-1">
- <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
- <Link2 className="h-3 w-3" />
- {t("associatedDomains")}
- </p>
- <div className="flex flex-wrap gap-2">
- {ip.domains.map((domain) => {
- const domainColor = getDomainColor(domain);
- return (
- <div
- key={domain}
- className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all">
- <div
- className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md ${domainColor.bg} ${domainColor.text} flex items-center justify-center shrink-0`}>
- <Globe className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
- </div>
- <span className="text-xs font-medium truncate max-w-[180px] sm:max-w-[200px]">
- {domain}
- </span>
- </div>
- );
- })}
- </div>
- </div>
- </div>
- </div>
+ <IPExpandedDetails
+ ip={ip}
+ proxyStats={proxyStats[ip.ip]}
+ proxyStatsLoading={proxyStatsLoading === ip.ip}
+ domainDetails={domainDetails[ip.ip]}
+ domainDetailsLoading={domainDetailsLoading === ip.ip}
+ associatedDomainsIcon="link"
+ labels={{
+ proxyTraffic: t("proxyTraffic"),
+ associatedDomains: t("associatedDomains"),
+ conn: t("conn"),
+ }}
+ />
)}
</div>
);
diff --git a/apps/web/components/overview/top-proxies-simple.tsx b/apps/web/components/overview/top-proxies-simple.tsx
index 39e843a..287ae5d 100644
--- a/apps/web/components/overview/top-proxies-simple.tsx
+++ b/apps/web/components/overview/top-proxies-simple.tsx
@@ -15,8 +15,12 @@ interface TopProxiesSimpleProps {
}
function simplifyProxyName(name: string): string {
- // Keep original name with emojis, just trim whitespace
- return name.trim();
+ const normalized = name.trim();
+ const parts = normalized
+ .split(">")
+ .map((part) => part.trim())
+ .filter(Boolean);
+ return parts[0] || normalized;
}
export const TopProxiesSimple = React.memo(
diff --git a/apps/web/components/proxy-chain-badge.tsx b/apps/web/components/proxy-chain-badge.tsx
new file mode 100644
index 0000000..98b1c9d
--- /dev/null
+++ b/apps/web/components/proxy-chain-badge.tsx
@@ -0,0 +1,164 @@
+"use client";
+
+import { ChevronRight, Waypoints } from "lucide-react";
+import { cn } from "@/lib/utils";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+
+interface ProxyChainBadgeProps {
+ chains?: string[] | null;
+ truncateLabel?: boolean;
+ wrapperClassName?: string;
+ badgeClassName?: string;
+ countClassName?: string;
+ emptyClassName?: string;
+}
+
+function ChainFlow({ chain }: { chain: string }) {
+ const segments = chain
+ .split(">")
+ .map((part) => part.trim())
+ .filter(Boolean);
+
+ // Backend stores full chain as "proxy > ... > rule", display as "rule > ... > proxy".
+ const displaySegments = segments.length > 1 ? [...segments].reverse() : segments;
+
+ const getNodeTone = (idx: number, total: number) => {
+ if (idx === 0) {
+ return "border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-200 dark:border-violet-400/35 dark:bg-violet-500/20";
+ }
+ if (idx === total - 1) {
+ return "border-emerald-500/35 bg-emerald-500/10 text-emerald-700 dark:text-emerald-200 dark:border-emerald-400/40 dark:bg-emerald-500/20";
+ }
+ return "border-blue-500/30 bg-blue-500/10 text-blue-700 dark:text-blue-200 dark:border-blue-400/35 dark:bg-blue-500/20";
+ };
+
+ const getLinkTone = (idx: number, total: number) => {
+ if (idx === 0) {
+ return {
+ line: "bg-gradient-to-r from-violet-400/80 to-blue-400/80 dark:from-violet-300/80 dark:to-blue-300/80",
+ dot: "bg-blue-500/80 dark:bg-blue-300/90",
+ };
+ }
+ if (idx === total - 2) {
+ return {
+ line: "bg-gradient-to-r from-blue-400/80 to-emerald-400/80 dark:from-blue-300/80 dark:to-emerald-300/80",
+ dot: "bg-emerald-500/80 dark:bg-emerald-300/90",
+ };
+ }
+ return {
+ line: "bg-gradient-to-r from-blue-400/80 to-blue-300/80 dark:from-blue-300/80 dark:to-blue-200/80",
+ dot: "bg-blue-500/80 dark:bg-blue-300/90",
+ };
+ };
+
+ return (
+ <div className="overflow-x-auto pb-0.5">
+ <div className="inline-flex items-center gap-1.5 min-w-max">
+ {displaySegments.map((segment, idx) => (
+ <span key={`${segment}-${idx}`} className="inline-flex items-center gap-1">
+ <span
+ className={cn(
+ "px-2 py-0.5 rounded-md border text-[11px] font-medium whitespace-nowrap",
+ getNodeTone(idx, displaySegments.length),
+ )}
+ >
+ {segment}
+ </span>
+ {idx < displaySegments.length - 1 && (
+ <span className="relative inline-flex items-center w-6 h-3.5 shrink-0">
+ <span
+ className={cn(
+ "h-[2px] w-full rounded-full",
+ getLinkTone(idx, displaySegments.length).line,
+ )}
+ />
+ <span
+ className={cn(
+ "absolute left-1/2 -translate-x-1/2 h-1.5 w-1.5 rounded-full animate-pulse",
+ getLinkTone(idx, displaySegments.length).dot,
+ )}
+ />
+ <ChevronRight className="absolute -right-1 h-3 w-3 text-muted-foreground/70 shrink-0" />
+ </span>
+ )}
+ </span>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+export function ProxyChainBadge({
+ chains,
+ truncateLabel = true,
+ wrapperClassName,
+ badgeClassName,
+ countClassName,
+ emptyClassName,
+}: ProxyChainBadgeProps) {
+ if (!chains || chains.length === 0) {
+ return <span className={cn("text-xs text-muted-foreground", emptyClassName)}>-</span>;
+ }
+
+ const firstChain = chains[0];
+ const landingProxy = firstChain.split(">").map((p) => p.trim()).filter(Boolean)[0] || firstChain;
+
+ return (
+ <TooltipProvider delayDuration={250}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className={cn("inline-flex items-center gap-1.5 min-w-0", wrapperClassName)}>
+ <span
+ className={cn(
+ "inline-flex items-center gap-1 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-[11px] font-medium",
+ truncateLabel ? "px-1.5 py-0.5 truncate max-w-[120px]" : "px-2 py-0.5 whitespace-nowrap",
+ badgeClassName,
+ )}
+ >
+ <Waypoints className="h-2.5 w-2.5 shrink-0" />
+ {landingProxy}
+ </span>
+ {chains.length > 1 && (
+ <span className={cn("text-[11px] text-muted-foreground shrink-0", countClassName)}>
+ +{chains.length - 1}
+ </span>
+ )}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent
+ side="top"
+ align="start"
+ className="max-w-[560px] p-2 border border-border bg-popover text-popover-foreground shadow-xl"
+ >
+ <div className="max-h-[280px] overflow-auto pr-1 space-y-1.5">
+ {chains.map((chain, idx) => (
+ <div
+ key={`${chain}-${idx}`}
+ className={cn(
+ "rounded-md border border-border bg-card text-card-foreground px-2 py-1.5",
+ idx > 0 && "mt-1",
+ )}
+ >
+ <div className="flex items-center gap-2">
+ {chains.length > 1 && (
+ <span className="inline-flex items-center justify-center h-5 min-w-5 px-1 rounded-full bg-muted text-[10px] font-semibold text-muted-foreground shrink-0">
+ {idx + 1}
+ </span>
+ )}
+ <div className="min-w-0 flex-1">
+ <ChainFlow chain={chain} />
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+}
diff --git a/apps/web/components/proxy-stats-chart.tsx b/apps/web/components/proxy-stats-chart.tsx
index 6fea91d..29c7888 100644
--- a/apps/web/components/proxy-stats-chart.tsx
+++ b/apps/web/components/proxy-stats-chart.tsx
@@ -28,7 +28,12 @@ const COLORS = [
// Format proxy name for display
function formatProxyName(name: string): string {
if (!name) return "DIRECT";
- return name.replace(/^\["?/, "").replace(/"?\]$/, "").trim();
+ const normalized = name.replace(/^\["?/, "").replace(/"?\]$/, "").trim();
+ const parts = normalized
+ .split(">")
+ .map((part) => part.trim())
+ .filter(Boolean);
+ return parts[0] || normalized;
}
export function ProxyStatsChart({ data }: ProxyStatsChartProps) {
diff --git a/apps/web/components/proxy-top-grid.tsx b/apps/web/components/proxy-top-grid.tsx
index 6418890..2c83988 100644
--- a/apps/web/components/proxy-top-grid.tsx
+++ b/apps/web/components/proxy-top-grid.tsx
@@ -20,10 +20,15 @@ type SortBy = "traffic" | "connections";
const COLORS = ["#3B82F6", "#8B5CF6", "#06B6D4", "#10B981", "#F59E0B", "#EF4444"];
function normalizeProxyName(name: string): string {
- return name
+ const normalized = name
.replace(/^\["?/, "")
.replace(/"?\]$/, "")
.trim();
+ const parts = normalized
+ .split(">")
+ .map((part) => part.trim())
+ .filter(Boolean);
+ return parts[0] || normalized;
}
function formatProxyName(name: string): string {
diff --git a/apps/web/components/proxy-top-list.tsx b/apps/web/components/proxy-top-list.tsx
index 71052c7..50a2f01 100644
--- a/apps/web/components/proxy-top-list.tsx
+++ b/apps/web/components/proxy-top-list.tsx
@@ -21,10 +21,15 @@ type SortBy = "traffic" | "connections";
const COLORS = ["#3B82F6", "#8B5CF6", "#06B6D4", "#10B981", "#F59E0B"];
function normalizeProxyName(name: string): string {
- return name
+ const normalized = name
.replace(/^\["?/, "")
.replace(/"?\]$/, "")
.trim();
+ const parts = normalized
+ .split(">")
+ .map((part) => part.trim())
+ .filter(Boolean);
+ return parts[0] || normalized;
}
function formatProxyName(name: string): string {
diff --git a/apps/web/components/stats-tables/domain-stats-table.tsx b/apps/web/components/stats-tables/domain-stats-table.tsx
index 148fc4d..1a8af07 100644
--- a/apps/web/components/stats-tables/domain-stats-table.tsx
+++ b/apps/web/components/stats-tables/domain-stats-table.tsx
@@ -1,7 +1,18 @@
"use client";
-import { useState, useMemo } from "react";
-import { ChevronLeft, ChevronRight, Loader2, Rows3, ArrowUpDown, ArrowDown, ArrowUp, Globe, ChevronDown, ChevronUp, Server } from "lucide-react";
+import { useState, useMemo, useCallback, useEffect } from "react";
+import {
+ ChevronLeft,
+ ChevronRight,
+ Loader2,
+ Rows3,
+ ArrowUpDown,
+ ArrowDown,
+ ArrowUp,
+ ChevronDown,
+ ChevronUp,
+ Server,
+} from "lucide-react";
import { useTranslations } from "next-intl";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
@@ -14,32 +25,48 @@ import {
} from "@/components/ui/dropdown-menu";
import { formatBytes, formatNumber } from "@/lib/utils";
import { cn } from "@/lib/utils";
+import { api, type TimeRange } from "@/lib/api";
import { Favicon } from "@/components/favicon";
-import {
- PAGE_SIZE_OPTIONS,
- getIPGradient,
+import { DomainExpandedDetails } from "@/components/stats-tables/expanded-details";
+import { ProxyChainBadge } from "@/components/proxy-chain-badge";
+import {
+ PAGE_SIZE_OPTIONS,
getPageNumbers,
type PageSize,
type DomainSortKey,
type SortOrder,
} from "@/lib/stats-utils";
-import type { DomainStats } from "@clashmaster/shared";
+import type { DomainStats, ProxyTrafficStats, IPStats } from "@clashmaster/shared";
interface DomainStatsTableProps {
domains: DomainStats[];
loading?: boolean;
title?: string;
showHeader?: boolean;
+ activeBackendId?: number;
+ timeRange?: TimeRange;
+ sourceIP?: string;
+ sourceChain?: string;
+ richExpand?: boolean;
+ showProxyColumn?: boolean;
+ showProxyTrafficInExpand?: boolean;
}
-export function DomainStatsTable({
- domains,
+export function DomainStatsTable({
+ domains,
loading = false,
title,
showHeader = true,
+ activeBackendId,
+ timeRange,
+ sourceIP,
+ sourceChain,
+ richExpand = false,
+ showProxyColumn = true,
+ showProxyTrafficInExpand = true,
}: DomainStatsTableProps) {
const t = useTranslations("domains");
-
+
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState<PageSize>(10);
const [search, setSearch] = useState("");
@@ -47,7 +74,92 @@ export function DomainStatsTable({
const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
const [expandedDomain, setExpandedDomain] = useState<string | null>(null);
- // Sort handler
+ const [proxyStats, setProxyStats] = useState<Record<string, ProxyTrafficStats[]>>({});
+ const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(null);
+ const [ipDetails, setIPDetails] = useState<Record<string, IPStats[]>>({});
+ const [ipDetailsLoading, setIPDetailsLoading] = useState<string | null>(null);
+
+ useEffect(() => {
+ // Context switch (backend/device/proxy/rule binding change): collapse.
+ setExpandedDomain(null);
+ setProxyStats({});
+ setIPDetails({});
+ setProxyStatsLoading(null);
+ setIPDetailsLoading(null);
+ }, [activeBackendId, sourceIP, sourceChain, richExpand]);
+
+ const fetchProxyStats = useCallback(
+ async (domain: string, options?: { force?: boolean; background?: boolean }) => {
+ const force = options?.force ?? false;
+ const background = options?.background ?? false;
+ const hasCached = !!proxyStats[domain];
+ if (!richExpand || (!force && hasCached)) return;
+ if (!background || !hasCached) {
+ setProxyStatsLoading(domain);
+ }
+ try {
+ const stats = await api.getDomainProxyStats(
+ domain,
+ activeBackendId,
+ timeRange,
+ sourceIP,
+ sourceChain,
+ );
+ setProxyStats((prev) => ({ ...prev, [domain]: stats }));
+ } catch (err) {
+ console.error(`Failed to fetch proxy stats for ${domain}:`, err);
+ setProxyStats((prev) => ({ ...prev, [domain]: [] }));
+ } finally {
+ if (proxyStatsLoading === domain) {
+ setProxyStatsLoading(null);
+ }
+ }
+ },
+ [proxyStats, activeBackendId, timeRange, sourceIP, sourceChain, richExpand, proxyStatsLoading],
+ );
+
+ const fetchIPDetails = useCallback(
+ async (domain: string, options?: { force?: boolean; background?: boolean }) => {
+ const force = options?.force ?? false;
+ const background = options?.background ?? false;
+ const hasCached = !!ipDetails[domain];
+ if (!richExpand || (!force && hasCached)) return;
+ if (!background || !hasCached) {
+ setIPDetailsLoading(domain);
+ }
+ try {
+ const details = await api.getDomainIPDetails(
+ domain,
+ activeBackendId,
+ timeRange,
+ sourceIP,
+ sourceChain,
+ );
+ setIPDetails((prev) => ({ ...prev, [domain]: details }));
+ } catch (err) {
+ console.error(`Failed to fetch IP details for ${domain}:`, err);
+ setIPDetails((prev) => ({ ...prev, [domain]: [] }));
+ } finally {
+ if (ipDetailsLoading === domain) {
+ setIPDetailsLoading(null);
+ }
+ }
+ },
+ [ipDetails, activeBackendId, timeRange, sourceIP, sourceChain, richExpand, ipDetailsLoading],
+ );
+
+ useEffect(() => {
+ if (!expandedDomain || !richExpand) return;
+ fetchProxyStats(expandedDomain);
+ fetchIPDetails(expandedDomain);
+ }, [expandedDomain, richExpand, fetchProxyStats, fetchIPDetails]);
+
+ useEffect(() => {
+ if (!expandedDomain || !richExpand) return;
+ fetchProxyStats(expandedDomain, { force: true, background: true });
+ fetchIPDetails(expandedDomain, { force: true, background: true });
+ }, [timeRange?.start, timeRange?.end, expandedDomain, richExpand, fetchProxyStats, fetchIPDetails]);
+
const handleSort = (key: DomainSortKey) => {
if (sortKey === key) {
setSortOrder(sortOrder === "asc" ? "desc" : "asc");
@@ -58,12 +170,15 @@ export function DomainStatsTable({
setPage(1);
};
- // Toggle expand
const toggleExpand = (domain: string) => {
- setExpandedDomain(expandedDomain === domain ? null : domain);
+ const newExpanded = expandedDomain === domain ? null : domain;
+ setExpandedDomain(newExpanded);
+ if (newExpanded && richExpand) {
+ fetchProxyStats(newExpanded);
+ fetchIPDetails(newExpanded);
+ }
};
- // Sort icon component
const SortIcon = ({ column }: { column: DomainSortKey }) => {
if (sortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
return sortOrder === "asc" ? (
@@ -73,12 +188,11 @@ export function DomainStatsTable({
);
};
- // Filter and sort
const filteredDomains = useMemo(() => {
let result = [...domains];
if (search) {
const lower = search.toLowerCase();
- result = result.filter(d => d.domain.toLowerCase().includes(lower));
+ result = result.filter((d) => d.domain.toLowerCase().includes(lower));
}
result.sort((a, b) => {
const aVal = a[sortKey] ?? "";
@@ -91,17 +205,16 @@ export function DomainStatsTable({
return result;
}, [domains, search, sortKey, sortOrder]);
- // Paginate
const paginatedDomains = useMemo(() => {
const start = (page - 1) * pageSize;
return filteredDomains.slice(start, start + pageSize);
}, [filteredDomains, page, pageSize]);
const totalPages = Math.ceil(filteredDomains.length / pageSize);
+ const domainColumnClass = showProxyColumn ? "col-span-3" : "col-span-5";
return (
<Card>
- {/* Header with search */}
{showHeader && (
<div className="p-4 border-b border-border/50">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
@@ -137,42 +250,44 @@ export function DomainStatsTable({
</div>
) : (
<>
- {/* Desktop Table Header */}
<div className="hidden sm:grid grid-cols-12 gap-3 px-5 py-3 bg-secondary/30 text-xs font-medium text-muted-foreground uppercase tracking-wider">
- <div
- className="col-span-4 flex items-center cursor-pointer hover:text-foreground transition-colors"
+ <div
+ className={cn(
+ domainColumnClass,
+ "flex items-center cursor-pointer hover:text-foreground transition-colors",
+ )}
onClick={() => handleSort("domain")}
>
{t("domain")}
<SortIcon column="domain" />
</div>
- <div
+ {showProxyColumn && (
+ <div className="col-span-2 flex items-center">{t("proxy")}</div>
+ )}
+ <div
className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("totalDownload")}
>
{t("download")}
<SortIcon column="totalDownload" />
</div>
- <div
+ <div
className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("totalUpload")}
>
{t("upload")}
<SortIcon column="totalUpload" />
</div>
- <div
- className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
+ <div
+ className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("totalConnections")}
>
{t("conn")}
<SortIcon column="totalConnections" />
</div>
- <div className="col-span-2 flex items-center justify-end">
- {t("ipCount")}
- </div>
+ <div className="col-span-2 flex items-center justify-end">{t("ipCount")}</div>
</div>
- {/* Mobile Sort Bar */}
<div className="sm:hidden flex items-center gap-2 px-4 py-2 bg-secondary/30 overflow-x-auto scrollbar-hide">
{([
{ key: "domain" as DomainSortKey, label: t("domain") },
@@ -186,69 +301,67 @@ export function DomainStatsTable({
"flex items-center gap-0.5 px-2 py-1 rounded-md text-xs font-medium whitespace-nowrap transition-colors",
sortKey === key
? "bg-primary/10 text-primary"
- : "text-muted-foreground hover:text-foreground"
+ : "text-muted-foreground hover:text-foreground",
)}
onClick={() => handleSort(key)}
>
{label}
- {sortKey === key && (
- sortOrder === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
- )}
+ {sortKey === key &&
+ (sortOrder === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />)}
</button>
))}
</div>
- {/* Domain List */}
<div className="divide-y divide-border/30">
{paginatedDomains.map((domain, index) => {
const isExpanded = expandedDomain === domain.domain;
-
+
return (
<div key={domain.domain} className="group">
- {/* Desktop Row */}
<div
className={cn(
"hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer",
- isExpanded && "bg-secondary/10"
+ isExpanded && "bg-secondary/10",
)}
style={{ animationDelay: `${index * 50}ms` }}
onClick={() => toggleExpand(domain.domain)}
>
- {/* Domain with Favicon */}
- <div className="col-span-4 flex items-center gap-3 min-w-0">
+ <div className={cn(domainColumnClass, "flex items-center gap-3 min-w-0")}>
<Favicon domain={domain.domain} size="sm" className="shrink-0" />
<span className="font-medium text-sm truncate" title={domain.domain}>
- {domain.domain}
+ {domain.domain || t("unknown")}
</span>
</div>
- {/* Download */}
+ {showProxyColumn && (
+ <div className="col-span-2 flex items-center gap-1.5 min-w-0">
+ <ProxyChainBadge chains={domain.chains} />
+ </div>
+ )}
+
<div className="col-span-2 text-right tabular-nums text-sm">
<span className="text-blue-500">{formatBytes(domain.totalDownload)}</span>
</div>
- {/* Upload */}
<div className="col-span-2 text-right tabular-nums text-sm">
<span className="text-purple-500">{formatBytes(domain.totalUpload)}</span>
</div>
- {/* Connections */}
- <div className="col-span-2 flex items-center justify-end">
+ <div className="col-span-1 flex items-center justify-end">
<span className="px-2 py-0.5 rounded-full bg-secondary text-xs font-medium">
{formatNumber(domain.totalConnections)}
</span>
</div>
- {/* IP Count - Clickable */}
<div className="col-span-2 flex items-center justify-end">
<Button
variant="ghost"
size="sm"
className={cn(
"h-7 px-2 gap-1 text-xs font-medium transition-all",
- isExpanded
- ? "bg-primary/10 text-primary hover:bg-primary/20"
- : "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary"
+ isExpanded
+ ? "bg-primary/10 text-primary hover:bg-primary/20"
+ : "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary",
)}
onClick={(e) => {
e.stopPropagation();
@@ -266,28 +379,24 @@ export function DomainStatsTable({
</div>
</div>
- {/* Mobile Row - Card-style layout */}
<div
className={cn(
"sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",
- isExpanded && "bg-secondary/10"
+ isExpanded && "bg-secondary/10",
)}
onClick={() => toggleExpand(domain.domain)}
>
- {/* Top: Favicon + Domain + Expand */}
<div className="flex items-center gap-2.5 mb-2">
<Favicon domain={domain.domain} size="sm" className="shrink-0" />
<span className="font-medium text-sm truncate flex-1" title={domain.domain}>
- {domain.domain}
+ {domain.domain || t("unknown")}
</span>
<Button
variant="ghost"
size="sm"
className={cn(
"h-7 px-2 gap-1 text-xs font-medium shrink-0",
- isExpanded
- ? "bg-primary/10 text-primary"
- : "bg-secondary/50 text-muted-foreground"
+ isExpanded ? "bg-primary/10 text-primary" : "bg-secondary/50 text-muted-foreground",
)}
onClick={(e) => {
e.stopPropagation();
@@ -300,7 +409,12 @@ export function DomainStatsTable({
</Button>
</div>
- {/* Bottom: Stats row */}
+ {showProxyColumn && domain.chains && domain.chains.length > 0 && (
+ <div className="flex items-center gap-1.5 mb-2 pl-[30px]">
+ <ProxyChainBadge chains={domain.chains} truncateLabel={false} />
+ </div>
+ )}
+
<div className="flex items-center justify-between text-xs pl-[30px]">
<span className="text-blue-500 tabular-nums">↓ {formatBytes(domain.totalDownload)}</span>
<span className="text-purple-500 tabular-nums">↑ {formatBytes(domain.totalUpload)}</span>
@@ -310,41 +424,27 @@ export function DomainStatsTable({
</div>
</div>
- {/* Expanded Details: Associated IPs */}
- {isExpanded && domain.ips && domain.ips.length > 0 && (
- <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
- <div className="pt-3">
- <div className="px-1">
- <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
- <Globe className="h-3 w-3" />
- {t("associatedIPs")}
- </p>
- <div className="flex flex-wrap gap-2">
- {domain.ips.map((ip) => {
- const gradient = getIPGradient(ip);
- return (
- <div
- key={ip}
- className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
- >
- <div className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md bg-gradient-to-br ${gradient} flex items-center justify-center shrink-0`}>
- <Server className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-white" />
- </div>
- <code className="text-xs font-mono break-all">{ip}</code>
- </div>
- );
- })}
- </div>
- </div>
- </div>
- </div>
+ {isExpanded && (
+ <DomainExpandedDetails
+ domain={domain}
+ richExpand={richExpand}
+ proxyStats={proxyStats[domain.domain]}
+ proxyStatsLoading={proxyStatsLoading === domain.domain}
+ ipDetails={ipDetails[domain.domain]}
+ ipDetailsLoading={ipDetailsLoading === domain.domain}
+ labels={{
+ proxyTraffic: t("proxyTraffic"),
+ associatedIPs: t("associatedIPs"),
+ conn: t("conn"),
+ }}
+ showProxyTraffic={showProxyTrafficInExpand}
+ />
)}
</div>
);
})}
</div>
- {/* Pagination */}
{filteredDomains.length > 0 && (
<div className="p-3 border-t border-border/50 bg-secondary/20">
<div className="flex flex-col sm:flex-row items-center justify-between gap-3">
@@ -384,14 +484,16 @@ export function DomainStatsTable({
variant="ghost"
size="icon"
className="h-8 w-8"
- onClick={() => setPage(p => Math.max(1, p - 1))}
+ onClick={() => setPage((p) => Math.max(1, p - 1))}
disabled={page === 1}
>
<ChevronLeft className="h-4 w-4" />
</Button>
- {getPageNumbers(page, totalPages).map((p, idx) => (
- p === '...' ? (
- <span key={`ellipsis-${idx}`} className="px-1 text-muted-foreground text-xs">...</span>
+ {getPageNumbers(page, totalPages).map((p, idx) =>
+ p === "..." ? (
+ <span key={`ellipsis-${idx}`} className="px-1 text-muted-foreground text-xs">
+ ...
+ </span>
) : (
<Button
key={p}
@@ -402,13 +504,13 @@ export function DomainStatsTable({
>
{p}
</Button>
- )
- ))}
+ ),
+ )}
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
- onClick={() => setPage(p => Math.min(totalPages, p + 1))}
+ onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
disabled={page === totalPages}
>
<ChevronRight className="h-4 w-4" />
diff --git a/apps/web/components/stats-tables/expanded-details.tsx b/apps/web/components/stats-tables/expanded-details.tsx
new file mode 100644
index 0000000..a6e5e3c
--- /dev/null
+++ b/apps/web/components/stats-tables/expanded-details.tsx
@@ -0,0 +1,465 @@
+"use client";
+
+import { Globe, Link2, Loader2, Server, Waypoints } from "lucide-react";
+import { CountryFlag } from "@/components/country-flag";
+import { Favicon } from "@/components/favicon";
+import { getDomainColor, getIPGradient } from "@/lib/stats-utils";
+import { formatBytes, formatNumber } from "@/lib/utils";
+import type { DomainStats, IPStats, ProxyTrafficStats } from "@clashmaster/shared";
+
+interface DomainExpandedDetailsProps {
+ domain: Pick<
+ DomainStats,
+ "domain" | "ips" | "chains" | "totalDownload" | "totalUpload"
+ >;
+ richExpand?: boolean;
+ proxyStats?: ProxyTrafficStats[];
+ proxyStatsLoading?: boolean;
+ ipDetails?: IPStats[];
+ ipDetailsLoading?: boolean;
+ labels: {
+ proxyTraffic: string;
+ associatedIPs: string;
+ conn: string;
+ };
+ showProxyTraffic?: boolean;
+}
+
+interface IPExpandedDetailsProps {
+ ip: Pick<
+ IPStats,
+ "ip" | "domains" | "chains" | "totalDownload" | "totalUpload"
+ >;
+ richExpand?: boolean;
+ proxyStats?: ProxyTrafficStats[];
+ proxyStatsLoading?: boolean;
+ domainDetails?: DomainStats[];
+ domainDetailsLoading?: boolean;
+ labels: {
+ proxyTraffic: string;
+ associatedDomains: string;
+ conn: string;
+ };
+ associatedDomainsIcon?: "link" | "globe";
+ showProxyTraffic?: boolean;
+}
+
+function getLandingProxy(chain: string): string {
+ const parts = chain
+ .split(">")
+ .map((part) => part.trim())
+ .filter(Boolean);
+ return parts[0] || chain;
+}
+
+function LoadingBlock() {
+ return (
+ <div className="flex items-center justify-center py-4">
+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
+ </div>
+ );
+}
+
+function TrafficBar({
+ percent,
+ downloadPercent,
+ uploadPercent,
+}: {
+ percent: number;
+ downloadPercent: number;
+ uploadPercent: number;
+}) {
+ return (
+ <div className="w-full h-1.5 rounded-full bg-secondary/80 mb-1.5 overflow-hidden flex">
+ <div
+ className="h-full bg-blue-500 transition-all"
+ style={{ width: `${Math.max(percent * (downloadPercent / 100), 0.5)}%` }}
+ />
+ <div
+ className="h-full bg-purple-500 transition-all"
+ style={{ width: `${Math.max(percent * (uploadPercent / 100), 0.5)}%` }}
+ />
+ </div>
+ );
+}
+
+function ProxyFallbackChains({ chains }: { chains: string[] }) {
+ if (!chains.length) {
+ return <span className="text-xs text-muted-foreground">-</span>;
+ }
+
+ const proxies = Array.from(new Set(chains.map(getLandingProxy).filter(Boolean)));
+
+ return (
+ <div className="flex flex-wrap gap-1.5">
+ {proxies.map((proxy) => (
+ <span
+ key={proxy}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-xs font-medium max-w-full min-w-0"
+ title={proxy}
+ >
+ <Waypoints className="h-3 w-3 shrink-0" />
+ <span className="truncate min-w-0">{proxy}</span>
+ </span>
+ ))}
+ </div>
+ );
+}
+
+function ProxyTrafficCards({
+ proxyStats,
+ totalDownload,
+ totalUpload,
+ connLabel,
+}: {
+ proxyStats: ProxyTrafficStats[];
+ totalDownload: number;
+ totalUpload: number;
+ connLabel: string;
+}) {
+ const grouped = new Map<string, ProxyTrafficStats>();
+ for (const stat of proxyStats) {
+ const proxy = getLandingProxy(stat.chain);
+ const prev = grouped.get(proxy);
+ if (prev) {
+ prev.totalDownload += stat.totalDownload;
+ prev.totalUpload += stat.totalUpload;
+ prev.totalConnections += stat.totalConnections;
+ } else {
+ grouped.set(proxy, {
+ chain: proxy,
+ totalDownload: stat.totalDownload,
+ totalUpload: stat.totalUpload,
+ totalConnections: stat.totalConnections,
+ });
+ }
+ }
+ const mergedStats = Array.from(grouped.values()).sort(
+ (a, b) =>
+ b.totalDownload + b.totalUpload - (a.totalDownload + a.totalUpload),
+ );
+
+ const totalTraffic = totalDownload + totalUpload;
+ return (
+ <div className="space-y-2">
+ {mergedStats.map((ps) => {
+ const proxyTraffic = ps.totalDownload + ps.totalUpload;
+ const percent = totalTraffic > 0 ? (proxyTraffic / totalTraffic) * 100 : 0;
+ const proxyTotal = ps.totalDownload + ps.totalUpload;
+ const downloadPercent = proxyTotal > 0 ? (ps.totalDownload / proxyTotal) * 100 : 0;
+ const uploadPercent = proxyTotal > 0 ? (ps.totalUpload / proxyTotal) * 100 : 0;
+
+ return (
+ <div key={ps.chain} className="px-3 py-2 rounded-lg bg-card border border-border/50">
+ <div className="flex items-center justify-between mb-1.5">
+ <span
+ className="inline-flex items-center gap-1.5 text-xs font-medium truncate max-w-[60%]"
+ title={ps.chain}
+ >
+ <Waypoints className="h-3 w-3 text-orange-500 shrink-0" />
+ {ps.chain}
+ </span>
+ <span className="text-[11px] text-muted-foreground tabular-nums shrink-0">
+ {percent.toFixed(1)}%
+ </span>
+ </div>
+ <TrafficBar
+ percent={percent}
+ downloadPercent={downloadPercent}
+ uploadPercent={uploadPercent}
+ />
+ <div className="flex flex-wrap items-center gap-2 sm:gap-3 text-[11px] tabular-nums">
+ <span className="text-blue-500">↓ {formatBytes(ps.totalDownload)}</span>
+ <span className="text-purple-500">↑ {formatBytes(ps.totalUpload)}</span>
+ <span className="text-muted-foreground">
+ {formatNumber(ps.totalConnections)} {connLabel}
+ </span>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+function IPFallbackChips({ ips }: { ips: string[] }) {
+ return (
+ <div className="flex flex-wrap gap-2">
+ {ips.map((ip) => {
+ const gradient = getIPGradient(ip);
+ return (
+ <div
+ key={ip}
+ className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
+ >
+ <div
+ className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md bg-gradient-to-br ${gradient} flex items-center justify-center shrink-0`}
+ >
+ <Server className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-white" />
+ </div>
+ <code className="text-xs font-mono break-all">{ip}</code>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+function DomainFallbackChips({ domains }: { domains: string[] }) {
+ return (
+ <div className="flex flex-wrap gap-2">
+ {domains.map((domain) => {
+ const domainColor = getDomainColor(domain);
+ return (
+ <div
+ key={domain}
+ className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
+ >
+ <div
+ className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md ${domainColor.bg} ${domainColor.text} flex items-center justify-center shrink-0`}
+ >
+ <Globe className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
+ </div>
+ <span className="text-xs font-medium truncate max-w-[180px] sm:max-w-[200px]">
+ {domain}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+export function DomainExpandedDetails({
+ domain,
+ richExpand = true,
+ proxyStats = [],
+ proxyStatsLoading = false,
+ ipDetails = [],
+ ipDetailsLoading = false,
+ labels,
+ showProxyTraffic = true,
+}: DomainExpandedDetailsProps) {
+ if (!richExpand) {
+ return (
+ <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
+ <div className="pt-3">
+ <div className="px-1">
+ <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
+ <Globe className="h-3 w-3" />
+ {labels.associatedIPs}
+ </p>
+ <IPFallbackChips ips={domain.ips || []} />
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const totalIPTraffic = ipDetails.reduce((sum, ip) => sum + ip.totalDownload + ip.totalUpload, 0);
+
+ return (
+ <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
+ <div className={showProxyTraffic ? "pt-3 grid grid-cols-1 sm:grid-cols-2 gap-4" : "pt-3"}>
+ {showProxyTraffic && (
+ <div className="px-1">
+ <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
+ <Waypoints className="h-3 w-3" />
+ {labels.proxyTraffic}
+ </p>
+ {proxyStatsLoading ? (
+ <LoadingBlock />
+ ) : proxyStats.length > 0 ? (
+ <ProxyTrafficCards
+ proxyStats={proxyStats}
+ totalDownload={domain.totalDownload}
+ totalUpload={domain.totalUpload}
+ connLabel={labels.conn}
+ />
+ ) : (
+ <ProxyFallbackChains chains={domain.chains || []} />
+ )}
+ </div>
+ )}
+
+ <div className="px-1">
+ <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
+ <Globe className="h-3 w-3" />
+ {labels.associatedIPs}
+ </p>
+ {ipDetailsLoading ? (
+ <LoadingBlock />
+ ) : ipDetails.length > 0 ? (
+ <div className="space-y-2">
+ {ipDetails.map((ipStat) => {
+ const country = ipStat.geoIP?.[0];
+ const location =
+ ipStat.geoIP && ipStat.geoIP.length > 1
+ ? ipStat.geoIP[1]
+ : ipStat.geoIP?.[0] || null;
+ const ipTraffic = ipStat.totalDownload + ipStat.totalUpload;
+ const percent = totalIPTraffic > 0 ? (ipTraffic / totalIPTraffic) * 100 : 0;
+ const downloadPercent = ipTraffic > 0 ? (ipStat.totalDownload / ipTraffic) * 100 : 0;
+ const uploadPercent = ipTraffic > 0 ? (ipStat.totalUpload / ipTraffic) * 100 : 0;
+
+ return (
+ <div
+ key={ipStat.ip}
+ className="px-3 py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
+ >
+ <div className="flex items-center justify-between mb-1.5">
+ <div className="flex items-center gap-1.5">
+ <Waypoints className="h-3 w-3 text-orange-500 shrink-0" />
+ <code className="text-xs font-mono">{ipStat.ip}</code>
+ </div>
+ <span className="text-[11px] text-muted-foreground tabular-nums shrink-0">
+ {percent.toFixed(1)}%
+ </span>
+ </div>
+ <TrafficBar
+ percent={percent}
+ downloadPercent={downloadPercent}
+ uploadPercent={uploadPercent}
+ />
+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-0">
+ <div className="flex flex-wrap items-center gap-2 sm:gap-3 text-[11px] tabular-nums">
+ <span className="text-blue-500">↓ {formatBytes(ipStat.totalDownload)}</span>
+ <span className="text-purple-500">↑ {formatBytes(ipStat.totalUpload)}</span>
+ <span className="text-muted-foreground">
+ {formatNumber(ipStat.totalConnections)} {labels.conn}
+ </span>
+ </div>
+ {location && (
+ <span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground">
+ <CountryFlag country={country} className="h-3 w-4" />
+ <span>{location}</span>
+ </span>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ ) : (
+ <IPFallbackChips ips={domain.ips || []} />
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function IPExpandedDetails({
+ ip,
+ richExpand = true,
+ proxyStats = [],
+ proxyStatsLoading = false,
+ domainDetails = [],
+ domainDetailsLoading = false,
+ labels,
+ associatedDomainsIcon = "link",
+ showProxyTraffic = true,
+}: IPExpandedDetailsProps) {
+ const AssociatedDomainsTitleIcon = associatedDomainsIcon === "globe" ? Globe : Link2;
+
+ if (!richExpand) {
+ return (
+ <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
+ <div className="pt-3">
+ <div className="px-1">
+ <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
+ <AssociatedDomainsTitleIcon className="h-3 w-3" />
+ {labels.associatedDomains}
+ </p>
+ <DomainFallbackChips domains={ip.domains || []} />
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const totalDomainTraffic = domainDetails.reduce(
+ (sum, domain) => sum + domain.totalDownload + domain.totalUpload,
+ 0,
+ );
+
+ return (
+ <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
+ <div className={showProxyTraffic ? "pt-3 grid grid-cols-1 sm:grid-cols-2 gap-4" : "pt-3"}>
+ {showProxyTraffic && (
+ <div className="px-1">
+ <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
+ <Waypoints className="h-3 w-3" />
+ {labels.proxyTraffic}
+ </p>
+ {proxyStatsLoading ? (
+ <LoadingBlock />
+ ) : proxyStats.length > 0 ? (
+ <ProxyTrafficCards
+ proxyStats={proxyStats}
+ totalDownload={ip.totalDownload}
+ totalUpload={ip.totalUpload}
+ connLabel={labels.conn}
+ />
+ ) : (
+ <ProxyFallbackChains chains={ip.chains || []} />
+ )}
+ </div>
+ )}
+
+ <div className="px-1">
+ <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
+ <AssociatedDomainsTitleIcon className="h-3 w-3" />
+ {labels.associatedDomains}
+ </p>
+ {domainDetailsLoading ? (
+ <LoadingBlock />
+ ) : domainDetails.length > 0 ? (
+ <div className="space-y-2">
+ {domainDetails.map((domain) => {
+ const domainTraffic = domain.totalDownload + domain.totalUpload;
+ const percent =
+ totalDomainTraffic > 0 ? (domainTraffic / totalDomainTraffic) * 100 : 0;
+ const downloadPercent =
+ domainTraffic > 0 ? (domain.totalDownload / domainTraffic) * 100 : 0;
+ const uploadPercent =
+ domainTraffic > 0 ? (domain.totalUpload / domainTraffic) * 100 : 0;
+
+ return (
+ <div
+ key={domain.domain}
+ className="px-3 py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
+ >
+ <div className="flex items-center justify-between mb-1.5">
+ <div className="flex items-center gap-1.5 min-w-0">
+ <Favicon domain={domain.domain} size="sm" className="shrink-0" />
+ <span className="text-xs font-medium truncate">{domain.domain}</span>
+ </div>
+ <span className="text-[11px] text-muted-foreground tabular-nums shrink-0">
+ {percent.toFixed(1)}%
+ </span>
+ </div>
+ <TrafficBar
+ percent={percent}
+ downloadPercent={downloadPercent}
+ uploadPercent={uploadPercent}
+ />
+ <div className="flex flex-wrap items-center gap-2 sm:gap-3 text-[11px] tabular-nums">
+ <span className="text-blue-500">↓ {formatBytes(domain.totalDownload)}</span>
+ <span className="text-purple-500">↑ {formatBytes(domain.totalUpload)}</span>
+ <span className="text-muted-foreground">
+ {formatNumber(domain.totalConnections)} {labels.conn}
+ </span>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ ) : (
+ <DomainFallbackChips domains={ip.domains || []} />
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/components/stats-tables/ip-stats-table.tsx b/apps/web/components/stats-tables/ip-stats-table.tsx
index 7392bec..f40785c 100644
--- a/apps/web/components/stats-tables/ip-stats-table.tsx
+++ b/apps/web/components/stats-tables/ip-stats-table.tsx
@@ -1,7 +1,19 @@
"use client";
-import { useState, useMemo } from "react";
-import { ChevronLeft, ChevronRight, Loader2, Rows3, ArrowUpDown, ArrowDown, ArrowUp, Globe, ChevronDown, ChevronUp, Server } from "lucide-react";
+import { useState, useMemo, useCallback, useEffect } from "react";
+import {
+ ChevronLeft,
+ ChevronRight,
+ Loader2,
+ Rows3,
+ ArrowUpDown,
+ ArrowDown,
+ ArrowUp,
+ Globe,
+ ChevronDown,
+ ChevronUp,
+ Server,
+} from "lucide-react";
import { useTranslations } from "next-intl";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
@@ -15,32 +27,48 @@ import {
} from "@/components/ui/dropdown-menu";
import { formatBytes, formatNumber } from "@/lib/utils";
import { cn } from "@/lib/utils";
-import { Favicon } from "@/components/favicon";
-import {
- PAGE_SIZE_OPTIONS,
- getIPGradient,
+import { api, type TimeRange } from "@/lib/api";
+import { IPExpandedDetails } from "@/components/stats-tables/expanded-details";
+import { ProxyChainBadge } from "@/components/proxy-chain-badge";
+import {
+ PAGE_SIZE_OPTIONS,
+ getIPGradient,
getPageNumbers,
type PageSize,
type IPSortKey,
type SortOrder,
} from "@/lib/stats-utils";
-import type { IPStats } from "@clashmaster/shared";
+import type { IPStats, ProxyTrafficStats, DomainStats } from "@clashmaster/shared";
interface IPStatsTableProps {
ips: IPStats[];
loading?: boolean;
title?: string;
showHeader?: boolean;
+ activeBackendId?: number;
+ timeRange?: TimeRange;
+ sourceIP?: string;
+ sourceChain?: string;
+ richExpand?: boolean;
+ showProxyColumn?: boolean;
+ showProxyTrafficInExpand?: boolean;
}
-export function IPStatsTable({
- ips,
+export function IPStatsTable({
+ ips,
loading = false,
title,
showHeader = true,
+ activeBackendId,
+ timeRange,
+ sourceIP,
+ sourceChain,
+ richExpand = false,
+ showProxyColumn = true,
+ showProxyTrafficInExpand = true,
}: IPStatsTableProps) {
const t = useTranslations("ips");
-
+
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState<PageSize>(10);
const [search, setSearch] = useState("");
@@ -48,7 +76,93 @@ export function IPStatsTable({
const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
const [expandedIP, setExpandedIP] = useState<string | null>(null);
- // Sort handler
+ const [proxyStats, setProxyStats] = useState<Record<string, ProxyTrafficStats[]>>({});
+ const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(null);
+ const [domainDetails, setDomainDetails] = useState<Record<string, DomainStats[]>>({});
+ const [domainDetailsLoading, setDomainDetailsLoading] = useState<string | null>(null);
+
+ useEffect(() => {
+ // Context switch (backend/device/proxy/rule binding change): collapse.
+ setExpandedIP(null);
+ setProxyStats({});
+ setDomainDetails({});
+ setProxyStatsLoading(null);
+ setDomainDetailsLoading(null);
+ }, [activeBackendId, sourceIP, sourceChain, richExpand]);
+
+ const fetchProxyStats = useCallback(
+ async (ip: string, options?: { force?: boolean; background?: boolean }) => {
+ const force = options?.force ?? false;
+ const background = options?.background ?? false;
+ const hasCached = !!proxyStats[ip];
+ if (!richExpand || (!force && hasCached)) return;
+ if (!background || !hasCached) {
+ setProxyStatsLoading(ip);
+ }
+ try {
+ const stats = await api.getIPProxyStats(
+ ip,
+ activeBackendId,
+ timeRange,
+ sourceIP,
+ sourceChain,
+ );
+ setProxyStats((prev) => ({ ...prev, [ip]: stats }));
+ } catch (err) {
+ console.error(`Failed to fetch proxy stats for ${ip}:`, err);
+ setProxyStats((prev) => ({ ...prev, [ip]: [] }));
+ } finally {
+ if (proxyStatsLoading === ip) {
+ setProxyStatsLoading(null);
+ }
+ }
+ },
+ [proxyStats, activeBackendId, timeRange, sourceIP, sourceChain, richExpand, proxyStatsLoading],
+ );
+
+ const fetchDomainDetails = useCallback(
+ async (ip: string, options?: { force?: boolean; background?: boolean }) => {
+ const force = options?.force ?? false;
+ const background = options?.background ?? false;
+ const hasCached = !!domainDetails[ip];
+ if (!richExpand || (!force && hasCached)) return;
+ if (!background || !hasCached) {
+ setDomainDetailsLoading(ip);
+ }
+ try {
+ const details = await api.getIPDomainDetails(
+ ip,
+ activeBackendId,
+ timeRange,
+ sourceIP,
+ undefined,
+ sourceChain,
+ );
+ setDomainDetails((prev) => ({ ...prev, [ip]: details }));
+ } catch (err) {
+ console.error(`Failed to fetch domain details for ${ip}:`, err);
+ setDomainDetails((prev) => ({ ...prev, [ip]: [] }));
+ } finally {
+ if (domainDetailsLoading === ip) {
+ setDomainDetailsLoading(null);
+ }
+ }
+ },
+ [domainDetails, activeBackendId, timeRange, sourceIP, sourceChain, richExpand, domainDetailsLoading],
+ );
+
+ useEffect(() => {
+ if (!expandedIP || !richExpand) return;
+ fetchProxyStats(expandedIP);
+ fetchDomainDetails(expandedIP);
+ }, [expandedIP, richExpand, fetchProxyStats, fetchDomainDetails]);
+
+ useEffect(() => {
+ if (!expandedIP || !richExpand) return;
+ fetchProxyStats(expandedIP, { force: true, background: true });
+ fetchDomainDetails(expandedIP, { force: true, background: true });
+ }, [timeRange?.start, timeRange?.end, expandedIP, richExpand, fetchProxyStats, fetchDomainDetails]);
+
const handleSort = (key: IPSortKey) => {
if (sortKey === key) {
setSortOrder(sortOrder === "asc" ? "desc" : "asc");
@@ -59,12 +173,15 @@ export function IPStatsTable({
setPage(1);
};
- // Toggle expand
const toggleExpand = (ip: string) => {
- setExpandedIP(expandedIP === ip ? null : ip);
+ const newExpanded = expandedIP === ip ? null : ip;
+ setExpandedIP(newExpanded);
+ if (newExpanded && richExpand) {
+ fetchProxyStats(newExpanded);
+ fetchDomainDetails(newExpanded);
+ }
};
- // Sort icon component
const SortIcon = ({ column }: { column: IPSortKey }) => {
if (sortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
return sortOrder === "asc" ? (
@@ -74,12 +191,11 @@ export function IPStatsTable({
);
};
- // Filter and sort
const filteredIPs = useMemo(() => {
let result = [...ips];
if (search) {
const lower = search.toLowerCase();
- result = result.filter(ip => ip.ip.toLowerCase().includes(lower));
+ result = result.filter((ip) => ip.ip.toLowerCase().includes(lower));
}
result.sort((a, b) => {
const aVal = a[sortKey] ?? "";
@@ -92,17 +208,18 @@ export function IPStatsTable({
return result;
}, [ips, search, sortKey, sortOrder]);
- // Paginate
const paginatedIPs = useMemo(() => {
const start = (page - 1) * pageSize;
return filteredIPs.slice(start, start + pageSize);
}, [filteredIPs, page, pageSize]);
const totalPages = Math.ceil(filteredIPs.length / pageSize);
+ const ipColumnClass = showProxyColumn ? "col-span-3" : "col-span-4";
+ const locationColumnClass = "col-span-2";
+ const domainCountColumnClass = showProxyColumn ? "col-span-1" : "col-span-2";
return (
<Card>
- {/* Header with search */}
{showHeader && (
<div className="p-4 border-b border-border/50">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
@@ -138,45 +255,47 @@ export function IPStatsTable({
</div>
) : (
<>
- {/* Desktop Table Header */}
<div className="hidden sm:grid grid-cols-12 gap-3 px-5 py-3 bg-secondary/30 text-xs font-medium text-muted-foreground uppercase tracking-wider">
- <div
- className="col-span-3 flex items-center cursor-pointer hover:text-foreground transition-colors"
+ <div
+ className={cn(
+ ipColumnClass,
+ "flex items-center cursor-pointer hover:text-foreground transition-colors",
+ )}
onClick={() => handleSort("ip")}
>
{t("ip")}
<SortIcon column="ip" />
</div>
- <div className="col-span-2 flex items-center">
- {t("location")}
- </div>
- <div
+ {showProxyColumn && (
+ <div className="col-span-2 flex items-center">{t("proxy")}</div>
+ )}
+ <div className={cn(locationColumnClass, "flex items-center")}>{t("location")}</div>
+ <div
className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("totalDownload")}
>
{t("download")}
<SortIcon column="totalDownload" />
</div>
- <div
- className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
+ <div
+ className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("totalUpload")}
>
{t("upload")}
<SortIcon column="totalUpload" />
</div>
- <div
+ <div
className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort("totalConnections")}
>
{t("conn")}
<SortIcon column="totalConnections" />
</div>
- <div className="col-span-2 flex items-center justify-end">
+ <div className={cn(domainCountColumnClass, "flex items-center justify-end")}>
{t("domainCount")}
</div>
</div>
- {/* Mobile Sort Bar */}
<div className="sm:hidden flex items-center gap-2 px-4 py-2 bg-secondary/30 overflow-x-auto scrollbar-hide">
{([
{ key: "ip" as IPSortKey, label: t("ip") },
@@ -190,80 +309,77 @@ export function IPStatsTable({
"flex items-center gap-0.5 px-2 py-1 rounded-md text-xs font-medium whitespace-nowrap transition-colors",
sortKey === key
? "bg-primary/10 text-primary"
- : "text-muted-foreground hover:text-foreground"
+ : "text-muted-foreground hover:text-foreground",
)}
onClick={() => handleSort(key)}
>
{label}
- {sortKey === key && (
- sortOrder === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
- )}
+ {sortKey === key &&
+ (sortOrder === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />)}
</button>
))}
</div>
- {/* IP List */}
<div className="divide-y divide-border/30">
{paginatedIPs.map((ip) => {
const isExpanded = expandedIP === ip.ip;
-
+
return (
<div key={ip.ip} className="group">
- {/* Desktop Row */}
<div
className={cn(
"hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer",
- isExpanded && "bg-secondary/10"
+ isExpanded && "bg-secondary/10",
)}
onClick={() => toggleExpand(ip.ip)}
>
- {/* IP Address */}
- <div className="col-span-3 flex items-center gap-3 min-w-0">
+ <div className={cn(ipColumnClass, "flex items-center gap-3 min-w-0")}>
<div className={`w-5 h-5 rounded-md bg-gradient-to-br ${getIPGradient(ip.ip)} flex items-center justify-center shrink-0`}>
<Server className="w-3 h-3 text-white" />
</div>
<code className="font-mono text-sm truncate">{ip.ip}</code>
</div>
- {/* Location */}
- <div className="col-span-2 flex items-center gap-1.5 min-w-0">
+ {showProxyColumn && (
+ <div className="col-span-2 flex items-center gap-1.5 min-w-0">
+ <ProxyChainBadge chains={ip.chains} />
+ </div>
+ )}
+
+ <div className={cn(locationColumnClass, "flex items-center gap-1.5 min-w-0")}>
{ip.geoIP && ip.geoIP.length > 0 ? (
<>
<CountryFlag country={ip.geoIP[0]} className="h-3.5 w-5" title={ip.geoIP[1] || ip.geoIP[0]} />
- <span className="text-xs truncate">{ip.geoIP[1] || ip.geoIP[0]}</span>
+ <span className="text-xs whitespace-nowrap">{ip.geoIP[1] || ip.geoIP[0]}</span>
</>
) : (
<span className="text-xs text-muted-foreground">-</span>
)}
</div>
- {/* Download */}
<div className="col-span-2 text-right tabular-nums text-sm">
<span className="text-blue-500">{formatBytes(ip.totalDownload)}</span>
</div>
- {/* Upload */}
- <div className="col-span-2 text-right tabular-nums text-sm">
+ <div className="col-span-1 text-right tabular-nums text-sm">
<span className="text-purple-500">{formatBytes(ip.totalUpload)}</span>
</div>
- {/* Connections */}
<div className="col-span-1 flex items-center justify-end">
<span className="px-2 py-0.5 rounded-full bg-secondary text-xs font-medium">
{formatNumber(ip.totalConnections)}
</span>
</div>
- {/* Domain Count - Clickable */}
- <div className="col-span-2 flex items-center justify-end">
+ <div className={cn(domainCountColumnClass, "flex items-center justify-end")}>
<Button
variant="ghost"
size="sm"
className={cn(
"h-7 px-2 gap-1 text-xs font-medium transition-all",
- isExpanded
- ? "bg-primary/10 text-primary hover:bg-primary/20"
- : "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary"
+ isExpanded
+ ? "bg-primary/10 text-primary hover:bg-primary/20"
+ : "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary",
)}
onClick={(e) => {
e.stopPropagation();
@@ -281,31 +397,24 @@ export function IPStatsTable({
</div>
</div>
- {/* Mobile Row */}
<div
className={cn(
"sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",
- isExpanded && "bg-secondary/10"
+ isExpanded && "bg-secondary/10",
)}
onClick={() => toggleExpand(ip.ip)}
>
- {/* Top: IP Address + Location + Expand */}
<div className="flex items-center gap-2.5 mb-2">
<div className={`w-5 h-5 rounded-md bg-gradient-to-br ${getIPGradient(ip.ip)} flex items-center justify-center shrink-0`}>
<Server className="w-2.5 h-2.5 text-white" />
</div>
<code className="font-mono text-sm flex-1 truncate">{ip.ip}</code>
- {ip.geoIP && ip.geoIP.length > 0 && (
- <CountryFlag country={ip.geoIP[0]} className="h-3.5 w-5" title={ip.geoIP[1] || ip.geoIP[0]} />
- )}
<Button
variant="ghost"
size="sm"
className={cn(
"h-7 px-2 gap-1 text-xs font-medium shrink-0",
- isExpanded
- ? "bg-primary/10 text-primary"
- : "bg-secondary/50 text-muted-foreground"
+ isExpanded ? "bg-primary/10 text-primary" : "bg-secondary/50 text-muted-foreground",
)}
onClick={(e) => {
e.stopPropagation();
@@ -318,7 +427,18 @@ export function IPStatsTable({
</Button>
</div>
- {/* Bottom: Stats row */}
+ <div className="flex items-center gap-2 mb-2 pl-[30px] flex-wrap">
+ {ip.geoIP && ip.geoIP.length > 0 && (
+ <span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground">
+ <CountryFlag country={ip.geoIP[0]} className="h-3.5 w-5" />
+ <span className="truncate">{ip.geoIP[1] || ip.geoIP[0]}</span>
+ </span>
+ )}
+ {showProxyColumn && ip.chains && ip.chains.length > 0 && (
+ <ProxyChainBadge chains={ip.chains} truncateLabel={false} />
+ )}
+ </div>
+
<div className="flex items-center justify-between text-xs pl-[30px]">
<span className="text-blue-500 tabular-nums">↓ {formatBytes(ip.totalDownload)}</span>
<span className="text-purple-500 tabular-nums">↑ {formatBytes(ip.totalUpload)}</span>
@@ -328,36 +448,28 @@ export function IPStatsTable({
</div>
</div>
- {/* Expanded Details: Associated Domains */}
- {isExpanded && ip.domains && ip.domains.length > 0 && (
- <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
- <div className="pt-3">
- <div className="px-1">
- <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
- <Globe className="h-3 w-3" />
- {t("associatedDomains")}
- </p>
- <div className="flex flex-wrap gap-2">
- {ip.domains.map((domain) => (
- <div
- key={domain}
- className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
- >
- <Favicon domain={domain} size="sm" />
- <span className="text-xs truncate max-w-[200px]">{domain}</span>
- </div>
- ))}
- </div>
- </div>
- </div>
- </div>
+ {isExpanded && (
+ <IPExpandedDetails
+ ip={ip}
+ richExpand={richExpand}
+ proxyStats={proxyStats[ip.ip]}
+ proxyStatsLoading={proxyStatsLoading === ip.ip}
+ domainDetails={domainDetails[ip.ip]}
+ domainDetailsLoading={domainDetailsLoading === ip.ip}
+ associatedDomainsIcon="link"
+ labels={{
+ proxyTraffic: t("proxyTraffic"),
+ associatedDomains: t("associatedDomains"),
+ conn: t("conn"),
+ }}
+ showProxyTraffic={showProxyTrafficInExpand}
+ />
)}
</div>
);
})}
</div>
- {/* Pagination */}
{filteredIPs.length > 0 && (
<div className="p-3 border-t border-border/50 bg-secondary/20">
<div className="flex flex-col sm:flex-row items-center justify-between gap-3">
@@ -397,14 +509,16 @@ export function IPStatsTable({
variant="ghost"
size="icon"
className="h-8 w-8"
- onClick={() => setPage(p => Math.max(1, p - 1))}
+ onClick={() => setPage((p) => Math.max(1, p - 1))}
disabled={page === 1}
>
<ChevronLeft className="h-4 w-4" />
</Button>
- {getPageNumbers(page, totalPages).map((p, idx) => (
- p === '...' ? (
- <span key={`ellipsis-${idx}`} className="px-1 text-muted-foreground text-xs">...</span>
+ {getPageNumbers(page, totalPages).map((p, idx) =>
+ p === "..." ? (
+ <span key={`ellipsis-${idx}`} className="px-1 text-muted-foreground text-xs">
+ ...
+ </span>
) : (
<Button
key={p}
@@ -415,13 +529,13 @@ export function IPStatsTable({
>
{p}
</Button>
- )
- ))}
+ ),
+ )}
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
- onClick={() => setPage(p => Math.min(totalPages, p + 1))}
+ onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
disabled={page === totalPages}
>
<ChevronRight className="h-4 w-4" />
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index 14a1ea9..663f9a7 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -228,33 +228,77 @@ export const api = {
buildUrl(`${API_BASE}/stats/connections`, { backendId, limit })
),
- getDomainProxyStats: (domain: string, backendId?: number, range?: TimeRange) =>
+ getDomainProxyStats: (
+ domain: string,
+ backendId?: number,
+ range?: TimeRange,
+ sourceIP?: string,
+ sourceChain?: string,
+ ) =>
fetchJson<ProxyTrafficStats[]>(
buildUrl(`${API_BASE}/stats/domains/proxy-stats`, {
domain,
backendId,
start: range?.start,
end: range?.end,
+ sourceIP,
+ sourceChain,
})
),
- getDomainIPDetails: (domain: string, backendId?: number, range?: TimeRange) =>
+ getDomainIPDetails: (
+ domain: string,
+ backendId?: number,
+ range?: TimeRange,
+ sourceIP?: string,
+ sourceChain?: string,
+ ) =>
fetchJson<IPStats[]>(
buildUrl(`${API_BASE}/stats/domains/ip-details`, {
domain,
backendId,
start: range?.start,
end: range?.end,
+ sourceIP,
+ sourceChain,
})
),
- getIPProxyStats: (ip: string, backendId?: number, range?: TimeRange) =>
+ getIPProxyStats: (
+ ip: string,
+ backendId?: number,
+ range?: TimeRange,
+ sourceIP?: string,
+ sourceChain?: string,
+ ) =>
fetchJson<ProxyTrafficStats[]>(
buildUrl(`${API_BASE}/stats/ips/proxy-stats`, {
ip,
backendId,
start: range?.start,
end: range?.end,
+ sourceIP,
+ sourceChain,
+ })
+ ),
+
+ getIPDomainDetails: (
+ ip: string,
+ backendId?: number,
+ range?: TimeRange,
+ sourceIP?: string,
+ limit = DETAIL_FETCH_LIMIT,
+ sourceChain?: string,
+ ) =>
+ fetchJson<DomainStats[]>(
+ buildUrl(`${API_BASE}/stats/ips/domain-details`, {
+ ip,
+ limit,
+ backendId,
+ start: range?.start,
+ end: range?.end,
+ sourceIP,
+ sourceChain,
})
),
@@ -330,6 +374,74 @@ export const api = {
})
),
+ getRuleDomainProxyStats: (
+ rule: string,
+ domain: string,
+ backendId?: number,
+ range?: TimeRange,
+ ) =>
+ fetchJson<ProxyTrafficStats[]>(
+ buildUrl(`${API_BASE}/stats/rules/domains/proxy-stats`, {
+ rule,
+ domain,
+ backendId,
+ start: range?.start,
+ end: range?.end,
+ })
+ ),
+
+ getRuleDomainIPDetails: (
+ rule: string,
+ domain: string,
+ backendId?: number,
+ range?: TimeRange,
+ limit = DETAIL_FETCH_LIMIT,
+ ) =>
+ fetchJson<IPStats[]>(
+ buildUrl(`${API_BASE}/stats/rules/domains/ip-details`, {
+ rule,
+ domain,
+ limit,
+ backendId,
+ start: range?.start,
+ end: range?.end,
+ })
+ ),
+
+ getRuleIPProxyStats: (
+ rule: string,
+ ip: string,
+ backendId?: number,
+ range?: TimeRange,
+ ) =>
+ fetchJson<ProxyTrafficStats[]>(
+ buildUrl(`${API_BASE}/stats/rules/ips/proxy-stats`, {
+ rule,
+ ip,
+ backendId,
+ start: range?.start,
+ end: range?.end,
+ })
+ ),
+
+ getRuleIPDomainDetails: (
+ rule: string,
+ ip: string,
+ backendId?: number,
+ range?: TimeRange,
+ limit = DETAIL_FETCH_LIMIT,
+ ) =>
+ fetchJson<DomainStats[]>(
+ buildUrl(`${API_BASE}/stats/rules/ips/domain-details`, {
+ rule,
+ ip,
+ limit,
+ backendId,
+ start: range?.start,
+ end: range?.end,
+ })
+ ),
+
getRuleChainFlow: (rule: string, backendId?: number, range?: TimeRange) =>
fetchJson<{ nodes: Array<{ name: string; totalUpload: number; totalDownload: number; totalConnections: number }>; links: Array<{ source: number; target: number }> }>(
buildUrl(`${API_BASE}/stats/rules/chain-flow`, {
diff --git a/package.json b/package.json
index 82dd6e6..cd1f524 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "clash-master",
- "version": "1.1.0",
+ "version": "1.1.1",
"private": true,
"workspaces": [
"apps/*",
diff --git a/tweet-draft.md b/tweet-draft.md
deleted file mode 100644
index aae0654..0000000
--- a/tweet-draft.md
+++ /dev/null
@@ -1,57 +0,0 @@
-## 推文版本 1(推荐 - 场景切入)
-
-> 用 OpenClash 做旁路由的朋友,你们真的了解自己家的流量都去了哪里吗?
->
-> 开源了 Clash Master —— 一个优雅的流量可视化分析工具:
-> • 域名/IP/代理节点 全维度统计
-> • 实时流量趋势 + 世界地图分布
-> • 多后端同时监控,数据持久化存储
-> • 深色模式,中英双语支持
->
-> 部署简单,开箱即用。
->
-> 🔗 github.com/foru17/clash-master
-
----
-
-## 推文版本 2(功能清单型)
-
-> Clash Master:专为 OpenClash 设计的流量分析面板
->
-> ✅ 域名流量排行 & 关联 IP 追踪
-> ✅ 代理节点分流统计
-> ✅ IP 归属地 + ASN 信息
-> ✅ 30分钟~24小时趋势分析
-> ✅ 多后端集中管理
-> ✅ SQLite 持久化,数据不丢失
->
-> 界面清爽,功能齐全。
->
-> 👉 github.com/foru17/clash-master
-
----
-
-## 推文版本 3(极简型,适合配图)
-
-> 家里用 OpenClash 的,推荐一个自用的流量分析工具。
->
-> 能看域名统计、节点分流、IP 归属地,还有世界地图可视化。
-> 支持多后端监控,数据自动持久化。
->
-> 开源地址:github.com/foru17/clash-master
-
----
-
-## 推文版本 4(痛点解决型)
-
-> 受够了命令行和简陋界面?
->
-> Clash Master 给 OpenClash 带来了现代化的流量分析体验:
-> • 可视化流量趋势(30min/1h/24h)
-> • 域名 & IP 深度分析
-> • 多后端统一管理
-> • 数据持久化,随时回溯
->
-> 现已开源。
->
-> 🔗 github.com/foru17/clash-master