trilium/src/public/javascripts/services/import.js

74 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-10-20 16:00:18 +08:00
import toastService from "./toast.js";
import server from "./server.js";
import ws from "./ws.js";
import utils from "./utils.js";
2020-01-24 22:44:24 +08:00
import appContext from "./app_context.js";
export async function uploadFiles(parentNoteId, files, options) {
if (files.length === 0) {
return;
}
const taskId = utils.randomString(10);
let noteId;
let counter = 0;
for (const file of files) {
counter++;
const formData = new FormData();
formData.append('upload', file);
formData.append('taskId', taskId);
formData.append('last', counter === files.length ? "true" : "false");
for (const key in options) {
formData.append(key, options[key]);
}
({noteId} = await $.ajax({
url: baseApiUrl + 'notes/' + parentNoteId + '/import',
headers: server.getHeaders(),
data: formData,
dataType: 'json',
type: 'POST',
timeout: 60 * 60 * 1000,
contentType: false, // NEEDED, DON'T REMOVE THIS
processData: false, // NEEDED, DON'T REMOVE THIS
}));
}
}
2019-10-18 03:15:27 +08:00
function makeToast(id, message) {
return {
id: id,
title: "Import status",
2019-10-18 03:15:27 +08:00
message: message,
2019-10-18 02:44:51 +08:00
icon: "plus"
};
2019-10-18 03:15:27 +08:00
}
2019-10-18 02:44:51 +08:00
2019-10-18 03:15:27 +08:00
ws.subscribeToMessages(async message => {
2019-10-19 05:19:16 +08:00
if (message.taskType !== 'import') {
return;
}
if (message.type === 'task-error') {
2019-10-20 16:00:18 +08:00
toastService.closePersistent(message.taskId);
toastService.showError(message.message);
2019-10-19 05:19:16 +08:00
} else if (message.type === 'task-progress-count') {
2019-10-20 16:00:18 +08:00
toastService.showPersistent(makeToast(message.taskId, "Import in progress: " + message.progressCount));
2019-10-19 05:19:16 +08:00
} else if (message.type === 'task-succeeded') {
2019-10-18 03:15:27 +08:00
const toast = makeToast(message.taskId, "Import finished successfully.");
2019-10-18 02:44:51 +08:00
toast.closeAfter = 5000;
2019-10-20 16:00:18 +08:00
toastService.showPersistent(toast);
2019-10-19 06:11:07 +08:00
if (message.result.importedNoteId) {
2020-03-21 04:57:16 +08:00
await appContext.tabManager.getActiveTabContext().setNote(message.result.importedNoteId);
}
}
});
export default {
uploadFiles
}