Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 4da01f9

Browse files
authored
Admin API for reported events (#8217)
Add an admin API to read entries of table `event_reports`. API: `GET /_synapse/admin/v1/event_reports`
1 parent b29a9bd commit 4da01f9

File tree

6 files changed

+697
-0
lines changed

6 files changed

+697
-0
lines changed

changelog.d/8217.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add an admin API `GET /_synapse/admin/v1/event_reports` to read entries of table `event_reports`. Contributed by @dklimpel.

docs/admin_api/event_reports.rst

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
Show reported events
2+
====================
3+
4+
This API returns information about reported events.
5+
6+
The api is::
7+
8+
GET /_synapse/admin/v1/event_reports?from=0&limit=10
9+
10+
To use it, you will need to authenticate by providing an ``access_token`` for a
11+
server admin: see `README.rst <README.rst>`_.
12+
13+
It returns a JSON body like the following:
14+
15+
.. code:: jsonc
16+
17+
{
18+
"event_reports": [
19+
{
20+
"content": {
21+
"reason": "foo",
22+
"score": -100
23+
},
24+
"event_id": "$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY",
25+
"event_json": {
26+
"auth_events": [
27+
"$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M",
28+
"$oggsNXxzPFRE3y53SUNd7nsj69-QzKv03a1RucHu-ws"
29+
],
30+
"content": {
31+
"body": "matrix.org: This Week in Matrix",
32+
"format": "org.matrix.custom.html",
33+
"formatted_body": "<strong>matrix.org</strong>:<br><a href=\"https://matrix.org/blog/\"><strong>This Week in Matrix</strong></a>",
34+
"msgtype": "m.notice"
35+
},
36+
"depth": 546,
37+
"hashes": {
38+
"sha256": "xK1//xnmvHJIOvbgXlkI8eEqdvoMmihVDJ9J4SNlsAw"
39+
},
40+
"origin": "matrix.org",
41+
"origin_server_ts": 1592291711430,
42+
"prev_events": [
43+
"$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M"
44+
],
45+
"prev_state": [],
46+
"room_id": "!ERAgBpSOcCCuTJqQPk:matrix.org",
47+
"sender": "@foobar:matrix.org",
48+
"signatures": {
49+
"matrix.org": {
50+
"ed25519:a_JaEG": "cs+OUKW/iHx5pEidbWxh0UiNNHwe46Ai9LwNz+Ah16aWDNszVIe2gaAcVZfvNsBhakQTew51tlKmL2kspXk/Dg"
51+
}
52+
},
53+
"type": "m.room.message",
54+
"unsigned": {
55+
"age_ts": 1592291711430,
56+
}
57+
},
58+
"id": 2,
59+
"reason": "foo",
60+
"received_ts": 1570897107409,
61+
"room_alias": "#alias1:matrix.org",
62+
"room_id": "!ERAgBpSOcCCuTJqQPk:matrix.org",
63+
"sender": "@foobar:matrix.org",
64+
"user_id": "@foo:matrix.org"
65+
},
66+
{
67+
"content": {
68+
"reason": "bar",
69+
"score": -100
70+
},
71+
"event_id": "$3IcdZsDaN_En-S1DF4EMCy3v4gNRKeOJs8W5qTOKj4I",
72+
"event_json": {
73+
// hidden items
74+
// see above
75+
},
76+
"id": 3,
77+
"reason": "bar",
78+
"received_ts": 1598889612059,
79+
"room_alias": "#alias2:matrix.org",
80+
"room_id": "!eGvUQuTCkHGVwNMOjv:matrix.org",
81+
"sender": "@foobar:matrix.org",
82+
"user_id": "@bar:matrix.org"
83+
}
84+
],
85+
"next_token": 2,
86+
"total": 4
87+
}
88+
89+
To paginate, check for ``next_token`` and if present, call the endpoint again
90+
with ``from`` set to the value of ``next_token``. This will return a new page.
91+
92+
If the endpoint does not return a ``next_token`` then there are no more
93+
reports to paginate through.
94+
95+
**URL parameters:**
96+
97+
- ``limit``: integer - Is optional but is used for pagination,
98+
denoting the maximum number of items to return in this call. Defaults to ``100``.
99+
- ``from``: integer - Is optional but used for pagination,
100+
denoting the offset in the returned results. This should be treated as an opaque value and
101+
not explicitly set to anything other than the return value of ``next_token`` from a previous call.
102+
Defaults to ``0``.
103+
- ``dir``: string - Direction of event report order. Whether to fetch the most recent first (``b``) or the
104+
oldest first (``f``). Defaults to ``b``.
105+
- ``user_id``: string - Is optional and filters to only return users with user IDs that contain this value.
106+
This is the user who reported the event and wrote the reason.
107+
- ``room_id``: string - Is optional and filters to only return rooms with room IDs that contain this value.
108+
109+
**Response**
110+
111+
The following fields are returned in the JSON response body:
112+
113+
- ``id``: integer - ID of event report.
114+
- ``received_ts``: integer - The timestamp (in milliseconds since the unix epoch) when this report was sent.
115+
- ``room_id``: string - The ID of the room in which the event being reported is located.
116+
- ``event_id``: string - The ID of the reported event.
117+
- ``user_id``: string - This is the user who reported the event and wrote the reason.
118+
- ``reason``: string - Comment made by the ``user_id`` in this report. May be blank.
119+
- ``content``: object - Content of reported event.
120+
121+
- ``reason``: string - Comment made by the ``user_id`` in this report. May be blank.
122+
- ``score``: integer - Content is reported based upon a negative score, where -100 is "most offensive" and 0 is "inoffensive".
123+
124+
- ``sender``: string - This is the ID of the user who sent the original message/event that was reported.
125+
- ``room_alias``: string - The alias of the room. ``null`` if the room does not have a canonical alias set.
126+
- ``event_json``: object - Details of the original event that was reported.
127+
- ``next_token``: integer - Indication for pagination. See above.
128+
- ``total``: integer - Total number of event reports related to the query (``user_id`` and ``room_id``).
129+

synapse/rest/admin/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
DeviceRestServlet,
3232
DevicesRestServlet,
3333
)
34+
from synapse.rest.admin.event_reports import EventReportsRestServlet
3435
from synapse.rest.admin.groups import DeleteGroupAdminRestServlet
3536
from synapse.rest.admin.media import ListMediaInRoom, register_servlets_for_media_repo
3637
from synapse.rest.admin.purge_room_servlet import PurgeRoomServlet
@@ -216,6 +217,7 @@ def register_servlets(hs, http_server):
216217
DeviceRestServlet(hs).register(http_server)
217218
DevicesRestServlet(hs).register(http_server)
218219
DeleteDevicesRestServlet(hs).register(http_server)
220+
EventReportsRestServlet(hs).register(http_server)
219221

220222

221223
def register_servlets_for_client_rest_resource(hs, http_server):
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# -*- coding: utf-8 -*-
2+
# Copyright 2020 Dirk Klimpel
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
16+
import logging
17+
18+
from synapse.api.errors import Codes, SynapseError
19+
from synapse.http.servlet import RestServlet, parse_integer, parse_string
20+
from synapse.rest.admin._base import admin_patterns, assert_requester_is_admin
21+
22+
logger = logging.getLogger(__name__)
23+
24+
25+
class EventReportsRestServlet(RestServlet):
26+
"""
27+
List all reported events that are known to the homeserver. Results are returned
28+
in a dictionary containing report information. Supports pagination.
29+
The requester must have administrator access in Synapse.
30+
31+
GET /_synapse/admin/v1/event_reports
32+
returns:
33+
200 OK with list of reports if success otherwise an error.
34+
35+
Args:
36+
The parameters `from` and `limit` are required only for pagination.
37+
By default, a `limit` of 100 is used.
38+
The parameter `dir` can be used to define the order of results.
39+
The parameter `user_id` can be used to filter by user id.
40+
The parameter `room_id` can be used to filter by room id.
41+
Returns:
42+
A list of reported events and an integer representing the total number of
43+
reported events that exist given this query
44+
"""
45+
46+
PATTERNS = admin_patterns("/event_reports$")
47+
48+
def __init__(self, hs):
49+
self.hs = hs
50+
self.auth = hs.get_auth()
51+
self.store = hs.get_datastore()
52+
53+
async def on_GET(self, request):
54+
await assert_requester_is_admin(self.auth, request)
55+
56+
start = parse_integer(request, "from", default=0)
57+
limit = parse_integer(request, "limit", default=100)
58+
direction = parse_string(request, "dir", default="b")
59+
user_id = parse_string(request, "user_id")
60+
room_id = parse_string(request, "room_id")
61+
62+
if start < 0:
63+
raise SynapseError(
64+
400,
65+
"The start parameter must be a positive integer.",
66+
errcode=Codes.INVALID_PARAM,
67+
)
68+
69+
if limit < 0:
70+
raise SynapseError(
71+
400,
72+
"The limit parameter must be a positive integer.",
73+
errcode=Codes.INVALID_PARAM,
74+
)
75+
76+
if direction not in ("f", "b"):
77+
raise SynapseError(
78+
400, "Unknown direction: %s" % (direction,), errcode=Codes.INVALID_PARAM
79+
)
80+
81+
event_reports, total = await self.store.get_event_reports_paginate(
82+
start, limit, direction, user_id, room_id
83+
)
84+
ret = {"event_reports": event_reports, "total": total}
85+
if (start + limit) < total:
86+
ret["next_token"] = start + len(event_reports)
87+
88+
return 200, ret

synapse/storage/databases/main/room.py

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1328,6 +1328,101 @@ async def add_event_report(
13281328
desc="add_event_report",
13291329
)
13301330

1331+
async def get_event_reports_paginate(
1332+
self,
1333+
start: int,
1334+
limit: int,
1335+
direction: str = "b",
1336+
user_id: Optional[str] = None,
1337+
room_id: Optional[str] = None,
1338+
) -> Tuple[List[Dict[str, Any]], int]:
1339+
"""Retrieve a paginated list of event reports
1340+
1341+
Args:
1342+
start: event offset to begin the query from
1343+
limit: number of rows to retrieve
1344+
direction: Whether to fetch the most recent first (`"b"`) or the
1345+
oldest first (`"f"`)
1346+
user_id: search for user_id. Ignored if user_id is None
1347+
room_id: search for room_id. Ignored if room_id is None
1348+
Returns:
1349+
event_reports: json list of event reports
1350+
count: total number of event reports matching the filter criteria
1351+
"""
1352+
1353+
def _get_event_reports_paginate_txn(txn):
1354+
filters = []
1355+
args = []
1356+
1357+
if user_id:
1358+
filters.append("er.user_id LIKE ?")
1359+
args.extend(["%" + user_id + "%"])
1360+
if room_id:
1361+
filters.append("er.room_id LIKE ?")
1362+
args.extend(["%" + room_id + "%"])
1363+
1364+
if direction == "b":
1365+
order = "DESC"
1366+
else:
1367+
order = "ASC"
1368+
1369+
where_clause = "WHERE " + " AND ".join(filters) if len(filters) > 0 else ""
1370+
1371+
sql = """
1372+
SELECT COUNT(*) as total_event_reports
1373+
FROM event_reports AS er
1374+
{}
1375+
""".format(
1376+
where_clause
1377+
)
1378+
txn.execute(sql, args)
1379+
count = txn.fetchone()[0]
1380+
1381+
sql = """
1382+
SELECT
1383+
er.id,
1384+
er.received_ts,
1385+
er.room_id,
1386+
er.event_id,
1387+
er.user_id,
1388+
er.reason,
1389+
er.content,
1390+
events.sender,
1391+
room_aliases.room_alias,
1392+
event_json.json AS event_json
1393+
FROM event_reports AS er
1394+
LEFT JOIN room_aliases
1395+
ON room_aliases.room_id = er.room_id
1396+
JOIN events
1397+
ON events.event_id = er.event_id
1398+
JOIN event_json
1399+
ON event_json.event_id = er.event_id
1400+
{where_clause}
1401+
ORDER BY er.received_ts {order}
1402+
LIMIT ?
1403+
OFFSET ?
1404+
""".format(
1405+
where_clause=where_clause, order=order,
1406+
)
1407+
1408+
args += [limit, start]
1409+
txn.execute(sql, args)
1410+
event_reports = self.db_pool.cursor_to_dict(txn)
1411+
1412+
if count > 0:
1413+
for row in event_reports:
1414+
try:
1415+
row["content"] = db_to_json(row["content"])
1416+
row["event_json"] = db_to_json(row["event_json"])
1417+
except Exception:
1418+
continue
1419+
1420+
return event_reports, count
1421+
1422+
return await self.db_pool.runInteraction(
1423+
"get_event_reports_paginate", _get_event_reports_paginate_txn
1424+
)
1425+
13311426
def get_current_public_room_stream_id(self):
13321427
return self._public_room_id_gen.get_current_token()
13331428

0 commit comments

Comments
 (0)