Skip to main content

tuwunel_service/rooms/threads/
summary.rs

1//! The `m.thread` summary a thread root stores in its `unsigned`.
2//!
3//! The functions here build, read and rewrite the bundle the threads service
4//! keeps on the root's accepted row, and render a reply as its latest event.
5
6use std::collections::BTreeMap;
7
8use ruma::{
9	CanonicalJsonObject, CanonicalJsonValue, UInt, events::AnySyncMessageLikeEvent, serde::Raw,
10	uint,
11};
12use tuwunel_matrix::{Event, Pdu};
13
14const BUNDLE_PATH: [&str; 3] = ["unsigned", "m.relations", "m.thread"];
15
16/// Records `event` as the newest reply in a root's `unsigned`.
17///
18/// Sets the bundle's `latest_event`, counts the reply, and marks the thread as
19/// participated in only when the bundle does not say either way.
20pub(super) fn update_thread_bundle<E>(unsigned: &mut CanonicalJsonObject, event: &E)
21where
22	E: Event,
23{
24	update_thread_bundle_raw(unsigned, &event.to_sync_message_like_without_unsigned());
25}
26
27pub(super) fn update_thread_bundle_raw(
28	unsigned: &mut CanonicalJsonObject,
29	latest_event: &Raw<AnySyncMessageLikeEvent>,
30) {
31	add_reply(
32		unsigned,
33		canonical_json(latest_event).expect("thread latest event should be canonical JSON"),
34	);
35}
36
37pub(super) fn thread_reply_json(pdu: &Pdu) -> Option<CanonicalJsonValue> {
38	canonical_json(&pdu.to_sync_message_like_without_unsigned()).ok()
39}
40
41/// Whether a root's `m.thread` summary still counts a reply.
42///
43/// A summary recounted to zero lists no thread; one without a count is taken to
44/// count a reply.
45pub(super) fn counts_replies(root: &CanonicalJsonObject) -> bool {
46	thread_bundle(root).is_some_and(|thread| bundle_count(thread) != Some(uint!(0)))
47}
48
49pub(super) fn thread_count(root: &CanonicalJsonObject) -> Option<UInt> {
50	thread_bundle(root).and_then(bundle_count)
51}
52
53pub(super) fn thread_bundle(root: &CanonicalJsonObject) -> Option<&CanonicalJsonObject> {
54	BUNDLE_PATH
55		.into_iter()
56		.try_fold(root, |object, field| object.get(field)?.as_object())
57}
58
59pub(super) fn thread_latest(root: &CanonicalJsonObject) -> Option<&str> {
60	thread_bundle(root)?
61		.get("latest_event")?
62		.as_object()?
63		.get("event_id")?
64		.as_str()
65}
66
67pub(super) fn set_thread_count(
68	mut root: CanonicalJsonObject,
69	count: Option<UInt>,
70) -> CanonicalJsonObject {
71	if let Some((thread, count)) = thread_bundle_mut(&mut root).zip(count) {
72		thread.insert("count".into(), CanonicalJsonValue::Integer(count.into()));
73	}
74
75	root
76}
77
78/// Borrows the stored thread bundle for a summary rewrite.
79///
80/// Returns `None` when any component is missing or is not an object.
81pub(crate) fn thread_bundle_mut(
82	root: &mut CanonicalJsonObject,
83) -> Option<&mut CanonicalJsonObject> {
84	BUNDLE_PATH
85		.into_iter()
86		.try_fold(root, |object, field| object.get_mut(field)?.as_object_mut())
87}
88
89pub(super) fn set_thread_latest(
90	mut root: CanonicalJsonObject,
91	latest: Option<CanonicalJsonValue>,
92) -> CanonicalJsonObject {
93	let Some(latest) = latest else {
94		return remove_thread_bundle(root);
95	};
96
97	if let Some(thread) = thread_bundle_mut(&mut root) {
98		thread.insert("latest_event".into(), latest);
99	}
100
101	root
102}
103
104pub(super) fn omit_thread_latest(mut root: CanonicalJsonObject) -> CanonicalJsonObject {
105	if thread_count(&root).is_none_or(|count| count == uint!(0)) {
106		return remove_thread_bundle(root);
107	}
108
109	if let Some(thread) = thread_bundle_mut(&mut root) {
110		thread.remove("latest_event");
111	}
112
113	root
114}
115
116fn canonical_json(
117	event: &Raw<AnySyncMessageLikeEvent>,
118) -> serde_json::Result<CanonicalJsonValue> {
119	serde_json::from_str(event.json().get())
120}
121
122fn add_reply(unsigned: &mut CanonicalJsonObject, latest_event: CanonicalJsonValue) {
123	let thread = BUNDLE_PATH
124		.into_iter()
125		.skip(1)
126		.fold(unsigned, canonical_object_field);
127
128	let count = bundle_count(thread)
129		.unwrap_or_default()
130		.saturating_add(uint!(1));
131
132	thread.insert("latest_event".into(), latest_event);
133	thread.insert("count".into(), CanonicalJsonValue::Integer(count.into()));
134
135	if !matches!(thread.get("current_user_participated"), Some(CanonicalJsonValue::Bool(_))) {
136		thread.insert("current_user_participated".into(), CanonicalJsonValue::Bool(true));
137	}
138}
139
140fn canonical_object_field<'a>(
141	object: &'a mut CanonicalJsonObject,
142	field: &str,
143) -> &'a mut CanonicalJsonObject {
144	if !matches!(object.get(field), Some(CanonicalJsonValue::Object(_))) {
145		object.insert(field.into(), CanonicalJsonValue::Object(BTreeMap::new()));
146	}
147
148	object
149		.get_mut(field)
150		.and_then(CanonicalJsonValue::as_object_mut)
151		.expect("canonical object field was initialized as an object")
152}
153
154fn bundle_count(thread: &CanonicalJsonObject) -> Option<UInt> {
155	thread
156		.get("count")?
157		.as_integer()
158		.map(i64::from)
159		.and_then(|count| count.try_into().ok())
160}
161
162fn remove_thread_bundle(mut root: CanonicalJsonObject) -> CanonicalJsonObject {
163	let Some(unsigned) = root
164		.get_mut("unsigned")
165		.and_then(CanonicalJsonValue::as_object_mut)
166	else {
167		return root;
168	};
169
170	let Some(relations) = unsigned
171		.get_mut("m.relations")
172		.and_then(CanonicalJsonValue::as_object_mut)
173	else {
174		return root;
175	};
176
177	relations.remove("m.thread");
178	if relations.is_empty() {
179		unsigned.remove("m.relations");
180	}
181
182	root
183}