-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
Copy pathClipperServer.ts
246 lines (202 loc) · 6.85 KB
/
ClipperServer.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
import Setting from './models/Setting';
import Logger from './Logger';
import Api, { RequestFile } from './services/rest/Api';
import ApiResponse from './services/rest/ApiResponse';
const urlParser = require('url');
const { randomClipperPort, startPort } = require('./randomClipperPort');
const enableServerDestroy = require('server-destroy');
const multiparty = require('multiparty');
export enum StartState {
Idle = 'idle',
Starting = 'starting',
Started = 'started',
}
export default class ClipperServer {
private logger_: Logger;
private startState_: StartState = StartState.Idle;
private server_: any = null;
private port_: number = null;
private api_: Api = null;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
private dispatch_: Function;
private static instance_: ClipperServer = null;
public constructor() {
this.logger_ = new Logger();
}
public static instance() {
if (this.instance_) return this.instance_;
this.instance_ = new ClipperServer();
return this.instance_;
}
public get api(): Api {
return this.api_;
}
public initialize(actionApi: any = null) {
this.api_ = new Api(() => {
return Setting.value('api.token');
}, (action: any) => { this.dispatch(action); }, actionApi);
}
public setLogger(l: Logger) {
this.logger_ = l;
}
public logger() {
return this.logger_;
}
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
public setDispatch(d: Function) {
this.dispatch_ = d;
}
public dispatch(action: any) {
if (!this.dispatch_) throw new Error('dispatch not set!');
this.dispatch_(action);
}
public setStartState(v: StartState) {
if (this.startState_ === v) return;
this.startState_ = v;
this.dispatch({
type: 'CLIPPER_SERVER_SET',
startState: v,
});
}
public setPort(v: number) {
if (this.port_ === v) return;
this.port_ = v;
this.dispatch({
type: 'CLIPPER_SERVER_SET',
port: v,
});
}
public async findAvailablePort() {
const tcpPortUsed = require('tcp-port-used');
let state = null;
for (let i = 0; i < 10000; i++) {
state = randomClipperPort(state, Setting.value('env'));
const inUse = await tcpPortUsed.check(state.port);
if (!inUse) return state.port;
}
throw new Error('All potential ports are in use or not available.');
}
public async isRunning() {
const tcpPortUsed = require('tcp-port-used');
const port = Setting.value('api.port') ? Setting.value('api.port') : startPort(Setting.value('env'));
const inUse = await tcpPortUsed.check(port);
return inUse ? port : 0;
}
public async start() {
this.setPort(null);
this.setStartState(StartState.Starting);
const settingPort = Setting.value('api.port');
try {
const p = settingPort ? settingPort : await this.findAvailablePort();
this.setPort(p);
} catch (error) {
this.setStartState(StartState.Idle);
this.logger().error(error);
return;
}
this.server_ = require('http').createServer();
this.server_.on('request', async (request: any, response: any) => {
const writeCorsHeaders = (code: any, contentType = 'application/json', additionalHeaders: any = null) => {
const headers = {
'Content-Type': contentType,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers': 'X-Requested-With,content-type',
...(additionalHeaders ? additionalHeaders : {}),
};
response.writeHead(code, headers);
};
const writeResponseJson = (code: any, object: any) => {
writeCorsHeaders(code);
response.write(JSON.stringify(object));
response.end();
};
const writeResponseText = (code: any, text: any) => {
writeCorsHeaders(code, 'text/plain');
response.write(text);
response.end();
};
const writeResponseInstance = (code: any, instance: any) => {
if (instance.type === 'attachment') {
const filename = instance.attachmentFilename ? instance.attachmentFilename : 'file';
writeCorsHeaders(code, instance.contentType ? instance.contentType : 'application/octet-stream', {
'Content-disposition': `attachment; filename=${filename}`,
'Content-Length': instance.body.length,
});
response.end(instance.body);
} else {
throw new Error('Not implemented');
}
};
const writeResponse = (code: any, response: any) => {
if (response instanceof ApiResponse) {
writeResponseInstance(code, response);
} else if (typeof response === 'string') {
writeResponseText(code, response);
} else if (response === null || response === undefined) {
writeResponseText(code, '');
} else {
writeResponseJson(code, response);
}
};
this.logger().info(`Request: ${request.method} ${request.url}`);
const url = urlParser.parse(request.url, true);
const execRequest = async (request: any, body = '', files: RequestFile[] = []) => {
try {
const response = await this.api_.route(request.method, url.pathname, url.query, body, files);
writeResponse(200, response);
} catch (error) {
this.logger().error(error);
const httpCode = error.httpCode ? error.httpCode : 500;
const msg = [];
if (httpCode >= 500) msg.push('Internal Server Error');
if (error.message) msg.push(error.message);
if (error.stack) msg.push(`\n\n${error.stack}`);
writeResponse(httpCode, { error: msg.join(': ') });
}
};
const contentType = request.headers['content-type'] ? request.headers['content-type'] : '';
if (request.method === 'OPTIONS') {
writeCorsHeaders(200);
response.end();
} else {
if (contentType.indexOf('multipart/form-data') === 0) {
const form = new multiparty.Form();
form.parse(request, (error: any, fields: any, files: any) => {
if (error) {
writeResponse(error.httpCode ? error.httpCode : 500, error.message);
return;
} else {
void execRequest(request, fields && fields.props && fields.props.length ? fields.props[0] : '', files && files.data ? files.data : []);
}
});
} else {
if (request.method === 'POST' || request.method === 'PUT') {
let body = '';
request.on('data', (data: any) => {
body += data;
});
request.on('end', async () => {
void execRequest(request, body);
});
} else {
void execRequest(request);
}
}
}
});
enableServerDestroy(this.server_);
this.logger().info(`Starting Clipper server on port ${this.port_}`);
this.server_.listen(this.port_, '127.0.0.1');
this.setStartState(StartState.Started);
// We return an empty promise that never resolves so that it's possible to `await` the server indefinitely.
// This is used only in command-server.js
return new Promise(() => {});
}
public async stop() {
this.server_.destroy();
this.server_ = null;
this.setStartState(StartState.Idle);
this.setPort(null);
}
}