"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const fs_extra_1 = require("fs-extra");
const sequelize_1 = require("sequelize");
const webtorrent_1 = require("../../server/helpers/webtorrent");
const constants_1 = require("../../server/initializers/constants");
const video_privacy_1 = require("../../server/lib/video-privacy");
const video_1 = require("../../server/models/video/video");
const database_1 = require("../../server/initializers/database");
run()
    .then(() => process.exit(0))
    .catch(err => {
    console.error(err);
    process.exit(-1);
});
function run() {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        console.log('Moving private video files in dedicated folders.');
        yield (0, fs_extra_1.ensureDir)(constants_1.DIRECTORIES.HLS_STREAMING_PLAYLIST.PRIVATE);
        yield (0, fs_extra_1.ensureDir)(constants_1.DIRECTORIES.VIDEOS.PRIVATE);
        yield (0, database_1.initDatabaseModels)(true);
        const videos = yield video_1.VideoModel.unscoped().findAll({
            attributes: ['uuid'],
            where: {
                privacy: {
                    [sequelize_1.Op.in]: [3, 4]
                }
            }
        });
        for (const { uuid } of videos) {
            try {
                console.log('Moving files of video %s.', uuid);
                const video = yield video_1.VideoModel.loadFull(uuid);
                try {
                    yield (0, video_privacy_1.moveFilesIfPrivacyChanged)(video, 1);
                }
                catch (err) {
                    console.error('Cannot move files of video %s.', uuid, err);
                }
                try {
                    yield updateTorrents(video);
                }
                catch (err) {
                    console.error('Cannot regenerate torrents of video %s.', uuid, err);
                }
            }
            catch (err) {
                console.error('Cannot process video %s.', uuid, err);
            }
        }
    });
}
function updateTorrents(video) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        for (const file of video.VideoFiles) {
            yield (0, webtorrent_1.updateTorrentMetadata)(video, file);
            yield file.save();
        }
        const playlist = video.getHLSPlaylist();
        for (const file of ((playlist === null || playlist === void 0 ? void 0 : playlist.VideoFiles) || [])) {
            yield (0, webtorrent_1.updateTorrentMetadata)(playlist, file);
            yield file.save();
        }
    });
}
//# sourceMappingURL=peertube-5.0.js.map