Skip to content

Commit

Permalink
feat: cancel job if exists
Browse files Browse the repository at this point in the history
  • Loading branch information
oae committed Oct 14, 2022
1 parent bce4832 commit 130c339
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
28 changes: 24 additions & 4 deletions src/server/queue/checkChapters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const checkChapters = async (manga: MangaWithLibrary) => {
opts: {
jobId: `${sanitizer(manga.title)}_${chapterIndex - 1}_download`,
},
name: `${sanitizer(manga.title)}_${chapterIndex - 1}_download`,
name: `${sanitizer(manga.title)}_chapter#${chapterIndex - 1}_download`,
data: {
chapterIndex: chapterIndex - 1,
source: manga.source,
Expand Down Expand Up @@ -78,19 +78,39 @@ export const checkChaptersWorker = new Worker(
},
);

export const getJobIdFromTitle = (title: string) => `check_${sanitizer(title)}_chapters`;

export const removeJob = async (title: string) => {
const jobId = getJobIdFromTitle(title);
const jobs = await checkChaptersQueue.getJobs('delayed');
await Promise.all(
jobs
.filter((job) => job.opts.repeat?.jobId === jobId)
.map(async (job) => {
if (job.id) {
return checkChaptersQueue.remove(job.id);
}
return null;
}),
);
};

export const schedule = async (manga: MangaWithLibrary) => {
if (manga.interval === 'never') {
return;
}

await removeJob(manga.title);
const jobId = getJobIdFromTitle(manga.title);

await checkChaptersQueue.add(
`check_${manga.title}_chapters`,
jobId,
{
manga,
},
{
jobId: `check_${manga.libraryId}_${manga.id}_chapters`,
repeatJobKey: `check_${manga.libraryId}_${manga.id}_chapters`,
jobId,
repeatJobKey: jobId,
repeat: {
pattern: cronMap[manga.interval as keyof typeof cronMap],
},
Expand Down
4 changes: 2 additions & 2 deletions src/server/trpc/router/manga.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { TRPCError } from '@trpc/server';
import path from 'path';
import { z } from 'zod';
import { sanitizer } from '../../../utils/sanitize';
import { schedule } from '../../queue/checkChapters';
import { removeJob, schedule } from '../../queue/checkChapters';
import { getAvailableSources, getMangaDetail, removeManga, search } from '../../utils/mangal';
import { t } from '../trpc';

Expand Down Expand Up @@ -68,7 +68,7 @@ export const mangaRouter = t.router({
});
const mangaPath = path.resolve(removed.Library.path, sanitizer(removed.title));
await removeManga(mangaPath);
// TODO: remove jobs also
await removeJob(removed.title);
}),
add: t.procedure
.input(
Expand Down

0 comments on commit 130c339

Please sign in to comment.