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

View File

@@ -6,16 +6,16 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * 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 IconButton from '@mui/material/IconButton';
import RefreshIcon from '@mui/icons-material/Refresh'; import RefreshIcon from '@mui/icons-material/Refresh';
import CircularProgress from '@mui/material/CircularProgress'; import CircularProgress from '@mui/material/CircularProgress';
import { Box } from '@mui/material'; import { Box } from '@mui/material';
import Typography from '@mui/material/Typography'; import Typography from '@mui/material/Typography';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { IUpdateStatus } from '@/typings';
import requestManager from '@/lib/requests/RequestManager.ts'; import requestManager from '@/lib/requests/RequestManager.ts';
import makeToast from '@/components/util/Toast'; import makeToast from '@/components/util/Toast';
import { UpdaterSubscription } from '@/lib/graphql/generated/graphql.ts';
interface IProgressProps { interface IProgressProps {
progress: number; progress: number;
@@ -32,62 +32,44 @@ function Progress({ progress }: IProgressProps) {
); );
} }
interface IUpdateCheckerProps { const calcProgress = (status: UpdaterSubscription['updateStatusChanged'] | undefined) => {
handleFinishedUpdate: (time: number) => void; 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 { t } = useTranslation();
const [loading, setLoading] = useState(false); const { data: updaterData } = requestManager.useUpdaterSubscription();
const [progress, setProgress] = useState(0); 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 () => { const onClick = async () => {
try { try {
setLoading(true);
setProgress(0);
await requestManager.startGlobalUpdate().response; await requestManager.startGlobalUpdate().response;
} catch (e) { } catch (e) {
makeToast(t('global.error.label.update_failed'), 'error'); 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 ( return (
<IconButton onClick={onClick} disabled={loading}> <IconButton onClick={onClick} disabled={loading}>
{loading ? <Progress progress={progress} /> : <RefreshIcon />} {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 React from 'react';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { IDownloadChapter } from '@/typings';
import requestManager from '@/lib/requests/RequestManager.ts'; import requestManager from '@/lib/requests/RequestManager.ts';
import { getUploadDateString } from '@/util/date'; import { getUploadDateString } from '@/util/date';
import DownloadStateIndicator from '@/components/molecules/DownloadStateIndicator'; 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 { interface IProps {
chapter: ChapterType; chapter: ChapterType;
chapterIds: number[]; chapterIds: number[];
downloadChapter: IDownloadChapter | undefined; downloadChapter: DownloadType | undefined;
showChapterNumber: boolean; showChapterNumber: boolean;
onSelect: (selected: boolean) => void; onSelect: (selected: boolean) => void;
selected: boolean | null; 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 React, { ComponentProps, useEffect, useMemo, useRef, useState } from 'react';
import { Virtuoso } from 'react-virtuoso'; import { Virtuoso } from 'react-virtuoso';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { IDownloadChapter, IQueue, TranslationKey } from '@/typings'; import { TranslationKey } from '@/typings';
import requestManager from '@/lib/requests/RequestManager.ts'; import requestManager from '@/lib/requests/RequestManager.ts';
import useSubscription from '@/components/library/useSubscription';
import ChapterCard from '@/components/manga/ChapterCard'; import ChapterCard from '@/components/manga/ChapterCard';
import ResumeFab from '@/components/manga/ResumeFAB'; import ResumeFab from '@/components/manga/ResumeFAB';
import { filterAndSortChapters, useChapterOptions } from '@/components/manga/util'; import { filterAndSortChapters, useChapterOptions } from '@/components/manga/util';
@@ -22,7 +21,7 @@ import makeToast from '@/components/util/Toast';
import ChaptersToolbarMenu from '@/components/manga/ChaptersToolbarMenu'; import ChaptersToolbarMenu from '@/components/manga/ChaptersToolbarMenu';
import SelectionFAB from '@/components/manga/SelectionFAB'; import SelectionFAB from '@/components/manga/SelectionFAB';
import { DEFAULT_FULL_FAB_HEIGHT } from '@/components/util/StyledFab'; 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 }) => ({ const StyledVirtuoso = styled(Virtuoso)(({ theme }) => ({
listStyle: 'none', listStyle: 'none',
@@ -70,7 +69,7 @@ const actionsStrings: {
export interface IChapterWithMeta { export interface IChapterWithMeta {
chapter: ChapterType; chapter: ChapterType;
downloadChapter: IDownloadChapter | undefined; downloadChapter: DownloadType | undefined;
selected: boolean | null; selected: boolean | null;
} }
@@ -83,8 +82,9 @@ const ChapterList: React.FC<IProps> = ({ manga, isRefreshing }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [selection, setSelection] = useState<number[] | null>(null); const [selection, setSelection] = useState<number[] | null>(null);
const prevQueueRef = useRef<IDownloadChapter[]>(); const prevQueueRef = useRef<DownloadType[]>();
const queue = useSubscription<IQueue>('downloads').data?.queue; const { data: downloaderData } = requestManager.useDownloadSubscription();
const queue = (downloaderData?.downloadChanged.queue as DownloadType[]) ?? [];
const [options, dispatch] = useChapterOptions(manga.id); const [options, dispatch] = useChapterOptions(manga.id);
const { data: chaptersData, loading: isLoading, refetch } = requestManager.useGetMangaChapters(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 prevQueue = prevQueueRef.current;
const changedDownloads = queue.filter((cd) => { const changedDownloads = queue.filter((cd) => {
const prevChapterDownload = prevQueue.find( 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; if (!prevChapterDownload) return true;
return cd.state !== prevChapterDownload.state; return cd.state !== prevChapterDownload.state;
}); });
if (changedDownloads.length > 0) { if (changedDownloads.length > 0 || prevQueue?.length !== queue.length) {
refetch(); refetch();
} }
} }
@@ -179,7 +181,7 @@ const ChapterList: React.FC<IProps> = ({ manga, isRefreshing }) => {
() => () =>
visibleChapters.map((chapter) => { visibleChapters.map((chapter) => {
const downloadChapter = queue?.find( 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; const selected = selection?.includes(chapter.id) ?? null;
return { return {

View File

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

View File

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

View File

@@ -18,9 +18,12 @@ import {
QueryHookOptions as ApolloQueryHookOptions, QueryHookOptions as ApolloQueryHookOptions,
QueryOptions as ApolloQueryOptions, QueryOptions as ApolloQueryOptions,
QueryResult, QueryResult,
SubscriptionHookOptions as ApolloSubscriptionHookOptions,
SubscriptionResult,
TypedDocumentNode, TypedDocumentNode,
useMutation, useMutation,
useQuery, useQuery,
useSubscription,
} from '@apollo/client'; } from '@apollo/client';
import { OperationVariables } from '@apollo/client/core'; import { OperationVariables } from '@apollo/client/core';
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
@@ -47,6 +50,8 @@ import {
DequeueChapterDownloadMutationVariables, DequeueChapterDownloadMutationVariables,
DequeueChapterDownloadsMutation, DequeueChapterDownloadsMutation,
DequeueChapterDownloadsMutationVariables, DequeueChapterDownloadsMutationVariables,
DownloadStatusSubscription,
DownloadStatusSubscriptionVariables,
EnqueueChapterDownloadMutation, EnqueueChapterDownloadMutation,
EnqueueChapterDownloadMutationVariables, EnqueueChapterDownloadMutationVariables,
EnqueueChapterDownloadsMutation, EnqueueChapterDownloadsMutation,
@@ -127,6 +132,8 @@ import {
UpdateMangaMutation, UpdateMangaMutation,
UpdateMangaMutationVariables, UpdateMangaMutationVariables,
UpdateMangaPatchInput, UpdateMangaPatchInput,
UpdaterSubscription,
UpdaterSubscriptionVariables,
UpdateSourcePreferencesMutation, UpdateSourcePreferencesMutation,
UpdateSourcePreferencesMutationVariables, UpdateSourcePreferencesMutationVariables,
ValidateBackupQuery, ValidateBackupQuery,
@@ -188,12 +195,15 @@ import { GET_UPDATE_STATUS } from '@/lib/graphql/queries/UpdaterQuery.ts';
import { CustomCache } from '@/lib/requests/CustomCache.ts'; import { CustomCache } from '@/lib/requests/CustomCache.ts';
import { RESTORE_BACKUP } from '@/lib/graphql/mutations/BackupMutation.ts'; import { RESTORE_BACKUP } from '@/lib/graphql/mutations/BackupMutation.ts';
import { VALIDATE_BACKUP } from '@/lib/graphql/queries/BackupQuery.ts'; import { VALIDATE_BACKUP } from '@/lib/graphql/queries/BackupQuery.ts';
import { DOWNLOAD_STATUS_SUBSCRIPTION } from '@/lib/graphql/subscriptions/DownloaderSubscription.ts';
import { UPDATER_SUBSCRIPTION } from '@/lib/graphql/subscriptions/UpdaterSubscription.ts';
enum GQLMethod { enum GQLMethod {
QUERY = 'QUERY', QUERY = 'QUERY',
USE_QUERY = 'USE_QUERY', USE_QUERY = 'USE_QUERY',
USE_MUTATION = 'USE_MUTATION', USE_MUTATION = 'USE_MUTATION',
MUTATION = 'MUTATION', MUTATION = 'MUTATION',
USE_SUBSCRIPTION = 'USE_SUBSCRIPTION',
} }
type CustomApolloOptions = { type CustomApolloOptions = {
@@ -209,14 +219,12 @@ type CustomApolloOptions = {
*/ */
omitAbortSignal?: boolean; omitAbortSignal?: boolean;
}; };
type QueryOptions<Variables extends OperationVariables = OperationVariables, Data = any> = ApolloQueryOptions< type QueryOptions<Variables extends OperationVariables = OperationVariables, Data = any> = Partial<
Variables, ApolloQueryOptions<Variables, Data>
Data
> & > &
CustomApolloOptions; CustomApolloOptions;
type QueryHookOptions<Data = any, Variables extends OperationVariables = OperationVariables> = ApolloQueryHookOptions< type QueryHookOptions<Data = any, Variables extends OperationVariables = OperationVariables> = Partial<
Data, ApolloQueryHookOptions<Data, Variables>
Variables
> & > &
CustomApolloOptions; CustomApolloOptions;
type MutationHookOptions<Data = any, Variables extends OperationVariables = OperationVariables> = Partial< type MutationHookOptions<Data = any, Variables extends OperationVariables = OperationVariables> = Partial<
@@ -227,10 +235,13 @@ type MutationOptions<Data = any, Variables extends OperationVariables = Operatio
ApolloMutationOptions<Data, Variables> ApolloMutationOptions<Data, Variables>
> & > &
CustomApolloOptions; CustomApolloOptions;
type ApolloPaginatedMutationOptions< type ApolloPaginatedMutationOptions<Data = any, Variables extends OperationVariables = OperationVariables> = Partial<
Data = any, MutationHookOptions<Data, Variables>
Variables extends OperationVariables = OperationVariables, > & { skipRequest?: boolean };
> = MutationHookOptions<Data, Variables> & { skipRequest?: boolean }; type SubscriptionHookOptions<Data = any, Variables extends OperationVariables = OperationVariables> = Partial<
ApolloSubscriptionHookOptions<Data, Variables>
> &
Omit<CustomApolloOptions, 'omitAbortSignal'> & { omitAbortSignal?: never };
type AbortableRequest = { abortRequest: AbortController['abort'] }; type AbortableRequest = { abortRequest: AbortController['abort'] };
@@ -292,22 +303,6 @@ export class RequestManager {
return this.restClient.getClient().defaults.baseURL!; return this.restClient.getClient().defaults.baseURL!;
} }
public getWebSocketBaseUrl(): string {
return this.getBaseUrl().replace('http', 'ws');
}
public getValidWebSocketUrl(path: string, apiVersion = RequestManager.API_VERSION): string {
return `${this.getWebSocketBaseUrl()}${apiVersion}${path}`;
}
public getUpdateWebSocket(): WebSocket {
return new WebSocket(this.getValidWebSocketUrl('update'));
}
public getDownloadWebSocket(): WebSocket {
return new WebSocket(this.getValidWebSocketUrl('downloads'));
}
public getValidUrlFor(endpoint: string, apiVersion: string = RequestManager.API_VERSION): string { public getValidUrlFor(endpoint: string, apiVersion: string = RequestManager.API_VERSION): string {
return `${this.getBaseUrl()}${apiVersion}${endpoint}`; return `${this.getBaseUrl()}${apiVersion}${endpoint}`;
} }
@@ -654,46 +649,55 @@ export class RequestManager {
private doRequestNew<Data, Variables extends OperationVariables = OperationVariables>( private doRequestNew<Data, Variables extends OperationVariables = OperationVariables>(
method: GQLMethod.QUERY, method: GQLMethod.QUERY,
operation: TypedDocumentNode<Data, Variables>, operation: DocumentNode | TypedDocumentNode<Data, Variables>,
variables: Variables, variables: Variables | undefined,
options?: Partial<QueryOptions<Variables, Data>>, options?: QueryOptions<Variables, Data>,
): AbortabaleApolloQueryResponse<Data>; ): AbortabaleApolloQueryResponse<Data>;
private doRequestNew<Data, Variables extends OperationVariables = OperationVariables>( private doRequestNew<Data, Variables extends OperationVariables = OperationVariables>(
method: GQLMethod.USE_QUERY, method: GQLMethod.USE_QUERY,
operation: TypedDocumentNode<Data, Variables>, operation: DocumentNode | TypedDocumentNode<Data, Variables>,
variables: Variables, variables: Variables | undefined,
options?: Partial<QueryHookOptions<Data, Variables>>, options?: QueryHookOptions<Data, Variables>,
): AbortableApolloUseQueryResponse<Data, Variables>; ): AbortableApolloUseQueryResponse<Data, Variables>;
private doRequestNew<Data, Variables extends OperationVariables = OperationVariables>( private doRequestNew<Data, Variables extends OperationVariables = OperationVariables>(
method: GQLMethod.USE_MUTATION, method: GQLMethod.USE_MUTATION,
operation: TypedDocumentNode<Data, Variables>, operation: DocumentNode | TypedDocumentNode<Data, Variables>,
variables: Variables | undefined, variables: Variables | undefined,
options?: Partial<MutationHookOptions<Data, Variables>>, options?: MutationHookOptions<Data, Variables>,
): AbortableApolloUseMutationResponse<Data, Variables>; ): AbortableApolloUseMutationResponse<Data, Variables>;
private doRequestNew<Data, Variables extends OperationVariables = OperationVariables>( private doRequestNew<Data, Variables extends OperationVariables = OperationVariables>(
method: GQLMethod.MUTATION, method: GQLMethod.MUTATION,
operation: TypedDocumentNode<Data, Variables>, operation: DocumentNode | TypedDocumentNode<Data, Variables>,
variables: Variables, variables: Variables | undefined,
options?: Partial<MutationOptions<Data, Variables>>, options?: MutationOptions<Data, Variables>,
): AbortableApolloMutationResponse<Data>; ): AbortableApolloMutationResponse<Data>;
private doRequestNew<Data, Variables extends OperationVariables = OperationVariables>(
method: GQLMethod.USE_SUBSCRIPTION,
operation: DocumentNode | TypedDocumentNode<Data, Variables>,
variables: Variables | undefined,
options?: SubscriptionHookOptions<Data, Variables>,
): SubscriptionResult<Data, Variables>;
private doRequestNew<Data, Variables extends OperationVariables = OperationVariables>( private doRequestNew<Data, Variables extends OperationVariables = OperationVariables>(
method: GQLMethod, method: GQLMethod,
operation: TypedDocumentNode<Data, Variables>, operation: DocumentNode | TypedDocumentNode<Data, Variables>,
variables: Variables, variables: Variables | undefined,
options?: options?:
| QueryOptions<Variables, Data> | QueryOptions<Variables, Data>
| QueryHookOptions<Data, Variables> | QueryHookOptions<Data, Variables>
| MutationHookOptions<Data, Variables> | MutationHookOptions<Data, Variables>
| MutationOptions<Data, Variables>, | MutationOptions<Data, Variables>
| SubscriptionHookOptions<Data, Variables>,
): ):
| AbortabaleApolloQueryResponse<Data> | AbortabaleApolloQueryResponse<Data>
| AbortableApolloUseQueryResponse<Data, Variables> | AbortableApolloUseQueryResponse<Data, Variables>
| AbortableApolloUseMutationResponse<Data, Variables> | AbortableApolloUseMutationResponse<Data, Variables>
| AbortableApolloMutationResponse<Data> { | AbortableApolloMutationResponse<Data>
| SubscriptionResult<Data, Variables> {
const { signal, abortRequest } = this.createAbortController(); const { signal, abortRequest } = this.createAbortController();
switch (method) { switch (method) {
case GQLMethod.QUERY: case GQLMethod.QUERY:
@@ -760,6 +764,12 @@ export class RequestManager {
}), }),
abortRequest, abortRequest,
}; };
case GQLMethod.USE_SUBSCRIPTION:
return useSubscription<Data, Variables>(operation, {
client: this.graphQLClient.client,
variables,
...(options as SubscriptionHookOptions<Data, Variables>),
});
default: default:
throw new Error(`unexpected GQLRequest type "${method}"`); throw new Error(`unexpected GQLRequest type "${method}"`);
} }
@@ -1566,6 +1576,18 @@ export class RequestManager {
): AbortableApolloUseQueryResponse<GetUpdateStatusQuery, GetUpdateStatusQueryVariables> { ): AbortableApolloUseQueryResponse<GetUpdateStatusQuery, GetUpdateStatusQueryVariables> {
return this.doRequestNew(GQLMethod.USE_QUERY, GET_UPDATE_STATUS, {}, options); return this.doRequestNew(GQLMethod.USE_QUERY, GET_UPDATE_STATUS, {}, options);
} }
public useDownloadSubscription(
options?: SubscriptionHookOptions<DownloadStatusSubscription, DownloadStatusSubscriptionVariables>,
): SubscriptionResult<DownloadStatusSubscription, DownloadStatusSubscriptionVariables> {
return this.doRequestNew(GQLMethod.USE_SUBSCRIPTION, DOWNLOAD_STATUS_SUBSCRIPTION, {}, options);
}
public useUpdaterSubscription(
options?: SubscriptionHookOptions<UpdaterSubscription, UpdaterSubscriptionVariables>,
): SubscriptionResult<UpdaterSubscription, UpdaterSubscriptionVariables> {
return this.doRequestNew(GQLMethod.USE_SUBSCRIPTION, UPDATER_SUBSCRIPTION, {}, options);
}
} }
const requestManager = new RequestManager(); const requestManager = new RequestManager();

View File

@@ -18,31 +18,26 @@ import { DragDropContext, Draggable } from 'react-beautiful-dnd';
import Typography from '@mui/material/Typography'; import Typography from '@mui/material/Typography';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { IChapter, IQueue } from '@/typings';
import requestManager from '@/lib/requests/RequestManager.ts'; import requestManager from '@/lib/requests/RequestManager.ts';
import StrictModeDroppable from '@/lib/StrictModeDroppable'; import StrictModeDroppable from '@/lib/StrictModeDroppable';
import makeToast from '@/components/util/Toast'; import makeToast from '@/components/util/Toast';
import { NavbarToolbar } from '@/components/navbar/DefaultNavBar'; import { NavbarToolbar } from '@/components/navbar/DefaultNavBar';
import DownloadStateIndicator from '@/components/molecules/DownloadStateIndicator'; import DownloadStateIndicator from '@/components/molecules/DownloadStateIndicator';
import useSubscription from '@/components/library/useSubscription';
import EmptyView from '@/components/util/EmptyView'; import EmptyView from '@/components/util/EmptyView';
import NavbarContext from '@/components/context/NavbarContext'; import NavbarContext from '@/components/context/NavbarContext';
import { ChapterType, DownloadType } from '@/lib/graphql/generated/graphql.ts';
const initialQueue = {
status: 'Stopped',
queue: [],
} as IQueue;
const DownloadQueue: React.FC = () => { const DownloadQueue: React.FC = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: queueState } = useSubscription<IQueue>('downloads'); const { data: downloaderData } = requestManager.useDownloadSubscription();
const { queue, status } = queueState ?? initialQueue; const queue = (downloaderData?.downloadChanged.queue as DownloadType[]) ?? [];
const status = downloaderData?.downloadChanged.state ?? 'STARTED';
const { setTitle, setAction } = useContext(NavbarContext); const { setTitle, setAction } = useContext(NavbarContext);
const toggleQueueStatus = () => { const toggleQueueStatus = () => {
if (status === 'Stopped') { if (status === 'STOPPED') {
requestManager.startDownloads(); requestManager.startDownloads();
} else { } else {
requestManager.stopDownloads(); requestManager.stopDownloads();
@@ -60,8 +55,8 @@ const DownloadQueue: React.FC = () => {
return <EmptyView message={t('download.queue.label.no_downloads')} />; return <EmptyView message={t('download.queue.label.no_downloads')} />;
} }
const handleDelete = async (chapter: IChapter) => { const handleDelete = async (chapter: ChapterType) => {
const isRunning = status === 'Started'; const isRunning = status === 'STARTED';
try { try {
if (isRunning) { if (isRunning) {
@@ -91,7 +86,7 @@ const DownloadQueue: React.FC = () => {
<> <>
<NavbarToolbar> <NavbarToolbar>
<IconButton onClick={toggleQueueStatus} size="large"> <IconButton onClick={toggleQueueStatus} size="large">
{status === 'Stopped' ? <PlayArrowIcon /> : <PauseIcon />} {status === 'STOPPED' ? <PlayArrowIcon /> : <PauseIcon />}
</IconButton> </IconButton>
</NavbarToolbar> </NavbarToolbar>
<DragDropContext onDragEnd={onDragEnd}> <DragDropContext onDragEnd={onDragEnd}>
@@ -100,8 +95,8 @@ const DownloadQueue: React.FC = () => {
<Box ref={droppableProvided.innerRef} sx={{ pt: 1 }}> <Box ref={droppableProvided.innerRef} sx={{ pt: 1 }}>
{queue.map((item, index) => ( {queue.map((item, index) => (
<Draggable <Draggable
key={`${item.mangaId}-${item.chapterIndex}`} key={`${item.chapter.manga.id}-${item.chapter.sourceOrder}`}
draggableId={`${item.mangaId}-${item.chapterIndex}`} draggableId={`${item.chapter.manga.id}-${item.chapter.sourceOrder}`}
index={index} index={index}
> >
{(draggableProvided, snapshot) => ( {(draggableProvided, snapshot) => (
@@ -129,7 +124,7 @@ const DownloadQueue: React.FC = () => {
<DragHandle /> <DragHandle />
</IconButton> </IconButton>
<Stack sx={{ flex: 1, ml: 1 }} direction="column"> <Stack sx={{ flex: 1, ml: 1 }} direction="column">
<Typography variant="h6">{item.manga.title}</Typography> <Typography variant="h6">{item.chapter.manga.title}</Typography>
<Typography variant="caption" display="block" gutterBottom> <Typography variant="caption" display="block" gutterBottom>
{item.chapter.name} {item.chapter.name}
</Typography> </Typography>

View File

@@ -7,7 +7,7 @@
*/ */
import { Chip, Tab, Tabs, styled, Box } from '@mui/material'; import { Chip, Tab, Tabs, styled, Box } from '@mui/material';
import React, { useContext, useEffect, useMemo, useState } from 'react'; import React, { useContext, useEffect, useMemo, useRef } from 'react';
import { useQueryParam, NumberParam } from 'use-query-params'; import { useQueryParam, NumberParam } from 'use-query-params';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import requestManager from '@/lib/requests/RequestManager.ts'; import requestManager from '@/lib/requests/RequestManager.ts';
@@ -63,7 +63,6 @@ export default function Library() {
const { t } = useTranslation(); const { t } = useTranslation();
const { options } = useLibraryOptionsContext(); const { options } = useLibraryOptionsContext();
const [lastLibraryUpdate, setLastLibraryUpdate] = useState(Date.now());
const { const {
data: categoriesResponse, data: categoriesResponse,
error: tabsError, error: tabsError,
@@ -85,7 +84,7 @@ export default function Library() {
data: categoryMangaResponse, data: categoryMangaResponse,
error: mangaError, error: mangaError,
loading: mangaLoading, loading: mangaLoading,
} = requestManager.useGetCategoryMangas(activeTab?.id, { skip: !activeTab }); } = requestManager.useGetCategoryMangas(activeTab?.id, { skip: !activeTab, nextFetchPolicy: 'cache-only' });
const mangas = (categoryMangaResponse?.category.mangas.nodes as unknown as MangaType[]) ?? []; const mangas = (categoryMangaResponse?.category.mangas.nodes as unknown as MangaType[]) ?? [];
const { setTitle, setAction } = useContext(NavbarContext); const { setTitle, setAction } = useContext(NavbarContext);
@@ -102,7 +101,7 @@ export default function Library() {
<> <>
<AppbarSearch /> <AppbarSearch />
<LibraryToolbarMenu /> <LibraryToolbarMenu />
<UpdateChecker handleFinishedUpdate={setLastLibraryUpdate} /> <UpdateChecker />
</>, </>,
); );
return () => { return () => {
@@ -136,7 +135,6 @@ export default function Library() {
return ( return (
<LibraryMangaGrid <LibraryMangaGrid
mangas={mangas} mangas={mangas}
lastLibraryUpdate={lastLibraryUpdate}
message={t('library.error.label.empty')} message={t('library.error.label.empty')}
isLoading={activeTab != null && mangaLoading} isLoading={activeTab != null && mangaLoading}
/> />
@@ -183,7 +181,6 @@ export default function Library() {
) : ( ) : (
<LibraryMangaGrid <LibraryMangaGrid
mangas={mangas} mangas={mangas}
lastLibraryUpdate={lastLibraryUpdate}
message={t('library.error.label.empty')} message={t('library.error.label.empty')}
isLoading={mangaLoading} isLoading={mangaLoading}
/> />

View File

@@ -13,18 +13,17 @@ import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent'; import CardContent from '@mui/material/CardContent';
import IconButton from '@mui/material/IconButton'; import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography'; import Typography from '@mui/material/Typography';
import React, { useCallback, useContext, useEffect, useMemo, useState } from 'react'; import React, { useCallback, useContext, useEffect, useMemo } from 'react';
import { Link, useLocation } from 'react-router-dom'; import { Link, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { t as translate } from 'i18next'; import { t as translate } from 'i18next';
import { GroupedVirtuoso } from 'react-virtuoso'; import { GroupedVirtuoso } from 'react-virtuoso';
import { IQueue } from '@/typings';
import requestManager from '@/lib/requests/RequestManager.ts'; import requestManager from '@/lib/requests/RequestManager.ts';
import LoadingPlaceholder from '@/components/util/LoadingPlaceholder'; import LoadingPlaceholder from '@/components/util/LoadingPlaceholder';
import EmptyView from '@/components/util/EmptyView'; import EmptyView from '@/components/util/EmptyView';
import DownloadStateIndicator from '@/components/molecules/DownloadStateIndicator'; import DownloadStateIndicator from '@/components/molecules/DownloadStateIndicator';
import NavbarContext from '@/components/context/NavbarContext'; import NavbarContext from '@/components/context/NavbarContext';
import { ChapterType } from '@/lib/graphql/generated/graphql.ts'; import { ChapterType, DownloadType } from '@/lib/graphql/generated/graphql.ts';
const StyledGroupedVirtuoso = styled(GroupedVirtuoso)(({ theme }) => ({ const StyledGroupedVirtuoso = styled(GroupedVirtuoso)(({ theme }) => ({
// 64px header // 64px header
@@ -96,11 +95,6 @@ const groupByDate = (updates: ChapterType[]): [date: string, items: number][] =>
return [...dateToItemMap.entries()]; return [...dateToItemMap.entries()];
}; };
const initialQueue = {
status: 'Stopped',
queue: [],
} as IQueue;
const Updates: React.FC = () => { const Updates: React.FC = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const location = useLocation(); const location = useLocation();
@@ -120,20 +114,8 @@ const Updates: React.FC = () => {
const updateEntries = (chapterUpdateData?.chapters.nodes as ChapterType[]) ?? []; const updateEntries = (chapterUpdateData?.chapters.nodes as ChapterType[]) ?? [];
const groupedUpdates = useMemo(() => groupByDate(updateEntries), [updateEntries]); const groupedUpdates = useMemo(() => groupByDate(updateEntries), [updateEntries]);
const groupCounts: number[] = useMemo(() => groupedUpdates.map((group) => group[1]), [groupedUpdates]); const groupCounts: number[] = useMemo(() => groupedUpdates.map((group) => group[1]), [groupedUpdates]);
const [, setWsClient] = useState<WebSocket>(); const { data: downloaderData } = requestManager.useDownloadSubscription();
const [{ queue }, setQueueState] = useState<IQueue>(initialQueue); const queue = (downloaderData?.downloadChanged.queue as DownloadType[]) ?? [];
useEffect(() => {
const wsc = requestManager.getDownloadWebSocket();
wsc.onmessage = (e) => {
const data = JSON.parse(e.data) as IQueue;
setQueueState(data);
};
setWsClient(wsc);
return () => wsc.close();
}, []);
useEffect(() => { useEffect(() => {
setTitle(t('updates.title')); setTitle(t('updates.title'));
@@ -146,7 +128,7 @@ const Updates: React.FC = () => {
sourceOrder, sourceOrder,
manga: { id: mangaId }, manga: { id: mangaId },
} = chapter; } = chapter;
return queue.find((q) => sourceOrder === q.chapterIndex && mangaId === q.mangaId); return queue.find((q) => sourceOrder === q.chapter.sourceOrder && mangaId === q.chapter.manga.id);
}; };
const downloadChapter = (chapter: ChapterType) => { const downloadChapter = (chapter: ChapterType) => {