| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474 |
- 'use client';
- import { useState, useEffect } from 'react';
- import { X, Plus, FileText, Sparkles, Check, AlertCircle } from 'lucide-react';
- import { toast } from 'react-hot-toast';
- import { proxyService } from '@/lib/services';
- import { ProxyStatus } from '@/types';
- interface ProxyAddModalProps {
- isOpen: boolean;
- onClose: () => void;
- onSuccess: () => void;
- existingPools?: string[];
- }
- const EMPTY_POOLS: string[] = [];
- interface ParsedProxy {
- pool_name: string;
- proto: string;
- ip: string;
- port: number;
- username?: string | null;
- password?: string | null;
- status: ProxyStatus;
- }
- export default function ProxyAddModal({
- isOpen,
- onClose,
- onSuccess,
- existingPools = EMPTY_POOLS,
- }: ProxyAddModalProps) {
- const [mode, setMode] = useState<'single' | 'batch'>('single');
- // 单条表单状态
- const [singleForm, setSingleForm] = useState({
- pool_name: '',
- proto: 'http',
- ip: '',
- port: 8080,
- username: '',
- password: '',
- status: 'active' as ProxyStatus,
- });
- // 批量导入状态
- const [batchPool, setBatchPool] = useState('');
- const [batchDefaultProto, setBatchDefaultProto] = useState('http');
- const [batchDefaultStatus, setBatchDefaultStatus] = useState<ProxyStatus>('active');
- const [batchText, setBatchText] = useState('');
- const [submitting, setSubmitting] = useState(false);
- useEffect(() => {
- if (isOpen) {
- const defaultPool = existingPools.length > 0 ? existingPools[0] : '';
- setSingleForm({
- pool_name: defaultPool,
- proto: 'http',
- ip: '',
- port: 8080,
- username: '',
- password: '',
- status: 'active',
- });
- setBatchPool(defaultPool);
- setBatchDefaultProto('http');
- setBatchDefaultStatus('active');
- setBatchText('');
- setMode('single');
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isOpen]);
- if (!isOpen) return null;
- const parseBatchText = (): ParsedProxy[] => {
- if (!batchText.trim()) return [];
- const lines = batchText.split('\n');
- const result: ParsedProxy[] = [];
- const poolName = batchPool.trim() || 'default';
- for (const rawLine of lines) {
- const line = rawLine.trim();
- if (!line || line.startsWith('#') || line.startsWith('//')) continue;
- try {
- if (line.includes('://')) {
- const url = new URL(line);
- const proto = url.protocol.replace(':', '');
- const ip = url.hostname;
- const port = Number(url.port) || (proto === 'https' ? 443 : 80);
- const username = url.username ? decodeURIComponent(url.username) : null;
- const password = url.password ? decodeURIComponent(url.password) : null;
- if (ip && port > 0) {
- result.push({
- pool_name: poolName,
- proto,
- ip,
- port,
- username,
- password,
- status: batchDefaultStatus,
- });
- continue;
- }
- }
- const parts = line.split(':');
- if (parts.length >= 2) {
- const ip = parts[0].trim();
- const port = Number(parts[1].trim());
- const username = parts.length >= 3 ? parts[2].trim() : null;
- const password = parts.length >= 4 ? parts[3].trim() : null;
- if (ip && port > 0 && !isNaN(port)) {
- result.push({
- pool_name: poolName,
- proto: batchDefaultProto,
- ip,
- port,
- username: username || null,
- password: password || null,
- status: batchDefaultStatus,
- });
- }
- }
- } catch {
- // ignore parse line error
- }
- }
- return result;
- };
- const parsedBatchList = parseBatchText();
- const handleSingleSubmit = async () => {
- if (!singleForm.pool_name.trim()) {
- toast.error('请填写代理池名称');
- return;
- }
- if (!singleForm.ip.trim()) {
- toast.error('请填写代理 IP 地址');
- return;
- }
- if (!singleForm.port || singleForm.port <= 0 || singleForm.port > 65535) {
- toast.error('端口号必须在 1-65535 之间');
- return;
- }
- setSubmitting(true);
- try {
- const res = await proxyService.create({
- pool_name: singleForm.pool_name.trim(),
- proto: singleForm.proto,
- ip: singleForm.ip.trim(),
- port: Number(singleForm.port),
- username: singleForm.username.trim() || undefined,
- password: singleForm.password.trim() || undefined,
- status: singleForm.status,
- });
- if (res?.code === 0 || res?.data) {
- toast.success(`代理 ${singleForm.ip}:${singleForm.port} 添加成功`);
- onSuccess();
- onClose();
- } else {
- toast.error(res?.msg || '添加失败');
- }
- } catch (e: any) {
- toast.error('添加失败: ' + (e.response?.data?.msg || e.message || '网络错误'));
- } finally {
- setSubmitting(false);
- }
- };
- const handleBatchSubmit = async () => {
- if (parsedBatchList.length === 0) {
- toast.error('未能从文本中解析出有效的代理记录');
- return;
- }
- setSubmitting(true);
- let successCount = 0;
- let failCount = 0;
- try {
- for (const item of parsedBatchList) {
- try {
- const res = await proxyService.create({
- pool_name: item.pool_name,
- proto: item.proto,
- ip: item.ip,
- port: item.port,
- username: item.username || undefined,
- password: item.password || undefined,
- status: item.status,
- });
- if (res?.code === 0 || res?.data) {
- successCount++;
- } else {
- failCount++;
- }
- } catch {
- failCount++;
- }
- }
- toast.success(`批量导入完成: 成功 ${successCount} 个, 失败 ${failCount} 个`);
- onSuccess();
- onClose();
- } catch {
- toast.error('导入过程中发生异常');
- } finally {
- setSubmitting(false);
- }
- };
- return (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-grayscale p-4 font-mono">
- <div className="bg-neutral-50 border-2 border-black shadow-[8px_8px_0px_#000] w-full max-w-lg overflow-hidden flex flex-col animate-in zoom-in-95 duration-200">
-
- {/* Header */}
- <div className="px-5 py-3.5 border-b-2 border-black flex justify-between items-center bg-neutral-200 text-black select-none shrink-0">
- <div className="flex items-center gap-2">
- <span className="w-2.5 h-2.5 bg-amber-300 border border-black inline-block" />
- <h3 className="font-black text-black text-xs md:text-sm uppercase tracking-wider">
- [ ADD PROXY NODE // 登记代理出口节点 ]
- </h3>
- </div>
- <button
- onClick={onClose}
- className="w-6 h-6 bg-white hover:bg-amber-300 border border-black flex items-center justify-center font-bold text-xs transition"
- >
- ✕
- </button>
- </div>
- {/* Mode Tabs */}
- <div className="flex border-b-2 border-black bg-neutral-100 px-4 text-xs font-bold uppercase shrink-0">
- <button
- type="button"
- onClick={() => setMode('single')}
- className={`py-2.5 px-3 border-b-2 transition ${
- mode === 'single'
- ? 'border-black bg-amber-300 text-black font-black'
- : 'border-transparent text-neutral-600 hover:text-black'
- }`}
- >
- 单条精准录入
- </button>
- <button
- type="button"
- onClick={() => setMode('batch')}
- className={`py-2.5 px-3 border-b-2 transition ${
- mode === 'batch'
- ? 'border-black bg-amber-300 text-black font-black'
- : 'border-transparent text-neutral-600 hover:text-black'
- }`}
- >
- 多行文本批量导入
- </button>
- </div>
- {/* Body */}
- <div className="p-5 space-y-3.5 max-h-[70vh] overflow-y-auto bg-white text-xs">
- {mode === 'single' ? (
- <>
- {/* Pool & Status */}
- <div className="grid grid-cols-2 gap-3">
- <div className="space-y-1">
- <label className="font-bold uppercase text-black block">
- 所属代理池 <span className="text-black">*</span>
- </label>
- <input
- type="text"
- list="proxy-pools-list"
- placeholder="default / residential"
- className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000]"
- value={singleForm.pool_name}
- onChange={(e) => setSingleForm({ ...singleForm, pool_name: e.target.value })}
- />
- <datalist id="proxy-pools-list">
- {existingPools.map((p) => (
- <option key={p} value={p} />
- ))}
- </datalist>
- </div>
- <div className="space-y-1">
- <label className="font-bold uppercase text-black block">初始状态</label>
- <select
- className="w-full px-3 py-2 border-2 border-black bg-neutral-50 text-xs font-bold text-black outline-none shadow-[2px_2px_0px_#000]"
- value={singleForm.status}
- onChange={(e) => setSingleForm({ ...singleForm, status: e.target.value as ProxyStatus })}
- >
- <option value="active">🟢 Active (可用)</option>
- <option value="disable">🔴 Disable (禁用)</option>
- </select>
- </div>
- </div>
- {/* Protocol, IP & Port */}
- <div className="grid grid-cols-12 gap-2">
- <div className="col-span-3 space-y-1">
- <label className="font-bold uppercase text-black block">协议</label>
- <select
- className="w-full px-2 py-2 border-2 border-black bg-neutral-50 text-xs font-bold text-black outline-none shadow-[2px_2px_0px_#000]"
- value={singleForm.proto}
- onChange={(e) => setSingleForm({ ...singleForm, proto: e.target.value })}
- >
- <option value="http">HTTP</option>
- <option value="https">HTTPS</option>
- <option value="socks5">SOCKS5</option>
- </select>
- </div>
- <div className="col-span-6 space-y-1">
- <label className="font-bold uppercase text-black block">
- IP 地址 / 域名 <span className="text-black">*</span>
- </label>
- <input
- type="text"
- placeholder="127.0.0.1"
- className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000]"
- value={singleForm.ip}
- onChange={(e) => setSingleForm({ ...singleForm, ip: e.target.value })}
- />
- </div>
- <div className="col-span-3 space-y-1">
- <label className="font-bold uppercase text-black block">
- 端口 <span className="text-black">*</span>
- </label>
- <input
- type="number"
- placeholder="8080"
- className="w-full px-2 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono font-bold text-black outline-none shadow-[2px_2px_0px_#000]"
- value={singleForm.port}
- onChange={(e) => setSingleForm({ ...singleForm, port: Number(e.target.value) })}
- />
- </div>
- </div>
- {/* Username & Password */}
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
- <div className="space-y-1">
- <label className="font-bold uppercase text-black block">
- 鉴权用户名 (可选)
- </label>
- <input
- type="text"
- placeholder="username"
- className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000]"
- value={singleForm.username}
- onChange={(e) => setSingleForm({ ...singleForm, username: e.target.value })}
- />
- </div>
- <div className="space-y-1">
- <label className="font-bold uppercase text-black block">
- 鉴权密码 (可选)
- </label>
- <input
- type="text"
- placeholder="password"
- className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000]"
- value={singleForm.password}
- onChange={(e) => setSingleForm({ ...singleForm, password: e.target.value })}
- />
- </div>
- </div>
- </>
- ) : (
- /* 批量文本导入模式 */
- <div className="space-y-3">
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 bg-neutral-50 p-3 border-2 border-black shadow-[2px_2px_0px_#000]">
- <div className="space-y-1">
- <label className="font-bold uppercase text-black block text-[10px]">统一代理池</label>
- <input
- type="text"
- list="proxy-pools-batch"
- placeholder="default"
- className="w-full px-2 py-1.5 border border-black text-xs font-mono bg-white outline-none"
- value={batchPool}
- onChange={(e) => setBatchPool(e.target.value)}
- />
- <datalist id="proxy-pools-batch">
- {existingPools.map((p) => (
- <option key={p} value={p} />
- ))}
- </datalist>
- </div>
- <div className="space-y-1">
- <label className="font-bold uppercase text-black block text-[10px]">默认协议</label>
- <select
- className="w-full px-2 py-1.5 border border-black text-xs bg-white outline-none"
- value={batchDefaultProto}
- onChange={(e) => setBatchDefaultProto(e.target.value)}
- >
- <option value="http">HTTP</option>
- <option value="https">HTTPS</option>
- <option value="socks5">SOCKS5</option>
- </select>
- </div>
- <div className="space-y-1">
- <label className="font-bold uppercase text-black block text-[10px]">初始状态</label>
- <select
- className="w-full px-2 py-1.5 border border-black text-xs bg-white outline-none"
- value={batchDefaultStatus}
- onChange={(e) => setBatchDefaultStatus(e.target.value as ProxyStatus)}
- >
- <option value="active">Active</option>
- <option value="disable">Disable</option>
- </select>
- </div>
- </div>
- <div className="space-y-1">
- <div className="flex items-center justify-between">
- <label className="font-bold uppercase text-black block">[ 多行粘贴代理文本 ]</label>
- <span className="text-black font-mono font-bold text-[10px]">
- 已识别: {parsedBatchList.length} 条
- </span>
- </div>
- <textarea
- className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white outline-none font-mono text-xs text-black shadow-[2px_2px_0px_#000]"
- rows={7}
- value={batchText}
- onChange={(e) => setBatchText(e.target.value)}
- placeholder={`每行一条,支持:\n127.0.0.1:8080\n127.0.0.1:8080:user:pass\nhttp://user:pass@127.0.0.1:8080\nsocks5://127.0.0.1:1080`}
- />
- </div>
- </div>
- )}
- </div>
- {/* Footer */}
- <div className="px-5 py-3 bg-neutral-200 flex justify-end gap-2 border-t-2 border-black shrink-0">
- <button
- type="button"
- onClick={onClose}
- className="px-4 py-1.5 bg-white hover:bg-neutral-100 border-2 border-black text-xs font-bold uppercase shadow-[2px_2px_0px_#000]"
- disabled={submitting}
- >
- [ 取消 ]
- </button>
- <button
- type="button"
- onClick={mode === 'single' ? handleSingleSubmit : handleBatchSubmit}
- disabled={submitting || (mode === 'batch' && parsedBatchList.length === 0)}
- className="px-5 py-1.5 bg-amber-300 hover:bg-amber-400 text-black border-2 border-black text-xs font-black uppercase shadow-[2px_2px_0px_#000] transition active:translate-x-0.5 active:translate-y-0.5 disabled:opacity-50 flex items-center gap-1.5"
- >
- <Plus size={13} />
- <span>
- {submitting
- ? '提交中...'
- : mode === 'single'
- ? '[ 确认添加 ]'
- : `[ 确认批量导入 (${parsedBatchList.length}条) ]`}
- </span>
- </button>
- </div>
- </div>
- </div>
- );
- }
|