2020-08-01 03:17:07 +03:00
|
|
|
import * as Constants from "~/node_common/constants";
|
|
|
|
import * as LibraryManager from "~/node_common/managers/library";
|
|
|
|
import * as Utilities from "~/node_common/utilities";
|
|
|
|
|
|
|
|
import FS from "fs-extra";
|
|
|
|
import FORM from "formidable";
|
|
|
|
|
2020-08-04 04:35:31 +03:00
|
|
|
// TODO(jim): Ideally we never keep the file locally.
|
2020-08-01 03:17:07 +03:00
|
|
|
export const formMultipart = (req, res, { user }) =>
|
|
|
|
new Promise((resolve, reject) => {
|
|
|
|
const f = new FORM.IncomingForm();
|
|
|
|
f.uploadDir = Constants.FILE_STORAGE_URL;
|
|
|
|
f.keepExtensions = true;
|
|
|
|
f.parse(req, async (e, fields, files) => {
|
|
|
|
if (e) {
|
|
|
|
return reject({
|
|
|
|
decorator: "SERVER_UPLOAD_PARSE_FAILURE",
|
|
|
|
error: true,
|
|
|
|
message: e,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-08-02 09:00:04 +03:00
|
|
|
if (!files.data) {
|
2020-08-01 03:17:07 +03:00
|
|
|
return reject({
|
2020-08-04 04:35:31 +03:00
|
|
|
decorator: "SERVER_UPLOAD_ERROR_CHECK_FORM_TYPE",
|
2020-08-01 03:17:07 +03:00
|
|
|
error: true,
|
|
|
|
message: files,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-08-02 09:00:04 +03:00
|
|
|
const path = files.data._writeStream.path;
|
2020-08-01 03:17:07 +03:00
|
|
|
const localPath = `./${path}`;
|
2020-08-02 09:00:04 +03:00
|
|
|
const data = LibraryManager.createLocalDataIncomplete(files.data);
|
2020-08-01 03:17:07 +03:00
|
|
|
|
2020-08-14 13:10:14 +03:00
|
|
|
const { buckets, bucketKey, bucketName } = await Utilities.getBucketAPIFromUserToken(user.data.tokens.api);
|
2020-08-01 03:17:07 +03:00
|
|
|
|
|
|
|
let readFile;
|
|
|
|
let push;
|
|
|
|
try {
|
2020-08-04 04:35:31 +03:00
|
|
|
readFile = FS.createReadStream(path, {
|
|
|
|
highWaterMark: 1024 * 1024 * 3,
|
|
|
|
});
|
|
|
|
|
2020-08-01 03:17:07 +03:00
|
|
|
push = await buckets.pushPath(bucketKey, data.name, readFile);
|
|
|
|
} catch (e) {
|
2020-08-02 09:00:04 +03:00
|
|
|
await FS.unlinkSync(localPath);
|
|
|
|
|
2020-08-01 03:17:07 +03:00
|
|
|
return reject({
|
|
|
|
decorator: "SERVER_BUCKETS_PUSH_ISSUE",
|
|
|
|
error: true,
|
|
|
|
message: e,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
// NOTE(jim): Remove the file when you're done with it.
|
|
|
|
await FS.unlinkSync(localPath);
|
|
|
|
|
|
|
|
return resolve({ data, ipfs: push.path.path });
|
|
|
|
});
|
|
|
|
});
|