Use gql for "subscriptions"

This commit is contained in:
schroda
2023-10-04 22:34:32 +02:00
parent b79fbcf71d
commit d3e15e9d3b
11 changed files with 136 additions and 205 deletions

View File

@@ -110,12 +110,7 @@ interface LibraryMangaGridProps {
message?: string;
}
const LibraryMangaGrid: React.FC<LibraryMangaGridProps & { lastLibraryUpdate: number }> = ({
mangas,
isLoading,
message,
lastLibraryUpdate,
}) => {
const LibraryMangaGrid: React.FC<LibraryMangaGridProps> = ({ mangas, isLoading, message }) => {
const { t } = useTranslation();
const [query] = useQueryParam('query', StringParam);
@@ -129,7 +124,7 @@ const LibraryMangaGrid: React.FC<LibraryMangaGridProps & { lastLibraryUpdate: nu
);
const sortedMangas = useMemo(
() => sortManga(filteredMangas, options.sorts, options.sortDesc),
[filteredMangas, lastLibraryUpdate, options.sorts, options.sortDesc],
[filteredMangas, options.sorts, options.sortDesc],
);
const showFilteredOutMessage =
@@ -137,7 +132,7 @@ const LibraryMangaGrid: React.FC<LibraryMangaGridProps & { lastLibraryUpdate: nu
useEffect(() => {
window.scrollTo(0, 0);
}, [filteredMangas]);
}, [query, unread, downloaded]);
return (
<MangaGrid

View File

@@ -6,16 +6,16 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useEffect, useState } from 'react';
import { useMemo } from 'react';
import IconButton from '@mui/material/IconButton';
import RefreshIcon from '@mui/icons-material/Refresh';
import CircularProgress from '@mui/material/CircularProgress';
import { Box } from '@mui/material';
import Typography from '@mui/material/Typography';
import { useTranslation } from 'react-i18next';
import { IUpdateStatus } from '@/typings';
import requestManager from '@/lib/requests/RequestManager.ts';
import makeToast from '@/components/util/Toast';
import { UpdaterSubscription } from '@/lib/graphql/generated/graphql.ts';
interface IProgressProps {
progress: number;
@@ -32,62 +32,44 @@ function Progress({ progress }: IProgressProps) {
);
}
interface IUpdateCheckerProps {
handleFinishedUpdate: (time: number) => void;
}
const calcProgress = (status: UpdaterSubscription['updateStatusChanged'] | undefined) => {
if (!status) {
return 0;
}
function UpdateChecker({ handleFinishedUpdate }: IUpdateCheckerProps) {
const finishedUpdates = status.failedJobs.mangas.totalCount + status.completeJobs.mangas.totalCount;
const totalMangas = finishedUpdates + status.pendingJobs.mangas.totalCount + status.runningJobs.mangas.totalCount;
const progress = 100 * (finishedUpdates / totalMangas);
return Number.isNaN(progress) ? 0 : progress;
};
function UpdateChecker() {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [progress, setProgress] = useState(0);
const { data: updaterData } = requestManager.useUpdaterSubscription();
const status = updaterData?.updateStatusChanged;
const loading = !!status?.isRunning;
const progress = useMemo(
() => calcProgress(status),
[
status?.failedJobs.mangas.totalCount,
status?.completeJobs.mangas.totalCount,
status?.pendingJobs.mangas.totalCount,
status?.runningJobs.mangas.totalCount,
],
);
const onClick = async () => {
try {
setLoading(true);
setProgress(0);
await requestManager.startGlobalUpdate().response;
} catch (e) {
makeToast(t('global.error.label.update_failed'), 'error');
setLoading(false);
}
};
useEffect(() => {
const wsc = requestManager.getUpdateWebSocket();
// "loading" can't be used since it will be outdated once the state gets changed
// it could be used by adding it as a dependency of "useEffect" but then the socket would
// get closed and connected again every time it changes
let updateStarted = false;
wsc.onmessage = (e) => {
const { running, mangaStatusMap } = JSON.parse(e.data) as IUpdateStatus;
const { COMPLETE = [], RUNNING = [], PENDING = [] } = mangaStatusMap;
const currentProgress = 100 * (COMPLETE.length / (COMPLETE.length + RUNNING.length + PENDING.length));
const isUpdateFinished = currentProgress === 100;
const ignoreFaultyMessage = !updateStarted && !running && isUpdateFinished;
// for some reason the server sends 100% completed manga updates when connecting to the
// socket while no update is running
if (ignoreFaultyMessage) {
return;
}
updateStarted = running;
setLoading(running);
setProgress(Number.isNaN(currentProgress) ? 0 : currentProgress);
if (isUpdateFinished) {
handleFinishedUpdate(Date.now());
}
};
return () => wsc.close();
}, []);
return (
<IconButton onClick={onClick} disabled={loading}>
{loading ? <Progress progress={progress} /> : <RefreshIcon />}

View File

@@ -1,37 +0,0 @@
/*
* 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 { useEffect, useState } from 'react';
import requestManager from '@/lib/requests/RequestManager.ts';
const useSubscription = <T>(path: string, callback?: (newValue: T) => boolean | void) => {
const [state, setState] = useState<T | undefined>();
useEffect(() => {
const wsc = new WebSocket(requestManager.getValidWebSocketUrl(path));
wsc.onmessage = (e) => {
const data = JSON.parse(e.data) as T;
if (callback) {
// If callback is specified, only update state if callback returns true
// This is so that useSubscription can be used without causing rerender
if (callback(data) === true) {
setState(data);
}
} else {
setState(data);
}
};
return () => wsc.close();
}, [path]);
return { data: state };
};
export default useSubscription;

View File

@@ -27,16 +27,15 @@ import Typography from '@mui/material/Typography';
import React from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { IDownloadChapter } from '@/typings';
import requestManager from '@/lib/requests/RequestManager.ts';
import { getUploadDateString } from '@/util/date';
import DownloadStateIndicator from '@/components/molecules/DownloadStateIndicator';
import { ChapterType, UpdateChapterPatchInput } from '@/lib/graphql/generated/graphql.ts';
import { ChapterType, DownloadType, UpdateChapterPatchInput } from '@/lib/graphql/generated/graphql.ts';
interface IProps {
chapter: ChapterType;
chapterIds: number[];
downloadChapter: IDownloadChapter | undefined;
downloadChapter: DownloadType | undefined;
showChapterNumber: boolean;
onSelect: (selected: boolean) => void;
selected: boolean | null;

View File

@@ -11,9 +11,8 @@ import Typography from '@mui/material/Typography';
import React, { ComponentProps, useEffect, useMemo, useRef, useState } from 'react';
import { Virtuoso } from 'react-virtuoso';
import { useTranslation } from 'react-i18next';
import { IDownloadChapter, IQueue, TranslationKey } from '@/typings';
import { TranslationKey } from '@/typings';
import requestManager from '@/lib/requests/RequestManager.ts';
import useSubscription from '@/components/library/useSubscription';
import ChapterCard from '@/components/manga/ChapterCard';
import ResumeFab from '@/components/manga/ResumeFAB';
import { filterAndSortChapters, useChapterOptions } from '@/components/manga/util';
@@ -22,7 +21,7 @@ import makeToast from '@/components/util/Toast';
import ChaptersToolbarMenu from '@/components/manga/ChaptersToolbarMenu';
import SelectionFAB from '@/components/manga/SelectionFAB';
import { DEFAULT_FULL_FAB_HEIGHT } from '@/components/util/StyledFab';
import { ChapterType, MangaType, UpdateChapterPatchInput } from '@/lib/graphql/generated/graphql.ts';
import { ChapterType, DownloadType, MangaType, UpdateChapterPatchInput } from '@/lib/graphql/generated/graphql.ts';
const StyledVirtuoso = styled(Virtuoso)(({ theme }) => ({
listStyle: 'none',
@@ -70,7 +69,7 @@ const actionsStrings: {
export interface IChapterWithMeta {
chapter: ChapterType;
downloadChapter: IDownloadChapter | undefined;
downloadChapter: DownloadType | undefined;
selected: boolean | null;
}
@@ -83,8 +82,9 @@ const ChapterList: React.FC<IProps> = ({ manga, isRefreshing }) => {
const { t } = useTranslation();
const [selection, setSelection] = useState<number[] | null>(null);
const prevQueueRef = useRef<IDownloadChapter[]>();
const queue = useSubscription<IQueue>('downloads').data?.queue;
const prevQueueRef = useRef<DownloadType[]>();
const { data: downloaderData } = requestManager.useDownloadSubscription();
const queue = (downloaderData?.downloadChanged.queue as DownloadType[]) ?? [];
const [options, dispatch] = useChapterOptions(manga.id);
const { data: chaptersData, loading: isLoading, refetch } = requestManager.useGetMangaChapters(manga.id);
@@ -99,13 +99,15 @@ const ChapterList: React.FC<IProps> = ({ manga, isRefreshing }) => {
const prevQueue = prevQueueRef.current;
const changedDownloads = queue.filter((cd) => {
const prevChapterDownload = prevQueue.find(
(pcd) => cd.chapterIndex === pcd.chapterIndex && cd.mangaId === pcd.mangaId,
(pcd) =>
cd.chapter.sourceOrder === pcd.chapter.sourceOrder &&
cd.chapter.manga.id === pcd.chapter.manga.id,
);
if (!prevChapterDownload) return true;
return cd.state !== prevChapterDownload.state;
});
if (changedDownloads.length > 0) {
if (changedDownloads.length > 0 || prevQueue?.length !== queue.length) {
refetch();
}
}
@@ -179,7 +181,7 @@ const ChapterList: React.FC<IProps> = ({ manga, isRefreshing }) => {
() =>
visibleChapters.map((chapter) => {
const downloadChapter = queue?.find(
(cd) => cd.chapterIndex === chapter.sourceOrder && cd.mangaId === chapter.manga.id,
(cd) => cd.chapter.sourceOrder === chapter.sourceOrder && cd.chapter.manga.id === chapter.manga.id,
);
const selected = selection?.includes(chapter.id) ?? null;
return {

View File

@@ -12,7 +12,6 @@ import PublicIcon from '@mui/icons-material/Public';
import { styled } from '@mui/material/styles';
import React, { useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { mutate } from 'swr';
import { t as translate } from 'i18next';
import Button from '@mui/material/Button';
import { ISource } from '@/typings';
@@ -177,17 +176,11 @@ const MangaDetails: React.FC<IProps> = ({ manga }) => {
}, [manga.source]);
const addToLibrary = () => {
mutate(`/api/v1/manga/${manga.id}`, { ...manga, inLibrary: true }, { revalidate: false });
requestManager
.updateManga(manga.id, { inLibrary: true })
.response.then(() => mutate(`/api/v1/manga/${manga.id}`));
requestManager.updateManga(manga.id, { inLibrary: true });
};
const removeFromLibrary = () => {
mutate(`/api/v1/manga/${manga.id}`, { ...manga, inLibrary: false }, { revalidate: false });
requestManager
.updateManga(manga.id, { inLibrary: false })
.response.then(() => mutate(`/api/v1/manga/${manga.id}`));
requestManager.updateManga(manga.id, { inLibrary: false });
};
return (

View File

@@ -10,17 +10,18 @@ import { CircularProgress, Box } from '@mui/material';
import Typography from '@mui/material/Typography';
import React from 'react';
import { useTranslation } from 'react-i18next';
import { IDownloadChapter, TranslationKey } from '@/typings';
import { TranslationKey } from '@/typings';
import { DownloadState, DownloadType } from '@/lib/graphql/generated/graphql.ts';
interface DownloadStateIndicatorProps {
download: IDownloadChapter;
download: DownloadType;
}
const DOWNLOAD_STATE_TO_TRANSLATION_KEY_MAP: { [state in IDownloadChapter['state']]: TranslationKey } = {
Downloading: 'download.state.label.downloading',
Error: 'download.state.label.error',
Finished: 'download.state.label.finished',
Queued: 'download.state.label.queued',
const DOWNLOAD_STATE_TO_TRANSLATION_KEY_MAP: { [state in DownloadState]: TranslationKey } = {
DOWNLOADING: 'download.state.label.downloading',
ERROR: 'download.state.label.error',
FINISHED: 'download.state.label.finished',
QUEUED: 'download.state.label.queued',
} as const;
const DownloadStateIndicator: React.FC<DownloadStateIndicatorProps> = ({ download }) => {