清理不必要的測試檔案

This commit is contained in:
2025-09-21 03:23:26 +08:00
parent 8b3af6608e
commit f6abef38e9
58 changed files with 1 additions and 8621 deletions

View File

@@ -1,371 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Loader2, Database, Trash2, Settings, Activity, Clock, Users } from 'lucide-react';
interface ConnectionStats {
totalConnections: number;
idleConnections: number;
oldConnections: number;
maxIdleTime: number;
maxConnectionAge: number;
connections: Array<{
createdAt: string;
lastUsed: string;
idleTime: number;
age: number;
userId?: string;
sessionId?: string;
}>;
}
export default function ConnectionMonitorPage() {
const [stats, setStats] = useState<ConnectionStats | null>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
const [maxIdleTime, setMaxIdleTime] = useState<number>(300000); // 5分鐘
const [maxConnectionAge, setMaxConnectionAge] = useState<number>(1800000); // 30分鐘
// 獲取連線統計
const fetchStats = async () => {
try {
setLoading(true);
const response = await fetch('/api/connection-monitor?action=stats');
const data = await response.json();
if (data.success) {
setStats(data.data);
setMessage('統計更新成功');
setError('');
} else {
setError(data.error || '獲取統計失敗');
}
} catch (err) {
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 強制清理連線
const forceCleanup = async () => {
if (!confirm('確定要強制清理所有連線嗎?這可能會影響正在進行的操作!')) {
return;
}
try {
setLoading(true);
const response = await fetch('/api/connection-monitor?action=cleanup');
const data = await response.json();
if (data.success) {
setMessage('連線清理完成');
setError('');
await fetchStats(); // 重新獲取統計
} else {
setError(data.error || '清理失敗');
}
} catch (err) {
setError('清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 測試智能連線
const testConnection = async () => {
try {
setLoading(true);
const response = await fetch('/api/connection-monitor?action=test');
const data = await response.json();
if (data.success) {
setMessage('智能連線測試成功');
setError('');
await fetchStats(); // 重新獲取統計
} else {
setError(data.error || '測試失敗');
}
} catch (err) {
setError('測試錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 更新清理配置
const updateConfig = async () => {
try {
setLoading(true);
const response = await fetch('/api/connection-monitor', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'config',
maxIdleTime,
maxConnectionAge
}),
});
const data = await response.json();
if (data.success) {
setMessage('清理配置更新成功');
setError('');
await fetchStats(); // 重新獲取統計
} else {
setError(data.error || '配置更新失敗');
}
} catch (err) {
setError('配置更新錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 格式化時間
const formatTime = (ms: number) => {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) return `${hours}h ${minutes % 60}m`;
if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
return `${seconds}s`;
};
// 組件載入時獲取統計
useEffect(() => {
fetchStats();
// 每30秒自動更新統計
const interval = setInterval(fetchStats, 30000);
return () => clearInterval(interval);
}, []);
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold"></h1>
<p className="text-muted-foreground">
</p>
</div>
<Button
onClick={fetchStats}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Activity className="h-4 w-4" />}
</Button>
</div>
{/* 統計概覽 */}
{stats && (
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<Card>
<CardContent className="p-6">
<div className="flex items-center gap-2">
<Database className="h-5 w-5 text-blue-500" />
<div>
<p className="text-sm font-medium text-muted-foreground"></p>
<p className="text-2xl font-bold">{stats.totalConnections}</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center gap-2">
<Clock className="h-5 w-5 text-yellow-500" />
<div>
<p className="text-sm font-medium text-muted-foreground"></p>
<p className="text-2xl font-bold">{stats.idleConnections}</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center gap-2">
<Users className="h-5 w-5 text-red-500" />
<div>
<p className="text-sm font-medium text-muted-foreground"></p>
<p className="text-2xl font-bold">{stats.oldConnections}</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center gap-2">
<Activity className="h-5 w-5 text-green-500" />
<div>
<p className="text-sm font-medium text-muted-foreground"></p>
<p className="text-2xl font-bold">
{stats.idleConnections + stats.oldConnections === 0 ? '良好' : '需清理'}
</p>
</div>
</div>
</CardContent>
</Card>
</div>
)}
{/* 操作按鈕 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Settings className="h-5 w-5" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Button
onClick={testConnection}
disabled={loading}
variant="outline"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Database className="h-4 w-4" />}
</Button>
<Button
onClick={forceCleanup}
disabled={loading}
variant="destructive"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
</Button>
<Button
onClick={updateConfig}
disabled={loading}
variant="secondary"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Settings className="h-4 w-4" />}
</Button>
</div>
{/* 配置設定 */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t">
<div className="space-y-2">
<Label htmlFor="maxIdleTime"> ()</Label>
<Input
id="maxIdleTime"
type="number"
value={maxIdleTime}
onChange={(e) => setMaxIdleTime(Number(e.target.value))}
placeholder="300000 (5分鐘)"
/>
</div>
<div className="space-y-2">
<Label htmlFor="maxConnectionAge"> ()</Label>
<Input
id="maxConnectionAge"
type="number"
value={maxConnectionAge}
onChange={(e) => setMaxConnectionAge(Number(e.target.value))}
placeholder="1800000 (30分鐘)"
/>
</div>
</div>
</CardContent>
</Card>
{/* 連線詳情 */}
{stats && stats.connections.length > 0 && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
{stats.connections.map((conn, index) => (
<div key={index} className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-4">
<Badge variant="outline">#{index + 1}</Badge>
<div>
<p className="text-sm font-medium">
: {new Date(conn.createdAt).toLocaleString()}
</p>
<p className="text-sm text-muted-foreground">
使: {new Date(conn.lastUsed).toLocaleString()}
</p>
</div>
</div>
<div className="flex items-center gap-2">
<Badge variant={conn.idleTime > stats.maxIdleTime ? "destructive" : "default"}>
: {formatTime(conn.idleTime)}
</Badge>
<Badge variant={conn.age > stats.maxConnectionAge ? "destructive" : "default"}>
: {formatTime(conn.age)}
</Badge>
{conn.userId && (
<Badge variant="secondary">: {conn.userId}</Badge>
)}
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* 訊息顯示 */}
{message && (
<Alert>
<Activity className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<Database className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 說明資訊 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong>:</strong> 30</p>
<p> <strong>:</strong> 使</p>
<p> <strong>:</strong> </p>
<p> <strong>:</strong> </p>
<p> <strong>:</strong> </p>
</CardContent>
</Card>
</div>
);
}

View File

@@ -1,267 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, Power, AlertTriangle, CheckCircle } from 'lucide-react';
interface ShutdownStatus {
isShuttingDown: boolean;
handlerCount: number;
registeredHandlers: string[];
}
export default function DatabaseShutdownPage() {
const [status, setStatus] = useState<ShutdownStatus | null>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
// 獲取關閉狀態
const fetchStatus = async () => {
try {
setLoading(true);
const response = await fetch('/api/test-shutdown?action=status');
const data = await response.json();
if (data.success) {
setStatus(data.data);
setMessage('狀態更新成功');
setError('');
} else {
setError(data.error || '獲取狀態失敗');
}
} catch (err) {
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 測試關閉機制
const testShutdown = async () => {
try {
setLoading(true);
const response = await fetch('/api/test-shutdown?action=test');
const data = await response.json();
if (data.success) {
setMessage('關閉機制測試成功');
setError('');
await fetchStatus(); // 重新獲取狀態
} else {
setError(data.error || '測試失敗');
}
} catch (err) {
setError('測試錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 強制關閉測試
const forceShutdown = async () => {
if (!confirm('確定要執行強制關閉測試嗎?這可能會影響應用程式運行!')) {
return;
}
try {
setLoading(true);
const response = await fetch('/api/test-shutdown?action=force');
const data = await response.json();
if (data.success) {
setMessage('強制關閉測試完成');
setError('');
await fetchStatus(); // 重新獲取狀態
} else {
setError(data.error || '強制關閉測試失敗');
}
} catch (err) {
setError('強制關閉錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 優雅關閉測試
const gracefulShutdown = async () => {
if (!confirm('確定要執行優雅關閉測試嗎?這會關閉所有資料庫連線!')) {
return;
}
try {
setLoading(true);
const response = await fetch('/api/test-shutdown', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'graceful' }),
});
const data = await response.json();
if (data.success) {
setMessage('優雅關閉測試完成');
setError('');
await fetchStatus(); // 重新獲取狀態
} else {
setError(data.error || '優雅關閉測試失敗');
}
} catch (err) {
setError('優雅關閉錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 組件載入時獲取狀態
useEffect(() => {
fetchStatus();
}, []);
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold"></h1>
<p className="text-muted-foreground">
</p>
</div>
<Button
onClick={fetchStatus}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Database className="h-4 w-4" />}
</Button>
</div>
{/* 狀態顯示 */}
{status && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="flex items-center gap-2">
<span className="text-sm font-medium">:</span>
<Badge variant={status.isShuttingDown ? "destructive" : "default"}>
{status.isShuttingDown ? "關閉中" : "正常"}
</Badge>
</div>
<div className="flex items-center gap-2">
<span className="text-sm font-medium">:</span>
<Badge variant="outline">{status.handlerCount}</Badge>
</div>
<div className="flex items-center gap-2">
<span className="text-sm font-medium">:</span>
<Badge variant={status.isShuttingDown ? "destructive" : "default"}>
{status.isShuttingDown ? "異常" : "正常"}
</Badge>
</div>
</div>
<div>
<span className="text-sm font-medium">:</span>
<div className="mt-2 flex flex-wrap gap-2">
{status.registeredHandlers.map((handler, index) => (
<Badge key={index} variant="secondary">
{handler}
</Badge>
))}
</div>
</div>
</CardContent>
</Card>
)}
{/* 操作按鈕 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Power className="h-5 w-5" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Button
onClick={testShutdown}
disabled={loading}
variant="outline"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <CheckCircle className="h-4 w-4" />}
</Button>
<Button
onClick={forceShutdown}
disabled={loading}
variant="destructive"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <AlertTriangle className="h-4 w-4" />}
</Button>
<Button
onClick={gracefulShutdown}
disabled={loading}
variant="destructive"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Power className="h-4 w-4" />}
</Button>
</div>
</CardContent>
</Card>
{/* 訊息顯示 */}
{message && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 說明資訊 */}
<Card>
<CardHeader>
<CardTitle>使</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong>:</strong> </p>
<p> <strong>:</strong> </p>
<p> <strong>:</strong> </p>
<p> SIGINT SIGTERM </p>
<p> </p>
</CardContent>
</Card>
</div>
);
}

View File

@@ -1,281 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, AlertTriangle, Trash2, Eye, Zap } from 'lucide-react';
interface ConnectionDetail {
ID: number;
USER: string;
HOST: string;
DB: string;
COMMAND: string;
TIME: number;
STATE: string;
INFO?: string;
}
interface ConnectionData {
connectionCount: number;
connections: ConnectionDetail[];
}
export default function EmergencyCleanupPage() {
const [connectionData, setConnectionData] = useState<ConnectionData | null>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
// 獲取連線詳情
const fetchConnectionDetails = async () => {
try {
setLoading(true);
const response = await fetch('/api/emergency-cleanup?action=details');
const data = await response.json();
if (data.success) {
setConnectionData(data.data);
setMessage('連線詳情更新成功');
setError('');
} else {
setError(data.error || '獲取連線詳情失敗');
}
} catch (err) {
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 執行緊急清理
const executeEmergencyCleanup = async () => {
if (!confirm('確定要執行緊急清理嗎?這會關閉所有資料庫連線!')) {
return;
}
try {
setLoading(true);
const response = await fetch('/api/emergency-cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'cleanup' }),
});
const data = await response.json();
if (data.success) {
setMessage('緊急清理完成');
setError('');
await fetchConnectionDetails(); // 重新獲取詳情
} else {
setError(data.error || '緊急清理失敗');
}
} catch (err) {
setError('緊急清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 強制殺死所有連線
const forceKillAllConnections = async () => {
if (!confirm('確定要強制殺死所有連線嗎?這會立即終止所有資料庫連線!')) {
return;
}
try {
setLoading(true);
const response = await fetch('/api/emergency-cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'kill-all' }),
});
const data = await response.json();
if (data.success) {
setMessage('強制殺死連線完成');
setError('');
await fetchConnectionDetails(); // 重新獲取詳情
} else {
setError(data.error || '強制殺死連線失敗');
}
} catch (err) {
setError('強制殺死連線錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 組件載入時獲取連線詳情
useEffect(() => {
fetchConnectionDetails();
}, []);
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold text-red-600"></h1>
<p className="text-muted-foreground">
</p>
</div>
<Button
onClick={fetchConnectionDetails}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
{/* 警告提示 */}
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
<strong></strong> 使
</AlertDescription>
</Alert>
{/* 連線統計 */}
{connectionData && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-4">
<Badge variant="outline" className="text-lg px-3 py-1">
: {connectionData.connectionCount}
</Badge>
<Badge
variant={connectionData.connectionCount > 10 ? "destructive" : "default"}
className="text-lg px-3 py-1"
>
: {connectionData.connectionCount > 10 ? "異常" : "正常"}
</Badge>
</div>
</CardContent>
</Card>
)}
{/* 緊急操作 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-red-600">
<Zap className="h-5 w-5" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Button
onClick={executeEmergencyCleanup}
disabled={loading}
variant="destructive"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
</Button>
<Button
onClick={forceKillAllConnections}
disabled={loading}
variant="destructive"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <AlertTriangle className="h-4 w-4" />}
</Button>
</div>
</CardContent>
</Card>
{/* 連線詳情列表 */}
{connectionData && connectionData.connections.length > 0 && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2 max-h-96 overflow-y-auto">
{connectionData.connections.map((conn, index) => (
<div key={conn.ID} className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-4">
<Badge variant="outline">#{conn.ID}</Badge>
<div>
<p className="text-sm font-medium">
: {conn.USER} | : {conn.HOST}
</p>
<p className="text-sm text-muted-foreground">
: {conn.DB} | : {conn.COMMAND}
</p>
<p className="text-sm text-muted-foreground">
: {conn.TIME}s | : {conn.STATE}
</p>
{conn.INFO && (
<p className="text-xs text-muted-foreground mt-1">
: {conn.INFO.length > 100 ? conn.INFO.substring(0, 100) + '...' : conn.INFO}
</p>
)}
</div>
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* 訊息顯示 */}
{message && (
<Alert>
<Database className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 使用說明 */}
<Card>
<CardHeader>
<CardTitle>使</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong>:</strong> </p>
<p> <strong>:</strong> </p>
<p> <strong>:</strong> </p>
<p> 使</p>
</CardContent>
</Card>
</div>
);
}

View File

@@ -1,442 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Loader2, Database, AlertTriangle, Trash2, Eye, Zap, Globe } from 'lucide-react';
interface ConnectionDetail {
ID: number;
USER: string;
HOST: string;
DB: string;
COMMAND: string;
TIME: number;
STATE: string;
INFO?: string;
}
interface ConnectionStatus {
ip: string;
connectionCount: number;
connections: ConnectionDetail[];
}
interface LocalStats {
clientIP: string;
trackedConnections: number;
connections: Array<{
connectionId: string;
createdAt: string;
lastUsed: string;
userAgent?: string;
}>;
}
export default function IPCleanupPage() {
const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus | null>(null);
const [localStats, setLocalStats] = useState<LocalStats | null>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
const [targetIP, setTargetIP] = useState<string>('');
// 獲取當前 IP 的連線狀態
const fetchCurrentIPStatus = async () => {
try {
setLoading(true);
const response = await fetch('/api/ip-cleanup?action=status');
const data = await response.json();
if (data.success) {
setConnectionStatus(data.data);
setMessage('當前 IP 連線狀態更新成功');
setError('');
} else {
setError(data.error || '獲取當前 IP 連線狀態失敗');
}
} catch (err) {
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 獲取指定 IP 的連線狀態
const fetchSpecificIPStatus = async () => {
if (!targetIP.trim()) {
setError('請輸入目標 IP 地址');
return;
}
try {
setLoading(true);
const response = await fetch(`/api/ip-cleanup?action=status-specific&ip=${encodeURIComponent(targetIP)}`);
const data = await response.json();
if (data.success) {
setConnectionStatus(data.data);
setMessage(`指定 IP ${targetIP} 的連線狀態更新成功`);
setError('');
} else {
setError(data.error || '獲取指定 IP 連線狀態失敗');
}
} catch (err) {
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 獲取本地連線統計
const fetchLocalStats = async () => {
try {
setLoading(true);
const response = await fetch('/api/ip-cleanup?action=local-stats');
const data = await response.json();
if (data.success) {
setLocalStats(data.data);
setMessage('本地連線統計更新成功');
setError('');
} else {
setError(data.error || '獲取本地連線統計失敗');
}
} catch (err) {
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 清理當前 IP 的連線
const cleanupCurrentIP = async () => {
if (!confirm('確定要清理當前 IP 的所有連線嗎?')) {
return;
}
try {
setLoading(true);
const response = await fetch('/api/ip-cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'cleanup-current' }),
});
const data = await response.json();
if (data.success) {
setMessage(data.message || '當前 IP 連線清理完成');
setError('');
await fetchCurrentIPStatus(); // 重新獲取狀態
} else {
setError(data.error || '當前 IP 連線清理失敗');
}
} catch (err) {
setError('當前 IP 連線清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 清理指定 IP 的連線
const cleanupSpecificIP = async () => {
if (!targetIP.trim()) {
setError('請輸入目標 IP 地址');
return;
}
if (!confirm(`確定要清理 IP ${targetIP} 的所有連線嗎?`)) {
return;
}
try {
setLoading(true);
const response = await fetch('/api/ip-cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'cleanup-specific',
targetIP: targetIP.trim()
}),
});
const data = await response.json();
if (data.success) {
setMessage(data.message || `IP ${targetIP} 連線清理完成`);
setError('');
await fetchSpecificIPStatus(); // 重新獲取狀態
} else {
setError(data.error || `IP ${targetIP} 連線清理失敗`);
}
} catch (err) {
setError(`IP ${targetIP} 連線清理錯誤: ` + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 清理本地追蹤的連線
const cleanupLocalConnections = async () => {
try {
setLoading(true);
const response = await fetch('/api/ip-cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'cleanup-local' }),
});
const data = await response.json();
if (data.success) {
setMessage(data.message || '本地連線清理完成');
setError('');
await fetchLocalStats(); // 重新獲取統計
} else {
setError(data.error || '本地連線清理失敗');
}
} catch (err) {
setError('本地連線清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 組件載入時獲取狀態
useEffect(() => {
fetchCurrentIPStatus();
fetchLocalStats();
}, []);
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold">IP </h1>
<p className="text-muted-foreground">
IP
</p>
</div>
<div className="flex gap-2">
<Button
onClick={fetchCurrentIPStatus}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Eye className="h-4 w-4" />}
IP
</Button>
<Button
onClick={fetchLocalStats}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Database className="h-4 w-4" />}
</Button>
</div>
</div>
{/* 當前 IP 連線狀態 */}
{connectionStatus && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Globe className="h-5 w-5" />
IP
</CardTitle>
<CardDescription>
IP: {connectionStatus.ip} | : {connectionStatus.connectionCount}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-4">
<Badge variant="outline" className="text-lg px-3 py-1">
: {connectionStatus.connectionCount}
</Badge>
<Badge
variant={connectionStatus.connectionCount > 5 ? "destructive" : "default"}
className="text-lg px-3 py-1"
>
: {connectionStatus.connectionCount > 5 ? "異常" : "正常"}
</Badge>
</div>
</CardContent>
</Card>
)}
{/* 本地連線統計 */}
{localStats && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" />
</CardTitle>
<CardDescription>
IP: {localStats.clientIP} | : {localStats.trackedConnections}
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
{localStats.connections.map((conn, index) => (
<div key={index} className="flex items-center justify-between p-2 border rounded">
<div>
<p className="text-sm font-medium"> ID: {conn.connectionId}</p>
<p className="text-xs text-muted-foreground">
: {new Date(conn.createdAt).toLocaleString()} |
使: {new Date(conn.lastUsed).toLocaleString()}
</p>
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* 操作按鈕 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Trash2 className="h-5 w-5" />
IP
</CardTitle>
<CardDescription>
IP
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Button
onClick={cleanupCurrentIP}
disabled={loading}
variant="destructive"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
IP
</Button>
<Button
onClick={cleanupLocalConnections}
disabled={loading}
variant="outline"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Database className="h-4 w-4" />}
</Button>
</div>
{/* 指定 IP 清理 */}
<div className="space-y-2">
<Label htmlFor="targetIP"> IP </Label>
<div className="flex gap-2">
<Input
id="targetIP"
value={targetIP}
onChange={(e) => setTargetIP(e.target.value)}
placeholder="例如: 192.168.1.100"
className="flex-1"
/>
<Button
onClick={fetchSpecificIPStatus}
disabled={loading || !targetIP.trim()}
variant="outline"
>
<Eye className="h-4 w-4" />
</Button>
<Button
onClick={cleanupSpecificIP}
disabled={loading || !targetIP.trim()}
variant="destructive"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
{/* 連線詳情列表 */}
{connectionStatus && connectionStatus.connections.length > 0 && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
IP {connectionStatus.ip}
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2 max-h-96 overflow-y-auto">
{connectionStatus.connections.map((conn, index) => (
<div key={conn.ID} className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-4">
<Badge variant="outline">#{conn.ID}</Badge>
<div>
<p className="text-sm font-medium">
: {conn.USER} | : {conn.HOST}
</p>
<p className="text-sm text-muted-foreground">
: {conn.DB} | : {conn.COMMAND}
</p>
<p className="text-sm text-muted-foreground">
: {conn.TIME}s | : {conn.STATE}
</p>
{conn.INFO && (
<p className="text-xs text-muted-foreground mt-1">
: {conn.INFO.length > 100 ? conn.INFO.substring(0, 100) + '...' : conn.INFO}
</p>
)}
</div>
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* 訊息顯示 */}
{message && (
<Alert>
<Database className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 使用說明 */}
<Card>
<CardHeader>
<CardTitle>IP </CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong> IP :</strong> </p>
<p> <strong> IP :</strong> IP IP </p>
<p> <strong>:</strong> </p>
<p> <strong>:</strong> IP </p>
<p> <strong>:</strong> IP </p>
</CardContent>
</Card>
</div>
);
}

View File

@@ -1,195 +0,0 @@
"use client"
import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { CheckCircle, Edit, Loader2 } from "lucide-react"
export default function ScoringFormTestPage() {
const [showScoringForm, setShowScoringForm] = useState(false)
const [manualScoring, setManualScoring] = useState({
judgeId: "judge1",
participantId: "app1",
scores: {
"創新性": 0,
"技術性": 0,
"實用性": 0,
"展示效果": 0,
"影響力": 0
},
comments: ""
})
const [isLoading, setIsLoading] = useState(false)
const scoringRules = [
{ name: "創新性", description: "技術創新程度和獨特性", weight: 25 },
{ name: "技術性", description: "技術實現的複雜度和穩定性", weight: 20 },
{ name: "實用性", description: "實際應用價值和用戶體驗", weight: 25 },
{ name: "展示效果", description: "演示效果和表達能力", weight: 15 },
{ name: "影響力", description: "對行業和社會的潛在影響", weight: 15 }
]
const calculateTotalScore = (scores: Record<string, number>): number => {
let totalScore = 0
let totalWeight = 0
scoringRules.forEach(rule => {
const score = scores[rule.name] || 0
const weight = rule.weight || 1
totalScore += score * weight
totalWeight += weight
})
return totalWeight > 0 ? Math.round(totalScore / totalWeight) : 0
}
const handleSubmitScore = async () => {
setIsLoading(true)
// 模擬提交
setTimeout(() => {
setIsLoading(false)
setShowScoringForm(false)
}, 2000)
}
return (
<div className="container mx-auto py-6">
<div className="mb-6">
<h1 className="text-3xl font-bold"></h1>
<p className="text-gray-600"></p>
</div>
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<Button onClick={() => setShowScoringForm(true)} size="lg">
<Edit className="w-5 h-5 mr-2" />
</Button>
</CardContent>
</Card>
<Dialog open={showScoringForm} onOpenChange={setShowScoringForm}>
<DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center space-x-2">
<Edit className="w-5 h-5" />
<span></span>
</DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
<div className="space-y-6">
{/* 評分項目 */}
<div className="space-y-4">
<h3 className="text-lg font-semibold"></h3>
{scoringRules.map((rule, index) => (
<div key={index} className="space-y-4 p-6 border rounded-lg bg-white shadow-sm">
<div className="flex justify-between items-start">
<div className="flex-1">
<Label className="text-lg font-semibold text-gray-900">{rule.name}</Label>
<p className="text-sm text-gray-600 mt-2 leading-relaxed">{rule.description}</p>
<p className="text-xs text-purple-600 mt-2 font-medium">{rule.weight}%</p>
</div>
<div className="text-right ml-4">
<span className="text-2xl font-bold text-blue-600">
{manualScoring.scores[rule.name] || 0} / 10
</span>
</div>
</div>
{/* 評分按鈕 */}
<div className="flex flex-wrap gap-3">
{Array.from({ length: 10 }, (_, i) => i + 1).map((score) => (
<button
key={score}
type="button"
onClick={() => setManualScoring({
...manualScoring,
scores: { ...manualScoring.scores, [rule.name]: score }
})}
className={`w-12 h-12 rounded-lg border-2 font-semibold text-lg transition-all duration-200 ${
(manualScoring.scores[rule.name] || 0) === score
? 'bg-blue-600 text-white border-blue-600 shadow-lg scale-105'
: 'bg-white text-gray-700 border-gray-300 hover:border-blue-400 hover:bg-blue-50 hover:scale-105'
}`}
>
{score}
</button>
))}
</div>
</div>
))}
</div>
{/* 總分顯示 */}
<div className="p-6 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg border-2 border-blue-200">
<div className="flex justify-between items-center">
<div>
<span className="text-xl font-bold text-gray-900"></span>
<p className="text-sm text-gray-600 mt-1"></p>
</div>
<div className="flex items-center space-x-3">
<span className="text-4xl font-bold text-blue-600">
{calculateTotalScore(manualScoring.scores)}
</span>
<span className="text-xl text-gray-500 font-medium">/ 10</span>
</div>
</div>
</div>
{/* 評審意見 */}
<div className="space-y-3">
<Label className="text-lg font-semibold"> *</Label>
<Textarea
placeholder="請詳細填寫評審意見、優點分析、改進建議等..."
value={manualScoring.comments}
onChange={(e) => setManualScoring({ ...manualScoring, comments: e.target.value })}
rows={6}
className="min-h-[120px] resize-none"
/>
<p className="text-xs text-gray-500"></p>
</div>
</div>
<div className="flex justify-end space-x-4 pt-6 border-t border-gray-200">
<Button
variant="outline"
size="lg"
onClick={() => setShowScoringForm(false)}
className="px-8"
>
</Button>
<Button
onClick={handleSubmitScore}
disabled={isLoading}
size="lg"
className="px-8 bg-blue-600 hover:bg-blue-700"
>
{isLoading ? (
<>
<Loader2 className="w-5 h-5 mr-2 animate-spin" />
...
</>
) : (
<>
<CheckCircle className="w-5 h-5 mr-2" />
</>
)}
</Button>
</div>
</DialogContent>
</Dialog>
</div>
)
}

View File

@@ -1,13 +0,0 @@
import { ScoringManagement } from "@/components/admin/scoring-management"
export default function ScoringTestPage() {
return (
<div className="container mx-auto py-6">
<div className="mb-6">
<h1 className="text-3xl font-bold"></h1>
<p className="text-gray-600"></p>
</div>
<ScoringManagement />
</div>
)
}

View File

@@ -1,13 +0,0 @@
import { ScoringManagement } from "@/components/admin/scoring-management"
export default function ScoringPage() {
return (
<div className="container mx-auto py-6">
<div className="mb-6">
<h1 className="text-3xl font-bold"></h1>
<p className="text-gray-600"></p>
</div>
<ScoringManagement />
</div>
)
}

View File

@@ -1,314 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, AlertTriangle, Trash2, Eye, Zap, Skull } from 'lucide-react';
interface ConnectionStatus {
currentConnections: number;
maxConnections: number;
usagePercentage: number;
connectionDetails: Array<{
ID: number;
USER: string;
HOST: string;
DB: string;
COMMAND: string;
TIME: number;
STATE: string;
INFO?: string;
}>;
connectionCount: number;
}
export default function UltimateKillPage() {
const [status, setStatus] = useState<ConnectionStatus | null>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
// 獲取連線狀態
const fetchStatus = async () => {
try {
setLoading(true);
const response = await fetch('/api/ultimate-kill?action=status');
const data = await response.json();
if (data.success) {
setStatus(data.data);
setMessage('狀態更新成功');
setError('');
} else {
setError(data.error || '獲取狀態失敗');
}
} catch (err) {
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 終極清理 - 殺死所有連線
const ultimateKill = async () => {
if (!confirm('確定要執行終極清理嗎?這會強制殺死所有資料庫連線!')) {
return;
}
try {
setLoading(true);
const response = await fetch('/api/ultimate-kill', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'kill-all' }),
});
const data = await response.json();
if (data.success) {
setMessage(data.message || '終極清理完成');
setError('');
await fetchStatus(); // 重新獲取狀態
} else {
setError(data.error || '終極清理失敗');
}
} catch (err) {
setError('終極清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 強制重啟資料庫連線
const forceRestart = async () => {
if (!confirm('確定要強制重啟資料庫連線嗎?這會先殺死所有連線然後重新建立!')) {
return;
}
try {
setLoading(true);
const response = await fetch('/api/ultimate-kill', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'restart' }),
});
const data = await response.json();
if (data.success) {
setMessage(data.message || '強制重啟完成');
setError('');
await fetchStatus(); // 重新獲取狀態
} else {
setError(data.error || '強制重啟失敗');
}
} catch (err) {
setError('強制重啟錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 組件載入時獲取狀態
useEffect(() => {
fetchStatus();
// 每10秒自動更新狀態
const interval = setInterval(fetchStatus, 10000);
return () => clearInterval(interval);
}, []);
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold text-red-600"></h1>
<p className="text-muted-foreground">
-
</p>
</div>
<Button
onClick={fetchStatus}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
{/* 嚴重警告 */}
<Alert variant="destructive">
<Skull className="h-4 w-4" />
<AlertDescription>
<strong></strong>
</AlertDescription>
</Alert>
{/* 連線狀態概覽 */}
{status && (
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<Card>
<CardContent className="p-6">
<div className="flex items-center gap-2">
<Database className="h-5 w-5 text-blue-500" />
<div>
<p className="text-sm font-medium text-muted-foreground"></p>
<p className="text-2xl font-bold">{status.currentConnections}</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-yellow-500" />
<div>
<p className="text-sm font-medium text-muted-foreground"></p>
<p className="text-2xl font-bold">{status.maxConnections}</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center gap-2">
<Zap className="h-5 w-5 text-red-500" />
<div>
<p className="text-sm font-medium text-muted-foreground">使</p>
<p className="text-2xl font-bold">{status.usagePercentage.toFixed(1)}%</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center gap-2">
<Trash2 className="h-5 w-5 text-green-500" />
<div>
<p className="text-sm font-medium text-muted-foreground"></p>
<p className="text-2xl font-bold">
{status.connectionCount <= 1 ? '正常' : '異常'}
</p>
</div>
</div>
</CardContent>
</Card>
</div>
)}
{/* 終極操作 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-red-600">
<Skull className="h-5 w-5" />
</CardTitle>
<CardDescription>
-
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Button
onClick={ultimateKill}
disabled={loading}
variant="destructive"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Skull className="h-4 w-4" />}
-
</Button>
<Button
onClick={forceRestart}
disabled={loading}
variant="destructive"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Zap className="h-4 w-4" />}
</Button>
</div>
</CardContent>
</Card>
{/* 連線詳情列表 */}
{status && status.connectionDetails.length > 0 && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2 max-h-96 overflow-y-auto">
{status.connectionDetails.map((conn, index) => (
<div key={conn.ID} className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-4">
<Badge variant="outline">#{conn.ID}</Badge>
<div>
<p className="text-sm font-medium">
: {conn.USER} | : {conn.HOST}
</p>
<p className="text-sm text-muted-foreground">
: {conn.DB} | : {conn.COMMAND}
</p>
<p className="text-sm text-muted-foreground">
: {conn.TIME}s | : {conn.STATE}
</p>
{conn.INFO && (
<p className="text-xs text-muted-foreground mt-1">
: {conn.INFO.length > 100 ? conn.INFO.substring(0, 100) + '...' : conn.INFO}
</p>
)}
</div>
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* 訊息顯示 */}
{message && (
<Alert>
<Database className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 使用說明 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong>:</strong> </p>
<p> <strong>:</strong> </p>
<p> <strong>:</strong> 10</p>
<p> <strong>:</strong> </p>
<p> 使</p>
</CardContent>
</Card>
</div>
);
}

View File

@@ -1,122 +0,0 @@
// =====================================================
// 連線監控 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { smartPool } from '@/lib/smart-connection-pool';
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const action = searchParams.get('action') || 'stats';
switch (action) {
case 'stats':
// 獲取連線統計
const stats = smartPool.getConnectionStats();
return NextResponse.json({
success: true,
message: '連線統計獲取成功',
data: stats
});
case 'cleanup':
// 強制清理連線
console.log('🧹 執行強制連線清理...');
smartPool.forceCleanup();
const newStats = smartPool.getConnectionStats();
return NextResponse.json({
success: true,
message: '連線清理完成',
data: newStats
});
case 'test':
// 測試智能連線
try {
const testResult = await smartPool.executeQueryOne(
'SELECT 1 as test_value',
[],
{ userId: 'test', sessionId: 'test-session', requestId: 'test-request' }
);
return NextResponse.json({
success: true,
message: '智能連線測試成功',
data: {
testResult,
stats: smartPool.getConnectionStats()
}
});
} catch (error) {
return NextResponse.json({
success: false,
error: '智能連線測試失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['stats', 'cleanup', 'test']
}, { status: 400 });
}
} catch (error) {
console.error('❌ 連線監控 API 錯誤:', error);
return NextResponse.json({
success: false,
error: 'API 請求失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { action, maxIdleTime, maxConnectionAge } = body;
switch (action) {
case 'config':
// 更新清理配置
smartPool.setCleanupParams(maxIdleTime, maxConnectionAge);
return NextResponse.json({
success: true,
message: '清理配置更新成功',
data: {
maxIdleTime: maxIdleTime || '未變更',
maxConnectionAge: maxConnectionAge || '未變更'
}
});
case 'cleanup':
// 強制清理連線
console.log('🧹 執行強制連線清理...');
smartPool.forceCleanup();
const stats = smartPool.getConnectionStats();
return NextResponse.json({
success: true,
message: '連線清理完成',
data: stats
});
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['config', 'cleanup']
}, { status: 400 });
}
} catch (error) {
console.error('❌ 連線監控 POST API 錯誤:', error);
return NextResponse.json({
success: false,
error: 'API 請求失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}

View File

@@ -1,59 +0,0 @@
// =====================================================
// IP 調試 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { smartIPDetector } from '@/lib/smart-ip-detector';
export async function GET(request: NextRequest) {
try {
// 使用智能 IP 偵測器
const ipDetection = smartIPDetector.detectClientIP(request);
// 收集所有可能的 IP 信息
const ipInfo = {
// 智能偵測結果
smartDetection: ipDetection,
// 請求標頭
headers: {
'x-forwarded-for': request.headers.get('x-forwarded-for'),
'x-real-ip': request.headers.get('x-real-ip'),
'cf-connecting-ip': request.headers.get('cf-connecting-ip'),
'x-client-ip': request.headers.get('x-client-ip'),
'x-forwarded': request.headers.get('x-forwarded'),
'x-cluster-client-ip': request.headers.get('x-cluster-client-ip'),
'x-original-forwarded-for': request.headers.get('x-original-forwarded-for'),
'x-remote-addr': request.headers.get('x-remote-addr'),
'remote-addr': request.headers.get('remote-addr'),
'client-ip': request.headers.get('client-ip'),
'user-agent': request.headers.get('user-agent'),
'host': request.headers.get('host'),
},
// NextRequest 的 IP
nextRequestIP: request.ip,
// 環境變數
env: {
NODE_ENV: process.env.NODE_ENV,
VERCEL: process.env.VERCEL,
VERCEL_REGION: process.env.VERCEL_REGION,
},
// 所有標頭(用於調試)
allHeaders: Object.fromEntries(request.headers.entries()),
};
return NextResponse.json({
success: true,
message: 'IP 調試信息獲取成功',
data: ipInfo,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('❌ IP 調試 API 錯誤:', error);
return NextResponse.json({
success: false,
error: 'IP 調試失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}

View File

@@ -1,45 +0,0 @@
// =====================================================
// 調試競賽 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { CompetitionService } from '@/lib/services/database-service';
// 獲取所有競賽和當前競賽狀態
export async function GET(request: NextRequest) {
try {
// 獲取所有競賽
const allCompetitions = await CompetitionService.getAllCompetitions();
// 獲取當前競賽
const currentCompetition = await CompetitionService.getCurrentCompetition();
return NextResponse.json({
success: true,
data: {
allCompetitions: allCompetitions.map(c => ({
id: c.id,
name: c.name,
status: c.status,
is_current: c.is_current,
is_active: c.is_active
})),
currentCompetition: currentCompetition ? {
id: currentCompetition.id,
name: currentCompetition.name,
status: currentCompetition.status,
is_current: currentCompetition.is_current,
is_active: currentCompetition.is_active
} : null
}
});
} catch (error) {
console.error('調試競賽失敗:', error);
return NextResponse.json({
success: false,
message: '調試競賽失敗',
error: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}

View File

@@ -1,54 +0,0 @@
// =====================================================
// 環境變數調試 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
try {
console.log('🔍 檢查 Next.js 中的環境變數...');
// 檢查所有相關的環境變數
const envVars = {
DB_HOST: process.env.DB_HOST,
DB_PORT: process.env.DB_PORT,
DB_NAME: process.env.DB_NAME,
DB_USER: process.env.DB_USER,
DB_PASSWORD: process.env.DB_PASSWORD ? '***' : undefined,
SLAVE_DB_HOST: process.env.SLAVE_DB_HOST,
SLAVE_DB_PORT: process.env.SLAVE_DB_PORT,
SLAVE_DB_NAME: process.env.SLAVE_DB_NAME,
SLAVE_DB_USER: process.env.SLAVE_DB_USER,
SLAVE_DB_PASSWORD: process.env.SLAVE_DB_PASSWORD ? '***' : undefined,
DB_DUAL_WRITE_ENABLED: process.env.DB_DUAL_WRITE_ENABLED,
DB_MASTER_PRIORITY: process.env.DB_MASTER_PRIORITY,
NODE_ENV: process.env.NODE_ENV,
};
console.log('📋 Next.js 環境變數檢查結果:');
Object.entries(envVars).forEach(([key, value]) => {
if (value) {
console.log(`${key}: ${value}`);
} else {
console.log(`${key}: undefined`);
}
});
return NextResponse.json({
success: true,
message: '環境變數檢查完成',
data: {
envVars,
timestamp: new Date().toISOString(),
nodeEnv: process.env.NODE_ENV,
}
});
} catch (error) {
console.error('❌ 環境變數檢查失敗:', error);
return NextResponse.json({
success: false,
message: '環境變數檢查失敗',
error: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}

View File

@@ -1,44 +0,0 @@
// =====================================================
// 簡單環境變數測試
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
try {
// 直接檢查環境變數
const envCheck = {
NODE_ENV: process.env.NODE_ENV,
DB_HOST: process.env.DB_HOST,
DB_PORT: process.env.DB_PORT,
DB_NAME: process.env.DB_NAME,
DB_USER: process.env.DB_USER,
DB_PASSWORD: process.env.DB_PASSWORD ? '***' : undefined,
// 檢查所有可能的環境變數
ALL_ENV_KEYS: Object.keys(process.env).filter(key => key.startsWith('DB_')),
};
console.log('🔍 環境變數檢查:');
console.log('NODE_ENV:', process.env.NODE_ENV);
console.log('DB_HOST:', process.env.DB_HOST);
console.log('DB_PORT:', process.env.DB_PORT);
console.log('DB_NAME:', process.env.DB_NAME);
console.log('DB_USER:', process.env.DB_USER);
console.log('DB_PASSWORD:', process.env.DB_PASSWORD ? '***' : 'undefined');
console.log('所有 DB_ 開頭的環境變數:', Object.keys(process.env).filter(key => key.startsWith('DB_')));
return NextResponse.json({
success: true,
message: '環境變數檢查完成',
data: envCheck,
timestamp: new Date().toISOString(),
});
} catch (error) {
console.error('❌ 環境變數檢查失敗:', error);
return NextResponse.json({
success: false,
message: '環境變數檢查失敗',
error: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}

View File

@@ -1,104 +0,0 @@
// =====================================================
// 緊急連線清理 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { emergencyCleanup } from '@/lib/emergency-connection-cleanup';
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { action } = body;
switch (action) {
case 'cleanup':
// 執行緊急清理
console.log('🚨 收到緊急清理請求');
await emergencyCleanup.emergencyCleanup();
return NextResponse.json({
success: true,
message: '緊急清理完成',
timestamp: new Date().toISOString()
});
case 'kill-all':
// 強制殺死所有連線
console.log('💀 收到強制殺死連線請求');
await emergencyCleanup.forceKillAllConnections();
return NextResponse.json({
success: true,
message: '強制殺死連線完成',
timestamp: new Date().toISOString()
});
case 'details':
// 獲取連線詳情
const connections = await emergencyCleanup.getConnectionDetails();
return NextResponse.json({
success: true,
message: '連線詳情獲取成功',
data: {
connectionCount: connections.length,
connections: connections
},
timestamp: new Date().toISOString()
});
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['cleanup', 'kill-all', 'details']
}, { status: 400 });
}
} catch (error) {
console.error('❌ 緊急清理 API 錯誤:', error);
return NextResponse.json({
success: false,
error: '緊急清理失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const action = searchParams.get('action') || 'details';
switch (action) {
case 'details':
// 獲取連線詳情
const connections = await emergencyCleanup.getConnectionDetails();
return NextResponse.json({
success: true,
message: '連線詳情獲取成功',
data: {
connectionCount: connections.length,
connections: connections
},
timestamp: new Date().toISOString()
});
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['details']
}, { status: 400 });
}
} catch (error) {
console.error('❌ 緊急清理 GET API 錯誤:', error);
return NextResponse.json({
success: false,
error: '獲取連線詳情失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}

View File

@@ -1,177 +0,0 @@
// =====================================================
// 基於 IP 的連線清理 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { smartIPPool } from '@/lib/smart-ip-connection-pool';
import { smartIPDetector } from '@/lib/smart-ip-detector';
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { action, targetIP } = body;
// 使用智能 IP 偵測器
const ipDetection = smartIPDetector.detectClientIP(request);
const clientIP = ipDetection.detectedIP;
console.log('🎯 智能 IP 偵測結果:', {
detectedIP: clientIP,
confidence: ipDetection.confidence,
source: ipDetection.source,
isPublicIP: ipDetection.isPublicIP,
allCandidates: ipDetection.allCandidates
});
// 設置客戶端 IP
smartIPPool.setClientIP(clientIP);
switch (action) {
case 'cleanup-current':
// 清理當前 IP 的連線
console.log(`🧹 收到清理當前 IP 連線請求: ${clientIP}`);
const cleanupResult = await smartIPPool.cleanupCurrentIPConnections();
return NextResponse.json({
success: cleanupResult.success,
message: cleanupResult.message,
data: {
clientIP,
killedCount: cleanupResult.killedCount
},
timestamp: new Date().toISOString()
});
case 'cleanup-specific':
// 清理指定 IP 的連線
if (!targetIP) {
return NextResponse.json({
success: false,
error: '缺少目標 IP 參數'
}, { status: 400 });
}
console.log(`🧹 收到清理指定 IP 連線請求: ${targetIP}`);
const specificCleanupResult = await smartIPPool.cleanupIPConnections(targetIP);
return NextResponse.json({
success: specificCleanupResult.success,
message: specificCleanupResult.message,
data: {
targetIP,
killedCount: specificCleanupResult.killedCount
},
timestamp: new Date().toISOString()
});
case 'cleanup-local':
// 清理本地追蹤的連線
console.log('🧹 收到清理本地連線請求');
const localCleanupCount = smartIPPool.cleanupLocalConnections();
return NextResponse.json({
success: true,
message: `已清理 ${localCleanupCount} 個本地追蹤的連線`,
data: {
clientIP,
cleanedCount: localCleanupCount
},
timestamp: new Date().toISOString()
});
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['cleanup-current', 'cleanup-specific', 'cleanup-local']
}, { status: 400 });
}
} catch (error) {
console.error('❌ IP 清理 API 錯誤:', error);
return NextResponse.json({
success: false,
error: 'IP 清理失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const action = searchParams.get('action') || 'status';
const targetIP = searchParams.get('ip');
// 使用智能 IP 偵測器
const ipDetection = smartIPDetector.detectClientIP(request);
const clientIP = ipDetection.detectedIP;
// 設置客戶端 IP
smartIPPool.setClientIP(clientIP);
switch (action) {
case 'status':
// 獲取當前 IP 的連線狀態
const currentIPStatus = await smartIPPool.getCurrentIPConnections();
return NextResponse.json({
success: true,
message: '連線狀態獲取成功',
data: {
detectedIP: clientIP,
...currentIPStatus
},
timestamp: new Date().toISOString()
});
case 'status-specific':
// 獲取指定 IP 的連線狀態
if (!targetIP) {
return NextResponse.json({
success: false,
error: '缺少目標 IP 參數'
}, { status: 400 });
}
const specificIPStatus = await smartIPPool.getIPConnections(targetIP);
return NextResponse.json({
success: true,
message: '指定 IP 連線狀態獲取成功',
data: {
targetIP,
...specificIPStatus
},
timestamp: new Date().toISOString()
});
case 'local-stats':
// 獲取本地連線統計
const localStats = smartIPPool.getLocalConnectionStats();
return NextResponse.json({
success: true,
message: '本地連線統計獲取成功',
data: {
detectedIP: clientIP,
...localStats
},
timestamp: new Date().toISOString()
});
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['status', 'status-specific', 'local-stats']
}, { status: 400 });
}
} catch (error) {
console.error('❌ IP 清理 GET API 錯誤:', error);
return NextResponse.json({
success: false,
error: '獲取連線狀態失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}

View File

@@ -1,78 +0,0 @@
// =====================================================
// 手動設置客戶端 IP API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { smartIPPool } from '@/lib/smart-ip-connection-pool';
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { clientIP } = body;
if (!clientIP) {
return NextResponse.json({
success: false,
error: '缺少客戶端 IP 參數'
}, { status: 400 });
}
console.log('🔧 手動設置客戶端 IP:', clientIP);
// 設置客戶端 IP
smartIPPool.setClientIP(clientIP);
return NextResponse.json({
success: true,
message: `客戶端 IP 已設置為: ${clientIP}`,
data: {
clientIP,
timestamp: new Date().toISOString()
}
});
} catch (error) {
console.error('❌ 設置客戶端 IP 失敗:', error);
return NextResponse.json({
success: false,
error: '設置客戶端 IP 失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const clientIP = searchParams.get('ip');
if (!clientIP) {
return NextResponse.json({
success: false,
error: '缺少 IP 參數'
}, { status: 400 });
}
console.log('🔧 通過 GET 設置客戶端 IP:', clientIP);
// 設置客戶端 IP
smartIPPool.setClientIP(clientIP);
return NextResponse.json({
success: true,
message: `客戶端 IP 已設置為: ${clientIP}`,
data: {
clientIP,
timestamp: new Date().toISOString()
}
});
} catch (error) {
console.error('❌ 設置客戶端 IP 失敗:', error);
return NextResponse.json({
success: false,
error: '設置客戶端 IP 失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}

View File

@@ -1,59 +0,0 @@
// =====================================================
// 智能連線清理 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { smartConnectionCleaner } from '@/lib/smart-connection-cleaner';
export async function POST(request: NextRequest) {
try {
console.log('🧠 收到智能清理請求');
// 執行智能清理
const result = await smartConnectionCleaner.smartCleanup(request);
return NextResponse.json({
success: result.success,
message: result.message,
data: {
killedCount: result.killedCount,
details: result.details,
timestamp: new Date().toISOString()
}
});
} catch (error) {
console.error('❌ 智能清理 API 錯誤:', error);
return NextResponse.json({
success: false,
error: '智能清理失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}
export async function GET(request: NextRequest) {
try {
console.log('📊 收到連線統計請求');
// 獲取連線統計
const stats = await smartConnectionCleaner.getConnectionStats();
return NextResponse.json({
success: true,
message: '連線統計獲取成功',
data: {
stats,
timestamp: new Date().toISOString()
}
});
} catch (error) {
console.error('❌ 連線統計 API 錯誤:', error);
return NextResponse.json({
success: false,
error: '獲取連線統計失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}

View File

@@ -1,38 +0,0 @@
// =====================================================
// 資料庫連接測試 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/database';
export async function GET(request: NextRequest) {
try {
// 測試基本查詢
const result = await db.query('SELECT 1 as test');
// 測試競賽表
const competitions = await db.query('SELECT id, name, type FROM competitions WHERE is_active = TRUE LIMIT 3');
// 測試評審表
const judges = await db.query('SELECT id, name, title FROM judges WHERE is_active = TRUE LIMIT 3');
return NextResponse.json({
success: true,
message: '資料庫連接測試成功',
data: {
basicQuery: result,
competitions: competitions,
judges: judges
}
});
} catch (error) {
console.error('❌ 資料庫連接測試失敗:', error);
return NextResponse.json({
success: false,
message: '資料庫連接測試失敗',
error: error instanceof Error ? error.message : '未知錯誤',
stack: error instanceof Error ? error.stack : undefined
}, { status: 500 });
}
}

View File

@@ -1,100 +0,0 @@
// =====================================================
// 測試資料庫關閉機制 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { dbShutdownManager } from '@/lib/database-shutdown-manager';
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const action = searchParams.get('action') || 'status';
switch (action) {
case 'status':
// 獲取關閉狀態
const status = dbShutdownManager.getShutdownStatus();
return NextResponse.json({
success: true,
message: '關閉狀態查詢成功',
data: status
});
case 'test':
// 測試關閉機制(不會真的關閉)
console.log('🧪 測試關閉機制...');
const testStatus = dbShutdownManager.getShutdownStatus();
return NextResponse.json({
success: true,
message: '關閉機制測試成功',
data: {
...testStatus,
testTime: new Date().toISOString()
}
});
case 'force':
// 強制關閉(僅用於測試)
console.log('🚨 執行強制關閉測試...');
dbShutdownManager.forceShutdown();
return NextResponse.json({
success: true,
message: '強制關閉測試完成',
data: {
timestamp: new Date().toISOString()
}
});
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['status', 'test', 'force']
}, { status: 400 });
}
} catch (error) {
console.error('❌ 測試關閉機制時發生錯誤:', error);
return NextResponse.json({
success: false,
error: '測試失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { action } = body;
switch (action) {
case 'graceful':
// 優雅關閉(僅用於測試)
console.log('🔄 執行優雅關閉測試...');
await dbShutdownManager.gracefulShutdown();
return NextResponse.json({
success: true,
message: '優雅關閉測試完成',
data: {
timestamp: new Date().toISOString()
}
});
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['graceful']
}, { status: 400 });
}
} catch (error) {
console.error('❌ 執行關閉測試時發生錯誤:', error);
return NextResponse.json({
success: false,
error: '關閉測試失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}

View File

@@ -1,96 +0,0 @@
// =====================================================
// 終極連線清理 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { ultimateKiller } from '@/lib/ultimate-connection-killer';
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { action } = body;
switch (action) {
case 'kill-all':
// 終極清理 - 殺死所有連線
console.log('💀 收到終極清理請求');
const killResult = await ultimateKiller.ultimateKill();
return NextResponse.json({
success: killResult.success,
message: killResult.message || '終極清理完成',
data: killResult,
timestamp: new Date().toISOString()
});
case 'restart':
// 強制重啟資料庫連線
console.log('🔄 收到強制重啟請求');
const restartResult = await ultimateKiller.forceRestart();
return NextResponse.json({
success: restartResult.success,
message: restartResult.message || '強制重啟完成',
data: restartResult,
timestamp: new Date().toISOString()
});
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['kill-all', 'restart']
}, { status: 400 });
}
} catch (error) {
console.error('❌ 終極清理 API 錯誤:', error);
return NextResponse.json({
success: false,
error: '終極清理失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const action = searchParams.get('action') || 'status';
switch (action) {
case 'status':
// 檢查連線狀態
const status = await ultimateKiller.checkStatus();
if (status) {
return NextResponse.json({
success: true,
message: '連線狀態獲取成功',
data: status,
timestamp: new Date().toISOString()
});
} else {
return NextResponse.json({
success: false,
error: '無法獲取連線狀態'
}, { status: 500 });
}
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['status']
}, { status: 400 });
}
} catch (error) {
console.error('❌ 終極清理 GET API 錯誤:', error);
return NextResponse.json({
success: false,
error: '獲取連線狀態失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}

View File

@@ -1,297 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, CheckCircle, AlertTriangle, RefreshCw, Trash2 } from 'lucide-react';
interface IPDetectionResult {
detectedIP: string;
confidence: 'high' | 'medium' | 'low';
source: string;
isPublicIP: boolean;
allCandidates: string[];
}
interface ConnectionStatus {
ip: string;
connectionCount: number;
connections: any[];
}
export default function AutoIPTestPage() {
const [ipDetection, setIpDetection] = useState<IPDetectionResult | null>(null);
const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus | null>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
// 自動偵測 IP
const detectIP = async () => {
try {
setLoading(true);
const response = await fetch('/api/debug-ip');
const data = await response.json();
if (data.success && data.data.smartDetection) {
setIpDetection(data.data.smartDetection);
setMessage(`IP 偵測成功: ${data.data.smartDetection.detectedIP}`);
setError('');
} else {
setError('IP 偵測失敗');
}
} catch (err) {
setError('IP 偵測錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 獲取連線狀態
const getConnectionStatus = async () => {
try {
setLoading(true);
const response = await fetch('/api/ip-cleanup?action=status');
const data = await response.json();
if (data.success) {
setConnectionStatus(data.data);
setMessage(`連線狀態獲取成功: ${data.data.connectionCount} 個連線`);
setError('');
} else {
setError('獲取連線狀態失敗');
}
} catch (err) {
setError('獲取連線狀態錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 清理當前 IP 連線
const cleanupConnections = async () => {
try {
setLoading(true);
const response = await fetch('/api/ip-cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'cleanup-current' }),
});
const data = await response.json();
if (data.success) {
setMessage(`清理成功: ${data.message}`);
setError('');
// 重新獲取連線狀態
await getConnectionStatus();
} else {
setError(data.error || '清理失敗');
}
} catch (err) {
setError('清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 組件載入時自動偵測
useEffect(() => {
detectIP();
}, []);
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold"> IP </h1>
<p className="text-muted-foreground">
IP
</p>
</div>
<div className="flex gap-2">
<Button
onClick={detectIP}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
IP
</Button>
<Button
onClick={getConnectionStatus}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Database className="h-4 w-4" />}
</Button>
</div>
</div>
{/* IP 偵測結果 */}
{ipDetection && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<CheckCircle className="h-5 w-5" />
IP
</CardTitle>
<CardDescription>
IP
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-4">
<Badge
variant={ipDetection.isPublicIP ? "default" : "secondary"}
className="text-lg px-3 py-1"
>
{ipDetection.detectedIP}
</Badge>
<Badge
variant={
ipDetection.confidence === 'high' ? "default" :
ipDetection.confidence === 'medium' ? "secondary" : "destructive"
}
className="text-lg px-3 py-1"
>
: {ipDetection.confidence}
</Badge>
<Badge variant="outline" className="text-lg px-3 py-1">
: {ipDetection.source}
</Badge>
</div>
{ipDetection.allCandidates.length > 1 && (
<div>
<p className="text-sm font-medium mb-2"> IP:</p>
<div className="flex flex-wrap gap-2">
{ipDetection.allCandidates.map((ip, index) => (
<Badge
key={index}
variant={ip === ipDetection.detectedIP ? "default" : "outline"}
className="text-sm"
>
{ip}
</Badge>
))}
</div>
</div>
)}
</CardContent>
</Card>
)}
{/* 連線狀態 */}
{connectionStatus && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" />
</CardTitle>
<CardDescription>
IP
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-4">
<Badge variant="default" className="text-lg px-3 py-1">
IP: {connectionStatus.ip}
</Badge>
<Badge
variant={connectionStatus.connectionCount > 0 ? "destructive" : "default"}
className="text-lg px-3 py-1"
>
: {connectionStatus.connectionCount}
</Badge>
</div>
{connectionStatus.connections.length > 0 && (
<div>
<p className="text-sm font-medium mb-2">:</p>
<div className="space-y-2 max-h-48 overflow-y-auto">
{connectionStatus.connections.map((conn, index) => (
<div key={index} className="flex items-center justify-between p-2 border rounded text-sm">
<span>ID: {conn.ID}</span>
<span>HOST: {conn.HOST}</span>
<span>: {conn.TIME}s</span>
<span>: {conn.STATE || 'Sleep'}</span>
</div>
))}
</div>
</div>
)}
</CardContent>
</Card>
)}
{/* 操作按鈕 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
IP
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex gap-4">
<Button
onClick={cleanupConnections}
disabled={loading || !ipDetection}
variant="destructive"
className="flex-1"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
</Button>
<Button
onClick={getConnectionStatus}
disabled={loading}
variant="outline"
className="flex-1"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
</Button>
</div>
</CardContent>
</Card>
{/* 使用說明 */}
<Card>
<CardHeader>
<CardTitle>使</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong>:</strong> IP </p>
<p> <strong>:</strong> 使 IP </p>
<p> <strong>:</strong> IP </p>
<p> <strong>:</strong> IP </p>
<p> <strong>:</strong> </p>
</CardContent>
</Card>
{/* 訊息顯示 */}
{message && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
</div>
);
}

View File

@@ -1,325 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, Eye, RefreshCw } from 'lucide-react';
interface IPInfo {
smartDetection?: {
detectedIP: string;
confidence: 'high' | 'medium' | 'low';
source: string;
allCandidates: string[];
isPublicIP: boolean;
};
headers: Record<string, string | null>;
nextRequestIP: string | undefined;
env: Record<string, string | undefined>;
allHeaders: Record<string, string>;
}
export default function DebugIPPage() {
const [ipInfo, setIpInfo] = useState<IPInfo | null>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
const [recommendedIP, setRecommendedIP] = useState<string>('');
// 獲取 IP 調試信息
const fetchIPInfo = async () => {
try {
setLoading(true);
const response = await fetch('/api/debug-ip');
const data = await response.json();
if (data.success) {
setIpInfo(data.data);
// 提取智能偵測結果
if (data.data.smartDetection) {
const smartDetection = data.data.smartDetection;
setRecommendedIP(smartDetection.detectedIP);
setMessage(`智能偵測結果: ${smartDetection.detectedIP} (可信度: ${smartDetection.confidence}, 來源: ${smartDetection.source})`);
} else {
setMessage('IP 調試信息更新成功');
}
setError('');
} else {
setError(data.error || '獲取 IP 調試信息失敗');
}
} catch (err) {
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 組件載入時獲取 IP 信息
useEffect(() => {
fetchIPInfo();
}, []);
// 獲取推薦的 IP
const getRecommendedIP = () => {
if (!ipInfo) return 'unknown';
// 優先使用智能偵測結果
if (ipInfo.smartDetection) {
return ipInfo.smartDetection.detectedIP;
}
// 回退到舊的邏輯
const { headers, nextRequestIP } = ipInfo;
// 優先順序檢查
if (headers['cf-connecting-ip']) return headers['cf-connecting-ip'];
if (headers['x-real-ip']) return headers['x-real-ip'];
if (headers['x-client-ip']) return headers['x-client-ip'];
if (headers['x-cluster-client-ip']) return headers['x-cluster-client-ip'];
if (headers['x-forwarded']) return headers['x-forwarded'];
if (headers['x-forwarded-for']) {
const ips = headers['x-forwarded-for']!.split(',').map(ip => ip.trim());
const publicIPs = ips.filter(ip =>
ip &&
ip !== '127.0.0.1' &&
ip !== '::1' &&
!ip.startsWith('192.168.') &&
!ip.startsWith('10.') &&
!ip.startsWith('172.')
);
if (publicIPs.length > 0) return publicIPs[0];
return ips[0];
}
if (nextRequestIP && nextRequestIP !== '::1' && nextRequestIP !== '127.0.0.1') {
return nextRequestIP;
}
return 'unknown';
};
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold">IP 調</h1>
<p className="text-muted-foreground">
調 IP
</p>
</div>
<Button
onClick={fetchIPInfo}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
</Button>
</div>
{/* 智能偵測結果 */}
{ipInfo?.smartDetection && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Eye className="h-5 w-5" />
IP
</CardTitle>
<CardDescription>
使 IP
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-4">
<Badge
variant={ipInfo.smartDetection.isPublicIP ? "default" : "secondary"}
className="text-lg px-3 py-1"
>
{ipInfo.smartDetection.detectedIP}
</Badge>
<Badge
variant={
ipInfo.smartDetection.confidence === 'high' ? "default" :
ipInfo.smartDetection.confidence === 'medium' ? "secondary" : "destructive"
}
className="text-lg px-3 py-1"
>
: {ipInfo.smartDetection.confidence}
</Badge>
<Badge variant="outline" className="text-lg px-3 py-1">
: {ipInfo.smartDetection.source}
</Badge>
</div>
{ipInfo.smartDetection.allCandidates.length > 1 && (
<div>
<p className="text-sm font-medium mb-2"> IP:</p>
<div className="flex flex-wrap gap-2">
{ipInfo.smartDetection.allCandidates.map((ip, index) => (
<Badge
key={index}
variant={ip === ipInfo.smartDetection.detectedIP ? "default" : "outline"}
className="text-sm"
>
{ip}
</Badge>
))}
</div>
</div>
)}
</CardContent>
</Card>
)}
{/* 推薦的 IP (回退顯示) */}
{ipInfo && !ipInfo.smartDetection && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Eye className="h-5 w-5" />
IP
</CardTitle>
<CardDescription>
使 IP
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center gap-4">
<Badge variant="default" className="text-lg px-3 py-1">
{getRecommendedIP()}
</Badge>
<Badge
variant={getRecommendedIP() === 'unknown' ? "destructive" : "default"}
className="text-lg px-3 py-1"
>
: {getRecommendedIP() === 'unknown' ? "無法識別" : "已識別"}
</Badge>
</div>
</CardContent>
</Card>
)}
{/* 請求標頭 */}
{ipInfo && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
HTTP IP
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
{Object.entries(ipInfo.headers).map(([key, value]) => (
<div key={key} className="flex items-center justify-between p-2 border rounded">
<span className="font-medium text-sm">{key}:</span>
<span className="text-sm text-muted-foreground">
{value || 'null'}
</span>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* NextRequest IP */}
{ipInfo && (
<Card>
<CardHeader>
<CardTitle>NextRequest IP</CardTitle>
<CardDescription>
Next.js IP
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center gap-4">
<Badge variant="outline" className="text-lg px-3 py-1">
{ipInfo.nextRequestIP || 'undefined'}
</Badge>
</div>
</CardContent>
</Card>
)}
{/* 環境信息 */}
{ipInfo && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
{Object.entries(ipInfo.env).map(([key, value]) => (
<div key={key} className="flex items-center justify-between p-2 border rounded">
<span className="font-medium text-sm">{key}:</span>
<span className="text-sm text-muted-foreground">
{value || 'undefined'}
</span>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* 所有標頭(用於調試) */}
{ipInfo && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
HTTP
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2 max-h-96 overflow-y-auto">
{Object.entries(ipInfo.allHeaders).map(([key, value]) => (
<div key={key} className="flex items-center justify-between p-2 border rounded text-xs">
<span className="font-medium">{key}:</span>
<span className="text-muted-foreground break-all">
{value}
</span>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* 訊息顯示 */}
{message && (
<Alert>
<Database className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<Eye className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* 使用說明 */}
<Card>
<CardHeader>
<CardTitle>使</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong> IP:</strong> 使 IP </p>
<p> <strong>:</strong> IP </p>
<p> <strong>NextRequest IP:</strong> Next.js IP </p>
<p> <strong>:</strong> </p>
<p> IP "unknown"</p>
</CardContent>
</Card>
</div>
);
}

View File

@@ -1,180 +0,0 @@
'use client'
import { useEffect, useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
export default function DebugScoringPage() {
const [competitions, setCompetitions] = useState<any[]>([])
const [selectedCompetition, setSelectedCompetition] = useState<any>(null)
const [competitionJudges, setCompetitionJudges] = useState<any[]>([])
const [competitionParticipants, setCompetitionParticipants] = useState<any[]>([])
const [loading, setLoading] = useState(false)
const [logs, setLogs] = useState<string[]>([])
const addLog = (message: string) => {
setLogs(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`])
}
// 載入競賽列表
const loadCompetitions = async () => {
try {
addLog('🔄 開始載入競賽列表...')
const response = await fetch('/api/competitions')
const data = await response.json()
addLog(`📋 競賽API回應: ${JSON.stringify(data)}`)
if (data.success && data.data) {
setCompetitions(data.data)
addLog(`✅ 載入 ${data.data.length} 個競賽`)
} else {
addLog(`❌ 競賽載入失敗: ${data.message}`)
}
} catch (error) {
addLog(`❌ 競賽載入錯誤: ${error.message}`)
}
}
// 載入競賽數據
const loadCompetitionData = async (competitionId: string) => {
if (!competitionId) return
setLoading(true)
addLog(`🔍 開始載入競賽數據ID: ${competitionId}`)
try {
// 載入評審
addLog('📋 載入評審...')
const judgesResponse = await fetch(`/api/competitions/${competitionId}/judges`)
const judgesData = await judgesResponse.json()
addLog(`評審API回應: ${JSON.stringify(judgesData)}`)
if (judgesData.success && judgesData.data && judgesData.data.judges) {
setCompetitionJudges(judgesData.data.judges)
addLog(`✅ 載入 ${judgesData.data.judges.length} 個評審`)
} else {
addLog(`❌ 評審載入失敗: ${judgesData.message}`)
setCompetitionJudges([])
}
// 載入參賽者
addLog('📱 載入參賽者...')
const [appsResponse, teamsResponse] = await Promise.all([
fetch(`/api/competitions/${competitionId}/apps`),
fetch(`/api/competitions/${competitionId}/teams`)
])
const appsData = await appsResponse.json()
const teamsData = await teamsResponse.json()
addLog(`應用API回應: ${JSON.stringify(appsData)}`)
addLog(`團隊API回應: ${JSON.stringify(teamsData)}`)
const participants = []
if (appsData.success && appsData.data && appsData.data.apps) {
participants.push(...appsData.data.apps.map((app: any) => ({
id: app.id,
name: app.name,
type: 'individual',
creator: app.creator
})))
addLog(`✅ 載入 ${appsData.data.apps.length} 個應用`)
} else {
addLog(`❌ 應用載入失敗: ${appsData.message}`)
}
if (teamsData.success && teamsData.data && teamsData.data.teams) {
participants.push(...teamsData.data.teams.map((team: any) => ({
id: team.id,
name: team.name,
type: 'team',
creator: team.members && team.members.find((m: any) => m.role === '隊長')?.name || '未知隊長'
})))
addLog(`✅ 載入 ${teamsData.data.teams.length} 個團隊`)
} else {
addLog(`❌ 團隊載入失敗: ${teamsData.message}`)
}
setCompetitionParticipants(participants)
addLog(`✅ 參賽者載入完成: ${participants.length}`)
} catch (error) {
addLog(`❌ 載入失敗: ${error.message}`)
} finally {
setLoading(false)
}
}
useEffect(() => {
loadCompetitions()
}, [])
return (
<div className="container mx-auto p-6 space-y-6">
<Card>
<CardHeader>
<CardTitle>調</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div>
<label className="block text-sm font-medium mb-2">:</label>
<select
value={selectedCompetition?.id || ""}
onChange={(e) => {
const competition = competitions.find(c => c.id === e.target.value)
setSelectedCompetition(competition)
if (competition) {
loadCompetitionData(competition.id)
}
}}
className="w-full p-2 border rounded"
>
<option value=""></option>
{competitions.map(comp => (
<option key={comp.id} value={comp.id}>
{comp.name} ({comp.type})
</option>
))}
</select>
</div>
{selectedCompetition && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<h3 className="font-semibold mb-2"> ({competitionJudges.length})</h3>
<div className="space-y-2">
{competitionJudges.map(judge => (
<div key={judge.id} className="p-2 bg-gray-100 rounded">
{judge.name} - {judge.title} - {judge.department}
</div>
))}
</div>
</div>
<div>
<h3 className="font-semibold mb-2"> ({competitionParticipants.length})</h3>
<div className="space-y-2">
{competitionParticipants.map(participant => (
<div key={participant.id} className="p-2 bg-gray-100 rounded">
{participant.name} ({participant.type}) - {participant.creator}
</div>
))}
</div>
</div>
</div>
)}
<div>
<h3 className="font-semibold mb-2">調</h3>
<div className="bg-gray-100 p-4 rounded max-h-96 overflow-y-auto">
{logs.map((log, index) => (
<div key={index} className="text-sm font-mono">{log}</div>
))}
</div>
</div>
</CardContent>
</Card>
</div>
)
}

View File

@@ -1,100 +0,0 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* 隱藏滾動條 */
.scrollbar-hide {
-ms-overflow-style: none; /* Internet Explorer 10+ */
scrollbar-width: none; /* Firefox */
}
.scrollbar-hide::-webkit-scrollbar {
display: none; /* Safari and Chrome */
}
@layer utilities {
.text-balance {
text-wrap: balance;
}
}
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 0 0% 3.9%;
--card: 0 0% 100%;
--card-foreground: 0 0% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 0 0% 3.9%;
--primary: 0 0% 9%;
--primary-foreground: 0 0% 98%;
--secondary: 0 0% 96.1%;
--secondary-foreground: 0 0% 9%;
--muted: 0 0% 96.1%;
--muted-foreground: 0 0% 45.1%;
--accent: 0 0% 96.1%;
--accent-foreground: 0 0% 9%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 89.8%;
--input: 0 0% 89.8%;
--ring: 0 0% 3.9%;
--chart-1: 12 76% 61%;
--chart-2: 173 58% 39%;
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;
--radius: 0.5rem;
--sidebar-background: 0 0% 98%;
--sidebar-foreground: 240 5.3% 26.1%;
--sidebar-primary: 240 5.9% 10%;
--sidebar-primary-foreground: 0 0% 98%;
--sidebar-accent: 240 4.8% 95.9%;
--sidebar-accent-foreground: 240 5.9% 10%;
--sidebar-border: 220 13% 91%;
--sidebar-ring: 217.2 91.2% 59.8%;
}
.dark {
--background: 0 0% 3.9%;
--foreground: 0 0% 98%;
--card: 0 0% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 0 0% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 0 0% 9%;
--secondary: 0 0% 14.9%;
--secondary-foreground: 0 0% 98%;
--muted: 0 0% 14.9%;
--muted-foreground: 0 0% 63.9%;
--accent: 0 0% 14.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 14.9%;
--input: 0 0% 14.9%;
--ring: 0 0% 83.1%;
--chart-1: 220 70% 50%;
--chart-2: 160 60% 45%;
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%;
--sidebar-background: 240 5.9% 10%;
--sidebar-foreground: 240 4.8% 95.9%;
--sidebar-primary: 224.3 76.3% 48%;
--sidebar-primary-foreground: 0 0% 100%;
--sidebar-accent: 240 3.7% 15.9%;
--sidebar-accent-foreground: 240 4.8% 95.9%;
--sidebar-border: 240 3.7% 15.9%;
--sidebar-ring: 217.2 91.2% 59.8%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

View File

@@ -1,11 +1,10 @@
import type React from "react"
import { Inter } from "next/font/google"
import "./globals.css"
import "../styles/globals.css"
import { AuthProvider } from "@/contexts/auth-context"
import { CompetitionProvider } from "@/contexts/competition-context"
import { Toaster } from "@/components/ui/toaster"
import { ChatBot } from "@/components/chat-bot"
import { ClientConnectionCleanup } from "@/components/client-connection-cleanup"
import "@/lib/app-initializer" // 自動初始化應用程式
const inter = Inter({ subsets: ["latin"] })
@@ -30,7 +29,6 @@ export default function RootLayout({
{children}
<Toaster />
<ChatBot />
<ClientConnectionCleanup />
</CompetitionProvider>
</AuthProvider>
</body>

View File

@@ -1,174 +0,0 @@
'use client';
import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, CheckCircle, AlertTriangle } from 'lucide-react';
export default function SetIPPage() {
const [clientIP, setClientIP] = useState('61-227-253-171');
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
// 設置客戶端 IP
const handleSetClientIP = async () => {
if (!clientIP.trim()) {
setError('請輸入客戶端 IP 地址');
return;
}
try {
setLoading(true);
const response = await fetch('/api/set-client-ip', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ clientIP: clientIP.trim() }),
});
const data = await response.json();
if (data.success) {
setMessage(data.message || '客戶端 IP 設置成功');
setError('');
} else {
setError(data.error || '設置客戶端 IP 失敗');
}
} catch (err) {
setError('設置錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 快速設置你的 IP
const handleSetYourIP = () => {
setClientIP('61-227-253-171');
};
// 測試清理功能
const handleTestCleanup = async () => {
try {
setLoading(true);
const response = await fetch('/api/ip-cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'cleanup-current' }),
});
const data = await response.json();
if (data.success) {
setMessage(`清理完成: ${data.message}`);
setError('');
} else {
setError(data.error || '清理失敗');
}
} catch (err) {
setError('清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
return (
<div className="container mx-auto p-6 space-y-6">
<div>
<h1 className="text-3xl font-bold"> IP</h1>
<p className="text-muted-foreground">
IP
</p>
</div>
{/* IP 設置 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" />
IP
</CardTitle>
<CardDescription>
IP 使 IP
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="clientIP"> IP </Label>
<div className="flex gap-2">
<Input
id="clientIP"
value={clientIP}
onChange={(e) => setClientIP(e.target.value)}
placeholder="例如: 61-227-253-171"
className="flex-1"
/>
<Button
onClick={handleSetYourIP}
disabled={loading}
variant="outline"
>
使 IP
</Button>
</div>
</div>
<div className="flex gap-2">
<Button
onClick={handleSetClientIP}
disabled={loading || !clientIP.trim()}
className="flex-1"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <CheckCircle className="h-4 w-4" />}
IP
</Button>
<Button
onClick={handleTestCleanup}
disabled={loading}
variant="destructive"
className="flex-1"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <AlertTriangle className="h-4 w-4" />}
</Button>
</div>
</CardContent>
</Card>
{/* 使用說明 */}
<Card>
<CardHeader>
<CardTitle>使</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong> IP:</strong> 61-227-253-171</p>
<p> <strong> IP:</strong> IP IP</p>
<p> <strong>:</strong> IP </p>
<p> <strong>:</strong> IP </p>
</CardContent>
</Card>
{/* 訊息顯示 */}
{message && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
</div>
);
}

View File

@@ -1,280 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, CheckCircle, AlertTriangle, RefreshCw, Trash2, BarChart3 } from 'lucide-react';
interface ConnectionStats {
total: number;
user: number;
infrastructure: number;
other: number;
details: Array<{
id: number;
host: string;
time: number;
state: string;
type: 'user' | 'infrastructure' | 'other';
}>;
}
interface CleanupResult {
success: boolean;
message: string;
data: {
killedCount: number;
details: {
userRealIP?: string;
infrastructureIPs?: string[];
cleanedConnections: Array<{
id: number;
host: string;
time: number;
state: string;
}>;
};
};
}
export default function SmartCleanupTestPage() {
const [stats, setStats] = useState<ConnectionStats | null>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
// 獲取連線統計
const fetchStats = async () => {
try {
setLoading(true);
const response = await fetch('/api/smart-cleanup');
const data = await response.json();
if (data.success) {
setStats(data.data.stats);
setMessage('連線統計更新成功');
setError('');
} else {
setError(data.error || '獲取連線統計失敗');
}
} catch (err) {
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 執行智能清理
const performSmartCleanup = async () => {
try {
setLoading(true);
const response = await fetch('/api/smart-cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const data: CleanupResult = await response.json();
if (data.success) {
setMessage(`智能清理完成: ${data.message}`);
setError('');
// 重新獲取統計
await fetchStats();
} else {
setError(data.error || '智能清理失敗');
}
} catch (err) {
setError('清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 組件載入時獲取統計
useEffect(() => {
fetchStats();
}, []);
// 獲取類型顏色
const getTypeColor = (type: 'user' | 'infrastructure' | 'other') => {
switch (type) {
case 'user': return 'default';
case 'infrastructure': return 'destructive';
case 'other': return 'secondary';
default: return 'outline';
}
};
// 獲取類型標籤
const getTypeLabel = (type: 'user' | 'infrastructure' | 'other') => {
switch (type) {
case 'user': return '用戶連線';
case 'infrastructure': return '基礎設施';
case 'other': return '其他';
default: return '未知';
}
};
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold"></h1>
<p className="text-muted-foreground">
IP
</p>
</div>
<div className="flex gap-2">
<Button
onClick={fetchStats}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
</Button>
<Button
onClick={performSmartCleanup}
disabled={loading}
variant="destructive"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
</Button>
</div>
</div>
{/* 連線統計概覽 */}
{stats && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<BarChart3 className="h-5 w-5" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="text-center">
<div className="text-2xl font-bold">{stats.total}</div>
<div className="text-sm text-muted-foreground"></div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-blue-600">{stats.user}</div>
<div className="text-sm text-muted-foreground"></div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-red-600">{stats.infrastructure}</div>
<div className="text-sm text-muted-foreground"></div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-gray-600">{stats.other}</div>
<div className="text-sm text-muted-foreground"></div>
</div>
</div>
</CardContent>
</Card>
)}
{/* 連線詳情 */}
{stats && stats.details.length > 0 && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2 max-h-96 overflow-y-auto">
{stats.details.map((conn, index) => (
<div key={index} className="flex items-center justify-between p-3 border rounded">
<div className="flex items-center gap-3">
<Badge variant={getTypeColor(conn.type)}>
{getTypeLabel(conn.type)}
</Badge>
<span className="font-mono text-sm">ID: {conn.id}</span>
<span className="text-sm text-muted-foreground">
{conn.host}
</span>
</div>
<div className="flex items-center gap-3">
<span className="text-sm">: {conn.time}s</span>
<span className="text-sm text-muted-foreground">
: {conn.state}
</span>
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* 功能說明 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<h4 className="font-semibold text-blue-600 mb-2"></h4>
<ul className="text-sm text-muted-foreground space-y-1">
<li> IP (61-227-253-171)</li>
<li> IP </li>
<li> </li>
<li> </li>
</ul>
</div>
<div>
<h4 className="font-semibold text-red-600 mb-2"></h4>
<ul className="text-sm text-muted-foreground space-y-1">
<li> AWS EC2 </li>
<li> Vercel </li>
<li> </li>
<li> </li>
</ul>
</div>
</div>
</CardContent>
</Card>
{/* 使用說明 */}
<Card>
<CardHeader>
<CardTitle>使</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong>:</strong> </p>
<p> <strong>:</strong> IP </p>
<p> <strong>:</strong> IP </p>
<p> <strong>:</strong> Vercel/AWS </p>
<p> <strong>:</strong> </p>
</CardContent>
</Card>
{/* 訊息顯示 */}
{message && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
</div>
);
}

View File

@@ -1,72 +0,0 @@
'use client'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
export default function TestAPIPage() {
const [competitionId, setCompetitionId] = useState('be47d842-91f1-11f0-8595-bd825523ae01')
const [results, setResults] = useState<any>({})
const testAPI = async (endpoint: string, name: string) => {
try {
const response = await fetch(`/api/competitions/${competitionId}/${endpoint}`)
const data = await response.json()
setResults(prev => ({ ...prev, [name]: data }))
console.log(`${name} API回應:`, data)
} catch (error) {
console.error(`${name} API錯誤:`, error)
setResults(prev => ({ ...prev, [name]: { error: error.message } }))
}
}
const testAllAPIs = async () => {
setResults({})
await Promise.all([
testAPI('judges', '評審'),
testAPI('apps', '應用'),
testAPI('teams', '團隊')
])
}
return (
<div className="container mx-auto p-6 space-y-6">
<Card>
<CardHeader>
<CardTitle>API </CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div>
<label className="block text-sm font-medium mb-2">ID:</label>
<input
type="text"
value={competitionId}
onChange={(e) => setCompetitionId(e.target.value)}
className="w-full p-2 border rounded"
/>
</div>
<div className="flex space-x-2">
<Button onClick={testAllAPIs}>API</Button>
<Button onClick={() => testAPI('judges', '評審')}>API</Button>
<Button onClick={() => testAPI('apps', '應用')}>API</Button>
<Button onClick={() => testAPI('teams', '團隊')}>API</Button>
</div>
</CardContent>
</Card>
{Object.entries(results).map(([name, data]) => (
<Card key={name}>
<CardHeader>
<CardTitle>{name} API </CardTitle>
</CardHeader>
<CardContent>
<pre className="bg-gray-100 p-4 rounded overflow-auto text-sm">
{JSON.stringify(data, null, 2)}
</pre>
</CardContent>
</Card>
))}
</div>
)
}

View File

@@ -1,226 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, Trash2, Eye, Zap } from 'lucide-react';
import { clientCleanup } from '@/lib/client-connection-cleanup';
export default function TestIPCleanupPage() {
const [status, setStatus] = useState<any>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
// 獲取連線狀態
const fetchStatus = async () => {
try {
setLoading(true);
const status = await clientCleanup.getConnectionStatus();
setStatus(status);
setMessage('連線狀態更新成功');
setError('');
} catch (err) {
setError('獲取狀態失敗: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 手動清理
const manualCleanup = async () => {
try {
setLoading(true);
const success = await clientCleanup.manualCleanup();
if (success) {
setMessage('手動清理完成');
setError('');
await fetchStatus(); // 重新獲取狀態
} else {
setError('手動清理失敗');
}
} catch (err) {
setError('手動清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 模擬關閉頁面
const simulatePageClose = () => {
if (confirm('確定要模擬關閉頁面嗎?這會觸發自動清理機制。')) {
// 觸發 beforeunload 事件
window.dispatchEvent(new Event('beforeunload'));
// 等待一下再觸發 unload 事件
setTimeout(() => {
window.dispatchEvent(new Event('unload'));
}, 100);
}
};
// 組件載入時獲取狀態
useEffect(() => {
fetchStatus();
}, []);
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold">IP </h1>
<p className="text-muted-foreground">
IP
</p>
</div>
<Button
onClick={fetchStatus}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
{/* 客戶端信息 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
<p><strong> ID:</strong> {clientCleanup.getClientId()}</p>
<p><strong>:</strong> {navigator.userAgent}</p>
<p><strong>:</strong> {new Date().toLocaleString()}</p>
</div>
</CardContent>
</Card>
{/* 連線狀態 */}
{status && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Eye className="h-5 w-5" />
</CardTitle>
<CardDescription>
IP: {status.ip} | : {status.connectionCount}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-4">
<Badge variant="outline" className="text-lg px-3 py-1">
: {status.connectionCount}
</Badge>
<Badge
variant={status.connectionCount > 5 ? "destructive" : "default"}
className="text-lg px-3 py-1"
>
: {status.connectionCount > 5 ? "異常" : "正常"}
</Badge>
</div>
{status.connections && status.connections.length > 0 && (
<div className="space-y-2">
<h4 className="font-medium">:</h4>
{status.connections.slice(0, 5).map((conn: any, index: number) => (
<div key={index} className="p-2 border rounded text-sm">
<p>ID: {conn.ID} | HOST: {conn.HOST} | : {conn.TIME}s</p>
</div>
))}
{status.connections.length > 5 && (
<p className="text-sm text-muted-foreground">
... {status.connections.length - 5}
</p>
)}
</div>
)}
</CardContent>
</Card>
)}
{/* 測試操作 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Zap className="h-5 w-5" />
</CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Button
onClick={manualCleanup}
disabled={loading}
variant="outline"
className="w-full"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
</Button>
<Button
onClick={simulatePageClose}
disabled={loading}
variant="destructive"
className="w-full"
>
<Zap className="h-4 w-4" />
</Button>
<Button
onClick={() => window.location.reload()}
disabled={loading}
variant="secondary"
className="w-full"
>
<Database className="h-4 w-4" />
</Button>
</div>
</CardContent>
</Card>
{/* 自動清理說明 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong>:</strong> IP </p>
<p> <strong>:</strong> </p>
<p> <strong>:</strong> 5</p>
<p> <strong>:</strong> </p>
<p> <strong>:</strong> IP </p>
</CardContent>
</Card>
{/* 訊息顯示 */}
{message && (
<Alert>
<Database className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<Trash2 className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
</div>
);
}

View File

@@ -1,101 +0,0 @@
'use client'
import { useState, useEffect } from 'react'
import { CompetitionProvider } from '@/contexts/competition-context'
export default function TestManualScoringPage() {
const [competition, setCompetition] = useState<any>(null)
const [teams, setTeams] = useState<any[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
loadCompetitionData()
}, [])
const loadCompetitionData = async () => {
try {
// 載入競賽信息
const competitionResponse = await fetch('/api/competitions/be4b0a71-91f1-11f0-bb38-4adff2d0e33e')
const competitionData = await competitionResponse.json()
if (competitionData.success) {
setCompetition(competitionData.data.competition)
}
// 載入團隊數據
const teamsResponse = await fetch('/api/competitions/be4b0a71-91f1-11f0-bb38-4adff2d0e33e/teams')
const teamsData = await teamsResponse.json()
if (teamsData.success) {
setTeams(teamsData.data.teams)
}
} catch (error) {
console.error('❌ 載入數據失敗:', error)
} finally {
setLoading(false)
}
}
if (loading) {
return <div className="p-8">...</div>
}
return (
<CompetitionProvider>
<div className="p-8">
<h1 className="text-2xl font-bold mb-4"></h1>
<div className="mb-6">
<h2 className="text-lg font-semibold mb-2"></h2>
{competition ? (
<div className="bg-gray-100 p-4 rounded">
<p><strong>:</strong> {competition.name}</p>
<p><strong>:</strong> {competition.type}</p>
<p><strong>:</strong> {competition.status}</p>
</div>
) : (
<p className="text-red-500"></p>
)}
</div>
<div className="mb-6">
<h2 className="text-lg font-semibold mb-2"></h2>
{teams.length > 0 ? (
<div className="space-y-4">
{teams.map((team) => (
<div key={team.id} className="bg-gray-100 p-4 rounded">
<h3 className="font-semibold">{team.name}</h3>
<p><strong>ID:</strong> {team.id}</p>
<p><strong>APP數量:</strong> {team.apps?.length || 0}</p>
{team.apps && team.apps.length > 0 && (
<div className="mt-2">
<h4 className="font-medium">APP列表:</h4>
<ul className="ml-4">
{team.apps.map((app: any) => (
<li key={app.id} className="text-sm">
{app.name} ({app.id})
</li>
))}
</ul>
</div>
)}
</div>
))}
</div>
) : (
<p className="text-red-500"></p>
)}
</div>
<div className="mb-6">
<h2 className="text-lg font-semibold mb-2"></h2>
<p className="text-gray-600">
</p>
</div>
</div>
</CompetitionProvider>
)
}

View File

@@ -1,313 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Database, Eye, RefreshCw, AlertTriangle, CheckCircle } from 'lucide-react';
interface VercelIPInfo {
smartDetection: {
detectedIP: string;
confidence: 'high' | 'medium' | 'low';
source: string;
isPublicIP: boolean;
allCandidates: string[];
isInfrastructureIP?: boolean;
isUserRealIP?: boolean;
infrastructureIPs?: string[];
userRealIPs?: string[];
};
headers: Record<string, string | null>;
nextRequestIP: string | undefined;
env: Record<string, string | undefined>;
allHeaders: Record<string, string>;
}
export default function VercelIPDebugPage() {
const [ipInfo, setIpInfo] = useState<VercelIPInfo | null>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>('');
const [error, setError] = useState<string>('');
// 獲取 IP 調試信息
const fetchIPInfo = async () => {
try {
setLoading(true);
const response = await fetch('/api/debug-ip');
const data = await response.json();
if (data.success) {
setIpInfo(data.data);
if (data.data.smartDetection) {
const smartDetection = data.data.smartDetection;
setMessage(`Vercel IP 偵測結果: ${smartDetection.detectedIP} (可信度: ${smartDetection.confidence}, 來源: ${smartDetection.source})`);
} else {
setMessage('IP 調試信息更新成功');
}
setError('');
} else {
setError(data.error || '獲取 IP 調試信息失敗');
}
} catch (err) {
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
} finally {
setLoading(false);
}
};
// 組件載入時獲取 IP 信息
useEffect(() => {
fetchIPInfo();
}, []);
// 檢查是否為基礎設施 IP
const isInfrastructureIP = (ip: string): boolean => {
if (!ip) return false;
return ip.includes('ec2-') && ip.includes('.amazonaws.com');
};
// 檢查是否為用戶真實 IP
const isUserRealIP = (ip: string): boolean => {
if (!ip || ip === 'unknown') return false;
return !isInfrastructureIP(ip) && ip !== '::1' && ip !== '127.0.0.1';
};
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold">Vercel IP 調</h1>
<p className="text-muted-foreground">
調 Vercel IP
</p>
</div>
<Button
onClick={fetchIPInfo}
disabled={loading}
variant="outline"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
</Button>
</div>
{/* 智能偵測結果 */}
{ipInfo?.smartDetection && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Eye className="h-5 w-5" />
IP
</CardTitle>
<CardDescription>
IP IP
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-4">
<Badge
variant={
isUserRealIP(ipInfo.smartDetection.detectedIP) ? "default" :
isInfrastructureIP(ipInfo.smartDetection.detectedIP) ? "destructive" : "secondary"
}
className="text-lg px-3 py-1"
>
{ipInfo.smartDetection.detectedIP}
</Badge>
<Badge
variant={
ipInfo.smartDetection.confidence === 'high' ? "default" :
ipInfo.smartDetection.confidence === 'medium' ? "secondary" : "destructive"
}
className="text-lg px-3 py-1"
>
: {ipInfo.smartDetection.confidence}
</Badge>
<Badge variant="outline" className="text-lg px-3 py-1">
: {ipInfo.smartDetection.source}
</Badge>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<p className="text-sm font-medium mb-2"> IP:</p>
<div className="flex flex-wrap gap-2">
{ipInfo.smartDetection.userRealIPs?.map((ip, index) => (
<Badge
key={index}
variant="default"
className="text-sm"
>
{ip}
</Badge>
)) || <span className="text-muted-foreground text-sm"></span>}
</div>
</div>
<div>
<p className="text-sm font-medium mb-2"> IP ():</p>
<div className="flex flex-wrap gap-2">
{ipInfo.smartDetection.infrastructureIPs?.map((ip, index) => (
<Badge
key={index}
variant="destructive"
className="text-sm"
>
{ip}
</Badge>
)) || <span className="text-muted-foreground text-sm"></span>}
</div>
</div>
</div>
</CardContent>
</Card>
)}
{/* 請求標頭分析 */}
{ipInfo && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
HTTP IP
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{Object.entries(ipInfo.headers).map(([key, value]) => {
if (!value) return null;
const isInfra = isInfrastructureIP(value);
const isUser = isUserRealIP(value);
return (
<div key={key} className="flex items-center justify-between p-3 border rounded">
<div className="flex-1">
<span className="font-medium text-sm">{key}:</span>
<div className="mt-1">
<Badge
variant={
isUser ? "default" :
isInfra ? "destructive" : "outline"
}
className="text-sm"
>
{value}
</Badge>
<div className="flex gap-2 mt-1">
{isUser && <Badge variant="default" className="text-xs"> IP</Badge>}
{isInfra && <Badge variant="destructive" className="text-xs"> IP</Badge>}
</div>
</div>
</div>
</div>
);
})}
</div>
</CardContent>
</Card>
)}
{/* 環境信息 */}
{ipInfo && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription>
Vercel
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
{Object.entries(ipInfo.env).map(([key, value]) => (
<div key={key} className="flex items-center justify-between p-2 border rounded">
<span className="font-medium text-sm">{key}:</span>
<span className="text-sm text-muted-foreground">
{value || 'undefined'}
</span>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* 問題診斷 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5" />
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{ipInfo?.smartDetection && (
<>
{isInfrastructureIP(ipInfo.smartDetection.detectedIP) && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
<strong>:</strong> Vercel/AWS IP IP
<br />
<strong>:</strong> x-forwarded-for IP
</AlertDescription>
</Alert>
)}
{isUserRealIP(ipInfo.smartDetection.detectedIP) && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>
<strong>:</strong> IP
</AlertDescription>
</Alert>
)}
{!isUserRealIP(ipInfo.smartDetection.detectedIP) && !isInfrastructureIP(ipInfo.smartDetection.detectedIP) && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
<strong>:</strong> IP
<br />
<strong>:</strong>
</AlertDescription>
</Alert>
)}
</>
)}
</CardContent>
</Card>
{/* 使用說明 */}
<Card>
<CardHeader>
<CardTitle>使</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p> <strong> IP:</strong> Vercel/AWS IP IP</p>
<p> <strong> IP:</strong> IP </p>
<p> <strong>x-forwarded-for:</strong> IP "用戶IP,代理IP"</p>
<p> <strong>:</strong> IP</p>
</CardContent>
</Card>
{/* 訊息顯示 */}
{message && (
<Alert>
<Database className="h-4 w-4" />
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<Eye className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
</div>
);
}