"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VideoViews = void 0;
const tslib_1 = require("tslib");
const logger_1 = require("../../../helpers/logger");
const send_view_1 = require("../../activitypub/send/send-view");
const video_1 = require("../../video");
const application_1 = require("../../../models/application/application");
const extra_utils_1 = require("../../../../shared/extra-utils");
const redis_1 = require("../../redis");
const lTags = (0, logger_1.loggerTagsFactory)('views');
class VideoViews {
    addLocalView(options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { video, ip, watchTime } = options;
            logger_1.logger.debug('Adding local view to video %s.', video.uuid, Object.assign({ watchTime }, lTags(video.uuid)));
            if (!(yield this.hasEnoughWatchTime(video, watchTime)))
                return false;
            const viewExists = yield redis_1.Redis.Instance.doesVideoIPViewExist(ip, video.uuid);
            if (viewExists)
                return false;
            yield redis_1.Redis.Instance.setIPVideoView(ip, video.uuid);
            yield this.addView(video);
            yield (0, send_view_1.sendView)({ byActor: yield (0, application_1.getServerActor)(), video, type: 'view', viewerIdentifier: (0, extra_utils_1.buildUUID)() });
            return true;
        });
    }
    addRemoteView(options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { video } = options;
            logger_1.logger.debug('Adding remote view to video %s.', video.uuid, Object.assign({}, lTags(video.uuid)));
            yield this.addView(video);
            return true;
        });
    }
    addView(video) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const promises = [];
            if (video.isOwned()) {
                promises.push(redis_1.Redis.Instance.addLocalVideoView(video.id));
            }
            promises.push(redis_1.Redis.Instance.addVideoViewStats(video.id));
            yield Promise.all(promises);
        });
    }
    hasEnoughWatchTime(video, watchTime) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { duration, isLive } = yield (0, video_1.getCachedVideoDuration)(video.id);
            if (isLive || duration >= 30)
                return watchTime >= 30;
            return duration / watchTime < 2;
        });
    }
}
exports.VideoViews = VideoViews;
//# sourceMappingURL=video-views.js.map