"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const KoaRouter = require("@koa/router");
// import * as KoaBody from 'koa-body';
const KoaSend = require("koa-send");
const Config_1 = require("../lib/Config");
const Logger_1 = require("../lib/Logger");
const MediaStream_1 = require("../store/MediaStream");
const Auth_1 = require("../middlewares/Auth");
const RBAC_1 = require("../middlewares/RBAC");
const Room_1 = require("../store/Room");
const Session_1 = require("../store/Session");
const router = new KoaRouter();
const logger = Logger_1.default.of('http');
router.get('/media-stream/:id/index.m3u8', Auth_1.default, RBAC_1.default, async (ctx, next) => {
    const streamId = Number(ctx.params.id);
    const { ownerType, ownerId } = ctx.state;
    const session = Session_1.default.get(`${ownerType}/${ownerId}`);
    const stream = await MediaStream_1.default.findByPk(streamId);
    const room = await Room_1.Room.findByPk(stream.roomId, session.gapperToken);
    const roles = await (0, RBAC_1.contextRoles)(ctx, (room === null || room === void 0 ? void 0 : room.groupId) || 0);
    if (![
        'admin',
        '%admin',
        '@matrix.admin',
        '@matrix.view_video',
        'app.rtsp-proxy',
        'authenticated.device',
        '@rtsp-proxy.admin',
    ].find((it) => roles.includes(it))) {
        ctx.status = 401;
        return;
    }
    if (stream === undefined) {
        return;
    }
    if (!ownerType || (ownerType === 'device' && (!stream.devices || !stream.devices.includes(ownerId)))) {
        ctx.status = 401;
        logger.debug(`401 state=${JSON.stringify(ctx.state)} devices=${JSON.stringify(stream.devices)}`, {
            state: ctx.state,
            devices: stream.devices,
        });
        return;
    }
    try {
        await stream.startConversion();
        ctx.state.stream = stream;
        await next();
    }
    catch (e) {
        ctx.status = 400;
        ctx.body = e.message || String(e);
    }
});
// router.use(KoaBody({ multipart: true }));
// GET http://xxxx/media-stream/:id/index.m3u8
router.get('/media-stream/:id/:path*', async (ctx) => {
    const streamId = Number(ctx.params.id);
    const filePath = String(ctx.params.path);
    if (!filePath || filePath.startsWith('.')) {
        return;
    }
    const stream = ctx.state.stream || (await MediaStream_1.default.findByPk(streamId));
    if (stream === undefined) {
        return;
    }
    try {
        if ((0, fs_1.existsSync)(`${Config_1.default.cacheRoot}/${streamId}/${filePath}`)) {
            // if (stream.status === MediaStreamStatus.DECODING || stream.status === MediaStreamStatus.END) {
            await KoaSend(ctx, filePath, {
                root: `${Config_1.default.cacheRoot}/${streamId}`,
                immutable: false,
                maxAge: 0,
            });
        }
        else {
            logger.error('in noise');
            await KoaSend(ctx, filePath, {
                root: `${Config_1.default.assetRoot}/noise`,
                immutable: false,
                maxAge: 0,
            });
        }
    }
    catch (e) {
        logger.error(e.message || String(e));
    }
});
exports.default = router.routes();
