ProxyAddModal.tsx 18 KB

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