"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.viewRouter = void 0;
const tslib_1 = require("tslib");
const express_1 = tslib_1.__importDefault(require("express"));
const hooks_1 = require("../../../lib/plugins/hooks");
const video_views_manager_1 = require("../../../lib/views/video-views-manager");
const middlewares_1 = require("../../../middlewares");
const user_video_history_1 = require("../../../models/user/user-video-history");
const viewRouter = express_1.default.Router();
exports.viewRouter = viewRouter;
viewRouter.all(['/:videoId/views', '/:videoId/watching'], (0, middlewares_1.openapiOperationDoc)({ operationId: 'addView' }), (0, middlewares_1.methodsValidator)(['PUT', 'POST']), middlewares_1.optionalAuthenticate, (0, middlewares_1.asyncMiddleware)(middlewares_1.videoViewValidator), (0, middlewares_1.asyncMiddleware)(viewVideo));
function viewVideo(req, res) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const video = res.locals.onlyImmutableVideo;
        const body = req.body;
        const ip = req.ip;
        const { successView } = yield video_views_manager_1.VideoViewsManager.Instance.processLocalView({
            video,
            ip,
            currentTime: body.currentTime,
            viewEvent: body.viewEvent
        });
        if (successView) {
            hooks_1.Hooks.runAction('action:api.video.viewed', { video, ip, req, res });
        }
        yield updateUserHistoryIfNeeded(body, video, res);
        return res.status(204).end();
    });
}
function updateUserHistoryIfNeeded(body, video, res) {
    var _a;
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const user = (_a = res.locals.oauth) === null || _a === void 0 ? void 0 : _a.token.User;
        if (!user)
            return;
        if (user.videosHistoryEnabled !== true)
            return;
        yield user_video_history_1.UserVideoHistoryModel.upsert({
            videoId: video.id,
            userId: user.id,
            currentTime: body.currentTime
        });
    });
}
//# sourceMappingURL=view.js.map