matrix-synapse 1.142.0rc3__cp314-abi3-musllinux_1_2_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of matrix-synapse might be problematic. Click here for more details.

Files changed (1057) hide show
  1. matrix_synapse-1.142.0rc3.dist-info/AUTHORS.rst +51 -0
  2. matrix_synapse-1.142.0rc3.dist-info/LICENSE-AGPL-3.0 +661 -0
  3. matrix_synapse-1.142.0rc3.dist-info/LICENSE-COMMERCIAL +6 -0
  4. matrix_synapse-1.142.0rc3.dist-info/METADATA +375 -0
  5. matrix_synapse-1.142.0rc3.dist-info/RECORD +1057 -0
  6. matrix_synapse-1.142.0rc3.dist-info/WHEEL +4 -0
  7. matrix_synapse-1.142.0rc3.dist-info/entry_points.txt +14 -0
  8. matrix_synapse.libs/libgcc_s-2d945d6c.so.1 +0 -0
  9. synapse/__init__.py +97 -0
  10. synapse/_scripts/__init__.py +0 -0
  11. synapse/_scripts/export_signing_key.py +109 -0
  12. synapse/_scripts/generate_config.py +83 -0
  13. synapse/_scripts/generate_log_config.py +56 -0
  14. synapse/_scripts/generate_signing_key.py +55 -0
  15. synapse/_scripts/generate_workers_map.py +318 -0
  16. synapse/_scripts/hash_password.py +95 -0
  17. synapse/_scripts/move_remote_media_to_new_store.py +128 -0
  18. synapse/_scripts/register_new_matrix_user.py +374 -0
  19. synapse/_scripts/review_recent_signups.py +212 -0
  20. synapse/_scripts/synapse_port_db.py +1603 -0
  21. synapse/_scripts/synctl.py +365 -0
  22. synapse/_scripts/update_synapse_database.py +130 -0
  23. synapse/api/__init__.py +20 -0
  24. synapse/api/auth/__init__.py +207 -0
  25. synapse/api/auth/base.py +406 -0
  26. synapse/api/auth/internal.py +299 -0
  27. synapse/api/auth/mas.py +457 -0
  28. synapse/api/auth/msc3861_delegated.py +617 -0
  29. synapse/api/auth_blocking.py +144 -0
  30. synapse/api/constants.py +362 -0
  31. synapse/api/errors.py +907 -0
  32. synapse/api/filtering.py +539 -0
  33. synapse/api/presence.py +104 -0
  34. synapse/api/ratelimiting.py +482 -0
  35. synapse/api/room_versions.py +535 -0
  36. synapse/api/urls.py +119 -0
  37. synapse/app/__init__.py +60 -0
  38. synapse/app/_base.py +866 -0
  39. synapse/app/admin_cmd.py +388 -0
  40. synapse/app/appservice.py +30 -0
  41. synapse/app/client_reader.py +30 -0
  42. synapse/app/complement_fork_starter.py +206 -0
  43. synapse/app/event_creator.py +29 -0
  44. synapse/app/federation_reader.py +30 -0
  45. synapse/app/federation_sender.py +30 -0
  46. synapse/app/frontend_proxy.py +30 -0
  47. synapse/app/generic_worker.py +475 -0
  48. synapse/app/homeserver.py +504 -0
  49. synapse/app/media_repository.py +30 -0
  50. synapse/app/phone_stats_home.py +296 -0
  51. synapse/app/pusher.py +30 -0
  52. synapse/app/synchrotron.py +30 -0
  53. synapse/app/user_dir.py +31 -0
  54. synapse/appservice/__init__.py +461 -0
  55. synapse/appservice/api.py +569 -0
  56. synapse/appservice/scheduler.py +567 -0
  57. synapse/config/__init__.py +27 -0
  58. synapse/config/__main__.py +62 -0
  59. synapse/config/_base.py +1108 -0
  60. synapse/config/_base.pyi +217 -0
  61. synapse/config/_util.py +99 -0
  62. synapse/config/account_validity.py +116 -0
  63. synapse/config/api.py +141 -0
  64. synapse/config/appservice.py +210 -0
  65. synapse/config/auth.py +80 -0
  66. synapse/config/auto_accept_invites.py +43 -0
  67. synapse/config/background_updates.py +44 -0
  68. synapse/config/cache.py +231 -0
  69. synapse/config/captcha.py +90 -0
  70. synapse/config/cas.py +116 -0
  71. synapse/config/consent.py +73 -0
  72. synapse/config/database.py +184 -0
  73. synapse/config/emailconfig.py +367 -0
  74. synapse/config/experimental.py +595 -0
  75. synapse/config/federation.py +114 -0
  76. synapse/config/homeserver.py +141 -0
  77. synapse/config/jwt.py +55 -0
  78. synapse/config/key.py +447 -0
  79. synapse/config/logger.py +390 -0
  80. synapse/config/mas.py +191 -0
  81. synapse/config/matrixrtc.py +66 -0
  82. synapse/config/metrics.py +84 -0
  83. synapse/config/modules.py +40 -0
  84. synapse/config/oembed.py +185 -0
  85. synapse/config/oidc.py +509 -0
  86. synapse/config/password_auth_providers.py +82 -0
  87. synapse/config/push.py +64 -0
  88. synapse/config/ratelimiting.py +254 -0
  89. synapse/config/redis.py +74 -0
  90. synapse/config/registration.py +296 -0
  91. synapse/config/repository.py +311 -0
  92. synapse/config/retention.py +162 -0
  93. synapse/config/room.py +88 -0
  94. synapse/config/room_directory.py +165 -0
  95. synapse/config/saml2.py +251 -0
  96. synapse/config/server.py +1170 -0
  97. synapse/config/server_notices.py +84 -0
  98. synapse/config/spam_checker.py +66 -0
  99. synapse/config/sso.py +121 -0
  100. synapse/config/stats.py +54 -0
  101. synapse/config/third_party_event_rules.py +40 -0
  102. synapse/config/tls.py +192 -0
  103. synapse/config/tracer.py +71 -0
  104. synapse/config/user_directory.py +47 -0
  105. synapse/config/user_types.py +44 -0
  106. synapse/config/voip.py +59 -0
  107. synapse/config/workers.py +642 -0
  108. synapse/crypto/__init__.py +20 -0
  109. synapse/crypto/context_factory.py +278 -0
  110. synapse/crypto/event_signing.py +194 -0
  111. synapse/crypto/keyring.py +931 -0
  112. synapse/event_auth.py +1266 -0
  113. synapse/events/__init__.py +668 -0
  114. synapse/events/auto_accept_invites.py +216 -0
  115. synapse/events/builder.py +387 -0
  116. synapse/events/presence_router.py +245 -0
  117. synapse/events/snapshot.py +559 -0
  118. synapse/events/utils.py +928 -0
  119. synapse/events/validator.py +305 -0
  120. synapse/federation/__init__.py +22 -0
  121. synapse/federation/federation_base.py +383 -0
  122. synapse/federation/federation_client.py +2134 -0
  123. synapse/federation/federation_server.py +1544 -0
  124. synapse/federation/persistence.py +71 -0
  125. synapse/federation/send_queue.py +532 -0
  126. synapse/federation/sender/__init__.py +1165 -0
  127. synapse/federation/sender/per_destination_queue.py +884 -0
  128. synapse/federation/sender/transaction_manager.py +210 -0
  129. synapse/federation/transport/__init__.py +28 -0
  130. synapse/federation/transport/client.py +1201 -0
  131. synapse/federation/transport/server/__init__.py +334 -0
  132. synapse/federation/transport/server/_base.py +429 -0
  133. synapse/federation/transport/server/federation.py +912 -0
  134. synapse/federation/units.py +133 -0
  135. synapse/handlers/__init__.py +20 -0
  136. synapse/handlers/account.py +162 -0
  137. synapse/handlers/account_data.py +362 -0
  138. synapse/handlers/account_validity.py +361 -0
  139. synapse/handlers/admin.py +618 -0
  140. synapse/handlers/appservice.py +991 -0
  141. synapse/handlers/auth.py +2494 -0
  142. synapse/handlers/cas.py +413 -0
  143. synapse/handlers/deactivate_account.py +363 -0
  144. synapse/handlers/delayed_events.py +635 -0
  145. synapse/handlers/device.py +1873 -0
  146. synapse/handlers/devicemessage.py +399 -0
  147. synapse/handlers/directory.py +554 -0
  148. synapse/handlers/e2e_keys.py +1834 -0
  149. synapse/handlers/e2e_room_keys.py +455 -0
  150. synapse/handlers/event_auth.py +390 -0
  151. synapse/handlers/events.py +201 -0
  152. synapse/handlers/federation.py +2043 -0
  153. synapse/handlers/federation_event.py +2420 -0
  154. synapse/handlers/identity.py +812 -0
  155. synapse/handlers/initial_sync.py +528 -0
  156. synapse/handlers/jwt.py +120 -0
  157. synapse/handlers/message.py +2347 -0
  158. synapse/handlers/oidc.py +1803 -0
  159. synapse/handlers/pagination.py +768 -0
  160. synapse/handlers/password_policy.py +102 -0
  161. synapse/handlers/presence.py +2638 -0
  162. synapse/handlers/profile.py +655 -0
  163. synapse/handlers/push_rules.py +164 -0
  164. synapse/handlers/read_marker.py +79 -0
  165. synapse/handlers/receipts.py +351 -0
  166. synapse/handlers/register.py +1060 -0
  167. synapse/handlers/relations.py +624 -0
  168. synapse/handlers/reports.py +98 -0
  169. synapse/handlers/room.py +2447 -0
  170. synapse/handlers/room_list.py +632 -0
  171. synapse/handlers/room_member.py +2365 -0
  172. synapse/handlers/room_member_worker.py +146 -0
  173. synapse/handlers/room_policy.py +186 -0
  174. synapse/handlers/room_summary.py +1057 -0
  175. synapse/handlers/saml.py +524 -0
  176. synapse/handlers/search.py +723 -0
  177. synapse/handlers/send_email.py +209 -0
  178. synapse/handlers/set_password.py +71 -0
  179. synapse/handlers/sliding_sync/__init__.py +1701 -0
  180. synapse/handlers/sliding_sync/extensions.py +970 -0
  181. synapse/handlers/sliding_sync/room_lists.py +2266 -0
  182. synapse/handlers/sliding_sync/store.py +128 -0
  183. synapse/handlers/sso.py +1292 -0
  184. synapse/handlers/state_deltas.py +82 -0
  185. synapse/handlers/stats.py +322 -0
  186. synapse/handlers/sync.py +3109 -0
  187. synapse/handlers/thread_subscriptions.py +190 -0
  188. synapse/handlers/typing.py +606 -0
  189. synapse/handlers/ui_auth/__init__.py +48 -0
  190. synapse/handlers/ui_auth/checkers.py +332 -0
  191. synapse/handlers/user_directory.py +783 -0
  192. synapse/handlers/worker_lock.py +365 -0
  193. synapse/http/__init__.py +106 -0
  194. synapse/http/additional_resource.py +62 -0
  195. synapse/http/client.py +1360 -0
  196. synapse/http/connectproxyclient.py +309 -0
  197. synapse/http/federation/__init__.py +19 -0
  198. synapse/http/federation/matrix_federation_agent.py +490 -0
  199. synapse/http/federation/srv_resolver.py +196 -0
  200. synapse/http/federation/well_known_resolver.py +367 -0
  201. synapse/http/matrixfederationclient.py +1875 -0
  202. synapse/http/proxy.py +290 -0
  203. synapse/http/proxyagent.py +497 -0
  204. synapse/http/replicationagent.py +203 -0
  205. synapse/http/request_metrics.py +309 -0
  206. synapse/http/server.py +1114 -0
  207. synapse/http/servlet.py +1019 -0
  208. synapse/http/site.py +825 -0
  209. synapse/http/types.py +27 -0
  210. synapse/logging/__init__.py +31 -0
  211. synapse/logging/_remote.py +261 -0
  212. synapse/logging/_terse_json.py +95 -0
  213. synapse/logging/context.py +1211 -0
  214. synapse/logging/formatter.py +63 -0
  215. synapse/logging/handlers.py +99 -0
  216. synapse/logging/loggers.py +25 -0
  217. synapse/logging/opentracing.py +1132 -0
  218. synapse/logging/scopecontextmanager.py +161 -0
  219. synapse/media/_base.py +827 -0
  220. synapse/media/filepath.py +417 -0
  221. synapse/media/media_repository.py +1580 -0
  222. synapse/media/media_storage.py +704 -0
  223. synapse/media/oembed.py +277 -0
  224. synapse/media/preview_html.py +559 -0
  225. synapse/media/storage_provider.py +195 -0
  226. synapse/media/thumbnailer.py +833 -0
  227. synapse/media/url_previewer.py +875 -0
  228. synapse/metrics/__init__.py +754 -0
  229. synapse/metrics/_gc.py +219 -0
  230. synapse/metrics/_reactor_metrics.py +171 -0
  231. synapse/metrics/_types.py +38 -0
  232. synapse/metrics/background_process_metrics.py +556 -0
  233. synapse/metrics/common_usage_metrics.py +94 -0
  234. synapse/metrics/jemalloc.py +248 -0
  235. synapse/module_api/__init__.py +2154 -0
  236. synapse/module_api/callbacks/__init__.py +50 -0
  237. synapse/module_api/callbacks/account_validity_callbacks.py +106 -0
  238. synapse/module_api/callbacks/media_repository_callbacks.py +160 -0
  239. synapse/module_api/callbacks/ratelimit_callbacks.py +79 -0
  240. synapse/module_api/callbacks/spamchecker_callbacks.py +1113 -0
  241. synapse/module_api/callbacks/third_party_event_rules_callbacks.py +599 -0
  242. synapse/module_api/errors.py +42 -0
  243. synapse/notifier.py +972 -0
  244. synapse/push/__init__.py +212 -0
  245. synapse/push/bulk_push_rule_evaluator.py +637 -0
  246. synapse/push/clientformat.py +126 -0
  247. synapse/push/emailpusher.py +333 -0
  248. synapse/push/httppusher.py +564 -0
  249. synapse/push/mailer.py +1012 -0
  250. synapse/push/presentable_names.py +216 -0
  251. synapse/push/push_tools.py +114 -0
  252. synapse/push/push_types.py +141 -0
  253. synapse/push/pusher.py +87 -0
  254. synapse/push/pusherpool.py +501 -0
  255. synapse/push/rulekinds.py +33 -0
  256. synapse/py.typed +0 -0
  257. synapse/replication/__init__.py +20 -0
  258. synapse/replication/http/__init__.py +68 -0
  259. synapse/replication/http/_base.py +468 -0
  260. synapse/replication/http/account_data.py +297 -0
  261. synapse/replication/http/deactivate_account.py +81 -0
  262. synapse/replication/http/delayed_events.py +62 -0
  263. synapse/replication/http/devices.py +254 -0
  264. synapse/replication/http/federation.py +334 -0
  265. synapse/replication/http/login.py +106 -0
  266. synapse/replication/http/membership.py +364 -0
  267. synapse/replication/http/presence.py +133 -0
  268. synapse/replication/http/push.py +156 -0
  269. synapse/replication/http/register.py +172 -0
  270. synapse/replication/http/send_events.py +182 -0
  271. synapse/replication/http/state.py +82 -0
  272. synapse/replication/http/streams.py +101 -0
  273. synapse/replication/tcp/__init__.py +56 -0
  274. synapse/replication/tcp/client.py +552 -0
  275. synapse/replication/tcp/commands.py +569 -0
  276. synapse/replication/tcp/context.py +41 -0
  277. synapse/replication/tcp/external_cache.py +156 -0
  278. synapse/replication/tcp/handler.py +942 -0
  279. synapse/replication/tcp/protocol.py +608 -0
  280. synapse/replication/tcp/redis.py +509 -0
  281. synapse/replication/tcp/resource.py +348 -0
  282. synapse/replication/tcp/streams/__init__.py +96 -0
  283. synapse/replication/tcp/streams/_base.py +766 -0
  284. synapse/replication/tcp/streams/events.py +287 -0
  285. synapse/replication/tcp/streams/federation.py +92 -0
  286. synapse/replication/tcp/streams/partial_state.py +80 -0
  287. synapse/res/providers.json +29 -0
  288. synapse/res/templates/_base.html +29 -0
  289. synapse/res/templates/account_previously_renewed.html +6 -0
  290. synapse/res/templates/account_renewed.html +6 -0
  291. synapse/res/templates/add_threepid.html +8 -0
  292. synapse/res/templates/add_threepid.txt +6 -0
  293. synapse/res/templates/add_threepid_failure.html +7 -0
  294. synapse/res/templates/add_threepid_success.html +6 -0
  295. synapse/res/templates/already_in_use.html +12 -0
  296. synapse/res/templates/already_in_use.txt +10 -0
  297. synapse/res/templates/auth_success.html +21 -0
  298. synapse/res/templates/invalid_token.html +6 -0
  299. synapse/res/templates/mail-Element.css +7 -0
  300. synapse/res/templates/mail-Vector.css +7 -0
  301. synapse/res/templates/mail-expiry.css +4 -0
  302. synapse/res/templates/mail.css +156 -0
  303. synapse/res/templates/notice_expiry.html +46 -0
  304. synapse/res/templates/notice_expiry.txt +7 -0
  305. synapse/res/templates/notif.html +51 -0
  306. synapse/res/templates/notif.txt +22 -0
  307. synapse/res/templates/notif_mail.html +59 -0
  308. synapse/res/templates/notif_mail.txt +10 -0
  309. synapse/res/templates/password_reset.html +10 -0
  310. synapse/res/templates/password_reset.txt +7 -0
  311. synapse/res/templates/password_reset_confirmation.html +15 -0
  312. synapse/res/templates/password_reset_failure.html +7 -0
  313. synapse/res/templates/password_reset_success.html +6 -0
  314. synapse/res/templates/recaptcha.html +42 -0
  315. synapse/res/templates/registration.html +12 -0
  316. synapse/res/templates/registration.txt +10 -0
  317. synapse/res/templates/registration_failure.html +6 -0
  318. synapse/res/templates/registration_success.html +6 -0
  319. synapse/res/templates/registration_token.html +18 -0
  320. synapse/res/templates/room.html +33 -0
  321. synapse/res/templates/room.txt +9 -0
  322. synapse/res/templates/sso.css +129 -0
  323. synapse/res/templates/sso_account_deactivated.html +25 -0
  324. synapse/res/templates/sso_auth_account_details.html +186 -0
  325. synapse/res/templates/sso_auth_account_details.js +116 -0
  326. synapse/res/templates/sso_auth_bad_user.html +26 -0
  327. synapse/res/templates/sso_auth_confirm.html +27 -0
  328. synapse/res/templates/sso_auth_success.html +26 -0
  329. synapse/res/templates/sso_error.html +71 -0
  330. synapse/res/templates/sso_footer.html +19 -0
  331. synapse/res/templates/sso_login_idp_picker.html +60 -0
  332. synapse/res/templates/sso_new_user_consent.html +30 -0
  333. synapse/res/templates/sso_partial_profile.html +19 -0
  334. synapse/res/templates/sso_redirect_confirm.html +39 -0
  335. synapse/res/templates/style.css +33 -0
  336. synapse/res/templates/terms.html +27 -0
  337. synapse/rest/__init__.py +197 -0
  338. synapse/rest/admin/__init__.py +390 -0
  339. synapse/rest/admin/_base.py +72 -0
  340. synapse/rest/admin/background_updates.py +171 -0
  341. synapse/rest/admin/devices.py +221 -0
  342. synapse/rest/admin/event_reports.py +173 -0
  343. synapse/rest/admin/events.py +69 -0
  344. synapse/rest/admin/experimental_features.py +137 -0
  345. synapse/rest/admin/federation.py +243 -0
  346. synapse/rest/admin/media.py +540 -0
  347. synapse/rest/admin/registration_tokens.py +358 -0
  348. synapse/rest/admin/rooms.py +1061 -0
  349. synapse/rest/admin/scheduled_tasks.py +70 -0
  350. synapse/rest/admin/server_notice_servlet.py +132 -0
  351. synapse/rest/admin/statistics.py +132 -0
  352. synapse/rest/admin/username_available.py +58 -0
  353. synapse/rest/admin/users.py +1608 -0
  354. synapse/rest/client/__init__.py +20 -0
  355. synapse/rest/client/_base.py +113 -0
  356. synapse/rest/client/account.py +930 -0
  357. synapse/rest/client/account_data.py +319 -0
  358. synapse/rest/client/account_validity.py +103 -0
  359. synapse/rest/client/appservice_ping.py +125 -0
  360. synapse/rest/client/auth.py +218 -0
  361. synapse/rest/client/auth_metadata.py +122 -0
  362. synapse/rest/client/capabilities.py +121 -0
  363. synapse/rest/client/delayed_events.py +111 -0
  364. synapse/rest/client/devices.py +587 -0
  365. synapse/rest/client/directory.py +211 -0
  366. synapse/rest/client/events.py +116 -0
  367. synapse/rest/client/filter.py +112 -0
  368. synapse/rest/client/initial_sync.py +65 -0
  369. synapse/rest/client/keys.py +678 -0
  370. synapse/rest/client/knock.py +104 -0
  371. synapse/rest/client/login.py +754 -0
  372. synapse/rest/client/login_token_request.py +127 -0
  373. synapse/rest/client/logout.py +93 -0
  374. synapse/rest/client/matrixrtc.py +52 -0
  375. synapse/rest/client/media.py +286 -0
  376. synapse/rest/client/mutual_rooms.py +93 -0
  377. synapse/rest/client/notifications.py +137 -0
  378. synapse/rest/client/openid.py +109 -0
  379. synapse/rest/client/password_policy.py +69 -0
  380. synapse/rest/client/presence.py +131 -0
  381. synapse/rest/client/profile.py +291 -0
  382. synapse/rest/client/push_rule.py +331 -0
  383. synapse/rest/client/pusher.py +181 -0
  384. synapse/rest/client/read_marker.py +104 -0
  385. synapse/rest/client/receipts.py +165 -0
  386. synapse/rest/client/register.py +1067 -0
  387. synapse/rest/client/relations.py +138 -0
  388. synapse/rest/client/rendezvous.py +76 -0
  389. synapse/rest/client/reporting.py +207 -0
  390. synapse/rest/client/room.py +1669 -0
  391. synapse/rest/client/room_keys.py +426 -0
  392. synapse/rest/client/room_upgrade_rest_servlet.py +112 -0
  393. synapse/rest/client/sendtodevice.py +85 -0
  394. synapse/rest/client/sync.py +1131 -0
  395. synapse/rest/client/tags.py +129 -0
  396. synapse/rest/client/thirdparty.py +130 -0
  397. synapse/rest/client/thread_subscriptions.py +247 -0
  398. synapse/rest/client/tokenrefresh.py +52 -0
  399. synapse/rest/client/transactions.py +149 -0
  400. synapse/rest/client/user_directory.py +90 -0
  401. synapse/rest/client/versions.py +191 -0
  402. synapse/rest/client/voip.py +88 -0
  403. synapse/rest/consent/__init__.py +0 -0
  404. synapse/rest/consent/consent_resource.py +210 -0
  405. synapse/rest/health.py +38 -0
  406. synapse/rest/key/__init__.py +20 -0
  407. synapse/rest/key/v2/__init__.py +40 -0
  408. synapse/rest/key/v2/local_key_resource.py +125 -0
  409. synapse/rest/key/v2/remote_key_resource.py +302 -0
  410. synapse/rest/media/__init__.py +0 -0
  411. synapse/rest/media/config_resource.py +53 -0
  412. synapse/rest/media/create_resource.py +90 -0
  413. synapse/rest/media/download_resource.py +110 -0
  414. synapse/rest/media/media_repository_resource.py +113 -0
  415. synapse/rest/media/preview_url_resource.py +77 -0
  416. synapse/rest/media/thumbnail_resource.py +142 -0
  417. synapse/rest/media/upload_resource.py +187 -0
  418. synapse/rest/media/v1/__init__.py +39 -0
  419. synapse/rest/media/v1/_base.py +23 -0
  420. synapse/rest/media/v1/media_storage.py +23 -0
  421. synapse/rest/media/v1/storage_provider.py +23 -0
  422. synapse/rest/synapse/__init__.py +20 -0
  423. synapse/rest/synapse/client/__init__.py +93 -0
  424. synapse/rest/synapse/client/federation_whitelist.py +66 -0
  425. synapse/rest/synapse/client/jwks.py +77 -0
  426. synapse/rest/synapse/client/new_user_consent.py +115 -0
  427. synapse/rest/synapse/client/oidc/__init__.py +45 -0
  428. synapse/rest/synapse/client/oidc/backchannel_logout_resource.py +42 -0
  429. synapse/rest/synapse/client/oidc/callback_resource.py +48 -0
  430. synapse/rest/synapse/client/password_reset.py +129 -0
  431. synapse/rest/synapse/client/pick_idp.py +107 -0
  432. synapse/rest/synapse/client/pick_username.py +153 -0
  433. synapse/rest/synapse/client/rendezvous.py +58 -0
  434. synapse/rest/synapse/client/saml2/__init__.py +42 -0
  435. synapse/rest/synapse/client/saml2/metadata_resource.py +46 -0
  436. synapse/rest/synapse/client/saml2/response_resource.py +52 -0
  437. synapse/rest/synapse/client/sso_register.py +56 -0
  438. synapse/rest/synapse/client/unsubscribe.py +88 -0
  439. synapse/rest/synapse/mas/__init__.py +71 -0
  440. synapse/rest/synapse/mas/_base.py +55 -0
  441. synapse/rest/synapse/mas/devices.py +239 -0
  442. synapse/rest/synapse/mas/users.py +469 -0
  443. synapse/rest/well_known.py +148 -0
  444. synapse/server.py +1258 -0
  445. synapse/server_notices/__init__.py +0 -0
  446. synapse/server_notices/consent_server_notices.py +136 -0
  447. synapse/server_notices/resource_limits_server_notices.py +215 -0
  448. synapse/server_notices/server_notices_manager.py +388 -0
  449. synapse/server_notices/server_notices_sender.py +67 -0
  450. synapse/server_notices/worker_server_notices_sender.py +46 -0
  451. synapse/spam_checker_api/__init__.py +31 -0
  452. synapse/state/__init__.py +1022 -0
  453. synapse/state/v1.py +370 -0
  454. synapse/state/v2.py +985 -0
  455. synapse/static/client/login/index.html +47 -0
  456. synapse/static/client/login/js/jquery-3.4.1.min.js +2 -0
  457. synapse/static/client/login/js/login.js +291 -0
  458. synapse/static/client/login/spinner.gif +0 -0
  459. synapse/static/client/login/style.css +79 -0
  460. synapse/static/index.html +63 -0
  461. synapse/storage/__init__.py +43 -0
  462. synapse/storage/_base.py +245 -0
  463. synapse/storage/admin_client_config.py +26 -0
  464. synapse/storage/background_updates.py +1189 -0
  465. synapse/storage/controllers/__init__.py +57 -0
  466. synapse/storage/controllers/persist_events.py +1239 -0
  467. synapse/storage/controllers/purge_events.py +456 -0
  468. synapse/storage/controllers/state.py +954 -0
  469. synapse/storage/controllers/stats.py +119 -0
  470. synapse/storage/database.py +2720 -0
  471. synapse/storage/databases/__init__.py +175 -0
  472. synapse/storage/databases/main/__init__.py +424 -0
  473. synapse/storage/databases/main/account_data.py +1060 -0
  474. synapse/storage/databases/main/appservice.py +473 -0
  475. synapse/storage/databases/main/cache.py +911 -0
  476. synapse/storage/databases/main/censor_events.py +225 -0
  477. synapse/storage/databases/main/client_ips.py +817 -0
  478. synapse/storage/databases/main/delayed_events.py +560 -0
  479. synapse/storage/databases/main/deviceinbox.py +1272 -0
  480. synapse/storage/databases/main/devices.py +2581 -0
  481. synapse/storage/databases/main/directory.py +212 -0
  482. synapse/storage/databases/main/e2e_room_keys.py +690 -0
  483. synapse/storage/databases/main/end_to_end_keys.py +1896 -0
  484. synapse/storage/databases/main/event_federation.py +2509 -0
  485. synapse/storage/databases/main/event_push_actions.py +1937 -0
  486. synapse/storage/databases/main/events.py +3746 -0
  487. synapse/storage/databases/main/events_bg_updates.py +2910 -0
  488. synapse/storage/databases/main/events_forward_extremities.py +126 -0
  489. synapse/storage/databases/main/events_worker.py +2784 -0
  490. synapse/storage/databases/main/experimental_features.py +130 -0
  491. synapse/storage/databases/main/filtering.py +231 -0
  492. synapse/storage/databases/main/keys.py +291 -0
  493. synapse/storage/databases/main/lock.py +553 -0
  494. synapse/storage/databases/main/media_repository.py +1070 -0
  495. synapse/storage/databases/main/metrics.py +460 -0
  496. synapse/storage/databases/main/monthly_active_users.py +443 -0
  497. synapse/storage/databases/main/openid.py +61 -0
  498. synapse/storage/databases/main/presence.py +511 -0
  499. synapse/storage/databases/main/profile.py +541 -0
  500. synapse/storage/databases/main/purge_events.py +511 -0
  501. synapse/storage/databases/main/push_rule.py +972 -0
  502. synapse/storage/databases/main/pusher.py +794 -0
  503. synapse/storage/databases/main/receipts.py +1342 -0
  504. synapse/storage/databases/main/registration.py +3076 -0
  505. synapse/storage/databases/main/rejections.py +38 -0
  506. synapse/storage/databases/main/relations.py +1118 -0
  507. synapse/storage/databases/main/room.py +2781 -0
  508. synapse/storage/databases/main/roommember.py +2112 -0
  509. synapse/storage/databases/main/search.py +941 -0
  510. synapse/storage/databases/main/session.py +151 -0
  511. synapse/storage/databases/main/signatures.py +94 -0
  512. synapse/storage/databases/main/sliding_sync.py +603 -0
  513. synapse/storage/databases/main/state.py +1006 -0
  514. synapse/storage/databases/main/state_deltas.py +329 -0
  515. synapse/storage/databases/main/stats.py +791 -0
  516. synapse/storage/databases/main/stream.py +2580 -0
  517. synapse/storage/databases/main/tags.py +360 -0
  518. synapse/storage/databases/main/task_scheduler.py +225 -0
  519. synapse/storage/databases/main/thread_subscriptions.py +591 -0
  520. synapse/storage/databases/main/transactions.py +681 -0
  521. synapse/storage/databases/main/ui_auth.py +420 -0
  522. synapse/storage/databases/main/user_directory.py +1331 -0
  523. synapse/storage/databases/main/user_erasure_store.py +117 -0
  524. synapse/storage/databases/state/__init__.py +22 -0
  525. synapse/storage/databases/state/bg_updates.py +499 -0
  526. synapse/storage/databases/state/deletion.py +558 -0
  527. synapse/storage/databases/state/store.py +949 -0
  528. synapse/storage/engines/__init__.py +70 -0
  529. synapse/storage/engines/_base.py +154 -0
  530. synapse/storage/engines/postgres.py +261 -0
  531. synapse/storage/engines/sqlite.py +199 -0
  532. synapse/storage/invite_rule.py +112 -0
  533. synapse/storage/keys.py +40 -0
  534. synapse/storage/prepare_database.py +731 -0
  535. synapse/storage/push_rule.py +28 -0
  536. synapse/storage/roommember.py +89 -0
  537. synapse/storage/schema/README.md +4 -0
  538. synapse/storage/schema/__init__.py +182 -0
  539. synapse/storage/schema/common/delta/25/00background_updates.sql +40 -0
  540. synapse/storage/schema/common/delta/35/00background_updates_add_col.sql +36 -0
  541. synapse/storage/schema/common/delta/58/00background_update_ordering.sql +38 -0
  542. synapse/storage/schema/common/full_schemas/72/full.sql.postgres +8 -0
  543. synapse/storage/schema/common/full_schemas/72/full.sql.sqlite +6 -0
  544. synapse/storage/schema/common/schema_version.sql +60 -0
  545. synapse/storage/schema/main/delta/12/v12.sql +82 -0
  546. synapse/storage/schema/main/delta/13/v13.sql +38 -0
  547. synapse/storage/schema/main/delta/14/v14.sql +42 -0
  548. synapse/storage/schema/main/delta/15/appservice_txns.sql +50 -0
  549. synapse/storage/schema/main/delta/15/presence_indices.sql +2 -0
  550. synapse/storage/schema/main/delta/15/v15.sql +24 -0
  551. synapse/storage/schema/main/delta/16/events_order_index.sql +4 -0
  552. synapse/storage/schema/main/delta/16/remote_media_cache_index.sql +2 -0
  553. synapse/storage/schema/main/delta/16/remove_duplicates.sql +9 -0
  554. synapse/storage/schema/main/delta/16/room_alias_index.sql +3 -0
  555. synapse/storage/schema/main/delta/16/unique_constraints.sql +72 -0
  556. synapse/storage/schema/main/delta/16/users.sql +56 -0
  557. synapse/storage/schema/main/delta/17/drop_indexes.sql +37 -0
  558. synapse/storage/schema/main/delta/17/server_keys.sql +43 -0
  559. synapse/storage/schema/main/delta/17/user_threepids.sql +9 -0
  560. synapse/storage/schema/main/delta/18/server_keys_bigger_ints.sql +51 -0
  561. synapse/storage/schema/main/delta/19/event_index.sql +38 -0
  562. synapse/storage/schema/main/delta/20/dummy.sql +1 -0
  563. synapse/storage/schema/main/delta/20/pushers.py +93 -0
  564. synapse/storage/schema/main/delta/21/end_to_end_keys.sql +53 -0
  565. synapse/storage/schema/main/delta/21/receipts.sql +57 -0
  566. synapse/storage/schema/main/delta/22/receipts_index.sql +41 -0
  567. synapse/storage/schema/main/delta/22/user_threepids_unique.sql +19 -0
  568. synapse/storage/schema/main/delta/24/stats_reporting.sql +37 -0
  569. synapse/storage/schema/main/delta/25/fts.py +81 -0
  570. synapse/storage/schema/main/delta/25/guest_access.sql +44 -0
  571. synapse/storage/schema/main/delta/25/history_visibility.sql +44 -0
  572. synapse/storage/schema/main/delta/25/tags.sql +57 -0
  573. synapse/storage/schema/main/delta/26/account_data.sql +36 -0
  574. synapse/storage/schema/main/delta/27/account_data.sql +55 -0
  575. synapse/storage/schema/main/delta/27/forgotten_memberships.sql +45 -0
  576. synapse/storage/schema/main/delta/27/ts.py +61 -0
  577. synapse/storage/schema/main/delta/28/event_push_actions.sql +46 -0
  578. synapse/storage/schema/main/delta/28/events_room_stream.sql +39 -0
  579. synapse/storage/schema/main/delta/28/public_roms_index.sql +39 -0
  580. synapse/storage/schema/main/delta/28/receipts_user_id_index.sql +41 -0
  581. synapse/storage/schema/main/delta/28/upgrade_times.sql +40 -0
  582. synapse/storage/schema/main/delta/28/users_is_guest.sql +41 -0
  583. synapse/storage/schema/main/delta/29/push_actions.sql +54 -0
  584. synapse/storage/schema/main/delta/30/alias_creator.sql +35 -0
  585. synapse/storage/schema/main/delta/30/as_users.py +82 -0
  586. synapse/storage/schema/main/delta/30/deleted_pushers.sql +44 -0
  587. synapse/storage/schema/main/delta/30/presence_stream.sql +49 -0
  588. synapse/storage/schema/main/delta/30/public_rooms.sql +42 -0
  589. synapse/storage/schema/main/delta/30/push_rule_stream.sql +57 -0
  590. synapse/storage/schema/main/delta/30/threepid_guest_access_tokens.sql +43 -0
  591. synapse/storage/schema/main/delta/31/invites.sql +61 -0
  592. synapse/storage/schema/main/delta/31/local_media_repository_url_cache.sql +46 -0
  593. synapse/storage/schema/main/delta/31/pushers_0.py +92 -0
  594. synapse/storage/schema/main/delta/31/pushers_index.sql +41 -0
  595. synapse/storage/schema/main/delta/31/search_update.py +65 -0
  596. synapse/storage/schema/main/delta/32/events.sql +35 -0
  597. synapse/storage/schema/main/delta/32/openid.sql +9 -0
  598. synapse/storage/schema/main/delta/32/pusher_throttle.sql +42 -0
  599. synapse/storage/schema/main/delta/32/remove_indices.sql +52 -0
  600. synapse/storage/schema/main/delta/32/reports.sql +44 -0
  601. synapse/storage/schema/main/delta/33/access_tokens_device_index.sql +36 -0
  602. synapse/storage/schema/main/delta/33/devices.sql +40 -0
  603. synapse/storage/schema/main/delta/33/devices_for_e2e_keys.sql +38 -0
  604. synapse/storage/schema/main/delta/33/devices_for_e2e_keys_clear_unknown_device.sql +39 -0
  605. synapse/storage/schema/main/delta/33/event_fields.py +61 -0
  606. synapse/storage/schema/main/delta/33/remote_media_ts.py +43 -0
  607. synapse/storage/schema/main/delta/33/user_ips_index.sql +36 -0
  608. synapse/storage/schema/main/delta/34/appservice_stream.sql +42 -0
  609. synapse/storage/schema/main/delta/34/cache_stream.py +50 -0
  610. synapse/storage/schema/main/delta/34/device_inbox.sql +43 -0
  611. synapse/storage/schema/main/delta/34/push_display_name_rename.sql +39 -0
  612. synapse/storage/schema/main/delta/34/received_txn_purge.py +36 -0
  613. synapse/storage/schema/main/delta/35/contains_url.sql +36 -0
  614. synapse/storage/schema/main/delta/35/device_outbox.sql +58 -0
  615. synapse/storage/schema/main/delta/35/device_stream_id.sql +40 -0
  616. synapse/storage/schema/main/delta/35/event_push_actions_index.sql +36 -0
  617. synapse/storage/schema/main/delta/35/public_room_list_change_stream.sql +52 -0
  618. synapse/storage/schema/main/delta/35/stream_order_to_extrem.sql +56 -0
  619. synapse/storage/schema/main/delta/36/readd_public_rooms.sql +45 -0
  620. synapse/storage/schema/main/delta/37/remove_auth_idx.py +89 -0
  621. synapse/storage/schema/main/delta/37/user_threepids.sql +71 -0
  622. synapse/storage/schema/main/delta/38/postgres_fts_gist.sql +38 -0
  623. synapse/storage/schema/main/delta/39/appservice_room_list.sql +48 -0
  624. synapse/storage/schema/main/delta/39/device_federation_stream_idx.sql +35 -0
  625. synapse/storage/schema/main/delta/39/event_push_index.sql +36 -0
  626. synapse/storage/schema/main/delta/39/federation_out_position.sql +41 -0
  627. synapse/storage/schema/main/delta/39/membership_profile.sql +39 -0
  628. synapse/storage/schema/main/delta/40/current_state_idx.sql +36 -0
  629. synapse/storage/schema/main/delta/40/device_inbox.sql +40 -0
  630. synapse/storage/schema/main/delta/40/device_list_streams.sql +79 -0
  631. synapse/storage/schema/main/delta/40/event_push_summary.sql +57 -0
  632. synapse/storage/schema/main/delta/40/pushers.sql +58 -0
  633. synapse/storage/schema/main/delta/41/device_list_stream_idx.sql +36 -0
  634. synapse/storage/schema/main/delta/41/device_outbound_index.sql +35 -0
  635. synapse/storage/schema/main/delta/41/event_search_event_id_idx.sql +36 -0
  636. synapse/storage/schema/main/delta/41/ratelimit.sql +41 -0
  637. synapse/storage/schema/main/delta/42/current_state_delta.sql +48 -0
  638. synapse/storage/schema/main/delta/42/device_list_last_id.sql +52 -0
  639. synapse/storage/schema/main/delta/42/event_auth_state_only.sql +36 -0
  640. synapse/storage/schema/main/delta/42/user_dir.py +88 -0
  641. synapse/storage/schema/main/delta/43/blocked_rooms.sql +40 -0
  642. synapse/storage/schema/main/delta/43/quarantine_media.sql +36 -0
  643. synapse/storage/schema/main/delta/43/url_cache.sql +35 -0
  644. synapse/storage/schema/main/delta/43/user_share.sql +52 -0
  645. synapse/storage/schema/main/delta/44/expire_url_cache.sql +60 -0
  646. synapse/storage/schema/main/delta/45/group_server.sql +186 -0
  647. synapse/storage/schema/main/delta/45/profile_cache.sql +47 -0
  648. synapse/storage/schema/main/delta/46/drop_refresh_tokens.sql +36 -0
  649. synapse/storage/schema/main/delta/46/drop_unique_deleted_pushers.sql +54 -0
  650. synapse/storage/schema/main/delta/46/group_server.sql +51 -0
  651. synapse/storage/schema/main/delta/46/local_media_repository_url_idx.sql +43 -0
  652. synapse/storage/schema/main/delta/46/user_dir_null_room_ids.sql +54 -0
  653. synapse/storage/schema/main/delta/46/user_dir_typos.sql +43 -0
  654. synapse/storage/schema/main/delta/47/last_access_media.sql +35 -0
  655. synapse/storage/schema/main/delta/47/postgres_fts_gin.sql +36 -0
  656. synapse/storage/schema/main/delta/47/push_actions_staging.sql +47 -0
  657. synapse/storage/schema/main/delta/48/add_user_consent.sql +37 -0
  658. synapse/storage/schema/main/delta/48/add_user_ips_last_seen_index.sql +36 -0
  659. synapse/storage/schema/main/delta/48/deactivated_users.sql +44 -0
  660. synapse/storage/schema/main/delta/48/group_unique_indexes.py +67 -0
  661. synapse/storage/schema/main/delta/48/groups_joinable.sql +41 -0
  662. synapse/storage/schema/main/delta/49/add_user_consent_server_notice_sent.sql +39 -0
  663. synapse/storage/schema/main/delta/49/add_user_daily_visits.sql +40 -0
  664. synapse/storage/schema/main/delta/49/add_user_ips_last_seen_only_index.sql +36 -0
  665. synapse/storage/schema/main/delta/50/add_creation_ts_users_index.sql +38 -0
  666. synapse/storage/schema/main/delta/50/erasure_store.sql +40 -0
  667. synapse/storage/schema/main/delta/50/make_event_content_nullable.py +102 -0
  668. synapse/storage/schema/main/delta/51/e2e_room_keys.sql +58 -0
  669. synapse/storage/schema/main/delta/51/monthly_active_users.sql +46 -0
  670. synapse/storage/schema/main/delta/52/add_event_to_state_group_index.sql +38 -0
  671. synapse/storage/schema/main/delta/52/device_list_streams_unique_idx.sql +55 -0
  672. synapse/storage/schema/main/delta/52/e2e_room_keys.sql +72 -0
  673. synapse/storage/schema/main/delta/53/add_user_type_to_users.sql +38 -0
  674. synapse/storage/schema/main/delta/53/drop_sent_transactions.sql +35 -0
  675. synapse/storage/schema/main/delta/53/event_format_version.sql +35 -0
  676. synapse/storage/schema/main/delta/53/user_dir_populate.sql +49 -0
  677. synapse/storage/schema/main/delta/53/user_ips_index.sql +49 -0
  678. synapse/storage/schema/main/delta/53/user_share.sql +63 -0
  679. synapse/storage/schema/main/delta/53/user_threepid_id.sql +48 -0
  680. synapse/storage/schema/main/delta/53/users_in_public_rooms.sql +47 -0
  681. synapse/storage/schema/main/delta/54/account_validity_with_renewal.sql +49 -0
  682. synapse/storage/schema/main/delta/54/add_validity_to_server_keys.sql +42 -0
  683. synapse/storage/schema/main/delta/54/delete_forward_extremities.sql +42 -0
  684. synapse/storage/schema/main/delta/54/drop_legacy_tables.sql +49 -0
  685. synapse/storage/schema/main/delta/54/drop_presence_list.sql +35 -0
  686. synapse/storage/schema/main/delta/54/relations.sql +46 -0
  687. synapse/storage/schema/main/delta/54/stats.sql +99 -0
  688. synapse/storage/schema/main/delta/54/stats2.sql +47 -0
  689. synapse/storage/schema/main/delta/55/access_token_expiry.sql +37 -0
  690. synapse/storage/schema/main/delta/55/track_threepid_validations.sql +50 -0
  691. synapse/storage/schema/main/delta/55/users_alter_deactivated.sql +38 -0
  692. synapse/storage/schema/main/delta/56/add_spans_to_device_lists.sql +39 -0
  693. synapse/storage/schema/main/delta/56/current_state_events_membership.sql +41 -0
  694. synapse/storage/schema/main/delta/56/current_state_events_membership_mk2.sql +43 -0
  695. synapse/storage/schema/main/delta/56/delete_keys_from_deleted_backups.sql +44 -0
  696. synapse/storage/schema/main/delta/56/destinations_failure_ts.sql +44 -0
  697. synapse/storage/schema/main/delta/56/destinations_retry_interval_type.sql.postgres +18 -0
  698. synapse/storage/schema/main/delta/56/device_stream_id_insert.sql +39 -0
  699. synapse/storage/schema/main/delta/56/devices_last_seen.sql +43 -0
  700. synapse/storage/schema/main/delta/56/drop_unused_event_tables.sql +39 -0
  701. synapse/storage/schema/main/delta/56/event_expiry.sql +40 -0
  702. synapse/storage/schema/main/delta/56/event_labels.sql +49 -0
  703. synapse/storage/schema/main/delta/56/event_labels_background_update.sql +36 -0
  704. synapse/storage/schema/main/delta/56/fix_room_keys_index.sql +37 -0
  705. synapse/storage/schema/main/delta/56/hidden_devices.sql +37 -0
  706. synapse/storage/schema/main/delta/56/hidden_devices_fix.sql.sqlite +42 -0
  707. synapse/storage/schema/main/delta/56/nuke_empty_communities_from_db.sql +48 -0
  708. synapse/storage/schema/main/delta/56/public_room_list_idx.sql +35 -0
  709. synapse/storage/schema/main/delta/56/redaction_censor.sql +35 -0
  710. synapse/storage/schema/main/delta/56/redaction_censor2.sql +41 -0
  711. synapse/storage/schema/main/delta/56/redaction_censor3_fix_update.sql.postgres +25 -0
  712. synapse/storage/schema/main/delta/56/redaction_censor4.sql +35 -0
  713. synapse/storage/schema/main/delta/56/remove_tombstoned_rooms_from_directory.sql +38 -0
  714. synapse/storage/schema/main/delta/56/room_key_etag.sql +36 -0
  715. synapse/storage/schema/main/delta/56/room_membership_idx.sql +37 -0
  716. synapse/storage/schema/main/delta/56/room_retention.sql +52 -0
  717. synapse/storage/schema/main/delta/56/signing_keys.sql +75 -0
  718. synapse/storage/schema/main/delta/56/signing_keys_nonunique_signatures.sql +41 -0
  719. synapse/storage/schema/main/delta/56/stats_separated.sql +175 -0
  720. synapse/storage/schema/main/delta/56/unique_user_filter_index.py +46 -0
  721. synapse/storage/schema/main/delta/56/user_external_ids.sql +43 -0
  722. synapse/storage/schema/main/delta/56/users_in_public_rooms_idx.sql +36 -0
  723. synapse/storage/schema/main/delta/57/delete_old_current_state_events.sql +41 -0
  724. synapse/storage/schema/main/delta/57/device_list_remote_cache_stale.sql +44 -0
  725. synapse/storage/schema/main/delta/57/local_current_membership.py +111 -0
  726. synapse/storage/schema/main/delta/57/remove_sent_outbound_pokes.sql +40 -0
  727. synapse/storage/schema/main/delta/57/rooms_version_column.sql +43 -0
  728. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.postgres +35 -0
  729. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.sqlite +22 -0
  730. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.postgres +39 -0
  731. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.sqlite +23 -0
  732. synapse/storage/schema/main/delta/58/02remove_dup_outbound_pokes.sql +41 -0
  733. synapse/storage/schema/main/delta/58/03persist_ui_auth.sql +55 -0
  734. synapse/storage/schema/main/delta/58/05cache_instance.sql.postgres +30 -0
  735. synapse/storage/schema/main/delta/58/06dlols_unique_idx.py +83 -0
  736. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.postgres +33 -0
  737. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.sqlite +44 -0
  738. synapse/storage/schema/main/delta/58/07persist_ui_auth_ips.sql +44 -0
  739. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.postgres +18 -0
  740. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.sqlite +18 -0
  741. synapse/storage/schema/main/delta/58/09shadow_ban.sql +37 -0
  742. synapse/storage/schema/main/delta/58/10_pushrules_enabled_delete_obsolete.sql +47 -0
  743. synapse/storage/schema/main/delta/58/10drop_local_rejections_stream.sql +41 -0
  744. synapse/storage/schema/main/delta/58/10federation_pos_instance_name.sql +41 -0
  745. synapse/storage/schema/main/delta/58/11dehydration.sql +39 -0
  746. synapse/storage/schema/main/delta/58/11fallback.sql +43 -0
  747. synapse/storage/schema/main/delta/58/11user_id_seq.py +38 -0
  748. synapse/storage/schema/main/delta/58/12room_stats.sql +51 -0
  749. synapse/storage/schema/main/delta/58/13remove_presence_allow_inbound.sql +36 -0
  750. synapse/storage/schema/main/delta/58/14events_instance_name.sql +35 -0
  751. synapse/storage/schema/main/delta/58/14events_instance_name.sql.postgres +28 -0
  752. synapse/storage/schema/main/delta/58/15_catchup_destination_rooms.sql +61 -0
  753. synapse/storage/schema/main/delta/58/15unread_count.sql +45 -0
  754. synapse/storage/schema/main/delta/58/16populate_stats_process_rooms_fix.sql +41 -0
  755. synapse/storage/schema/main/delta/58/17_catchup_last_successful.sql +40 -0
  756. synapse/storage/schema/main/delta/58/18stream_positions.sql +41 -0
  757. synapse/storage/schema/main/delta/58/19instance_map.sql.postgres +25 -0
  758. synapse/storage/schema/main/delta/58/19txn_id.sql +59 -0
  759. synapse/storage/schema/main/delta/58/20instance_name_event_tables.sql +36 -0
  760. synapse/storage/schema/main/delta/58/20user_daily_visits.sql +37 -0
  761. synapse/storage/schema/main/delta/58/21as_device_stream.sql +36 -0
  762. synapse/storage/schema/main/delta/58/21drop_device_max_stream_id.sql +1 -0
  763. synapse/storage/schema/main/delta/58/22puppet_token.sql +36 -0
  764. synapse/storage/schema/main/delta/58/22users_have_local_media.sql +2 -0
  765. synapse/storage/schema/main/delta/58/23e2e_cross_signing_keys_idx.sql +36 -0
  766. synapse/storage/schema/main/delta/58/24drop_event_json_index.sql +38 -0
  767. synapse/storage/schema/main/delta/58/25user_external_ids_user_id_idx.sql +36 -0
  768. synapse/storage/schema/main/delta/58/26access_token_last_validated.sql +37 -0
  769. synapse/storage/schema/main/delta/58/27local_invites.sql +37 -0
  770. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.postgres +16 -0
  771. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.sqlite +62 -0
  772. synapse/storage/schema/main/delta/59/01ignored_user.py +85 -0
  773. synapse/storage/schema/main/delta/59/02shard_send_to_device.sql +37 -0
  774. synapse/storage/schema/main/delta/59/03shard_send_to_device_sequence.sql.postgres +25 -0
  775. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql +71 -0
  776. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql.postgres +16 -0
  777. synapse/storage/schema/main/delta/59/04drop_account_data.sql +36 -0
  778. synapse/storage/schema/main/delta/59/05cache_invalidation.sql +36 -0
  779. synapse/storage/schema/main/delta/59/06chain_cover_index.sql +36 -0
  780. synapse/storage/schema/main/delta/59/06shard_account_data.sql +39 -0
  781. synapse/storage/schema/main/delta/59/06shard_account_data.sql.postgres +32 -0
  782. synapse/storage/schema/main/delta/59/07shard_account_data_fix.sql +37 -0
  783. synapse/storage/schema/main/delta/59/08delete_pushers_for_deactivated_accounts.sql +39 -0
  784. synapse/storage/schema/main/delta/59/08delete_stale_pushers.sql +39 -0
  785. synapse/storage/schema/main/delta/59/09rejected_events_metadata.sql +45 -0
  786. synapse/storage/schema/main/delta/59/10delete_purged_chain_cover.sql +36 -0
  787. synapse/storage/schema/main/delta/59/11add_knock_members_to_stats.sql +39 -0
  788. synapse/storage/schema/main/delta/59/11drop_thumbnail_constraint.sql.postgres +22 -0
  789. synapse/storage/schema/main/delta/59/12account_validity_token_used_ts_ms.sql +37 -0
  790. synapse/storage/schema/main/delta/59/12presence_stream_instance.sql +37 -0
  791. synapse/storage/schema/main/delta/59/12presence_stream_instance_seq.sql.postgres +20 -0
  792. synapse/storage/schema/main/delta/59/13users_to_send_full_presence_to.sql +53 -0
  793. synapse/storage/schema/main/delta/59/14refresh_tokens.sql +53 -0
  794. synapse/storage/schema/main/delta/59/15locks.sql +56 -0
  795. synapse/storage/schema/main/delta/59/16federation_inbound_staging.sql +51 -0
  796. synapse/storage/schema/main/delta/60/01recreate_stream_ordering.sql.postgres +45 -0
  797. synapse/storage/schema/main/delta/60/02change_stream_ordering_columns.sql.postgres +30 -0
  798. synapse/storage/schema/main/delta/61/01change_appservices_txns.sql.postgres +23 -0
  799. synapse/storage/schema/main/delta/61/01insertion_event_lookups.sql +68 -0
  800. synapse/storage/schema/main/delta/61/02drop_redundant_room_depth_index.sql +37 -0
  801. synapse/storage/schema/main/delta/61/03recreate_min_depth.py +74 -0
  802. synapse/storage/schema/main/delta/62/01insertion_event_extremities.sql +43 -0
  803. synapse/storage/schema/main/delta/63/01create_registration_tokens.sql +42 -0
  804. synapse/storage/schema/main/delta/63/02delete_unlinked_email_pushers.sql +39 -0
  805. synapse/storage/schema/main/delta/63/02populate-rooms-creator.sql +36 -0
  806. synapse/storage/schema/main/delta/63/03session_store.sql +42 -0
  807. synapse/storage/schema/main/delta/63/04add_presence_stream_not_offline_index.sql +37 -0
  808. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.postgres +23 -0
  809. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.sqlite +37 -0
  810. synapse/storage/schema/main/delta/65/01msc2716_insertion_event_edges.sql +38 -0
  811. synapse/storage/schema/main/delta/65/03remove_hidden_devices_from_device_inbox.sql +41 -0
  812. synapse/storage/schema/main/delta/65/04_local_group_updates.sql +37 -0
  813. synapse/storage/schema/main/delta/65/05_remove_room_stats_historical_and_user_stats_historical.sql +38 -0
  814. synapse/storage/schema/main/delta/65/06remove_deleted_devices_from_device_inbox.sql +53 -0
  815. synapse/storage/schema/main/delta/65/07_arbitrary_relations.sql +37 -0
  816. synapse/storage/schema/main/delta/65/08_device_inbox_background_updates.sql +37 -0
  817. synapse/storage/schema/main/delta/65/10_expirable_refresh_tokens.sql +47 -0
  818. synapse/storage/schema/main/delta/65/11_devices_auth_provider_session.sql +46 -0
  819. synapse/storage/schema/main/delta/67/01drop_public_room_list_stream.sql +37 -0
  820. synapse/storage/schema/main/delta/68/01event_columns.sql +45 -0
  821. synapse/storage/schema/main/delta/68/02_msc2409_add_device_id_appservice_stream_type.sql +40 -0
  822. synapse/storage/schema/main/delta/68/03_delete_account_data_for_deactivated_accounts.sql +39 -0
  823. synapse/storage/schema/main/delta/68/04_refresh_tokens_index_next_token_id.sql +47 -0
  824. synapse/storage/schema/main/delta/68/04partial_state_rooms.sql +60 -0
  825. synapse/storage/schema/main/delta/68/05_delete_non_strings_from_event_search.sql.sqlite +22 -0
  826. synapse/storage/schema/main/delta/68/05partial_state_rooms_triggers.py +80 -0
  827. synapse/storage/schema/main/delta/68/06_msc3202_add_device_list_appservice_stream_type.sql +42 -0
  828. synapse/storage/schema/main/delta/69/01as_txn_seq.py +54 -0
  829. synapse/storage/schema/main/delta/69/01device_list_oubound_by_room.sql +57 -0
  830. synapse/storage/schema/main/delta/69/02cache_invalidation_index.sql +37 -0
  831. synapse/storage/schema/main/delta/70/01clean_table_purged_rooms.sql +39 -0
  832. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.postgres +43 -0
  833. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.sqlite +47 -0
  834. synapse/storage/schema/main/delta/71/01remove_noop_background_updates.sql +80 -0
  835. synapse/storage/schema/main/delta/71/02event_push_summary_unique.sql +37 -0
  836. synapse/storage/schema/main/delta/72/01add_room_type_to_state_stats.sql +38 -0
  837. synapse/storage/schema/main/delta/72/01event_push_summary_receipt.sql +54 -0
  838. synapse/storage/schema/main/delta/72/02event_push_actions_index.sql +38 -0
  839. synapse/storage/schema/main/delta/72/03bg_populate_events_columns.py +57 -0
  840. synapse/storage/schema/main/delta/72/03drop_event_reference_hashes.sql +36 -0
  841. synapse/storage/schema/main/delta/72/03remove_groups.sql +50 -0
  842. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.postgres +17 -0
  843. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.sqlite +40 -0
  844. synapse/storage/schema/main/delta/72/05receipts_event_stream_ordering.sql +38 -0
  845. synapse/storage/schema/main/delta/72/05remove_unstable_private_read_receipts.sql +38 -0
  846. synapse/storage/schema/main/delta/72/06add_consent_ts_to_users.sql +35 -0
  847. synapse/storage/schema/main/delta/72/06thread_notifications.sql +49 -0
  848. synapse/storage/schema/main/delta/72/07force_update_current_state_events_membership.py +67 -0
  849. synapse/storage/schema/main/delta/72/07thread_receipts.sql.postgres +30 -0
  850. synapse/storage/schema/main/delta/72/07thread_receipts.sql.sqlite +70 -0
  851. synapse/storage/schema/main/delta/72/08begin_cache_invalidation_seq_at_2.sql.postgres +23 -0
  852. synapse/storage/schema/main/delta/72/08thread_receipts.sql +39 -0
  853. synapse/storage/schema/main/delta/72/09partial_indices.sql.sqlite +56 -0
  854. synapse/storage/schema/main/delta/73/01event_failed_pull_attempts.sql +48 -0
  855. synapse/storage/schema/main/delta/73/02add_pusher_enabled.sql +35 -0
  856. synapse/storage/schema/main/delta/73/02room_id_indexes_for_purging.sql +41 -0
  857. synapse/storage/schema/main/delta/73/03pusher_device_id.sql +39 -0
  858. synapse/storage/schema/main/delta/73/03users_approved_column.sql +39 -0
  859. synapse/storage/schema/main/delta/73/04partial_join_details.sql +42 -0
  860. synapse/storage/schema/main/delta/73/04pending_device_list_updates.sql +47 -0
  861. synapse/storage/schema/main/delta/73/05old_push_actions.sql.postgres +22 -0
  862. synapse/storage/schema/main/delta/73/05old_push_actions.sql.sqlite +24 -0
  863. synapse/storage/schema/main/delta/73/06thread_notifications_thread_id_idx.sql +42 -0
  864. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.postgres +23 -0
  865. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.sqlite +76 -0
  866. synapse/storage/schema/main/delta/73/09partial_joined_via_destination.sql +37 -0
  867. synapse/storage/schema/main/delta/73/09threads_table.sql +49 -0
  868. synapse/storage/schema/main/delta/73/10_update_sqlite_fts4_tokenizer.py +71 -0
  869. synapse/storage/schema/main/delta/73/10login_tokens.sql +54 -0
  870. synapse/storage/schema/main/delta/73/11event_search_room_id_n_distinct.sql.postgres +33 -0
  871. synapse/storage/schema/main/delta/73/12refactor_device_list_outbound_pokes.sql +72 -0
  872. synapse/storage/schema/main/delta/73/13add_device_lists_index.sql +39 -0
  873. synapse/storage/schema/main/delta/73/20_un_partial_stated_room_stream.sql +51 -0
  874. synapse/storage/schema/main/delta/73/21_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  875. synapse/storage/schema/main/delta/73/22_rebuild_user_dir_stats.sql +48 -0
  876. synapse/storage/schema/main/delta/73/22_un_partial_stated_event_stream.sql +53 -0
  877. synapse/storage/schema/main/delta/73/23_fix_thread_index.sql +52 -0
  878. synapse/storage/schema/main/delta/73/23_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  879. synapse/storage/schema/main/delta/73/24_events_jump_to_date_index.sql +36 -0
  880. synapse/storage/schema/main/delta/73/25drop_presence.sql +36 -0
  881. synapse/storage/schema/main/delta/74/01_user_directory_stale_remote_users.sql +58 -0
  882. synapse/storage/schema/main/delta/74/02_set_device_id_for_pushers_bg_update.sql +38 -0
  883. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.postgres +29 -0
  884. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.sqlite +23 -0
  885. synapse/storage/schema/main/delta/74/03_room_membership_index.sql +38 -0
  886. synapse/storage/schema/main/delta/74/04_delete_e2e_backup_keys_for_deactivated_users.sql +36 -0
  887. synapse/storage/schema/main/delta/74/04_membership_tables_event_stream_ordering_triggers.py +87 -0
  888. synapse/storage/schema/main/delta/74/05_events_txn_id_device_id.sql +72 -0
  889. synapse/storage/schema/main/delta/74/90COMMENTS_destinations.sql.postgres +52 -0
  890. synapse/storage/schema/main/delta/76/01_add_profiles_full_user_id_column.sql +39 -0
  891. synapse/storage/schema/main/delta/76/02_add_user_filters_full_user_id_column.sql +39 -0
  892. synapse/storage/schema/main/delta/76/03_per_user_experimental_features.sql +46 -0
  893. synapse/storage/schema/main/delta/76/04_add_room_forgetter.sql +43 -0
  894. synapse/storage/schema/main/delta/77/01_add_profiles_not_valid_check.sql.postgres +16 -0
  895. synapse/storage/schema/main/delta/77/02_add_user_filters_not_valid_check.sql.postgres +16 -0
  896. synapse/storage/schema/main/delta/77/03bg_populate_full_user_id_profiles.sql +35 -0
  897. synapse/storage/schema/main/delta/77/04bg_populate_full_user_id_user_filters.sql +35 -0
  898. synapse/storage/schema/main/delta/77/05thread_notifications_backfill.sql +67 -0
  899. synapse/storage/schema/main/delta/77/06thread_notifications_not_null.sql.sqlite +102 -0
  900. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions.sql.postgres +27 -0
  901. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions_staging.sql.postgres +27 -0
  902. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_summary.sql.postgres +29 -0
  903. synapse/storage/schema/main/delta/77/14bg_indices_event_stream_ordering.sql +39 -0
  904. synapse/storage/schema/main/delta/78/01_validate_and_update_profiles.py +99 -0
  905. synapse/storage/schema/main/delta/78/02_validate_and_update_user_filters.py +100 -0
  906. synapse/storage/schema/main/delta/78/03_remove_unused_indexes_user_filters.py +72 -0
  907. synapse/storage/schema/main/delta/78/03event_extremities_constraints.py +65 -0
  908. synapse/storage/schema/main/delta/78/04_add_full_user_id_index_user_filters.py +32 -0
  909. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.postgres +102 -0
  910. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.sqlite +72 -0
  911. synapse/storage/schema/main/delta/79/04_mitigate_stream_ordering_update_race.py +70 -0
  912. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.postgres +69 -0
  913. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.sqlite +65 -0
  914. synapse/storage/schema/main/delta/80/01_users_alter_locked.sql +35 -0
  915. synapse/storage/schema/main/delta/80/02_read_write_locks_unlogged.sql.postgres +30 -0
  916. synapse/storage/schema/main/delta/80/02_scheduled_tasks.sql +47 -0
  917. synapse/storage/schema/main/delta/80/03_read_write_locks_triggers.sql.postgres +37 -0
  918. synapse/storage/schema/main/delta/80/04_read_write_locks_deadlock.sql.postgres +71 -0
  919. synapse/storage/schema/main/delta/82/02_scheduled_tasks_index.sql +35 -0
  920. synapse/storage/schema/main/delta/82/04_add_indices_for_purging_rooms.sql +39 -0
  921. synapse/storage/schema/main/delta/82/05gaps.sql +44 -0
  922. synapse/storage/schema/main/delta/83/01_drop_old_tables.sql +43 -0
  923. synapse/storage/schema/main/delta/83/03_instance_name_receipts.sql.sqlite +17 -0
  924. synapse/storage/schema/main/delta/83/05_cross_signing_key_update_grant.sql +34 -0
  925. synapse/storage/schema/main/delta/83/06_event_push_summary_room.sql +36 -0
  926. synapse/storage/schema/main/delta/84/01_auth_links_stats.sql.postgres +20 -0
  927. synapse/storage/schema/main/delta/84/02_auth_links_index.sql +16 -0
  928. synapse/storage/schema/main/delta/84/03_auth_links_analyze.sql.postgres +16 -0
  929. synapse/storage/schema/main/delta/84/04_access_token_index.sql +15 -0
  930. synapse/storage/schema/main/delta/85/01_add_suspended.sql +14 -0
  931. synapse/storage/schema/main/delta/85/02_add_instance_names.sql +27 -0
  932. synapse/storage/schema/main/delta/85/03_new_sequences.sql.postgres +54 -0
  933. synapse/storage/schema/main/delta/85/04_cleanup_device_federation_outbox.sql +15 -0
  934. synapse/storage/schema/main/delta/85/05_add_instance_names_converted_pos.sql +16 -0
  935. synapse/storage/schema/main/delta/85/06_add_room_reports.sql +20 -0
  936. synapse/storage/schema/main/delta/86/01_authenticate_media.sql +15 -0
  937. synapse/storage/schema/main/delta/86/02_receipts_event_id_index.sql +15 -0
  938. synapse/storage/schema/main/delta/87/01_sliding_sync_memberships.sql +169 -0
  939. synapse/storage/schema/main/delta/87/02_per_connection_state.sql +81 -0
  940. synapse/storage/schema/main/delta/87/03_current_state_index.sql +19 -0
  941. synapse/storage/schema/main/delta/88/01_add_delayed_events.sql +43 -0
  942. synapse/storage/schema/main/delta/88/01_custom_profile_fields.sql +15 -0
  943. synapse/storage/schema/main/delta/88/02_fix_sliding_sync_membership_snapshots_forgotten_column.sql +21 -0
  944. synapse/storage/schema/main/delta/88/03_add_otk_ts_added_index.sql +18 -0
  945. synapse/storage/schema/main/delta/88/04_current_state_delta_index.sql +18 -0
  946. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.postgres +19 -0
  947. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.sqlite +19 -0
  948. synapse/storage/schema/main/delta/88/05_sliding_sync_room_config_index.sql +20 -0
  949. synapse/storage/schema/main/delta/88/06_events_received_ts_index.sql +17 -0
  950. synapse/storage/schema/main/delta/89/01_sliding_sync_membership_snapshot_index.sql +15 -0
  951. synapse/storage/schema/main/delta/90/01_add_column_participant_room_memberships_table.sql +16 -0
  952. synapse/storage/schema/main/delta/91/01_media_hash.sql +28 -0
  953. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.postgres +16 -0
  954. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.sqlite +16 -0
  955. synapse/storage/schema/main/delta/92/02_remove_populate_participant_bg_update.sql +17 -0
  956. synapse/storage/schema/main/delta/92/04_ss_membership_snapshot_idx.sql +16 -0
  957. synapse/storage/schema/main/delta/92/04_thread_subscriptions.sql +59 -0
  958. synapse/storage/schema/main/delta/92/04_thread_subscriptions_seq.sql.postgres +19 -0
  959. synapse/storage/schema/main/delta/92/05_fixup_max_depth_cap.sql +17 -0
  960. synapse/storage/schema/main/delta/92/05_thread_subscriptions_comments.sql.postgres +18 -0
  961. synapse/storage/schema/main/delta/92/06_device_federation_inbox_index.sql +16 -0
  962. synapse/storage/schema/main/delta/92/06_threads_last_sent_stream_ordering_comments.sql.postgres +24 -0
  963. synapse/storage/schema/main/delta/92/07_add_user_reports.sql +22 -0
  964. synapse/storage/schema/main/delta/92/07_event_txn_id_device_id_txn_id2.sql +15 -0
  965. synapse/storage/schema/main/delta/92/08_room_ban_redactions.sql +21 -0
  966. synapse/storage/schema/main/delta/92/08_thread_subscriptions_seq_fixup.sql.postgres +19 -0
  967. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql +20 -0
  968. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql.postgres +18 -0
  969. synapse/storage/schema/main/full_schemas/72/full.sql.postgres +1344 -0
  970. synapse/storage/schema/main/full_schemas/72/full.sql.sqlite +646 -0
  971. synapse/storage/schema/state/delta/23/drop_state_index.sql +35 -0
  972. synapse/storage/schema/state/delta/32/remove_state_indices.sql +38 -0
  973. synapse/storage/schema/state/delta/35/add_state_index.sql +36 -0
  974. synapse/storage/schema/state/delta/35/state.sql +41 -0
  975. synapse/storage/schema/state/delta/35/state_dedupe.sql +36 -0
  976. synapse/storage/schema/state/delta/47/state_group_seq.py +38 -0
  977. synapse/storage/schema/state/delta/56/state_group_room_idx.sql +36 -0
  978. synapse/storage/schema/state/delta/61/02state_groups_state_n_distinct.sql.postgres +34 -0
  979. synapse/storage/schema/state/delta/70/08_state_group_edges_unique.sql +36 -0
  980. synapse/storage/schema/state/delta/89/01_state_groups_deletion.sql +39 -0
  981. synapse/storage/schema/state/delta/90/02_delete_unreferenced_state_groups.sql +16 -0
  982. synapse/storage/schema/state/delta/90/03_remove_old_deletion_bg_update.sql +15 -0
  983. synapse/storage/schema/state/full_schemas/72/full.sql.postgres +30 -0
  984. synapse/storage/schema/state/full_schemas/72/full.sql.sqlite +20 -0
  985. synapse/storage/types.py +185 -0
  986. synapse/storage/util/__init__.py +20 -0
  987. synapse/storage/util/id_generators.py +909 -0
  988. synapse/storage/util/partial_state_events_tracker.py +194 -0
  989. synapse/storage/util/sequence.py +315 -0
  990. synapse/streams/__init__.py +43 -0
  991. synapse/streams/config.py +92 -0
  992. synapse/streams/events.py +203 -0
  993. synapse/synapse_rust/__init__.pyi +3 -0
  994. synapse/synapse_rust/acl.pyi +20 -0
  995. synapse/synapse_rust/events.pyi +136 -0
  996. synapse/synapse_rust/http_client.pyi +32 -0
  997. synapse/synapse_rust/push.pyi +86 -0
  998. synapse/synapse_rust/rendezvous.pyi +30 -0
  999. synapse/synapse_rust/segmenter.pyi +1 -0
  1000. synapse/synapse_rust.abi3.so +0 -0
  1001. synapse/types/__init__.py +1600 -0
  1002. synapse/types/handlers/__init__.py +93 -0
  1003. synapse/types/handlers/policy_server.py +16 -0
  1004. synapse/types/handlers/sliding_sync.py +909 -0
  1005. synapse/types/rest/__init__.py +25 -0
  1006. synapse/types/rest/client/__init__.py +415 -0
  1007. synapse/types/state.py +635 -0
  1008. synapse/types/storage/__init__.py +66 -0
  1009. synapse/util/__init__.py +170 -0
  1010. synapse/util/async_helpers.py +1067 -0
  1011. synapse/util/batching_queue.py +202 -0
  1012. synapse/util/caches/__init__.py +300 -0
  1013. synapse/util/caches/cached_call.py +143 -0
  1014. synapse/util/caches/deferred_cache.py +530 -0
  1015. synapse/util/caches/descriptors.py +694 -0
  1016. synapse/util/caches/dictionary_cache.py +350 -0
  1017. synapse/util/caches/expiringcache.py +251 -0
  1018. synapse/util/caches/lrucache.py +977 -0
  1019. synapse/util/caches/response_cache.py +323 -0
  1020. synapse/util/caches/stream_change_cache.py +370 -0
  1021. synapse/util/caches/treecache.py +189 -0
  1022. synapse/util/caches/ttlcache.py +197 -0
  1023. synapse/util/cancellation.py +63 -0
  1024. synapse/util/check_dependencies.py +335 -0
  1025. synapse/util/clock.py +500 -0
  1026. synapse/util/constants.py +22 -0
  1027. synapse/util/daemonize.py +165 -0
  1028. synapse/util/distributor.py +159 -0
  1029. synapse/util/events.py +134 -0
  1030. synapse/util/file_consumer.py +164 -0
  1031. synapse/util/frozenutils.py +57 -0
  1032. synapse/util/gai_resolver.py +180 -0
  1033. synapse/util/hash.py +38 -0
  1034. synapse/util/httpresourcetree.py +108 -0
  1035. synapse/util/iterutils.py +189 -0
  1036. synapse/util/json.py +56 -0
  1037. synapse/util/linked_list.py +156 -0
  1038. synapse/util/logcontext.py +46 -0
  1039. synapse/util/logformatter.py +28 -0
  1040. synapse/util/macaroons.py +325 -0
  1041. synapse/util/manhole.py +191 -0
  1042. synapse/util/metrics.py +340 -0
  1043. synapse/util/module_loader.py +116 -0
  1044. synapse/util/msisdn.py +51 -0
  1045. synapse/util/patch_inline_callbacks.py +250 -0
  1046. synapse/util/pydantic_models.py +56 -0
  1047. synapse/util/ratelimitutils.py +420 -0
  1048. synapse/util/retryutils.py +339 -0
  1049. synapse/util/rlimit.py +42 -0
  1050. synapse/util/rust.py +134 -0
  1051. synapse/util/sentinel.py +21 -0
  1052. synapse/util/stringutils.py +293 -0
  1053. synapse/util/task_scheduler.py +493 -0
  1054. synapse/util/templates.py +126 -0
  1055. synapse/util/threepids.py +123 -0
  1056. synapse/util/wheel_timer.py +112 -0
  1057. synapse/visibility.py +836 -0
@@ -0,0 +1,2781 @@
1
+ #
2
+ # This file is licensed under the Affero General Public License (AGPL) version 3.
3
+ #
4
+ # Copyright 2019, 2022 The Matrix.org Foundation C.I.C.
5
+ # Copyright 2014-2016 OpenMarket Ltd
6
+ # Copyright (C) 2023 New Vector, Ltd
7
+ #
8
+ # This program is free software: you can redistribute it and/or modify
9
+ # it under the terms of the GNU Affero General Public License as
10
+ # published by the Free Software Foundation, either version 3 of the
11
+ # License, or (at your option) any later version.
12
+ #
13
+ # See the GNU Affero General Public License for more details:
14
+ # <https://www.gnu.org/licenses/agpl-3.0.html>.
15
+ #
16
+ # Originally licensed under the Apache License, Version 2.0:
17
+ # <http://www.apache.org/licenses/LICENSE-2.0>.
18
+ #
19
+ # [This file includes modifications made by New Vector Limited]
20
+ #
21
+ #
22
+
23
+ import logging
24
+ from enum import Enum
25
+ from typing import (
26
+ TYPE_CHECKING,
27
+ AbstractSet,
28
+ Any,
29
+ Collection,
30
+ Mapping,
31
+ Optional,
32
+ Union,
33
+ cast,
34
+ )
35
+
36
+ import attr
37
+
38
+ from synapse.api.constants import (
39
+ Direction,
40
+ EventContentFields,
41
+ EventTypes,
42
+ JoinRules,
43
+ PublicRoomsFilterFields,
44
+ )
45
+ from synapse.api.errors import StoreError
46
+ from synapse.api.room_versions import RoomVersion, RoomVersions
47
+ from synapse.config.homeserver import HomeServerConfig
48
+ from synapse.events import EventBase
49
+ from synapse.replication.tcp.streams.partial_state import UnPartialStatedRoomStream
50
+ from synapse.storage._base import (
51
+ db_to_json,
52
+ make_in_list_sql_clause,
53
+ )
54
+ from synapse.storage.database import (
55
+ DatabasePool,
56
+ LoggingDatabaseConnection,
57
+ LoggingTransaction,
58
+ make_tuple_in_list_sql_clause,
59
+ )
60
+ from synapse.storage.databases.main.cache import CacheInvalidationWorkerStore
61
+ from synapse.storage.types import Cursor
62
+ from synapse.storage.util.id_generators import IdGenerator, MultiWriterIdGenerator
63
+ from synapse.types import JsonDict, RetentionPolicy, StrCollection, ThirdPartyInstanceID
64
+ from synapse.util.caches.descriptors import cached, cachedList
65
+ from synapse.util.json import json_encoder
66
+ from synapse.util.stringutils import MXC_REGEX
67
+
68
+ if TYPE_CHECKING:
69
+ from synapse.server import HomeServer
70
+
71
+ logger = logging.getLogger(__name__)
72
+
73
+
74
+ @attr.s(slots=True, frozen=True, auto_attribs=True)
75
+ class RatelimitOverride:
76
+ # n.b. elsewhere in Synapse messages_per_second is represented as a float, but it is
77
+ # an integer in the database
78
+ messages_per_second: int
79
+ burst_count: int
80
+
81
+
82
+ @attr.s(slots=True, frozen=True, auto_attribs=True)
83
+ class LargestRoomStats:
84
+ room_id: str
85
+ name: Optional[str]
86
+ canonical_alias: Optional[str]
87
+ joined_members: int
88
+ join_rules: Optional[str]
89
+ guest_access: Optional[str]
90
+ history_visibility: Optional[str]
91
+ state_events: int
92
+ avatar: Optional[str]
93
+ topic: Optional[str]
94
+ room_type: Optional[str]
95
+
96
+
97
+ @attr.s(slots=True, frozen=True, auto_attribs=True)
98
+ class RoomStats(LargestRoomStats):
99
+ joined_local_members: int
100
+ version: Optional[str]
101
+ creator: Optional[str]
102
+ encryption: Optional[str]
103
+ federatable: bool
104
+ public: bool
105
+
106
+
107
+ class RoomSortOrder(Enum):
108
+ """
109
+ Enum to define the sorting method used when returning rooms with get_rooms_paginate
110
+
111
+ NAME = sort rooms alphabetically by name
112
+ JOINED_MEMBERS = sort rooms by membership size, highest to lowest
113
+ """
114
+
115
+ # ALPHABETICAL and SIZE are deprecated.
116
+ # ALPHABETICAL is the same as NAME.
117
+ ALPHABETICAL = "alphabetical"
118
+ # SIZE is the same as JOINED_MEMBERS.
119
+ SIZE = "size"
120
+ NAME = "name"
121
+ CANONICAL_ALIAS = "canonical_alias"
122
+ JOINED_MEMBERS = "joined_members"
123
+ JOINED_LOCAL_MEMBERS = "joined_local_members"
124
+ VERSION = "version"
125
+ CREATOR = "creator"
126
+ ENCRYPTION = "encryption"
127
+ FEDERATABLE = "federatable"
128
+ PUBLIC = "public"
129
+ JOIN_RULES = "join_rules"
130
+ GUEST_ACCESS = "guest_access"
131
+ HISTORY_VISIBILITY = "history_visibility"
132
+ STATE_EVENTS = "state_events"
133
+
134
+
135
+ @attr.s(slots=True, frozen=True, auto_attribs=True)
136
+ class PartialStateResyncInfo:
137
+ joined_via: Optional[str]
138
+ servers_in_room: set[str] = attr.ib(factory=set)
139
+
140
+
141
+ class RoomWorkerStore(CacheInvalidationWorkerStore):
142
+ def __init__(
143
+ self,
144
+ database: DatabasePool,
145
+ db_conn: LoggingDatabaseConnection,
146
+ hs: "HomeServer",
147
+ ):
148
+ super().__init__(database, db_conn, hs)
149
+
150
+ self.config: HomeServerConfig = hs.config
151
+
152
+ self._un_partial_stated_rooms_stream_id_gen: MultiWriterIdGenerator
153
+
154
+ self._un_partial_stated_rooms_stream_id_gen = MultiWriterIdGenerator(
155
+ db_conn=db_conn,
156
+ db=database,
157
+ notifier=hs.get_replication_notifier(),
158
+ stream_name="un_partial_stated_room_stream",
159
+ server_name=self.server_name,
160
+ instance_name=self._instance_name,
161
+ tables=[("un_partial_stated_room_stream", "instance_name", "stream_id")],
162
+ sequence_name="un_partial_stated_room_stream_sequence",
163
+ # TODO(faster_joins, multiple writers) Support multiple writers.
164
+ writers=["master"],
165
+ )
166
+
167
+ def process_replication_position(
168
+ self, stream_name: str, instance_name: str, token: int
169
+ ) -> None:
170
+ if stream_name == UnPartialStatedRoomStream.NAME:
171
+ self._un_partial_stated_rooms_stream_id_gen.advance(instance_name, token)
172
+ return super().process_replication_position(stream_name, instance_name, token)
173
+
174
+ async def store_room(
175
+ self,
176
+ room_id: str,
177
+ room_creator_user_id: str,
178
+ is_public: bool,
179
+ room_version: RoomVersion,
180
+ ) -> None:
181
+ """Stores a room.
182
+
183
+ Args:
184
+ room_id: The desired room ID, can be None.
185
+ room_creator_user_id: The user ID of the room creator.
186
+ is_public: True to indicate that this room should appear in
187
+ public room lists.
188
+ room_version: The version of the room
189
+ Raises:
190
+ StoreError if the room could not be stored.
191
+ """
192
+ try:
193
+ await self.db_pool.simple_insert(
194
+ "rooms",
195
+ {
196
+ "room_id": room_id,
197
+ "creator": room_creator_user_id,
198
+ "is_public": is_public,
199
+ "room_version": room_version.identifier,
200
+ "has_auth_chain_index": True,
201
+ },
202
+ desc="store_room",
203
+ )
204
+ except Exception as e:
205
+ logger.error("store_room with room_id=%s failed: %s", room_id, e)
206
+ raise StoreError(500, "Problem creating room.")
207
+
208
+ async def get_room(self, room_id: str) -> Optional[tuple[bool, bool]]:
209
+ """Retrieve a room.
210
+
211
+ Args:
212
+ room_id: The ID of the room to retrieve.
213
+ Returns:
214
+ A tuple containing the room information:
215
+ * True if the room is public
216
+ * True if the room has an auth chain index
217
+
218
+ or None if the room is unknown.
219
+ """
220
+ row = cast(
221
+ Optional[tuple[Optional[Union[int, bool]], Optional[Union[int, bool]]]],
222
+ await self.db_pool.simple_select_one(
223
+ table="rooms",
224
+ keyvalues={"room_id": room_id},
225
+ retcols=("is_public", "has_auth_chain_index"),
226
+ desc="get_room",
227
+ allow_none=True,
228
+ ),
229
+ )
230
+ if row is None:
231
+ return row
232
+ return bool(row[0]), bool(row[1])
233
+
234
+ async def get_room_with_stats(self, room_id: str) -> Optional[RoomStats]:
235
+ """Retrieve room with statistics.
236
+
237
+ Args:
238
+ room_id: The ID of the room to retrieve.
239
+ Returns:
240
+ A dict containing the room information, or None if the room is unknown.
241
+ """
242
+
243
+ def get_room_with_stats_txn(
244
+ txn: LoggingTransaction, room_id: str
245
+ ) -> Optional[RoomStats]:
246
+ sql = """
247
+ SELECT room_id, state.name, state.canonical_alias, curr.joined_members,
248
+ curr.local_users_in_room AS joined_local_members, rooms.room_version AS version,
249
+ rooms.creator, state.encryption, state.is_federatable AS federatable,
250
+ rooms.is_public AS public, state.join_rules, state.guest_access,
251
+ state.history_visibility, curr.current_state_events AS state_events,
252
+ state.avatar, state.topic, state.room_type
253
+ FROM rooms
254
+ LEFT JOIN room_stats_state state USING (room_id)
255
+ LEFT JOIN room_stats_current curr USING (room_id)
256
+ WHERE room_id = ?
257
+ """
258
+ txn.execute(sql, [room_id])
259
+ row = txn.fetchone()
260
+ if not row:
261
+ return None
262
+ return RoomStats(
263
+ room_id=row[0],
264
+ name=row[1],
265
+ canonical_alias=row[2],
266
+ joined_members=row[3],
267
+ joined_local_members=row[4],
268
+ version=row[5],
269
+ creator=row[6],
270
+ encryption=row[7],
271
+ federatable=bool(row[8]),
272
+ public=bool(row[9]),
273
+ join_rules=row[10],
274
+ guest_access=row[11],
275
+ history_visibility=row[12],
276
+ state_events=row[13],
277
+ avatar=row[14],
278
+ topic=row[15],
279
+ room_type=row[16],
280
+ )
281
+
282
+ return await self.db_pool.runInteraction(
283
+ "get_room_with_stats", get_room_with_stats_txn, room_id
284
+ )
285
+
286
+ async def get_public_room_ids(self) -> list[str]:
287
+ return await self.db_pool.simple_select_onecol(
288
+ table="rooms",
289
+ keyvalues={"is_public": True},
290
+ retcol="room_id",
291
+ desc="get_public_room_ids",
292
+ )
293
+
294
+ def _construct_room_type_where_clause(
295
+ self, room_types: Union[list[Union[str, None]], None]
296
+ ) -> tuple[Union[str, None], list]:
297
+ if not room_types:
298
+ return None, []
299
+
300
+ # Since None is used to represent a room without a type, care needs to
301
+ # be taken into account when constructing the where clause.
302
+ clauses = []
303
+ args: list = []
304
+
305
+ room_types_set = set(room_types)
306
+
307
+ # We use None to represent a room without a type.
308
+ if None in room_types_set:
309
+ clauses.append("room_type IS NULL")
310
+ room_types_set.remove(None)
311
+
312
+ # If there are other room types, generate the proper clause.
313
+ if room_types:
314
+ list_clause, args = make_in_list_sql_clause(
315
+ self.database_engine, "room_type", room_types_set
316
+ )
317
+ clauses.append(list_clause)
318
+
319
+ return f"({' OR '.join(clauses)})", args
320
+
321
+ async def count_public_rooms(
322
+ self,
323
+ network_tuple: Optional[ThirdPartyInstanceID],
324
+ ignore_non_federatable: bool,
325
+ search_filter: Optional[dict],
326
+ ) -> int:
327
+ """Counts the number of public rooms as tracked in the room_stats_current
328
+ and room_stats_state table.
329
+
330
+ Args:
331
+ network_tuple
332
+ ignore_non_federatable: If true filters out non-federatable rooms
333
+ search_filter
334
+ """
335
+
336
+ def _count_public_rooms_txn(txn: LoggingTransaction) -> int:
337
+ query_args = []
338
+
339
+ if network_tuple:
340
+ if network_tuple.appservice_id:
341
+ published_sql = """
342
+ SELECT room_id from appservice_room_list
343
+ WHERE appservice_id = ? AND network_id = ?
344
+ """
345
+ query_args.append(network_tuple.appservice_id)
346
+ assert network_tuple.network_id is not None
347
+ query_args.append(network_tuple.network_id)
348
+ else:
349
+ published_sql = """
350
+ SELECT room_id FROM rooms WHERE is_public
351
+ """
352
+ else:
353
+ published_sql = """
354
+ SELECT room_id FROM rooms WHERE is_public
355
+ UNION SELECT room_id from appservice_room_list
356
+ """
357
+
358
+ room_type_clause, args = self._construct_room_type_where_clause(
359
+ search_filter.get(PublicRoomsFilterFields.ROOM_TYPES, None)
360
+ if search_filter
361
+ else None
362
+ )
363
+ room_type_clause = f" AND {room_type_clause}" if room_type_clause else ""
364
+ query_args += args
365
+
366
+ sql = f"""
367
+ SELECT
368
+ COUNT(*)
369
+ FROM (
370
+ {published_sql}
371
+ ) published
372
+ INNER JOIN room_stats_state USING (room_id)
373
+ INNER JOIN room_stats_current USING (room_id)
374
+ WHERE
375
+ (
376
+ join_rules = '{JoinRules.PUBLIC}'
377
+ OR join_rules = '{JoinRules.KNOCK}'
378
+ OR join_rules = '{JoinRules.KNOCK_RESTRICTED}'
379
+ OR history_visibility = 'world_readable'
380
+ )
381
+ {room_type_clause}
382
+ AND joined_members > 0
383
+ """
384
+
385
+ txn.execute(sql, query_args)
386
+ return cast(tuple[int], txn.fetchone())[0]
387
+
388
+ return await self.db_pool.runInteraction(
389
+ "count_public_rooms", _count_public_rooms_txn
390
+ )
391
+
392
+ async def get_room_count(self) -> int:
393
+ """Retrieve the total number of rooms."""
394
+
395
+ def f(txn: LoggingTransaction) -> int:
396
+ sql = "SELECT count(*) FROM rooms"
397
+ txn.execute(sql)
398
+ row = cast(tuple[int], txn.fetchone())
399
+ return row[0]
400
+
401
+ return await self.db_pool.runInteraction("get_rooms", f)
402
+
403
+ async def get_largest_public_rooms(
404
+ self,
405
+ network_tuple: Optional[ThirdPartyInstanceID],
406
+ search_filter: Optional[dict],
407
+ limit: Optional[int],
408
+ bounds: Optional[tuple[int, str]],
409
+ forwards: bool,
410
+ ignore_non_federatable: bool = False,
411
+ ) -> list[LargestRoomStats]:
412
+ """Gets the largest public rooms (where largest is in terms of joined
413
+ members, as tracked in the statistics table).
414
+
415
+ Args:
416
+ network_tuple
417
+ search_filter
418
+ limit: Maxmimum number of rows to return, unlimited otherwise.
419
+ bounds: An uppoer or lower bound to apply to result set if given,
420
+ consists of a joined member count and room_id (these are
421
+ excluded from result set).
422
+ forwards: true iff going forwards, going backwards otherwise
423
+ ignore_non_federatable: If true filters out non-federatable rooms.
424
+
425
+ Returns:
426
+ Rooms in order: biggest number of joined users first.
427
+ We then arbitrarily use the room_id as a tie breaker.
428
+
429
+ """
430
+
431
+ where_clauses = []
432
+ query_args: list[Union[str, int]] = []
433
+
434
+ if network_tuple:
435
+ if network_tuple.appservice_id:
436
+ published_sql = """
437
+ SELECT room_id from appservice_room_list
438
+ WHERE appservice_id = ? AND network_id = ?
439
+ """
440
+ query_args.append(network_tuple.appservice_id)
441
+ assert network_tuple.network_id is not None
442
+ query_args.append(network_tuple.network_id)
443
+ else:
444
+ published_sql = """
445
+ SELECT room_id FROM rooms WHERE is_public
446
+ """
447
+ else:
448
+ published_sql = """
449
+ SELECT room_id FROM rooms WHERE is_public
450
+ UNION SELECT room_id from appservice_room_list
451
+ """
452
+
453
+ # Work out the bounds if we're given them, these bounds look slightly
454
+ # odd, but are designed to help query planner use indices by pulling
455
+ # out a common bound.
456
+ if bounds:
457
+ last_joined_members, last_room_id = bounds
458
+ if forwards:
459
+ where_clauses.append(
460
+ """
461
+ joined_members <= ? AND (
462
+ joined_members < ? OR room_id < ?
463
+ )
464
+ """
465
+ )
466
+ else:
467
+ where_clauses.append(
468
+ """
469
+ joined_members >= ? AND (
470
+ joined_members > ? OR room_id > ?
471
+ )
472
+ """
473
+ )
474
+
475
+ query_args += [last_joined_members, last_joined_members, last_room_id]
476
+
477
+ if ignore_non_federatable:
478
+ where_clauses.append("is_federatable")
479
+
480
+ if search_filter and search_filter.get(
481
+ PublicRoomsFilterFields.GENERIC_SEARCH_TERM, None
482
+ ):
483
+ search_term = (
484
+ "%" + search_filter[PublicRoomsFilterFields.GENERIC_SEARCH_TERM] + "%"
485
+ )
486
+
487
+ where_clauses.append(
488
+ """
489
+ (
490
+ LOWER(name) LIKE ?
491
+ OR LOWER(topic) LIKE ?
492
+ OR LOWER(canonical_alias) LIKE ?
493
+ )
494
+ """
495
+ )
496
+ query_args += [
497
+ search_term.lower(),
498
+ search_term.lower(),
499
+ search_term.lower(),
500
+ ]
501
+
502
+ room_type_clause, args = self._construct_room_type_where_clause(
503
+ search_filter.get(PublicRoomsFilterFields.ROOM_TYPES, None)
504
+ if search_filter
505
+ else None
506
+ )
507
+ if room_type_clause:
508
+ where_clauses.append(room_type_clause)
509
+ query_args += args
510
+
511
+ where_clause = ""
512
+ if where_clauses:
513
+ where_clause = " AND " + " AND ".join(where_clauses)
514
+
515
+ dir = "DESC" if forwards else "ASC"
516
+ sql = f"""
517
+ SELECT
518
+ room_id, name, topic, canonical_alias, joined_members,
519
+ avatar, history_visibility, guest_access, join_rules, room_type
520
+ FROM (
521
+ {published_sql}
522
+ ) published
523
+ INNER JOIN room_stats_state USING (room_id)
524
+ INNER JOIN room_stats_current USING (room_id)
525
+ WHERE
526
+ (
527
+ join_rules = '{JoinRules.PUBLIC}'
528
+ OR join_rules = '{JoinRules.KNOCK}'
529
+ OR join_rules = '{JoinRules.KNOCK_RESTRICTED}'
530
+ OR history_visibility = 'world_readable'
531
+ )
532
+ AND joined_members > 0
533
+ {where_clause}
534
+ ORDER BY
535
+ joined_members {dir},
536
+ room_id {dir}
537
+ """
538
+
539
+ if limit is not None:
540
+ query_args.append(limit)
541
+
542
+ sql += """
543
+ LIMIT ?
544
+ """
545
+
546
+ def _get_largest_public_rooms_txn(
547
+ txn: LoggingTransaction,
548
+ ) -> list[LargestRoomStats]:
549
+ txn.execute(sql, query_args)
550
+
551
+ results = [
552
+ LargestRoomStats(
553
+ room_id=r[0],
554
+ name=r[1],
555
+ canonical_alias=r[3],
556
+ joined_members=r[4],
557
+ join_rules=r[8],
558
+ guest_access=r[7],
559
+ history_visibility=r[6],
560
+ state_events=0,
561
+ avatar=r[5],
562
+ topic=r[2],
563
+ room_type=r[9],
564
+ )
565
+ for r in txn
566
+ ]
567
+
568
+ if not forwards:
569
+ results.reverse()
570
+
571
+ return results
572
+
573
+ return await self.db_pool.runInteraction(
574
+ "get_largest_public_rooms", _get_largest_public_rooms_txn
575
+ )
576
+
577
+ @cached(max_entries=10000)
578
+ async def is_room_blocked(self, room_id: str) -> Optional[bool]:
579
+ return await self.db_pool.simple_select_one_onecol(
580
+ table="blocked_rooms",
581
+ keyvalues={"room_id": room_id},
582
+ retcol="1",
583
+ allow_none=True,
584
+ desc="is_room_blocked",
585
+ )
586
+
587
+ async def room_is_blocked_by(self, room_id: str) -> Optional[str]:
588
+ """
589
+ Function to retrieve user who has blocked the room.
590
+ user_id is non-nullable
591
+ It returns None if the room is not blocked.
592
+ """
593
+ return await self.db_pool.simple_select_one_onecol(
594
+ table="blocked_rooms",
595
+ keyvalues={"room_id": room_id},
596
+ retcol="user_id",
597
+ allow_none=True,
598
+ desc="room_is_blocked_by",
599
+ )
600
+
601
+ async def get_rooms_paginate(
602
+ self,
603
+ start: int,
604
+ limit: int,
605
+ order_by: str,
606
+ reverse_order: bool,
607
+ search_term: Optional[str],
608
+ public_rooms: Optional[bool],
609
+ empty_rooms: Optional[bool],
610
+ ) -> tuple[list[dict[str, Any]], int]:
611
+ """Function to retrieve a paginated list of rooms as json.
612
+
613
+ Args:
614
+ start: offset in the list
615
+ limit: maximum amount of rooms to retrieve
616
+ order_by: the sort order of the returned list
617
+ reverse_order: whether to reverse the room list
618
+ search_term: a string to filter room names,
619
+ canonical alias and room ids by.
620
+ Room ID must match exactly. Canonical alias must match a substring of the local part.
621
+ public_rooms: Optional flag to filter public and non-public rooms. If true, public rooms are queried.
622
+ if false, public rooms are excluded from the query. When it is
623
+ none (the default), both public rooms and none-public-rooms are queried.
624
+ empty_rooms: Optional flag to filter empty and non-empty rooms.
625
+ A room is empty if joined_members is zero.
626
+ If true, empty rooms are queried.
627
+ if false, empty rooms are excluded from the query. When it is
628
+ none (the default), both empty rooms and none-empty rooms are queried.
629
+ Returns:
630
+ A list of room dicts and an integer representing the total number of
631
+ rooms that exist given this query
632
+ """
633
+ # Filter room names by a string
634
+ filter_ = []
635
+ where_args = []
636
+ if search_term:
637
+ filter_ = [
638
+ "LOWER(state.name) LIKE ? OR "
639
+ "LOWER(state.canonical_alias) LIKE ? OR "
640
+ "state.room_id = ?"
641
+ ]
642
+
643
+ # Our postgres db driver converts ? -> %s in SQL strings as that's the
644
+ # placeholder for postgres.
645
+ # HOWEVER, if you put a % into your SQL then everything goes wibbly.
646
+ # To get around this, we're going to surround search_term with %'s
647
+ # before giving it to the database in python instead
648
+ where_args = [
649
+ f"%{search_term.lower()}%",
650
+ f"#%{search_term.lower()}%:%",
651
+ search_term,
652
+ ]
653
+ if public_rooms is not None:
654
+ filter_arg = "1" if public_rooms else "0"
655
+ filter_.append(f"rooms.is_public = '{filter_arg}'")
656
+
657
+ if empty_rooms is not None:
658
+ if empty_rooms:
659
+ filter_.append("curr.joined_members = 0")
660
+ else:
661
+ filter_.append("curr.joined_members <> 0")
662
+
663
+ where_clause = "WHERE " + " AND ".join(filter_) if len(filter_) > 0 else ""
664
+
665
+ # Set ordering
666
+ if RoomSortOrder(order_by) == RoomSortOrder.SIZE:
667
+ # Deprecated in favour of RoomSortOrder.JOINED_MEMBERS
668
+ order_by_column = "curr.joined_members"
669
+ order_by_asc = False
670
+ elif RoomSortOrder(order_by) == RoomSortOrder.ALPHABETICAL:
671
+ # Deprecated in favour of RoomSortOrder.NAME
672
+ order_by_column = "state.name"
673
+ order_by_asc = True
674
+ elif RoomSortOrder(order_by) == RoomSortOrder.NAME:
675
+ order_by_column = "state.name"
676
+ order_by_asc = True
677
+ elif RoomSortOrder(order_by) == RoomSortOrder.CANONICAL_ALIAS:
678
+ order_by_column = "state.canonical_alias"
679
+ order_by_asc = True
680
+ elif RoomSortOrder(order_by) == RoomSortOrder.JOINED_MEMBERS:
681
+ order_by_column = "curr.joined_members"
682
+ order_by_asc = False
683
+ elif RoomSortOrder(order_by) == RoomSortOrder.JOINED_LOCAL_MEMBERS:
684
+ order_by_column = "curr.local_users_in_room"
685
+ order_by_asc = False
686
+ elif RoomSortOrder(order_by) == RoomSortOrder.VERSION:
687
+ order_by_column = "rooms.room_version"
688
+ order_by_asc = False
689
+ elif RoomSortOrder(order_by) == RoomSortOrder.CREATOR:
690
+ order_by_column = "rooms.creator"
691
+ order_by_asc = True
692
+ elif RoomSortOrder(order_by) == RoomSortOrder.ENCRYPTION:
693
+ order_by_column = "state.encryption"
694
+ order_by_asc = True
695
+ elif RoomSortOrder(order_by) == RoomSortOrder.FEDERATABLE:
696
+ order_by_column = "state.is_federatable"
697
+ order_by_asc = True
698
+ elif RoomSortOrder(order_by) == RoomSortOrder.PUBLIC:
699
+ order_by_column = "rooms.is_public"
700
+ order_by_asc = True
701
+ elif RoomSortOrder(order_by) == RoomSortOrder.JOIN_RULES:
702
+ order_by_column = "state.join_rules"
703
+ order_by_asc = True
704
+ elif RoomSortOrder(order_by) == RoomSortOrder.GUEST_ACCESS:
705
+ order_by_column = "state.guest_access"
706
+ order_by_asc = True
707
+ elif RoomSortOrder(order_by) == RoomSortOrder.HISTORY_VISIBILITY:
708
+ order_by_column = "state.history_visibility"
709
+ order_by_asc = True
710
+ elif RoomSortOrder(order_by) == RoomSortOrder.STATE_EVENTS:
711
+ order_by_column = "curr.current_state_events"
712
+ order_by_asc = False
713
+ else:
714
+ raise StoreError(
715
+ 500, "Incorrect value for order_by provided: %s" % order_by
716
+ )
717
+
718
+ # Whether to return the list in reverse order
719
+ if reverse_order:
720
+ # Flip the boolean
721
+ order_by_asc = not order_by_asc
722
+
723
+ # Create one query for getting the limited number of events that the user asked
724
+ # for, and another query for getting the total number of events that could be
725
+ # returned. Thus allowing us to see if there are more events to paginate through
726
+ info_sql = """
727
+ SELECT state.room_id, state.name, state.canonical_alias, curr.joined_members,
728
+ curr.local_users_in_room, rooms.room_version, rooms.creator,
729
+ state.encryption, state.is_federatable, rooms.is_public, state.join_rules,
730
+ state.guest_access, state.history_visibility, curr.current_state_events,
731
+ state.room_type
732
+ FROM room_stats_state state
733
+ INNER JOIN room_stats_current curr USING (room_id)
734
+ INNER JOIN rooms USING (room_id)
735
+ {where}
736
+ ORDER BY {order_by} {direction}, state.room_id {direction}
737
+ LIMIT ?
738
+ OFFSET ?
739
+ """.format(
740
+ where=where_clause,
741
+ order_by=order_by_column,
742
+ direction="ASC" if order_by_asc else "DESC",
743
+ )
744
+
745
+ # Use a nested SELECT statement as SQL can't count(*) with an OFFSET
746
+ count_sql = """
747
+ SELECT count(*) FROM (
748
+ SELECT room_id FROM room_stats_state state
749
+ INNER JOIN room_stats_current curr USING (room_id)
750
+ INNER JOIN rooms USING (room_id)
751
+ {where}
752
+ ) AS get_room_ids
753
+ """.format(
754
+ where=where_clause,
755
+ )
756
+
757
+ def _get_rooms_paginate_txn(
758
+ txn: LoggingTransaction,
759
+ ) -> tuple[list[dict[str, Any]], int]:
760
+ # Add the search term into the WHERE clause
761
+ # and execute the data query
762
+ txn.execute(info_sql, where_args + [limit, start])
763
+
764
+ # Refactor room query data into a structured dictionary
765
+ rooms = []
766
+ for room in txn:
767
+ rooms.append(
768
+ {
769
+ "room_id": room[0],
770
+ "name": room[1],
771
+ "canonical_alias": room[2],
772
+ "joined_members": room[3],
773
+ "joined_local_members": room[4],
774
+ "version": room[5],
775
+ "creator": room[6],
776
+ "encryption": room[7],
777
+ # room_stats_state.federatable is an integer on sqlite.
778
+ "federatable": bool(room[8]),
779
+ # rooms.is_public is an integer on sqlite.
780
+ "public": bool(room[9]),
781
+ "join_rules": room[10],
782
+ "guest_access": room[11],
783
+ "history_visibility": room[12],
784
+ "state_events": room[13],
785
+ "room_type": room[14],
786
+ }
787
+ )
788
+
789
+ # Execute the count query
790
+
791
+ # Add the search term into the WHERE clause if present
792
+ txn.execute(count_sql, where_args)
793
+
794
+ room_count = cast(tuple[int], txn.fetchone())
795
+ return rooms, room_count[0]
796
+
797
+ return await self.db_pool.runInteraction(
798
+ "get_rooms_paginate",
799
+ _get_rooms_paginate_txn,
800
+ )
801
+
802
+ @cached(max_entries=10000)
803
+ async def get_ratelimit_for_user(self, user_id: str) -> Optional[RatelimitOverride]:
804
+ """Check if there are any overrides for ratelimiting for the given user
805
+
806
+ Args:
807
+ user_id: user ID of the user
808
+ Returns:
809
+ RatelimitOverride if there is an override, else None. If the contents
810
+ of RatelimitOverride are None or 0 then ratelimitng has been
811
+ disabled for that user entirely.
812
+ """
813
+ row = await self.db_pool.simple_select_one(
814
+ table="ratelimit_override",
815
+ keyvalues={"user_id": user_id},
816
+ retcols=("messages_per_second", "burst_count"),
817
+ allow_none=True,
818
+ desc="get_ratelimit_for_user",
819
+ )
820
+
821
+ if row:
822
+ return RatelimitOverride(messages_per_second=row[0], burst_count=row[1])
823
+ else:
824
+ return None
825
+
826
+ async def set_ratelimit_for_user(
827
+ self, user_id: str, messages_per_second: int, burst_count: int
828
+ ) -> None:
829
+ """Sets whether a user is set an overridden ratelimit.
830
+ Args:
831
+ user_id: user ID of the user
832
+ messages_per_second: The number of actions that can be performed in a second.
833
+ burst_count: How many actions that can be performed before being limited.
834
+ """
835
+
836
+ def set_ratelimit_txn(txn: LoggingTransaction) -> None:
837
+ self.db_pool.simple_upsert_txn(
838
+ txn,
839
+ table="ratelimit_override",
840
+ keyvalues={"user_id": user_id},
841
+ values={
842
+ "messages_per_second": messages_per_second,
843
+ "burst_count": burst_count,
844
+ },
845
+ )
846
+
847
+ self._invalidate_cache_and_stream(
848
+ txn, self.get_ratelimit_for_user, (user_id,)
849
+ )
850
+
851
+ await self.db_pool.runInteraction("set_ratelimit", set_ratelimit_txn)
852
+
853
+ async def delete_ratelimit_for_user(self, user_id: str) -> None:
854
+ """Delete an overridden ratelimit for a user.
855
+ Args:
856
+ user_id: user ID of the user
857
+ """
858
+
859
+ def delete_ratelimit_txn(txn: LoggingTransaction) -> None:
860
+ row = self.db_pool.simple_select_one_txn(
861
+ txn,
862
+ table="ratelimit_override",
863
+ keyvalues={"user_id": user_id},
864
+ retcols=["user_id"],
865
+ allow_none=True,
866
+ )
867
+
868
+ if not row:
869
+ return
870
+
871
+ # They are there, delete them.
872
+ self.db_pool.simple_delete_one_txn(
873
+ txn, "ratelimit_override", keyvalues={"user_id": user_id}
874
+ )
875
+
876
+ self._invalidate_cache_and_stream(
877
+ txn, self.get_ratelimit_for_user, (user_id,)
878
+ )
879
+
880
+ await self.db_pool.runInteraction("delete_ratelimit", delete_ratelimit_txn)
881
+
882
+ @cached()
883
+ async def get_retention_policy_for_room(self, room_id: str) -> RetentionPolicy:
884
+ """Get the retention policy for a given room.
885
+
886
+ If no retention policy has been found for this room, returns a policy defined
887
+ by the configured default policy (which has None as both the 'min_lifetime' and
888
+ the 'max_lifetime' if no default policy has been defined in the server's
889
+ configuration).
890
+
891
+ If support for retention policies is disabled, a policy with a 'min_lifetime' and
892
+ 'max_lifetime' of None is returned.
893
+
894
+ Args:
895
+ room_id: The ID of the room to get the retention policy of.
896
+
897
+ Returns:
898
+ A dict containing "min_lifetime" and "max_lifetime" for this room.
899
+ """
900
+ # If the room retention feature is disabled, return a policy with no minimum nor
901
+ # maximum. This prevents incorrectly filtering out events when sending to
902
+ # the client.
903
+ if not self.config.retention.retention_enabled:
904
+ return RetentionPolicy()
905
+
906
+ def get_retention_policy_for_room_txn(
907
+ txn: LoggingTransaction,
908
+ ) -> Optional[tuple[Optional[int], Optional[int]]]:
909
+ txn.execute(
910
+ """
911
+ SELECT min_lifetime, max_lifetime FROM room_retention
912
+ INNER JOIN current_state_events USING (event_id, room_id)
913
+ WHERE room_id = ?;
914
+ """,
915
+ (room_id,),
916
+ )
917
+
918
+ return cast(Optional[tuple[Optional[int], Optional[int]]], txn.fetchone())
919
+
920
+ ret = await self.db_pool.runInteraction(
921
+ "get_retention_policy_for_room",
922
+ get_retention_policy_for_room_txn,
923
+ )
924
+
925
+ # If we don't know this room ID, ret will be None, in this case return the default
926
+ # policy.
927
+ if not ret:
928
+ return RetentionPolicy(
929
+ min_lifetime=self.config.retention.retention_default_min_lifetime,
930
+ max_lifetime=self.config.retention.retention_default_max_lifetime,
931
+ )
932
+
933
+ min_lifetime, max_lifetime = ret
934
+
935
+ # If one of the room's policy's attributes isn't defined, use the matching
936
+ # attribute from the default policy.
937
+ # The default values will be None if no default policy has been defined, or if one
938
+ # of the attributes is missing from the default policy.
939
+ if min_lifetime is None:
940
+ min_lifetime = self.config.retention.retention_default_min_lifetime
941
+
942
+ if max_lifetime is None:
943
+ max_lifetime = self.config.retention.retention_default_max_lifetime
944
+
945
+ return RetentionPolicy(
946
+ min_lifetime=min_lifetime,
947
+ max_lifetime=max_lifetime,
948
+ )
949
+
950
+ async def get_media_mxcs_in_room(self, room_id: str) -> tuple[list[str], list[str]]:
951
+ """Retrieves all the local and remote media MXC URIs in a given room
952
+
953
+ Args:
954
+ room_id
955
+
956
+ Returns:
957
+ The local and remote media as a lists of the media IDs.
958
+ """
959
+
960
+ def _get_media_mxcs_in_room_txn(
961
+ txn: LoggingTransaction,
962
+ ) -> tuple[list[str], list[str]]:
963
+ local_mxcs, remote_mxcs = self._get_media_mxcs_in_room_txn(txn, room_id)
964
+ local_media_mxcs = []
965
+ remote_media_mxcs = []
966
+
967
+ # Convert the IDs to MXC URIs
968
+ for media_id in local_mxcs:
969
+ local_media_mxcs.append("mxc://%s/%s" % (self.hs.hostname, media_id))
970
+ for hostname, media_id in remote_mxcs:
971
+ remote_media_mxcs.append("mxc://%s/%s" % (hostname, media_id))
972
+
973
+ return local_media_mxcs, remote_media_mxcs
974
+
975
+ return await self.db_pool.runInteraction(
976
+ "get_media_ids_in_room", _get_media_mxcs_in_room_txn
977
+ )
978
+
979
+ async def quarantine_media_ids_in_room(
980
+ self, room_id: str, quarantined_by: str
981
+ ) -> int:
982
+ """For a room loops through all events with media and quarantines
983
+ the associated media
984
+ """
985
+
986
+ logger.info("Quarantining media in room: %s", room_id)
987
+
988
+ def _quarantine_media_in_room_txn(txn: LoggingTransaction) -> int:
989
+ local_mxcs, remote_mxcs = self._get_media_mxcs_in_room_txn(txn, room_id)
990
+ return self._quarantine_media_txn(
991
+ txn, local_mxcs, remote_mxcs, quarantined_by
992
+ )
993
+
994
+ return await self.db_pool.runInteraction(
995
+ "quarantine_media_in_room", _quarantine_media_in_room_txn
996
+ )
997
+
998
+ def _get_media_mxcs_in_room_txn(
999
+ self, txn: LoggingTransaction, room_id: str
1000
+ ) -> tuple[list[str], list[tuple[str, str]]]:
1001
+ """Retrieves all the local and remote media MXC URIs in a given room
1002
+
1003
+ Returns:
1004
+ The local and remote media as a lists of tuples where the key is
1005
+ the hostname and the value is the media ID.
1006
+ """
1007
+ sql = """
1008
+ SELECT stream_ordering, json FROM events
1009
+ JOIN event_json USING (room_id, event_id)
1010
+ WHERE room_id = ?
1011
+ %(where_clause)s
1012
+ AND contains_url = TRUE AND outlier = FALSE
1013
+ ORDER BY stream_ordering DESC
1014
+ LIMIT ?
1015
+ """
1016
+ txn.execute(sql % {"where_clause": ""}, (room_id, 100))
1017
+
1018
+ local_media_mxcs = []
1019
+ remote_media_mxcs = []
1020
+
1021
+ while True:
1022
+ next_token = None
1023
+ for stream_ordering, content_json in txn:
1024
+ next_token = stream_ordering
1025
+ event_json = db_to_json(content_json)
1026
+ content = event_json["content"]
1027
+ content_url = content.get("url")
1028
+ info = content.get("info")
1029
+ if isinstance(info, dict):
1030
+ thumbnail_url = info.get("thumbnail_url")
1031
+ else:
1032
+ thumbnail_url = None
1033
+
1034
+ for url in (content_url, thumbnail_url):
1035
+ if not url:
1036
+ continue
1037
+ matches = MXC_REGEX.match(url)
1038
+ if matches:
1039
+ hostname = matches.group(1)
1040
+ media_id = matches.group(2)
1041
+ if hostname == self.hs.hostname:
1042
+ local_media_mxcs.append(media_id)
1043
+ else:
1044
+ remote_media_mxcs.append((hostname, media_id))
1045
+
1046
+ if next_token is None:
1047
+ # We've gone through the whole room, so we're finished.
1048
+ break
1049
+
1050
+ txn.execute(
1051
+ sql % {"where_clause": "AND stream_ordering < ?"},
1052
+ (room_id, next_token, 100),
1053
+ )
1054
+
1055
+ return local_media_mxcs, remote_media_mxcs
1056
+
1057
+ async def quarantine_media_by_id(
1058
+ self,
1059
+ server_name: str,
1060
+ media_id: str,
1061
+ quarantined_by: Optional[str],
1062
+ ) -> int:
1063
+ """quarantines or unquarantines a single local or remote media id
1064
+
1065
+ Args:
1066
+ server_name: The name of the server that holds this media
1067
+ media_id: The ID of the media to be quarantined
1068
+ quarantined_by: The user ID that initiated the quarantine request
1069
+ If it is `None` media will be removed from quarantine
1070
+ """
1071
+ logger.info("Quarantining media: %s/%s", server_name, media_id)
1072
+ is_local = self.hs.is_mine_server_name(server_name)
1073
+
1074
+ def _quarantine_media_by_id_txn(txn: LoggingTransaction) -> int:
1075
+ local_mxcs = [media_id] if is_local else []
1076
+ remote_mxcs = [(server_name, media_id)] if not is_local else []
1077
+
1078
+ return self._quarantine_media_txn(
1079
+ txn, local_mxcs, remote_mxcs, quarantined_by
1080
+ )
1081
+
1082
+ return await self.db_pool.runInteraction(
1083
+ "quarantine_media_by_user", _quarantine_media_by_id_txn
1084
+ )
1085
+
1086
+ async def quarantine_media_ids_by_user(
1087
+ self, user_id: str, quarantined_by: str
1088
+ ) -> int:
1089
+ """quarantines all local media associated with a single user
1090
+
1091
+ Args:
1092
+ user_id: The ID of the user to quarantine media of
1093
+ quarantined_by: The ID of the user who made the quarantine request
1094
+ """
1095
+
1096
+ def _quarantine_media_by_user_txn(txn: LoggingTransaction) -> int:
1097
+ local_media_ids = self._get_media_ids_by_user_txn(txn, user_id)
1098
+ return self._quarantine_media_txn(txn, local_media_ids, [], quarantined_by)
1099
+
1100
+ return await self.db_pool.runInteraction(
1101
+ "quarantine_media_by_user", _quarantine_media_by_user_txn
1102
+ )
1103
+
1104
+ def _get_media_ids_by_user_txn(
1105
+ self, txn: LoggingTransaction, user_id: str, filter_quarantined: bool = True
1106
+ ) -> list[str]:
1107
+ """Retrieves local media IDs by a given user
1108
+
1109
+ Args:
1110
+ txn (cursor)
1111
+ user_id: The ID of the user to retrieve media IDs of
1112
+
1113
+ Returns:
1114
+ The local and remote media as a lists of tuples where the key is
1115
+ the hostname and the value is the media ID.
1116
+ """
1117
+ # Local media
1118
+ sql = """
1119
+ SELECT media_id
1120
+ FROM local_media_repository
1121
+ WHERE user_id = ?
1122
+ """
1123
+ if filter_quarantined:
1124
+ sql += "AND quarantined_by IS NULL"
1125
+ txn.execute(sql, (user_id,))
1126
+
1127
+ local_media_ids = [row[0] for row in txn]
1128
+
1129
+ # TODO: Figure out all remote media a user has referenced in a message
1130
+
1131
+ return local_media_ids
1132
+
1133
+ def _quarantine_local_media_txn(
1134
+ self,
1135
+ txn: LoggingTransaction,
1136
+ hashes: set[str],
1137
+ media_ids: set[str],
1138
+ quarantined_by: Optional[str],
1139
+ ) -> int:
1140
+ """Quarantine and unquarantine local media items.
1141
+
1142
+ Args:
1143
+ txn (cursor)
1144
+ hashes: A set of sha256 hashes for any media that should be quarantined
1145
+ media_ids: A set of media IDs for any media that should be quarantined
1146
+ quarantined_by: The ID of the user who initiated the quarantine request
1147
+ If it is `None` media will be removed from quarantine
1148
+ Returns:
1149
+ The total number of media items quarantined
1150
+ """
1151
+ total_media_quarantined = 0
1152
+
1153
+ # Effectively a legacy path, update any media that was explicitly named.
1154
+ if media_ids:
1155
+ sql_many_clause_sql, sql_many_clause_args = make_in_list_sql_clause(
1156
+ txn.database_engine, "media_id", media_ids
1157
+ )
1158
+ sql = f"""
1159
+ UPDATE local_media_repository
1160
+ SET quarantined_by = ?
1161
+ WHERE {sql_many_clause_sql}"""
1162
+
1163
+ if quarantined_by is not None:
1164
+ sql += " AND safe_from_quarantine = FALSE"
1165
+
1166
+ txn.execute(sql, [quarantined_by] + sql_many_clause_args)
1167
+ # Note that a rowcount of -1 can be used to indicate no rows were affected.
1168
+ total_media_quarantined += txn.rowcount if txn.rowcount > 0 else 0
1169
+
1170
+ # Update any media that was identified via hash.
1171
+ if hashes:
1172
+ sql_many_clause_sql, sql_many_clause_args = make_in_list_sql_clause(
1173
+ txn.database_engine, "sha256", hashes
1174
+ )
1175
+ sql = f"""
1176
+ UPDATE local_media_repository
1177
+ SET quarantined_by = ?
1178
+ WHERE {sql_many_clause_sql}"""
1179
+
1180
+ if quarantined_by is not None:
1181
+ sql += " AND safe_from_quarantine = FALSE"
1182
+
1183
+ txn.execute(sql, [quarantined_by] + sql_many_clause_args)
1184
+ total_media_quarantined += txn.rowcount if txn.rowcount > 0 else 0
1185
+
1186
+ return total_media_quarantined
1187
+
1188
+ def _quarantine_remote_media_txn(
1189
+ self,
1190
+ txn: LoggingTransaction,
1191
+ hashes: set[str],
1192
+ media: set[tuple[str, str]],
1193
+ quarantined_by: Optional[str],
1194
+ ) -> int:
1195
+ """Quarantine and unquarantine remote items
1196
+
1197
+ Args:
1198
+ txn (cursor)
1199
+ hashes: A set of sha256 hashes for any media that should be quarantined
1200
+ media_ids: A set of tuples (media_origin, media_id) for any media that should be quarantined
1201
+ quarantined_by: The ID of the user who initiated the quarantine request
1202
+ If it is `None` media will be removed from quarantine
1203
+ Returns:
1204
+ The total number of media items quarantined
1205
+ """
1206
+ total_media_quarantined = 0
1207
+
1208
+ if media:
1209
+ sql_in_list_clause, sql_args = make_tuple_in_list_sql_clause(
1210
+ txn.database_engine,
1211
+ ("media_origin", "media_id"),
1212
+ media,
1213
+ )
1214
+ sql = f"""
1215
+ UPDATE remote_media_cache
1216
+ SET quarantined_by = ?
1217
+ WHERE {sql_in_list_clause}"""
1218
+
1219
+ txn.execute(sql, [quarantined_by] + sql_args)
1220
+ total_media_quarantined += txn.rowcount if txn.rowcount > 0 else 0
1221
+
1222
+ total_media_quarantined = 0
1223
+ if hashes:
1224
+ sql_many_clause_sql, sql_many_clause_args = make_in_list_sql_clause(
1225
+ txn.database_engine, "sha256", hashes
1226
+ )
1227
+ sql = f"""
1228
+ UPDATE remote_media_cache
1229
+ SET quarantined_by = ?
1230
+ WHERE {sql_many_clause_sql}"""
1231
+ txn.execute(sql, [quarantined_by] + sql_many_clause_args)
1232
+ total_media_quarantined += txn.rowcount if txn.rowcount > 0 else 0
1233
+
1234
+ return total_media_quarantined
1235
+
1236
+ def _quarantine_media_txn(
1237
+ self,
1238
+ txn: LoggingTransaction,
1239
+ local_mxcs: list[str],
1240
+ remote_mxcs: list[tuple[str, str]],
1241
+ quarantined_by: Optional[str],
1242
+ ) -> int:
1243
+ """Quarantine and unquarantine local and remote media items
1244
+
1245
+ Args:
1246
+ txn (cursor)
1247
+ local_mxcs: A list of local mxc URLs
1248
+ remote_mxcs: A list of (remote server, media id) tuples representing
1249
+ remote mxc URLs
1250
+ quarantined_by: The ID of the user who initiated the quarantine request
1251
+ If it is `None` media will be removed from quarantine
1252
+ Returns:
1253
+ The total number of media items quarantined
1254
+ """
1255
+ hashes = set()
1256
+ media_ids = set()
1257
+ remote_media = set()
1258
+
1259
+ # First, determine the hashes of the media we want to delete.
1260
+ # We also want the media_ids for any media that lacks a hash.
1261
+ if local_mxcs:
1262
+ hash_sql_many_clause_sql, hash_sql_many_clause_args = (
1263
+ make_in_list_sql_clause(txn.database_engine, "media_id", local_mxcs)
1264
+ )
1265
+ hash_sql = f"SELECT sha256, media_id FROM local_media_repository WHERE {hash_sql_many_clause_sql}"
1266
+ if quarantined_by is not None:
1267
+ hash_sql += " AND safe_from_quarantine = FALSE"
1268
+
1269
+ txn.execute(hash_sql, hash_sql_many_clause_args)
1270
+ for sha256, media_id in txn:
1271
+ if sha256:
1272
+ hashes.add(sha256)
1273
+ else:
1274
+ media_ids.add(media_id)
1275
+
1276
+ # Do the same for remote media
1277
+ if remote_mxcs:
1278
+ hash_sql_in_list_clause, hash_sql_args = make_tuple_in_list_sql_clause(
1279
+ txn.database_engine,
1280
+ ("media_origin", "media_id"),
1281
+ remote_mxcs,
1282
+ )
1283
+
1284
+ hash_sql = f"SELECT sha256, media_origin, media_id FROM remote_media_cache WHERE {hash_sql_in_list_clause}"
1285
+ txn.execute(hash_sql, hash_sql_args)
1286
+ for sha256, media_origin, media_id in txn:
1287
+ if sha256:
1288
+ hashes.add(sha256)
1289
+ else:
1290
+ remote_media.add((media_origin, media_id))
1291
+
1292
+ count = self._quarantine_local_media_txn(txn, hashes, media_ids, quarantined_by)
1293
+ count += self._quarantine_remote_media_txn(
1294
+ txn, hashes, remote_media, quarantined_by
1295
+ )
1296
+
1297
+ return count
1298
+
1299
+ async def block_room(self, room_id: str, user_id: str) -> None:
1300
+ """Marks the room as blocked.
1301
+
1302
+ Can be called multiple times (though we'll only track the last user to
1303
+ block this room).
1304
+
1305
+ Can be called on a room unknown to this homeserver.
1306
+
1307
+ Args:
1308
+ room_id: Room to block
1309
+ user_id: Who blocked it
1310
+ """
1311
+ await self.db_pool.simple_upsert(
1312
+ table="blocked_rooms",
1313
+ keyvalues={"room_id": room_id},
1314
+ values={},
1315
+ insertion_values={"user_id": user_id},
1316
+ desc="block_room",
1317
+ )
1318
+ await self.db_pool.runInteraction(
1319
+ "block_room_invalidation",
1320
+ self._invalidate_cache_and_stream,
1321
+ self.is_room_blocked,
1322
+ (room_id,),
1323
+ )
1324
+
1325
+ async def unblock_room(self, room_id: str) -> None:
1326
+ """Remove the room from blocking list.
1327
+
1328
+ Args:
1329
+ room_id: Room to unblock
1330
+ """
1331
+ await self.db_pool.simple_delete(
1332
+ table="blocked_rooms",
1333
+ keyvalues={"room_id": room_id},
1334
+ desc="unblock_room",
1335
+ )
1336
+ await self.db_pool.runInteraction(
1337
+ "block_room_invalidation",
1338
+ self._invalidate_cache_and_stream,
1339
+ self.is_room_blocked,
1340
+ (room_id,),
1341
+ )
1342
+
1343
+ async def get_rooms_for_retention_period_in_range(
1344
+ self, min_ms: Optional[int], max_ms: Optional[int], include_null: bool = False
1345
+ ) -> dict[str, RetentionPolicy]:
1346
+ """Retrieves all of the rooms within the given retention range.
1347
+
1348
+ Optionally includes the rooms which don't have a retention policy.
1349
+
1350
+ Args:
1351
+ min_ms: Duration in milliseconds that define the lower limit of
1352
+ the range to handle (exclusive). If None, doesn't set a lower limit.
1353
+ max_ms: Duration in milliseconds that define the upper limit of
1354
+ the range to handle (inclusive). If None, doesn't set an upper limit.
1355
+ include_null: Whether to include rooms which retention policy is NULL
1356
+ in the returned set.
1357
+
1358
+ Returns:
1359
+ The rooms within this range, along with their retention
1360
+ policy. The key is "room_id", and maps to a dict describing the retention
1361
+ policy associated with this room ID. The keys for this nested dict are
1362
+ "min_lifetime" (int|None), and "max_lifetime" (int|None).
1363
+ """
1364
+
1365
+ def get_rooms_for_retention_period_in_range_txn(
1366
+ txn: LoggingTransaction,
1367
+ ) -> dict[str, RetentionPolicy]:
1368
+ range_conditions = []
1369
+ args = []
1370
+
1371
+ if min_ms is not None:
1372
+ range_conditions.append("max_lifetime > ?")
1373
+ args.append(min_ms)
1374
+
1375
+ if max_ms is not None:
1376
+ range_conditions.append("max_lifetime <= ?")
1377
+ args.append(max_ms)
1378
+
1379
+ # Do a first query which will retrieve the rooms that have a retention policy
1380
+ # in their current state.
1381
+ sql = """
1382
+ SELECT room_id, min_lifetime, max_lifetime FROM room_retention
1383
+ INNER JOIN current_state_events USING (event_id, room_id)
1384
+ """
1385
+
1386
+ if len(range_conditions):
1387
+ sql += " WHERE (" + " AND ".join(range_conditions) + ")"
1388
+
1389
+ if include_null:
1390
+ sql += " OR max_lifetime IS NULL"
1391
+
1392
+ txn.execute(sql, args)
1393
+
1394
+ rooms_dict = {
1395
+ room_id: RetentionPolicy(
1396
+ min_lifetime=min_lifetime,
1397
+ max_lifetime=max_lifetime,
1398
+ )
1399
+ for room_id, min_lifetime, max_lifetime in txn
1400
+ }
1401
+
1402
+ if include_null:
1403
+ # If required, do a second query that retrieves all of the rooms we know
1404
+ # of so we can handle rooms with no retention policy.
1405
+ sql = "SELECT DISTINCT room_id FROM current_state_events"
1406
+
1407
+ txn.execute(sql)
1408
+
1409
+ # If a room isn't already in the dict (i.e. it doesn't have a retention
1410
+ # policy in its state), add it with a null policy.
1411
+ for (room_id,) in txn:
1412
+ if room_id not in rooms_dict:
1413
+ rooms_dict[room_id] = RetentionPolicy()
1414
+
1415
+ return rooms_dict
1416
+
1417
+ return await self.db_pool.runInteraction(
1418
+ "get_rooms_for_retention_period_in_range",
1419
+ get_rooms_for_retention_period_in_range_txn,
1420
+ )
1421
+
1422
+ async def get_partial_state_servers_at_join(
1423
+ self, room_id: str
1424
+ ) -> Optional[AbstractSet[str]]:
1425
+ """Gets the set of servers in a partial state room at the time we joined it.
1426
+
1427
+ Returns:
1428
+ The `servers_in_room` list from the `/send_join` response for partial state
1429
+ rooms. May not be accurate or complete, as it comes from a remote
1430
+ homeserver.
1431
+ `None` for full state rooms.
1432
+ """
1433
+ servers_in_room = await self._get_partial_state_servers_at_join(room_id)
1434
+
1435
+ if len(servers_in_room) == 0:
1436
+ return None
1437
+
1438
+ return servers_in_room
1439
+
1440
+ @cached(iterable=True)
1441
+ async def _get_partial_state_servers_at_join(
1442
+ self, room_id: str
1443
+ ) -> AbstractSet[str]:
1444
+ return frozenset(
1445
+ await self.db_pool.simple_select_onecol(
1446
+ "partial_state_rooms_servers",
1447
+ keyvalues={"room_id": room_id},
1448
+ retcol="server_name",
1449
+ desc="get_partial_state_servers_at_join",
1450
+ )
1451
+ )
1452
+
1453
+ async def get_partial_state_room_resync_info(
1454
+ self,
1455
+ ) -> Mapping[str, PartialStateResyncInfo]:
1456
+ """Get all rooms containing events with partial state, and the information
1457
+ needed to restart a "resync" of those rooms.
1458
+
1459
+ Returns:
1460
+ A dictionary of rooms with partial state, with room IDs as keys and
1461
+ lists of servers in rooms as values.
1462
+ """
1463
+ room_servers: dict[str, PartialStateResyncInfo] = {}
1464
+
1465
+ rows = cast(
1466
+ list[tuple[str, str]],
1467
+ await self.db_pool.simple_select_list(
1468
+ table="partial_state_rooms",
1469
+ keyvalues={},
1470
+ retcols=("room_id", "joined_via"),
1471
+ desc="get_server_which_served_partial_join",
1472
+ ),
1473
+ )
1474
+
1475
+ for room_id, joined_via in rows:
1476
+ room_servers[room_id] = PartialStateResyncInfo(joined_via=joined_via)
1477
+
1478
+ rows = cast(
1479
+ list[tuple[str, str]],
1480
+ await self.db_pool.simple_select_list(
1481
+ "partial_state_rooms_servers",
1482
+ keyvalues=None,
1483
+ retcols=("room_id", "server_name"),
1484
+ desc="get_partial_state_rooms",
1485
+ ),
1486
+ )
1487
+
1488
+ for room_id, server_name in rows:
1489
+ entry = room_servers.get(room_id)
1490
+ if entry is None:
1491
+ # There is a foreign key constraint which enforces that every room_id in
1492
+ # partial_state_rooms_servers appears in partial_state_rooms. So we
1493
+ # expect `entry` to be non-null. (This reasoning fails if we've
1494
+ # partial-joined between the two SELECTs, but this is unlikely to happen
1495
+ # in practice.)
1496
+ continue
1497
+ entry.servers_in_room.add(server_name)
1498
+
1499
+ return room_servers
1500
+
1501
+ @cached(max_entries=10000)
1502
+ async def is_partial_state_room(self, room_id: str) -> bool:
1503
+ """Checks if this room has partial state.
1504
+
1505
+ Returns true if this is a "partial-state" room, which means that the state
1506
+ at events in the room, and `current_state_events`, may not yet be
1507
+ complete.
1508
+ """
1509
+
1510
+ entry = await self.db_pool.simple_select_one_onecol(
1511
+ table="partial_state_rooms",
1512
+ keyvalues={"room_id": room_id},
1513
+ retcol="room_id",
1514
+ allow_none=True,
1515
+ desc="is_partial_state_room",
1516
+ )
1517
+
1518
+ return entry is not None
1519
+
1520
+ @cachedList(cached_method_name="is_partial_state_room", list_name="room_ids")
1521
+ async def is_partial_state_room_batched(
1522
+ self, room_ids: StrCollection
1523
+ ) -> Mapping[str, bool]:
1524
+ """Checks if the given rooms have partial state.
1525
+
1526
+ Returns true for "partial-state" rooms, which means that the state
1527
+ at events in the room, and `current_state_events`, may not yet be
1528
+ complete.
1529
+ """
1530
+
1531
+ rows = cast(
1532
+ list[tuple[str]],
1533
+ await self.db_pool.simple_select_many_batch(
1534
+ table="partial_state_rooms",
1535
+ column="room_id",
1536
+ iterable=room_ids,
1537
+ retcols=("room_id",),
1538
+ desc="is_partial_state_room_batched",
1539
+ ),
1540
+ )
1541
+ partial_state_rooms = {row[0] for row in rows}
1542
+ return {room_id: room_id in partial_state_rooms for room_id in room_ids}
1543
+
1544
+ @cached(max_entries=10000, iterable=True)
1545
+ async def get_partial_rooms(self) -> AbstractSet[str]:
1546
+ """Get any "partial-state" rooms which the user is in.
1547
+
1548
+ This is fast as the set of partially stated rooms at any point across
1549
+ the whole server is small, and so such a query is fast. This is also
1550
+ faster than looking up whether a set of room ID's are partially stated
1551
+ via `is_partial_state_room_batched(...)` because of the sheer amount of
1552
+ CPU time looking all the rooms up in the cache.
1553
+ """
1554
+
1555
+ def _get_partial_rooms_for_user_txn(
1556
+ txn: LoggingTransaction,
1557
+ ) -> AbstractSet[str]:
1558
+ sql = """
1559
+ SELECT room_id FROM partial_state_rooms
1560
+ """
1561
+ txn.execute(sql)
1562
+ return {room_id for (room_id,) in txn}
1563
+
1564
+ return await self.db_pool.runInteraction(
1565
+ "get_partial_rooms_for_user", _get_partial_rooms_for_user_txn
1566
+ )
1567
+
1568
+ async def get_join_event_id_and_device_lists_stream_id_for_partial_state(
1569
+ self, room_id: str
1570
+ ) -> tuple[str, int]:
1571
+ """Get the event ID of the initial join that started the partial
1572
+ join, and the device list stream ID at the point we started the partial
1573
+ join.
1574
+
1575
+ This only returns the minimum device list stream ID at the time of
1576
+ joining, not the full device list stream token. The only impact of this
1577
+ is that we may be sending again device list updates that we've already
1578
+ sent to some destinations, which is harmless.
1579
+ """
1580
+
1581
+ return cast(
1582
+ tuple[str, int],
1583
+ await self.db_pool.simple_select_one(
1584
+ table="partial_state_rooms",
1585
+ keyvalues={"room_id": room_id},
1586
+ retcols=("join_event_id", "device_lists_stream_id"),
1587
+ desc="get_join_event_id_for_partial_state",
1588
+ ),
1589
+ )
1590
+
1591
+ def get_un_partial_stated_rooms_token(self, instance_name: str) -> int:
1592
+ return self._un_partial_stated_rooms_stream_id_gen.get_current_token_for_writer(
1593
+ instance_name
1594
+ )
1595
+
1596
+ def get_un_partial_stated_rooms_id_generator(self) -> MultiWriterIdGenerator:
1597
+ return self._un_partial_stated_rooms_stream_id_gen
1598
+
1599
+ async def get_un_partial_stated_rooms_between(
1600
+ self, last_id: int, current_id: int, room_ids: Collection[str]
1601
+ ) -> set[str]:
1602
+ """Get all rooms that got un partial stated between `last_id` exclusive and
1603
+ `current_id` inclusive.
1604
+
1605
+ Returns:
1606
+ The list of room ids.
1607
+ """
1608
+
1609
+ if last_id == current_id:
1610
+ return set()
1611
+
1612
+ def _get_un_partial_stated_rooms_between_txn(
1613
+ txn: LoggingTransaction,
1614
+ ) -> set[str]:
1615
+ sql = """
1616
+ SELECT DISTINCT room_id FROM un_partial_stated_room_stream
1617
+ WHERE ? < stream_id AND stream_id <= ? AND
1618
+ """
1619
+
1620
+ clause, args = make_in_list_sql_clause(
1621
+ self.database_engine, "room_id", room_ids
1622
+ )
1623
+
1624
+ txn.execute(sql + clause, [last_id, current_id] + args)
1625
+
1626
+ return {r[0] for r in txn}
1627
+
1628
+ return await self.db_pool.runInteraction(
1629
+ "get_un_partial_stated_rooms_between",
1630
+ _get_un_partial_stated_rooms_between_txn,
1631
+ )
1632
+
1633
+ async def get_un_partial_stated_rooms_from_stream(
1634
+ self, instance_name: str, last_id: int, current_id: int, limit: int
1635
+ ) -> tuple[list[tuple[int, tuple[str]]], int, bool]:
1636
+ """Get updates for un partial stated rooms replication stream.
1637
+
1638
+ Args:
1639
+ instance_name: The writer we want to fetch updates from. Unused
1640
+ here since there is only ever one writer.
1641
+ last_id: The token to fetch updates from. Exclusive.
1642
+ current_id: The token to fetch updates up to. Inclusive.
1643
+ limit: The requested limit for the number of rows to return. The
1644
+ function may return more or fewer rows.
1645
+
1646
+ Returns:
1647
+ A tuple consisting of: the updates, a token to use to fetch
1648
+ subsequent updates, and whether we returned fewer rows than exists
1649
+ between the requested tokens due to the limit.
1650
+
1651
+ The token returned can be used in a subsequent call to this
1652
+ function to get further updatees.
1653
+
1654
+ The updates are a list of 2-tuples of stream ID and the row data
1655
+ """
1656
+
1657
+ if last_id == current_id:
1658
+ return [], current_id, False
1659
+
1660
+ def get_un_partial_stated_rooms_from_stream_txn(
1661
+ txn: LoggingTransaction,
1662
+ ) -> tuple[list[tuple[int, tuple[str]]], int, bool]:
1663
+ sql = """
1664
+ SELECT stream_id, room_id
1665
+ FROM un_partial_stated_room_stream
1666
+ WHERE ? < stream_id AND stream_id <= ? AND instance_name = ?
1667
+ ORDER BY stream_id ASC
1668
+ LIMIT ?
1669
+ """
1670
+ txn.execute(sql, (last_id, current_id, instance_name, limit))
1671
+ updates = [(row[0], (row[1],)) for row in txn]
1672
+ limited = False
1673
+ upto_token = current_id
1674
+ if len(updates) >= limit:
1675
+ upto_token = updates[-1][0]
1676
+ limited = True
1677
+
1678
+ return updates, upto_token, limited
1679
+
1680
+ return await self.db_pool.runInteraction(
1681
+ "get_un_partial_stated_rooms_from_stream",
1682
+ get_un_partial_stated_rooms_from_stream_txn,
1683
+ )
1684
+
1685
+ async def get_event_report(self, report_id: int) -> Optional[dict[str, Any]]:
1686
+ """Retrieve an event report
1687
+
1688
+ Args:
1689
+ report_id: ID of reported event in database
1690
+ Returns:
1691
+ JSON dict of information from an event report or None if the
1692
+ report does not exist.
1693
+ """
1694
+
1695
+ def _get_event_report_txn(
1696
+ txn: LoggingTransaction, report_id: int
1697
+ ) -> Optional[dict[str, Any]]:
1698
+ sql = """
1699
+ SELECT
1700
+ er.id,
1701
+ er.received_ts,
1702
+ er.room_id,
1703
+ er.event_id,
1704
+ er.user_id,
1705
+ er.content,
1706
+ events.sender,
1707
+ room_stats_state.canonical_alias,
1708
+ room_stats_state.name,
1709
+ event_json.json AS event_json
1710
+ FROM event_reports AS er
1711
+ LEFT JOIN events
1712
+ ON events.event_id = er.event_id
1713
+ JOIN event_json
1714
+ ON event_json.event_id = er.event_id
1715
+ JOIN room_stats_state
1716
+ ON room_stats_state.room_id = er.room_id
1717
+ WHERE er.id = ?
1718
+ """
1719
+
1720
+ txn.execute(sql, [report_id])
1721
+ row = txn.fetchone()
1722
+
1723
+ if not row:
1724
+ return None
1725
+
1726
+ event_report = {
1727
+ "id": row[0],
1728
+ "received_ts": row[1],
1729
+ "room_id": row[2],
1730
+ "event_id": row[3],
1731
+ "user_id": row[4],
1732
+ "score": db_to_json(row[5]).get("score"),
1733
+ "reason": db_to_json(row[5]).get("reason"),
1734
+ "sender": row[6],
1735
+ "canonical_alias": row[7],
1736
+ "name": row[8],
1737
+ "event_json": db_to_json(row[9]),
1738
+ }
1739
+
1740
+ return event_report
1741
+
1742
+ return await self.db_pool.runInteraction(
1743
+ "get_event_report", _get_event_report_txn, report_id
1744
+ )
1745
+
1746
+ async def get_event_reports_paginate(
1747
+ self,
1748
+ start: int,
1749
+ limit: int,
1750
+ direction: Direction = Direction.BACKWARDS,
1751
+ user_id: Optional[str] = None,
1752
+ room_id: Optional[str] = None,
1753
+ event_sender_user_id: Optional[str] = None,
1754
+ ) -> tuple[list[dict[str, Any]], int]:
1755
+ """Retrieve a paginated list of event reports
1756
+
1757
+ Args:
1758
+ start: event offset to begin the query from
1759
+ limit: number of rows to retrieve
1760
+ direction: Whether to fetch the most recent first (backwards) or the
1761
+ oldest first (forwards)
1762
+ user_id: search for user_id. Ignored if user_id is None
1763
+ room_id: search for room_id. Ignored if room_id is None
1764
+ event_sender_user_id: search for the sender of the reported event. Ignored if
1765
+ event_sender_user_id is None
1766
+ Returns:
1767
+ Tuple of:
1768
+ json list of event reports
1769
+ total number of event reports matching the filter criteria
1770
+ """
1771
+
1772
+ def _get_event_reports_paginate_txn(
1773
+ txn: LoggingTransaction,
1774
+ ) -> tuple[list[dict[str, Any]], int]:
1775
+ filters = []
1776
+ args: list[object] = []
1777
+
1778
+ if user_id:
1779
+ filters.append("er.user_id LIKE ?")
1780
+ args.extend(["%" + user_id + "%"])
1781
+ if room_id:
1782
+ filters.append("er.room_id LIKE ?")
1783
+ args.extend(["%" + room_id + "%"])
1784
+
1785
+ if event_sender_user_id:
1786
+ filters.append("events.sender = ?")
1787
+ args.extend([event_sender_user_id])
1788
+
1789
+ if direction == Direction.BACKWARDS:
1790
+ order = "DESC"
1791
+ else:
1792
+ order = "ASC"
1793
+
1794
+ where_clause = "WHERE " + " AND ".join(filters) if len(filters) > 0 else ""
1795
+
1796
+ # We join on room_stats_state despite not using any columns from it
1797
+ # because the join can influence the number of rows returned;
1798
+ # e.g. a room that doesn't have state, maybe because it was deleted.
1799
+ # The query returning the total count should be consistent with
1800
+ # the query returning the results.
1801
+ sql = """
1802
+ SELECT COUNT(*) as total_event_reports
1803
+ FROM event_reports AS er
1804
+ LEFT JOIN events USING(event_id)
1805
+ JOIN room_stats_state ON room_stats_state.room_id = er.room_id
1806
+ {}
1807
+ """.format(where_clause)
1808
+ txn.execute(sql, args)
1809
+ count = cast(tuple[int], txn.fetchone())[0]
1810
+
1811
+ sql = """
1812
+ SELECT
1813
+ er.id,
1814
+ er.received_ts,
1815
+ er.room_id,
1816
+ er.event_id,
1817
+ er.user_id,
1818
+ er.content,
1819
+ events.sender,
1820
+ room_stats_state.canonical_alias,
1821
+ room_stats_state.name
1822
+ FROM event_reports AS er
1823
+ LEFT JOIN events USING(event_id)
1824
+ JOIN room_stats_state
1825
+ ON room_stats_state.room_id = er.room_id
1826
+ {where_clause}
1827
+ ORDER BY er.received_ts {order}
1828
+ LIMIT ?
1829
+ OFFSET ?
1830
+ """.format(
1831
+ where_clause=where_clause,
1832
+ order=order,
1833
+ )
1834
+
1835
+ args += [limit, start]
1836
+ txn.execute(sql, args)
1837
+
1838
+ event_reports = []
1839
+ for row in txn:
1840
+ try:
1841
+ s = db_to_json(row[5]).get("score")
1842
+ r = db_to_json(row[5]).get("reason")
1843
+ except Exception:
1844
+ logger.error("Unable to parse json from event_reports: %s", row[0])
1845
+ continue
1846
+ event_reports.append(
1847
+ {
1848
+ "id": row[0],
1849
+ "received_ts": row[1],
1850
+ "room_id": row[2],
1851
+ "event_id": row[3],
1852
+ "user_id": row[4],
1853
+ "score": s,
1854
+ "reason": r,
1855
+ "sender": row[6],
1856
+ "canonical_alias": row[7],
1857
+ "name": row[8],
1858
+ }
1859
+ )
1860
+
1861
+ return event_reports, count
1862
+
1863
+ return await self.db_pool.runInteraction(
1864
+ "get_event_reports_paginate", _get_event_reports_paginate_txn
1865
+ )
1866
+
1867
+ async def delete_event_report(self, report_id: int) -> bool:
1868
+ """Remove an event report from database.
1869
+
1870
+ Args:
1871
+ report_id: Report to delete
1872
+
1873
+ Returns:
1874
+ Whether the report was successfully deleted or not.
1875
+ """
1876
+ try:
1877
+ await self.db_pool.simple_delete_one(
1878
+ table="event_reports",
1879
+ keyvalues={"id": report_id},
1880
+ desc="delete_event_report",
1881
+ )
1882
+ except StoreError:
1883
+ # Deletion failed because report does not exist
1884
+ return False
1885
+
1886
+ return True
1887
+
1888
+ async def set_room_is_public(self, room_id: str, is_public: bool) -> None:
1889
+ await self.db_pool.simple_update_one(
1890
+ table="rooms",
1891
+ keyvalues={"room_id": room_id},
1892
+ updatevalues={"is_public": is_public},
1893
+ desc="set_room_is_public",
1894
+ )
1895
+
1896
+ async def set_room_is_public_appservice(
1897
+ self, room_id: str, appservice_id: str, network_id: str, is_public: bool
1898
+ ) -> None:
1899
+ """Edit the appservice/network specific public room list.
1900
+
1901
+ Each appservice can have a number of published room lists associated
1902
+ with them, keyed off of an appservice defined `network_id`, which
1903
+ basically represents a single instance of a bridge to a third party
1904
+ network.
1905
+
1906
+ Args:
1907
+ room_id
1908
+ appservice_id
1909
+ network_id
1910
+ is_public: Whether to publish or unpublish the room from the list.
1911
+ """
1912
+
1913
+ if is_public:
1914
+ await self.db_pool.simple_upsert(
1915
+ table="appservice_room_list",
1916
+ keyvalues={
1917
+ "appservice_id": appservice_id,
1918
+ "network_id": network_id,
1919
+ "room_id": room_id,
1920
+ },
1921
+ values={},
1922
+ insertion_values={
1923
+ "appservice_id": appservice_id,
1924
+ "network_id": network_id,
1925
+ "room_id": room_id,
1926
+ },
1927
+ desc="set_room_is_public_appservice_true",
1928
+ )
1929
+ else:
1930
+ await self.db_pool.simple_delete(
1931
+ table="appservice_room_list",
1932
+ keyvalues={
1933
+ "appservice_id": appservice_id,
1934
+ "network_id": network_id,
1935
+ "room_id": room_id,
1936
+ },
1937
+ desc="set_room_is_public_appservice_false",
1938
+ )
1939
+
1940
+ async def has_auth_chain_index(self, room_id: str) -> bool:
1941
+ """Check if the room has (or can have) a chain cover index.
1942
+
1943
+ Defaults to True if we don't have an entry in `rooms` table nor any
1944
+ events for the room.
1945
+ """
1946
+
1947
+ has_auth_chain_index = await self.db_pool.simple_select_one_onecol(
1948
+ table="rooms",
1949
+ keyvalues={"room_id": room_id},
1950
+ retcol="has_auth_chain_index",
1951
+ desc="has_auth_chain_index",
1952
+ allow_none=True,
1953
+ )
1954
+
1955
+ if has_auth_chain_index:
1956
+ return True
1957
+
1958
+ # It's possible that we already have events for the room in our DB
1959
+ # without a corresponding room entry. If we do then we don't want to
1960
+ # mark the room as having an auth chain cover index.
1961
+ max_ordering = await self.db_pool.simple_select_one_onecol(
1962
+ table="events",
1963
+ keyvalues={"room_id": room_id},
1964
+ retcol="MAX(stream_ordering)",
1965
+ allow_none=True,
1966
+ desc="has_auth_chain_index_fallback",
1967
+ )
1968
+
1969
+ return max_ordering is None
1970
+
1971
+ async def maybe_store_room_on_outlier_membership(
1972
+ self, room_id: str, room_version: RoomVersion
1973
+ ) -> None:
1974
+ """
1975
+ When we receive an invite or any other event over federation that may relate to a room
1976
+ we are not in, store the version of the room if we don't already know the room version.
1977
+ """
1978
+ # It's possible that we already have events for the room in our DB
1979
+ # without a corresponding room entry. If we do then we don't want to
1980
+ # mark the room as having an auth chain cover index.
1981
+ has_auth_chain_index = await self.has_auth_chain_index(room_id)
1982
+
1983
+ await self.db_pool.simple_upsert(
1984
+ desc="maybe_store_room_on_outlier_membership",
1985
+ table="rooms",
1986
+ keyvalues={"room_id": room_id},
1987
+ values={},
1988
+ insertion_values={
1989
+ "room_version": room_version.identifier,
1990
+ "is_public": False,
1991
+ # We don't worry about setting the `creator` here because
1992
+ # we don't process any messages in a room while a user is
1993
+ # invited (only after the join).
1994
+ "creator": "",
1995
+ "has_auth_chain_index": has_auth_chain_index,
1996
+ },
1997
+ )
1998
+
1999
+
2000
+ class _BackgroundUpdates:
2001
+ REMOVE_TOMESTONED_ROOMS_BG_UPDATE = "remove_tombstoned_rooms_from_directory"
2002
+ ADD_ROOMS_ROOM_VERSION_COLUMN = "add_rooms_room_version_column"
2003
+ POPULATE_ROOM_DEPTH_MIN_DEPTH2 = "populate_room_depth_min_depth2"
2004
+ REPLACE_ROOM_DEPTH_MIN_DEPTH = "replace_room_depth_min_depth"
2005
+ POPULATE_ROOMS_CREATOR_COLUMN = "populate_rooms_creator_column"
2006
+ ADD_ROOM_TYPE_COLUMN = "add_room_type_column"
2007
+
2008
+
2009
+ _REPLACE_ROOM_DEPTH_SQL_COMMANDS = (
2010
+ "DROP TRIGGER populate_min_depth2_trigger ON room_depth",
2011
+ "DROP FUNCTION populate_min_depth2()",
2012
+ "ALTER TABLE room_depth DROP COLUMN min_depth",
2013
+ "ALTER TABLE room_depth RENAME COLUMN min_depth2 TO min_depth",
2014
+ )
2015
+
2016
+
2017
+ class RoomBackgroundUpdateStore(RoomWorkerStore):
2018
+ def __init__(
2019
+ self,
2020
+ database: DatabasePool,
2021
+ db_conn: LoggingDatabaseConnection,
2022
+ hs: "HomeServer",
2023
+ ):
2024
+ super().__init__(database, db_conn, hs)
2025
+
2026
+ self.db_pool.updates.register_background_update_handler(
2027
+ "insert_room_retention",
2028
+ self._background_insert_retention,
2029
+ )
2030
+
2031
+ self.db_pool.updates.register_background_update_handler(
2032
+ _BackgroundUpdates.REMOVE_TOMESTONED_ROOMS_BG_UPDATE,
2033
+ self._remove_tombstoned_rooms_from_directory,
2034
+ )
2035
+
2036
+ self.db_pool.updates.register_background_update_handler(
2037
+ _BackgroundUpdates.ADD_ROOMS_ROOM_VERSION_COLUMN,
2038
+ self._background_add_rooms_room_version_column,
2039
+ )
2040
+
2041
+ self.db_pool.updates.register_background_update_handler(
2042
+ _BackgroundUpdates.ADD_ROOM_TYPE_COLUMN,
2043
+ self._background_add_room_type_column,
2044
+ )
2045
+
2046
+ # BG updates to change the type of room_depth.min_depth
2047
+ self.db_pool.updates.register_background_update_handler(
2048
+ _BackgroundUpdates.POPULATE_ROOM_DEPTH_MIN_DEPTH2,
2049
+ self._background_populate_room_depth_min_depth2,
2050
+ )
2051
+ self.db_pool.updates.register_background_update_handler(
2052
+ _BackgroundUpdates.REPLACE_ROOM_DEPTH_MIN_DEPTH,
2053
+ self._background_replace_room_depth_min_depth,
2054
+ )
2055
+
2056
+ self.db_pool.updates.register_background_update_handler(
2057
+ _BackgroundUpdates.POPULATE_ROOMS_CREATOR_COLUMN,
2058
+ self._background_populate_rooms_creator_column,
2059
+ )
2060
+
2061
+ async def _background_insert_retention(
2062
+ self, progress: JsonDict, batch_size: int
2063
+ ) -> int:
2064
+ """Retrieves a list of all rooms within a range and inserts an entry for each of
2065
+ them into the room_retention table.
2066
+ NULLs the property's columns if missing from the retention event in the room's
2067
+ state (or NULLs all of them if there's no retention event in the room's state),
2068
+ so that we fall back to the server's retention policy.
2069
+ """
2070
+
2071
+ last_room = progress.get("room_id", "")
2072
+
2073
+ def _background_insert_retention_txn(txn: LoggingTransaction) -> bool:
2074
+ txn.execute(
2075
+ """
2076
+ SELECT state.room_id, state.event_id, events.json
2077
+ FROM current_state_events as state
2078
+ LEFT JOIN event_json AS events ON (state.event_id = events.event_id)
2079
+ WHERE state.room_id > ? AND state.type = '%s'
2080
+ ORDER BY state.room_id ASC
2081
+ LIMIT ?;
2082
+ """
2083
+ % EventTypes.Retention,
2084
+ (last_room, batch_size),
2085
+ )
2086
+
2087
+ rows = txn.fetchall()
2088
+
2089
+ if not rows:
2090
+ return True
2091
+
2092
+ for room_id, event_id, json in rows:
2093
+ if not json:
2094
+ retention_policy = {}
2095
+ else:
2096
+ ev = db_to_json(json)
2097
+ retention_policy = ev["content"]
2098
+
2099
+ self.db_pool.simple_insert_txn(
2100
+ txn=txn,
2101
+ table="room_retention",
2102
+ values={
2103
+ "room_id": room_id,
2104
+ "event_id": event_id,
2105
+ "min_lifetime": retention_policy.get("min_lifetime"),
2106
+ "max_lifetime": retention_policy.get("max_lifetime"),
2107
+ },
2108
+ )
2109
+
2110
+ logger.info("Inserted %d rows into room_retention", len(rows))
2111
+
2112
+ self.db_pool.updates._background_update_progress_txn(
2113
+ txn, "insert_room_retention", {"room_id": rows[-1][0]}
2114
+ )
2115
+
2116
+ if batch_size > len(rows):
2117
+ return True
2118
+ else:
2119
+ return False
2120
+
2121
+ end = await self.db_pool.runInteraction(
2122
+ "insert_room_retention",
2123
+ _background_insert_retention_txn,
2124
+ )
2125
+
2126
+ if end:
2127
+ await self.db_pool.updates._end_background_update("insert_room_retention")
2128
+
2129
+ return batch_size
2130
+
2131
+ async def _background_add_rooms_room_version_column(
2132
+ self, progress: JsonDict, batch_size: int
2133
+ ) -> int:
2134
+ """Background update to go and add room version information to `rooms`
2135
+ table from `current_state_events` table.
2136
+ """
2137
+
2138
+ last_room_id = progress.get("room_id", "")
2139
+
2140
+ def _background_add_rooms_room_version_column_txn(
2141
+ txn: LoggingTransaction,
2142
+ ) -> bool:
2143
+ sql = """
2144
+ SELECT room_id, json FROM current_state_events
2145
+ INNER JOIN event_json USING (room_id, event_id)
2146
+ WHERE room_id > ? AND type = 'm.room.create' AND state_key = ''
2147
+ ORDER BY room_id
2148
+ LIMIT ?
2149
+ """
2150
+
2151
+ txn.execute(sql, (last_room_id, batch_size))
2152
+
2153
+ updates = []
2154
+ for room_id, event_json in txn:
2155
+ event_dict = db_to_json(event_json)
2156
+ room_version_id = event_dict.get("content", {}).get(
2157
+ "room_version", RoomVersions.V1.identifier
2158
+ )
2159
+
2160
+ creator = event_dict.get("content").get("creator")
2161
+
2162
+ updates.append((room_id, creator, room_version_id))
2163
+
2164
+ if not updates:
2165
+ return True
2166
+
2167
+ new_last_room_id = ""
2168
+ for room_id, creator, room_version_id in updates:
2169
+ # We upsert here just in case we don't already have a row,
2170
+ # mainly for paranoia as much badness would happen if we don't
2171
+ # insert the row and then try and get the room version for the
2172
+ # room.
2173
+ self.db_pool.simple_upsert_txn(
2174
+ txn,
2175
+ table="rooms",
2176
+ keyvalues={"room_id": room_id},
2177
+ values={"room_version": room_version_id},
2178
+ insertion_values={"is_public": False, "creator": creator},
2179
+ )
2180
+ new_last_room_id = room_id
2181
+
2182
+ self.db_pool.updates._background_update_progress_txn(
2183
+ txn,
2184
+ _BackgroundUpdates.ADD_ROOMS_ROOM_VERSION_COLUMN,
2185
+ {"room_id": new_last_room_id},
2186
+ )
2187
+
2188
+ return False
2189
+
2190
+ end = await self.db_pool.runInteraction(
2191
+ "_background_add_rooms_room_version_column",
2192
+ _background_add_rooms_room_version_column_txn,
2193
+ )
2194
+
2195
+ if end:
2196
+ await self.db_pool.updates._end_background_update(
2197
+ _BackgroundUpdates.ADD_ROOMS_ROOM_VERSION_COLUMN
2198
+ )
2199
+
2200
+ return batch_size
2201
+
2202
+ async def _remove_tombstoned_rooms_from_directory(
2203
+ self, progress: JsonDict, batch_size: int
2204
+ ) -> int:
2205
+ """Removes any rooms with tombstone events from the room directory
2206
+
2207
+ Nowadays this is handled by the room upgrade handler, but we may have some
2208
+ that got left behind
2209
+ """
2210
+
2211
+ last_room = progress.get("room_id", "")
2212
+
2213
+ def _get_rooms(txn: LoggingTransaction) -> list[str]:
2214
+ txn.execute(
2215
+ """
2216
+ SELECT room_id
2217
+ FROM rooms r
2218
+ INNER JOIN current_state_events cse USING (room_id)
2219
+ WHERE room_id > ? AND r.is_public
2220
+ AND cse.type = '%s' AND cse.state_key = ''
2221
+ ORDER BY room_id ASC
2222
+ LIMIT ?;
2223
+ """
2224
+ % EventTypes.Tombstone,
2225
+ (last_room, batch_size),
2226
+ )
2227
+
2228
+ return [row[0] for row in txn]
2229
+
2230
+ rooms = await self.db_pool.runInteraction(
2231
+ "get_tombstoned_directory_rooms", _get_rooms
2232
+ )
2233
+
2234
+ if not rooms:
2235
+ await self.db_pool.updates._end_background_update(
2236
+ _BackgroundUpdates.REMOVE_TOMESTONED_ROOMS_BG_UPDATE
2237
+ )
2238
+ return 0
2239
+
2240
+ for room_id in rooms:
2241
+ logger.info("Removing tombstoned room %s from the directory", room_id)
2242
+ await self.set_room_is_public(room_id, False)
2243
+
2244
+ await self.db_pool.updates._background_update_progress(
2245
+ _BackgroundUpdates.REMOVE_TOMESTONED_ROOMS_BG_UPDATE, {"room_id": rooms[-1]}
2246
+ )
2247
+
2248
+ return len(rooms)
2249
+
2250
+ async def _background_populate_room_depth_min_depth2(
2251
+ self, progress: JsonDict, batch_size: int
2252
+ ) -> int:
2253
+ """Populate room_depth.min_depth2
2254
+
2255
+ This is to deal with the fact that min_depth was initially created as a
2256
+ 32-bit integer field.
2257
+ """
2258
+
2259
+ def process(txn: LoggingTransaction) -> int:
2260
+ last_room = progress.get("last_room", "")
2261
+ txn.execute(
2262
+ """
2263
+ UPDATE room_depth SET min_depth2=min_depth
2264
+ WHERE room_id IN (
2265
+ SELECT room_id FROM room_depth WHERE room_id > ?
2266
+ ORDER BY room_id LIMIT ?
2267
+ )
2268
+ RETURNING room_id;
2269
+ """,
2270
+ (last_room, batch_size),
2271
+ )
2272
+ row_count = txn.rowcount
2273
+ if row_count == 0:
2274
+ return 0
2275
+ last_room = max(row[0] for row in txn)
2276
+ logger.info("populated room_depth up to %s", last_room)
2277
+
2278
+ self.db_pool.updates._background_update_progress_txn(
2279
+ txn,
2280
+ _BackgroundUpdates.POPULATE_ROOM_DEPTH_MIN_DEPTH2,
2281
+ {"last_room": last_room},
2282
+ )
2283
+ return row_count
2284
+
2285
+ result = await self.db_pool.runInteraction(
2286
+ "_background_populate_min_depth2", process
2287
+ )
2288
+
2289
+ if result != 0:
2290
+ return result
2291
+
2292
+ await self.db_pool.updates._end_background_update(
2293
+ _BackgroundUpdates.POPULATE_ROOM_DEPTH_MIN_DEPTH2
2294
+ )
2295
+ return 0
2296
+
2297
+ async def _background_replace_room_depth_min_depth(
2298
+ self, progress: JsonDict, batch_size: int
2299
+ ) -> int:
2300
+ """Drop the old 'min_depth' column and rename 'min_depth2' into its place."""
2301
+
2302
+ def process(txn: Cursor) -> None:
2303
+ for sql in _REPLACE_ROOM_DEPTH_SQL_COMMANDS:
2304
+ logger.info("completing room_depth migration: %s", sql)
2305
+ txn.execute(sql)
2306
+
2307
+ await self.db_pool.runInteraction("_background_replace_room_depth", process)
2308
+
2309
+ await self.db_pool.updates._end_background_update(
2310
+ _BackgroundUpdates.REPLACE_ROOM_DEPTH_MIN_DEPTH,
2311
+ )
2312
+
2313
+ return 0
2314
+
2315
+ async def _background_populate_rooms_creator_column(
2316
+ self, progress: JsonDict, batch_size: int
2317
+ ) -> int:
2318
+ """Background update to go and add creator information to `rooms`
2319
+ table from `current_state_events` table.
2320
+ """
2321
+
2322
+ last_room_id = progress.get("room_id", "")
2323
+
2324
+ def _background_populate_rooms_creator_column_txn(
2325
+ txn: LoggingTransaction,
2326
+ ) -> bool:
2327
+ sql = """
2328
+ SELECT room_id, json FROM event_json
2329
+ INNER JOIN rooms AS room USING (room_id)
2330
+ INNER JOIN current_state_events AS state_event USING (room_id, event_id)
2331
+ WHERE room_id > ? AND (room.creator IS NULL OR room.creator = '') AND state_event.type = 'm.room.create' AND state_event.state_key = ''
2332
+ ORDER BY room_id
2333
+ LIMIT ?
2334
+ """
2335
+
2336
+ txn.execute(sql, (last_room_id, batch_size))
2337
+ room_id_to_create_event_results = txn.fetchall()
2338
+
2339
+ new_last_room_id = ""
2340
+ for room_id, event_json in room_id_to_create_event_results:
2341
+ event_dict = db_to_json(event_json)
2342
+
2343
+ # The creator property might not exist in newer room versions, but
2344
+ # for those versions the creator column should be properly populate
2345
+ # during room creation.
2346
+ creator = event_dict.get("content").get(EventContentFields.ROOM_CREATOR)
2347
+
2348
+ self.db_pool.simple_update_txn(
2349
+ txn,
2350
+ table="rooms",
2351
+ keyvalues={"room_id": room_id},
2352
+ updatevalues={"creator": creator},
2353
+ )
2354
+ new_last_room_id = room_id
2355
+
2356
+ if new_last_room_id == "":
2357
+ return True
2358
+
2359
+ self.db_pool.updates._background_update_progress_txn(
2360
+ txn,
2361
+ _BackgroundUpdates.POPULATE_ROOMS_CREATOR_COLUMN,
2362
+ {"room_id": new_last_room_id},
2363
+ )
2364
+
2365
+ return False
2366
+
2367
+ end = await self.db_pool.runInteraction(
2368
+ "_background_populate_rooms_creator_column",
2369
+ _background_populate_rooms_creator_column_txn,
2370
+ )
2371
+
2372
+ if end:
2373
+ await self.db_pool.updates._end_background_update(
2374
+ _BackgroundUpdates.POPULATE_ROOMS_CREATOR_COLUMN
2375
+ )
2376
+
2377
+ return batch_size
2378
+
2379
+ async def _background_add_room_type_column(
2380
+ self, progress: JsonDict, batch_size: int
2381
+ ) -> int:
2382
+ """Background update to go and add room_type information to `room_stats_state`
2383
+ table from `event_json` table.
2384
+ """
2385
+
2386
+ last_room_id = progress.get("room_id", "")
2387
+
2388
+ def _background_add_room_type_column_txn(
2389
+ txn: LoggingTransaction,
2390
+ ) -> bool:
2391
+ sql = """
2392
+ SELECT state.room_id, json FROM event_json
2393
+ INNER JOIN current_state_events AS state USING (event_id)
2394
+ WHERE state.room_id > ? AND type = 'm.room.create'
2395
+ ORDER BY state.room_id
2396
+ LIMIT ?
2397
+ """
2398
+
2399
+ txn.execute(sql, (last_room_id, batch_size))
2400
+ room_id_to_create_event_results = txn.fetchall()
2401
+
2402
+ new_last_room_id = None
2403
+ for room_id, event_json in room_id_to_create_event_results:
2404
+ event_dict = db_to_json(event_json)
2405
+
2406
+ room_type = event_dict.get("content", {}).get(
2407
+ EventContentFields.ROOM_TYPE, None
2408
+ )
2409
+ if isinstance(room_type, str):
2410
+ self.db_pool.simple_update_txn(
2411
+ txn,
2412
+ table="room_stats_state",
2413
+ keyvalues={"room_id": room_id},
2414
+ updatevalues={"room_type": room_type},
2415
+ )
2416
+
2417
+ new_last_room_id = room_id
2418
+
2419
+ if new_last_room_id is None:
2420
+ return True
2421
+
2422
+ self.db_pool.updates._background_update_progress_txn(
2423
+ txn,
2424
+ _BackgroundUpdates.ADD_ROOM_TYPE_COLUMN,
2425
+ {"room_id": new_last_room_id},
2426
+ )
2427
+
2428
+ return False
2429
+
2430
+ end = await self.db_pool.runInteraction(
2431
+ "_background_add_room_type_column",
2432
+ _background_add_room_type_column_txn,
2433
+ )
2434
+
2435
+ if end:
2436
+ await self.db_pool.updates._end_background_update(
2437
+ _BackgroundUpdates.ADD_ROOM_TYPE_COLUMN
2438
+ )
2439
+
2440
+ return batch_size
2441
+
2442
+
2443
+ class RoomStore(RoomBackgroundUpdateStore, RoomWorkerStore):
2444
+ def __init__(
2445
+ self,
2446
+ database: DatabasePool,
2447
+ db_conn: LoggingDatabaseConnection,
2448
+ hs: "HomeServer",
2449
+ ):
2450
+ super().__init__(database, db_conn, hs)
2451
+
2452
+ self._event_reports_id_gen = IdGenerator(db_conn, "event_reports", "id")
2453
+ self._room_reports_id_gen = IdGenerator(db_conn, "room_reports", "id")
2454
+ self._user_reports_id_gen = IdGenerator(db_conn, "user_reports", "id")
2455
+
2456
+ self._instance_name = hs.get_instance_name()
2457
+
2458
+ async def upsert_room_on_join(
2459
+ self, room_id: str, room_version: RoomVersion, state_events: list[EventBase]
2460
+ ) -> None:
2461
+ """Ensure that the room is stored in the table
2462
+
2463
+ Called when we join a room over federation, and overwrites any room version
2464
+ currently in the table.
2465
+ """
2466
+ # It's possible that we already have events for the room in our DB
2467
+ # without a corresponding room entry. If we do then we don't want to
2468
+ # mark the room as having an auth chain cover index.
2469
+ has_auth_chain_index = await self.has_auth_chain_index(room_id)
2470
+
2471
+ create_event = None
2472
+ for e in state_events:
2473
+ if (e.type, e.state_key) == (EventTypes.Create, ""):
2474
+ create_event = e
2475
+ break
2476
+
2477
+ if create_event is None:
2478
+ # If the state doesn't have a create event then the room is
2479
+ # invalid, and it would fail auth checks anyway.
2480
+ raise StoreError(400, "No create event in state")
2481
+
2482
+ # Before MSC2175, the room creator was a separate field.
2483
+ if not room_version.implicit_room_creator:
2484
+ room_creator = create_event.content.get(EventContentFields.ROOM_CREATOR)
2485
+
2486
+ if not isinstance(room_creator, str):
2487
+ # If the create event does not have a creator then the room is
2488
+ # invalid, and it would fail auth checks anyway.
2489
+ raise StoreError(400, "No creator defined on the create event")
2490
+ else:
2491
+ room_creator = create_event.sender
2492
+
2493
+ await self.db_pool.simple_upsert(
2494
+ desc="upsert_room_on_join",
2495
+ table="rooms",
2496
+ keyvalues={"room_id": room_id},
2497
+ values={"room_version": room_version.identifier},
2498
+ insertion_values={
2499
+ "is_public": False,
2500
+ "creator": room_creator,
2501
+ "has_auth_chain_index": has_auth_chain_index,
2502
+ },
2503
+ )
2504
+
2505
+ async def store_partial_state_room(
2506
+ self,
2507
+ room_id: str,
2508
+ servers: AbstractSet[str],
2509
+ device_lists_stream_id: int,
2510
+ joined_via: str,
2511
+ ) -> None:
2512
+ """Mark the given room as containing events with partial state.
2513
+
2514
+ We also store additional data that describes _when_ we first partial-joined this
2515
+ room, which helps us to keep other homeservers in sync when we finally fully
2516
+ join this room.
2517
+
2518
+ We do not include a `join_event_id` here---we need to wait for the join event
2519
+ to be persisted first.
2520
+
2521
+ Args:
2522
+ room_id: the ID of the room
2523
+ servers: other servers known to be in the room. must include `joined_via`.
2524
+ device_lists_stream_id: the device_lists stream ID at the time when we first
2525
+ joined the room.
2526
+ joined_via: the server name we requested a partial join from.
2527
+ """
2528
+ assert joined_via in servers
2529
+
2530
+ await self.db_pool.runInteraction(
2531
+ "store_partial_state_room",
2532
+ self._store_partial_state_room_txn,
2533
+ room_id,
2534
+ servers,
2535
+ device_lists_stream_id,
2536
+ joined_via,
2537
+ )
2538
+
2539
+ def _store_partial_state_room_txn(
2540
+ self,
2541
+ txn: LoggingTransaction,
2542
+ room_id: str,
2543
+ servers: AbstractSet[str],
2544
+ device_lists_stream_id: int,
2545
+ joined_via: str,
2546
+ ) -> None:
2547
+ DatabasePool.simple_insert_txn(
2548
+ txn,
2549
+ table="partial_state_rooms",
2550
+ values={
2551
+ "room_id": room_id,
2552
+ "device_lists_stream_id": device_lists_stream_id,
2553
+ # To be updated later once the join event is persisted.
2554
+ "join_event_id": None,
2555
+ "joined_via": joined_via,
2556
+ },
2557
+ )
2558
+ DatabasePool.simple_insert_many_txn(
2559
+ txn,
2560
+ table="partial_state_rooms_servers",
2561
+ keys=("room_id", "server_name"),
2562
+ values=[(room_id, s) for s in servers],
2563
+ )
2564
+ self._invalidate_cache_and_stream(txn, self.is_partial_state_room, (room_id,))
2565
+ self._invalidate_cache_and_stream(
2566
+ txn, self._get_partial_state_servers_at_join, (room_id,)
2567
+ )
2568
+ self._invalidate_all_cache_and_stream(txn, self.get_partial_rooms)
2569
+
2570
+ async def write_partial_state_rooms_join_event_id(
2571
+ self,
2572
+ room_id: str,
2573
+ join_event_id: str,
2574
+ ) -> None:
2575
+ """Record the join event which resulted from a partial join.
2576
+
2577
+ We do this separately to `store_partial_state_room` because we need to wait for
2578
+ the join event to be persisted. Otherwise we violate a foreign key constraint.
2579
+ """
2580
+ await self.db_pool.runInteraction(
2581
+ "write_partial_state_rooms_join_event_id",
2582
+ self._write_partial_state_rooms_join_event_id,
2583
+ room_id,
2584
+ join_event_id,
2585
+ )
2586
+
2587
+ def _write_partial_state_rooms_join_event_id(
2588
+ self,
2589
+ txn: LoggingTransaction,
2590
+ room_id: str,
2591
+ join_event_id: str,
2592
+ ) -> None:
2593
+ DatabasePool.simple_update_txn(
2594
+ txn,
2595
+ table="partial_state_rooms",
2596
+ keyvalues={"room_id": room_id},
2597
+ updatevalues={"join_event_id": join_event_id},
2598
+ )
2599
+
2600
+ async def add_event_report(
2601
+ self,
2602
+ room_id: str,
2603
+ event_id: str,
2604
+ user_id: str,
2605
+ reason: Optional[str],
2606
+ content: JsonDict,
2607
+ received_ts: int,
2608
+ ) -> int:
2609
+ """Add an event report
2610
+
2611
+ Args:
2612
+ room_id: Room that contains the reported event.
2613
+ event_id: The reported event.
2614
+ user_id: User who reports the event.
2615
+ reason: Description that the user specifies.
2616
+ content: Report request body (score and reason).
2617
+ received_ts: Time when the user submitted the report (milliseconds).
2618
+ Returns:
2619
+ Id of the event report.
2620
+ """
2621
+ next_id = self._event_reports_id_gen.get_next()
2622
+ await self.db_pool.simple_insert(
2623
+ table="event_reports",
2624
+ values={
2625
+ "id": next_id,
2626
+ "received_ts": received_ts,
2627
+ "room_id": room_id,
2628
+ "event_id": event_id,
2629
+ "user_id": user_id,
2630
+ "reason": reason,
2631
+ "content": json_encoder.encode(content),
2632
+ },
2633
+ desc="add_event_report",
2634
+ )
2635
+ return next_id
2636
+
2637
+ async def add_room_report(
2638
+ self,
2639
+ room_id: str,
2640
+ user_id: str,
2641
+ reason: str,
2642
+ received_ts: int,
2643
+ ) -> int:
2644
+ """Add a room report
2645
+
2646
+ Args:
2647
+ room_id: The room ID being reported.
2648
+ user_id: User who reports the room.
2649
+ reason: Description that the user specifies.
2650
+ received_ts: Time when the user submitted the report (milliseconds).
2651
+ Returns:
2652
+ Id of the room report.
2653
+ """
2654
+ next_id = self._room_reports_id_gen.get_next()
2655
+ await self.db_pool.simple_insert(
2656
+ table="room_reports",
2657
+ values={
2658
+ "id": next_id,
2659
+ "received_ts": received_ts,
2660
+ "room_id": room_id,
2661
+ "user_id": user_id,
2662
+ "reason": reason,
2663
+ },
2664
+ desc="add_room_report",
2665
+ )
2666
+ return next_id
2667
+
2668
+ async def add_user_report(
2669
+ self,
2670
+ target_user_id: str,
2671
+ user_id: str,
2672
+ reason: str,
2673
+ received_ts: int,
2674
+ ) -> int:
2675
+ """Add a user report
2676
+
2677
+ Args:
2678
+ target_user_id: The user ID being reported.
2679
+ user_id: User who reported the user.
2680
+ reason: Description that the user specifies.
2681
+ received_ts: Time when the user submitted the report (milliseconds).
2682
+ Returns:
2683
+ ID of the room report.
2684
+ """
2685
+ next_id = self._user_reports_id_gen.get_next()
2686
+ await self.db_pool.simple_insert(
2687
+ table="user_reports",
2688
+ values={
2689
+ "id": next_id,
2690
+ "received_ts": received_ts,
2691
+ "target_user_id": target_user_id,
2692
+ "user_id": user_id,
2693
+ "reason": reason,
2694
+ },
2695
+ desc="add_user_report",
2696
+ )
2697
+ return next_id
2698
+
2699
+ async def clear_partial_state_room(self, room_id: str) -> Optional[int]:
2700
+ """Clears the partial state flag for a room.
2701
+
2702
+ Args:
2703
+ room_id: The room whose partial state flag is to be cleared.
2704
+
2705
+ Returns:
2706
+ The corresponding stream id for the un-partial-stated rooms stream.
2707
+
2708
+ `None` if the partial state flag could not be cleared because the room
2709
+ still contains events with partial state.
2710
+ """
2711
+ try:
2712
+ async with (
2713
+ self._un_partial_stated_rooms_stream_id_gen.get_next() as un_partial_state_room_stream_id
2714
+ ):
2715
+ await self.db_pool.runInteraction(
2716
+ "clear_partial_state_room",
2717
+ self._clear_partial_state_room_txn,
2718
+ room_id,
2719
+ un_partial_state_room_stream_id,
2720
+ )
2721
+ return un_partial_state_room_stream_id
2722
+ except self.db_pool.engine.module.IntegrityError as e:
2723
+ # Assume that any `IntegrityError`s are due to partial state events.
2724
+ logger.info(
2725
+ "Exception while clearing lazy partial-state-room %s, retrying: %s",
2726
+ room_id,
2727
+ e,
2728
+ )
2729
+ return None
2730
+
2731
+ def _clear_partial_state_room_txn(
2732
+ self,
2733
+ txn: LoggingTransaction,
2734
+ room_id: str,
2735
+ un_partial_state_room_stream_id: int,
2736
+ ) -> None:
2737
+ DatabasePool.simple_delete_txn(
2738
+ txn,
2739
+ table="partial_state_rooms_servers",
2740
+ keyvalues={"room_id": room_id},
2741
+ )
2742
+ DatabasePool.simple_delete_one_txn(
2743
+ txn,
2744
+ table="partial_state_rooms",
2745
+ keyvalues={"room_id": room_id},
2746
+ )
2747
+ self._invalidate_cache_and_stream(txn, self.is_partial_state_room, (room_id,))
2748
+ self._invalidate_cache_and_stream(
2749
+ txn, self._get_partial_state_servers_at_join, (room_id,)
2750
+ )
2751
+ self._invalidate_all_cache_and_stream(txn, self.get_partial_rooms)
2752
+
2753
+ DatabasePool.simple_insert_txn(
2754
+ txn,
2755
+ "un_partial_stated_room_stream",
2756
+ {
2757
+ "stream_id": un_partial_state_room_stream_id,
2758
+ "instance_name": self._instance_name,
2759
+ "room_id": room_id,
2760
+ },
2761
+ )
2762
+
2763
+ # We now delete anything from `device_lists_remote_pending` with a
2764
+ # stream ID less than the minimum
2765
+ # `partial_state_rooms.device_lists_stream_id`, as we no longer need them.
2766
+ device_lists_stream_id = DatabasePool.simple_select_one_onecol_txn(
2767
+ txn,
2768
+ table="partial_state_rooms",
2769
+ keyvalues={},
2770
+ retcol="MIN(device_lists_stream_id)",
2771
+ allow_none=True,
2772
+ )
2773
+ if device_lists_stream_id is None:
2774
+ # There are no rooms being currently partially joined, so we delete everything.
2775
+ txn.execute("DELETE FROM device_lists_remote_pending")
2776
+ else:
2777
+ sql = """
2778
+ DELETE FROM device_lists_remote_pending
2779
+ WHERE stream_id <= ?
2780
+ """
2781
+ txn.execute(sql, (device_lists_stream_id,))