picgo-plugin-s3-own
Version:
picgo amazon s3 uploader for Own use
118 lines (117 loc) • 3.51 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const client_s3_1 = require("@aws-sdk/client-s3");
const s3_request_presigner_1 = require("@aws-sdk/s3-request-presigner");
const node_http_handler_1 = require("@smithy/node-http-handler");
const url_1 = __importDefault(require("url"));
const utils_1 = require("./utils");
function createS3Client(opts) {
let sslEnabled = true;
try {
const u = url_1.default.parse(opts.endpoint);
sslEnabled = u.protocol === "https:";
}
catch (_a) {
// eslint-disable-next-line no-empty
}
const httpHandlerOpts = {};
if (sslEnabled) {
httpHandlerOpts.httpsAgent = ((0, utils_1.getProxyAgent)(opts.proxy, true, opts.rejectUnauthorized));
}
else {
httpHandlerOpts.httpAgent = ((0, utils_1.getProxyAgent)(opts.proxy, false, opts.rejectUnauthorized));
}
const clientOptions = {
region: opts.region || "auto",
endpoint: opts.endpoint || undefined,
credentials: {
accessKeyId: opts.accessKeyID,
secretAccessKey: opts.secretAccessKey,
},
tls: sslEnabled,
forcePathStyle: opts.pathStyleAccess,
requestHandler: new node_http_handler_1.NodeHttpHandler(httpHandlerOpts),
};
const client = new client_s3_1.S3Client(clientOptions);
return client;
}
async function createUploadTask(opts) {
if (!opts.item.buffer && !opts.item.base64Image) {
return Promise.reject(new Error("undefined image"));
}
let body;
let contentType;
let contentEncoding;
try {
;
({ body, contentType, contentEncoding } = await (0, utils_1.extractInfo)(opts.item));
}
catch (err) {
return Promise.reject(err);
}
const acl = opts.acl;
const command = new client_s3_1.PutObjectCommand({
Bucket: opts.bucketName,
Key: opts.path,
ACL: acl,
Body: body,
ContentType: contentType,
ContentEncoding: contentEncoding,
});
let output;
try {
output = await opts.client.send(command);
}
catch (err) {
return Promise.reject(err);
}
let url;
if (!opts.urlPrefix) {
try {
url = await getFileURL(opts, output.ETag, output.VersionId);
}
catch (err) {
return Promise.reject(err);
}
}
else {
if (opts.trimmedUploadPath) {
url = `${opts.urlPrefix}/${opts.trimmedUploadPath}`;
}
else {
url = `${opts.urlPrefix}/${opts.path}`;
}
}
return {
index: opts.index,
key: opts.path,
url: url,
imgURL: url,
versionId: output.VersionId,
eTag: output.ETag,
};
}
async function getFileURL(opts, eTag, versionId) {
try {
const signedUrl = await (0, s3_request_presigner_1.getSignedUrl)(opts.client, new client_s3_1.GetObjectCommand({
Bucket: opts.bucketName,
Key: opts.path,
IfMatch: eTag,
VersionId: versionId,
}), { expiresIn: 3600 });
const urlObject = new URL(signedUrl);
urlObject.search = "";
return urlObject.href;
}
catch (err) {
return Promise.reject(err);
}
}
exports.default = {
createS3Client,
createUploadTask,
getFileURL,
};