"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AzureProvider = void 0;
const storage_blob_1 = require("@azure/storage-blob");
const common_1 = require("@nestjs/common");
const path_1 = require("path");
const abstract_provider_1 = require("./abstract.provider");
class AzureProvider extends abstract_provider_1.AbstractProvider {
    constructor(setting) {
        super();
        this.setting = setting;
        this.initValidation();
    }
    async initValidation() {
        if (!this.setting['storage-abs-account']) {
            throw new common_1.BadRequestException(`You must set the storage-abs-account in the setting.`);
        }
        if (!this.setting['storage-abs-key']) {
            throw new common_1.BadRequestException(`You must set the storage-abs-key in the setting.`);
        }
        if (!this.setting['storage-abs-container']) {
            throw new common_1.BadRequestException(`You must set the storage-abs-container in the setting.`);
        }
        const blobServiceClient = await this.getClient();
        const containerClient = blobServiceClient.getContainerClient(this.setting['storage-abs-container']);
        const exists = await containerClient.exists();
        if (!exists) {
            throw new common_1.BadRequestException(`The container "${this.setting['storage-abs-container']}" does not exist.`);
        }
    }
    async getClient() {
        const sharedKeyCredential = new storage_blob_1.StorageSharedKeyCredential(this.setting['storage-abs-account'], this.setting['storage-abs-key']);
        const blobServiceClient = new storage_blob_1.BlobServiceClient(`https://${this.setting['storage-abs-account']}.blob.core.windows.net`, sharedKeyCredential);
        return blobServiceClient;
    }
    async uploadFromString(destination, filename, fileContent, mimetype = 'text/plain') {
        const blobServiceClient = await this.getClient();
        const containerClient = blobServiceClient.getContainerClient(this.setting['storage-abs-container']);
        const filepath = [destination, this.getFilename(filename)].join('/');
        const blobClient = containerClient.getBlockBlobClient(filepath);
        await blobClient.upload(fileContent, fileContent.length, {
            blobHTTPHeaders: { blobContentType: mimetype },
        });
        return `https://${this.setting['storage-abs-container']}.azureedge.net/${filepath}`;
    }
    async upload(destination, file) {
        const blobServiceClient = await this.getClient();
        const containerClient = blobServiceClient.getContainerClient(this.setting['storage-abs-container']);
        const filepath = [destination, this.getFilename(file.originalname)].join('/');
        const blobClient = containerClient.getBlockBlobClient(filepath);
        await blobClient.uploadData(file.buffer, {
            blobHTTPHeaders: { blobContentType: file.mimetype },
        });
        return `https://${this.setting['storage-abs-container']}.azureedge.net/${filepath}`;
    }
    async uploadFromPath(destination, filePath, options) {
        var _a;
        const blobServiceClient = await this.getClient();
        const containerClient = blobServiceClient.getContainerClient(this.setting['storage-abs-container']);
        const filepath = [destination, this.getFilename((_a = options === null || options === void 0 ? void 0 : options.filename) !== null && _a !== void 0 ? _a : (0, path_1.basename)(filePath))].join('/');
        const blobClient = containerClient.getBlockBlobClient(filepath);
        await blobClient.uploadFile(filePath, {
            blobHTTPHeaders: (options === null || options === void 0 ? void 0 : options.mimetype)
                ? { blobContentType: options.mimetype }
                : undefined,
        });
        return `https://${this.setting['storage-abs-container']}.azureedge.net/${filepath}`;
    }
    async delete(filepath) {
        const url = new URL(filepath);
        if (!url.pathname) {
            throw new Error(`Invalid filepath "${filepath}" for S3`);
        }
        const blobServiceClient = await this.getClient();
        const containerClient = blobServiceClient.getContainerClient(this.setting['storage-abs-container']);
        const blobClient = containerClient.getBlockBlobClient(url.pathname.split('/').slice(1).join('/'));
        return await blobClient.delete();
    }
    async readStream(filepath) {
        const blobServiceClient = await this.getClient();
        const containerClient = blobServiceClient.getContainerClient(this.setting['storage-abs-container']);
        const blobClient = containerClient.getBlockBlobClient(filepath);
        const downloadBlockBlobResponse = await blobClient.download();
        return downloadBlockBlobResponse.readableStreamBody;
    }
    async metaData(filepath) {
        const blobServiceClient = await this.getClient();
        const containerClient = blobServiceClient.getContainerClient(this.setting['storage-abs-container']);
        const blobClient = containerClient.getBlockBlobClient(filepath);
        const properties = await blobClient.getProperties();
        return properties;
    }
    async buffer(filepath) {
        const blobServiceClient = await this.getClient();
        const containerClient = blobServiceClient.getContainerClient(this.setting['storage-abs-container']);
        const blobClient = containerClient.getBlockBlobClient(filepath);
        const buffer = await blobClient.downloadToBuffer();
        return buffer;
    }
    async tempURL(filepath, expires) {
        const sharedKeyCredential = new storage_blob_1.StorageSharedKeyCredential(this.setting['storage-abs-account'], this.setting['storage-abs-key']);
        const blobServiceClient = new storage_blob_1.BlobServiceClient(`https://${this.setting['storage-abs-account']}.blob.core.windows.net`, sharedKeyCredential);
        const containerClient = blobServiceClient.getContainerClient(this.setting['storage-abs-container']);
        const blobClient = containerClient.getBlobClient(filepath);
        const expiresOn = new Date(new Date().getTime() + expires * 1000);
        const blobSAS = (0, storage_blob_1.generateBlobSASQueryParameters)({
            containerName: this.setting['storage-abs-container'],
            blobName: filepath,
            permissions: storage_blob_1.ContainerSASPermissions.parse('r'),
            expiresOn,
        }, sharedKeyCredential).toString();
        return blobClient.url + '?' + blobSAS;
    }
}
exports.AzureProvider = AzureProvider;
//# sourceMappingURL=azure.provider.js.map