1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-11-27 08:21:03 +02:00
joplin/packages/lib/ClipperServer.ts

260 lines
8.2 KiB
TypeScript
Raw Permalink Normal View History

import Setting from './models/Setting';
import Logger from '@joplin/utils/Logger';
import Api, { RequestFile } from './services/rest/Api';
import ApiResponse from './services/rest/ApiResponse';
2019-07-29 15:43:53 +02:00
const urlParser = require('url');
2020-11-05 18:58:23 +02:00
const { randomClipperPort, startPort } = require('./randomClipperPort');
const enableServerDestroy = require('server-destroy');
2018-09-28 20:24:57 +02:00
const multiparty = require('multiparty');
2018-05-16 15:16:14 +02:00
export enum StartState {
Idle = 'idle',
Starting = 'starting',
Started = 'started',
}
export default class ClipperServer {
private logger_: Logger;
private startState_: StartState = StartState.Idle;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
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_;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
public initialize(actionApi: any = null) {
this.api_ = new Api(() => {
return Setting.value('api.token');
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
}, (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;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
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;
}
2019-07-29 15:43:53 +02:00
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 null;
}
2018-05-16 15:16:14 +02:00
this.server_ = require('http').createServer();
2018-05-16 15:16:14 +02:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
this.server_.on('request', async (request: any, response: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
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 : {}),
};
2018-09-30 11:15:46 +02:00
response.writeHead(code, headers);
2019-07-29 15:43:53 +02:00
};
2018-05-16 15:16:14 +02:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const writeResponseJson = (code: any, object: any) => {
2018-05-16 15:16:14 +02:00
writeCorsHeaders(code);
response.write(JSON.stringify(object));
response.end();
2019-07-29 15:43:53 +02:00
};
2018-05-16 15:16:14 +02:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const writeResponseText = (code: any, text: any) => {
writeCorsHeaders(code, 'text/plain');
response.write(text);
response.end();
2019-07-29 15:43:53 +02:00
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const writeResponseInstance = (code: any, instance: any) => {
2019-07-29 15:43:53 +02:00
if (instance.type === 'attachment') {
const filename = instance.attachmentFilename ? instance.attachmentFilename : 'file';
writeCorsHeaders(code, instance.contentType ? instance.contentType : 'application/octet-stream', {
2019-09-19 23:51:18 +02:00
'Content-disposition': `attachment; filename=${filename}`,
2019-07-29 15:43:53 +02:00
'Content-Length': instance.body.length,
});
response.end(instance.body);
} else {
throw new Error('Not implemented');
}
};
2018-09-30 11:15:46 +02:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const writeResponse = (code: any, response: any) => {
2018-09-30 11:15:46 +02:00
if (response instanceof ApiResponse) {
2019-07-29 15:43:53 +02:00
writeResponseInstance(code, response);
2018-09-30 11:15:46 +02:00
} else if (typeof response === 'string') {
writeResponseText(code, response);
} else if (response === null || response === undefined) {
writeResponseText(code, '');
} else {
writeResponseJson(code, response);
}
2019-07-29 15:43:53 +02:00
};
2018-05-16 15:16:14 +02:00
2019-09-19 23:51:18 +02:00
this.logger().info(`Request: ${request.method} ${request.url}`);
2018-05-16 15:16:14 +02:00
const url = urlParser.parse(request.url, true);
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const execRequest = async (request: any, body = '', files: RequestFile[] = []) => {
try {
2018-09-28 20:24:57 +02:00
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(': ') });
}
2019-07-29 15:43:53 +02:00
};
2018-09-28 20:24:57 +02:00
const contentType = request.headers['content-type'] ? request.headers['content-type'] : '';
if (request.method === 'OPTIONS') {
writeCorsHeaders(200);
response.end();
} else {
2018-09-28 20:24:57 +02:00
if (contentType.indexOf('multipart/form-data') === 0) {
2019-07-29 15:43:53 +02:00
const form = new multiparty.Form();
2018-09-28 20:24:57 +02:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
form.parse(request, (error: any, fields: any, files: any) => {
2019-07-29 15:43:53 +02:00
if (error) {
2018-09-28 20:24:57 +02:00
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 : []);
2018-09-28 20:24:57 +02:00
}
2019-07-29 15:43:53 +02:00
});
2018-05-16 15:16:14 +02:00
} else {
if (request.method === 'POST' || request.method === 'PUT') {
2018-09-28 20:24:57 +02:00
let body = '';
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
request.on('data', (data: any) => {
2018-09-28 20:24:57 +02:00
body += data;
});
request.on('end', async () => {
void execRequest(request, body);
2018-09-28 20:24:57 +02:00
});
} else {
void execRequest(request);
2018-09-28 20:24:57 +02:00
}
2018-05-16 15:16:14 +02:00
}
}
});
enableServerDestroy(this.server_);
2019-09-19 23:51:18 +02:00
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(() => {});
}
2018-05-16 15:16:14 +02:00
public async stop() {
this.server_.destroy();
this.server_ = null;
this.setStartState(StartState.Idle);
this.setPort(null);
2018-05-16 15:16:14 +02:00
}
}