/api/file/random support is_ad and is_nsfw

This commit is contained in:
2023-06-22 20:59:54 +08:00
parent 03b65d71c2
commit 1611c99390
2 changed files with 39 additions and 10 deletions

40
db.ts
View File

@@ -766,13 +766,39 @@ export class EhDb {
[gid],
)[0][0];
}
get_random_file() {
const s = this.convert_file(
this.db.queryEntries<EhFileRaw>(
"SELECT * FROM file ORDER BY RANDOM() LIMIT 1;",
),
);
return s.length ? s[0] : undefined;
get_random_file(is_nsfw: boolean | null, is_ad: boolean | null) {
if (is_nsfw === null && is_ad === null) {
const s = this.convert_file(
this.db.queryEntries<EhFileRaw>(
"SELECT * FROM file ORDER BY RANDOM() LIMIT 1;",
),
);
return s.length ? s[0] : undefined;
} else if (is_nsfw === null) {
const s = this.convert_file(
this.db.queryEntries<EhFileRaw>(
"SELECT file.* FROM file LEFT JOIN filemeta ON file.token = filemeta.token WHERE IFNULL(filemeta.is_ad, 0) = ? ORDER BY RANDOM() LIMIT 1;",
[is_ad],
),
);
return s.length ? s[0] : undefined;
} else if (is_ad === null) {
const s = this.convert_file(
this.db.queryEntries<EhFileRaw>(
"SELECT file.* FROM file LEFT JOIN filemeta ON file.token = filemeta.token WHERE IFNULL(filemeta.is_nsfw, 0) = ? ORDER BY RANDOM() LIMIT 1;",
[is_nsfw],
),
);
return s.length ? s[0] : undefined;
} else {
const s = this.convert_file(
this.db.queryEntries<EhFileRaw>(
"SELECT file.* FROM file LEFT JOIN filemeta ON file.token = filemeta.token WHERE IFNULL(filemeta.is_nsfw, 0) = ? AND IFNULL(filemeta.is_ad, 0) = ? ORDER BY RANDOM() LIMIT 1;",
[is_nsfw, is_ad],
),
);
return s.length ? s[0] : undefined;
}
}
get_tasks() {
return this.transaction(() =>

View File

@@ -1,12 +1,15 @@
import { Handlers } from "$fresh/server.ts";
import { get_task_manager } from "../../../server.ts";
import { parse_bool } from "../../../server/parse_form.ts";
export const handler: Handlers = {
GET(req, _ctx) {
async GET(req, _ctx) {
const m = get_task_manager();
const f = m.db.get_random_file();
if (!f) return new Response("File not found.", { status: 404 });
const u = new URL(req.url);
const is_nsfw = await parse_bool(u.searchParams.get("is_nsfw"), null);
const is_ad = await parse_bool(u.searchParams.get("is_ad"), null);
const f = m.db.get_random_file(is_nsfw, is_ad);
if (!f) return new Response("File not found.", { status: 404 });
return Response.redirect(`${u.origin}/api/file/${f.id}`);
},
};