feat: schedule next airing episode

happens when new title is saved, or when new episode internal route is run successfully
This commit is contained in:
2024-09-09 03:53:34 -05:00
parent 38195776c2
commit 336701a84b
14 changed files with 353 additions and 19 deletions

View File

@@ -1,14 +1,15 @@
import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { Client } from "@upstash/qstash";
import { Hono, type HonoRequest } from "hono";
import { env } from "hono/adapter";
import mapKeys from "lodash.mapkeys";
import { DateTime } from "luxon";
import { z } from "zod";
import { Case, changeStringCase } from "~/libs/changeStringCase";
import type { AdminSdkCredentials } from "~/libs/fcm/getGoogleAuthToken";
import { sendFcmMessage } from "~/libs/fcm/sendFcmMessage";
import { getCurrentDomain } from "~/libs/getCurrentDomain";
import { maybeScheduleNextAiringEpisode } from "~/libs/maybeScheduleNextAiringEpisode";
import { verifyQstashHeader } from "~/libs/qstash/verifyQstashHeader";
import { readEnvVariable } from "~/libs/readEnvVariable";
import { getTokensSubscribedToTitle } from "~/models/token";
@@ -48,6 +49,7 @@ app.post(
`${domain}/episodes/${aniListId}`,
).then((res) => res.json<EpisodesResponseSchema>());
if (!success) {
await scheduleRetry(readEnvVariable(c.env, "QSTASH_TOKEN"), c.req);
return c.json(ErrorResponse, { status: 500 });
}
@@ -56,6 +58,7 @@ app.post(
(episode) => episode.number === episodeNumber,
);
if (!episode) {
await scheduleRetry(readEnvVariable(c.env, "QSTASH_TOKEN"), c.req);
return c.json(ErrorResponse, { status: 404 });
}
@@ -73,6 +76,7 @@ app.post(
},
).then((res) => res.json<FetchUrlResponse>());
if (!fetchUrlSuccess) {
await scheduleRetry(readEnvVariable(c.env, "QSTASH_TOKEN"), c.req);
return c.json(ErrorResponse, { status: 500 });
}
@@ -103,8 +107,23 @@ app.post(
}),
);
await maybeScheduleNextAiringEpisode(
env<Env, typeof c>(c, "workerd"),
c.req,
aniListId,
);
return c.json(SuccessResponse, 200);
},
);
async function scheduleRetry(qstashToken: string, req: HonoRequest) {
return new Client({ token: qstashToken }).publishJSON({
body: await req.text(),
url: req.url,
retries: 0,
delay: "1h",
});
}
export default app;