@nocobase/plugin-file-manager
Version:
Provides files storage services with files collection template and attachment field.
148 lines (146 loc) • 5.43 kB
JavaScript
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var ali_oss_exports = {};
__export(ali_oss_exports, {
default: () => ali_oss_default
});
module.exports = __toCommonJS(ali_oss_exports);
var import_util = require("util");
var import_path = __toESM(require("path"));
var import_crypto = __toESM(require("crypto"));
var import__ = require(".");
var import_constants = require("../../constants");
var import_utils = require("../utils");
const ERROR_NO_CLIENT = new Error("oss client undefined");
function getRandomFilename(req, file, cb) {
import_crypto.default.pseudoRandomBytes(16, function(err, raw) {
cb(err, err ? void 0 : `${raw.toString("hex")}${import_path.default.extname(file.originalname)}`);
});
}
class AliYunOssStorage {
client;
getDestination;
getFilename;
constructor({ config, destination = "", filename = getRandomFilename }) {
const OSS = require("ali-oss");
this.client = new OSS(config);
this.getDestination = typeof destination === "string" ? (req, file, cb) => cb(null, destination) : destination;
this.getFilename = filename;
}
_handleFile(req, file, cb) {
if (!this.client) {
return cb(ERROR_NO_CLIENT);
}
const getDestination = (0, import_util.promisify)(this.getDestination);
const getFilename = (0, import_util.promisify)(this.getFilename);
let size = 0;
Promise.all([getDestination(req, file), getFilename(req, file)]).then(([destination, filename]) => {
file.stream.on("data", (chunk) => {
size += Buffer.byteLength(chunk);
});
const options = {};
if (file.mimetype === "text/plain") {
options.mime = "text/plain; charset=utf-8";
}
return this.client.putStream(`${destination}/${filename}`, file.stream, options);
}).then((result) => {
const { url, name } = result;
const lastSlashIndex = name.lastIndexOf("/");
const path = name.substr(0, lastSlashIndex);
cb(null, {
destination: path,
filename: name.substr(lastSlashIndex + 1),
path,
size,
url
});
}).catch(cb);
}
async _removeFile(req, file, cb) {
if (!this.client) {
return cb(ERROR_NO_CLIENT);
}
try {
const result = await this.client.delete(file.filename);
cb(null, result);
} catch (error) {
cb(error);
}
}
}
class ali_oss_default extends import__.StorageType {
static defaults() {
return {
title: "\u963F\u91CC\u4E91\u5BF9\u8C61\u5B58\u50A8",
type: import_constants.STORAGE_TYPE_ALI_OSS,
name: "ali-oss-1",
baseUrl: process.env.ALI_OSS_STORAGE_BASE_URL,
options: {
region: process.env.ALI_OSS_REGION,
accessKeyId: process.env.ALI_OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.ALI_OSS_ACCESS_KEY_SECRET,
bucket: process.env.ALI_OSS_BUCKET
}
};
}
make() {
return new AliYunOssStorage({
config: { timeout: 6e5, ...this.storage.options },
filename: (0, import_utils.cloudFilenameGetter)(this.storage)
});
}
async exists(record) {
const { client } = this.make();
try {
await client.head((0, import_utils.getFileKey)(record));
return true;
} catch (error) {
if (["NoSuchKey", "NotFoundError"].includes(error.name)) {
return false;
}
throw error;
}
}
async copy(source, target) {
const { client } = this.make();
await client.copy((0, import_utils.getFileKey)(target), (0, import_utils.getFileKey)(source));
}
async delete(records) {
const { client } = this.make();
const { deleted } = await client.deleteMulti(records.map(import_utils.getFileKey));
return [deleted.length, records.filter((record) => !deleted.find((item) => item.Key === (0, import_utils.getFileKey)(record)))];
}
}