"use strict";
// Copyright 2019 - 2021 The Matrix.org Foundation C.I.C.
// Copyright 2022 - 2024 Gnuxie <Gnuxie@protonmail.com>
//
// SPDX-License-Identifier: Apache-2.0
//
// SPDX-FileAttributionText: <text>
// This modified file incorporates work from mjolnir
// https://github.com/matrix-org/mjolnir
// </text>
Object.defineProperty(exports, "__esModule", { value: true });
exports.JoinRoomsOnInviteProtection = void 0;
const matrix_protection_suite_1 = require("matrix-protection-suite");
const inviteCore_1 = require("./inviteCore");
const mps_interface_adaptor_1 = require("@the-draupnir-project/mps-interface-adaptor");
const ProtectRoomsOnInvite_1 = require("./ProtectRoomsOnInvite");
const WatchRoomsOnInvite_1 = require("./WatchRoomsOnInvite");
const matrix_basic_types_1 = require("@the-draupnir-project/matrix-basic-types");
const interface_manager_1 = require("@the-draupnir-project/interface-manager");
const log = new matrix_protection_suite_1.Logger("JoinRoomsOnInviteProtection");
class JoinRoomsOnInviteProtection extends matrix_protection_suite_1.AbstractProtection {
    draupnir;
    promptedToProtectedDeduplicator = new matrix_protection_suite_1.StandardDeduplicator();
    protectRoomsOnInvite;
    watchRoomsOnInvite;
    constructor(description, lifetime, capabilities, protectedRoomsSet, draupnir) {
        super(description, lifetime, capabilities, protectedRoomsSet, {});
        this.draupnir = draupnir;
        this.protectRoomsOnInvite = new ProtectRoomsOnInvite_1.ProtectroomsOnInvite(this.draupnir, this.protectedRoomsSet);
        this.watchRoomsOnInvite = new WatchRoomsOnInvite_1.WatchRoomsOnInvite(this.draupnir, this.protectedRoomsSet);
    }
    handleProtectionDisable() {
        this.protectRoomsOnInvite.handleProtectionDisable();
        this.watchRoomsOnInvite.handleProtectionDisable();
    }
    handleExternalMembership(roomID, event) {
        if (!(0, inviteCore_1.isInvitationForUser)(event, this.protectedRoomsSet.userID)) {
            return;
        }
        // The event handler gets called again when we join the room we were invited to.
        // As sometimes we get the invitation a second time from the join section of sync.
        if (this.promptedToProtectedDeduplicator.isDuplicate(roomID)) {
            return;
        }
        void (0, matrix_protection_suite_1.Task)(this.checkAgainstRequiredMembershipRoom(event));
    }
    async checkAgainstRequiredMembershipRoom(event) {
        const revision = this.draupnir.acceptInvitesFromRoomIssuer.currentRevision;
        if ((0, inviteCore_1.isSenderJoinedInRevision)(event.sender, revision)) {
            return await this.joinAndIssuePrompts(event);
        }
        else {
            this.reportUnknownInvite(event, revision.room);
            return (0, matrix_protection_suite_1.Ok)(undefined);
        }
    }
    reportUnknownInvite(event, requiredMembershipRoom) {
        const renderUnknownInvite = () => {
            return (interface_manager_1.DeadDocumentJSX.JSXFactory("root", null,
                (0, mps_interface_adaptor_1.renderMentionPill)(event.sender, event.sender),
                " has invited me to",
                (0, mps_interface_adaptor_1.renderRoomPill)(matrix_basic_types_1.MatrixRoomReference.fromRoomID(event.room_id)),
                "but they are not joined to ",
                (0, mps_interface_adaptor_1.renderRoomPill)(requiredMembershipRoom),
                ", which prevents me from accepting their invitation.",
                interface_manager_1.DeadDocumentJSX.JSXFactory("br", null),
                "If you would like this room protected, use",
                " ",
                interface_manager_1.DeadDocumentJSX.JSXFactory("code", null,
                    "!draupnir rooms add ",
                    event.room_id)));
        };
        void (0, matrix_protection_suite_1.Task)((0, mps_interface_adaptor_1.sendMatrixEventsFromDeadDocument)(this.draupnir.clientPlatform.toRoomMessageSender(), this.draupnir.managementRoomID, renderUnknownInvite(), {}));
    }
    async joinInvitedRoom(event, room) {
        const renderFailedTojoin = (error) => {
            const title = (interface_manager_1.DeadDocumentJSX.JSXFactory("fragment", null,
                "Unfortunatley I was unable to accept the invitation from",
                " ",
                (0, mps_interface_adaptor_1.renderMentionPill)(event.sender, event.sender),
                " to the room",
                " ",
                (0, mps_interface_adaptor_1.renderRoomPill)(room),
                "."));
            return (interface_manager_1.DeadDocumentJSX.JSXFactory("root", null, (0, mps_interface_adaptor_1.renderFailedSingularConsequence)(this.description, title, error)));
        };
        const joinResult = await this.draupnir.clientPlatform
            .toRoomJoiner()
            .joinRoom(room);
        if ((0, matrix_protection_suite_1.isError)(joinResult)) {
            const sendResult = await (0, mps_interface_adaptor_1.sendMatrixEventsFromDeadDocument)(this.draupnir.clientPlatform.toRoomMessageSender(), this.draupnir.managementRoomID, renderFailedTojoin(joinResult.error), {});
            if ((0, matrix_protection_suite_1.isError)(sendResult)) {
                log.error(`couldn't send join failure to management room`, sendResult.error);
            }
        }
        return joinResult;
    }
    async joinAndIssuePrompts(event) {
        const invitedRoomReference = matrix_basic_types_1.MatrixRoomReference.fromRoomID(event.room_id, [
            (0, matrix_basic_types_1.userServerName)(event.sender),
            (0, matrix_basic_types_1.userServerName)(event.state_key),
        ]);
        const joinResult = await this.joinInvitedRoom(event, invitedRoomReference);
        if ((0, matrix_protection_suite_1.isError)(joinResult)) {
            return joinResult;
        }
        this.watchRoomsOnInvite.promptIfPossiblePolicyRoom(invitedRoomReference, event);
        if (!this.draupnir.config.protectAllJoinedRooms &&
            !this.protectedRoomsSet.isProtectedRoom(event.room_id)) {
            this.protectRoomsOnInvite.promptToProtect(invitedRoomReference, event);
        }
        return (0, matrix_protection_suite_1.Ok)(undefined);
    }
}
exports.JoinRoomsOnInviteProtection = JoinRoomsOnInviteProtection;
(0, matrix_protection_suite_1.describeProtection)({
    name: JoinRoomsOnInviteProtection.name,
    description: "Automatically joins rooms when invited by members of the management room and offers to protect them",
    capabilityInterfaces: {},
    defaultCapabilities: {},
    async factory(description, lifetime, protectedRoomsSet, draupnir, capabilities, _settings) {
        return (0, matrix_protection_suite_1.allocateProtection)(lifetime, new JoinRoomsOnInviteProtection(description, lifetime, capabilities, protectedRoomsSet, draupnir));
    },
});
//# sourceMappingURL=JoinRoomsOnInviteProtection.js.map