"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: all[name]
    });
}
_export(exports, {
    ServerPrivateController: function() {
        return ServerPrivateController;
    },
    default: function() {
        return _default;
    }
});
const _stream = require("stream");
const _awilixexpress = require("awilix-express");
const _authenticate = require("../middleware/authenticate");
const _logger = require("../handlers/logger");
const _serverconstants = require("../server.constants");
const _authorizationconstants = require("../constants/authorization.constants");
const _envutils = require("../utils/env.utils");
const _validators = require("../handlers/validators");
const _demomiddleware = require("../middleware/demo.middleware");
class ServerPrivateController {
    clientBundleService;
    printerCache;
    printerService;
    printerSocketStore;
    githubService;
    yamlService;
    multerService;
    logDumpService;
    logger = new _logger.LoggerService(ServerPrivateController.name);
    serverUpdateService;
    serverReleaseService;
    constructor({ serverUpdateService, serverReleaseService, printerCache, printerService, clientBundleService, githubService, logDumpService, printerSocketStore, yamlService, multerService }){
        this.serverReleaseService = serverReleaseService;
        this.serverUpdateService = serverUpdateService;
        this.clientBundleService = clientBundleService;
        this.githubService = githubService;
        this.logDumpService = logDumpService;
        this.printerSocketStore = printerSocketStore;
        this.printerCache = printerCache;
        this.printerService = printerService;
        this.yamlService = yamlService;
        this.multerService = multerService;
    }
    async getClientReleases(req, res) {
        const releaseSpec = await this.clientBundleService.getReleases();
        res.send(releaseSpec);
    }
    async updateClientBundleGithub(req, res) {
        const inputRules = {
            downloadRelease: "string",
            allowDowngrade: "boolean"
        };
        const updateDto = await (0, _validators.validateMiddleware)(req, inputRules);
        const willExecute = await this.clientBundleService.shouldUpdateWithReason(true, _serverconstants.AppConstants.defaultClientMinimum, updateDto.downloadRelease, updateDto.allowDowngrade);
        this.logger.log(`Will execute: ${willExecute?.shouldUpdate}, reason: ${willExecute?.reason}`);
        if (!willExecute?.shouldUpdate) {
            return res.send({
                executed: false,
                requestedVersion: willExecute.requestedVersion,
                currentVersion: willExecute.currentVersion,
                minimumVersion: willExecute.minimumVersion,
                shouldUpdate: willExecute.shouldUpdate,
                targetVersion: willExecute.targetVersion,
                reason: willExecute?.reason
            });
        }
        const tag_name = await this.clientBundleService.downloadClientUpdate(willExecute.targetVersion);
        return res.send({
            executed: true,
            requestedVersion: willExecute.requestedVersion,
            currentVersion: willExecute.currentVersion,
            minimumVersion: willExecute.minimumVersion,
            shouldUpdate: willExecute.shouldUpdate,
            targetVersion: willExecute.targetVersion,
            reason: willExecute?.reason
        });
    }
    async getGithubRateLimit(req, res) {
        const rateLimitResponse = await this.githubService.getRateLimit();
        res.send(rateLimitResponse.data);
    }
    async getReleaseStateInfo(req, res) {
        await this.serverReleaseService.syncLatestRelease();
        const updateState = this.serverReleaseService.getState();
        res.send(updateState);
    }
    async pullGitUpdates(req, res) {
        const result = await this.serverUpdateService.checkGitUpdates();
        res.send(result);
    }
    async restartServer(req, res) {
        if (!(0, _envutils.isTestEnvironment)()) {
            this.logger.warn("Server restart command fired. Expect the server to be unavailable for a moment");
        }
        const result = await this.serverUpdateService.restartServer();
        res.send(result);
    }
    async importPrintersAndFloorsYaml(req, res) {
        const files = await this.multerService.multerLoadFileAsync(req, res, ".yaml", false);
        const firstFile = files[0];
        const spec = await this.yamlService.importPrintersAndFloors(firstFile.buffer.toString());
        res.send({
            success: true,
            spec
        });
    }
    async exportPrintersAndFloorsYaml(req, res) {
        const yaml = await this.yamlService.exportPrintersAndFloors(req.body);
        const fileContents = Buffer.from(yaml);
        const readStream = new _stream.PassThrough();
        readStream.end(fileContents);
        const fileName = `export-${_serverconstants.AppConstants.serverRepoName}-` + Date.now() + ".yaml";
        res.set("Content-disposition", "attachment; filename=" + fileName);
        res.set("Content-Type", "text/plain");
        readStream.pipe(res);
    }
    async deleteAllPrinters(req, res) {
        const printers = await this.printerCache.listCachedPrinters(true);
        const printerIds = printers.map((p)=>p.id);
        await this.printerService.deleteMany(printerIds);
        res.send();
    }
    async clearLogs(req, res) {
        const counts = await this.logDumpService.deleteOlderThanWeekAndMismatchingLogFiles();
        res.send(counts);
    }
    async dumpLogZips(req, res) {
        const filePath = await this.logDumpService.dumpZip();
        res.sendFile(filePath);
    }
}
const _default = (0, _awilixexpress.createController)(ServerPrivateController).prefix(_serverconstants.AppConstants.apiRoute + "/server").before([
    (0, _authenticate.authenticate)(),
    (0, _authenticate.authorizeRoles)([
        _authorizationconstants.ROLES.ADMIN
    ]),
    _demomiddleware.demoUserNotAllowed
]).get("/", "getReleaseStateInfo").get("/client-releases", "getClientReleases").get("/github-rate-limit", "getGithubRateLimit").post("/update-client-bundle-github", "updateClientBundleGithub").post("/export-printers-floors-yaml", "exportPrintersAndFloorsYaml").post("/import-printers-floors-yaml", "importPrintersAndFloorsYaml").post("/git-update", "pullGitUpdates").post("/restart", "restartServer").get("/dump-fdm-monster-logs", "dumpLogZips").post("/dump-fdm-monster-logs", "dumpLogZips").delete("/clear-outdated-fdm-monster-logs", "clearLogs").delete("/delete-all-printers", "deleteAllPrinters");

//# sourceMappingURL=server-private.controller.js.map