slate/node_common/upload.js

128 lines
3.0 KiB
JavaScript
Raw Normal View History

import * as LibraryManager from "~/node_common/managers/library";
import * as Utilities from "~/node_common/utilities";
import * as Social from "~/node_common/social";
import B from "busboy";
const HIGH_WATER_MARK = 1024 * 1024 * 3;
2020-08-17 07:22:35 +03:00
export const formMultipart = async (req, res, { user }) => {
let data = null;
2020-08-17 07:22:35 +03:00
const upload = () =>
new Promise(async (resolve, reject) => {
let form = new B({
headers: req.headers,
highWaterMark: HIGH_WATER_MARK,
});
form.on("file", async function(
fieldname,
stream,
filename,
encoding,
mime
) {
2020-08-17 07:22:35 +03:00
data = LibraryManager.createLocalDataIncomplete({
name: filename,
2020-08-17 07:22:35 +03:00
type: mime,
});
const token = user.data.tokens.api;
const {
buckets,
bucketKey,
2020-09-23 12:46:59 +03:00
} = await Utilities.getBucketAPIFromUserToken({ user });
if (!buckets) {
return reject({
decorator: "SERVER_BUCKET_INIT_FAILURE",
error: true,
});
}
2020-08-17 07:22:35 +03:00
let push;
try {
console.log("[upload] pushing to textile");
2020-08-17 07:22:35 +03:00
push = await buckets.pushPath(bucketKey, data.id, stream);
console.log("[upload] finished pushing to textile");
2020-08-17 07:22:35 +03:00
} catch (e) {
Social.sendTextileSlackMessage({
file: "/node_common/upload.js",
user,
message: e.message,
code: e.code,
functionName: `buckets.pushPath`,
});
2020-08-17 07:22:35 +03:00
return reject({
decorator: "SERVER_BUCKETS_PUSH_ISSUE",
error: true,
message: e,
});
}
return resolve({
decorator: "SERVER_BUCKET_STREAM_SUCCESS",
data: push.path.path,
});
});
2020-08-17 07:22:35 +03:00
form.on("error", (e) => {
Social.sendTextileSlackMessage({
file: "/node_common/upload.js",
user,
message: e.message,
code: e.code,
functionName: `form`,
});
return reject({
2020-08-17 07:22:35 +03:00
decorator: "SERVER_BUCKET_STREAM_FAILURE",
error: true,
message: e,
});
2020-08-17 07:22:35 +03:00
});
2020-08-17 07:22:35 +03:00
req.pipe(form);
});
2020-08-17 07:22:35 +03:00
const response = await upload();
if (response && response.error) {
2020-08-17 07:22:35 +03:00
return response;
}
// TODO(jim): Put this call into a file for all Textile related calls.
const token = user.data.tokens.api;
2020-09-23 12:46:59 +03:00
const { buckets } = await Utilities.getBucketAPIFromUserToken({ user });
if (!buckets) {
return {
decorator: "SERVER_BUCKET_INIT_FAILURE",
error: true,
};
}
2020-08-17 07:22:35 +03:00
try {
const newUpload = await buckets.listIpfsPath(response.data);
data.size = newUpload.size;
} catch (e) {
Social.sendTextileSlackMessage({
file: "/node_common/upload.js",
user,
message: e.message,
code: e.code,
functionName: `buckets.listIpfsPath`,
});
2020-08-17 07:22:35 +03:00
return {
decorator: "SERVER_BUCKETS_VERIFY_ISSUE",
error: true,
message: e,
};
}
return { decorator: "SERVER_UPLOAD_SUCCESS", data, ipfs: response.data };
};