"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "ServerPrivateController", {
    enumerable: true,
    get: function() {
        return ServerPrivateController;
    }
});
const _nodestream = require("node:stream");
const _awilixexpress = require("awilix-express");
const _authenticate = require("../middleware/authenticate");
const _serverconstants = require("../server.constants");
const _authorizationconstants = require("../constants/authorization.constants");
const _validators = require("../handlers/validators");
const _serverreleaseservice = require("../services/core/server-release.service");
const _clientbundleservice = require("../services/core/client-bundle.service");
const _printercache = require("../state/printer.cache");
const _yamlservice = require("../services/core/yaml.service");
const _multerservice = require("../services/core/multer.service");
const _logsmanagerservice = require("../services/core/logs-manager.service");
const _express = require("express");
const _demomiddleware = require("../middleware/demo.middleware");
const _githubservice = require("../services/core/github.service");
const _printerserviceinterface = require("../services/interfaces/printer.service.interface");
const _serverprivatevalidation = require("./validation/server-private.validation");
const _loggerfactory = require("../handlers/logger-factory");
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 ServerPrivateController {
    serverReleaseService;
    printerCache;
    printerService;
    clientBundleService;
    githubService;
    logDumpService;
    yamlService;
    multerService;
    logger;
    constructor(loggerFactory, serverReleaseService, printerCache, printerService, clientBundleService, githubService, logDumpService, yamlService, multerService){
        this.serverReleaseService = serverReleaseService;
        this.printerCache = printerCache;
        this.printerService = printerService;
        this.clientBundleService = clientBundleService;
        this.githubService = githubService;
        this.logDumpService = logDumpService;
        this.yamlService = yamlService;
        this.multerService = multerService;
        this.logger = loggerFactory(ServerPrivateController.name);
    }
    async getReleaseStateInfo(req, res) {
        await this.serverReleaseService.syncLatestRelease();
        const updateState = this.serverReleaseService.getState();
        res.send(updateState);
    }
    async getClientReleases(_req, res) {
        const releaseSpec = await this.clientBundleService.getReleases();
        res.send(releaseSpec);
    }
    async updateClientBundleGithub(req, res) {
        const updateDto = await (0, _validators.validateMiddleware)(req, _serverprivatevalidation.updateClientBundleSchema);
        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
            });
        }
        if (willExecute.targetVersion) {
            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 importYaml(req, res) {
        const files = await this.multerService.multerLoadFileAsync(req, res, [
            ".yaml",
            ".yml"
        ], false);
        const firstFile = files[0];
        const spec = await this.yamlService.importYaml(firstFile.buffer.toString());
        res.send({
            success: true,
            spec
        });
    }
    async exportYaml(req, res) {
        const yaml = await this.yamlService.exportYaml(req.body);
        const fileContents = Buffer.from(yaml);
        const readStream = new _nodestream.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);
    }
}
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/"),
    _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)
], ServerPrivateController.prototype, "getReleaseStateInfo", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/client-releases"),
    _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)
], ServerPrivateController.prototype, "getClientReleases", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/update-client-bundle-github"),
    _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)
], ServerPrivateController.prototype, "updateClientBundleGithub", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/github-rate-limit"),
    _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)
], ServerPrivateController.prototype, "getGithubRateLimit", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/yaml-import"),
    _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)
], ServerPrivateController.prototype, "importYaml", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/yaml-export"),
    _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)
], ServerPrivateController.prototype, "exportYaml", null);
_ts_decorate([
    (0, _awilixexpress.DELETE)(),
    (0, _awilixexpress.route)("/delete-all-printers"),
    _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)
], ServerPrivateController.prototype, "deleteAllPrinters", null);
_ts_decorate([
    (0, _awilixexpress.DELETE)(),
    (0, _awilixexpress.route)("/clear-outdated-fdm-monster-logs"),
    _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)
], ServerPrivateController.prototype, "clearLogs", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/dump-fdm-monster-logs"),
    _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)
], ServerPrivateController.prototype, "dumpLogZips", null);
ServerPrivateController = _ts_decorate([
    (0, _awilixexpress.route)(_serverconstants.AppConstants.apiRoute + "/server"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authenticate)(),
        (0, _authenticate.authorizeRoles)([
            _authorizationconstants.ROLES.ADMIN
        ]),
        _demomiddleware.demoUserNotAllowed
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _loggerfactory.ILoggerFactory === "undefined" ? Object : _loggerfactory.ILoggerFactory,
        typeof _serverreleaseservice.ServerReleaseService === "undefined" ? Object : _serverreleaseservice.ServerReleaseService,
        typeof _printercache.PrinterCache === "undefined" ? Object : _printercache.PrinterCache,
        typeof _printerserviceinterface.IPrinterService === "undefined" ? Object : _printerserviceinterface.IPrinterService,
        typeof _clientbundleservice.ClientBundleService === "undefined" ? Object : _clientbundleservice.ClientBundleService,
        typeof _githubservice.GithubService === "undefined" ? Object : _githubservice.GithubService,
        typeof _logsmanagerservice.LogDumpService === "undefined" ? Object : _logsmanagerservice.LogDumpService,
        typeof _yamlservice.YamlService === "undefined" ? Object : _yamlservice.YamlService,
        typeof _multerservice.MulterService === "undefined" ? Object : _multerservice.MulterService
    ])
], ServerPrivateController);

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