Files
Trilium/src/public/app/services/server.ts

270 lines
8.0 KiB
TypeScript
Raw Normal View History

import utils from './utils.js';
import ValidationError from "./validation_error.js";
2024-07-25 00:23:29 +03:00
type Headers = Record<string, string | null | undefined>;
type Method = string;
interface Response {
headers: Headers;
body: unknown;
}
interface Arg extends Response {
statusCode: number;
method: Method;
url: string;
requestId: string;
}
interface RequestData {
resolve: (value: unknown) => any;
reject: (reason: unknown) => any;
silentNotFound: boolean;
}
async function getHeaders(headers?: Headers) {
2022-12-01 13:07:23 +01:00
const appContext = (await import('../components/app_context.js')).default;
2021-05-22 12:35:41 +02:00
const activeNoteContext = appContext.tabManager ? appContext.tabManager.getActiveContext() : null;
2020-11-23 22:52:48 +01:00
// headers need to be lowercase because node.js automatically converts them to lower case
// also avoiding using underscores instead of dashes since nginx filters them out by default
2024-07-25 00:23:29 +03:00
const allHeaders: Headers = {
'trilium-component-id': glob.componentId,
'trilium-local-now-datetime': utils.localNowDateTime(),
2021-05-22 12:26:45 +02:00
'trilium-hoisted-note-id': activeNoteContext ? activeNoteContext.hoistedNoteId : null,
2020-01-28 21:54:28 +01:00
'x-csrf-token': glob.csrfToken
};
2020-01-28 21:54:28 +01:00
for (const headerName in headers) {
if (headers[headerName]) {
allHeaders[headerName] = headers[headerName];
}
}
if (utils.isElectron()) {
// passing it explicitly here because of the electron HTTP bypass
2019-10-19 15:12:25 +02:00
allHeaders.cookie = document.cookie;
}
2019-10-19 15:12:25 +02:00
return allHeaders;
}
2024-07-25 00:23:29 +03:00
async function getWithSilentNotFound<T>(url: string, componentId?: string) {
return await call<T>('GET', url, componentId, { silentNotFound: true });
}
2024-07-25 00:23:29 +03:00
async function get<T>(url: string, componentId?: string) {
return await call<T>('GET', url, componentId);
}
async function post<T>(url: string, data?: unknown, componentId?: string) {
2024-07-25 00:23:29 +03:00
return await call<T>('POST', url, componentId, { data });
}
2024-07-25 00:23:29 +03:00
async function put<T>(url: string, data: unknown, componentId?: string) {
return await call<T>('PUT', url, componentId, { data });
}
2024-07-25 00:23:29 +03:00
async function patch<T>(url: string, data: unknown, componentId?: string) {
return await call<T>('PATCH', url, componentId, { data });
2022-01-10 17:09:20 +01:00
}
2024-07-25 00:23:29 +03:00
async function remove<T>(url: string, componentId?: string) {
return await call<T>('DELETE', url, componentId);
}
2024-07-25 00:23:29 +03:00
async function upload(url: string, fileToUpload: File) {
2023-06-30 15:25:45 +02:00
const formData = new FormData();
formData.append('upload', fileToUpload);
return await $.ajax({
url: window.glob.baseApiUrl + url,
headers: await getHeaders(),
data: formData,
type: 'PUT',
timeout: 60 * 60 * 1000,
contentType: false, // NEEDED, DON'T REMOVE THIS
processData: false, // NEEDED, DON'T REMOVE THIS
});
}
let idCounter = 1;
2024-07-25 00:23:29 +03:00
const idToRequestMap: Record<string, RequestData> = {};
let maxKnownEntityChangeId = 0;
2024-07-25 00:23:29 +03:00
interface CallOptions {
data?: unknown;
silentNotFound?: boolean;
}
async function call<T>(method: string, url: string, componentId?: string, options: CallOptions = {}) {
let resp;
const headers = await getHeaders({
'trilium-component-id': componentId
});
const {data} = options;
2020-11-23 22:52:48 +01:00
2018-03-24 23:37:55 -04:00
if (utils.isElectron()) {
2020-04-12 14:22:51 +02:00
const ipc = utils.dynamicRequire('electron').ipcRenderer;
const requestId = idCounter++;
resp = await new Promise((resolve, reject) => {
idToRequestMap[requestId] = {
resolve,
reject,
silentNotFound: !!options.silentNotFound
};
ipc.send('server-request', {
requestId: requestId,
2020-11-23 22:52:48 +01:00
headers: headers,
method: method,
2023-05-03 22:49:24 +02:00
url: `/${window.glob.baseApiUrl}${url}`,
data: data
});
2024-07-25 00:23:29 +03:00
}) as any;
}
else {
resp = await ajax(url, method, data, headers, !!options.silentNotFound);
}
const maxEntityChangeIdStr = resp.headers['trilium-max-entity-change-id'];
if (maxEntityChangeIdStr && maxEntityChangeIdStr.trim()) {
maxKnownEntityChangeId = Math.max(maxKnownEntityChangeId, parseInt(maxEntityChangeIdStr));
}
2024-07-25 00:23:29 +03:00
return resp.body as T;
}
2024-07-25 00:23:29 +03:00
function ajax(url: string, method: string, data: unknown, headers: Headers, silentNotFound: boolean): Promise<Response> {
return new Promise((res, rej) => {
2024-07-25 00:23:29 +03:00
const options: JQueryAjaxSettings = {
2023-05-03 22:49:24 +02:00
url: window.glob.baseApiUrl + url,
type: method,
2020-11-23 22:52:48 +01:00
headers: headers,
timeout: 60000,
success: (body, textStatus, jqXhr) => {
2024-07-25 00:23:29 +03:00
const respHeaders: Headers = {};
jqXhr.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(line => {
const parts = line.split(': ');
const header = parts.shift();
2024-07-25 00:23:29 +03:00
if (header) {
respHeaders[header] = parts.join(': ');
}
});
res({
body,
headers: respHeaders
});
},
2022-12-18 16:12:29 +01:00
error: async jqXhr => {
if (silentNotFound && jqXhr.status === 404) {
// report nothing
} else {
await reportError(method, url, jqXhr.status, jqXhr.responseText);
}
rej(jqXhr.responseText);
}
};
if (data) {
try {
options.data = JSON.stringify(data);
} catch (e) {
console.log("Can't stringify data: ", data, " because of error: ", e)
}
options.contentType = "application/json";
2018-03-27 21:46:38 -04:00
}
$.ajax(options);
});
}
2018-04-05 23:17:19 -04:00
if (utils.isElectron()) {
2020-04-12 14:22:51 +02:00
const ipc = utils.dynamicRequire('electron').ipcRenderer;
2018-03-25 13:13:26 -04:00
2024-07-25 00:23:29 +03:00
ipc.on('server-response', async (event: string, arg: Arg) => {
2021-02-14 11:43:31 +01:00
if (arg.statusCode >= 200 && arg.statusCode < 300) {
2023-06-30 15:25:45 +02:00
handleSuccessfulResponse(arg);
2021-02-14 11:43:31 +01:00
}
else {
if (arg.statusCode === 404 && idToRequestMap[arg.requestId]?.silentNotFound) {
// report nothing
} else {
await reportError(arg.method, arg.url, arg.statusCode, arg.body);
}
2021-02-14 11:43:31 +01:00
2023-11-04 22:53:09 +01:00
idToRequestMap[arg.requestId].reject(new Error(`Server responded with ${arg.statusCode}`));
2021-02-14 11:43:31 +01:00
}
2018-03-25 13:13:26 -04:00
delete idToRequestMap[arg.requestId];
2018-04-05 23:17:19 -04:00
});
2023-06-30 15:25:45 +02:00
2024-07-25 00:23:29 +03:00
function handleSuccessfulResponse(arg: Arg) {
if (arg.headers['Content-Type'] === 'application/json' && typeof arg.body === "string") {
2023-06-30 15:25:45 +02:00
arg.body = JSON.parse(arg.body);
}
if (!(arg.requestId in idToRequestMap)) {
2023-06-30 15:25:45 +02:00
// this can happen when reload happens between firing up the request and receiving the response
throw new Error(`Unknown requestId '${arg.requestId}'`);
2023-06-30 15:25:45 +02:00
}
idToRequestMap[arg.requestId].resolve({
2023-06-30 15:25:45 +02:00
body: arg.body,
headers: arg.headers
});
}
}
2024-07-25 00:23:29 +03:00
async function reportError(method: string, url: string, statusCode: number, response: unknown) {
2023-06-30 15:25:45 +02:00
let message = response;
if (typeof response === 'string') {
try {
response = JSON.parse(response);
2024-07-25 00:23:29 +03:00
message = (response as any).message;
2023-06-30 15:25:45 +02:00
}
catch (e) {}
}
const toastService = (await import("./toast.js")).default;
2024-08-04 12:35:42 +03:00
const messageStr = (typeof message === "string" ? message : JSON.stringify(message));
2023-06-30 15:25:45 +02:00
if ([400, 404].includes(statusCode) && response && typeof response === 'object') {
2024-08-04 12:35:42 +03:00
toastService.showError(messageStr);
2023-06-30 15:25:45 +02:00
throw new ValidationError({
requestUrl: url,
method,
statusCode,
...response
});
} else {
const title = `${statusCode} ${method} ${url}`;
2024-08-04 12:35:42 +03:00
toastService.showErrorTitleAndMessage(title, messageStr);
2023-06-30 15:25:45 +02:00
toastService.throwError(`${title} - ${message}`);
}
2018-04-05 23:17:19 -04:00
}
2018-03-25 13:13:26 -04:00
export default {
get,
getWithSilentNotFound,
post,
put,
2022-01-10 17:09:20 +01:00
patch,
remove,
2023-06-30 15:25:45 +02:00
upload,
// don't remove, used from CKEditor image upload!
getHeaders,
getMaxKnownEntityChangeId: () => maxKnownEntityChangeId
};