This repository has been archived by the owner on Feb 4, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
382 lines (336 loc) · 10.9 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import phin from "phin";
import util from "util";
import pkg from "./package.json";
import * as fs from "fs";
import qs from "querystring";
export class APIError extends Error {
constructor(err: string, message: string, response?: any) {
response ? super(`${err}, ${message}, response: ${util.inspect(response, { depth: 1 })}`) : super(`${err}, ${message}`);
this.name = "APIError";
}
}
// a lot of changes and removes due to e621 api changes
export interface E621Post {
id: number;
created_at: string; // ISO timestamp
updated_at: string; // ISO timestamp
file: {
width: number;
height: number;
ext: string;
size: number;
md5: string;
url: string;
};
preview: {
width: number;
height: number;
url: string;
};
sample: {
has: boolean;
height: number;
width: number;
url: string;
};
score: {
up: number;
down: number;
total: number;
};
tags: {
[k in "general" | "species" | "character" | "copyright" | "artist" | "invalid" | "lore" | "meta"]: string[];
};
locked_tags: string[]; // @TODO
change_seq: number;
flags: {
[k in "pending" | "flagged" | "note_locked" | "status_locked" | "rating_locked" | "deleted"]: boolean;
};
rating: "s" | "q" | "e";
fav_count: number;
sources: string[];
pools: number[];
relationships: {
parent_id?: number;
has_childeren: boolean;
has_active_childeren: boolean;
childeren: number[];
};
approver_id?: number;
uploader_id?: number;
description: string;
comment_count: number;
is_favorited: boolean;
}
export class E6API {
apiKey: string;
userAgent: string;
constructor(options?: {
apiKey?: string;
userAgent?: string;
}) {
if (!options) options = {};
if (!options.apiKey) options.apiKey = "";
if (!options.userAgent) options.userAgent = `E6API/${pkg.version} (https://github.com/FurryBotCo/E6API)`;
this.apiKey = options.apiKey;
this.userAgent = options.userAgent;
}
/*async login(user: string, pass: string) {
return phin({
method: "GET",
url: `https://e621.net/user/login.json?name=${user}&password=${pass}`,
headers: {
"User-Agent": this.userAgent
}
}).then(res => {
if (res.statusCode !== 200) throw new APIError(`${res.statusCode} ${res.statusMessage}`, res.body.toString());
const b = JSON.parse(res.body.toString());
return this.apiKey = b.password_hash;
}).catch(err => {
throw err;
});
}*/
// not implemented yet
/*async createPost(post: {
tags: string[];
file: fs.WriteStream;
upload_url?: string;
rating: "safe" | "questionable" | "explicit";
source: string[];
description?: string;
is_rating_locked?: boolean;
is_note_locked?: boolean;
parent_id?: number;
} | {
tags: string[];
file?: fs.WriteStream;
upload_url: string;
rating: "safe" | "questionable" | "explicit";
source: string[];
description?: string;
is_rating_locked?: boolean;
is_note_locked?: boolean;
parent_id?: number;
}): Promise<any> {
}*/
// not tested/finished yet
/*async updatePost(id: number, post: {
tags?: string[];
old_tags?: string[];
rating?: "safe" | "questionable" | "explicit";
source?: string[];
description?: string;
is_rating_locked?: boolean;
is_note_locked?: boolean;
parent_id?: number;
}, reason: string) {
return phin({
method: "POST",
url: "https://e621.net/post/update.json",
data: {
id,
post,
reason
},
parse: "json"
}).then(res => {
if (res.statusCode !== 200) throw new APIError(`${res.statusCode} ${res.statusMessage}`, res.body);
else return res.body;
}).catch(err => {
throw err;
});
}*/
getPostById(id: number, fetchImage?: false): Promise<E621Post>;
getPostById(id: number, fetchImage?: true): Promise<{ image: Buffer; post: E621Post }>;
async getPostById(id: number, fetchImage?: boolean) {
if (typeof fetchImage !== "boolean") fetchImage = false;
return phin({
method: "GET",
url: `https://e621.net/posts/${id}.json`,
headers: {
"User-Agent": this.userAgent
}
}).then(async (res) => {
if (res.statusCode === 404) return null/*throw new APIError(`${res.statusCode} ${res.statusMessage}`, "invalid post id")*/;
if (res.statusCode !== 200) throw new APIError(`${res.statusCode} ${res.statusMessage}`, res.body.toString());
const b = JSON.parse(res.body.toString());
if (fetchImage) return {
image: await phin(b.post.file_url).then(i => i.body),
post: b.post
};
else return b.post;
}).catch(err => {
throw err;
});
}
/*getPostByMD5(md5: string, fetchImage?: false): Promise<E621Post>;
getPostByMD5(md5: string, fetchImage?: true): Promise<{ image: Buffer; post: E621Post }>;
async getPostByMD5(md5: string, fetchImage?: boolean) {
if (typeof fetchImage !== "boolean") fetchImage = false;
return phin({
method: "GET",
url: `https://e621.net/post/check_md5.json?md5=${md5}`,
headers: {
"User-Agent": this.userAgent
}
}).then(async (res): Promise<any> => {
if (res.statusCode === 404) return null;
if (res.statusCode !== 200) throw new APIError(`${res.statusCode} ${res.statusMessage}`, res.body.toString());
const b = JSON.parse(res.body.toString());
if (!b.exists) return null;
return fetchImage ? this.getPostById(b.post_id, fetchImage as true) : this.getPostById(b.post_id, fetchImage as false);
});
}*/
/*async getPostTagsById(id: number): Promise<{ id: number; tags: E621Tag[] }> {
return phin({
method: "GET",
url: `https://e621.net/posts/${id}.json`,
headers: {
"User-Agent": this.userAgent
}
}).then(res => {
if (res.statusCode === 404) return null;
if (res.statusCode !== 200) throw new APIError(`${res.statusCode} ${res.statusMessage}`, res.body.toString());
const b = JSON.parse(res.body.toString());
return {
id,
tags: b.tags
};
}).catch(err => {
throw err;
});
}*/
async getPostByMD5(md5: string): Promise<E621Post> {
return phin({
method: "GET",
url: `https://e621.net/posts.json?md5=${md5}`,
headers: {
"User-Agent": this.userAgent
}
}).then(res => {
if (res.statusCode === 404) return null;
if (res.statusCode !== 200) throw new APIError(`${res.statusCode} ${res.statusMessage}`, res.body.toString());
return JSON.parse(res.body.toString()).post;
}).catch(err => {
throw err;
});
}
async listPosts(tags?: string[], limit?: number, page?: number, beforeId?: number, filterTags?: string[]): Promise<E621Post[]> {
const q: {
tags?: string;
limit?: number;
page?: number;
before_id?: number;
} = {};
if (filterTags) filterTags = filterTags.map(t => t.startsWith("-") ? t.slice(1, t.length) : t);
if (tags && filterTags) if (tags.some(t => filterTags.map(t => t.startsWith("-") ? t.slice(1, t.length).toLowerCase() : t.toLowerCase()).includes(t.toLowerCase()))) throw new TypeError("'tags' conatins a tag that is listed in 'filterTags'");
if (tags && tags.length > 0) {
if (tags.length > 40) throw new TypeError("you cannot use more than 40 tags");
else q.tags = tags.join(" ");
if (filterTags && tags.some(t => filterTags.map(t => t.startsWith("-") ? t.slice(1, t.length).toLowerCase() : t.toLowerCase()).includes(t.toLowerCase()))) throw new TypeError("'tags' conatins a tag that is listed in 'filterTags'");
}
if (limit && limit > 0 && limit < 320) q.limit = limit;
if (page && page > 0 && page < 750) q.page = page;
if (beforeId) q.before_id = beforeId;
return phin({
method: "GET",
url: `https://e621.net/posts.json${Object.keys(q).length > 0 ? `?${qs.encode(q)}` : ""}`,
headers: {
"User-Agent": this.userAgent
}
}).then(res => {
if (res.statusCode === 404) return null;
if (res.statusCode !== 200) throw new APIError(`${res.statusCode} ${res.statusMessage}`, res.body.toString());
const b = JSON.parse(res.body.toString()).posts;
return filterTags && filterTags.length > 0 ? b.filter((p: E621Post) => !filterTags.some(t => Object.values(p.tags).reduce((a, b) => a.concat(b)).includes(t))) : b;
}).catch(err => {
throw err;
});
}
// flagPost(id: number, flagOption: "inferior", inferiorParent: number): Promise<boolean>;
// flagPost(id: number, flagOption: "uploader" | "inferior" | 1 | 2 | 3 | 4 | 5 | 6): Promise<boolean>;
// untested
/*async flagPost(id: number, flagOption: "uploader" | "inferior" | 1 | 2 | 3 | 4 | 5 | 6, inferiorParent?) {
return phin({
method: "GET",
url: `https://e621.net/post/flag.json?id=${id}&flag_option=${flagOption}${flagOption === "inferior" ? `&inferior_parent=${inferiorParent}` : ""}`,
headers: {
"Authorization": this.apiKey,
"User-Agent": this.userAgent
},
parse: "json"
}).then(res => {
if (res.statusCode === 404) return false;
else if (res.statusCode !== 200) throw new APIError(`${res.statusCode} ${res.statusMessage}`, res.body);
return true;
}).catch(err => {
throw err;
});
}*/
// untested
/*async deletePost(id: number, reason: string, permanent: boolean): Promise<boolean> {
return phin({
method: "GET",
url: `https://e621.net/post/delete.json?id=${id}&reason=${reason}`,
headers: {
"Authorization": this.apiKey,
"User-Agent": this.userAgent
},
parse: "json"
}).then(async (res) => {
if (res.statusCode === 404) return null;
else if (res.statusCode !== 200) throw new APIError(`${res.statusCode} ${res.statusMessage}`, res.body);
if (permanent) return phin({
method: "GET",
url: `https://e621.net/post/delete.json?id=${id}&reason=${reason}&mode=1`,
headers: {
"Authorization": this.apiKey,
"User-Agent": this.userAgent
},
parse: "json"
}).then(res => {
if (res.statusCode === 404) return null;
else if (res.statusCode !== 200) throw new APIError(`${res.statusCode} ${res.statusMessage}`, res.body);
return true;
});
return true;
}).catch(err => {
throw err;
});
}*/
/*async getDeletedPosts(page?: number, userId?: number): Promise<{ id: number; creator_id: number; author?: string; tags: string; delreason: string; }[]> {
return phin({
method: "GET",
url: `https://e621.net/post/deleted_index.json${page || userId ? `?${page ? `page=${page}${userId ? `&user_id=${userId}` : ""}` : ""}` : ""}`,
headers: {
"User-Agent": this.userAgent
}
}).then(res => {
if (res.statusCode === 404) return null;
if (res.statusCode !== 200) throw new APIError(`${res.statusCode} ${res.statusMessage}`, res.body.toString());
const b = JSON.parse(res.body.toString());
return b;
}).catch(err => {
throw err;
});
}*/
async getPopularPosts(type: "day" | "week" | "month"): Promise<E621Post[]> {
return phin({
method: "GET",
url: `https://e621.net/explore/posts/popular.json?scale=${type}`,
headers: {
"User-Agent": this.userAgent
}
}).then(res => {
if (res.statusCode === 404) return null;
if (res.statusCode !== 200) throw new APIError(`${res.statusCode} ${res.statusMessage}`, res.body.toString());
const b = JSON.parse(res.body.toString()).posts;
return b;
}).then(err => {
throw err;
});
}
/*async revertPostTags(id: number, historyId: number) {
}*/
}
export default E6API;