import { Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, MenuItem, Stack, Switch, Tab, Tabs, TextField, Typography, } from "@mui/material"; import { useMutation, useQuery } from "@tanstack/react-query"; import { open } from "@tauri-apps/plugin-dialog"; import { enqueueSnackbar } from "notistack"; import React, { useEffect, useState } from "react"; import { qbAddTorrent, qbCategoriesQueryOptions, toQbError, } from "@/utils/qbittorrent"; import type { QbAddResult, QbSettings, QbTorrent, } from "@/utils/qbittorrent/types"; type Props = { open: boolean; onClose: () => void; settings: QbSettings; onAdded: (result: QbAddResult) => void; /** Used to preselect the category of a torrent being retried. */ torrent?: QbTorrent | null; }; type TabValue = "magnet" | "file"; export default function AddTorrentDialog({ open: isOpen, onClose, settings, onAdded, torrent, }: Props) { const [tab, setTab] = useState("magnet"); const [magnet, setMagnet] = useState(""); const [filePath, setFilePath] = useState(null); const [fileName, setFileName] = useState(null); const [category, setCategory] = useState(settings.defaultCategory ?? ""); const [paused, setPaused] = useState(settings.addPaused); const [autoTmm, setAutoTmm] = useState(settings.autoTmm); const categories = useQuery(qbCategoriesQueryOptions(isOpen)); useEffect(() => { if (!isOpen) return; setTab("magnet"); setMagnet(""); setFilePath(null); setFileName(null); setCategory(torrent?.category || settings.defaultCategory || ""); setPaused(settings.addPaused); setAutoTmm(settings.autoTmm); }, [isOpen, torrent, settings]); const pickFile = async () => { try { const selected = await open({ multiple: false, directory: false, filters: [{ name: "Torrent", extensions: ["torrent"] }], }); if (typeof selected === "string") { setFilePath(selected); setFileName(selected.split(/[\\/]/).pop() ?? selected); } } catch (error) { enqueueSnackbar(`Не удалось открыть диалог файла: ${error}`, { variant: "error", }); } }; const add = useMutation({ mutationFn: () => qbAddTorrent({ magnet: tab === "magnet" ? magnet.trim() : null, filePath: tab === "file" ? filePath : null, category: category || null, paused, autoTmm, }), onSuccess: (result) => { if (result.status === "duplicate") { enqueueSnackbar( result.message ?? "Такая раздача уже добавлена в qBittorrent", { variant: "warning" }, ); return; } if (result.status === "invalid") { enqueueSnackbar( result.message ?? "qBittorrent не принял этот торрент", { variant: "error" }, ); return; } enqueueSnackbar( result.status === "pending" ? "Раздача добавлена, qBittorrent получает метаданные" : "Раздача добавлена", { variant: "success" }, ); onAdded(result); onClose(); }, onError: (error) => { enqueueSnackbar(toQbError(error).message, { variant: "error" }); }, }); const magnetValid = magnet.trim().startsWith("magnet:?"); const canSubmit = !add.isPending && ((tab === "magnet" && magnetValid) || (tab === "file" && !!filePath)); const selectedCategory = categories.data?.find( (item) => item.name === category, ); return ( download Добавить раздачу setTab(value)} variant="fullWidth" sx={{ mb: 2, minHeight: 40 }} > {tab === "magnet" ? ( setMagnet(event.target.value)} error={magnet.length > 0 && !magnetValid} helperText={ magnet.length > 0 && !magnetValid ? "Ссылка должна начинаться с magnet:?" : "Например, magnet:?xt=urn:btih:…" } /> ) : ( Файл отправится в qBittorrent как есть; категория и папка применятся на стороне сервера. )} setCategory(event.target.value)} sx={{ mt: 2 }} disabled={categories.isLoading} helperText={ categories.isError ? "Не удалось загрузить категории qBittorrent" : selectedCategory ? `Папка: ${selectedCategory.savePath || "по умолчанию"}` : "Без категории — папка qBittorrent по умолчанию" } > Без категории {(categories.data ?? []).map((item) => ( {item.name} ))} setPaused(checked)} /> } label="Добавить на паузе" /> setAutoTmm(checked)} /> } label="Автоуправление категорией" /> ); }