"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "PrinterFilesController", {
    enumerable: true,
    get: function() {
        return PrinterFilesController;
    }
});
const _awilixexpress = require("awilix-express");
const _authenticate = require("../middleware/authenticate");
const _validators = require("../handlers/validators");
const _serverconstants = require("../server.constants");
const _printerfilescontrollervalidation = require("./validation/printer-files-controller.validation");
const _runtimeexceptions = require("../exceptions/runtime.exceptions");
const _printer = require("../middleware/printer");
const _authorizationconstants = require("../constants/authorization.constants");
const _express = require("express");
function _ts_decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function _ts_metadata(k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
}
class PrinterFilesController {
    printerApi;
    printerFilesStore;
    settingsStore;
    batchCallService;
    multerService;
    printerFileCleanTask;
    logger;
    constructor({ printerApi, printerFilesStore, batchCallService, printerFileCleanTask, settingsStore, loggerFactory, multerService }){
        this.printerApi = printerApi;
        this.printerFilesStore = printerFilesStore;
        this.settingsStore = settingsStore;
        this.printerFileCleanTask = printerFileCleanTask;
        this.batchCallService = batchCallService;
        this.multerService = multerService;
        this.logger = loggerFactory(PrinterFilesController.name);
    }
    getTrackedUploads(req, res) {
        const sessions = this.multerService.getSessions();
        res.send(sessions);
    }
    async purgeIndexedFiles(req, res) {
        await this.printerFilesStore.purgeFiles();
        res.send();
    }
    async getFiles(req, res) {
        const { currentPrinterId } = (0, _validators.getScopedPrinter)(req);
        this.logger.log("Refreshing file storage (eager load)");
        const files = await this.printerFilesStore.loadFiles(currentPrinterId);
        res.send(files);
    }
    async startPrintFile(req, res) {
        const { filePath } = await (0, _validators.validateInput)(req.body, _printerfilescontrollervalidation.startPrintFileRules);
        await this.printerApi.startPrint(filePath);
        res.send();
    }
    async getFilesCache(req, res) {
        const { currentPrinter } = (0, _validators.getScopedPrinter)(req);
        res.send(this.printerFilesStore.getFiles(currentPrinter.id));
    }
    async downloadFile(req, res) {
        this.logger.log(`Downloading file ${req.params.path}`);
        const { path } = await (0, _validators.validateInput)(req.params, _printerfilescontrollervalidation.downloadFileRules);
        const response = await this.printerApi.downloadFile(path);
        res.setHeader("Content-Type", response.headers["content-type"]);
        res.setHeader("Content-Length", response.headers["content-length"]);
        res.setHeader("Content-Disposition", response.headers["content-disposition"]);
        if (response.headers["etag"]?.length) {
            res.setHeader("ETag", response.headers["etag"]);
        }
        response.data.pipe(res);
    }
    async deleteFileOrFolder(req, res) {
        const { currentPrinterId } = (0, _validators.getScopedPrinter)(req);
        const { path } = await (0, _validators.validateInput)(req.query, _printerfilescontrollervalidation.getFileRules);
        const result = await this.printerApi.deleteFile(path);
        await this.printerFilesStore.deleteFile(currentPrinterId, path);
        res.send(result);
    }
    async clearPrinterFiles(req, res) {
        const { currentPrinterId } = (0, _validators.getScopedPrinter)(req);
        const failedFiles = [];
        const succeededFiles = [];
        const nonRecursiveFiles = await this.printerApi.getFiles();
        for (let file of nonRecursiveFiles){
            try {
                await this.printerApi.deleteFile(file.path);
                succeededFiles.push(file);
            } catch (e) {
                failedFiles.push(file);
            }
        }
        await this.printerFilesStore.purgePrinterFiles(currentPrinterId);
        res.send({
            failedFiles,
            succeededFiles
        });
    }
    async uploadFile(req, res) {
        const { currentPrinterId } = (0, _validators.getScopedPrinter)(req);
        const files = await this.multerService.multerLoadFileAsync(req, res, ".gcode", true);
        if (!files?.length) {
            throw new _runtimeexceptions.ValidationException({
                error: "No file was available for upload. Did you upload files with extension '.gcode'?"
            });
        }
        if (files.length > 1) {
            throw new _runtimeexceptions.ValidationException({
                error: "Only 1 .gcode file can be uploaded at a time due to bandwidth restrictions"
            });
        }
        const fileCleanEnabled = this.settingsStore.isPreUploadFileCleanEnabled();
        if (fileCleanEnabled) {
            await this.printerFileCleanTask.cleanPrinterFiles(currentPrinterId);
        }
        const uploadedFile = files[0];
        const token = this.multerService.startTrackingSession(uploadedFile);
        await this.printerApi.uploadFile(uploadedFile, token);
        await this.printerFilesStore.loadFiles(currentPrinterId);
        res.send();
    }
}
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/tracked-uploads"),
    (0, _awilixexpress.before)((0, _authenticate.authorizePermission)(_authorizationconstants.PERMS.PrinterFiles.Upload)),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", void 0)
], PrinterFilesController.prototype, "getTrackedUploads", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/purge"),
    (0, _awilixexpress.before)((0, _authenticate.authorizePermission)(_authorizationconstants.PERMS.PrinterFiles.Clear)),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PrinterFilesController.prototype, "purgeIndexedFiles", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/:id"),
    (0, _awilixexpress.before)((0, _authenticate.authorizePermission)(_authorizationconstants.PERMS.PrinterFiles.Get)),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PrinterFilesController.prototype, "getFiles", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:id/select"),
    (0, _awilixexpress.route)("/:id/print"),
    (0, _awilixexpress.before)((0, _authenticate.authorizePermission)(_authorizationconstants.PERMS.PrinterFiles.Actions)),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PrinterFilesController.prototype, "startPrintFile", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/:id/cache"),
    (0, _awilixexpress.before)((0, _authenticate.authorizePermission)(_authorizationconstants.PERMS.PrinterFiles.Get)),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PrinterFilesController.prototype, "getFilesCache", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/:id/download/:path"),
    (0, _awilixexpress.before)((0, _authenticate.authorizePermission)(_authorizationconstants.PERMS.PrinterFiles.Get)),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PrinterFilesController.prototype, "downloadFile", null);
_ts_decorate([
    (0, _awilixexpress.DELETE)(),
    (0, _awilixexpress.route)("/:id"),
    (0, _awilixexpress.before)((0, _authenticate.authorizePermission)(_authorizationconstants.PERMS.PrinterFiles.Delete)),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PrinterFilesController.prototype, "deleteFileOrFolder", null);
_ts_decorate([
    (0, _awilixexpress.DELETE)(),
    (0, _awilixexpress.route)("/:id/clear"),
    (0, _awilixexpress.before)((0, _authenticate.authorizePermission)(_authorizationconstants.PERMS.PrinterFiles.Clear)),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PrinterFilesController.prototype, "clearPrinterFiles", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:id/upload"),
    (0, _awilixexpress.before)((0, _authenticate.authorizePermission)(_authorizationconstants.PERMS.PrinterFiles.Upload)),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PrinterFilesController.prototype, "uploadFile", null);
PrinterFilesController = _ts_decorate([
    (0, _awilixexpress.route)(_serverconstants.AppConstants.apiRoute + "/printer-files"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authenticate)(),
        (0, _authenticate.authorizeRoles)([
            _authorizationconstants.ROLES.ADMIN,
            _authorizationconstants.ROLES.OPERATOR
        ]),
        (0, _printer.printerResolveMiddleware)()
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        Object
    ])
], PrinterFilesController);

//# sourceMappingURL=printer-files.controller.js.map