aboutsummaryrefslogtreecommitdiff
path: root/matrix-redact.py
blob: 40f6b6147b68a5dd982d2acd2b8451e52929a183 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#!/usr/bin/env python3

"""
matrix-redact: Delete all messages and media a user has sent in a matrix room.
"""

import random
import math
import asyncio
import argparse
import getpass
import sys
import subprocess
from nio import(
        AsyncClient,
        MatrixRoom,
        LoginResponse,
        RoomInfo,
        MessageDirection,
        RedactedEvent,
        RedactionEvent,
        RoomMessagesError,
        RoomRedactError,

        RoomMemberEvent,
        RoomCreateEvent,
        RoomEncryptionEvent,
        RoomGuestAccessEvent,
        RoomHistoryVisibilityEvent,
        RoomJoinRulesEvent,
        PowerLevelsEvent,

        responses
)
from typing import Optional


async def select_room(client: AsyncClient, sync_response) -> MatrixRoom:
    rooms = []
    for room_id, room in client.rooms.items():
        if room_id in sync_response.rooms.join:
            rooms.append({
                "room_id": room_id,
                "display_name": room.display_name,
            })
            print(f"{rooms[-1]['room_id']} | {rooms[-1]['display_name']}")

    selection = input("\nManually type the full room ID to which redaction will be performed: ")
    for room in rooms:
        if room['room_id'] == selection:
            print(f"{selection} will be redacted")
            return room
    print(f"{selection} is invalid. ")
    return None

async def client_login() -> Optional[AsyncClient]:
    uid = input("Full user ID (eg. @user:matrix.server.com): ")
    upass = getpass.getpass(f"Enter the password for {uid}: ")
    user, hserv = uid[1:].split(':', 1)
    client = AsyncClient(f"https://{hserv}", uid)

    if not isinstance(await client.login(upass), LoginResponse):
        print("could not login, returning None")
        return None
    print("login was successful, returning client.")
    return client

async def redact_room(client: AsyncClient, room: MatrixRoom) -> None:
    print(f"\nAll events sent by '{client.user_id}' in " +
          f"'{room['room_id']}' ({room['display_name']}) will be deleted.")
    if not input("\n\nIs this room correct? (Type 'Continue') to proceed: ") == "Continue":
        return None

    sync_resp = await client.sync(timeout=30000, full_state=True)
    start_token = sync_resp.rooms.join[room['room_id']].timeline.prev_batch
    current_token = start_token

    tracked = set()
    events_redacted = 0
    print(f"start_token: {start_token}")
    print(f"current_token: {current_token}")

    while True:
        try:
            print(f"getting messages in {room['room_id']}")
            resp = await client.room_messages(
                    room['room_id'],
                    current_token,
                    limit=500,
                    direction=MessageDirection.back,
            )
        except Exception as e:
            print(f"could not get room message: {e}")
            break
        if isinstance(resp, RoomMessagesError):
            print(f"Could not get room message: {resp}")
            break
        current_token = resp.end
        if len(resp.chunk) == 0:
            print("no more messages to fetch.")
            break

        for event in resp.chunk:
            event_id = event.event_id
            print(f"Event class: {type(event).__name__}, "
                  f"ID: {event_id}, "
                  f"Sender: {event.sender if hasattr(event, 'sender') else 'Unknown'}")

            if event_id in tracked:
                print(f"Event {event_id} already processed, skipping.")
                continue

            tracked.add(event_id)

            if not hasattr(event, 'sender') or event.sender != client.user_id:
                continue

            if isinstance(event, (RedactionEvent)):
                print(f"Skipping redaction event {event_id}")
                continue

            if isinstance(event, (RedactedEvent)):
                print(f"Skipping already redacted event {event_id}")
                continue

            print(f"Processing event_id: {event_id} from {event.sender}")

            if isinstance(event, (RoomMemberEvent,
                                  RoomCreateEvent,
                                  RoomEncryptionEvent,
                                  RoomGuestAccessEvent,
                                  RoomHistoryVisibilityEvent,
                                  RoomJoinRulesEvent,
                                  PowerLevelsEvent)):
                print(f"Skipping room state event {event_id}")
                continue


            try:
                print(f"attempting to redact event {event_id}")
                redact_resp = await client.room_redact(
                        room['room_id'],
                        event_id,
                        reason=""
                )

                if isinstance(redact_resp, RoomRedactError):
                    print(f"Could not redact event {event.event_id} in {room['room_id']}: {redact_resp}")
                else:
                    print(f"Successfully redacted event {event.event_id} in {room['room_id']}")
                    events_redacted += 1
                    print(f"current redactions: {events_redacted}")

                await asyncio.sleep(4)
            except Exception as e:
                print(f"Error redacting event {event.event_id}: {e}")

    if events_redacted:
        print(f"Total messages redacted: {events_redacted}")
    else:
        print("Could not redact any messages, room is probably redacted already")

async def main(args) -> None:
    print("\n" + "="*80)
    print("WARNING: THIS PROGRAM PERFORMS A PERMANENT DESTRUCTIVE ACTION IN A PROVIDED MATRIX ROOM.")
    print("""
          This program will (applies only to a provided room and user ID):
          - Delete all user-uploaded media (images, files, etc.)
          - Delete all messages you've sent
          - Delete any other content you've posted
          - Operate *irreversibly* on the room ID you provide
          - Act as the logged-in user on the specified homeserver

          THIS ACTION IS DESTRUCTIVE AND CANNOT BE UNDONE.

          Make absolutely sure you understand what this program does before proceeding.
          We take zero liability for any misuse of this program.
          """)

    confirmation = input("Type 'YES I UNDERSTAND' to continue: ")
    if confirmation != "YES I UNDERSTAND":
        print("Exiting.")
        sys.exit(1)

    x = random.randint(2, 12)
    a = random.randint(2, 12)
    b = a * x

    print(f"Solve this: {a} * x = {b}")
    if int(input("Answer: ").strip()) != x:
        print("Incorrect math solution. Exiting.")
        sys.exit(1)

    client = None
    try:
        client = await client_login()
        if not client:
            print("Could not login.")
            sys.exit(1)

        sync_resp = await client.sync(timeout=30000, full_state=True)
        room = await select_room(client, sync_resp)

        if room:
            await redact_room(client, room)

    except Exception as e:
        print(f"Error: {e}")
    finally:
        if client:
            print("logging out.")
            await client.logout()
            await client.close()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
            description="matrix-mcnt: Matrix Unread Message Count"
    )

    asyncio.run(main(parser.parse_args()))