tuwunel_service/appservice/
append.rs1use futures::{FutureExt, StreamExt, TryFutureExt};
2use ruma::{UserId, events::TimelineEventType};
3use tuwunel_core::{
4 Result, error, implement,
5 utils::{
6 ReadyExt,
7 stream::{IterStream, automatic_width},
8 },
9};
10use tuwunel_matrix::{
11 event::Event,
12 pdu::{Pdu, RawPduId},
13};
14
15use super::{RegistrationInfo, receivers};
16
17#[implement(super::Service)]
19#[tracing::instrument(name = "append", level = "debug", skip_all)]
20pub(crate) async fn append_pdu(&self, pdu_id: RawPduId, pdu: &Pdu) -> Result {
21 let registrations = self.read().await;
22
23 receivers(®istrations)
24 .stream()
25 .for_each_concurrent(automatic_width(), |appservice| {
26 self.append_pdu_to(appservice, pdu_id, pdu)
27 .inspect_err(|e| {
28 error!(
29 event_id = %pdu.event_id(),
30 appservice = ?appservice.registration.id,
31 "Failed to send PDU to appservice: {e}"
32 );
33 })
34 .map(drop)
35 })
36 .await;
37
38 Ok(())
39}
40
41#[implement(super::Service)]
42#[tracing::instrument(
43 name = "append_to",
44 level = "debug",
45 skip_all,
46 fields(id = %appservice.registration.id),
47)]
48async fn append_pdu_to(
49 &self,
50 appservice: &RegistrationInfo,
51 pdu_id: RawPduId,
52 pdu: &Pdu,
53) -> Result {
54 if self.should_append_to(appservice, pdu).await {
55 self.services
56 .sending
57 .send_pdu_appservice(appservice.registration.id.clone(), pdu_id)?;
58 }
59
60 Ok(())
61}
62
63#[implement(super::Service)]
64async fn should_append_to(&self, appservice: &RegistrationInfo, pdu: &Pdu) -> bool {
65 if self
66 .services
67 .state_cache
68 .appservice_in_room(pdu.room_id(), appservice)
69 .await
70 {
71 return true;
72 }
73
74 if appservice.is_user_match(pdu.sender()) {
75 return true;
76 }
77
78 if *pdu.kind() == TimelineEventType::RoomMember
79 && pdu
80 .state_key
81 .as_ref()
82 .and_then(|state_key| UserId::parse(state_key.as_str()).ok())
83 .is_some_and(|user_id| appservice.is_user_match(&user_id))
84 {
85 return true;
86 }
87
88 if self
89 .services
90 .alias
91 .local_aliases_for_room(pdu.room_id())
92 .ready_any(|room_alias| appservice.aliases.is_match(room_alias.as_str()))
93 .await
94 {
95 return true;
96 }
97
98 if appservice.rooms.is_match(pdu.room_id().as_str()) {
99 return true;
100 }
101
102 false
103}