"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.objectStorageProxyRouter = void 0;
const tslib_1 = require("tslib");
const cors_1 = tslib_1.__importDefault(require("cors"));
const express_1 = tslib_1.__importDefault(require("express"));
const stream_1 = require("stream");
const logger_1 = require("../helpers/logger");
const stream_replacer_1 = require("../helpers/stream-replacer");
const constants_1 = require("../initializers/constants");
const hls_1 = require("../lib/hls");
const object_storage_1 = require("../lib/object-storage");
const middlewares_1 = require("../middlewares");
const m3u8_playlist_1 = require("./shared/m3u8-playlist");
const objectStorageProxyRouter = express_1.default.Router();
exports.objectStorageProxyRouter = objectStorageProxyRouter;
objectStorageProxyRouter.use((0, cors_1.default)());
objectStorageProxyRouter.get(constants_1.OBJECT_STORAGE_PROXY_PATHS.PRIVATE_WEBSEED + ':filename', middlewares_1.ensurePrivateObjectStorageProxyIsEnabled, middlewares_1.optionalAuthenticate, (0, middlewares_1.asyncMiddleware)(middlewares_1.ensureCanAccessVideoPrivateWebTorrentFiles), (0, middlewares_1.asyncMiddleware)(proxifyWebTorrent));
objectStorageProxyRouter.get(constants_1.OBJECT_STORAGE_PROXY_PATHS.STREAMING_PLAYLISTS.PRIVATE_HLS + ':videoUUID/:filename', middlewares_1.ensurePrivateObjectStorageProxyIsEnabled, middlewares_1.optionalAuthenticate, (0, middlewares_1.asyncMiddleware)(middlewares_1.ensureCanAccessPrivateVideoHLSFiles), (0, middlewares_1.asyncMiddleware)(proxifyHLS));
function proxifyWebTorrent(req, res) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const filename = req.params.filename;
        logger_1.logger.debug('Proxifying WebTorrent file %s from object storage.', filename);
        try {
            const { response: s3Response, stream } = yield (0, object_storage_1.getWebTorrentFileReadStream)({
                filename,
                rangeHeader: req.header('range')
            });
            setS3Headers(res, s3Response);
            return stream.pipe(res);
        }
        catch (err) {
            return handleObjectStorageFailure(res, err);
        }
    });
}
function proxifyHLS(req, res) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const playlist = res.locals.videoStreamingPlaylist;
        const video = res.locals.onlyVideo;
        const filename = req.params.filename;
        logger_1.logger.debug('Proxifying HLS file %s from object storage.', filename);
        try {
            const { response: s3Response, stream } = yield (0, object_storage_1.getHLSFileReadStream)({
                playlist: playlist.withVideo(video),
                filename,
                rangeHeader: req.header('range')
            });
            setS3Headers(res, s3Response);
            const streamReplacer = filename.endsWith('.m3u8') && (0, m3u8_playlist_1.doReinjectVideoFileToken)(req)
                ? new stream_replacer_1.StreamReplacer(line => (0, hls_1.injectQueryToPlaylistUrls)(line, (0, m3u8_playlist_1.buildReinjectVideoFileTokenQuery)(req)))
                : new stream_1.PassThrough();
            return (0, stream_1.pipeline)(stream, streamReplacer, res, err => {
                if (!err)
                    return;
                handleObjectStorageFailure(res, err);
            });
        }
        catch (err) {
            return handleObjectStorageFailure(res, err);
        }
    });
}
function handleObjectStorageFailure(res, err) {
    if (err.name === 'NoSuchKey') {
        logger_1.logger.debug('Could not find key in object storage to proxify private HLS video file.', { err });
        return res.sendStatus(404);
    }
    return res.fail({
        status: 500,
        message: err.message,
        type: err.name
    });
}
function setS3Headers(res, s3Response) {
    if (s3Response.$metadata.httpStatusCode === 206) {
        res.status(206);
    }
}
//# sourceMappingURL=object-storage-proxy.js.map