"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkActivityPubUrls = exports.applicationExist = exports.usersExist = exports.checkFFmpegVersion = exports.clientsExist = exports.checkConfig = void 0;
const tslib_1 = require("tslib");
const config_1 = tslib_1.__importDefault(require("config"));
const url_1 = require("url");
const ffmpeg_1 = require("../helpers/ffmpeg");
const core_utils_1 = require("../../shared/core-utils");
const core_utils_2 = require("../helpers/core-utils");
const misc_1 = require("../helpers/custom-validators/misc");
const logger_1 = require("../helpers/logger");
const application_1 = require("../models/application/application");
const oauth_client_1 = require("../models/oauth/oauth-client");
const user_1 = require("../models/user/user");
const config_2 = require("./config");
const constants_1 = require("./constants");
function checkActivityPubUrls() {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const actor = yield (0, application_1.getServerActor)();
        const parsed = new url_1.URL(actor.url);
        if (constants_1.WEBSERVER.HOST !== parsed.host) {
            const NODE_ENV = config_1.default.util.getEnv('NODE_ENV');
            const NODE_CONFIG_DIR = config_1.default.util.getEnv('NODE_CONFIG_DIR');
            logger_1.logger.warn('It seems PeerTube was started (and created some data) with another domain name. ' +
                'This means you will not be able to federate! ' +
                'Please use %s %s npm run update-host to fix this.', NODE_CONFIG_DIR ? `NODE_CONFIG_DIR=${NODE_CONFIG_DIR}` : '', NODE_ENV ? `NODE_ENV=${NODE_ENV}` : '');
        }
    });
}
exports.checkActivityPubUrls = checkActivityPubUrls;
function checkConfig() {
    const configFiles = config_1.default.util.getConfigSources().map(s => s.name).join(' -> ');
    logger_1.logger.info('Using following configuration file hierarchy: %s.', configFiles);
    if (config_1.default.has('services.csp-logger')) {
        logger_1.logger.warn('services.csp-logger configuration has been renamed to csp.report_uri. Please update your configuration file.');
    }
    checkSecretsConfig();
    checkEmailConfig();
    checkNSFWPolicyConfig();
    checkLocalRedundancyConfig();
    checkRemoteRedundancyConfig();
    checkStorageConfig();
    checkTranscodingConfig();
    checkImportConfig();
    checkBroadcastMessageConfig();
    checkSearchConfig();
    checkLiveConfig();
    checkObjectStorageConfig();
    checkVideoStudioConfig();
}
exports.checkConfig = checkConfig;
function clientsExist() {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const totalClients = yield oauth_client_1.OAuthClientModel.countTotal();
        return totalClients !== 0;
    });
}
exports.clientsExist = clientsExist;
function usersExist() {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const totalUsers = yield user_1.UserModel.countTotal();
        return totalUsers !== 0;
    });
}
exports.usersExist = usersExist;
function applicationExist() {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const totalApplication = yield application_1.ApplicationModel.countTotal();
        return totalApplication !== 0;
    });
}
exports.applicationExist = applicationExist;
function checkFFmpegVersion() {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const version = yield (0, ffmpeg_1.getFFmpegVersion)();
        const { major, minor, patch } = (0, core_utils_2.parseSemVersion)(version);
        if (major < 4 || (major === 4 && minor < 1)) {
            logger_1.logger.warn('Your ffmpeg version (%s) is outdated. PeerTube supports ffmpeg >= 4.1. Please upgrade ffmpeg.', version);
        }
        if (major === 4 && minor === 4 && patch === 0) {
            logger_1.logger.warn('There is a bug in ffmpeg 4.4.0 with HLS videos. Please upgrade ffmpeg.');
        }
    });
}
exports.checkFFmpegVersion = checkFFmpegVersion;
function checkSecretsConfig() {
    if (!config_2.CONFIG.SECRETS.PEERTUBE) {
        throw new Error('secrets.peertube is missing in config. Generate one using `openssl rand -hex 32`');
    }
}
function checkEmailConfig() {
    if (!(0, config_2.isEmailEnabled)()) {
        if (config_2.CONFIG.SIGNUP.ENABLED && config_2.CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
            throw new Error('Emailer is disabled but you require signup email verification.');
        }
        if (config_2.CONFIG.CONTACT_FORM.ENABLED) {
            logger_1.logger.warn('Emailer is disabled so the contact form will not work.');
        }
    }
}
function checkNSFWPolicyConfig() {
    const defaultNSFWPolicy = config_2.CONFIG.INSTANCE.DEFAULT_NSFW_POLICY;
    const available = ['do_not_list', 'blur', 'display'];
    if (available.includes(defaultNSFWPolicy) === false) {
        throw new Error('NSFW policy setting should be ' + available.join(' or ') + ' instead of ' + defaultNSFWPolicy);
    }
}
function checkLocalRedundancyConfig() {
    const redundancyVideos = config_2.CONFIG.REDUNDANCY.VIDEOS.STRATEGIES;
    if ((0, misc_1.isArray)(redundancyVideos)) {
        const available = ['most-views', 'trending', 'recently-added'];
        for (const r of redundancyVideos) {
            if (available.includes(r.strategy) === false) {
                throw new Error('Videos redundancy should have ' + available.join(' or ') + ' strategy instead of ' + r.strategy);
            }
            if ((0, core_utils_2.isProdInstance)() && r.minLifetime < 1000 * 3600 * 10) {
                throw new Error('Video redundancy minimum lifetime should be >= 10 hours for strategy ' + r.strategy);
            }
        }
        const filtered = (0, core_utils_1.uniqify)(redundancyVideos.map(r => r.strategy));
        if (filtered.length !== redundancyVideos.length) {
            throw new Error('Redundancy video entries should have unique strategies');
        }
        const recentlyAddedStrategy = redundancyVideos.find(r => r.strategy === 'recently-added');
        if (recentlyAddedStrategy && isNaN(recentlyAddedStrategy.minViews)) {
            throw new Error('Min views in recently added strategy is not a number');
        }
    }
    else {
        throw new Error('Videos redundancy should be an array (you must uncomment lines containing - too)');
    }
}
function checkRemoteRedundancyConfig() {
    const acceptFrom = config_2.CONFIG.REMOTE_REDUNDANCY.VIDEOS.ACCEPT_FROM;
    const acceptFromValues = new Set(['nobody', 'anybody', 'followings']);
    if (acceptFromValues.has(acceptFrom) === false) {
        throw new Error('remote_redundancy.videos.accept_from has an incorrect value');
    }
}
function checkStorageConfig() {
    if ((0, core_utils_2.isProdInstance)()) {
        const configStorage = config_1.default.get('storage');
        for (const key of Object.keys(configStorage)) {
            if (configStorage[key].startsWith('storage/')) {
                logger_1.logger.warn('Directory of %s should not be in the production directory of PeerTube. Please check your production configuration file.', key);
            }
        }
    }
    if (config_2.CONFIG.STORAGE.VIDEOS_DIR === config_2.CONFIG.STORAGE.REDUNDANCY_DIR) {
        logger_1.logger.warn('Redundancy directory should be different than the videos folder.');
    }
}
function checkTranscodingConfig() {
    if (config_2.CONFIG.TRANSCODING.ENABLED) {
        if (config_2.CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false && config_2.CONFIG.TRANSCODING.HLS.ENABLED === false) {
            throw new Error('You need to enable at least WebTorrent transcoding or HLS transcoding.');
        }
        if (config_2.CONFIG.TRANSCODING.CONCURRENCY <= 0) {
            throw new Error('Transcoding concurrency should be > 0');
        }
    }
    if (config_2.CONFIG.IMPORT.VIDEOS.HTTP.ENABLED || config_2.CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED) {
        if (config_2.CONFIG.IMPORT.VIDEOS.CONCURRENCY <= 0) {
            throw new Error('Video import concurrency should be > 0');
        }
    }
}
function checkImportConfig() {
    if (config_2.CONFIG.IMPORT.VIDEO_CHANNEL_SYNCHRONIZATION.ENABLED && !config_2.CONFIG.IMPORT.VIDEOS.HTTP) {
        throw new Error('You need to enable HTTP import to allow synchronization');
    }
}
function checkBroadcastMessageConfig() {
    if (config_2.CONFIG.BROADCAST_MESSAGE.ENABLED) {
        const currentLevel = config_2.CONFIG.BROADCAST_MESSAGE.LEVEL;
        const available = ['info', 'warning', 'error'];
        if (available.includes(currentLevel) === false) {
            throw new Error('Broadcast message level should be ' + available.join(' or ') + ' instead of ' + currentLevel);
        }
    }
}
function checkSearchConfig() {
    if (config_2.CONFIG.SEARCH.SEARCH_INDEX.ENABLED === true) {
        if (config_2.CONFIG.SEARCH.REMOTE_URI.USERS === false) {
            throw new Error('You cannot enable search index without enabling remote URI search for users.');
        }
    }
}
function checkLiveConfig() {
    if (config_2.CONFIG.LIVE.ENABLED === true) {
        if (config_2.CONFIG.LIVE.ALLOW_REPLAY === true && config_2.CONFIG.TRANSCODING.ENABLED === false) {
            throw new Error('Live allow replay cannot be enabled if transcoding is not enabled.');
        }
        if (config_2.CONFIG.LIVE.RTMP.ENABLED === false && config_2.CONFIG.LIVE.RTMPS.ENABLED === false) {
            throw new Error('You must enable at least RTMP or RTMPS');
        }
        if (config_2.CONFIG.LIVE.RTMPS.ENABLED) {
            if (!config_2.CONFIG.LIVE.RTMPS.KEY_FILE) {
                throw new Error('You must specify a key file to enabled RTMPS');
            }
            if (!config_2.CONFIG.LIVE.RTMPS.CERT_FILE) {
                throw new Error('You must specify a cert file to enable RTMPS');
            }
        }
    }
}
function checkObjectStorageConfig() {
    if (config_2.CONFIG.OBJECT_STORAGE.ENABLED === true) {
        if (!config_2.CONFIG.OBJECT_STORAGE.VIDEOS.BUCKET_NAME) {
            throw new Error('videos_bucket should be set when object storage support is enabled.');
        }
        if (!config_2.CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS.BUCKET_NAME) {
            throw new Error('streaming_playlists_bucket should be set when object storage support is enabled.');
        }
        if (config_2.CONFIG.OBJECT_STORAGE.VIDEOS.BUCKET_NAME === config_2.CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS.BUCKET_NAME &&
            config_2.CONFIG.OBJECT_STORAGE.VIDEOS.PREFIX === config_2.CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS.PREFIX) {
            if (config_2.CONFIG.OBJECT_STORAGE.VIDEOS.PREFIX === '') {
                throw new Error('Object storage bucket prefixes should be set when the same bucket is used for both types of video.');
            }
            throw new Error('Object storage bucket prefixes should be set to different values when the same bucket is used for both types of video.');
        }
        if (!config_2.CONFIG.OBJECT_STORAGE.UPLOAD_ACL.PUBLIC) {
            throw new Error('object_storage.upload_acl.public must be set');
        }
        if (!config_2.CONFIG.OBJECT_STORAGE.UPLOAD_ACL.PRIVATE) {
            throw new Error('object_storage.upload_acl.private must be set');
        }
    }
}
function checkVideoStudioConfig() {
    if (config_2.CONFIG.VIDEO_STUDIO.ENABLED === true && config_2.CONFIG.TRANSCODING.ENABLED === false) {
        throw new Error('Video studio cannot be enabled if transcoding is disabled');
    }
}
//# sourceMappingURL=checker-after-init.js.map