"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const bluebird_1 = tslib_1.__importDefault(require("bluebird"));
const fs_extra_1 = require("fs-extra");
const path_1 = require("path");
const videos_1 = require("../../server/lib/activitypub/videos");
const job_queue_1 = require("../../server/lib/job-queue");
const paths_1 = require("../../server/lib/paths");
const video_path_manager_1 = require("../../server/lib/video-path-manager");
const video_1 = require("../../server/models/video/video");
const video_streaming_playlist_1 = require("../../server/models/video/video-streaming-playlist");
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('Migrate old HLS paths to new format.');
        yield (0, database_1.initDatabaseModels)(true);
        job_queue_1.JobQueue.Instance.init();
        const ids = yield video_1.VideoModel.listLocalIds();
        yield bluebird_1.default.map(ids, (id) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                yield processVideo(id);
            }
            catch (err) {
                console.error('Cannot process video %s.', { err });
            }
        }), { concurrency: 5 });
        console.log('Migration finished!');
    });
}
function processVideo(videoId) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const video = yield video_1.VideoModel.loadWithFiles(videoId);
        const hls = video.getHLSPlaylist();
        if (video.isLive || !hls || hls.playlistFilename !== 'master.m3u8' || hls.VideoFiles.length === 0) {
            return;
        }
        console.log(`Renaming HLS playlist files of video ${video.name}.`);
        const playlist = yield video_streaming_playlist_1.VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id);
        const hlsDirPath = video_path_manager_1.VideoPathManager.Instance.getFSHLSOutputPath(video);
        const masterPlaylistPath = (0, path_1.join)(hlsDirPath, playlist.playlistFilename);
        let masterPlaylistContent = yield (0, fs_extra_1.readFile)(masterPlaylistPath, 'utf8');
        for (const videoFile of hls.VideoFiles) {
            const srcName = `${videoFile.resolution}.m3u8`;
            const dstName = (0, paths_1.getHlsResolutionPlaylistFilename)(videoFile.filename);
            const src = (0, path_1.join)(hlsDirPath, srcName);
            const dst = (0, path_1.join)(hlsDirPath, dstName);
            try {
                yield (0, fs_extra_1.move)(src, dst);
                masterPlaylistContent = masterPlaylistContent.replace(new RegExp('^' + srcName + '$', 'm'), dstName);
            }
            catch (err) {
                console.error('Cannot move video file %s to %s.', src, dst, err);
            }
        }
        yield (0, fs_extra_1.writeFile)(masterPlaylistPath, masterPlaylistContent);
        if (playlist.segmentsSha256Filename === 'segments-sha256.json') {
            try {
                const newName = (0, paths_1.generateHlsSha256SegmentsFilename)(video.isLive);
                const dst = (0, path_1.join)(hlsDirPath, newName);
                yield (0, fs_extra_1.move)((0, path_1.join)(hlsDirPath, playlist.segmentsSha256Filename), dst);
                playlist.segmentsSha256Filename = newName;
            }
            catch (err) {
                console.error(`Cannot rename ${video.name} segments-sha256.json file to a new name`, err);
            }
        }
        if (playlist.playlistFilename === 'master.m3u8') {
            try {
                const newName = (0, paths_1.generateHLSMasterPlaylistFilename)(video.isLive);
                const dst = (0, path_1.join)(hlsDirPath, newName);
                yield (0, fs_extra_1.move)((0, path_1.join)(hlsDirPath, playlist.playlistFilename), dst);
                playlist.playlistFilename = newName;
            }
            catch (err) {
                console.error(`Cannot rename ${video.name} master.m3u8 file to a new name`, err);
            }
        }
        yield playlist.save();
        const allVideo = yield video_1.VideoModel.loadFull(video.id);
        yield (0, videos_1.federateVideoIfNeeded)(allVideo, false);
        console.log(`Successfully moved HLS files of ${video.name}.`);
    });
}
//# sourceMappingURL=peertube-4.0.js.map