e621-client 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.README ADDED
@@ -0,0 +1,47 @@
1
+ # e621 Client
2
+
3
+ This is a small client to do some stuff with the e621 API. It is created to fit my needs, but you can use it too, if it works for you.
4
+
5
+ I can't guarantee it will work in the future, so I recommend you just use another package instead or build a client yourself.
6
+
7
+ ### Supported Endpoints
8
+
9
+ - `/favorites`
10
+ - `/users`
11
+ - `/users/:id`
12
+ - `/posts`
13
+ - `/posts/:id`
14
+
15
+ ### Getting Started
16
+
17
+ Just create an instance of the client like so:
18
+
19
+ ```ts
20
+ const client = new E621ApiClient({
21
+ client: "Your client name",
22
+ isBrowser: false,
23
+ });
24
+ ```
25
+
26
+ Now you can use it to do some stuff:
27
+
28
+ ```ts
29
+ // not useful but still here (like me)
30
+ const posts = await client.getPosts();
31
+
32
+ // search posts by tags
33
+ const postsWithTags = await client.getPosts({
34
+ tags: "male score:>100",
35
+ });
36
+
37
+ // search users by names (_ for wildcards)
38
+ const toms = await client.getUsers({
39
+ nameMatches: "tom_",
40
+ });
41
+
42
+ // if you have credentials set, they will be sent with your requests as well:
43
+ client.setCredentials({
44
+ username: "HornyFurry",
45
+ apiKey: "wouldntyouliketoknowweatherboy",
46
+ });
47
+ ```
@@ -0,0 +1,49 @@
1
+ import { E621Post } from "../types/e621/E621Post";
2
+ import { E621User } from "../types/e621/E621User";
3
+ import { E621ApiHeaders } from "./E621ApiHeaders";
4
+ export interface E621ApiOptions {
5
+ client: string;
6
+ isBrowser: boolean;
7
+ credentials?: Credentials;
8
+ }
9
+ export type GetOptions = {
10
+ route: Route;
11
+ params?: Params;
12
+ headers?: E621ApiHeaders;
13
+ };
14
+ export interface Credentials {
15
+ username: string;
16
+ apiKey: string;
17
+ }
18
+ export type EntityId = string | number;
19
+ export type Route = string | number | (string | number)[];
20
+ export type Params = Record<string, string>;
21
+ export type Pagination = {
22
+ limit?: string;
23
+ page?: string;
24
+ };
25
+ export type GetUsersOptions = {
26
+ nameMatches?: string;
27
+ } & Params & Pagination;
28
+ export type GetPostsOptions = {
29
+ tags?: string;
30
+ } & Pagination;
31
+ export type GetFavoritesOptions = {
32
+ userId?: string;
33
+ } & Pagination;
34
+ export declare class E621ApiClient {
35
+ protected static readonly BASE_URL = "https://e621.net/";
36
+ private readonly client;
37
+ private readonly isBrowser;
38
+ private credentials;
39
+ constructor(options: E621ApiOptions);
40
+ getUsers(options?: GetUsersOptions): Promise<E621User[]>;
41
+ getUserById(id: EntityId): Promise<E621User | null>;
42
+ getPosts(options?: GetPostsOptions): Promise<E621Post[]>;
43
+ getPostById(id: EntityId): Promise<E621Post | null>;
44
+ getFavorites(options?: GetFavoritesOptions): Promise<E621Post[]>;
45
+ setCredentials(credentials: Credentials | null): E621ApiClient;
46
+ checkCredentials(credentials?: Credentials): Promise<boolean>;
47
+ get<E>({ route, params, headers, }: GetOptions): Promise<E | null>;
48
+ private buildUrl;
49
+ }
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.E621ApiClient = void 0;
13
+ const E621Post_1 = require("../types/e621/E621Post");
14
+ const E621User_1 = require("../types/e621/E621User");
15
+ const utils_1 = require("../utils");
16
+ const E621ApiHeaders_1 = require("./E621ApiHeaders");
17
+ class E621ApiClient {
18
+ constructor(options) {
19
+ this.credentials = null;
20
+ this.client = options.client;
21
+ this.isBrowser = options.isBrowser;
22
+ this.credentials = options.credentials || null;
23
+ }
24
+ // Users
25
+ getUsers() {
26
+ return __awaiter(this, arguments, void 0, function* (options = {}) {
27
+ const users = yield this.get({
28
+ route: "users",
29
+ params: (0, utils_1.translateOptions)(options, {
30
+ nameMatches: "search[name_matches]",
31
+ }),
32
+ });
33
+ return (users === null || users === void 0 ? void 0 : users.map(E621User_1.parseUser)) || [];
34
+ });
35
+ }
36
+ getUserById(id) {
37
+ return __awaiter(this, void 0, void 0, function* () {
38
+ const user = yield this.get({ route: ["users", id] });
39
+ return user ? (0, E621User_1.parseUser)(user) : null;
40
+ });
41
+ }
42
+ // Posts
43
+ getPosts() {
44
+ return __awaiter(this, arguments, void 0, function* (options = {}) {
45
+ const response = yield this.get({
46
+ route: "posts",
47
+ params: options,
48
+ });
49
+ return (response === null || response === void 0 ? void 0 : response.posts.map(E621Post_1.parsePost)) || [];
50
+ });
51
+ }
52
+ getPostById(id) {
53
+ return __awaiter(this, void 0, void 0, function* () {
54
+ const response = yield this.get({ route: ["posts", id] });
55
+ return (response === null || response === void 0 ? void 0 : response.post) ? (0, E621Post_1.parsePost)(response.post) : null;
56
+ });
57
+ }
58
+ // Favorites
59
+ getFavorites() {
60
+ return __awaiter(this, arguments, void 0, function* (options = {}) {
61
+ var _a;
62
+ const response = yield this.get({
63
+ route: "favorites",
64
+ params: (0, utils_1.translateOptions)(options, { userId: "user_id" }),
65
+ });
66
+ return ((_a = response === null || response === void 0 ? void 0 : response.posts) === null || _a === void 0 ? void 0 : _a.map(E621Post_1.parsePost)) || [];
67
+ });
68
+ }
69
+ // Account
70
+ setCredentials(credentials) {
71
+ this.credentials = credentials;
72
+ return this;
73
+ }
74
+ checkCredentials(credentials) {
75
+ return __awaiter(this, void 0, void 0, function* () {
76
+ if (credentials) {
77
+ this.setCredentials(credentials);
78
+ }
79
+ const headers = new E621ApiHeaders_1.E621ApiHeaders();
80
+ if (!this.isBrowser) {
81
+ headers.addUserAgent(this.client);
82
+ }
83
+ return yield fetch(this.buildUrl("favorites"), {
84
+ headers: headers.addAuthorization(this.credentials).build(),
85
+ })
86
+ .then((res) => res.ok)
87
+ .catch(() => false);
88
+ });
89
+ }
90
+ get(_a) {
91
+ return __awaiter(this, arguments, void 0, function* ({ route, params, headers = new E621ApiHeaders_1.E621ApiHeaders(), }) {
92
+ if (!this.isBrowser) {
93
+ headers.addUserAgent(this.client);
94
+ }
95
+ const response = yield fetch(this.buildUrl(route, params), {
96
+ method: "GET",
97
+ headers: headers.addAuthorization(this.credentials).build(),
98
+ });
99
+ return response.json().catch(() => null);
100
+ });
101
+ }
102
+ buildUrl(route, params = {}) {
103
+ const queryParams = new URLSearchParams(params);
104
+ const url = E621ApiClient.BASE_URL + (0, utils_1.ensureArray)(route).join("/") + ".json";
105
+ if (this.isBrowser) {
106
+ queryParams.set("_client", this.client);
107
+ }
108
+ return queryParams.size > 0 ? `${url}?${queryParams}` : url;
109
+ }
110
+ }
111
+ exports.E621ApiClient = E621ApiClient;
112
+ E621ApiClient.BASE_URL = "https://e621.net/";
@@ -0,0 +1,10 @@
1
+ import { Credentials } from "./E621ApiClient";
2
+ export declare class E621ApiHeaders {
3
+ private readonly value;
4
+ constructor(value?: Record<string, string>);
5
+ addAuthorization(credentials: Credentials | null): E621ApiHeaders;
6
+ addFormContentType(): E621ApiHeaders;
7
+ addUserAgent(userAgent: string): E621ApiHeaders;
8
+ build(): Record<string, string>;
9
+ protected static buildAuthorization({ username, apiKey }: Credentials): string;
10
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.E621ApiHeaders = void 0;
4
+ class E621ApiHeaders {
5
+ constructor(value = {}) {
6
+ this.value = value;
7
+ }
8
+ addAuthorization(credentials) {
9
+ if (credentials) {
10
+ this.value.Authorization = E621ApiHeaders.buildAuthorization(credentials);
11
+ }
12
+ return this;
13
+ }
14
+ addFormContentType() {
15
+ this.value["Content-Type"] =
16
+ "application/x-www-form-urlencoded; charset=UTF-8";
17
+ return this;
18
+ }
19
+ addUserAgent(userAgent) {
20
+ this.value["User-Agent"] = userAgent;
21
+ return this;
22
+ }
23
+ build() {
24
+ return this.value;
25
+ }
26
+ static buildAuthorization({ username, apiKey }) {
27
+ const creds = `${username}:${apiKey}`;
28
+ if (canUseWindow()) {
29
+ return `Basic ${window.btoa(creds)}`;
30
+ }
31
+ else if (canUseBuffer()) {
32
+ return `Basic ${Buffer.from(creds).toString("base64")}`;
33
+ }
34
+ else {
35
+ throw new Error("Environment does not support base64 encoding");
36
+ }
37
+ }
38
+ }
39
+ exports.E621ApiHeaders = E621ApiHeaders;
40
+ function canUseWindow() {
41
+ return typeof window !== "undefined";
42
+ }
43
+ function canUseBuffer() {
44
+ return typeof Buffer !== "undefined" && typeof Buffer.from === "function";
45
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./client/E621ApiClient";
2
+ export * from "./types/e621/E621User";
3
+ export * from "./types/e621/E621Post";
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./client/E621ApiClient"), exports);
18
+ __exportStar(require("./types/e621/E621User"), exports);
19
+ __exportStar(require("./types/e621/E621Post"), exports);
@@ -0,0 +1,133 @@
1
+ export interface PostResponse {
2
+ id: number;
3
+ created_at: string;
4
+ updated_at: string;
5
+ file: {
6
+ width: number;
7
+ height: number;
8
+ ext: string;
9
+ size: number;
10
+ md5: string;
11
+ url: string;
12
+ };
13
+ preview: {
14
+ width: number;
15
+ height: number;
16
+ url: string | null;
17
+ };
18
+ sample: {
19
+ has: boolean;
20
+ width: number;
21
+ height: number;
22
+ url: string | null;
23
+ };
24
+ score: {
25
+ up: number;
26
+ down: number;
27
+ total: number;
28
+ };
29
+ tags: {
30
+ general: string[];
31
+ artist: string[];
32
+ copyright: string[];
33
+ character: string[];
34
+ species: string[];
35
+ invalid: string[];
36
+ meta: string[];
37
+ lore: string[];
38
+ };
39
+ locked_tags: string[];
40
+ change_seq: number;
41
+ flags: {
42
+ pending: boolean;
43
+ flagged: boolean;
44
+ note_locked: boolean;
45
+ status_locked: boolean;
46
+ rating_locked: boolean;
47
+ deleted: boolean;
48
+ };
49
+ rating: string;
50
+ fav_count: number;
51
+ sources: string[];
52
+ pools: number[];
53
+ relationships: {
54
+ parent_id: number | null;
55
+ has_children: boolean;
56
+ has_active_children: boolean;
57
+ children: number[];
58
+ };
59
+ approver_id: number | null;
60
+ uploader_id: number;
61
+ description: string;
62
+ comment_count: number;
63
+ is_favorited: boolean;
64
+ has_notes: boolean;
65
+ duration: number | null;
66
+ }
67
+ export interface E621Post {
68
+ id: number;
69
+ createdAt: Date;
70
+ updatedAt: Date;
71
+ file: {
72
+ width: number;
73
+ height: number;
74
+ ext: string;
75
+ size: number;
76
+ md5: string;
77
+ url: string;
78
+ };
79
+ preview: {
80
+ width: number;
81
+ height: number;
82
+ url: string | null;
83
+ };
84
+ sample: {
85
+ has: boolean;
86
+ width: number;
87
+ height: number;
88
+ url: string | null;
89
+ };
90
+ score: {
91
+ up: number;
92
+ down: number;
93
+ total: number;
94
+ };
95
+ tags: {
96
+ general: string[];
97
+ artist: string[];
98
+ copyright: string[];
99
+ character: string[];
100
+ species: string[];
101
+ invalid: string[];
102
+ meta: string[];
103
+ lore: string[];
104
+ };
105
+ lockedTags: string[];
106
+ changeSeq: number;
107
+ flags: {
108
+ pending: boolean;
109
+ flagged: boolean;
110
+ noteLocked: boolean;
111
+ statusLocked: boolean;
112
+ ratingLocked: boolean;
113
+ deleted: boolean;
114
+ };
115
+ rating: string;
116
+ favCount: number;
117
+ sources: string[];
118
+ pools: number[];
119
+ relationships: {
120
+ parentId: number | null;
121
+ hasChildren: boolean;
122
+ hasActiveChildren: boolean;
123
+ children: number[];
124
+ };
125
+ approverId: number | null;
126
+ uploaderId: number;
127
+ description: string;
128
+ commentCount: number;
129
+ isFavorited: boolean;
130
+ hasNotes: boolean;
131
+ duration: number | null;
132
+ }
133
+ export declare function parsePost(post: PostResponse): E621Post;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parsePost = void 0;
4
+ function parsePost(post) {
5
+ return {
6
+ id: post.id,
7
+ createdAt: new Date(post.created_at),
8
+ updatedAt: new Date(post.updated_at),
9
+ file: post.file,
10
+ preview: post.preview,
11
+ sample: post.sample,
12
+ score: post.score,
13
+ tags: post.tags,
14
+ lockedTags: post.locked_tags,
15
+ changeSeq: post.change_seq,
16
+ flags: {
17
+ pending: post.flags.pending,
18
+ flagged: post.flags.flagged,
19
+ noteLocked: post.flags.note_locked,
20
+ statusLocked: post.flags.status_locked,
21
+ ratingLocked: post.flags.rating_locked,
22
+ deleted: post.flags.deleted,
23
+ },
24
+ rating: post.rating,
25
+ favCount: post.fav_count,
26
+ sources: post.sources,
27
+ pools: post.pools,
28
+ relationships: {
29
+ parentId: post.relationships.parent_id,
30
+ hasChildren: post.relationships.has_children,
31
+ hasActiveChildren: post.relationships.has_active_children,
32
+ children: post.relationships.children,
33
+ },
34
+ approverId: post.approver_id,
35
+ uploaderId: post.uploader_id,
36
+ description: post.description,
37
+ commentCount: post.comment_count,
38
+ isFavorited: post.is_favorited,
39
+ hasNotes: post.has_notes,
40
+ duration: post.duration,
41
+ };
42
+ }
43
+ exports.parsePost = parsePost;
@@ -0,0 +1,63 @@
1
+ export interface UserResponse {
2
+ wiki_page_version_count: number;
3
+ artist_version_count: number;
4
+ pool_version_count: number;
5
+ forum_post_count: number;
6
+ comment_count: number;
7
+ flag_count: number;
8
+ favorite_count: number;
9
+ positive_feedback_count: number;
10
+ neutral_feedback_count: number;
11
+ negative_feedback_count: number;
12
+ upload_limit: number;
13
+ profile_about: string;
14
+ profile_artinfo: string;
15
+ id: number;
16
+ created_at: string;
17
+ name: string;
18
+ level: number;
19
+ base_upload_limit: number;
20
+ post_upload_count: number;
21
+ post_update_count: number;
22
+ note_update_count: number;
23
+ is_banned: boolean;
24
+ can_approve_posts: boolean;
25
+ can_upload_free: boolean;
26
+ level_string: string;
27
+ avatar_id: number | null;
28
+ }
29
+ export interface E621User {
30
+ id: number;
31
+ profile: {
32
+ name: string;
33
+ level: number;
34
+ about: string;
35
+ artInfo: string;
36
+ avatarId: number | null;
37
+ createdAt: Date;
38
+ levelString: string;
39
+ };
40
+ counts: {
41
+ wikiPageVersion: number;
42
+ artistVersion: number;
43
+ poolVersion: number;
44
+ forumPost: number;
45
+ comment: number;
46
+ flag: number;
47
+ favorite: number;
48
+ positiveFeedback: number;
49
+ neutralFeedback: number;
50
+ negativeFeedback: number;
51
+ };
52
+ limits: {
53
+ upload: number;
54
+ baseUpload: number;
55
+ postUpload: number;
56
+ postUpdate: number;
57
+ noteUpdate: number;
58
+ };
59
+ isBanned: boolean;
60
+ canApprovePosts: boolean;
61
+ canUploadFree: boolean;
62
+ }
63
+ export declare function parseUser(user: UserResponse): E621User;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseUser = void 0;
4
+ function parseUser(user) {
5
+ return {
6
+ id: user.id,
7
+ profile: {
8
+ name: user.name,
9
+ level: user.level,
10
+ about: user.profile_about,
11
+ artInfo: user.profile_artinfo,
12
+ avatarId: user.avatar_id,
13
+ createdAt: new Date(user.created_at),
14
+ levelString: user.level_string,
15
+ },
16
+ counts: {
17
+ wikiPageVersion: user.wiki_page_version_count,
18
+ artistVersion: user.artist_version_count,
19
+ poolVersion: user.pool_version_count,
20
+ forumPost: user.forum_post_count,
21
+ comment: user.comment_count,
22
+ flag: user.flag_count,
23
+ favorite: user.favorite_count,
24
+ positiveFeedback: user.positive_feedback_count,
25
+ neutralFeedback: user.neutral_feedback_count,
26
+ negativeFeedback: user.negative_feedback_count,
27
+ },
28
+ limits: {
29
+ upload: user.upload_limit,
30
+ baseUpload: user.base_upload_limit,
31
+ postUpload: user.post_upload_count,
32
+ postUpdate: user.post_update_count,
33
+ noteUpdate: user.note_update_count,
34
+ },
35
+ isBanned: user.is_banned,
36
+ canApprovePosts: user.can_approve_posts,
37
+ canUploadFree: user.can_upload_free,
38
+ };
39
+ }
40
+ exports.parseUser = parseUser;
@@ -0,0 +1,10 @@
1
+ import { PostResponse } from "./e621/E621Post";
2
+ export type GetFavoritesResponse = {
3
+ posts: PostResponse[] | null;
4
+ };
5
+ export type GetPostResponse = {
6
+ post: PostResponse | null;
7
+ };
8
+ export type GetPostsResponse = {
9
+ posts: PostResponse[];
10
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ export declare function ensureArray<T>(value: T | T[]): T[];
2
+ export declare function translateOptions<Options extends Record<string, string>>(options: Options, table: Partial<Options>): Record<string, string>;
package/dist/utils.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.translateOptions = exports.ensureArray = void 0;
4
+ function ensureArray(value) {
5
+ if (Array.isArray(value)) {
6
+ return value;
7
+ }
8
+ return [value];
9
+ }
10
+ exports.ensureArray = ensureArray;
11
+ function translateOptions(options, table) {
12
+ var _a;
13
+ const params = {};
14
+ for (const [key, value] of Object.entries(options)) {
15
+ params[(_a = table[key]) !== null && _a !== void 0 ? _a : key] = value;
16
+ }
17
+ return params;
18
+ }
19
+ exports.translateOptions = translateOptions;
package/package.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "e621-client",
3
+ "version": "1.0.0",
4
+ "main": "dist/index.js",
5
+ "scripts": {
6
+ "build": "tsc"
7
+ },
8
+ "keywords": [],
9
+ "author": "Tommus",
10
+ "license": "ISC",
11
+ "description": "A simple client for the e621 API",
12
+ "devDependencies": {
13
+ "@types/node": "^20.14.2",
14
+ "prettier": "^3.3.1",
15
+ "ts-node": "^10.9.2",
16
+ "typescript": "^5.4.5"
17
+ }
18
+ }
@@ -0,0 +1,140 @@
1
+ import { E621Post, parsePost } from "../types/e621/E621Post";
2
+ import { E621User, UserResponse, parseUser } from "../types/e621/E621User";
3
+ import {
4
+ GetFavoritesResponse,
5
+ GetPostResponse,
6
+ GetPostsResponse,
7
+ } from "../types/responses";
8
+ import { ensureArray, translateOptions } from "../utils";
9
+ import { E621ApiHeaders } from "./E621ApiHeaders";
10
+
11
+ export interface E621ApiOptions {
12
+ client: string;
13
+ isBrowser: boolean;
14
+ credentials?: Credentials;
15
+ }
16
+
17
+ export type GetOptions = {
18
+ route: Route;
19
+ params?: Params;
20
+ headers?: E621ApiHeaders;
21
+ };
22
+
23
+ export interface Credentials {
24
+ username: string;
25
+ apiKey: string;
26
+ }
27
+
28
+ export type EntityId = string | number;
29
+ export type Route = string | number | (string | number)[];
30
+ export type Params = Record<string, string>;
31
+ export type Pagination = { limit?: string; page?: string };
32
+
33
+ export type GetUsersOptions = { nameMatches?: string } & Params & Pagination;
34
+ export type GetPostsOptions = { tags?: string } & Pagination;
35
+ export type GetFavoritesOptions = { userId?: string } & Pagination;
36
+
37
+ export class E621ApiClient {
38
+ protected static readonly BASE_URL = "https://e621.net/";
39
+
40
+ private readonly client: string;
41
+ private readonly isBrowser: boolean;
42
+ private credentials: Credentials | null = null;
43
+
44
+ constructor(options: E621ApiOptions) {
45
+ this.client = options.client;
46
+ this.isBrowser = options.isBrowser;
47
+ this.credentials = options.credentials || null;
48
+ }
49
+
50
+ // Users
51
+ public async getUsers(options: GetUsersOptions = {}): Promise<E621User[]> {
52
+ const users = await this.get<UserResponse[]>({
53
+ route: "users",
54
+ params: translateOptions(options, {
55
+ nameMatches: "search[name_matches]",
56
+ }),
57
+ });
58
+ return users?.map(parseUser) || [];
59
+ }
60
+
61
+ public async getUserById(id: EntityId): Promise<E621User | null> {
62
+ const user = await this.get<UserResponse>({ route: ["users", id] });
63
+ return user ? parseUser(user) : null;
64
+ }
65
+
66
+ // Posts
67
+ public async getPosts(options: GetPostsOptions = {}): Promise<E621Post[]> {
68
+ const response = await this.get<GetPostsResponse>({
69
+ route: "posts",
70
+ params: options,
71
+ });
72
+ return response?.posts.map(parsePost) || [];
73
+ }
74
+
75
+ public async getPostById(id: EntityId): Promise<E621Post | null> {
76
+ const response = await this.get<GetPostResponse>({ route: ["posts", id] });
77
+ return response?.post ? parsePost(response.post) : null;
78
+ }
79
+
80
+ // Favorites
81
+ public async getFavorites(
82
+ options: GetFavoritesOptions = {}
83
+ ): Promise<E621Post[]> {
84
+ const response = await this.get<GetFavoritesResponse>({
85
+ route: "favorites",
86
+ params: translateOptions(options, { userId: "user_id" }),
87
+ });
88
+ return response?.posts?.map(parsePost) || [];
89
+ }
90
+
91
+ // Account
92
+ public setCredentials(credentials: Credentials | null): E621ApiClient {
93
+ this.credentials = credentials;
94
+ return this;
95
+ }
96
+
97
+ public async checkCredentials(credentials?: Credentials): Promise<boolean> {
98
+ if (credentials) {
99
+ this.setCredentials(credentials);
100
+ }
101
+
102
+ const headers = new E621ApiHeaders();
103
+ if (!this.isBrowser) {
104
+ headers.addUserAgent(this.client);
105
+ }
106
+
107
+ return await fetch(this.buildUrl("favorites"), {
108
+ headers: headers.addAuthorization(this.credentials).build(),
109
+ })
110
+ .then((res) => res.ok)
111
+ .catch(() => false);
112
+ }
113
+
114
+ public async get<E>({
115
+ route,
116
+ params,
117
+ headers = new E621ApiHeaders(),
118
+ }: GetOptions): Promise<E | null> {
119
+ if (!this.isBrowser) {
120
+ headers.addUserAgent(this.client);
121
+ }
122
+
123
+ const response = await fetch(this.buildUrl(route, params), {
124
+ method: "GET",
125
+ headers: headers.addAuthorization(this.credentials).build(),
126
+ });
127
+ return response.json().catch(() => null);
128
+ }
129
+
130
+ private buildUrl(route: Route, params: Params = {}): string {
131
+ const queryParams = new URLSearchParams(params);
132
+ const url = E621ApiClient.BASE_URL + ensureArray(route).join("/") + ".json";
133
+
134
+ if (this.isBrowser) {
135
+ queryParams.set("_client", this.client);
136
+ }
137
+
138
+ return queryParams.size > 0 ? `${url}?${queryParams}` : url;
139
+ }
140
+ }
@@ -0,0 +1,51 @@
1
+ import { Credentials } from "./E621ApiClient";
2
+
3
+ export class E621ApiHeaders {
4
+ private readonly value: Record<string, string>;
5
+
6
+ constructor(value: Record<string, string> = {}) {
7
+ this.value = value;
8
+ }
9
+
10
+ public addAuthorization(credentials: Credentials | null): E621ApiHeaders {
11
+ if (credentials) {
12
+ this.value.Authorization = E621ApiHeaders.buildAuthorization(credentials);
13
+ }
14
+ return this;
15
+ }
16
+
17
+ public addFormContentType(): E621ApiHeaders {
18
+ this.value["Content-Type"] =
19
+ "application/x-www-form-urlencoded; charset=UTF-8";
20
+ return this;
21
+ }
22
+
23
+ public addUserAgent(userAgent: string): E621ApiHeaders {
24
+ this.value["User-Agent"] = userAgent;
25
+ return this;
26
+ }
27
+
28
+ public build(): Record<string, string> {
29
+ return this.value;
30
+ }
31
+
32
+ protected static buildAuthorization({ username, apiKey }: Credentials) {
33
+ const creds = `${username}:${apiKey}`;
34
+
35
+ if (canUseWindow()) {
36
+ return `Basic ${window.btoa(creds)}`;
37
+ } else if (canUseBuffer()) {
38
+ return `Basic ${Buffer.from(creds).toString("base64")}`;
39
+ } else {
40
+ throw new Error("Environment does not support base64 encoding");
41
+ }
42
+ }
43
+ }
44
+
45
+ function canUseWindow() {
46
+ return typeof window !== "undefined";
47
+ }
48
+
49
+ function canUseBuffer() {
50
+ return typeof Buffer !== "undefined" && typeof Buffer.from === "function";
51
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./client/E621ApiClient";
2
+ export * from "./types/e621/E621User";
3
+ export * from "./types/e621/E621Post";
@@ -0,0 +1,173 @@
1
+ export interface PostResponse {
2
+ id: number;
3
+ created_at: string;
4
+ updated_at: string;
5
+ file: {
6
+ width: number;
7
+ height: number;
8
+ ext: string;
9
+ size: number;
10
+ md5: string;
11
+ url: string;
12
+ };
13
+ preview: {
14
+ width: number;
15
+ height: number;
16
+ url: string | null;
17
+ };
18
+ sample: {
19
+ has: boolean;
20
+ width: number;
21
+ height: number;
22
+ url: string | null;
23
+ };
24
+ score: {
25
+ up: number;
26
+ down: number;
27
+ total: number;
28
+ };
29
+ tags: {
30
+ general: string[];
31
+ artist: string[];
32
+ copyright: string[];
33
+ character: string[];
34
+ species: string[];
35
+ invalid: string[];
36
+ meta: string[];
37
+ lore: string[];
38
+ };
39
+ locked_tags: string[];
40
+ change_seq: number;
41
+ flags: {
42
+ pending: boolean;
43
+ flagged: boolean;
44
+ note_locked: boolean;
45
+ status_locked: boolean;
46
+ rating_locked: boolean;
47
+ deleted: boolean;
48
+ };
49
+ rating: string;
50
+ fav_count: number;
51
+ sources: string[];
52
+ pools: number[];
53
+ relationships: {
54
+ parent_id: number | null;
55
+ has_children: boolean;
56
+ has_active_children: boolean;
57
+ children: number[];
58
+ };
59
+ approver_id: number | null;
60
+ uploader_id: number;
61
+ description: string;
62
+ comment_count: number;
63
+ is_favorited: boolean;
64
+ has_notes: boolean;
65
+ duration: number | null;
66
+ }
67
+
68
+ export interface E621Post {
69
+ id: number;
70
+ createdAt: Date;
71
+ updatedAt: Date;
72
+ file: {
73
+ width: number;
74
+ height: number;
75
+ ext: string;
76
+ size: number;
77
+ md5: string;
78
+ url: string;
79
+ };
80
+ preview: {
81
+ width: number;
82
+ height: number;
83
+ url: string | null;
84
+ };
85
+ sample: {
86
+ has: boolean;
87
+ width: number;
88
+ height: number;
89
+ url: string | null;
90
+ };
91
+ score: {
92
+ up: number;
93
+ down: number;
94
+ total: number;
95
+ };
96
+ tags: {
97
+ general: string[];
98
+ artist: string[];
99
+ copyright: string[];
100
+ character: string[];
101
+ species: string[];
102
+ invalid: string[];
103
+ meta: string[];
104
+ lore: string[];
105
+ };
106
+ lockedTags: string[];
107
+ changeSeq: number;
108
+ flags: {
109
+ pending: boolean;
110
+ flagged: boolean;
111
+ noteLocked: boolean;
112
+ statusLocked: boolean;
113
+ ratingLocked: boolean;
114
+ deleted: boolean;
115
+ };
116
+ rating: string;
117
+ favCount: number;
118
+ sources: string[];
119
+ pools: number[];
120
+ relationships: {
121
+ parentId: number | null;
122
+ hasChildren: boolean;
123
+ hasActiveChildren: boolean;
124
+ children: number[];
125
+ };
126
+ approverId: number | null;
127
+ uploaderId: number;
128
+ description: string;
129
+ commentCount: number;
130
+ isFavorited: boolean;
131
+ hasNotes: boolean;
132
+ duration: number | null;
133
+ }
134
+
135
+ export function parsePost(post: PostResponse): E621Post {
136
+ return {
137
+ id: post.id,
138
+ createdAt: new Date(post.created_at),
139
+ updatedAt: new Date(post.updated_at),
140
+ file: post.file,
141
+ preview: post.preview,
142
+ sample: post.sample,
143
+ score: post.score,
144
+ tags: post.tags,
145
+ lockedTags: post.locked_tags,
146
+ changeSeq: post.change_seq,
147
+ flags: {
148
+ pending: post.flags.pending,
149
+ flagged: post.flags.flagged,
150
+ noteLocked: post.flags.note_locked,
151
+ statusLocked: post.flags.status_locked,
152
+ ratingLocked: post.flags.rating_locked,
153
+ deleted: post.flags.deleted,
154
+ },
155
+ rating: post.rating,
156
+ favCount: post.fav_count,
157
+ sources: post.sources,
158
+ pools: post.pools,
159
+ relationships: {
160
+ parentId: post.relationships.parent_id,
161
+ hasChildren: post.relationships.has_children,
162
+ hasActiveChildren: post.relationships.has_active_children,
163
+ children: post.relationships.children,
164
+ },
165
+ approverId: post.approver_id,
166
+ uploaderId: post.uploader_id,
167
+ description: post.description,
168
+ commentCount: post.comment_count,
169
+ isFavorited: post.is_favorited,
170
+ hasNotes: post.has_notes,
171
+ duration: post.duration,
172
+ };
173
+ }
@@ -0,0 +1,108 @@
1
+ export interface UserResponse {
2
+ wiki_page_version_count: number;
3
+ artist_version_count: number;
4
+ pool_version_count: number;
5
+ forum_post_count: number;
6
+ comment_count: number;
7
+ flag_count: number;
8
+ favorite_count: number;
9
+ positive_feedback_count: number;
10
+ neutral_feedback_count: number;
11
+ negative_feedback_count: number;
12
+ upload_limit: number;
13
+ profile_about: string;
14
+ profile_artinfo: string;
15
+ id: number;
16
+ created_at: string;
17
+ name: string;
18
+ level: number;
19
+ base_upload_limit: number;
20
+ post_upload_count: number;
21
+ post_update_count: number;
22
+ note_update_count: number;
23
+ is_banned: boolean;
24
+ can_approve_posts: boolean;
25
+ can_upload_free: boolean;
26
+ level_string: string;
27
+ avatar_id: number | null;
28
+ }
29
+
30
+ export interface E621User {
31
+ id: number;
32
+
33
+ profile: {
34
+ name: string;
35
+ level: number;
36
+ about: string;
37
+ artInfo: string;
38
+ avatarId: number | null;
39
+ createdAt: Date;
40
+ levelString: string;
41
+ };
42
+
43
+ counts: {
44
+ wikiPageVersion: number;
45
+ artistVersion: number;
46
+ poolVersion: number;
47
+ forumPost: number;
48
+ comment: number;
49
+ flag: number;
50
+ favorite: number;
51
+ positiveFeedback: number;
52
+ neutralFeedback: number;
53
+ negativeFeedback: number;
54
+ };
55
+
56
+ limits: {
57
+ upload: number;
58
+ baseUpload: number;
59
+ postUpload: number;
60
+ postUpdate: number;
61
+ noteUpdate: number;
62
+ };
63
+
64
+ isBanned: boolean;
65
+ canApprovePosts: boolean;
66
+ canUploadFree: boolean;
67
+ }
68
+
69
+ export function parseUser(user: UserResponse): E621User {
70
+ return {
71
+ id: user.id,
72
+
73
+ profile: {
74
+ name: user.name,
75
+ level: user.level,
76
+ about: user.profile_about,
77
+ artInfo: user.profile_artinfo,
78
+ avatarId: user.avatar_id,
79
+ createdAt: new Date(user.created_at),
80
+ levelString: user.level_string,
81
+ },
82
+
83
+ counts: {
84
+ wikiPageVersion: user.wiki_page_version_count,
85
+ artistVersion: user.artist_version_count,
86
+ poolVersion: user.pool_version_count,
87
+ forumPost: user.forum_post_count,
88
+ comment: user.comment_count,
89
+ flag: user.flag_count,
90
+ favorite: user.favorite_count,
91
+ positiveFeedback: user.positive_feedback_count,
92
+ neutralFeedback: user.neutral_feedback_count,
93
+ negativeFeedback: user.negative_feedback_count,
94
+ },
95
+
96
+ limits: {
97
+ upload: user.upload_limit,
98
+ baseUpload: user.base_upload_limit,
99
+ postUpload: user.post_upload_count,
100
+ postUpdate: user.post_update_count,
101
+ noteUpdate: user.note_update_count,
102
+ },
103
+
104
+ isBanned: user.is_banned,
105
+ canApprovePosts: user.can_approve_posts,
106
+ canUploadFree: user.can_upload_free,
107
+ };
108
+ }
@@ -0,0 +1,13 @@
1
+ import { PostResponse } from "./e621/E621Post";
2
+
3
+ export type GetFavoritesResponse = {
4
+ posts: PostResponse[] | null;
5
+ };
6
+
7
+ export type GetPostResponse = {
8
+ post: PostResponse | null;
9
+ };
10
+
11
+ export type GetPostsResponse = {
12
+ posts: PostResponse[];
13
+ };
package/src/utils.ts ADDED
@@ -0,0 +1,19 @@
1
+ export function ensureArray<T>(value: T | T[]): T[] {
2
+ if (Array.isArray(value)) {
3
+ return value;
4
+ }
5
+ return [value];
6
+ }
7
+
8
+ export function translateOptions<Options extends Record<string, string>>(
9
+ options: Options,
10
+ table: Partial<Options>
11
+ ): Record<string, string> {
12
+ const params: Record<string, string> = {};
13
+
14
+ for (const [key, value] of Object.entries(options)) {
15
+ params[table[key] ?? key] = value;
16
+ }
17
+
18
+ return params;
19
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,109 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
+
27
+ /* Modules */
28
+ "module": "commonjs" /* Specify what module code is generated. */,
29
+ // "rootDir": "./", /* Specify the root folder within your source files. */
30
+ // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
+ // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39
+ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40
+ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41
+ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42
+ // "resolveJsonModule": true, /* Enable importing .json files. */
43
+ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
45
+
46
+ /* JavaScript Support */
47
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50
+
51
+ /* Emit */
52
+ "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
53
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58
+ "outDir": "./dist" /* Specify an output folder for all emitted files. */,
59
+ // "removeComments": true, /* Disable emitting comments. */
60
+ // "noEmit": true, /* Disable emitting files from a compilation. */
61
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
69
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75
+
76
+ /* Interop Constraints */
77
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78
+ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80
+ "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
81
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82
+ "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
83
+
84
+ /* Type Checking */
85
+ "strict": true /* Enable all strict type-checking options. */,
86
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104
+
105
+ /* Completeness */
106
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
108
+ }
109
+ }