-
Notifications
You must be signed in to change notification settings - Fork 3
/
nopecha.js
258 lines (213 loc) · 6.25 KB
/
nopecha.js
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
"use strict";
const fetch = (...args) => import("node-fetch").then(({default: fetch}) => fetch(...args));
function sleep(t) {
return new Promise(resolve => setTimeout(resolve, t));
}
class NopeCHAError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
class InvalidRequestError extends NopeCHAError {
constructor(message) {
super(message);
}
}
class IncompleteJobError extends NopeCHAError {
constructor(message) {
super(message);
}
}
class RateLimitError extends NopeCHAError {
constructor(message) {
super(message);
}
}
class AuthenticationError extends NopeCHAError {
constructor(message) {
super(message);
}
}
class UnavailableFeatureError extends NopeCHAError {
constructor(message) {
super(message);
}
}
class InsufficientCreditError extends NopeCHAError {
constructor(message) {
super(message);
}
}
class UnknownError extends NopeCHAError {
constructor(message) {
super(message);
}
}
class Timeout extends NopeCHAError {
constructor(message) {
super(message);
}
}
class APIError extends NopeCHAError {
constructor(message) {
super(message);
}
}
class ServiceUnavailableError extends NopeCHAError {
constructor(message) {
super(message);
}
}
class Configuration {
constructor({apiKey, apiBase}) {
this.apiKey = apiKey;
this.apiBase = apiBase;
if (!this.apiKey) {
throw new Error("Invalid api key");
}
if (!this.apiBase) {
this.apiBase = "https://api.nopecha.com";
}
}
}
class NopeCHAApi {
constructor(configuration) {
this.apiKey = configuration.apiKey;
this.apiBase = configuration.apiBase;
}
default_headers() {
const user_agent = "NopeCHA NodeBindings";
const ua = {
"httplib": "node-fetch",
"lang": "node",
"lang_version": process.version,
"platform": process.platform,
"publisher": "nopecha",
};
return {
"Authorization": `Bearer ${this.apiKey}`,
"X-NopeCHA-Client-User-Agent": JSON.stringify(ua),
"User-Agent": user_agent,
};
}
get_headers() {
return this.default_headers();
}
post_headers() {
const headers = this.default_headers();
headers["Content-Type"] = "application/json";
return headers;
}
handle_error_response(rcode, resp) {
const error_data = "message" in resp ? resp.message : resp.error;
if (rcode === 429) {
return new RateLimitError(error_data);
} else if (rcode === 400) {
return new InvalidRequestError(error_data);
} else if (rcode === 401) {
return new AuthenticationError(error_data);
} else if (rcode === 402) {
return new UnavailableFeatureError(error_data);
} else if (rcode === 403) {
return new InsufficientCreditError(error_data);
} else if (rcode === 409) {
return new IncompleteJobError(error_data);
} else {
return new UnknownError(error_data);
}
}
async get(endpoint, data, retries, interval) {
const params = new URLSearchParams(data).toString();
for (let i = 0; i < retries; i++) {
await sleep(interval*1000);
const r = await fetch(`${this.apiBase}${endpoint}?${params}`, {
headers: this.get_headers(),
});
const status = r.status;
let response;
if (status === 503) {
response = ServiceUnavailableError("The server is overloaded or not ready yet.");
} else {
response = await r.json();
if ("error" in response) {
response = this.handle_error_response(status, response);
if (response instanceof IncompleteJobError) {
continue;
}
}
}
return response;
}
throw new Timeout('Failed to get results');
}
async post(endpoint, data) {
const r = await fetch(`${this.apiBase}${endpoint}`, {
method: "POST",
headers: this.post_headers(),
body: JSON.stringify(data),
});
const status = r.status;
let response;
if (status === 503) {
response = ServiceUnavailableError("The server is overloaded or not ready yet.");
} else {
response = await r.json();
if ("error" in response) {
response = this.handle_error_response(status, response);
}
}
return response;
}
async solve(endpoint, data, retries, interval) {
let r = await this.post(endpoint, data);
if (r instanceof NopeCHAError) {
throw r;
}
// console.log('POST', r);
r = await this.get(endpoint, {id: r.data}, retries, interval);
if (r instanceof NopeCHAError) {
throw r;
}
// console.log('GET', r);
return r.data;
}
async solveRecognition(data) {
return await this.solve('/', data, 120, 1);
}
async solveToken(data) {
return await this.solve('/token', data, 180, 1);
}
async getBalance() {
const r = await fetch(`${this.apiBase}/status`, {
headers: this.get_headers(),
});
const status = r.status;
let response;
if (status === 503) {
response = ServiceUnavailableError("The server is overloaded or not ready yet.");
} else {
response = await r.json();
if ("error" in response) {
throw this.handle_error_response(status, response);
}
}
return response;
}
}
module.exports = {
Configuration,
NopeCHAApi,
NopeCHAError,
InvalidRequestError,
IncompleteJobError,
RateLimitError,
AuthenticationError,
UnavailableFeatureError,
InsufficientCreditError,
UnknownError,
Timeout,
APIError,
ServiceUnavailableError,
};