"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadAWSMethods = loadAWSMethods;
var client_s3_1 = require("@aws-sdk/client-s3");
var s3_request_presigner_1 = require("@aws-sdk/s3-request-presigner");
var axios_1 = require("axios");
var simpl_schema_1 = require("simpl-schema");
var file_collection_1 = require("../collections/file.collection");
var resolveio_server_app_1 = require("../resolveio-server-app");
var common_1 = require("../util/common");
var fs = require('fs');
var path = require('path');
var pdfCnt = 1000000;
var NON_PDF_CONTENT_TYPES = {
    '.csv': 'text/csv; charset=utf-8',
    '.css': 'text/css; charset=utf-8',
    '.env': 'text/plain; charset=utf-8',
    '.gz': 'application/gzip',
    '.html': 'text/html; charset=utf-8',
    '.json': 'application/json',
    '.js': 'application/javascript',
    '.md': 'text/markdown; charset=utf-8',
    '.tar': 'application/x-tar',
    '.tgz': 'application/gzip',
    '.ts': 'application/typescript',
    '.txt': 'text/plain; charset=utf-8',
    '.xml': 'application/xml',
    '.yaml': 'application/yaml',
    '.yml': 'application/yaml',
    '.zip': 'application/zip'
};
function inferNonPDFContentType(fileName) {
    if (!fileName) {
        return 'application/octet-stream';
    }
    var normalized = fileName.toLowerCase();
    if (normalized.endsWith('.tar.gz')) {
        return 'application/gzip';
    }
    var extension = path.extname(normalized);
    return NON_PDF_CONTENT_TYPES[extension] || 'application/octet-stream';
}
function loadAWSMethods(methodManager) {
    methodManager.methods({
        uploadFileAndSave: {
            check: new simpl_schema_1.default({
                fileName: {
                    type: String
                },
                fileData: {
                    type: String
                },
                fileSize: {
                    type: Number
                },
                fileOrder: {
                    type: Number
                },
                fileType: {
                    type: String
                },
                compress: {
                    type: Boolean
                }
            }),
            // eslint-disable-next-line no-unused-vars
            function: function (fileName, fileData, fileSize, fileOrder, fileType, compress) {
                return __awaiter(this, void 0, void 0, function () {
                    var key, s3, maxRetries, attempt, _loop_1, state_1;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                if (!fileName) {
                                    throw new Error("Invalid File Name provided");
                                }
                                key = 'uploads/' + Date.now() + '-' + (pdfCnt++) + '-' + fileName;
                                s3 = this.getAWS().s3();
                                maxRetries = 3;
                                attempt = 0;
                                _loop_1 = function () {
                                    var res, err_1, backoff_1;
                                    return __generator(this, function (_b) {
                                        switch (_b.label) {
                                            case 0:
                                                _b.trys.push([0, 2, , 6]);
                                                return [4 /*yield*/, s3.putObject({
                                                        Bucket: process.env.AWS_S3_BUCKET,
                                                        Key: key,
                                                        Body: Buffer.from(fileData.replace('data:' + fileData.split(',')[0].split(':')[1].split(';')[0] + ';base64,', ''), 'base64'),
                                                        ACL: 'private',
                                                        ContentType: fileData.split(',')[0].split(':')[1].split(';')[0],
                                                        ContentDisposition: 'inline'
                                                    })];
                                            case 1:
                                                res = _b.sent();
                                                if (res) {
                                                    return [2 /*return*/, { value: file_collection_1.Files.create({
                                                                _id: (0, common_1.objectIdHexString)(), __v: 0, name: fileName, size: fileSize, key: key, order: fileOrder, type: fileType
                                                            }) }];
                                                }
                                                else {
                                                    return [2 /*return*/, { value: null }];
                                                }
                                                return [3 /*break*/, 6];
                                            case 2:
                                                err_1 = _b.sent();
                                                attempt++;
                                                if (!(attempt <= maxRetries)) return [3 /*break*/, 4];
                                                backoff_1 = Math.pow(2, attempt) * 1000;
                                                console.warn("Attempt ".concat(attempt, " failed. Retrying in ").concat(backoff_1 / 1000, " seconds..."));
                                                // eslint-disable-next-line no-restricted-syntax
                                                return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, backoff_1); })];
                                            case 3:
                                                // eslint-disable-next-line no-restricted-syntax
                                                _b.sent();
                                                return [3 /*break*/, 5];
                                            case 4: throw new Error("Error in AWS Upload File And Save: Failed to upload after ".concat(maxRetries, " attempts: ").concat(err_1.message));
                                            case 5: return [3 /*break*/, 6];
                                            case 6: return [2 /*return*/];
                                        }
                                    });
                                };
                                _a.label = 1;
                            case 1:
                                if (!(attempt <= maxRetries)) return [3 /*break*/, 3];
                                return [5 /*yield**/, _loop_1()];
                            case 2:
                                state_1 = _a.sent();
                                if (typeof state_1 === "object")
                                    return [2 /*return*/, state_1.value];
                                return [3 /*break*/, 1];
                            case 3: return [2 /*return*/, null];
                        }
                    });
                });
            }
        },
        uploadPDFBufferAndSave: {
            check: new simpl_schema_1.default({
                fileName: {
                    type: String
                },
                fileDataBuffer: {
                    type: Buffer
                },
                fileSize: {
                    type: Number
                },
                fileOrder: {
                    type: Number
                },
                fileType: {
                    type: String
                }
            }),
            function: function (fileName, fileDataBuffer, fileSize, fileOrder, fileType) {
                return __awaiter(this, void 0, void 0, function () {
                    var key, s3, maxRetries, attempt, _loop_2, state_2;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                if (!fileName) {
                                    throw new Error("Invalid File Name provided");
                                }
                                key = 'uploads/' + Date.now() + '-' + (pdfCnt++) + '-' + fileName;
                                s3 = this.getAWS().s3();
                                maxRetries = 3;
                                attempt = 0;
                                _loop_2 = function () {
                                    var res, err_2, backoff_2;
                                    return __generator(this, function (_b) {
                                        switch (_b.label) {
                                            case 0:
                                                _b.trys.push([0, 2, , 6]);
                                                return [4 /*yield*/, s3.putObject({
                                                        Bucket: process.env.AWS_S3_BUCKET,
                                                        Key: key,
                                                        Body: fileDataBuffer,
                                                        ACL: 'private',
                                                        ContentType: 'application/pdf',
                                                        ContentDisposition: 'inline'
                                                    })];
                                            case 1:
                                                res = _b.sent();
                                                if (res) {
                                                    return [2 /*return*/, { value: file_collection_1.Files.create({
                                                                _id: (0, common_1.objectIdHexString)(), __v: 0, name: fileName, size: fileSize, key: key, order: fileOrder, type: fileType
                                                            }) }];
                                                }
                                                else {
                                                    return [2 /*return*/, { value: null }];
                                                }
                                                return [3 /*break*/, 6];
                                            case 2:
                                                err_2 = _b.sent();
                                                attempt++;
                                                if (!(attempt <= maxRetries)) return [3 /*break*/, 4];
                                                backoff_2 = Math.pow(2, attempt) * 1000;
                                                console.warn("Attempt ".concat(attempt, " failed. Retrying in ").concat(backoff_2 / 1000, " seconds..."));
                                                // eslint-disable-next-line no-restricted-syntax
                                                return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, backoff_2); })];
                                            case 3:
                                                // eslint-disable-next-line no-restricted-syntax
                                                _b.sent();
                                                return [3 /*break*/, 5];
                                            case 4: throw new Error("Error in AWS Upload PDF Buffer And Save: Failed to upload after ".concat(maxRetries, " attempts: ").concat(err_2.message));
                                            case 5: return [3 /*break*/, 6];
                                            case 6: return [2 /*return*/];
                                        }
                                    });
                                };
                                _a.label = 1;
                            case 1:
                                if (!(attempt <= maxRetries)) return [3 /*break*/, 3];
                                return [5 /*yield**/, _loop_2()];
                            case 2:
                                state_2 = _a.sent();
                                if (typeof state_2 === "object")
                                    return [2 /*return*/, state_2.value];
                                return [3 /*break*/, 1];
                            case 3: return [2 /*return*/, null];
                        }
                    });
                });
            }
        },
        uploadNonPDFFileAndSave: {
            check: new simpl_schema_1.default({
                fileName: {
                    type: String
                },
                fileData: {
                    type: String
                },
                fileSize: {
                    type: Number
                },
                fileOrder: {
                    type: Number
                },
                fileType: {
                    type: String
                }
            }),
            function: function (fileName, fileData, fileSize, fileOrder, fileType) {
                return __awaiter(this, void 0, void 0, function () {
                    var key, s3, contentType, res, err_3;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                if (!fileName) {
                                    throw new Error("Invalid File Name provided");
                                }
                                key = 'uploads/' + Date.now() + '-' + fileName;
                                s3 = this.getAWS().s3();
                                _a.label = 1;
                            case 1:
                                _a.trys.push([1, 3, , 4]);
                                contentType = inferNonPDFContentType(fileName);
                                return [4 /*yield*/, s3.putObject({
                                        Bucket: process.env.AWS_S3_BUCKET,
                                        Key: key,
                                        Body: Buffer.from(fileData),
                                        ACL: 'private',
                                        ContentType: contentType,
                                        ContentDisposition: 'inline'
                                    })];
                            case 2:
                                res = _a.sent();
                                if (res) {
                                    return [2 /*return*/, file_collection_1.Files.create({
                                            _id: (0, common_1.objectIdHexString)(), __v: 0, name: fileName, size: fileSize, key: key, order: fileOrder, type: fileType
                                        })];
                                }
                                else {
                                    return [2 /*return*/, null];
                                }
                                return [3 /*break*/, 4];
                            case 3:
                                err_3 = _a.sent();
                                err_3.mesage = 'Error In AWS Upload Non PDF File And Save: ' + err_3.mesage;
                                throw err_3;
                            case 4: return [2 /*return*/];
                        }
                    });
                });
            }
        },
        uploadNonPDFBufferAndSave: {
            check: new simpl_schema_1.default({
                fileName: {
                    type: String
                },
                fileDataBuffer: {
                    type: Buffer
                },
                fileSize: {
                    type: Number
                },
                fileOrder: {
                    type: Number
                },
                fileType: {
                    type: String
                }
            }),
            function: function (fileName, fileDataBuffer, fileSize, fileOrder, fileType) {
                return __awaiter(this, void 0, void 0, function () {
                    var key, s3, contentType, res, err_4;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                if (!fileName) {
                                    throw new Error("Invalid File Name provided");
                                }
                                key = 'uploads/' + Date.now() + '-' + fileName;
                                s3 = this.getAWS().s3();
                                _a.label = 1;
                            case 1:
                                _a.trys.push([1, 3, , 4]);
                                contentType = inferNonPDFContentType(fileName);
                                return [4 /*yield*/, s3.putObject({
                                        Bucket: process.env.AWS_S3_BUCKET,
                                        Key: key,
                                        Body: fileDataBuffer,
                                        ACL: 'private',
                                        ContentType: contentType,
                                        ContentDisposition: 'inline'
                                    })];
                            case 2:
                                res = _a.sent();
                                if (res) {
                                    return [2 /*return*/, file_collection_1.Files.create({
                                            _id: (0, common_1.objectIdHexString)(), __v: 0, name: fileName, size: fileSize, key: key, order: fileOrder, type: fileType
                                        })];
                                }
                                else {
                                    return [2 /*return*/, null];
                                }
                                return [3 /*break*/, 4];
                            case 3:
                                err_4 = _a.sent();
                                err_4.mesage = 'Error In AWS Upload Non PDF Buffer And Save: ' + err_4.mesage;
                                throw err_4;
                            case 4: return [2 /*return*/];
                        }
                    });
                });
            }
        },
        uploadNonPDFStreamAndSave: {
            check: new simpl_schema_1.default({
                fileName: {
                    type: String
                },
                fileData: {
                    type: String
                },
                fileOrder: {
                    type: Number
                },
                fileType: {
                    type: String
                }
            }),
            function: function (fileName, fileData, fileOrder, fileType) {
                return __awaiter(this, void 0, void 0, function () {
                    var key, s3, contentType, res, err_5;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                if (!fileName) {
                                    throw new Error("Invalid File Name provided");
                                }
                                key = 'uploads/' + Date.now() + '-' + fileName;
                                s3 = this.getAWS().s3();
                                _a.label = 1;
                            case 1:
                                _a.trys.push([1, 3, , 4]);
                                contentType = inferNonPDFContentType(fileName);
                                return [4 /*yield*/, s3.putObject({
                                        Bucket: process.env.AWS_S3_BUCKET,
                                        Key: key,
                                        Body: fs.createReadStream(fileData),
                                        ACL: 'private',
                                        ContentType: contentType,
                                        ContentDisposition: 'inline'
                                    })];
                            case 2:
                                res = _a.sent();
                                if (res) {
                                    return [2 /*return*/, file_collection_1.Files.create({
                                            _id: (0, common_1.objectIdHexString)(), __v: 0, name: fileName, size: 1, key: key, order: fileOrder, type: fileType
                                        })];
                                }
                                else {
                                    return [2 /*return*/, null];
                                }
                                return [3 /*break*/, 4];
                            case 3:
                                err_5 = _a.sent();
                                err_5.mesage = 'Error In AWS Upload Non PDF Stream And Save: ' + err_5.mesage;
                                throw err_5;
                            case 4: return [2 /*return*/];
                        }
                    });
                });
            }
        },
        deleteFiles: {
            check: new simpl_schema_1.default({
                keys: {
                    type: Array
                },
                'keys.$': {
                    type: String
                }
            }),
            function: function (keys) {
                return __awaiter(this, void 0, void 0, function () {
                    var files, deleteCnt, files_1, files_1_1, file, s3, res, err_6, e_1_1;
                    var e_1, _a;
                    return __generator(this, function (_b) {
                        switch (_b.label) {
                            case 0:
                                if (!Array.isArray(keys) || keys.length === 0) {
                                    return [2 /*return*/, 0];
                                }
                                return [4 /*yield*/, file_collection_1.Files.find({ key: { $in: keys } })];
                            case 1:
                                files = _b.sent();
                                deleteCnt = files.length;
                                _b.label = 2;
                            case 2:
                                _b.trys.push([2, 10, 11, 12]);
                                files_1 = __values(files), files_1_1 = files_1.next();
                                _b.label = 3;
                            case 3:
                                if (!!files_1_1.done) return [3 /*break*/, 9];
                                file = files_1_1.value;
                                return [4 /*yield*/, file_collection_1.Files.deleteOne({ _id: file._id })];
                            case 4:
                                _b.sent();
                                s3 = this.getAWS().s3();
                                _b.label = 5;
                            case 5:
                                _b.trys.push([5, 7, , 8]);
                                return [4 /*yield*/, s3.deleteObject({
                                        Bucket: process.env.AWS_S3_BUCKET,
                                        Key: file.key
                                    })];
                            case 6:
                                res = _b.sent();
                                if (res) {
                                    deleteCnt--;
                                    if (!deleteCnt) {
                                        return [2 /*return*/, files.length];
                                    }
                                }
                                return [3 /*break*/, 8];
                            case 7:
                                err_6 = _b.sent();
                                err_6.mesage = 'Error In AWS Delete Files: ' + err_6.mesage;
                                throw err_6;
                            case 8:
                                files_1_1 = files_1.next();
                                return [3 /*break*/, 3];
                            case 9: return [3 /*break*/, 12];
                            case 10:
                                e_1_1 = _b.sent();
                                e_1 = { error: e_1_1 };
                                return [3 /*break*/, 12];
                            case 11:
                                try {
                                    if (files_1_1 && !files_1_1.done && (_a = files_1.return)) _a.call(files_1);
                                }
                                finally { if (e_1) throw e_1.error; }
                                return [7 /*endfinally*/];
                            case 12: return [2 /*return*/, 0];
                        }
                    });
                });
            }
        },
        deleteFile: {
            check: new simpl_schema_1.default({
                key: {
                    type: String
                }
            }),
            function: function (key) {
                return __awaiter(this, void 0, void 0, function () {
                    var file, err_7, s3, res, err_8;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, file_collection_1.Files.findOne({ key: key })];
                            case 1:
                                file = _a.sent();
                                if (!file) return [3 /*break*/, 5];
                                _a.label = 2;
                            case 2:
                                _a.trys.push([2, 4, , 5]);
                                return [4 /*yield*/, file_collection_1.Files.deleteOne({ _id: file._id })];
                            case 3:
                                _a.sent();
                                return [3 /*break*/, 5];
                            case 4:
                                err_7 = _a.sent();
                                err_7.mesage = 'Error In AWS Delete File (Resolve Side): ' + err_7.mesage;
                                throw err_7;
                            case 5:
                                s3 = this.getAWS().s3();
                                _a.label = 6;
                            case 6:
                                _a.trys.push([6, 8, , 9]);
                                return [4 /*yield*/, s3.deleteObject({
                                        Bucket: process.env.AWS_S3_BUCKET,
                                        Key: key
                                    })];
                            case 7:
                                res = _a.sent();
                                return [2 /*return*/, res];
                            case 8:
                                err_8 = _a.sent();
                                err_8.mesage = 'Error In AWS Delete File (AWS Side): ' + err_8.mesage;
                                throw err_8;
                            case 9: return [2 /*return*/];
                        }
                    });
                });
            }
        },
        deleteFileWithId: {
            check: new simpl_schema_1.default({
                id_file: {
                    type: String
                }
            }),
            function: function (id_file) {
                return __awaiter(this, void 0, void 0, function () {
                    var file, err_9, s3, res, err_10;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, file_collection_1.Files.findOne({ _id: id_file })];
                            case 1:
                                file = _a.sent();
                                if (!file) {
                                    throw new Error('Error in AWS Delete File With ID: Could not find file');
                                }
                                _a.label = 2;
                            case 2:
                                _a.trys.push([2, 4, , 5]);
                                return [4 /*yield*/, file_collection_1.Files.deleteOne({ _id: file._id })];
                            case 3:
                                _a.sent();
                                return [3 /*break*/, 5];
                            case 4:
                                err_9 = _a.sent();
                                err_9.mesage = 'Error In AWS Delete File With ID (Resolve Side): ' + err_9.mesage;
                                throw err_9;
                            case 5:
                                s3 = this.getAWS().s3();
                                _a.label = 6;
                            case 6:
                                _a.trys.push([6, 8, , 9]);
                                return [4 /*yield*/, s3.deleteObject({
                                        Bucket: process.env.AWS_S3_BUCKET,
                                        Key: file.key
                                    })];
                            case 7:
                                res = _a.sent();
                                return [2 /*return*/, res];
                            case 8:
                                err_10 = _a.sent();
                                err_10.mesage = 'Error In AWS Delete File With ID (AWS Side): ' + err_10.mesage;
                                throw err_10;
                            case 9: return [2 /*return*/];
                        }
                    });
                });
            }
        },
        getSignedUrlsAndFilesWithId: {
            check: new simpl_schema_1.default({
                ids: {
                    type: Array
                },
                'ids.$': {
                    type: String
                },
                expires: {
                    type: Number
                }
            }),
            function: function (ids, expires) {
                return __awaiter(this, void 0, void 0, function () {
                    var res, files, i, file, s3, getCommand, _a, _b;
                    return __generator(this, function (_c) {
                        switch (_c.label) {
                            case 0:
                                res = [];
                                return [4 /*yield*/, file_collection_1.Files.find({ _id: { $in: ids } })];
                            case 1:
                                files = _c.sent();
                                i = 0;
                                _c.label = 2;
                            case 2:
                                if (!(i < files.length)) return [3 /*break*/, 5];
                                file = files[i];
                                s3 = this.getAWS().s3();
                                getCommand = new client_s3_1.GetObjectCommand({
                                    Bucket: process.env.AWS_S3_BUCKET,
                                    Key: file.key
                                });
                                _b = (_a = res).push;
                                return [4 /*yield*/, (0, s3_request_presigner_1.getSignedUrl)(s3, getCommand, { expiresIn: expires })];
                            case 3:
                                _b.apply(_a, [_c.sent()]);
                                _c.label = 4;
                            case 4:
                                i++;
                                return [3 /*break*/, 2];
                            case 5: return [2 /*return*/, { res: res, fileArray: files.map(function (a) { return a.name; }) }];
                        }
                    });
                });
            }
        },
        getSignedUrlWithId: {
            check: new simpl_schema_1.default({
                id_file: {
                    type: String
                },
                expires: {
                    type: Number
                }
            }),
            function: function (id_file, expires) {
                return __awaiter(this, void 0, void 0, function () {
                    var file, s3, getCommand;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, file_collection_1.Files.findOne({ _id: id_file })];
                            case 1:
                                file = _a.sent();
                                s3 = this.getAWS().s3();
                                getCommand = new client_s3_1.GetObjectCommand({
                                    Bucket: process.env.AWS_S3_BUCKET,
                                    Key: file.key
                                });
                                return [2 /*return*/, (0, s3_request_presigner_1.getSignedUrl)(s3, getCommand, { expiresIn: expires })];
                        }
                    });
                });
            }
        },
        getSignedUrlUSEast1BucketAndKey: {
            check: new simpl_schema_1.default({
                bucket: {
                    type: String
                },
                key: {
                    type: String
                },
                expires: {
                    type: Number
                }
            }),
            function: function (bucket, key, expires) {
                var s3 = this.getAWS().s3USEast1();
                var getCommand = new client_s3_1.GetObjectCommand({
                    Bucket: bucket,
                    Key: key
                });
                return (0, s3_request_presigner_1.getSignedUrl)(s3, getCommand, { expiresIn: expires });
            }
        },
        getSignedUrl: {
            check: new simpl_schema_1.default({
                key: {
                    type: String
                },
                expires: {
                    type: Number
                }
            }),
            bypassLogs: true,
            function: function (key, expires) {
                var s3 = this.getAWS().s3();
                var getCommand = new client_s3_1.GetObjectCommand({
                    Bucket: process.env.AWS_S3_BUCKET,
                    Key: key
                });
                return (0, s3_request_presigner_1.getSignedUrl)(s3, getCommand, { expiresIn: expires });
            }
        },
        getSignedUrls: {
            check: new simpl_schema_1.default({
                keys: {
                    type: Array
                },
                'keys.$': {
                    type: String
                },
                expires: {
                    type: Number
                }
            }),
            bypassLogs: true,
            function: function (keys, expires) {
                return __awaiter(this, void 0, void 0, function () {
                    var res, i, key, s3, getCommand, _a, _b;
                    return __generator(this, function (_c) {
                        switch (_c.label) {
                            case 0:
                                res = [];
                                i = 0;
                                _c.label = 1;
                            case 1:
                                if (!(i < keys.length)) return [3 /*break*/, 4];
                                key = keys[i];
                                s3 = this.getAWS().s3();
                                getCommand = new client_s3_1.GetObjectCommand({
                                    Bucket: process.env.AWS_S3_BUCKET,
                                    Key: key
                                });
                                _b = (_a = res).push;
                                return [4 /*yield*/, (0, s3_request_presigner_1.getSignedUrl)(s3, getCommand, { expiresIn: expires })];
                            case 2:
                                _b.apply(_a, [_c.sent()]);
                                _c.label = 3;
                            case 3:
                                i++;
                                return [3 /*break*/, 1];
                            case 4: return [2 /*return*/, res];
                        }
                    });
                });
            }
        },
        getDataURIfromURL: {
            check: new simpl_schema_1.default({
                url: {
                    type: String
                }
            }),
            bypassLogs: true,
            function: function (url) {
                return __awaiter(this, void 0, void 0, function () {
                    var response, contentType, dataBase64;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, axios_1.default.get(url, {
                                    responseType: 'arraybuffer'
                                })];
                            case 1:
                                response = _a.sent();
                                if (response.status !== 200) {
                                    throw new Error("Error in Get Data URI From URL: Failed to fetch URL, status: ".concat(response.status));
                                }
                                contentType = response.headers['content-type'];
                                dataBase64 = Buffer.from(response.data).toString('base64');
                                return [2 /*return*/, "data:".concat(contentType, ";base64,").concat(dataBase64)];
                        }
                    });
                });
            }
        },
        emailFile: {
            check: new simpl_schema_1.default({
                id_file: {
                    type: String
                },
                email: {
                    type: String
                },
                additional_message: {
                    type: String
                }
            }),
            function: function (id_file, email, additional_message) {
                return __awaiter(this, void 0, void 0, function () {
                    var file, resPDF, emailMessage, emailMessage, err_11;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, file_collection_1.Files.findById(id_file)];
                            case 1:
                                file = _a.sent();
                                if (!file) {
                                    throw new Error('Error in AWS Email File: Could not find file');
                                }
                                _a.label = 2;
                            case 2:
                                _a.trys.push([2, 10, , 11]);
                                return [4 /*yield*/, this.callMethod('getSignedUrl', file.key, 259200)];
                            case 3:
                                resPDF = _a.sent();
                                if (!resPDF) return [3 /*break*/, 8];
                                if (!(file.size < 5000000)) return [3 /*break*/, 5];
                                emailMessage = 'Attached is the file requested for email.\n' + (additional_message !== '' ? '\nAdditional Message:\n' + additional_message + '\n' : '');
                                return [4 /*yield*/, this.sendEmail(email, resolveio_server_app_1.ResolveIOServer.getClientName() + ' File - ' + file.name, emailMessage, '', [{
                                            filename: file.name,
                                            path: resPDF
                                        }], null, '')];
                            case 4:
                                _a.sent();
                                return [3 /*break*/, 7];
                            case 5:
                                emailMessage = 'Please click the link to the requested file.\n' + (additional_message !== '' ? '\nAdditional Message:\n' + additional_message + '\n' : '');
                                return [4 /*yield*/, this.sendEmail(email, resolveio_server_app_1.ResolveIOServer.getClientName() + ' File - ' + file.name, emailMessage + resPDF, '', null, null, '')];
                            case 6:
                                _a.sent();
                                _a.label = 7;
                            case 7: return [2 /*return*/, true];
                            case 8: throw new Error('Error in AWS Email File: Could not get file URL');
                            case 9: return [3 /*break*/, 11];
                            case 10:
                                err_11 = _a.sent();
                                err_11.mesage = 'Error In AWS Email File: ' + err_11.mesage;
                                throw err_11;
                            case 11: return [2 /*return*/];
                        }
                    });
                });
            }
        }
    });
}

//# sourceMappingURL=aws.js.map
