-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathrequest.ts
More file actions
238 lines (192 loc) · 7.68 KB
/
request.ts
File metadata and controls
238 lines (192 loc) · 7.68 KB
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
"use strict";
import { isElectron } from "./utils.js";
import log from "./log.js";
import url from "url";
import syncOptions from "./sync_options.js";
import type { ExecOpts } from "./request_interface.js";
// this service provides abstraction over node's HTTP/HTTPS and electron net.client APIs
// this allows supporting system proxy
interface ClientOpts {
method: string;
url: string;
protocol?: string | null;
host?: string | null;
port?: string | null;
path?: string | null;
timeout?: number;
headers?: Record<string, string | number>;
agent?: any;
proxy?: string | null;
}
type RequestEvent = "error" | "response" | "abort";
interface Request {
on(event: RequestEvent, cb: (e: any) => void): void;
end(payload?: string): void;
}
interface Client {
request(opts: ClientOpts): Request;
}
async function exec<T>(opts: ExecOpts): Promise<T> {
const client = getClient(opts);
// hack for cases where electron.net does not work, but we don't want to set proxy
if (opts.proxy === "noproxy") {
opts.proxy = null;
}
const paging = opts.paging || {
pageCount: 1,
pageIndex: 0,
requestId: "n/a"
};
const proxyAgent = await getProxyAgent(opts);
const parsedTargetUrl = url.parse(opts.url);
return new Promise(async (resolve, reject) => {
try {
const headers: Record<string, string | number> = {
Cookie: (opts.cookieJar && opts.cookieJar.header) || "",
"Content-Type": paging.pageCount === 1 ? "application/json" : "text/plain",
pageCount: paging.pageCount,
pageIndex: paging.pageIndex,
requestId: paging.requestId
};
if (opts.auth) {
headers["trilium-cred"] = Buffer.from(`dummy:${opts.auth.password}`).toString("base64");
if (opts.auth.totpToken) {
headers["trilium-totp"] = opts.auth.totpToken;
}
}
const request = (await client).request({
method: opts.method,
// url is used by electron net module
url: opts.url,
// 4 fields below are used by http and https node modules
protocol: parsedTargetUrl.protocol,
host: parsedTargetUrl.hostname,
port: parsedTargetUrl.port,
path: parsedTargetUrl.path,
timeout: opts.timeout, // works only for node.js client
headers,
agent: proxyAgent
});
request.on("error", (err) => reject(generateError(opts, err)));
request.on("response", (response) => {
if (opts.cookieJar && response.headers["set-cookie"]) {
opts.cookieJar.header = response.headers["set-cookie"];
}
let responseStr = "";
let chunks: Buffer[] = [];
response.on("data", (chunk: Buffer) => chunks.push(chunk));
response.on("end", () => {
// use Buffer instead of string concatenation to avoid implicit decoding for each chunk
// decode the entire data chunks explicitly as utf-8
responseStr = Buffer.concat(chunks).toString("utf-8");
if ([200, 201, 204].includes(response.statusCode)) {
try {
const jsonObj = responseStr.trim() ? JSON.parse(responseStr) : null;
resolve(jsonObj);
} catch (e: any) {
log.error(`Failed to deserialize sync response: ${responseStr}`);
reject(generateError(opts, e.message));
}
} else {
let errorMessage;
try {
const jsonObj = JSON.parse(responseStr);
errorMessage = jsonObj?.message || "";
} catch (e: any) {
errorMessage = responseStr.substr(0, Math.min(responseStr.length, 100));
}
reject(generateError(opts, `${response.statusCode} ${response.statusMessage} ${errorMessage}`));
}
});
});
let payload;
if (opts.body) {
payload = typeof opts.body === "object" ? JSON.stringify(opts.body) : opts.body;
}
request.end(payload as string);
} catch (e: any) {
reject(generateError(opts, e.message));
}
});
}
async function getImage(imageUrl: string): Promise<Buffer> {
const proxyConf = syncOptions.getSyncProxy();
const opts: ClientOpts = {
method: "GET",
url: imageUrl,
proxy: proxyConf !== "noproxy" ? proxyConf : null
};
const client = await getClient(opts);
const proxyAgent = await getProxyAgent(opts);
const parsedTargetUrl = url.parse(opts.url);
return new Promise<Buffer>((resolve, reject) => {
try {
const request = client.request({
method: opts.method,
// url is used by electron net module
url: opts.url,
// 4 fields below are used by http and https node modules
protocol: parsedTargetUrl.protocol,
host: parsedTargetUrl.hostname,
port: parsedTargetUrl.port,
path: parsedTargetUrl.path,
timeout: opts.timeout, // works only for the node client
headers: {},
agent: proxyAgent
});
request.on("error", (err) => reject(generateError(opts, err)));
request.on("abort", (err) => reject(generateError(opts, err)));
request.on("response", (response) => {
if (![200, 201, 204].includes(response.statusCode)) {
reject(generateError(opts, `${response.statusCode} ${response.statusMessage}`));
}
const chunks: Buffer[] = [];
response.on("data", (chunk: Buffer) => chunks.push(chunk));
response.on("end", () => resolve(Buffer.concat(chunks)));
});
request.end(undefined);
} catch (e: any) {
reject(generateError(opts, e.message));
}
});
}
const HTTP = "http:",
HTTPS = "https:";
async function getProxyAgent(opts: ClientOpts) {
if (!opts.proxy) {
return null;
}
const { protocol } = url.parse(opts.url);
if (!protocol || ![HTTP, HTTPS].includes(protocol)) {
return null;
}
const AgentClass = HTTP === protocol ? (await import("http-proxy-agent")).HttpProxyAgent : (await import("https-proxy-agent")).HttpsProxyAgent;
return new AgentClass(opts.proxy);
}
async function getClient(opts: ClientOpts): Promise<Client> {
// it's not clear how to explicitly configure proxy (as opposed to system proxy),
// so in that case, we always use node's modules
if (isElectron && !opts.proxy) {
return (await import("electron")).net as unknown as Client;
} else {
const { protocol } = url.parse(opts.url);
if (protocol === "http:" || protocol === "https:") {
return await import(protocol.substr(0, protocol.length - 1));
} else {
throw new Error(`Unrecognized protocol '${protocol}'`);
}
}
}
function generateError(
opts: {
method: string;
url: string;
},
message: string
) {
return new Error(`Request to ${opts.method} ${opts.url} failed, error: ${message}`);
}
export default {
exec,
getImage
};