"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildPluginHelpers = void 0;
const tslib_1 = require("tslib");
const path_1 = require("path");
const ffprobe_utils_1 = require("../../helpers/ffmpeg/ffprobe-utils");
const logger_1 = require("../../helpers/logger");
const config_1 = require("../../initializers/config");
const constants_1 = require("../../initializers/constants");
const database_1 = require("../../initializers/database");
const account_1 = require("../../models/account/account");
const account_blocklist_1 = require("../../models/account/account-blocklist");
const application_1 = require("../../models/application/application");
const server_1 = require("../../models/server/server");
const server_blocklist_1 = require("../../models/server/server-blocklist");
const user_1 = require("../../models/user/user");
const video_1 = require("../../models/video/video");
const video_blacklist_1 = require("../../models/video/video-blacklist");
const blocklist_1 = require("../blocklist");
const peertube_socket_1 = require("../peertube-socket");
const server_config_manager_1 = require("../server-config-manager");
const video_blacklist_2 = require("../video-blacklist");
const video_path_manager_1 = require("../video-path-manager");
function buildPluginHelpers(httpServer, pluginModel, npmName) {
    const logger = buildPluginLogger(npmName);
    const database = buildDatabaseHelpers();
    const videos = buildVideosHelpers();
    const config = buildConfigHelpers();
    const server = buildServerHelpers(httpServer);
    const moderation = buildModerationHelpers();
    const plugin = buildPluginRelatedHelpers(pluginModel, npmName);
    const socket = buildSocketHelpers();
    const user = buildUserHelpers();
    return {
        logger,
        database,
        videos,
        config,
        moderation,
        plugin,
        server,
        socket,
        user
    };
}
exports.buildPluginHelpers = buildPluginHelpers;
function buildPluginLogger(npmName) {
    return (0, logger_1.buildLogger)(npmName);
}
function buildDatabaseHelpers() {
    return {
        query: database_1.sequelizeTypescript.query.bind(database_1.sequelizeTypescript)
    };
}
function buildServerHelpers(httpServer) {
    return {
        getHTTPServer: () => httpServer,
        getServerActor: () => (0, application_1.getServerActor)()
    };
}
function buildVideosHelpers() {
    return {
        loadByUrl: (url) => {
            return video_1.VideoModel.loadByUrl(url);
        },
        loadByIdOrUUID: (id) => {
            return video_1.VideoModel.load(id);
        },
        removeVideo: (id) => {
            return database_1.sequelizeTypescript.transaction((t) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                const video = yield video_1.VideoModel.loadFull(id, t);
                yield video.destroy({ transaction: t });
            }));
        },
        ffprobe: (path) => {
            return (0, ffprobe_utils_1.ffprobePromise)(path);
        },
        getFiles: (id) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            const video = yield video_1.VideoModel.loadFull(id);
            if (!video)
                return undefined;
            const webtorrentVideoFiles = (video.VideoFiles || []).map(f => ({
                path: f.storage === 0
                    ? video_path_manager_1.VideoPathManager.Instance.getFSVideoFileOutputPath(video, f)
                    : null,
                url: f.getFileUrl(video),
                resolution: f.resolution,
                size: f.size,
                fps: f.fps
            }));
            const hls = video.getHLSPlaylist();
            const hlsVideoFiles = hls
                ? (video.getHLSPlaylist().VideoFiles || []).map(f => {
                    return {
                        path: f.storage === 0
                            ? video_path_manager_1.VideoPathManager.Instance.getFSVideoFileOutputPath(hls, f)
                            : null,
                        url: f.getFileUrl(video),
                        resolution: f.resolution,
                        size: f.size,
                        fps: f.fps
                    };
                })
                : [];
            const thumbnails = video.Thumbnails.map(t => ({
                type: t.type,
                url: t.getFileUrl(video),
                path: t.getPath()
            }));
            return {
                webtorrent: {
                    videoFiles: webtorrentVideoFiles
                },
                hls: {
                    videoFiles: hlsVideoFiles
                },
                thumbnails
            };
        })
    };
}
function buildModerationHelpers() {
    return {
        blockServer: (options) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            const serverToBlock = yield server_1.ServerModel.loadOrCreateByHost(options.hostToBlock);
            yield (0, blocklist_1.addServerInBlocklist)(options.byAccountId, serverToBlock.id);
        }),
        unblockServer: (options) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            const serverBlock = yield server_blocklist_1.ServerBlocklistModel.loadByAccountAndHost(options.byAccountId, options.hostToUnblock);
            if (!serverBlock)
                return;
            yield (0, blocklist_1.removeServerFromBlocklist)(serverBlock);
        }),
        blockAccount: (options) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            const accountToBlock = yield account_1.AccountModel.loadByNameWithHost(options.handleToBlock);
            if (!accountToBlock)
                return;
            yield (0, blocklist_1.addAccountInBlocklist)(options.byAccountId, accountToBlock.id);
        }),
        unblockAccount: (options) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            const targetAccount = yield account_1.AccountModel.loadByNameWithHost(options.handleToUnblock);
            if (!targetAccount)
                return;
            const accountBlock = yield account_blocklist_1.AccountBlocklistModel.loadByAccountAndTarget(options.byAccountId, targetAccount.id);
            if (!accountBlock)
                return;
            yield (0, blocklist_1.removeAccountFromBlocklist)(accountBlock);
        }),
        blacklistVideo: (options) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            const video = yield video_1.VideoModel.loadFull(options.videoIdOrUUID);
            if (!video)
                return;
            yield (0, video_blacklist_2.blacklistVideo)(video, options.createOptions);
        }),
        unblacklistVideo: (options) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            const video = yield video_1.VideoModel.loadFull(options.videoIdOrUUID);
            if (!video)
                return;
            const videoBlacklist = yield video_blacklist_1.VideoBlacklistModel.loadByVideoId(video.id);
            if (!videoBlacklist)
                return;
            yield (0, video_blacklist_2.unblacklistVideo)(videoBlacklist, video);
        })
    };
}
function buildConfigHelpers() {
    return {
        getWebserverUrl() {
            return constants_1.WEBSERVER.URL;
        },
        getServerConfig() {
            return server_config_manager_1.ServerConfigManager.Instance.getServerConfig();
        }
    };
}
function buildPluginRelatedHelpers(plugin, npmName) {
    return {
        getBaseStaticRoute: () => `/plugins/${plugin.name}/${plugin.version}/static/`,
        getBaseRouterRoute: () => `/plugins/${plugin.name}/${plugin.version}/router/`,
        getBaseWebSocketRoute: () => `/plugins/${plugin.name}/${plugin.version}/ws/`,
        getDataDirectoryPath: () => (0, path_1.join)(config_1.CONFIG.STORAGE.PLUGINS_DIR, 'data', npmName)
    };
}
function buildSocketHelpers() {
    return {
        sendNotification: (userId, notification) => {
            peertube_socket_1.PeerTubeSocket.Instance.sendNotification(userId, notification);
        },
        sendVideoLiveNewState: (video) => {
            peertube_socket_1.PeerTubeSocket.Instance.sendVideoLiveNewState(video);
        }
    };
}
function buildUserHelpers() {
    return {
        loadById: (id) => {
            return user_1.UserModel.loadByIdFull(id);
        },
        getAuthUser: (res) => {
            var _a, _b;
            const user = (_b = (_a = res.locals.oauth) === null || _a === void 0 ? void 0 : _a.token) === null || _b === void 0 ? void 0 : _b.User;
            if (!user)
                return undefined;
            return user_1.UserModel.loadByIdFull(user.id);
        }
    };
}
//# sourceMappingURL=plugin-helpers-builder.js.map