Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add logic to reorder downloads #495

Merged
merged 1 commit into from
Dec 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 56 additions & 12 deletions src/lib/requests/RequestManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ import {
WebuiUpdateSubscription,
ResetWebuiUpdateStatusMutation,
ResetWebuiUpdateStatusMutationVariables,
GetDownloadStatusQuery,
GetDownloadStatusQueryVariables,
} from '@/lib/graphql/generated/graphql.ts';
import { GET_GLOBAL_METADATAS } from '@/lib/graphql/queries/GlobalMetadataQuery.ts';
import { SET_GLOBAL_METADATA } from '@/lib/graphql/mutations/GlobalMetadataMutation.ts';
Expand Down Expand Up @@ -221,10 +223,11 @@ import { DOWNLOAD_STATUS_SUBSCRIPTION } from '@/lib/graphql/subscriptions/Downlo
import { UPDATER_SUBSCRIPTION } from '@/lib/graphql/subscriptions/UpdaterSubscription.ts';
import { GET_SERVER_SETTINGS } from '@/lib/graphql/queries/SettingsQuery.ts';
import { UPDATE_SERVER_SETTINGS } from '@/lib/graphql/mutations/SettingsMutation.ts';
import { BASE_MANGA_FIELDS, FULL_EXTENSION_FIELDS } from '@/lib/graphql/Fragments.ts';
import { BASE_MANGA_FIELDS, FULL_DOWNLOAD_STATUS, FULL_EXTENSION_FIELDS } from '@/lib/graphql/Fragments.ts';
import { CLEAR_SERVER_CACHE } from '@/lib/graphql/mutations/ImageMutation.ts';
import { RESET_WEBUI_UPDATE_STATUS, UPDATE_WEBUI } from '@/lib/graphql/mutations/ServerInfoMutation.ts';
import { WEBUI_UPDATE_SUBSCRIPTION } from '@/lib/graphql/subscriptions/ServerInfoSubscription.ts';
import { GET_DOWNLOAD_STATUS } from '@/lib/graphql/queries/DownloaderQuery.ts';

enum GQLMethod {
QUERY = 'QUERY',
Expand Down Expand Up @@ -323,6 +326,7 @@ export const SPECIAL_ED_SOURCES = {
],
};

// TODO - extract logic to reduce the size of this file... grew waaaaaaaaaaaaay too big peepoFat
// TODO - correctly update cache after all mutations instead of refetching queries
export class RequestManager {
public static readonly API_VERSION = '/api/v1/';
Expand Down Expand Up @@ -1865,17 +1869,51 @@ export class RequestManager {
);
}

public reorderChapterInDownloadQueue(
chapterId: number,
position: number,
options?: MutationOptions<ReorderChapterDownloadMutation, ReorderChapterDownloadMutationVariables>,
): AbortableApolloMutationResponse<ReorderChapterDownloadMutation> {
return this.doRequest<ReorderChapterDownloadMutation, ReorderChapterDownloadMutationVariables>(
GQLMethod.MUTATION,
REORDER_CHAPTER_DOWNLOAD,
{ input: { chapterId, to: position } },
options,
);
public useReorderChapterInDownloadQueue(
options?: MutationHookOptions<ReorderChapterDownloadMutation, ReorderChapterDownloadMutationVariables>,
): AbortableApolloUseMutationResponse<ReorderChapterDownloadMutation, ReorderChapterDownloadMutationVariables> {
const [mutate, result] = this.doRequest(GQLMethod.USE_MUTATION, REORDER_CHAPTER_DOWNLOAD, undefined, options);

const wrappedMutate = (mutationOptions: Parameters<typeof mutate>[0]) => {
const variables = mutationOptions?.variables?.input;
const cachedDownloadStatus = this.graphQLClient.client.readFragment<
DownloadStatusSubscription['downloadChanged']
>({
id: 'DownloadStatus:{}',
fragment: FULL_DOWNLOAD_STATUS,
});

if (!variables) {
throw new Error('useReorderChapterInDownloadQueue: no variables passed');
}

if (!cachedDownloadStatus) {
throw new Error('useReorderChapterInDownloadQueue: there are no cached results');
}

const movedIndex = cachedDownloadStatus.queue.findIndex(
({ chapter }) => chapter.id === variables.chapterId,
);
const chapterDownload = cachedDownloadStatus.queue[movedIndex];
const queueWithoutChapterDownload = cachedDownloadStatus.queue.toSpliced(movedIndex, 1);
const updatedQueue = queueWithoutChapterDownload.toSpliced(variables.to, 0, chapterDownload);

return mutate({
optimisticResponse: {
__typename: 'Mutation',
reorderChapterDownload: {
__typename: 'ReorderChapterDownloadPayload',
downloadStatus: {
...cachedDownloadStatus,
queue: updatedQueue,
},
},
},
...mutationOptions,
});
};

return [wrappedMutate, result];
}

public addChaptersToDownloadQueue(
Expand Down Expand Up @@ -1983,6 +2021,12 @@ export class RequestManager {
return this.doRequest(GQLMethod.USE_QUERY, GET_UPDATE_STATUS, {}, options);
}

public useGetDownloadStatus(
options?: SubscriptionHookOptions<GetDownloadStatusQuery, GetDownloadStatusQueryVariables>,
): SubscriptionResult<GetDownloadStatusQuery, GetDownloadStatusQueryVariables> {
return this.doRequest(GQLMethod.USE_QUERY, GET_DOWNLOAD_STATUS, {}, options);
}

public useDownloadSubscription(
options?: SubscriptionHookOptions<DownloadStatusSubscription, DownloadStatusSubscriptionVariables>,
): SubscriptionResult<DownloadStatusSubscription, DownloadStatusSubscriptionVariables> {
Expand Down
2 changes: 2 additions & 0 deletions src/lib/requests/client/GraphQLClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ const typePolicies: StrictTypedTypePolicies = {
WebUIUpdateInfo: { keyFields: [] },
WebUIUpdateCheck: { keyFields: [] },
SettingsType: { keyFields: [] },
DownloadStatus: { keyFields: [] },
DownloadType: { keyFields: ['chapter'] },
Query: {
fields: {
chapters: {
Expand Down
31 changes: 26 additions & 5 deletions src/screens/DownloadQueue.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import { Card, CardActionArea, Stack, Box, Tooltip } from '@mui/material';
import IconButton from '@mui/material/IconButton';
import React, { useContext, useEffect } from 'react';
import { DragDropContext, Draggable, DraggableProvided } from 'react-beautiful-dnd';
import { DragDropContext, Draggable, DraggableProvided, DropResult } from 'react-beautiful-dnd';
import Typography from '@mui/material/Typography';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
Expand Down Expand Up @@ -97,9 +97,14 @@ const DownloadChapterItem = ({
export const DownloadQueue: React.FC = () => {
const { t } = useTranslation();

const { data: downloaderData, loading: isLoading } = requestManager.useDownloadSubscription();
const queue = (downloaderData?.downloadChanged.queue as DownloadType[]) ?? [];
const status = downloaderData?.downloadChanged.state ?? 'STARTED';
requestManager.useDownloadSubscription();
const [reorderDownload, { reset: revertReorder }] = requestManager.useReorderChapterInDownloadQueue();

const { data: downloadStatusData, loading: isLoading } = requestManager.useGetDownloadStatus();
const downloaderData = downloadStatusData?.downloadStatus;

const queue = (downloaderData?.queue as DownloadType[]) ?? [];
const status = downloaderData?.state ?? 'STARTED';
const isQueueEmpty = !queue.length;

const { setTitle, setAction } = useContext(NavBarContext);
Expand Down Expand Up @@ -156,7 +161,23 @@ export const DownloadQueue: React.FC = () => {
return () => window.removeEventListener('error', ignoreError);
}, []);

const onDragEnd = () => {};
const categoryReorder = (list: DownloadType[], from: number, to: number) => {
if (from === to) {
return;
}

reorderDownload({ variables: { input: { chapterId: list[from].chapter.id, to } } }).catch(() => {
revertReorder();
});
};

const onDragEnd = (result: DropResult) => {
if (!result.destination) {
return;
}

categoryReorder(queue, result.source.index, result.destination.index);
};

const handleDelete = async (chapter: TChapter) => {
const isRunning = status === 'STARTED';
Expand Down
Loading