ProxyAddModal.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. 'use client';
  2. import { useState, useEffect } from 'react';
  3. import { X, Plus, FileText, Sparkles, Check, AlertCircle } from 'lucide-react';
  4. import { toast } from 'react-hot-toast';
  5. import api from '@/lib/api';
  6. import { ProxyStatus } from '@/types';
  7. interface ProxyAddModalProps {
  8. isOpen: boolean;
  9. onClose: () => void;
  10. onSuccess: () => void;
  11. existingPools?: string[];
  12. }
  13. interface ParsedProxy {
  14. pool_name: string;
  15. proto: string;
  16. ip: string;
  17. port: number;
  18. username?: string | null;
  19. password?: string | null;
  20. status: ProxyStatus;
  21. }
  22. export default function ProxyAddModal({
  23. isOpen,
  24. onClose,
  25. onSuccess,
  26. existingPools = [],
  27. }: ProxyAddModalProps) {
  28. const [mode, setMode] = useState<'single' | 'batch'>('single');
  29. // 单条表单状态
  30. const [singleForm, setSingleForm] = useState({
  31. pool_name: '',
  32. proto: 'http',
  33. ip: '',
  34. port: 8080,
  35. username: '',
  36. password: '',
  37. status: 'active' as ProxyStatus,
  38. });
  39. // 批量导入状态
  40. const [batchPool, setBatchPool] = useState('');
  41. const [batchDefaultProto, setBatchDefaultProto] = useState('http');
  42. const [batchDefaultStatus, setBatchDefaultStatus] = useState<ProxyStatus>('active');
  43. const [batchText, setBatchText] = useState('');
  44. const [submitting, setSubmitting] = useState(false);
  45. useEffect(() => {
  46. if (isOpen) {
  47. const defaultPool = existingPools.length > 0 ? existingPools[0] : '';
  48. setSingleForm({
  49. pool_name: defaultPool,
  50. proto: 'http',
  51. ip: '',
  52. port: 8080,
  53. username: '',
  54. password: '',
  55. status: 'active',
  56. });
  57. setBatchPool(defaultPool);
  58. setBatchDefaultProto('http');
  59. setBatchDefaultStatus('active');
  60. setBatchText('');
  61. setMode('single');
  62. }
  63. }, [isOpen, existingPools]);
  64. if (!isOpen) return null;
  65. const parseBatchText = (): ParsedProxy[] => {
  66. if (!batchText.trim()) return [];
  67. const lines = batchText.split('\n');
  68. const result: ParsedProxy[] = [];
  69. const poolName = batchPool.trim() || 'default';
  70. for (const rawLine of lines) {
  71. const line = rawLine.trim();
  72. if (!line || line.startsWith('#') || line.startsWith('//')) continue;
  73. try {
  74. if (line.includes('://')) {
  75. const url = new URL(line);
  76. const proto = url.protocol.replace(':', '');
  77. const ip = url.hostname;
  78. const port = Number(url.port) || (proto === 'https' ? 443 : 80);
  79. const username = url.username ? decodeURIComponent(url.username) : null;
  80. const password = url.password ? decodeURIComponent(url.password) : null;
  81. if (ip && port > 0) {
  82. result.push({
  83. pool_name: poolName,
  84. proto,
  85. ip,
  86. port,
  87. username,
  88. password,
  89. status: batchDefaultStatus,
  90. });
  91. continue;
  92. }
  93. }
  94. const parts = line.split(':');
  95. if (parts.length >= 2) {
  96. const ip = parts[0].trim();
  97. const port = Number(parts[1].trim());
  98. const username = parts.length >= 3 ? parts[2].trim() : null;
  99. const password = parts.length >= 4 ? parts[3].trim() : null;
  100. if (ip && port > 0 && !isNaN(port)) {
  101. result.push({
  102. pool_name: poolName,
  103. proto: batchDefaultProto,
  104. ip,
  105. port,
  106. username: username || null,
  107. password: password || null,
  108. status: batchDefaultStatus,
  109. });
  110. }
  111. }
  112. } catch {
  113. // ignore parse line error
  114. }
  115. }
  116. return result;
  117. };
  118. const parsedBatchList = parseBatchText();
  119. const handleSingleSubmit = async () => {
  120. if (!singleForm.pool_name.trim()) {
  121. toast.error('请填写代理池名称');
  122. return;
  123. }
  124. if (!singleForm.ip.trim()) {
  125. toast.error('请填写代理 IP 地址');
  126. return;
  127. }
  128. if (!singleForm.port || singleForm.port <= 0 || singleForm.port > 65535) {
  129. toast.error('端口号必须在 1-65535 之间');
  130. return;
  131. }
  132. setSubmitting(true);
  133. try {
  134. const res = await api.post('/api/proxies/create', {
  135. pool_name: singleForm.pool_name.trim(),
  136. proto: singleForm.proto,
  137. ip: singleForm.ip.trim(),
  138. port: Number(singleForm.port),
  139. username: singleForm.username.trim() || undefined,
  140. password: singleForm.password.trim() || undefined,
  141. status: singleForm.status,
  142. });
  143. if (res.data?.code === 0 || res.status === 200) {
  144. toast.success(`代理 ${singleForm.ip}:${singleForm.port} 添加成功`);
  145. onSuccess();
  146. onClose();
  147. } else {
  148. toast.error(res.data?.msg || '添加失败');
  149. }
  150. } catch (e: any) {
  151. toast.error('添加失败: ' + (e.response?.data?.msg || e.message || '网络错误'));
  152. } finally {
  153. setSubmitting(false);
  154. }
  155. };
  156. const handleBatchSubmit = async () => {
  157. if (parsedBatchList.length === 0) {
  158. toast.error('未能从文本中解析出有效的代理记录');
  159. return;
  160. }
  161. setSubmitting(true);
  162. let successCount = 0;
  163. let failCount = 0;
  164. try {
  165. for (const item of parsedBatchList) {
  166. try {
  167. const res = await api.post('/api/proxies/create', {
  168. pool_name: item.pool_name,
  169. proto: item.proto,
  170. ip: item.ip,
  171. port: item.port,
  172. username: item.username || undefined,
  173. password: item.password || undefined,
  174. status: item.status,
  175. });
  176. if (res.data?.code === 0 || res.status === 200) {
  177. successCount++;
  178. } else {
  179. failCount++;
  180. }
  181. } catch {
  182. failCount++;
  183. }
  184. }
  185. toast.success(`批量导入完成: 成功 ${successCount} 个, 失败 ${failCount} 个`);
  186. onSuccess();
  187. onClose();
  188. } catch {
  189. toast.error('导入过程中发生异常');
  190. } finally {
  191. setSubmitting(false);
  192. }
  193. };
  194. return (
  195. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-grayscale p-4 font-mono">
  196. <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">
  197. {/* Header */}
  198. <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">
  199. <div className="flex items-center gap-2">
  200. <span className="w-2.5 h-2.5 bg-amber-300 border border-black inline-block" />
  201. <h3 className="font-black text-black text-xs md:text-sm uppercase tracking-wider">
  202. [ ADD PROXY NODE // 登记代理出口节点 ]
  203. </h3>
  204. </div>
  205. <button
  206. onClick={onClose}
  207. className="w-6 h-6 bg-white hover:bg-amber-300 border border-black flex items-center justify-center font-bold text-xs transition"
  208. >
  209. ✕
  210. </button>
  211. </div>
  212. {/* Mode Tabs */}
  213. <div className="flex border-b-2 border-black bg-neutral-100 px-4 text-xs font-bold uppercase shrink-0">
  214. <button
  215. type="button"
  216. onClick={() => setMode('single')}
  217. className={`py-2.5 px-3 border-b-2 transition ${
  218. mode === 'single'
  219. ? 'border-black bg-amber-300 text-black font-black'
  220. : 'border-transparent text-neutral-600 hover:text-black'
  221. }`}
  222. >
  223. 单条精准录入
  224. </button>
  225. <button
  226. type="button"
  227. onClick={() => setMode('batch')}
  228. className={`py-2.5 px-3 border-b-2 transition ${
  229. mode === 'batch'
  230. ? 'border-black bg-amber-300 text-black font-black'
  231. : 'border-transparent text-neutral-600 hover:text-black'
  232. }`}
  233. >
  234. 多行文本批量导入
  235. </button>
  236. </div>
  237. {/* Body */}
  238. <div className="p-5 space-y-3.5 max-h-[70vh] overflow-y-auto bg-white text-xs">
  239. {mode === 'single' ? (
  240. <>
  241. {/* Pool & Status */}
  242. <div className="grid grid-cols-2 gap-3">
  243. <div className="space-y-1">
  244. <label className="font-bold uppercase text-black block">
  245. 所属代理池 <span className="text-black">*</span>
  246. </label>
  247. <input
  248. type="text"
  249. list="proxy-pools-list"
  250. placeholder="default / residential"
  251. 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]"
  252. value={singleForm.pool_name}
  253. onChange={(e) => setSingleForm({ ...singleForm, pool_name: e.target.value })}
  254. />
  255. <datalist id="proxy-pools-list">
  256. {existingPools.map((p) => (
  257. <option key={p} value={p} />
  258. ))}
  259. </datalist>
  260. </div>
  261. <div className="space-y-1">
  262. <label className="font-bold uppercase text-black block">初始状态</label>
  263. <select
  264. 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]"
  265. value={singleForm.status}
  266. onChange={(e) => setSingleForm({ ...singleForm, status: e.target.value as ProxyStatus })}
  267. >
  268. <option value="active">🟢 Active (可用)</option>
  269. <option value="disable">🔴 Disable (禁用)</option>
  270. </select>
  271. </div>
  272. </div>
  273. {/* Protocol, IP & Port */}
  274. <div className="grid grid-cols-12 gap-2">
  275. <div className="col-span-3 space-y-1">
  276. <label className="font-bold uppercase text-black block">协议</label>
  277. <select
  278. 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]"
  279. value={singleForm.proto}
  280. onChange={(e) => setSingleForm({ ...singleForm, proto: e.target.value })}
  281. >
  282. <option value="http">HTTP</option>
  283. <option value="https">HTTPS</option>
  284. <option value="socks5">SOCKS5</option>
  285. </select>
  286. </div>
  287. <div className="col-span-6 space-y-1">
  288. <label className="font-bold uppercase text-black block">
  289. IP 地址 / 域名 <span className="text-black">*</span>
  290. </label>
  291. <input
  292. type="text"
  293. placeholder="127.0.0.1"
  294. 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]"
  295. value={singleForm.ip}
  296. onChange={(e) => setSingleForm({ ...singleForm, ip: e.target.value })}
  297. />
  298. </div>
  299. <div className="col-span-3 space-y-1">
  300. <label className="font-bold uppercase text-black block">
  301. 端口 <span className="text-black">*</span>
  302. </label>
  303. <input
  304. type="number"
  305. placeholder="8080"
  306. 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]"
  307. value={singleForm.port}
  308. onChange={(e) => setSingleForm({ ...singleForm, port: Number(e.target.value) })}
  309. />
  310. </div>
  311. </div>
  312. {/* Username & Password */}
  313. <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
  314. <div className="space-y-1">
  315. <label className="font-bold uppercase text-black block">
  316. 鉴权用户名 (可选)
  317. </label>
  318. <input
  319. type="text"
  320. placeholder="username"
  321. 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]"
  322. value={singleForm.username}
  323. onChange={(e) => setSingleForm({ ...singleForm, username: e.target.value })}
  324. />
  325. </div>
  326. <div className="space-y-1">
  327. <label className="font-bold uppercase text-black block">
  328. 鉴权密码 (可选)
  329. </label>
  330. <input
  331. type="text"
  332. placeholder="password"
  333. 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]"
  334. value={singleForm.password}
  335. onChange={(e) => setSingleForm({ ...singleForm, password: e.target.value })}
  336. />
  337. </div>
  338. </div>
  339. </>
  340. ) : (
  341. /* 批量文本导入模式 */
  342. <div className="space-y-3">
  343. <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]">
  344. <div className="space-y-1">
  345. <label className="font-bold uppercase text-black block text-[10px]">统一代理池</label>
  346. <input
  347. type="text"
  348. list="proxy-pools-batch"
  349. placeholder="default"
  350. className="w-full px-2 py-1.5 border border-black text-xs font-mono bg-white outline-none"
  351. value={batchPool}
  352. onChange={(e) => setBatchPool(e.target.value)}
  353. />
  354. <datalist id="proxy-pools-batch">
  355. {existingPools.map((p) => (
  356. <option key={p} value={p} />
  357. ))}
  358. </datalist>
  359. </div>
  360. <div className="space-y-1">
  361. <label className="font-bold uppercase text-black block text-[10px]">默认协议</label>
  362. <select
  363. className="w-full px-2 py-1.5 border border-black text-xs bg-white outline-none"
  364. value={batchDefaultProto}
  365. onChange={(e) => setBatchDefaultProto(e.target.value)}
  366. >
  367. <option value="http">HTTP</option>
  368. <option value="https">HTTPS</option>
  369. <option value="socks5">SOCKS5</option>
  370. </select>
  371. </div>
  372. <div className="space-y-1">
  373. <label className="font-bold uppercase text-black block text-[10px]">初始状态</label>
  374. <select
  375. className="w-full px-2 py-1.5 border border-black text-xs bg-white outline-none"
  376. value={batchDefaultStatus}
  377. onChange={(e) => setBatchDefaultStatus(e.target.value as ProxyStatus)}
  378. >
  379. <option value="active">Active</option>
  380. <option value="disable">Disable</option>
  381. </select>
  382. </div>
  383. </div>
  384. <div className="space-y-1">
  385. <div className="flex items-center justify-between">
  386. <label className="font-bold uppercase text-black block">[ 多行粘贴代理文本 ]</label>
  387. <span className="text-black font-mono font-bold text-[10px]">
  388. 已识别: {parsedBatchList.length} 条
  389. </span>
  390. </div>
  391. <textarea
  392. 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]"
  393. rows={7}
  394. value={batchText}
  395. onChange={(e) => setBatchText(e.target.value)}
  396. 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`}
  397. />
  398. </div>
  399. </div>
  400. )}
  401. </div>
  402. {/* Footer */}
  403. <div className="px-5 py-3 bg-neutral-200 flex justify-end gap-2 border-t-2 border-black shrink-0">
  404. <button
  405. type="button"
  406. onClick={onClose}
  407. 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]"
  408. disabled={submitting}
  409. >
  410. [ 取消 ]
  411. </button>
  412. <button
  413. type="button"
  414. onClick={mode === 'single' ? handleSingleSubmit : handleBatchSubmit}
  415. disabled={submitting || (mode === 'batch' && parsedBatchList.length === 0)}
  416. 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"
  417. >
  418. <Plus size={13} />
  419. <span>
  420. {submitting
  421. ? '提交中...'
  422. : mode === 'single'
  423. ? '[ 确认添加 ]'
  424. : `[ 确认批量导入 (${parsedBatchList.length}条) ]`}
  425. </span>
  426. </button>
  427. </div>
  428. </div>
  429. </div>
  430. );
  431. }