UNPKG

picgo-plugin-oss

Version:

picgo beecloud oss uploader

103 lines (102 loc) 3.09 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.extractInfo = exports.formatPath = void 0; const crypto_1 = __importDefault(require("crypto")); const file_type_1 = __importDefault(require("file-type")); const mime_1 = __importDefault(require("mime")); class FileNameGenerator { constructor(info) { this.date = new Date(); this.info = info; } year() { return `${this.date.getFullYear()}`; } month() { return this.date.getMonth() < 9 ? `0${this.date.getMonth() + 1}` : `${this.date.getMonth() + 1}`; } day() { return this.date.getDate() < 9 ? `0${this.date.getDate()}` : `${this.date.getDate()}`; } timestamp() { return `${this.date.getTime()}`; } fullName() { return this.info.fileName; } fileName() { return this.info.fileName.replace(this.info.extname, ''); } extName() { return this.info.extname.replace('.', ''); } md5() { return crypto_1.default.createHash('md5').update(this.imgBuffer()).digest('hex'); } sha1() { return crypto_1.default.createHash('sha1').update(this.imgBuffer()).digest('hex'); } sha256() { return crypto_1.default.createHash('sha256').update(this.imgBuffer()).digest('hex'); } imgBuffer() { return this.info.base64Image ? this.info.base64Image : this.info.buffer; } } FileNameGenerator.fields = [ 'year', 'month', 'day', 'timestamp', 'fullName', 'fileName', 'extName', 'md5', 'sha1', 'sha256' ]; function formatPath(info, format) { if (!format) { return info.fileName; } const fileNameGenerator = new FileNameGenerator(info); let formatPath = format; for (let key of FileNameGenerator.fields) { const re = new RegExp(`{${key}}`, 'g'); formatPath = formatPath.replace(re, fileNameGenerator[key]()); } return formatPath; } exports.formatPath = formatPath; async function extractInfo(info) { var _a; let result = {}; if (info.base64Image) { const body = info.base64Image.replace(/^data:[/\w]+;base64,/, ''); result.contentType = (_a = info.base64Image.match(/[^:]\w+\/[\w-+\d.]+(?=;|,)/)) === null || _a === void 0 ? void 0 : _a[0]; result.body = Buffer.from(body, 'base64'); result.contentEncoding = 'base64'; } else { if (info.extname) { result.contentType = mime_1.default.getType(info.extname); } result.body = info.buffer; } // fallback to detect from buffer if (!result.contentType) { const fileType = await file_type_1.default.fromBuffer(result.body); result.contentType = fileType === null || fileType === void 0 ? void 0 : fileType.mime; } return result; } exports.extractInfo = extractInfo;