@openade/fe
Version:
Fatturazione Elettronica - Electronic Invoicing for Sistema di Interscambio (SDI)
230 lines • 8.01 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AttachmentManager = void 0;
exports.createAttachmentManager = createAttachmentManager;
exports.addInvoiceAttachment = addInvoiceAttachment;
exports.getInvoiceAttachment = getInvoiceAttachment;
const crypto_1 = require("crypto");
const path_1 = require("path");
const compression_service_1 = require("./compression.service");
const encryption_service_1 = require("./encryption.service");
class AttachmentManager {
constructor(config) {
this.config = {
maxFileSize: 10 * 1024 * 1024,
allowedExtensions: [
'.pdf',
'.jpg',
'.jpeg',
'.png',
'.gif',
'.txt',
'.doc',
'.docx',
'.xls',
'.xlsx',
],
storageDir: './attachments',
compression: false,
encryption: false,
...config,
};
this.compressionService = new compression_service_1.CompressionService();
this.encryptionService = new encryption_service_1.EncryptionService();
}
async addAttachmentFromFile(filePath, description) {
try {
const content = await this.config.fileStorage.retrieve(filePath);
if (!content) {
return {
id: '',
success: false,
error: 'File not found',
};
}
const filename = (0, path_1.basename)(filePath);
const mimeType = this.getMimeType(filename);
return await this.addAttachment(Buffer.from(content), filename, mimeType, description);
}
catch (error) {
return {
id: '',
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
};
}
}
async addAttachment(content, filename, mimeType, description) {
try {
const validation = this.validateAttachment(content, filename);
if (!validation.valid) {
return {
id: '',
success: false,
error: validation.error,
};
}
const id = this.generateAttachmentId(filename, content);
let processedContent = content;
let compressed = false;
let encrypted = false;
if (this.config.compression) {
processedContent = await this.compressionService.compress(content);
compressed = true;
}
if (this.config.encryption) {
const encryptionKey = await this.encryptionService.generateKey();
processedContent = await this.encryptionService.encrypt(processedContent, encryptionKey);
encrypted = true;
}
const attachment = {
id,
filename,
content: processedContent.toString('base64'),
mimeType,
size: content.length,
hash: this.calculateHash(content),
description,
createdAt: new Date().toISOString(),
compressed,
encrypted,
};
await this.storeAttachment(attachment);
return {
id,
success: true,
attachment,
};
}
catch (error) {
return {
id: '',
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
};
}
}
async getAttachment(id) {
try {
return await this.loadAttachment(id);
}
catch {
return null;
}
}
async removeAttachment(id) {
try {
return await this.deleteAttachment(id);
}
catch {
return false;
}
}
async listAttachments() {
try {
return await this.listStoredAttachments();
}
catch {
return [];
}
}
validateAttachment(content, filename) {
if (content.length > this.config.maxFileSize) {
return {
valid: false,
error: `File size exceeds maximum allowed size of ${this.config.maxFileSize} bytes`,
};
}
const extension = (0, path_1.extname)(filename).toLowerCase();
if (!this.config.allowedExtensions.includes(extension)) {
return {
valid: false,
error: `File extension ${extension} is not allowed`,
};
}
return { valid: true };
}
generateAttachmentId(filename, content) {
const hash = this.calculateHash(content);
const timestamp = Date.now();
return `${hash.substring(0, 8)}_${timestamp}`;
}
calculateHash(content) {
return (0, crypto_1.createHash)('sha256').update(content).digest('hex');
}
getMimeType(filename) {
const extension = (0, path_1.extname)(filename).toLowerCase();
const mimeTypes = {
'.pdf': 'application/pdf',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.txt': 'text/plain',
'.doc': 'application/msword',
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.xls': 'application/vnd.ms-excel',
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
};
return mimeTypes[extension] || 'application/octet-stream';
}
async storeAttachment(attachment) {
const filePath = `${this.config.storageDir || 'attachments'}/${attachment.id}.json`;
await this.config.fileStorage.store(filePath, JSON.stringify(attachment, null, 2));
}
async loadAttachment(id) {
try {
const filePath = `${this.config.storageDir || 'attachments'}/${id}.json`;
const content = await this.config.fileStorage.retrieve(filePath);
if (!content) {
return null;
}
return JSON.parse(Buffer.from(content).toString('utf8'));
}
catch {
return null;
}
}
async deleteAttachment(id) {
try {
const filePath = `${this.config.storageDir || 'attachments'}/${id}.json`;
await this.config.fileStorage.delete(filePath);
return true;
}
catch {
return false;
}
}
async listStoredAttachments() {
try {
const storageDir = this.config.storageDir || 'attachments';
const files = await this.config.fileStorage.list(storageDir);
const jsonFiles = files.filter((file) => file.endsWith('.json'));
const attachments = [];
for (const file of jsonFiles) {
const id = file.replace('.json', '');
const attachment = await this.loadAttachment(id);
if (attachment) {
attachments.push(attachment);
}
}
return attachments;
}
catch {
return [];
}
}
}
exports.AttachmentManager = AttachmentManager;
function createAttachmentManager(config) {
return new AttachmentManager(config);
}
async function addInvoiceAttachment(filePath, description, config) {
const manager = createAttachmentManager(config);
return await manager.addAttachmentFromFile(filePath, description);
}
async function getInvoiceAttachment(id, config) {
const manager = createAttachmentManager(config);
return await manager.getAttachment(id);
}
//# sourceMappingURL=attachments.manager.js.map