"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.liveRouter = void 0;
const tslib_1 = require("tslib");
const express_1 = tslib_1.__importDefault(require("express"));
const misc_1 = require("../../../helpers/custom-validators/misc");
const express_utils_1 = require("../../../helpers/express-utils");
const utils_1 = require("../../../helpers/utils");
const constants_1 = require("../../../initializers/constants");
const url_1 = require("../../../lib/activitypub/url");
const videos_1 = require("../../../lib/activitypub/videos");
const hooks_1 = require("../../../lib/plugins/hooks");
const video_1 = require("../../../lib/video");
const video_live_1 = require("../../../middlewares/validators/videos/video-live");
const video_live_2 = require("../../../models/video/video-live");
const video_live_session_1 = require("../../../models/video/video-live-session");
const extra_utils_1 = require("../../../../shared/extra-utils");
const logger_1 = require("../../../helpers/logger");
const database_1 = require("../../../initializers/database");
const thumbnail_1 = require("../../../lib/thumbnail");
const middlewares_1 = require("../../../middlewares");
const video_2 = require("../../../models/video/video");
const liveRouter = express_1.default.Router();
exports.liveRouter = liveRouter;
const reqVideoFileLive = (0, express_utils_1.createReqFiles)(['thumbnailfile', 'previewfile'], constants_1.MIMETYPES.IMAGE.MIMETYPE_EXT);
liveRouter.post('/live', middlewares_1.authenticate, reqVideoFileLive, (0, middlewares_1.asyncMiddleware)(video_live_1.videoLiveAddValidator), (0, middlewares_1.asyncRetryTransactionMiddleware)(addLiveVideo));
liveRouter.get('/live/:videoId/sessions', middlewares_1.authenticate, (0, middlewares_1.asyncMiddleware)(video_live_1.videoLiveGetValidator), video_live_1.videoLiveListSessionsValidator, (0, middlewares_1.asyncMiddleware)(getLiveVideoSessions));
liveRouter.get('/live/:videoId', middlewares_1.optionalAuthenticate, (0, middlewares_1.asyncMiddleware)(video_live_1.videoLiveGetValidator), getLiveVideo);
liveRouter.put('/live/:videoId', middlewares_1.authenticate, (0, middlewares_1.asyncMiddleware)(video_live_1.videoLiveGetValidator), video_live_1.videoLiveUpdateValidator, (0, middlewares_1.asyncRetryTransactionMiddleware)(updateLiveVideo));
liveRouter.get('/:videoId/live-session', (0, middlewares_1.asyncMiddleware)(video_live_1.videoLiveFindReplaySessionValidator), getLiveReplaySession);
function getLiveVideo(req, res) {
    const videoLive = res.locals.videoLive;
    return res.json(videoLive.toFormattedJSON(canSeePrivateLiveInformation(res)));
}
function getLiveReplaySession(req, res) {
    const session = res.locals.videoLiveSession;
    return res.json(session.toFormattedJSON());
}
function getLiveVideoSessions(req, res) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const videoLive = res.locals.videoLive;
        const data = yield video_live_session_1.VideoLiveSessionModel.listSessionsOfLiveForAPI({ videoId: videoLive.videoId });
        return res.json((0, utils_1.getFormattedObjects)(data, data.length));
    });
}
function canSeePrivateLiveInformation(res) {
    var _a;
    const user = (_a = res.locals.oauth) === null || _a === void 0 ? void 0 : _a.token.User;
    if (!user)
        return false;
    if (user.hasRight(19))
        return true;
    const video = res.locals.videoAll;
    return video.VideoChannel.Account.userId === user.id;
}
function updateLiveVideo(req, res) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const body = req.body;
        const video = res.locals.videoAll;
        const videoLive = res.locals.videoLive;
        if ((0, misc_1.exists)(body.saveReplay))
            videoLive.saveReplay = body.saveReplay;
        if ((0, misc_1.exists)(body.permanentLive))
            videoLive.permanentLive = body.permanentLive;
        if ((0, misc_1.exists)(body.latencyMode))
            videoLive.latencyMode = body.latencyMode;
        video.VideoLive = yield videoLive.save();
        yield (0, videos_1.federateVideoIfNeeded)(video, false);
        return res.status(204).end();
    });
}
function addLiveVideo(req, res) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const videoInfo = req.body;
        let videoData = (0, video_1.buildLocalVideoFromReq)(videoInfo, res.locals.videoChannel.id);
        videoData = yield hooks_1.Hooks.wrapObject(videoData, 'filter:api.video.live.video-attribute.result');
        videoData.isLive = true;
        videoData.state = 4;
        videoData.duration = 0;
        const video = new video_2.VideoModel(videoData);
        video.url = (0, url_1.getLocalVideoActivityPubUrl)(video);
        const videoLive = new video_live_2.VideoLiveModel();
        videoLive.saveReplay = videoInfo.saveReplay || false;
        videoLive.permanentLive = videoInfo.permanentLive || false;
        videoLive.latencyMode = videoInfo.latencyMode || 1;
        videoLive.streamKey = (0, extra_utils_1.buildUUID)();
        const [thumbnailModel, previewModel] = yield (0, video_1.buildVideoThumbnailsFromReq)({
            video,
            files: req.files,
            fallback: type => {
                return (0, thumbnail_1.updateVideoMiniatureFromExisting)({
                    inputPath: constants_1.ASSETS_PATH.DEFAULT_LIVE_BACKGROUND,
                    video,
                    type,
                    automaticallyGenerated: true,
                    keepOriginal: true
                });
            }
        });
        const { videoCreated } = yield database_1.sequelizeTypescript.transaction((t) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            const sequelizeOptions = { transaction: t };
            const videoCreated = yield video.save(sequelizeOptions);
            if (thumbnailModel)
                yield videoCreated.addAndSaveThumbnail(thumbnailModel, t);
            if (previewModel)
                yield videoCreated.addAndSaveThumbnail(previewModel, t);
            videoCreated.VideoChannel = res.locals.videoChannel;
            videoLive.videoId = videoCreated.id;
            videoCreated.VideoLive = yield videoLive.save(sequelizeOptions);
            yield (0, video_1.setVideoTags)({ video, tags: videoInfo.tags, transaction: t });
            yield (0, videos_1.federateVideoIfNeeded)(videoCreated, true, t);
            logger_1.logger.info('Video live %s with uuid %s created.', videoInfo.name, videoCreated.uuid);
            return { videoCreated };
        }));
        hooks_1.Hooks.runAction('action:api.live-video.created', { video: videoCreated, req, res });
        return res.json({
            video: {
                id: videoCreated.id,
                shortUUID: (0, extra_utils_1.uuidToShort)(videoCreated.uuid),
                uuid: videoCreated.uuid
            }
        });
    });
}
//# sourceMappingURL=live.js.map