"use strict";
// Copyright 2022 Gnuxie <Gnuxie@protonmail.com>
// Copyright 2020 - 2021 The Matrix.org Foundation C.I.C.
//
// 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.DraupnirRoomsRemoveCommand = exports.DraupnirRoomsAddCommand = exports.DraupnirListProtectedRoomsCommand = void 0;
const matrix_protection_suite_1 = require("matrix-protection-suite");
const matrix_basic_types_1 = require("@the-draupnir-project/matrix-basic-types");
const interface_manager_1 = require("@the-draupnir-project/interface-manager");
const DraupnirCommandPrerequisites_1 = require("./DraupnirCommandPrerequisites");
const StatusCommand_1 = require("./StatusCommand");
exports.DraupnirListProtectedRoomsCommand = (0, interface_manager_1.describeCommand)({
    summary: "List all of the protected rooms.",
    parameters: [],
    async executor(draupnir) {
        const allJoinedRooms = draupnir.clientRooms.currentRevision.allJoinedRooms;
        const allProtectedRooms = draupnir.protectedRoomsSet.allProtectedRooms;
        const listInfo = (0, StatusCommand_1.groupWatchedPolicyRoomsByProtectionStatus)(draupnir.protectedRoomsSet.watchedPolicyRooms, draupnir.clientRooms.currentRevision.allJoinedRooms, draupnir.protectedRoomsSet.allProtectedRooms);
        const makeRoomListItem = (room) => {
            const revision = draupnir.protectedRoomsSet.setRoomState.getRevision(room.toRoomIDOrAlias());
            if (revision) {
                return { room, mostRecentRevision: revision.revisionID };
            }
            else {
                return { room };
            }
        };
        return (0, matrix_protection_suite_1.Ok)({
            joinedAndProtectedLists: listInfo.subscribedAndProtectedLists,
            joinedAndWatchedLists: listInfo.subscribedLists,
            partedAndWatchedLists: listInfo.subscribedButPartedLists,
            joinedAndProtectedRooms: allProtectedRooms
                .filter((room) => allJoinedRooms.includes(room.toRoomIDOrAlias()))
                .map(makeRoomListItem),
            joinedAndUnprotectedRooms: allJoinedRooms
                .filter((roomID) => !allProtectedRooms.find((room) => room.toRoomIDOrAlias() === roomID))
                .map((roomID) => makeRoomListItem(matrix_basic_types_1.MatrixRoomReference.fromRoomID(roomID))),
            partedAndProtectedRooms: allProtectedRooms
                .filter((room) => !allJoinedRooms.includes(room.toRoomIDOrAlias()))
                .map(makeRoomListItem),
        });
    },
});
function renderPolicyLists(rooms, options) {
    if (rooms.length === 0) {
        return interface_manager_1.DeadDocumentJSX.JSXFactory("fragment", null);
    }
    return (interface_manager_1.DeadDocumentJSX.JSXFactory("details", null,
        interface_manager_1.DeadDocumentJSX.JSXFactory("summary", null,
            options.name,
            " (",
            rooms.length,
            "):"),
        interface_manager_1.DeadDocumentJSX.JSXFactory("ul", null, rooms.map(StatusCommand_1.renderPolicyList))));
}
function renderRoomList(rooms, options) {
    if (rooms.length === 0) {
        return interface_manager_1.DeadDocumentJSX.JSXFactory("fragment", null);
    }
    return (interface_manager_1.DeadDocumentJSX.JSXFactory("details", null,
        interface_manager_1.DeadDocumentJSX.JSXFactory("summary", null,
            options.name,
            " (",
            rooms.length,
            "):"),
        interface_manager_1.DeadDocumentJSX.JSXFactory("ul", null, rooms.map((item) => (interface_manager_1.DeadDocumentJSX.JSXFactory("li", null,
            interface_manager_1.DeadDocumentJSX.JSXFactory("a", { href: item.room.toPermalink() }, item.room.toRoomIDOrAlias()),
            " ",
            "mostRecentRevision" in item ? (interface_manager_1.DeadDocumentJSX.JSXFactory("fragment", null,
                "(last update:",
                " ",
                interface_manager_1.DeadDocumentJSX.JSXFactory("code", null, new Date(item.mostRecentRevision.time).toLocaleString()),
                ")")) : (interface_manager_1.DeadDocumentJSX.JSXFactory("fragment", null))))))));
}
DraupnirCommandPrerequisites_1.DraupnirInterfaceAdaptor.describeRenderer(exports.DraupnirListProtectedRoomsCommand, {
    JSXRenderer(result) {
        if ((0, matrix_protection_suite_1.isError)(result)) {
            return (0, matrix_protection_suite_1.Ok)(undefined);
        }
        return (0, matrix_protection_suite_1.Ok)(interface_manager_1.DeadDocumentJSX.JSXFactory("root", null,
            result.ok.joinedAndProtectedRooms.length === 0 ? (interface_manager_1.DeadDocumentJSX.JSXFactory("b", null, "There are no joined and protected rooms.")) : (interface_manager_1.DeadDocumentJSX.JSXFactory("fragment", null)),
            renderPolicyLists(result.ok.joinedAndProtectedLists, {
                name: "Joined and protected policy rooms",
            }),
            renderPolicyLists(result.ok.joinedAndWatchedLists, {
                name: "Joined and watched unprotected policy rooms",
            }),
            renderPolicyLists(result.ok.partedAndWatchedLists, {
                name: "Parted policy rooms that are still marked as watched",
            }),
            renderRoomList(result.ok.joinedAndProtectedRooms, {
                name: "Protected rooms",
            }),
            renderRoomList(result.ok.joinedAndUnprotectedRooms, {
                name: "Joined, but unprotected rooms",
            }),
            renderRoomList(result.ok.partedAndProtectedRooms, {
                name: "Parted rooms that are still marked as protected",
            })));
    },
});
exports.DraupnirRoomsAddCommand = (0, interface_manager_1.describeCommand)({
    summary: "Protect the room using the watched policy lists, banning users and synchronizing server ACL.",
    parameters: (0, interface_manager_1.tuple)({
        name: "room",
        acceptor: interface_manager_1.MatrixRoomReferencePresentationSchema,
        description: "The room for Draupnir to protect.",
    }),
    async executor(draupnir, _info, _keywords, _rest, roomRef) {
        const joiner = draupnir.clientPlatform.toRoomJoiner();
        const room = await joiner.joinRoom(roomRef);
        if ((0, matrix_protection_suite_1.isError)(room)) {
            return room.elaborate(`The homeserver that Draupnir is hosted on cannot join this room using the room reference provided.\
                Try an alias or the "share room" button in your client to obtain a valid reference to the room.`);
        }
        return await draupnir.protectedRoomsSet.protectedRoomsManager.addRoom(room.ok);
    },
});
exports.DraupnirRoomsRemoveCommand = (0, interface_manager_1.describeCommand)({
    summary: "Stop protecting the room and leave.",
    parameters: (0, interface_manager_1.tuple)({
        name: "room",
        acceptor: interface_manager_1.MatrixRoomReferencePresentationSchema,
        description: "The room to stop protecting.",
    }),
    async executor(draupnir, _info, _keywords, _rest, roomRef) {
        const room = await draupnir.clientPlatform
            .toRoomResolver()
            .resolveRoom(roomRef);
        if ((0, matrix_protection_suite_1.isError)(room)) {
            return room.elaborate(`The homeserver that Draupnir is hosted on cannot join this room using the room reference provided.\
                Try an alias or the "share room" button in your client to obtain a valid reference to the room.`);
        }
        const removeResult = await draupnir.protectedRoomsSet.protectedRoomsManager.removeRoom(room.ok);
        if ((0, matrix_protection_suite_1.isError)(removeResult)) {
            return removeResult;
        }
        try {
            await draupnir.client.leaveRoom(room.ok.toRoomIDOrAlias());
        }
        catch (exception) {
            return matrix_protection_suite_1.ActionException.Result(`Failed to leave ${roomRef.toPermalink()} - the room is no longer being protected, but the bot could not leave.`, {
                exceptionKind: matrix_protection_suite_1.ActionExceptionKind.Unknown,
                exception: (0, matrix_protection_suite_1.assertThrowableIsError)(exception),
            });
        }
        return (0, matrix_protection_suite_1.Ok)(undefined);
    },
});
for (const command of [exports.DraupnirRoomsAddCommand, exports.DraupnirRoomsRemoveCommand]) {
    DraupnirCommandPrerequisites_1.DraupnirInterfaceAdaptor.describeRenderer(command, {
        isAlwaysSupposedToUseDefaultRenderer: true,
    });
}
//# sourceMappingURL=Rooms.js.map