Rename folder "modules" to "features"

This commit is contained in:
schroda
2025-08-15 22:02:58 +02:00
parent 7e6ced1d09
commit 1b4bf22542
415 changed files with 1859 additions and 1852 deletions

View File

@@ -0,0 +1,20 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
export const DOWNLOAD_AHEAD = {
min: 2,
max: 10,
default: 2,
step: 1,
};
export const DOWNLOAD_CONVERSION_COMPRESSION = {
min: 0,
max: 1,
step: 0.01,
};

View File

@@ -0,0 +1,14 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
export type MetadataDownloadSettings = {
deleteChaptersManuallyMarkedRead: boolean;
deleteChaptersWhileReading: number;
deleteChaptersWithBookmark: boolean;
downloadAheadLimit: number;
};

View File

@@ -0,0 +1,73 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useTranslation } from 'react-i18next';
import {
SelectSetting,
SelectSettingValue,
SelectSettingValueDisplayInfo,
} from '@/features/core/components/settings/SelectSetting.tsx';
const CHAPTERS_TO_DELETE = [0, 1, 2, 3, 4, 5] as const;
const CHAPTERS_TO_DELETE_TO_TRANSLATION_KEY: {
[flavor in (typeof CHAPTERS_TO_DELETE)[number]]: SelectSettingValueDisplayInfo;
} = {
0: {
text: 'global.label.disabled',
},
1: {
text: 'download.settings.delete_chapters.while_reading.option.label.first',
},
2: {
text: 'download.settings.delete_chapters.while_reading.option.label.second',
},
3: {
text: 'download.settings.delete_chapters.while_reading.option.label.third',
},
4: {
text: 'download.settings.delete_chapters.while_reading.option.label.fourth',
},
5: {
text: 'download.settings.delete_chapters.while_reading.option.label.fifth',
},
};
const CHAPTERS_TO_DELETE_SELECT_VALUES: SelectSettingValue<(typeof CHAPTERS_TO_DELETE)[number]>[] =
CHAPTERS_TO_DELETE.map((chapterToDelete) => [
chapterToDelete,
CHAPTERS_TO_DELETE_TO_TRANSLATION_KEY[chapterToDelete],
]);
const getNormalizedChapterToDelete = (chapterToDelete: number | boolean) => {
const isMigrationVersion0 = typeof chapterToDelete === 'boolean';
if (isMigrationVersion0) {
return Number(chapterToDelete);
}
return chapterToDelete;
};
export const DeleteChaptersWhileReadingSetting = ({
chapterToDelete,
handleChange,
}: {
chapterToDelete: number;
handleChange: (chapterToDelete: number) => void;
}) => {
const { t } = useTranslation();
const normalizedChapterToDelete = getNormalizedChapterToDelete(chapterToDelete);
return (
<SelectSetting
settingName={t('download.settings.delete_chapters.while_reading.label.title')}
value={normalizedChapterToDelete}
values={CHAPTERS_TO_DELETE_SELECT_VALUES}
handleChange={handleChange}
/>
);
};

View File

@@ -0,0 +1,76 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useTranslation } from 'react-i18next';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import Switch from '@mui/material/Switch';
import { NumberSetting } from '@/features/core/components/settings/NumberSetting.tsx';
import { getPersistedServerSetting, usePersistedValue } from '@/features/core/hooks/usePersistedValue.tsx';
import { updateMetadataServerSettings } from '@/features/settings/services/ServerSettingsMetadata.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { MetadataDownloadSettings } from '@/features/downloads/Downloads.types.ts';
import { MetadataServerSettings } from '@/features/settings/Settings.types.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { DOWNLOAD_AHEAD } from '@/features/downloads/Downloads.constants.ts';
export const DownloadAheadSetting = ({
downloadAheadLimit,
}: {
downloadAheadLimit: MetadataServerSettings['downloadAheadLimit'];
}) => {
const { t } = useTranslation();
const shouldDownloadAhead = !!downloadAheadLimit;
const [currentDownloadAheadLimit, persistDownloadAheadLimit] = usePersistedValue(
'lastDownloadAheadLimit',
DOWNLOAD_AHEAD.default,
downloadAheadLimit,
getPersistedServerSetting,
);
const updateSetting = (value: MetadataDownloadSettings['downloadAheadLimit']) => {
persistDownloadAheadLimit(value === 0 ? currentDownloadAheadLimit : value);
updateMetadataServerSettings('downloadAheadLimit', value).catch((e) =>
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)),
);
};
const setDoAutoUpdates = (enable: boolean) => {
const globalUpdateInterval = enable ? currentDownloadAheadLimit : 0;
updateSetting(globalUpdateInterval);
};
return (
<List>
<ListItem>
<ListItemText primary={t('download.settings.download_ahead.label.while_reading')} />
<Switch edge="end" checked={shouldDownloadAhead} onChange={(e) => setDoAutoUpdates(e.target.checked)} />
</ListItem>
<NumberSetting
settingTitle={t('download.settings.download_ahead.label.unread_chapters_to_download')}
settingValue={t('download.settings.download_ahead.label.value', {
chapters: currentDownloadAheadLimit,
count: currentDownloadAheadLimit,
})}
value={currentDownloadAheadLimit}
minValue={DOWNLOAD_AHEAD.min}
maxValue={DOWNLOAD_AHEAD.max}
defaultValue={DOWNLOAD_AHEAD.default}
stepSize={DOWNLOAD_AHEAD.step}
showSlider
dialogDescription={t('download.settings.download_ahead.label.description')}
dialogDisclaimer={t('download.settings.download_ahead.label.disclaimer')}
valueUnit={t('chapter.title_one')}
handleUpdate={updateSetting}
disabled={!shouldDownloadAhead}
/>
</List>
);
};

View File

@@ -0,0 +1,351 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useTranslation } from 'react-i18next';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemText from '@mui/material/ListItemText';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import { useState } from 'react';
import TextField from '@mui/material/TextField';
import Stack from '@mui/material/Stack';
import DeleteIcon from '@mui/icons-material/Delete';
import IconButton from '@mui/material/IconButton';
import InputAdornment from '@mui/material/InputAdornment';
import Button from '@mui/material/Button';
import DialogActions from '@mui/material/DialogActions';
import DialogContentText from '@mui/material/DialogContentText';
import { SettingsDownloadConversion } from '@/lib/graphql/generated/graphql.ts';
import { DOWNLOAD_CONVERSION_COMPRESSION } from '@/features/downloads/Downloads.constants.ts';
import { CustomTooltip } from '@/features/core/components/CustomTooltip.tsx';
import { TypographyMaxLines } from '@/features/core/components/texts/TypographyMaxLines.tsx';
const DEFAULT_MIME_TYPE = 'default';
const MIME_TYPE_PREFIX = 'image/';
const DEFAULT_FOCUS_INDEX = -1;
const normalizeMimeType = (mimeType: string): string => mimeType.replace(MIME_TYPE_PREFIX, '');
const isDefaultMimeType = (mimeType: string): boolean =>
normalizeMimeType(mimeType.toLowerCase().trim()) === DEFAULT_MIME_TYPE;
const isDuplicateConversion = (mimeType: string, index: number, conversions: SettingsDownloadConversion[]): boolean =>
conversions.slice(0, index).some((conversion) => conversion.mimeType === mimeType);
const isValidCompressionLevel = (compression: number | null | undefined): boolean =>
compression == null ||
(compression >= DOWNLOAD_CONVERSION_COMPRESSION.min && compression <= DOWNLOAD_CONVERSION_COMPRESSION.max);
const containsInvalidConversion = (conversions: SettingsDownloadConversion[]): boolean =>
conversions.some(
({ mimeType, compressionLevel }, index) =>
!isValidCompressionLevel(compressionLevel) || isDuplicateConversion(mimeType, index, conversions),
);
const normalizeConversions = (conversions: SettingsDownloadConversion[]): SettingsDownloadConversion[] =>
conversions.map((conversion) => ({
...conversion,
mimeType: normalizeMimeType(conversion.mimeType),
target: normalizeMimeType(conversion.target),
}));
const toValidServerConversions = (conversions: SettingsDownloadConversion[]): SettingsDownloadConversion[] =>
conversions
.filter(({ mimeType, target }) => !!mimeType && !!target)
.map((conversion) => ({
...conversion,
mimeType: `${MIME_TYPE_PREFIX}${conversion.mimeType}`,
target: `${MIME_TYPE_PREFIX}${conversion.target}`,
}));
const maybeAddDefault = (conversions: SettingsDownloadConversion[]) => {
const isDefaultDefined = conversions.some(({ mimeType }) => isDefaultMimeType(mimeType));
return [
...(isDefaultDefined
? []
: [
{
mimeType: DEFAULT_MIME_TYPE,
target: '',
compressionLevel: null,
},
]),
...conversions,
];
};
const didUpdateConversions = (
conversions: SettingsDownloadConversion[],
tmpConversions: SettingsDownloadConversion[],
): boolean => {
if (conversions.length !== tmpConversions.length) {
return true;
}
return conversions.some(({ mimeType, target, compressionLevel }, index) => {
const tmpConversion = tmpConversions[index];
return (
normalizeMimeType(mimeType) !== tmpConversion.mimeType ||
normalizeMimeType(target) !== tmpConversion.target ||
compressionLevel !== tmpConversion.compressionLevel
);
});
};
const MimeTypeTextField = ({
shouldAutoFocus,
isDefault,
isDuplicate,
label,
value,
onUpdate,
}: {
shouldAutoFocus: boolean;
isDefault: boolean;
isDuplicate: boolean;
label: string;
value: string;
onUpdate: (value: string) => void;
}) => {
const { t } = useTranslation();
return (
<TextField
sx={{ maxWidth: 150 }}
autoFocus={shouldAutoFocus}
label={label}
value={value}
disabled={isDefault}
error={isDuplicate}
helperText={isDuplicate && t('global.error.label.invalid_input')}
slotProps={{
input: {
startAdornment: <InputAdornment position="start">{MIME_TYPE_PREFIX}</InputAdornment>,
},
}}
onChange={(e) => onUpdate(e.target.value.trim())}
/>
);
};
const Conversion = ({
shouldAutoFocusMimeTypeTextField,
conversion: { mimeType, target, compressionLevel },
setFocusMimeTypeTextField,
onChange,
isDuplicate,
}: {
shouldAutoFocusMimeTypeTextField: boolean;
conversion: SettingsDownloadConversion;
setFocusMimeTypeTextField: (focus: boolean) => void;
onChange: (newConversion: SettingsDownloadConversion | null) => void;
isDuplicate: boolean;
}) => {
const { t } = useTranslation();
const isCompressionLevelValid = isValidCompressionLevel(compressionLevel);
const isDefault = isDefaultMimeType(mimeType) && !isDuplicate;
const isDisabled = isDefault && !target && compressionLevel == null;
return (
<Stack
sx={{
gap: 1,
flexDirection: 'row',
flexWrap: 'nowrap',
alignItems: 'center',
pt: 1,
}}
>
<Stack
sx={{
gap: 1,
flexDirection: 'row',
alignItems: 'baseline',
flexWrap: 'wrap',
}}
>
<MimeTypeTextField
shouldAutoFocus={shouldAutoFocusMimeTypeTextField}
isDefault={isDefault}
isDuplicate={isDuplicate}
label={t('download.settings.conversion.mime_type')}
value={mimeType}
onUpdate={(value) => {
setFocusMimeTypeTextField(true);
onChange({
mimeType: value,
target,
compressionLevel,
});
}}
/>
<TypographyMaxLines sx={{ mx: 1 }}></TypographyMaxLines>
<MimeTypeTextField
shouldAutoFocus={false}
isDefault={false}
isDuplicate={false}
label={t('download.settings.conversion.target')}
value={target}
onUpdate={(value) =>
onChange({
mimeType,
target: value,
compressionLevel,
})
}
/>
<TextField
label={t('download.settings.conversion.compression_level')}
value={compressionLevel ?? ''}
type="number"
error={!isCompressionLevelValid}
helperText={!isCompressionLevelValid ? t('global.error.label.invalid_input') : ''}
slotProps={{
input: {
inputProps: DOWNLOAD_CONVERSION_COMPRESSION,
},
}}
onChange={(e) => {
onChange({
mimeType,
target,
compressionLevel: e.target.value ? Number(e.target.value) : undefined,
});
}}
/>
</Stack>
<CustomTooltip disabled={isDisabled} title={t('chapter.action.download.delete.label.action')}>
<IconButton
disabled={isDisabled}
onClick={() => {
setFocusMimeTypeTextField(false);
onChange(null);
}}
>
<DeleteIcon />
</IconButton>
</CustomTooltip>
</Stack>
);
};
export const DownloadConversionSetting = ({
conversions,
updateSetting,
}: {
conversions: SettingsDownloadConversion[];
updateSetting: (conversions: SettingsDownloadConversion[]) => Promise<void>;
}) => {
const { t } = useTranslation();
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [tmpConversions, setTmpConversions] = useState(normalizeConversions(maybeAddDefault(conversions)));
const [focusedMimeTypeTextFieldIndex, setFocusedMimeTypeTextFieldIndex] = useState(DEFAULT_FOCUS_INDEX);
const hasInvalidConversion = containsInvalidConversion(tmpConversions);
const hasChanged = didUpdateConversions(normalizeConversions(maybeAddDefault(conversions)), tmpConversions);
const onClose = (newConversions: SettingsDownloadConversion[] = conversions) => {
setTmpConversions(normalizeConversions(maybeAddDefault(newConversions)));
setIsDialogOpen(false);
};
const onCancel = () => {
onClose(conversions);
};
return (
<>
<ListItemButton disabled={false} onClick={() => setIsDialogOpen(true)}>
<ListItemText
primary={t('download.settings.conversion.title')}
secondary={conversions
.map((conversion) => `${conversion.mimeType}${conversion.target}`)
.join('; ')}
secondaryTypographyProps={{ style: { display: 'flex', flexDirection: 'column' } }}
/>
</ListItemButton>
<Dialog open={isDialogOpen} onClose={onCancel}>
<DialogTitle>{t('download.settings.conversion.title')}</DialogTitle>
<DialogContent>
<DialogContentText sx={{ mb: 2, whiteSpace: 'pre-line' }}>
{t('download.settings.conversion.description', { value: 'none' })}
</DialogContentText>
<Stack sx={{ flexDirection: 'column', gap: 3 }}>
{tmpConversions.map((conversion, index) => {
const { mimeType } = conversion;
const isDuplicate = isDuplicateConversion(mimeType, index, tmpConversions);
const shouldAutoFocusMimeTypeTextField = index === focusedMimeTypeTextFieldIndex;
return (
<Conversion
// eslint-disable-next-line react/no-array-index-key
key={`${mimeType}-${index}`}
conversion={conversion}
isDuplicate={isDuplicate}
setFocusMimeTypeTextField={(focus) =>
setFocusedMimeTypeTextFieldIndex(focus ? index : DEFAULT_FOCUS_INDEX)
}
shouldAutoFocusMimeTypeTextField={shouldAutoFocusMimeTypeTextField}
onChange={(newConversion) => {
setTmpConversions((prev) =>
maybeAddDefault(
prev.toSpliced(index, 1, ...(newConversion ? [newConversion] : [])),
),
);
}}
/>
);
})}
</Stack>
</DialogContent>
<DialogActions>
<Stack
direction="row"
sx={{
justifyContent: 'space-between',
width: '100%',
}}
>
<Button
variant="outlined"
onClick={() => {
setTmpConversions((prev) => [
...prev,
{ mimeType: '', target: '', compressionLevel: null },
]);
}}
>
{t('global.button.add')}
</Button>
<Stack direction="row">
<Button onClick={onCancel}>{t('global.button.cancel')}</Button>
<Button
disabled={hasInvalidConversion || !hasChanged}
onClick={() =>
updateSetting(toValidServerConversions(tmpConversions)).then(() =>
onClose(toValidServerConversions(tmpConversions)),
)
}
>
{t('global.button.ok')}
</Button>
</Stack>
</Stack>
</DialogActions>
</Dialog>
</>
);
};

View File

@@ -0,0 +1,104 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import DeleteIcon from '@mui/icons-material/Delete';
import DragHandle from '@mui/icons-material/DragHandle';
import Card from '@mui/material/Card';
import CardActionArea from '@mui/material/CardActionArea';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import { memo, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { CustomTooltip } from '@/features/core/components/CustomTooltip.tsx';
import { ChapterDownloadRetryButton } from '@/features/chapter/components/buttons/ChapterDownloadRetryButton.tsx';
import { DownloadStateIndicator } from '@/features/core/components/downloads/DownloadStateIndicator.tsx';
import { ChapterCardMetadata } from '@/features/chapter/components/cards/ChapterCardMetadata.tsx';
import { MUIUtil } from '@/lib/mui/MUI.util.ts';
import { ListCardContent } from '@/features/core/components/lists/cards/ListCardContent.tsx';
import { AppRoutes } from '@/features/core/AppRoute.constants.ts';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { DownloaderState } from '@/lib/graphql/generated/graphql.ts';
import { ChapterDownloadStatus, ChapterIdInfo } from '@/features/chapter/Chapter.types.ts';
import { MediaQuery } from '@/features/core/utils/MediaQuery.tsx';
export const DownloadQueueChapterCard = memo(
({ item, status }: { item: ChapterDownloadStatus; status: DownloaderState }) => {
const { t } = useTranslation();
const preventMobileContextMenu = MediaQuery.usePreventMobileContextMenu();
const handleDelete = useCallback(
async (chapter: ChapterIdInfo) => {
const isRunning = status === DownloaderState.Started;
try {
if (isRunning) {
// required to stop before deleting otherwise the download kept going. Server issue?
await requestManager.stopDownloads().response;
}
await Promise.all([
// remove from download queue
requestManager.removeChapterFromDownloadQueue(chapter.id).response,
// delete partial download, should be handle server side?
// bug: The folder and the last image downloaded are not deleted
requestManager.deleteDownloadedChapter(chapter.id).response,
]);
} catch (e) {
makeToast(t('download.queue.error.label.failed_to_remove'), 'error', getErrorMessage(e));
}
if (!isRunning) {
return;
}
requestManager
.startDownloads()
.response.catch(defaultPromiseErrorHandler('DownloadQueue::startDownloads'));
},
[status],
);
return (
<Box sx={{ p: 1, pb: 0 }}>
<Card>
<CardActionArea
component={Link}
to={AppRoutes.manga.path(item.manga.id)}
onContextMenu={preventMobileContextMenu}
sx={MediaQuery.preventMobileContextMenuSx()}
>
<ListCardContent>
<IconButton {...MUIUtil.preventRippleProp()} sx={{ pointerEvents: 'none' }}>
<DragHandle />
</IconButton>
<ChapterCardMetadata title={item.manga.title} secondaryText={item.chapter.name} />
<DownloadStateIndicator chapterId={item.chapter.id} />
<ChapterDownloadRetryButton chapterId={item.chapter.id} />
<CustomTooltip title={t('chapter.action.download.delete.label.action')}>
<IconButton
{...MUIUtil.preventRippleProp()}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
handleDelete(item.chapter);
}}
>
<DeleteIcon />
</IconButton>
</CustomTooltip>
</ListCardContent>
</CardActionArea>
</Card>
</Box>
);
},
);

View File

@@ -0,0 +1,184 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import PauseIcon from '@mui/icons-material/Pause';
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import React, { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import DeleteSweepIcon from '@mui/icons-material/DeleteSweep';
import { closestCenter, DndContext, DragEndEvent } from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { useWindowEvent } from '@mantine/hooks';
import { CustomTooltip } from '@/features/core/components/CustomTooltip.tsx';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { EmptyViewAbsoluteCentered } from '@/features/core/components/feedback/EmptyViewAbsoluteCentered.tsx';
import { LoadingPlaceholder } from '@/features/core/components/feedback/LoadingPlaceholder.tsx';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { DownloaderState } from '@/lib/graphql/generated/graphql.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { DndSortableItem } from '@/lib/dnd-kit/DndSortableItem.tsx';
import { DndKitUtil } from '@/lib/dnd-kit/DndKitUtil.ts';
import { DndOverlayItem } from '@/lib/dnd-kit/DndOverlayItem.tsx';
import { DownloadQueueChapterCard } from '@/features/downloads/components/DownloadQueueChapterCard.tsx';
import { useAppTitle } from '@/features/navigation-bar/hooks/useAppTitle.ts';
import { useAppAction } from '@/features/navigation-bar/hooks/useAppAction.ts';
import { ChapterDownloadStatus } from '@/features/chapter/Chapter.types.ts';
import { VirtuosoPersisted } from '@/lib/virtuoso/Component/VirtuosoPersisted.tsx';
export const DownloadQueue: React.FC = () => {
const { t } = useTranslation();
useAppTitle(t('download.title.queue'));
const [reorderDownload, { reset: revertReorder }] = requestManager.useReorderChapterInDownloadQueue();
const {
data: downloadStatusData,
loading: isLoading,
error,
refetch,
} = requestManager.useGetDownloadStatus({ notifyOnNetworkStatusChange: true });
const downloaderData = downloadStatusData?.downloadStatus;
const queue = downloaderData?.queue ?? [];
const status = downloaderData?.state ?? DownloaderState.Started;
const isQueueEmpty = !queue.length;
const dndItems = useMemo(() => queue.map((download) => download.chapter), [queue]);
const dndSensors = DndKitUtil.useSensorsForDevice();
const [dndActiveDownload, setDndActiveDownload] = useState<ChapterDownloadStatus | null>(null);
const clearQueue = async () => {
try {
await requestManager.clearDownloads().response;
} catch (e) {
makeToast(t('download.queue.error.label.failed_delete_all'), 'error', getErrorMessage(e));
}
};
const toggleQueueStatus = () => {
if (status === DownloaderState.Stopped) {
requestManager.startDownloads();
} else {
requestManager.stopDownloads();
}
};
const categoryReorder = (list: ChapterDownloadStatus[], from: number, to: number) => {
if (from === to) {
return;
}
reorderDownload({ variables: { input: { chapterId: list[from].chapter.id, to } } }).catch(() => {
revertReorder();
});
};
const onDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
setDndActiveDownload(null);
if (!over || active.id === over.id) {
return;
}
const oldIndex = queue.findIndex((download) => download.chapter.id === active.id);
const newIndex = queue.findIndex((download) => download.chapter.id === over.id);
categoryReorder(queue, oldIndex, newIndex);
};
useAppAction(
<>
<CustomTooltip title={t('download.queue.label.delete_all')}>
<IconButton onClick={clearQueue} color="inherit">
<DeleteSweepIcon />
</IconButton>
</CustomTooltip>
<CustomTooltip
title={t(status === DownloaderState.Started ? 'global.button.start' : 'global.button.stop')}
disabled={isQueueEmpty}
>
<IconButton onClick={toggleQueueStatus} disabled={isQueueEmpty} color="inherit">
{status === DownloaderState.Stopped ? <PlayArrowIcon /> : <PauseIcon />}
</IconButton>
</CustomTooltip>
</>,
[status, isQueueEmpty],
);
// Virtuoso's resize observer can throw this error,
// which is caught by DnD and aborts dragging.
useWindowEvent('error', (e) => {
if (
e.message === 'ResizeObserver loop completed with undelivered notifications.' ||
e.message === 'ResizeObserver loop limit exceeded'
) {
e.stopImmediatePropagation();
}
});
if (isLoading) {
return <LoadingPlaceholder />;
}
if (error) {
return (
<EmptyViewAbsoluteCentered
message={t('global.error.label.failed_to_load_data')}
messageExtra={getErrorMessage(error)}
retry={() => refetch().catch(defaultPromiseErrorHandler('DownloadQueue::refetch'))}
/>
);
}
if (isQueueEmpty) {
return <EmptyViewAbsoluteCentered message={t('download.queue.label.no_downloads')} />;
}
return (
<Box sx={{ pb: 1 }}>
<DndContext
sensors={dndSensors}
collisionDetection={closestCenter}
onDragStart={(event) =>
setDndActiveDownload(queue.find((download) => download.chapter.id === event.active.id) ?? null)
}
onDragEnd={onDragEnd}
onDragCancel={() => setDndActiveDownload(null)}
onDragAbort={() => setDndActiveDownload(null)}
>
<SortableContext items={dndItems} strategy={verticalListSortingStrategy}>
<VirtuosoPersisted
persistKey="download-queue"
useWindowScroll
overscan={window.innerHeight * 0.5}
totalCount={queue.length}
computeItemKey={(index) => queue[index].chapter.id}
itemContent={(index) => (
<DndSortableItem
id={queue[index].chapter.id}
isDragging={queue[index].chapter.id === dndActiveDownload?.chapter.id}
>
<DownloadQueueChapterCard item={queue[index]} status={status} />
</DndSortableItem>
)}
/>
</SortableContext>
<DndOverlayItem isActive={!!dndActiveDownload}>
<DownloadQueueChapterCard item={dndActiveDownload!} status={status} />
</DndOverlayItem>
</DndContext>
</Box>
);
};

View File

@@ -0,0 +1,247 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useTranslation } from 'react-i18next';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import Switch from '@mui/material/Switch';
import ListSubheader from '@mui/material/ListSubheader';
import { TextSetting } from '@/features/core/components/settings/text/TextSetting.tsx';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { DownloadAheadSetting } from '@/features/downloads/components/DownloadAheadSetting.tsx';
import {
createUpdateMetadataServerSettings,
useMetadataServerSettings,
} from '@/features/settings/services/ServerSettingsMetadata.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { DeleteChaptersWhileReadingSetting } from '@/features/downloads/components/DeleteChaptersWhileReadingSetting.tsx';
import { CategoriesInclusionSetting } from '@/features/category/components/CategoriesInclusionSetting.tsx';
import { NumberSetting } from '@/features/core/components/settings/NumberSetting.tsx';
import { LoadingPlaceholder } from '@/features/core/components/feedback/LoadingPlaceholder.tsx';
import { EmptyViewAbsoluteCentered } from '@/features/core/components/feedback/EmptyViewAbsoluteCentered.tsx';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { GetCategoriesSettingsQuery, GetCategoriesSettingsQueryVariables } from '@/lib/graphql/generated/graphql.ts';
import { GET_CATEGORIES_SETTINGS } from '@/lib/graphql/queries/CategoryQuery.ts';
import { MetadataDownloadSettings } from '@/features/downloads/Downloads.types.ts';
import { ServerSettings } from '@/features/settings/Settings.types.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { useAppTitle } from '@/features/navigation-bar/hooks/useAppTitle.ts';
import { DownloadConversionSetting } from '@/features/downloads/components/DownloadConversionSetting.tsx';
type DownloadSettingsType = Pick<
ServerSettings,
| 'downloadAsCbz'
| 'downloadsPath'
| 'autoDownloadNewChapters'
| 'autoDownloadNewChaptersLimit'
| 'excludeEntryWithUnreadChapters'
| 'autoDownloadIgnoreReUploads'
| 'downloadConversions'
>;
const extractDownloadSettings = (settings: ServerSettings): DownloadSettingsType => ({
downloadAsCbz: settings.downloadAsCbz,
downloadsPath: settings.downloadsPath,
autoDownloadNewChapters: settings.autoDownloadNewChapters,
autoDownloadNewChaptersLimit: settings.autoDownloadNewChaptersLimit,
excludeEntryWithUnreadChapters: settings.excludeEntryWithUnreadChapters,
autoDownloadIgnoreReUploads: settings.autoDownloadIgnoreReUploads,
downloadConversions: settings.downloadConversions,
});
export const DownloadSettings = () => {
const { t } = useTranslation();
useAppTitle(t('download.title.download'));
const categories = requestManager.useGetCategories<GetCategoriesSettingsQuery, GetCategoriesSettingsQueryVariables>(
GET_CATEGORIES_SETTINGS,
);
const serverSettings = requestManager.useGetServerSettings({ notifyOnNetworkStatusChange: true });
const [mutateSettings] = requestManager.useUpdateServerSettings();
const {
settings: metadataSettings,
loading: areMetadataServerSettingsLoading,
request: { error: metadataServerSettingsError, refetch: refetchMetadataServerSettings },
} = useMetadataServerSettings();
const loading = serverSettings.loading || areMetadataServerSettingsLoading || categories.loading;
if (loading) {
return <LoadingPlaceholder />;
}
const error = serverSettings.error ?? metadataServerSettingsError ?? categories.error;
if (error) {
return (
<EmptyViewAbsoluteCentered
message={t('global.error.label.failed_to_load_data')}
messageExtra={getErrorMessage(error)}
retry={() => {
if (serverSettings.error) {
serverSettings
.refetch()
.catch(defaultPromiseErrorHandler('DownloadSettings::refetchServerSettings'));
}
if (metadataServerSettingsError) {
refetchMetadataServerSettings().catch(
defaultPromiseErrorHandler('refetchMetadataServerSettings::'),
);
}
if (categories.error) {
categories.refetch().catch(defaultPromiseErrorHandler('LibrarySettings::refetchCategories'));
}
}}
/>
);
}
const downloadSettings = extractDownloadSettings(serverSettings.data!.settings);
const updateSetting = <Setting extends keyof DownloadSettingsType>(
setting: Setting,
value: DownloadSettingsType[Setting],
): Promise<any> => {
const mutation = mutateSettings({ variables: { input: { settings: { [setting]: value } } } });
mutation.catch((e) => makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)));
return mutation;
};
const updateMetadataSetting = createUpdateMetadataServerSettings<keyof MetadataDownloadSettings>((e) =>
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)),
);
return (
<List sx={{ pt: 0 }}>
<TextSetting
settingName={t('download.settings.download_path.label.title')}
dialogDescription={t('download.settings.download_path.label.description')}
value={downloadSettings?.downloadsPath}
settingDescription={
downloadSettings?.downloadsPath.length ? downloadSettings.downloadsPath : t('global.label.default')
}
handleChange={(path) => updateSetting('downloadsPath', path)}
/>
<ListItem>
<ListItemText primary={t('download.settings.file_type.label.cbz')} />
<Switch
edge="end"
checked={!!downloadSettings?.downloadAsCbz}
onChange={(e) => updateSetting('downloadAsCbz', e.target.checked)}
/>
</ListItem>
<DownloadConversionSetting
conversions={downloadSettings?.downloadConversions}
updateSetting={(conversions) => updateSetting('downloadConversions', conversions)}
/>
<List
subheader={
<ListSubheader component="div" id="download-settings-auto-delete-downloads">
{t('download.settings.delete_chapters.title')}
</ListSubheader>
}
>
<ListItem>
<ListItemText primary={t('download.settings.delete_chapters.label.manually_marked_as_read')} />
<Switch
edge="end"
checked={metadataSettings.deleteChaptersManuallyMarkedRead}
onChange={(e) => updateMetadataSetting('deleteChaptersManuallyMarkedRead', e.target.checked)}
/>
</ListItem>
<DeleteChaptersWhileReadingSetting
chapterToDelete={metadataSettings.deleteChaptersWhileReading}
handleChange={(chapterToDelete) =>
updateMetadataSetting('deleteChaptersWhileReading', chapterToDelete)
}
/>
<ListItem>
<ListItemText primary={t('download.settings.delete_chapters.label.allow_deletion_of_bookmarked')} />
<Switch
edge="end"
checked={metadataSettings.deleteChaptersWithBookmark}
onChange={(e) => updateMetadataSetting('deleteChaptersWithBookmark', e.target.checked)}
/>
</ListItem>
</List>
<List
subheader={
<ListSubheader component="div" id="download-settings-auto-download">
{t('download.settings.auto_download.title')}
</ListSubheader>
}
>
<ListItem>
<ListItemText primary={t('download.settings.auto_download.label.new_chapters')} />
<Switch
edge="end"
checked={!!downloadSettings?.autoDownloadNewChapters}
onChange={(e) => updateSetting('autoDownloadNewChapters', e.target.checked)}
/>
</ListItem>
<NumberSetting
disabled={!downloadSettings?.autoDownloadNewChapters}
settingTitle={t('download.settings.auto_download.download_limit.label.title')}
dialogDescription={t('download.settings.auto_download.download_limit.label.description')}
value={downloadSettings?.autoDownloadNewChaptersLimit ?? 0}
settingValue={
!downloadSettings.autoDownloadNewChaptersLimit
? t('global.label.none')
: t('download.settings.download_ahead.label.value', {
chapters: downloadSettings.autoDownloadNewChaptersLimit,
count: downloadSettings.autoDownloadNewChaptersLimit,
})
}
defaultValue={0}
minValue={0}
maxValue={20}
showSlider
valueUnit={t('chapter.title_one')}
handleUpdate={(autoDownloadNewChaptersLimit) =>
updateSetting('autoDownloadNewChaptersLimit', autoDownloadNewChaptersLimit)
}
/>
<ListItem>
<ListItemText primary={t('download.settings.auto_download.label.ignore_with_unread_chapters')} />
<Switch
edge="end"
checked={!!downloadSettings?.excludeEntryWithUnreadChapters}
onChange={(e) => updateSetting('excludeEntryWithUnreadChapters', e.target.checked)}
disabled={!downloadSettings?.autoDownloadNewChapters}
/>
</ListItem>
<ListItem>
<ListItemText primary={t('download.settings.auto_download.label.ignore_re_uploads')} />
<Switch
edge="end"
checked={!!downloadSettings?.autoDownloadIgnoreReUploads}
onChange={(e) => updateSetting('autoDownloadIgnoreReUploads', e.target.checked)}
disabled={!downloadSettings?.autoDownloadNewChapters}
/>
</ListItem>
<CategoriesInclusionSetting
categories={categories.data!.categories.nodes}
includeField="includeInDownload"
dialogText={t('download.settings.auto_download.categories.label.include_in_download')}
/>
</List>
<List
subheader={
<ListSubheader component="div" id="download-settings-download-ahead">
{t('download.settings.download_ahead.title')}
</ListSubheader>
}
>
<DownloadAheadSetting downloadAheadLimit={metadataSettings.downloadAheadLimit} />
</List>
</List>
);
};