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

+1
View File
@@ -204,6 +204,7 @@
.appBar-groups,
.appBar-cast,
.appBar-favorite,
.appBar-downloads,
[aria-label="Главная"] {
display: none !important;
}
+10
View File
@@ -76,6 +76,7 @@ const AppBarContent = () => {
const fallbackTitle = (() => {
const path = location.pathname;
if (path === "/favorite") return "Избранное";
if (path === "/downloads") return "Загрузки";
if (path.startsWith("/music/")) return "Музыка";
if (path.startsWith("/player/audio")) return "Сейчас играет";
return "";
@@ -148,6 +149,15 @@ const AppBarContent = () => {
<span className="material-symbols-rounded">search</span>
</IconButton>
</Tooltip>
<Tooltip title="Загрузки">
<IconButton
className="appBar-downloads"
onClick={() => navigate({ to: "/downloads" })}
aria-label="Загрузки"
>
<span className="material-symbols-rounded">download</span>
</IconButton>
</Tooltip>
<Tooltip title="Пульт">
<IconButton
onClick={() => navigate({ to: "/remote" })}
@@ -99,6 +99,13 @@ export const NavigationDrawer = ({ open, onClose }: NavigationDrawerProps) => {
primary="Пульт"
onClick={onClose}
/>
<ListItemLink
className="library-drawer-item"
to="/downloads"
icon="download"
primary="Загрузки"
onClick={onClose}
/>
<ListItemLink
className="library-drawer-item"
to="/favorite"
@@ -0,0 +1,288 @@
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<TabValue>("magnet");
const [magnet, setMagnet] = useState("");
const [filePath, setFilePath] = useState<string | null>(null);
const [fileName, setFileName] = useState<string | null>(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 (
<Dialog
open={isOpen}
onClose={add.isPending ? undefined : onClose}
fullWidth
maxWidth="sm"
disableScrollLock
slotProps={{
paper: {
sx: {
backgroundColor: "rgba(20, 20, 30, 0.82)",
backdropFilter: "blur(24px) saturate(180%)",
backgroundImage:
"linear-gradient(rgba(255, 255, 255, 0.05), rgba(255, 255, 255, 0))",
border: "1px solid rgba(255, 255, 255, 0.08)",
boxShadow: "0 20px 50px rgba(0,0,0,0.5)",
borderRadius: 4,
overflow: "hidden",
},
},
}}
>
<DialogTitle sx={{ pb: 0 }}>
<Stack direction="row" spacing={1.5} sx={{ alignItems: "center" }}>
<span
className="material-symbols-rounded"
style={{ color: "var(--mui-palette-primary-main)" }}
>
download
</span>
<Typography variant="h6" sx={{ fontWeight: 700 }}>
Добавить раздачу
</Typography>
</Stack>
</DialogTitle>
<DialogContent sx={{ pt: 1 }}>
<Tabs
value={tab}
onChange={(_, value: TabValue) => setTab(value)}
variant="fullWidth"
sx={{ mb: 2, minHeight: 40 }}
>
<Tab value="magnet" label="Magnet-ссылка" />
<Tab value="file" label=".torrent файл" />
</Tabs>
{tab === "magnet" ? (
<TextField
autoFocus
fullWidth
multiline
minRows={3}
maxRows={6}
label="magnet:?xt=urn:btih:…"
placeholder="Вставьте magnet-ссылку"
value={magnet}
onChange={(event) => setMagnet(event.target.value)}
error={magnet.length > 0 && !magnetValid}
helperText={
magnet.length > 0 && !magnetValid
? "Ссылка должна начинаться с magnet:?"
: "Например, magnet:?xt=urn:btih:…"
}
/>
) : (
<Stack spacing={1.5}>
<Button
variant="outlined"
size="large"
onClick={pickFile}
startIcon={
<span className="material-symbols-rounded">folder_open</span>
}
sx={{
borderStyle: "dashed",
py: 3,
justifyContent: "flex-start",
textTransform: "none",
}}
>
{fileName ?? "Выбрать .torrent файл"}
</Button>
<Typography variant="caption" sx={{ opacity: 0.6 }}>
Файл отправится в qBittorrent как есть; категория и папка
применятся на стороне сервера.
</Typography>
</Stack>
)}
<TextField
select
fullWidth
label="Категория"
value={category}
onChange={(event) => setCategory(event.target.value)}
sx={{ mt: 2 }}
disabled={categories.isLoading}
helperText={
categories.isError
? "Не удалось загрузить категории qBittorrent"
: selectedCategory
? `Папка: ${selectedCategory.savePath || "по умолчанию"}`
: "Без категории — папка qBittorrent по умолчанию"
}
>
<MenuItem value="">Без категории</MenuItem>
{(categories.data ?? []).map((item) => (
<MenuItem key={item.name} value={item.name}>
{item.name}
</MenuItem>
))}
</TextField>
<Stack
direction={{ xs: "column", sm: "row" }}
spacing={{ xs: 0, sm: 2 }}
sx={{ mt: 1 }}
>
<FormControlLabel
control={
<Switch
checked={paused}
onChange={(_, checked) => setPaused(checked)}
/>
}
label="Добавить на паузе"
/>
<FormControlLabel
control={
<Switch
checked={autoTmm}
onChange={(_, checked) => setAutoTmm(checked)}
/>
}
label="Автоуправление категорией"
/>
</Stack>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2.5 }}>
<Button onClick={onClose} disabled={add.isPending}>
Отмена
</Button>
<Button
variant="contained"
loading={add.isPending}
disabled={!canSubmit}
onClick={() => add.mutate()}
>
Добавить
</Button>
</DialogActions>
</Dialog>
);
}
+139
View File
@@ -0,0 +1,139 @@
import { Chip, IconButton, Tooltip, Typography } from "@mui/material";
import React from "react";
import {
formatBytes,
formatEta,
formatPercent,
formatSpeed,
getTorrentState,
} from "@/utils/qbittorrent/format";
import type { QbTorrent } from "@/utils/qbittorrent/types";
type Props = {
torrent: QbTorrent;
busy?: boolean;
onPause: (torrent: QbTorrent) => void;
onResume: (torrent: QbTorrent) => void;
onDelete: (torrent: QbTorrent) => void;
};
export default function TorrentRow({
torrent,
busy,
onPause,
onResume,
onDelete,
}: Props) {
const info = getTorrentState(torrent.state);
const percent = Math.min(100, Math.max(0, torrent.progress * 100));
const showEta = !info.done && !info.error;
return (
<article className={`qb-row qb-row--${info.tone}`}>
<div className="qb-row-body">
<div className="qb-row-head">
<Typography className="qb-row-name" title={torrent.name}>
{torrent.name || "Без названия"}
</Typography>
<Chip
size="small"
className={`qb-state qb-state--${info.tone}`}
label={info.label}
/>
</div>
<div className="qb-row-meta">
{torrent.category ? (
<span className="qb-row-category">
<span className="material-symbols-rounded">label</span>
{torrent.category}
</span>
) : (
<span className="qb-row-category qb-row-category--muted">
Без категории
</span>
)}
<span>{formatBytes(torrent.size)}</span>
{torrent.numSeeds > 0 && (
<span className="qb-row-peers">
<span className="qb-seed">▲ {torrent.numSeeds}</span>
{torrent.numLeeches > 0 && (
<span className="qb-leech">▼ {torrent.numLeeches}</span>
)}
</span>
)}
{info.done && torrent.ratio > 0 && (
<span>Рейтинг {torrent.ratio.toFixed(2).replace(".", ",")}</span>
)}
</div>
{torrent.error && (
<div className="qb-row-error">
<span className="material-symbols-rounded">error</span>
{torrent.error}
</div>
)}
<div className="qb-row-progress" aria-hidden="true">
<div
className="qb-row-progress-fill"
style={{ width: `${percent}%` }}
/>
</div>
<div className="qb-row-stats">
<span className="qb-row-percent">
{formatPercent(torrent.progress)}
</span>
<span>
{formatBytes(torrent.completed)} из {formatBytes(torrent.size)}
</span>
{!info.done && (
<span className="qb-row-speed">
↓ {formatSpeed(torrent.dlspeed)}
</span>
)}
<span className="qb-row-speed qb-row-speed--up">
↑ {formatSpeed(torrent.upspeed)}
</span>
{showEta && (
<span className="qb-row-eta">
Осталось {formatEta(torrent.eta)}
</span>
)}
</div>
</div>
<div className="qb-row-actions">
<Tooltip title={info.paused ? "Продолжить" : "Пауза"}>
<span>
<IconButton
size="small"
disabled={busy}
aria-label={info.paused ? "Продолжить" : "Пауза"}
onClick={() =>
info.paused ? onResume(torrent) : onPause(torrent)
}
>
<span className="material-symbols-rounded">
{info.paused ? "play_arrow" : "pause"}
</span>
</IconButton>
</span>
</Tooltip>
<Tooltip title="Удалить">
<span>
<IconButton
size="small"
disabled={busy}
aria-label="Удалить"
onClick={() => onDelete(torrent)}
>
<span className="material-symbols-rounded">delete</span>
</IconButton>
</span>
</Tooltip>
</div>
</article>
);
}
+42
View File
@@ -11,6 +11,7 @@
import { Route as rootRouteImport } from './routes/__root'
import { Route as IndexRouteImport } from './routes/index'
import { Route as ApiRouteImport } from './routes/_api'
import { Route as ApiDownloadsRouteImport } from './routes/_api/downloads'
import { Route as ApiLoginRouteImport } from './routes/_api/login'
import { Route as ApiRemoteRouteImport } from './routes/_api/remote'
import { Route as ApiSettingsRouteImport } from './routes/_api/settings'
@@ -26,6 +27,7 @@ import { Route as ApiPlayerAudioRouteImport } from './routes/_api/player/audio'
import { Route as ApiPlayerPhotosRouteImport } from './routes/_api/player/photos'
import { Route as ApiSearchIndexRouteImport } from './routes/_api/search/index'
import { Route as ApiSettingsAboutRouteImport } from './routes/_api/settings/about'
import { Route as ApiSettingsDownloadsRouteImport } from './routes/_api/settings/downloads'
import { Route as ApiSettingsPreferencesRouteImport } from './routes/_api/settings/preferences'
import { Route as SetupServerAddRouteImport } from './routes/setup/server.add'
import { Route as SetupServerErrorRouteImport } from './routes/setup/server.error'
@@ -45,6 +47,11 @@ const ApiRoute = ApiRouteImport.update({
id: '/_api',
getParentRoute: () => rootRouteImport,
} as any)
const ApiDownloadsRoute = ApiDownloadsRouteImport.update({
id: '/downloads',
path: '/downloads',
getParentRoute: () => ApiRoute,
} as any)
const ApiLoginRoute = ApiLoginRouteImport.update({
id: '/login',
path: '/login',
@@ -120,6 +127,11 @@ const ApiSettingsAboutRoute = ApiSettingsAboutRouteImport.update({
path: '/about',
getParentRoute: () => ApiSettingsRoute,
} as any)
const ApiSettingsDownloadsRoute = ApiSettingsDownloadsRouteImport.update({
id: '/downloads',
path: '/downloads',
getParentRoute: () => ApiSettingsRoute,
} as any)
const ApiSettingsPreferencesRoute = ApiSettingsPreferencesRouteImport.update({
id: '/preferences',
path: '/preferences',
@@ -169,6 +181,7 @@ const ApiSettingsChangeServerIndexRoute =
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
'/downloads': typeof ApiDownloadsRoute
'/login': typeof ApiLoginRouteWithChildren
'/remote': typeof ApiRemoteRoute
'/settings': typeof ApiSettingsRouteWithChildren
@@ -180,6 +193,7 @@ export interface FileRoutesByFullPath {
'/player/audio': typeof ApiPlayerAudioRoute
'/player/photos': typeof ApiPlayerPhotosRoute
'/settings/about': typeof ApiSettingsAboutRoute
'/settings/downloads': typeof ApiSettingsDownloadsRoute
'/settings/preferences': typeof ApiSettingsPreferencesRoute
'/setup/server/add': typeof SetupServerAddRoute
'/setup/server/error': typeof SetupServerErrorRoute
@@ -196,6 +210,7 @@ export interface FileRoutesByFullPath {
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
'/downloads': typeof ApiDownloadsRoute
'/login': typeof ApiLoginRouteWithChildren
'/remote': typeof ApiRemoteRoute
'/settings': typeof ApiSettingsRouteWithChildren
@@ -207,6 +222,7 @@ export interface FileRoutesByTo {
'/player/audio': typeof ApiPlayerAudioRoute
'/player/photos': typeof ApiPlayerPhotosRoute
'/settings/about': typeof ApiSettingsAboutRoute
'/settings/downloads': typeof ApiSettingsDownloadsRoute
'/settings/preferences': typeof ApiSettingsPreferencesRoute
'/setup/server/add': typeof SetupServerAddRoute
'/setup/server/error': typeof SetupServerErrorRoute
@@ -225,6 +241,7 @@ export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
'/_api': typeof ApiRouteWithChildren
'/_api/downloads': typeof ApiDownloadsRoute
'/_api/login': typeof ApiLoginRouteWithChildren
'/_api/remote': typeof ApiRemoteRoute
'/_api/settings': typeof ApiSettingsRouteWithChildren
@@ -236,6 +253,7 @@ export interface FileRoutesById {
'/_api/player/audio': typeof ApiPlayerAudioRoute
'/_api/player/photos': typeof ApiPlayerPhotosRoute
'/_api/settings/about': typeof ApiSettingsAboutRoute
'/_api/settings/downloads': typeof ApiSettingsDownloadsRoute
'/_api/settings/preferences': typeof ApiSettingsPreferencesRoute
'/setup/server/add': typeof SetupServerAddRoute
'/setup/server/error': typeof SetupServerErrorRoute
@@ -254,6 +272,7 @@ export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths:
| '/'
| '/downloads'
| '/login'
| '/remote'
| '/settings'
@@ -265,6 +284,7 @@ export interface FileRouteTypes {
| '/player/audio'
| '/player/photos'
| '/settings/about'
| '/settings/downloads'
| '/settings/preferences'
| '/setup/server/add'
| '/setup/server/error'
@@ -281,6 +301,7 @@ export interface FileRouteTypes {
fileRoutesByTo: FileRoutesByTo
to:
| '/'
| '/downloads'
| '/login'
| '/remote'
| '/settings'
@@ -292,6 +313,7 @@ export interface FileRouteTypes {
| '/player/audio'
| '/player/photos'
| '/settings/about'
| '/settings/downloads'
| '/settings/preferences'
| '/setup/server/add'
| '/setup/server/error'
@@ -309,6 +331,7 @@ export interface FileRouteTypes {
| '__root__'
| '/'
| '/_api'
| '/_api/downloads'
| '/_api/login'
| '/_api/remote'
| '/_api/settings'
@@ -320,6 +343,7 @@ export interface FileRouteTypes {
| '/_api/player/audio'
| '/_api/player/photos'
| '/_api/settings/about'
| '/_api/settings/downloads'
| '/_api/settings/preferences'
| '/setup/server/add'
| '/setup/server/error'
@@ -360,6 +384,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ApiRouteImport
parentRoute: typeof rootRouteImport
}
'/_api/downloads': {
id: '/_api/downloads'
path: '/downloads'
fullPath: '/downloads'
preLoaderRoute: typeof ApiDownloadsRouteImport
parentRoute: typeof ApiRoute
}
'/_api/login': {
id: '/_api/login'
path: '/login'
@@ -465,6 +496,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ApiSettingsAboutRouteImport
parentRoute: typeof ApiSettingsRoute
}
'/_api/settings/downloads': {
id: '/_api/settings/downloads'
path: '/downloads'
fullPath: '/settings/downloads'
preLoaderRoute: typeof ApiSettingsDownloadsRouteImport
parentRoute: typeof ApiSettingsRoute
}
'/_api/settings/preferences': {
id: '/_api/settings/preferences'
path: '/preferences'
@@ -549,12 +587,14 @@ const ApiLoginRouteWithChildren = ApiLoginRoute._addFileChildren(
interface ApiSettingsRouteChildren {
ApiSettingsAboutRoute: typeof ApiSettingsAboutRoute
ApiSettingsDownloadsRoute: typeof ApiSettingsDownloadsRoute
ApiSettingsPreferencesRoute: typeof ApiSettingsPreferencesRoute
ApiSettingsChangeServerIndexRoute: typeof ApiSettingsChangeServerIndexRoute
}
const ApiSettingsRouteChildren: ApiSettingsRouteChildren = {
ApiSettingsAboutRoute: ApiSettingsAboutRoute,
ApiSettingsDownloadsRoute: ApiSettingsDownloadsRoute,
ApiSettingsPreferencesRoute: ApiSettingsPreferencesRoute,
ApiSettingsChangeServerIndexRoute: ApiSettingsChangeServerIndexRoute,
}
@@ -564,6 +604,7 @@ const ApiSettingsRouteWithChildren = ApiSettingsRoute._addFileChildren(
)
interface ApiRouteChildren {
ApiDownloadsRoute: typeof ApiDownloadsRoute
ApiLoginRoute: typeof ApiLoginRouteWithChildren
ApiRemoteRoute: typeof ApiRemoteRoute
ApiSettingsRoute: typeof ApiSettingsRouteWithChildren
@@ -581,6 +622,7 @@ interface ApiRouteChildren {
}
const ApiRouteChildren: ApiRouteChildren = {
ApiDownloadsRoute: ApiDownloadsRoute,
ApiLoginRoute: ApiLoginRouteWithChildren,
ApiRemoteRoute: ApiRemoteRoute,
ApiSettingsRoute: ApiSettingsRouteWithChildren,
+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>
);
}
+70
View File
@@ -0,0 +1,70 @@
import { invoke } from "@tauri-apps/api/core";
import type {
QbAddRequest,
QbAddResult,
QbCategory,
QbConnectionInfo,
QbError,
QbSettings,
QbSnapshot,
} from "./types";
export const qbGetSettings = () => invoke<QbSettings>("qb_get_settings");
export const qbSaveSettings = (settings: QbSettings, secret?: string) =>
invoke<QbSettings>("qb_save_settings", {
settings,
secret: secret?.trim() ? secret : null,
});
export const qbForgetSecret = () => invoke<QbSettings>("qb_forget_secret");
export const qbTestConnection = (settings: QbSettings, secret?: string) =>
invoke<QbConnectionInfo>("qb_test_connection", {
settings,
secret: secret?.trim() ? secret : null,
});
export const qbCategories = () => invoke<QbCategory[]>("qb_categories");
export const qbAddTorrent = (request: QbAddRequest) =>
invoke<QbAddResult>("qb_add_torrent", { request });
export const qbPoll = () => invoke<QbSnapshot>("qb_poll");
export const qbPause = (hashes: string[]) =>
invoke<void>("qb_pause", { hashes });
export const qbResume = (hashes: string[]) =>
invoke<void>("qb_resume", { hashes });
export const qbDelete = (hashes: string[], deleteFiles: boolean) =>
invoke<void>("qb_delete", { hashes, deleteFiles });
export const qbSetCategory = (hashes: string[], category: string) =>
invoke<void>("qb_set_category", { hashes, category });
/** Normalise an unknown `invoke` rejection into the shape the UI renders. */
export const toQbError = (error: unknown): QbError => {
if (
typeof error === "object" &&
error !== null &&
"message" in error &&
typeof (error as { message?: unknown }).message === "string"
) {
const value = error as Partial<QbError>;
return {
kind: value.kind ?? "http",
message: value.message ?? "Неизвестная ошибка qBittorrent",
status: value.status ?? null,
};
}
return {
kind: "http",
message:
typeof error === "string"
? error
: "Не удалось выполнить запрос к qBittorrent",
status: null,
};
};
+129
View File
@@ -0,0 +1,129 @@
const BYTE_UNITS = ["Б", "КБ", "МБ", "ГБ", "ТБ", "ПБ"];
export const formatBytes = (bytes: number) => {
if (!Number.isFinite(bytes) || bytes <= 0) return "0 Б";
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < BYTE_UNITS.length - 1) {
value /= 1024;
unit += 1;
}
const digits = value >= 100 || unit === 0 ? 0 : 1;
return `${value.toFixed(digits).replace(".", ",")} ${BYTE_UNITS[unit]}`;
};
export const formatSpeed = (bytesPerSecond: number) =>
`${formatBytes(bytesPerSecond)}/с`;
export const formatEta = (seconds: number) => {
if (!Number.isFinite(seconds) || seconds < 0 || seconds >= 8_640_000) {
return "∞";
}
if (seconds < 60) return `${Math.max(1, Math.round(seconds))} с`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes} мин`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
return rest > 0 ? `${hours} ч ${rest} мин` : `${hours} ч`;
};
export const formatPercent = (progress: number) =>
`${Math.min(100, Math.max(0, Math.round(progress * 100)))}%`;
export type TorrentTone =
| "downloading"
| "seeding"
| "paused"
| "error"
| "neutral";
export type TorrentStateInfo = {
label: string;
tone: TorrentTone;
/** The download has finished, regardless of seeding/paused state. */
done: boolean;
/** The torrent is stopped by the user. */
paused: boolean;
error: boolean;
};
const state = (
label: string,
tone: TorrentTone,
done = false,
paused = false,
error = false,
): TorrentStateInfo => ({ label, tone, done, paused, error });
export const getTorrentState = (value: string): TorrentStateInfo => {
switch (value) {
case "metaDL":
case "forcedMetaDL":
return state("Метаданные", "downloading");
case "downloading":
case "forcedDL":
return state("Скачивается", "downloading");
case "stalledDL":
return state("Нет пиров", "downloading");
case "queuedDL":
return state("В очереди", "downloading");
case "checkingDL":
return state("Проверка", "downloading");
case "allocating":
return state("Выделение места", "downloading");
case "moving":
return state("Перемещение", "downloading");
case "checkingResumeData":
return state("Проверка данных", "downloading");
case "pausedDL":
case "stoppedDL":
return state("Пауза", "paused", false, true);
case "uploading":
case "forcedUP":
return state("Раздаётся", "seeding", true);
case "stalledUP":
return state("Раздаётся", "seeding", true);
case "queuedUP":
return state("Завершено", "seeding", true);
case "checkingUP":
return state("Проверка", "seeding", true);
case "pausedUP":
case "stoppedUP":
return state("Завершено", "seeding", true, true);
case "error":
return state("Ошибка", "error", false, false, true);
case "missingFiles":
return state("Файлы не найдены", "error", false, false, true);
default:
return state("Неизвестно", "neutral");
}
};
export type TorrentFilter = "all" | "downloading" | "completed" | "error";
export const matchesFilter = (
torrent: { progress: number; state: string },
filter: TorrentFilter,
) => {
const info = getTorrentState(torrent.state);
if (filter === "all") return true;
if (filter === "downloading") return !info.done && !info.error;
if (filter === "completed") return info.done;
return info.error;
};
export const compareTorrents = (
left: { progress: number; state: string; addedOn: number },
right: { progress: number; state: string; addedOn: number },
) => {
const leftInfo = getTorrentState(left.state);
const rightInfo = getTorrentState(right.state);
const rank = (info: TorrentStateInfo) => {
if (info.error) return 0;
if (!info.done) return 1;
if (info.paused) return 3;
return 2;
};
const diff = rank(leftInfo) - rank(rightInfo);
return diff !== 0 ? diff : right.addedOn - left.addedOn;
};
+38
View File
@@ -0,0 +1,38 @@
import { queryOptions, useQuery } from "@tanstack/react-query";
import { qbCategories, qbGetSettings, qbPoll } from "./api";
import type { QbSettings } from "./types";
export const qbSettingsQueryOptions = queryOptions({
queryKey: ["qbittorrent", "settings"],
queryFn: qbGetSettings,
staleTime: Number.POSITIVE_INFINITY,
retry: false,
networkMode: "always",
});
export const useQbSettings = () => useQuery(qbSettingsQueryOptions);
export const qbCategoriesQueryOptions = (enabled: boolean) =>
queryOptions({
queryKey: ["qbittorrent", "categories"],
queryFn: qbCategories,
enabled,
staleTime: 60_000,
retry: false,
networkMode: "always",
});
const pollInterval = (settings?: QbSettings) =>
Math.max(1000, settings?.pollIntervalMs || 2000);
export const qbSnapshotQueryOptions = (settings?: QbSettings) =>
queryOptions({
queryKey: ["qbittorrent", "snapshot"],
queryFn: qbPoll,
enabled: Boolean(settings?.baseUrl && settings.hasSecret),
refetchInterval: () =>
document.visibilityState === "visible" ? pollInterval(settings) : false,
refetchIntervalInBackground: false,
retry: 1,
networkMode: "always",
});
+4
View File
@@ -0,0 +1,4 @@
export * from "./api";
export * from "./format";
export * from "./hooks";
export type * from "./types";
+101
View File
@@ -0,0 +1,101 @@
export type QbSettings = {
baseUrl: string;
username: string;
useApiKey: boolean;
rememberSecret: boolean;
defaultCategory: string;
autoTmm: boolean;
addPaused: boolean;
allowInvalidCerts: boolean;
refreshJellyfin: boolean;
notifyOnComplete: boolean;
pollIntervalMs: number;
secretSaved: boolean;
hasSecret: boolean;
};
export type QbCategory = {
name: string;
savePath: string;
downloadPath?: string | null;
};
export type QbTorrent = {
hash: string;
name: string;
category: string;
size: number;
completed: number;
downloaded: number;
progress: number;
dlspeed: number;
upspeed: number;
eta: number;
state: string;
savePath: string;
contentPath: string;
addedOn: number;
completionOn: number;
ratio: number;
numSeeds: number;
numLeeches: number;
error?: string | null;
tags: string;
seedingTime: number;
timeActive: number;
amountLeft: number;
tracker: string;
};
export type QbServerState = {
dlInfoSpeed: number;
upInfoSpeed: number;
dlInfoData: number;
upInfoData: number;
freeSpaceOnDisk: number;
connectionStatus: string;
queueing: boolean;
dhtNodes: number;
};
export type QbSnapshot = {
torrents: QbTorrent[];
serverState: QbServerState;
synced: boolean;
};
export type QbAddResult = {
status: "added" | "pending" | "duplicate" | "invalid";
addedHashes: string[];
message?: string | null;
};
export type QbConnectionInfo = {
appVersion: string;
apiVersion: string;
defaultSavePath: string;
};
export type QbAddRequest = {
magnet?: string | null;
filePath?: string | null;
category?: string | null;
paused?: boolean | null;
autoTmm?: boolean | null;
};
export type QbError = {
kind:
| "unreachable"
| "auth"
| "banned"
| "tls"
| "duplicate"
| "torrent"
| "http"
| "config"
| "internal"
| string;
message: string;
status?: number | null;
};