feat(downloads): add qBittorrent integration
Continuous Integration / build_web (push) Failing after 0s
Continuous Integration / build (macos-latest) (push) Skipped
Continuous Integration / build (ubuntu-22.04) (push) Skipped
Continuous Integration / build (windows-11-arm) (push) Skipped
Continuous Integration / build (windows-latest) (push) Skipped
Continuous Integration / nightly_release (push) Skipped

- Rust client for the WebUI API: password/API-key auth, categories,
  magnet and .torrent add, sync polling, pause/resume/delete
- downloads page with progress, speed, ETA, filters, notifications and
  per-torrent actions
- settings page with OS keyring storage, self-signed TLS, Jellyfin
  refresh and polling options
- cross-platform keyring setup for Windows, macOS and Linux
This commit is contained in:
1xDed committed 2026-12-01 12:56:53 +03:00
1 parent fe30c4f1f9
commit 87315d9679
22 files changed
+4031 -21

No files matched your search

+494
View File
@@ -0,0 +1,494 @@
@use "../../styles/variables.scss" as *;
.downloads-page {
max-width: 1180px;
margin: 0 auto;
padding-bottom: 4rem;
box-sizing: border-box;
&--centered {
display: flex;
align-items: center;
justify-content: center;
min-height: 60vh;
}
}
.downloads-header {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
.downloads-heading {
display: flex;
flex-direction: column;
gap: 0.15rem;
h4 {
font-size: clamp(1.8rem, 3vw, 2.4rem);
font-weight: 700;
letter-spacing: -0.02em;
line-height: 1.1;
margin: 0;
}
}
.downloads-subtitle {
color: rgb(255 255 255 / 0.5);
font-size: 0.85rem;
}
.downloads-actions {
display: flex;
align-items: center;
gap: 0.75rem;
}
}
.downloads-summary {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.9rem;
margin: 1.4rem 0 1rem;
}
.downloads-stat {
display: flex;
align-items: center;
gap: 0.85rem;
padding: 0.95rem 1.1rem;
border-radius: 18px;
background: rgb(255 255 255 / 0.04);
border: 1px solid rgb(255 255 255 / 0.07);
min-width: 0;
> .material-symbols-rounded {
font-size: 1.6rem;
color: $clr-accent-default;
opacity: 0.9;
flex: 0 0 auto;
}
&-value {
font-family: var(--font-mono);
font-size: 1rem;
font-weight: 600;
color: rgb(255 255 255 / 0.9);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
&-label {
font-size: 0.72rem;
color: rgb(255 255 255 / 0.45);
margin-top: 0.1rem;
}
}
.downloads-banner {
display: flex;
align-items: center;
gap: 0.7rem;
padding: 0.65rem 0.9rem;
border-radius: 14px;
background: rgb(255 160 80 / 0.1);
border: 1px solid rgb(255 160 80 / 0.25);
color: #ffc08a;
font-size: 0.84rem;
margin-bottom: 0.9rem;
.material-symbols-rounded {
font-size: 1.15rem;
}
span:nth-child(2) {
flex: 1;
min-width: 0;
}
}
.downloads-filters {
display: flex;
gap: 0.5rem;
overflow-x: auto;
padding: 0.25rem 0 1rem;
scrollbar-width: none;
&::-webkit-scrollbar {
display: none;
}
}
.downloads-filter {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 1rem;
border-radius: 999px;
border: 1px solid rgb(255 255 255 / 0.1);
background: transparent;
color: rgb(255 255 255 / 0.62);
font: inherit;
font-size: 0.86rem;
font-weight: 500;
white-space: nowrap;
cursor: pointer;
transition:
background-color 0.18s ease,
border-color 0.18s ease,
color 0.18s ease;
&:hover {
background: rgb(255 255 255 / 0.06);
color: rgb(255 255 255 / 0.85);
}
&--active {
background: rgba($clr-accent-default, 0.16);
border-color: rgba($clr-accent-default, 0.45);
color: #fff;
}
}
.downloads-filter-count {
min-width: 1.5em;
padding: 0.05em 0.4em;
border-radius: 999px;
background: rgb(255 255 255 / 0.08);
font-size: 0.7rem;
font-family: var(--font-mono);
text-align: center;
}
.downloads-list {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.qb-row {
display: flex;
align-items: stretch;
gap: 1rem;
padding: 1rem 1.1rem;
border-radius: 18px;
background: rgb(255 255 255 / 0.04);
border: 1px solid rgb(255 255 255 / 0.07);
transition:
background-color 0.18s ease,
border-color 0.18s ease;
&:hover {
background: rgb(255 255 255 / 0.06);
}
&--error {
border-color: rgb(255 110 110 / 0.28);
background: rgb(255 90 90 / 0.05);
}
&-body {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.45rem;
}
&-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 0.75rem;
}
&-name {
font-size: 0.96rem !important;
font-weight: 600 !important;
line-height: 1.35 !important;
color: rgb(255 255 255 / 0.92) !important;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
word-break: break-word;
}
&-meta {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.3rem 0.9rem;
font-size: 0.76rem;
color: rgb(255 255 255 / 0.5);
}
&-category {
display: inline-flex;
align-items: center;
gap: 0.25rem;
color: rgb(255 255 255 / 0.72);
.material-symbols-rounded {
font-size: 0.95rem;
opacity: 0.55;
}
&--muted {
opacity: 0.5;
}
}
&-peers {
display: inline-flex;
gap: 0.5rem;
font-family: var(--font-mono);
}
&-error {
display: flex;
align-items: center;
gap: 0.35rem;
font-size: 0.77rem;
color: #ff8a8a;
.material-symbols-rounded {
font-size: 1rem;
}
}
&-progress {
height: 6px;
border-radius: 999px;
background: rgb(255 255 255 / 0.08);
overflow: hidden;
}
&-progress-fill {
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, $clr-accent-default, #8a7dff);
transition: width 0.5s ease;
}
&--seeding &-progress-fill {
background: linear-gradient(90deg, #3fbf85, #7ee2a8);
}
&--error &-progress-fill {
background: #ff6b6b;
}
&--paused &-progress-fill {
background: rgb(255 255 255 / 0.35);
}
&-stats {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.3rem 0.9rem;
font-family: var(--font-mono);
font-size: 0.73rem;
color: rgb(255 255 255 / 0.5);
}
&-percent {
color: rgb(255 255 255 / 0.88);
font-weight: 600;
}
&-speed {
color: #7ee2a8;
&--up {
color: #9bb7ff;
}
}
&-eta {
color: rgb(255 255 255 / 0.42);
}
&-actions {
display: flex;
align-items: center;
gap: 0.1rem;
align-self: center;
.MuiIconButton-root {
color: rgb(255 255 255 / 0.55);
&:hover {
color: #fff;
background: rgb(255 255 255 / 0.08);
}
}
}
}
.qb-state {
height: 22px !important;
font-size: 0.7rem !important;
font-weight: 600 !important;
background: rgb(255 255 255 / 0.08) !important;
color: rgb(255 255 255 / 0.78) !important;
flex: 0 0 auto;
&--downloading {
background: rgba($clr-accent-default, 0.16) !important;
color: #ffb3d1 !important;
}
&--seeding {
background: rgb(80 210 150 / 0.14) !important;
color: #7ee2a8 !important;
}
&--paused {
background: rgb(255 255 255 / 0.07) !important;
color: rgb(255 255 255 / 0.55) !important;
}
&--error {
background: rgb(255 90 90 / 0.16) !important;
color: #ff8a8a !important;
}
}
.qb-seed {
color: #7ee2a8;
}
.qb-leech {
color: #ffb27a;
}
.downloads-state {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
gap: 0.9rem;
padding: clamp(2rem, 8vh, 5rem) 1.5rem;
margin-top: 1.5rem;
border-radius: 24px;
border: 1px dashed rgb(255 255 255 / 0.12);
background: rgb(255 255 255 / 0.025);
&-icon {
font-size: 3rem !important;
color: $clr-accent-default;
opacity: 0.9;
}
&-text {
max-width: 46ch;
color: rgb(255 255 255 / 0.58);
font-size: 0.88rem;
}
&--small {
padding: 2.5rem 1.5rem;
margin-top: 1rem;
}
&--error &-icon {
color: #ff8a8a;
}
}
.downloads-delete-name {
font-weight: 600 !important;
margin-bottom: 0.75rem !important;
word-break: break-word;
}
.downloads-settings-result {
display: flex;
align-items: flex-start;
gap: 0.75rem;
padding: 0.9rem 1rem;
border-radius: 14px;
background: rgb(80 210 150 / 0.08);
border: 1px solid rgb(80 210 150 / 0.22);
font-size: 0.86rem;
line-height: 1.5;
.material-symbols-rounded {
color: #7ee2a8;
font-size: 1.2rem;
}
&--error {
background: rgb(255 90 90 / 0.08);
border-color: rgb(255 90 90 / 0.25);
.material-symbols-rounded {
color: #ff8a8a;
}
}
}
@media (max-width: 900px) {
.downloads-summary {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.downloads-stat:last-child {
grid-column: 1 / -1;
}
}
@media (max-width: 640px) {
.downloads-page {
padding-bottom: 6.5rem;
}
.downloads-header {
align-items: flex-start;
.downloads-actions {
width: 100%;
justify-content: flex-end;
}
}
.downloads-summary {
grid-template-columns: 1fr;
gap: 0.6rem;
margin-top: 1rem;
}
.downloads-stat:last-child {
grid-column: auto;
}
.qb-row {
padding: 0.85rem;
gap: 0.5rem;
&-head {
flex-direction: column;
gap: 0.35rem;
}
&-stats {
font-size: 0.7rem;
gap: 0.25rem 0.65rem;
}
&-actions {
flex-direction: column;
align-self: flex-start;
}
}
.downloads-state {
padding: 2.25rem 1rem;
margin-top: 1rem;
}
}
+456
View File
@@ -0,0 +1,456 @@
import { getLibraryApi } from "@jellyfin/sdk/lib/utils/api/library-api";
import {
Button,
Checkbox,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
FormControlLabel,
IconButton,
Stack,
Tooltip,
Typography,
} from "@mui/material";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import {
isPermissionGranted,
requestPermission,
sendNotification,
} from "@tauri-apps/plugin-notification";
import { enqueueSnackbar } from "notistack";
import React, { useEffect, useMemo, useRef, useState } from "react";
import AddTorrentDialog from "@/components/downloads/addTorrentDialog";
import TorrentRow from "@/components/downloads/torrentRow";
import {
qbDelete,
qbPause,
qbResume,
qbSettingsQueryOptions,
qbSnapshotQueryOptions,
toQbError,
} from "@/utils/qbittorrent";
import {
compareTorrents,
formatBytes,
formatSpeed,
getTorrentState,
matchesFilter,
type TorrentFilter,
} from "@/utils/qbittorrent/format";
import type { QbTorrent } from "@/utils/qbittorrent/types";
import { useApiInContext } from "@/utils/store/api";
import "./downloads.scss";
export const Route = createFileRoute("/_api/downloads")({
component: DownloadsPage,
});
const FILTERS: { value: TorrentFilter; label: string }[] = [
{ value: "all", label: "Все" },
{ value: "downloading", label: "Скачиваются" },
{ value: "completed", label: "Завершённые" },
{ value: "error", label: "Ошибки" },
];
const prettyHost = (url: string) =>
url.replace(/^https?:\/\//, "").replace(/\/+$/, "");
const notifyCompletion = async (name: string) => {
try {
let granted = await isPermissionGranted();
if (!granted) {
granted = (await requestPermission()) === "granted";
}
if (granted) {
sendNotification({
title: "Загрузка завершена",
body: name,
});
}
} catch (error) {
// Notification backends are optional (e.g. Linux without libnotify).
console.warn("qBittorrent completion notification failed", error);
}
};
function DownloadsPage() {
const navigate = useNavigate();
const api = useApiInContext((state) => state.api);
const queryClient = useQueryClient();
const settingsQuery = useQuery(qbSettingsQueryOptions);
const settings = settingsQuery.data;
const configured = Boolean(settings?.baseUrl && settings.hasSecret);
const snapshotQuery = useQuery(qbSnapshotQueryOptions(settings));
const data = snapshotQuery.data;
const [filter, setFilter] = useState<TorrentFilter>("all");
const [addOpen, setAddOpen] = useState(false);
const [deleteTarget, setDeleteTarget] = useState<QbTorrent | null>(null);
const [deleteFiles, setDeleteFiles] = useState(false);
const previousProgress = useRef<Map<string, number>>(new Map());
const lastJellyfinRefresh = useRef(0);
const invalidateSnapshot = () =>
queryClient.invalidateQueries({ queryKey: ["qbittorrent", "snapshot"] });
const torrents = useMemo(
() => [...(data?.torrents ?? [])].sort(compareTorrents),
[data],
);
const counts = useMemo(() => {
const result: Record<TorrentFilter, number> = {
all: torrents.length,
downloading: 0,
completed: 0,
error: 0,
};
for (const torrent of torrents) {
for (const value of ["downloading", "completed", "error"] as const) {
if (matchesFilter(torrent, value)) result[value] += 1;
}
}
return result;
}, [torrents]);
const visibleTorrents = useMemo(
() => torrents.filter((torrent) => matchesFilter(torrent, filter)),
[torrents, filter],
);
const refreshJellyfin = () => {
if (!api || !settings?.refreshJellyfin) return;
const now = Date.now();
if (now - lastJellyfinRefresh.current < 30_000) return;
lastJellyfinRefresh.current = now;
getLibraryApi(api)
.refreshLibrary()
.catch((error) => console.warn("Jellyfin library refresh failed", error));
};
// Detect the download -> complete transition between two polls. The first
// snapshot only seeds the map, so torrents that were already complete when
// the page opened do not produce notifications.
useEffect(() => {
if (!data || !settings) return;
for (const torrent of data.torrents) {
const before = previousProgress.current.get(torrent.hash);
if (
before !== undefined &&
before < 1 &&
torrent.progress >= 1 &&
!getTorrentState(torrent.state).error
) {
if (settings.notifyOnComplete) {
void notifyCompletion(torrent.name || "Раздача");
}
refreshJellyfin();
}
previousProgress.current.set(torrent.hash, torrent.progress);
}
const present = new Set(data.torrents.map((torrent) => torrent.hash));
for (const hash of previousProgress.current.keys()) {
if (!present.has(hash)) previousProgress.current.delete(hash);
}
}, [data, settings]);
const action = useMutation({
mutationFn: (variables: {
torrent: QbTorrent;
action: "pause" | "resume";
}) =>
variables.action === "pause"
? qbPause([variables.torrent.hash])
: qbResume([variables.torrent.hash]),
onError: (error) => {
enqueueSnackbar(toQbError(error).message, { variant: "error" });
},
onSettled: invalidateSnapshot,
});
const remove = useMutation({
mutationFn: (variables: { torrent: QbTorrent; deleteFiles: boolean }) =>
qbDelete([variables.torrent.hash], variables.deleteFiles),
onSuccess: () => {
enqueueSnackbar("Раздача удалена", { variant: "success" });
setDeleteTarget(null);
setDeleteFiles(false);
void invalidateSnapshot();
},
onError: (error) => {
enqueueSnackbar(toQbError(error).message, { variant: "error" });
},
});
const pollError = snapshotQuery.isError
? toQbError(snapshotQuery.error)
: null;
if (settingsQuery.isLoading) {
return (
<div className="downloads-page downloads-page--centered">
<CircularProgress />
</div>
);
}
return (
<div className="scrollY padded-top downloads-page">
<header className="downloads-header">
<div className="downloads-heading">
<Typography variant="h4" sx={{ fontWeight: 700 }}>
Загрузки
</Typography>
<Typography variant="body2" className="downloads-subtitle">
qBittorrent
{settings?.baseUrl ? ` · ${prettyHost(settings.baseUrl)}` : ""}
</Typography>
</div>
<div className="downloads-actions">
<Tooltip title="Обновить">
<IconButton
aria-label="Обновить"
onClick={() => void snapshotQuery.refetch()}
disabled={!configured || snapshotQuery.isFetching}
>
<span className="material-symbols-rounded">refresh</span>
</IconButton>
</Tooltip>
<Button
variant="contained"
disabled={!configured}
onClick={() => setAddOpen(true)}
startIcon={<span className="material-symbols-rounded">add</span>}
>
Добавить
</Button>
</div>
</header>
{!settings?.hasSecret || !settings.baseUrl ? (
<section className="downloads-state">
<span className="material-symbols-rounded downloads-state-icon">
cloud_download
</span>
<Typography variant="h5" sx={{ fontWeight: 700 }}>
Подключите qBittorrent
</Typography>
<Typography className="downloads-state-text">
Добавляйте magnet-ссылки и .torrent файлы, выбирайте категорию и
следите за прогрессом каждой раздачи прямо из Blink.
</Typography>
<Button
variant="contained"
onClick={() => navigate({ to: "/settings/downloads" })}
>
Открыть настройки
</Button>
</section>
) : pollError && !data ? (
<section className="downloads-state downloads-state--error">
<span className="material-symbols-rounded downloads-state-icon">
cloud_off
</span>
<Typography variant="h5" sx={{ fontWeight: 700 }}>
qBittorrent не отвечает
</Typography>
<Typography className="downloads-state-text">
{pollError.message}
</Typography>
<Stack direction="row" spacing={1}>
<Button
variant="contained"
onClick={() => void snapshotQuery.refetch()}
>
Повторить
</Button>
<Button onClick={() => navigate({ to: "/settings/downloads" })}>
Настройки
</Button>
</Stack>
</section>
) : (
<>
{data && (
<section className="downloads-summary">
<div className="downloads-stat">
<span className="material-symbols-rounded">south</span>
<div>
<div className="downloads-stat-value">
{formatSpeed(data.serverState.dlInfoSpeed)}
</div>
<div className="downloads-stat-label">Скачивание</div>
</div>
</div>
<div className="downloads-stat">
<span className="material-symbols-rounded">north</span>
<div>
<div className="downloads-stat-value">
{formatSpeed(data.serverState.upInfoSpeed)}
</div>
<div className="downloads-stat-label">Раздача</div>
</div>
</div>
<div className="downloads-stat">
<span className="material-symbols-rounded">hard_drive</span>
<div>
<div className="downloads-stat-value">
{formatBytes(data.serverState.freeSpaceOnDisk)}
</div>
<div className="downloads-stat-label">Свободно на диске</div>
</div>
</div>
</section>
)}
{pollError && data && (
<div className="downloads-banner">
<span className="material-symbols-rounded">cloud_off</span>
<span>{pollError.message}</span>
<Button size="small" onClick={() => void snapshotQuery.refetch()}>
Повторить
</Button>
</div>
)}
<nav className="downloads-filters" aria-label="Фильтр раздач">
{FILTERS.map((item) => (
<button
key={item.value}
type="button"
className={
filter === item.value
? "downloads-filter downloads-filter--active"
: "downloads-filter"
}
onClick={() => setFilter(item.value)}
>
{item.label}
<span className="downloads-filter-count">
{counts[item.value]}
</span>
</button>
))}
</nav>
{visibleTorrents.length === 0 ? (
<section className="downloads-state downloads-state--small">
<span className="material-symbols-rounded downloads-state-icon">
{filter === "all" ? "download_done" : "filter_alt_off"}
</span>
<Typography variant="h6" sx={{ fontWeight: 600 }}>
{filter === "all"
? "Пока ничего не скачивается"
: "В этом фильтре пусто"}
</Typography>
{filter === "all" && (
<Typography className="downloads-state-text">
Вставьте magnet-ссылку или выберите .torrent файл — статус
появится здесь.
</Typography>
)}
{filter === "all" && (
<Button variant="contained" onClick={() => setAddOpen(true)}>
Добавить раздачу
</Button>
)}
</section>
) : (
<section className="downloads-list">
{visibleTorrents.map((torrent) => (
<TorrentRow
key={torrent.hash}
torrent={torrent}
busy={
action.isPending &&
action.variables?.torrent.hash === torrent.hash
}
onPause={(item) =>
action.mutate({ torrent: item, action: "pause" })
}
onResume={(item) =>
action.mutate({ torrent: item, action: "resume" })
}
onDelete={(item) => {
setDeleteFiles(false);
setDeleteTarget(item);
}}
/>
))}
</section>
)}
</>
)}
{settings && (
<AddTorrentDialog
open={addOpen}
onClose={() => setAddOpen(false)}
settings={settings}
onAdded={invalidateSnapshot}
/>
)}
<Dialog
open={Boolean(deleteTarget)}
onClose={remove.isPending ? undefined : () => setDeleteTarget(null)}
maxWidth="xs"
fullWidth
disableScrollLock
>
<DialogTitle>Удалить раздачу?</DialogTitle>
<DialogContent>
<Typography className="downloads-delete-name">
{deleteTarget?.name}
</Typography>
<FormControlLabel
control={
<Checkbox
checked={deleteFiles}
onChange={(_, checked) => setDeleteFiles(checked)}
/>
}
label="Удалить скачанные файлы"
/>
{deleteFiles && (
<Typography variant="caption" color="error">
Файлы будут удалены с диска сервера qBittorrent без возможности
восстановления.
</Typography>
)}
</DialogContent>
<DialogActions>
<Button
onClick={() => setDeleteTarget(null)}
disabled={remove.isPending}
>
Отмена
</Button>
<Button
variant="contained"
color="error"
disabled={remove.isPending}
onClick={() =>
deleteTarget &&
remove.mutate({
torrent: deleteTarget,
deleteFiles,
})
}
>
Удалить
</Button>
</DialogActions>
</Dialog>
</div>
);
}
+6
View File
@@ -104,6 +104,12 @@ function SettingsRoute() {
primary="Настройки"
className="settings-sidebar-list-item"
/>
<ListItemLink
to="/settings/downloads"
icon="download"
primary="Загрузки"
className="settings-sidebar-list-item"
/>
<ListItemLink
to="/settings/changeServer"
icon="dns"
+383
View File
@@ -0,0 +1,383 @@
import {
Button,
CircularProgress,
FormControlLabel,
MenuItem,
Stack,
Switch,
TextField,
Typography,
} from "@mui/material";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
import { enqueueSnackbar } from "notistack";
import React, { useEffect, useState } from "react";
import {
qbForgetSecret,
qbSaveSettings,
qbSettingsQueryOptions,
qbTestConnection,
toQbError,
} from "@/utils/qbittorrent";
import type { QbConnectionInfo, QbSettings } from "@/utils/qbittorrent/types";
export const Route = createFileRoute("/_api/settings/downloads")({
component: DownloadsSettingsPage,
});
function DownloadsSettingsPage() {
const queryClient = useQueryClient();
const settingsQuery = useQuery(qbSettingsQueryOptions);
const [form, setForm] = useState<QbSettings | null>(null);
const [secret, setSecret] = useState("");
const [testResult, setTestResult] = useState<QbConnectionInfo | null>(null);
useEffect(() => {
if (settingsQuery.data && !form) {
setForm(settingsQuery.data);
}
}, [settingsQuery.data, form]);
const update = <Key extends keyof QbSettings>(
key: Key,
value: QbSettings[Key],
) => {
setForm((current) => (current ? { ...current, [key]: value } : current));
};
const save = useMutation({
mutationFn: async () => {
if (!form) throw new Error("Настройки ещё не загружены");
if (!form.hasSecret && !secret.trim()) {
throw new Error("Введите пароль qBittorrent или API-ключ");
}
if (
settingsQuery.data &&
form.useApiKey !== settingsQuery.data.useApiKey &&
!secret.trim()
) {
throw new Error(
"Способ входа изменился — введите новый пароль или API-ключ",
);
}
return qbSaveSettings(form, secret || undefined);
},
onSuccess: (updated) => {
setForm(updated);
setSecret("");
setTestResult(null);
queryClient.setQueryData(["qbittorrent", "settings"], updated);
void queryClient.invalidateQueries({
queryKey: ["qbittorrent", "categories"],
});
void queryClient.invalidateQueries({
queryKey: ["qbittorrent", "snapshot"],
});
if (form?.rememberSecret && !updated.secretSaved) {
enqueueSnackbar(
"Настройки сохранены, но системное хранилище секретов недоступно. Пароль будет действовать до закрытия Blink.",
{ variant: "warning" },
);
} else {
enqueueSnackbar("Настройки загрузок сохранены", {
variant: "success",
});
}
},
onError: (error) => {
enqueueSnackbar(toQbError(error).message, { variant: "error" });
},
});
const test = useMutation({
mutationFn: async () => {
if (!form) throw new Error("Настройки ещё не загружены");
if (
settingsQuery.data &&
form.useApiKey !== settingsQuery.data.useApiKey &&
!secret.trim()
) {
throw new Error(
"Способ входа изменился — введите новый пароль или API-ключ",
);
}
return qbTestConnection(form, secret || undefined);
},
onSuccess: (result) => {
setTestResult(result);
enqueueSnackbar("Соединение с qBittorrent установлено", {
variant: "success",
});
},
onError: (error) => {
setTestResult(null);
enqueueSnackbar(toQbError(error).message, { variant: "error" });
},
});
const forget = useMutation({
mutationFn: qbForgetSecret,
onSuccess: (updated) => {
setForm(updated);
setSecret("");
setTestResult(null);
queryClient.setQueryData(["qbittorrent", "settings"], updated);
enqueueSnackbar("Сохранённый пароль удалён", { variant: "success" });
},
onError: (error) => {
enqueueSnackbar(toQbError(error).message, { variant: "error" });
},
});
if (settingsQuery.isError) {
return (
<div className="settings-page-scrollY">
<Typography variant="h4">Загрузки</Typography>
<div className="downloads-settings-result downloads-settings-result--error">
<span className="material-symbols-rounded">error</span>
<div>
{toQbError(settingsQuery.error).message}
<Button
size="small"
onClick={() => void settingsQuery.refetch()}
sx={{ ml: 1 }}
>
Повторить
</Button>
</div>
</div>
</div>
);
}
if (settingsQuery.isLoading || !form) {
return (
<div className="settings-page-scrollY">
<CircularProgress />
</div>
);
}
return (
<div className="settings-page-scrollY">
<Typography variant="h4">Загрузки</Typography>
<Typography variant="body2" sx={{ mt: 0.5, opacity: 0.6 }}>
Подключение к qBittorrent и поведение страницы загрузок.
</Typography>
<form
className="settings-form"
onSubmit={(event) => {
event.preventDefault();
test.reset();
save.mutate();
}}
>
<TextField
fullWidth
label="Адрес WebUI qBittorrent"
placeholder="http://192.168.1.10:8080"
value={form.baseUrl}
onChange={(event) => update("baseUrl", event.target.value)}
helperText="Без /api/v2. Поддерживаются http:// и https://."
/>
<TextField
fullWidth
select
label="Способ входа"
value={form.useApiKey ? "apiKey" : "password"}
onChange={(event) =>
update("useApiKey", event.target.value === "apiKey")
}
>
<MenuItem value="password">Логин и пароль</MenuItem>
<MenuItem value="apiKey">API-ключ (qBittorrent 5.3+)</MenuItem>
</TextField>
{!form.useApiKey && (
<TextField
fullWidth
label="Логин WebUI"
value={form.username}
onChange={(event) => update("username", event.target.value)}
autoComplete="username"
/>
)}
<TextField
fullWidth
type="password"
label={form.useApiKey ? "API-ключ" : "Пароль"}
value={secret}
onChange={(event) => setSecret(event.target.value)}
placeholder={form.hasSecret ? "•••••••• (задан)" : ""}
autoComplete="new-password"
helperText={
form.hasSecret
? "Оставьте поле пустым, чтобы не менять текущий секрет."
: form.useApiKey
? "Ключ создаётся в qBittorrent: WebUI → API."
: "Пароль хранится только в системном хранилище секретов."
}
/>
<Stack
direction={{ xs: "column", sm: "row" }}
spacing={{ xs: 0, sm: 2 }}
>
<FormControlLabel
control={
<Switch
checked={form.rememberSecret}
onChange={(_, checked) => update("rememberSecret", checked)}
/>
}
label="Запомнить секрет"
/>
<FormControlLabel
control={
<Switch
checked={form.allowInvalidCerts}
onChange={(_, checked) => update("allowInvalidCerts", checked)}
/>
}
label="Принимать самоподписанный сертификат"
/>
</Stack>
<Typography variant="caption" sx={{ opacity: 0.55, mt: -1 }}>
Без системного хранилища (например, на Linux без Secret Service)
пароль действует до закрытия Blink и не пишется в файл.
</Typography>
<TextField
fullWidth
label="Категория по умолчанию"
placeholder="movies"
value={form.defaultCategory}
onChange={(event) => update("defaultCategory", event.target.value)}
helperText="Подставляется в диалог добавления. Пустое поле — без категории."
/>
<Stack
direction={{ xs: "column", sm: "row" }}
spacing={{ xs: 0, sm: 2 }}
>
<FormControlLabel
control={
<Switch
checked={form.autoTmm}
onChange={(_, checked) => update("autoTmm", checked)}
/>
}
label="Автоуправление категорией"
/>
<FormControlLabel
control={
<Switch
checked={form.addPaused}
onChange={(_, checked) => update("addPaused", checked)}
/>
}
label="Добавлять на паузе"
/>
</Stack>
<Stack
direction={{ xs: "column", sm: "row" }}
spacing={{ xs: 0, sm: 2 }}
>
<FormControlLabel
control={
<Switch
checked={form.notifyOnComplete}
onChange={(_, checked) => update("notifyOnComplete", checked)}
/>
}
label="Уведомлять о завершении"
/>
<FormControlLabel
control={
<Switch
checked={form.refreshJellyfin}
onChange={(_, checked) => update("refreshJellyfin", checked)}
/>
}
label="Обновлять библиотеку Jellyfin"
/>
</Stack>
<TextField
fullWidth
type="number"
label="Интервал обновления, мс"
value={form.pollIntervalMs}
onChange={(event) =>
update("pollIntervalMs", Number(event.target.value) || 0)
}
onBlur={() =>
update(
"pollIntervalMs",
Math.min(60_000, Math.max(1000, form.pollIntervalMs)),
)
}
helperText="От 1000 до 60000 мс. По умолчанию 2000."
/>
{testResult && (
<div className="downloads-settings-result">
<span className="material-symbols-rounded">check_circle</span>
<div>
<strong>
qBittorrent {testResult.appVersion} · WebAPI{" "}
{testResult.apiVersion}
</strong>
<div>
Папка по умолчанию: {testResult.defaultSavePath || "не задана"}
</div>
</div>
</div>
)}
{test.isError && (
<div className="downloads-settings-result downloads-settings-result--error">
<span className="material-symbols-rounded">error</span>
<div>{toQbError(test.error).message}</div>
</div>
)}
<Stack
direction={{ xs: "column", sm: "row" }}
spacing={1.5}
sx={{ alignSelf: "flex-end", width: { xs: "100%", sm: "auto" } }}
>
{form.hasSecret && (
<Button
color="inherit"
onClick={() => forget.mutate()}
disabled={forget.isPending || save.isPending}
>
Забыть пароль
</Button>
)}
<Button
type="button"
variant="outlined"
onClick={() => test.mutate()}
disabled={test.isPending || save.isPending || !form.baseUrl}
>
Проверить соединение
</Button>
<Button
type="submit"
variant="contained"
disabled={save.isPending || !form.baseUrl}
>
Сохранить
</Button>
</Stack>
</form>
</div>
);
}