"use strict";
// Copyright 2022 Gnuxie <Gnuxie@protonmail.com>
// Copyright 2019, 2020 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.FirstMessageIsImageProtection = void 0;
const matrix_bot_sdk_1 = require("@vector-im/matrix-bot-sdk");
const matrix_protection_suite_1 = require("matrix-protection-suite");
(0, matrix_protection_suite_1.describeProtection)({
    name: "FirstMessageIsImageProtection",
    description: "If the first thing a user does after joining is to post an image or video, \
    they'll be banned for spam. This does not publish the ban to any of your ban lists.",
    capabilityInterfaces: {
        userConsequences: "UserConsequences",
        eventConsequences: "EventConsequences",
    },
    defaultCapabilities: {
        userConsequences: "StandardUserConsequences",
        eventConsequences: "StandardEventConsequences",
    },
    factory: async function (description, lifetime, protectedRoomsSet, draupnir, capabilities, _settings) {
        return (0, matrix_protection_suite_1.Ok)(new FirstMessageIsImageProtection(description, lifetime, capabilities, protectedRoomsSet, draupnir));
    },
});
class FirstMessageIsImageProtection extends matrix_protection_suite_1.AbstractProtection {
    draupnir;
    justJoined = {};
    recentlyBanned = [];
    userConsequences;
    eventConsequences;
    constructor(description, lifetime, capabilities, protectedRoomsSet, draupnir) {
        super(description, lifetime, capabilities, protectedRoomsSet, {});
        this.draupnir = draupnir;
        this.userConsequences = capabilities.userConsequences;
        this.eventConsequences = capabilities.eventConsequences;
    }
    async handleMembershipChange(revision, changes) {
        const roomID = revision.room.toRoomIDOrAlias();
        if (!this.justJoined[roomID])
            this.justJoined[roomID] = [];
        for (const change of changes) {
            if (change.membershipChangeType === matrix_protection_suite_1.MembershipChangeType.Joined) {
                this.justJoined[roomID].push(change.userID);
            }
        }
        return (0, matrix_protection_suite_1.Ok)(undefined);
    }
    async handleTimelineEvent(room, event) {
        const roomID = room.toRoomIDOrAlias();
        if (!this.justJoined[roomID])
            this.justJoined[roomID] = [];
        if (matrix_protection_suite_1.Value.Check(matrix_protection_suite_1.RoomMessage, event)) {
            if (!("msgtype" in event.content)) {
                return (0, matrix_protection_suite_1.Ok)(undefined);
            }
            const msgtype = event.content["msgtype"];
            const formattedBody = "formatted_body" in event.content
                ? event.content["formatted_body"] || ""
                : "";
            const isMedia = msgtype === "m.image" ||
                msgtype === "m.video" ||
                formattedBody.toLowerCase().includes("<img");
            if (isMedia && this.justJoined[roomID].includes(event["sender"])) {
                await this.draupnir.managementRoomOutput.logMessage(matrix_bot_sdk_1.LogLevel.WARN, "FirstMessageIsImage", `Banning ${event["sender"]} for posting an image as the first thing after joining in ${roomID}.`);
                if (!this.draupnir.config.noop) {
                    await this.userConsequences.consequenceForUserInRoom(roomID, event["sender"], "spam");
                }
                else {
                    await this.draupnir.managementRoomOutput.logMessage(matrix_bot_sdk_1.LogLevel.WARN, "FirstMessageIsImage", `Tried to ban ${event["sender"]} in ${roomID} but Draupnir is running in no-op mode`, roomID);
                }
                if (this.recentlyBanned.includes(event["sender"])) {
                    return (0, matrix_protection_suite_1.Ok)(undefined); // already handled (will be redacted)
                }
                this.draupnir.unlistedUserRedactionQueue.addUser(event["sender"]);
                this.recentlyBanned.push(event["sender"]); // flag to reduce spam
                // Redact the event
                if (!this.draupnir.config.noop) {
                    await this.eventConsequences.consequenceForEvent(roomID, event["event_id"], "spam");
                }
                else {
                    await this.draupnir.managementRoomOutput.logMessage(matrix_bot_sdk_1.LogLevel.WARN, "FirstMessageIsImage", `Tried to redact ${event["event_id"]} in ${roomID} but Draupnir is running in no-op mode`, roomID);
                }
            }
        }
        const idx = this.justJoined[roomID].indexOf(event["sender"]);
        if (idx >= 0) {
            matrix_bot_sdk_1.LogService.info("FirstMessageIsImage", `${event["sender"]} is no longer considered suspect`);
            this.justJoined[roomID].splice(idx, 1);
        }
        return (0, matrix_protection_suite_1.Ok)(undefined);
    }
}
exports.FirstMessageIsImageProtection = FirstMessageIsImageProtection;
//# sourceMappingURL=FirstMessageIsImage.js.map