Skip to content

Commit

Permalink
stash
Browse files Browse the repository at this point in the history
  • Loading branch information
hanydd committed Nov 13, 2024
1 parent 2ef4787 commit f7150e7
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/cronjob/refreshCid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { CronJob } from "cron";
import { db } from "../databases/databases";
import { DBSegment } from "../types/segments.model";
import { Logger } from "../utils/logger";
import { BilibiliAPI } from "../utils/bilibiliApi";
import { sleep } from "../utils/timeUtil";

export const refreshCidJob = new CronJob("0 5 * * *", () => refreshCid());

let isRunning = false;

async function refreshCid() {
if (isRunning) {
Logger.info("refreshCid already running, skipping");
return;
}

isRunning = true;
const allSegments: DBSegment[] = await db.prepare("all", `SELECT * FROM "sponsorTimes" WHERE "cid" = NULL or "cid" = ''`, []);
const videoSegmentMap = new Map<string, DBSegment[]>();
for (const segment of allSegments) {
if (!videoSegmentMap.has(segment.videoID)) {
videoSegmentMap.set(segment.videoID, []);
}
videoSegmentMap.get(segment.videoID)?.push(segment);
}
Logger.info(`Found ${videoSegmentMap.size} videos with missing cids`);

for (const [videoID, segments] of videoSegmentMap) {
try {
const biliVideoDetail = await BilibiliAPI.getVideoDetailView(videoID);
if (biliVideoDetail === null || biliVideoDetail === undefined) {
Logger.error(`Failed to get video detail for ${videoID}`);
continue;
}
for (const segment of segments) {
if (biliVideoDetail.pages.length === 1 || !!biliVideoDetail.pages[0].cid) {
await db.prepare("run", `UPDATE "sponsorTimes" SET "cid" = ? WHERE "videoID" = ?`, [biliVideoDetail.pages[0].cid, videoID]);
} else {
const segmentIndex = segment.startTime / biliVideoDetail.duration;
const segmentPage = biliVideoDetail.pages[Math.floor(segmentIndex)];
if (segmentPage !== undefined) {
segment.cid = segmentPage.cid;
}
}
await db.prepare("run", `UPDATE "sponsorTimes" SET "cid" = ? WHERE "UUID" = ?`, [videoSegments, segments]);
}
} catch (e) {
Logger.error(`Failed to get video detail for ${videoID}`);
continue;
}

await sleep(1000);
}

isRunning = false;
}
3 changes: 3 additions & 0 deletions src/utils/timeUtil.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function sleep(time: number) {
return new Promise((resolve) => setTimeout(resolve, time));
}

0 comments on commit f7150e7

Please sign in to comment.