"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.synchronizeChannel = void 0;
const tslib_1 = require("tslib");
const logger_1 = require("../helpers/logger");
const youtube_dl_1 = require("../helpers/youtube-dl");
const config_1 = require("../initializers/config");
const video_pre_import_1 = require("./video-pre-import");
const user_1 = require("../models/user/user");
const video_import_1 = require("../models/video/video-import");
const job_queue_1 = require("./job-queue");
const server_config_manager_1 = require("./server-config-manager");
function synchronizeChannel(options) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const { channel, externalChannelUrl, videosCountLimit, onlyAfter, channelSync } = options;
        if (channelSync) {
            channelSync.state = 2;
            channelSync.lastSyncAt = new Date();
            yield channelSync.save();
        }
        try {
            const user = yield user_1.UserModel.loadByChannelActorId(channel.actorId);
            const youtubeDL = new youtube_dl_1.YoutubeDLWrapper(externalChannelUrl, server_config_manager_1.ServerConfigManager.Instance.getEnabledResolutions('vod'), config_1.CONFIG.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION);
            const targetUrls = yield youtubeDL.getInfoForListImport({ latestVideosCount: videosCountLimit });
            logger_1.logger.info('Fetched %d candidate URLs for sync channel %s.', targetUrls.length, channel.Actor.preferredUsername, { targetUrls });
            if (targetUrls.length === 0) {
                if (channelSync) {
                    channelSync.state = 3;
                    yield channelSync.save();
                }
                return;
            }
            const children = [];
            for (const targetUrl of targetUrls) {
                if (yield skipImport(channel, targetUrl, onlyAfter))
                    continue;
                const { job } = yield (0, video_pre_import_1.buildYoutubeDLImport)({
                    user,
                    channel,
                    targetUrl,
                    channelSync,
                    importDataOverride: {
                        privacy: 1
                    }
                });
                children.push(job);
            }
            const parent = {
                type: 'after-video-channel-import',
                payload: {
                    channelSyncId: channelSync === null || channelSync === void 0 ? void 0 : channelSync.id
                }
            };
            yield job_queue_1.JobQueue.Instance.createJobWithChildren(parent, children);
        }
        catch (err) {
            logger_1.logger.error(`Failed to import channel ${channel.name}`, { err });
            channelSync.state = 4;
            yield channelSync.save();
        }
    });
}
exports.synchronizeChannel = synchronizeChannel;
function skipImport(channel, targetUrl, onlyAfter) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        if (yield video_import_1.VideoImportModel.urlAlreadyImported(channel.id, targetUrl)) {
            logger_1.logger.debug('%s is already imported for channel %s, skipping video channel synchronization.', targetUrl, channel.name);
            return true;
        }
        if (onlyAfter) {
            const youtubeDL = new youtube_dl_1.YoutubeDLWrapper(targetUrl, server_config_manager_1.ServerConfigManager.Instance.getEnabledResolutions('vod'), config_1.CONFIG.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION);
            const videoInfo = yield youtubeDL.getInfoForDownload();
            const onlyAfterWithoutTime = new Date(onlyAfter);
            onlyAfterWithoutTime.setHours(0, 0, 0, 0);
            if (videoInfo.originallyPublishedAtWithoutTime.getTime() < onlyAfterWithoutTime.getTime()) {
                return true;
            }
        }
        return false;
    });
}
//# sourceMappingURL=sync-channel.js.map