diff options
Diffstat (limited to 'src/api/e926')
| -rw-r--r-- | src/api/e926/index.ts | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/src/api/e926/index.ts b/src/api/e926/index.ts new file mode 100644 index 0000000..43a3179 --- /dev/null +++ b/src/api/e926/index.ts | |||
| @@ -0,0 +1,82 @@ | |||
| 1 | import got from "got"; | ||
| 2 | import config from "../../config"; | ||
| 3 | import delay from "../../util/delay"; | ||
| 4 | import PostDatabase from "../../services/postDatabase"; | ||
| 5 | |||
| 6 | export const dedupeDb = new PostDatabase("e926dedupe.json", 50); | ||
| 7 | |||
| 8 | export interface GetPostQuery { | ||
| 9 | tags: readonly string[]; | ||
| 10 | maxPage: number; | ||
| 11 | } | ||
| 12 | |||
| 13 | export interface Post { | ||
| 14 | id: number; | ||
| 15 | file: { | ||
| 16 | url: string; | ||
| 17 | }; | ||
| 18 | sources: readonly string[]; | ||
| 19 | |||
| 20 | tags: { | ||
| 21 | general: readonly string[]; | ||
| 22 | species: readonly string[]; | ||
| 23 | character: readonly string[]; | ||
| 24 | copyright: readonly string[]; | ||
| 25 | artist: readonly string[]; | ||
| 26 | invalid: readonly string[]; | ||
| 27 | lore: readonly string[]; | ||
| 28 | meta: readonly string[]; | ||
| 29 | }; | ||
| 30 | } | ||
| 31 | |||
| 32 | export const client = got.extend({ | ||
| 33 | headers: { | ||
| 34 | "User-Agent": config.e621.userAgent, | ||
| 35 | }, | ||
| 36 | }); | ||
| 37 | |||
| 38 | export async function getPostById(id: number) { | ||
| 39 | const response = await client | ||
| 40 | .get("https://e926.net/posts.json", { | ||
| 41 | searchParams: { | ||
| 42 | tags: `id:${id}`, | ||
| 43 | }, | ||
| 44 | }) | ||
| 45 | .json<{ posts: readonly Post[] }>(); | ||
| 46 | |||
| 47 | if (!response.posts.length) { | ||
| 48 | throw new Error("No posts received"); | ||
| 49 | } | ||
| 50 | |||
| 51 | return response.posts[0]; | ||
| 52 | } | ||
| 53 | |||
| 54 | export async function getRandomPost(query: GetPostQuery): Promise<Post> { | ||
| 55 | const page = Math.floor(Math.random() * (query.maxPage - 1)) + 1; | ||
| 56 | |||
| 57 | const response = await client | ||
| 58 | .get("https://e926.net/posts.json", { | ||
| 59 | searchParams: { | ||
| 60 | limit: 75, | ||
| 61 | page, | ||
| 62 | tags: query.tags.join(" "), | ||
| 63 | }, | ||
| 64 | }) | ||
| 65 | .json<{ posts: readonly Post[] }>(); | ||
| 66 | |||
| 67 | if (!response.posts.length) { | ||
| 68 | throw new Error("No posts received"); | ||
| 69 | } | ||
| 70 | |||
| 71 | const postIndex = Math.floor(Math.random() * response.posts.length); | ||
| 72 | const post = response.posts[postIndex]; | ||
| 73 | |||
| 74 | const isDupe = await dedupeDb.insertIfNotExists({ provider: "e926", id: post.id }); | ||
| 75 | |||
| 76 | if (isDupe) { | ||
| 77 | await delay(1000); | ||
| 78 | return getRandomPost(query); | ||
| 79 | } | ||
| 80 | |||
| 81 | return post; | ||
| 82 | } | ||
