src/windows/room/not_joined.rs

373 lines · 12647 bytes

23 symbols in this file
  1use matrix_sdk::ruma::room::{JoinRuleSummary, RestrictedSummary, RoomType as MatrixRoomType};
  2use matrix_sdk::ruma::{RoomAliasId, RoomOrAliasId};
  3
  4use crate::base::{HomeserverAction, SyncInfo};
  5use crate::prelude::*;
  6use crate::util::wrap;
  7use crate::windows::room::RoomState;
  8use crate::windows::{ROOM_PREVIEW_DEBOUNCE, room_name_from_preview};
  9use crate::worker::ClientResponse;
 10
 11fn can_join_restricted(summary: &RestrictedSummary, sync_info: &SyncInfo) -> bool {
 12    sync_info
 13        .spaces
 14        .iter()
 15        .map(|r| r.room_id())
 16        .chain(sync_info.chats())
 17        .any(|room_id| summary.allowed_room_ids.iter().any(|allowed| allowed == room_id))
 18}
 19
 20fn preview_join_rule(
 21    preview: &RoomPreview,
 22    store: &ProgramStore,
 23) -> (&'static str, Option<&'static str>) {
 24    match &preview.join_rule {
 25        Some(JoinRuleSummary::Public) => ("This room is public.", Some(":join")),
 26        Some(JoinRuleSummary::Knock) => ("This room is knock-only.", Some(":knock")),
 27        Some(JoinRuleSummary::Invite) => ("This room is invite-only.", None),
 28        Some(JoinRuleSummary::Restricted(summary)) => {
 29            if can_join_restricted(summary, &store.application.sync_info) {
 30                ("This room is restricted to members of a room you are in.", Some(":join"))
 31            } else {
 32                ("This room is restricted to members of a room you are not in.", None)
 33            }
 34        },
 35        Some(JoinRuleSummary::KnockRestricted(summary)) => {
 36            if can_join_restricted(summary, &store.application.sync_info) {
 37                ("This room is knock-restricted to members of a room you are in.", Some(":knock"))
 38            } else {
 39                ("This room is knock-restricted to members of a room you are not in.", None)
 40            }
 41        },
 42        _ => ("Room join rules unknown. Try `:join` or `:knock` to join this room.", None),
 43    }
 44}
 45
 46fn preview_state(
 47    preview: &RoomPreview,
 48    store: &ProgramStore,
 49) -> (&'static str, Option<&'static str>) {
 50    match preview.state {
 51        Some(MatrixRoomState::Invited) => {
 52            ("You have been invited to join this room.", Some(":invite accept"))
 53        },
 54        Some(MatrixRoomState::Knocked) => ("You have knocked on this room.", None),
 55        Some(MatrixRoomState::Banned) => ("You have been banned from this room.", None),
 56        Some(MatrixRoomState::Joined) => ("You have already joined this room.", None),
 57        Some(MatrixRoomState::Left) | None => preview_join_rule(preview, store),
 58    }
 59}
 60
 61pub struct NotJoinedState {
 62    alias: OwnedRoomOrAliasId,
 63    /// The resolved [`alias`](`Self::alias`).
 64    room_id: Option<OwnedRoomId>,
 65    err: Option<String>,
 66    joining: Option<ClientResponse<IambResult<OwnedRoomId>>>,
 67
 68    term_cursor: (u16, u16),
 69}
 70
 71impl NotJoinedState {
 72    /// Create a window for a room the user hasn't joined.
 73    pub fn new(alias: OwnedRoomOrAliasId, store: &mut ProgramStore) -> Self {
 74        store.application.need_load.need_preview(alias.clone());
 75
 76        Self {
 77            alias,
 78            room_id: None,
 79            err: None,
 80            joining: None,
 81            term_cursor: (0, 0),
 82        }
 83    }
 84
 85    pub fn alias(&self) -> &RoomOrAliasId {
 86        &self.alias
 87    }
 88
 89    pub fn room_id(&mut self, store: &ProgramStore) -> Option<&RoomId> {
 90        let alias_or_id: &RoomOrAliasId = &self.alias;
 91        match <&RoomId>::try_from(alias_or_id) {
 92            Ok(id) => Some(id),
 93            Err(alias) => {
 94                let room_id = store.application.aliases.get(alias);
 95                self.room_id = room_id.cloned();
 96                self.room_id.as_deref()
 97            },
 98        }
 99    }
100
101    pub fn refresh_room(&mut self, store: &mut ProgramStore) -> Option<RoomState> {
102        let room = if let Some(room) = self
103            .room_id(store)
104            .and_then(|id| store.application.worker.client.get_room(id))
105        {
106            room
107        } else {
108            match self.joining.as_ref().and_then(|chan| chan.try_recv())? {
109                Err(e) => {
110                    self.err = Some(e.to_string());
111                    self.joining = None;
112                },
113                Ok(room_id) => {
114                    // It is technically possible for a custom room alias to exist on a server
115                    // that is not then listed in the room's state events, so we make sure
116                    // to map the alias we used to join to the room ID at this point, so that
117                    // we can guarantee we see the room next time we're refreshed.
118                    if let Ok(alias) = <&RoomAliasId>::try_from(self.alias.deref()) {
119                        store.application.aliases.insert(alias.to_owned(), room_id);
120                    }
121                },
122            }
123            return None;
124        };
125
126        if room.state() == MatrixRoomState::Left {
127            // room previews have more information than left rooms
128            return None;
129        }
130
131        store.application.need_load.need_members(room.room_id().to_owned());
132
133        Some(RoomState::new(room, RoomView::Main, store))
134    }
135
136    pub fn dup(&self) -> Self {
137        Self {
138            alias: self.alias.clone(),
139            room_id: self.room_id.clone(),
140            err: self.err.clone(),
141            joining: None,
142            term_cursor: (0, 0),
143        }
144    }
145
146    pub fn get_tab_title(&self, store: &ProgramStore) -> Line<'_> {
147        if let Some((Ok(preview), _)) = store.application.room_previews.get(self.alias()) {
148            if let Some(name) = &preview.name {
149                return Line::from(name.to_string());
150            }
151
152            if let Some(alias) = &preview.canonical_alias {
153                return Line::from(alias.to_string());
154            }
155        }
156
157        Line::from(self.alias.as_str())
158    }
159
160    pub fn get_title(&self, store: &ProgramStore) -> Line<'_> {
161        if let Some((Ok(preview), _)) = store.application.room_previews.get(self.alias()) {
162            if let Some(name) = &preview.name {
163                return Line::from(vec![
164                    Span::styled(name.to_string(), StyleModifier::BOLD),
165                    Span::raw(" (unjoined)"),
166                ]);
167            }
168
169            if let Some(alias) = &preview.canonical_alias {
170                return Line::from(vec![
171                    Span::styled(alias.to_string(), StyleModifier::BOLD),
172                    Span::raw(" (unjoined)"),
173                ]);
174            }
175        }
176
177        Line::from(vec![
178            Span::styled(self.alias.as_str(), StyleModifier::BOLD),
179            Span::raw(" (unjoined)"),
180        ])
181    }
182
183    pub fn join(&mut self, store: &mut ProgramStore) {
184        let via = store
185            .application
186            .room_via
187            .get(self.alias())
188            .unwrap_or(&store.application.settings.tunables.default_via)
189            .iter()
190            .cloned()
191            .collect();
192        let chan = store.application.worker.join_room_chan(self.alias().to_owned(), via);
193        self.joining = Some(chan);
194        self.err = None;
195    }
196
197    pub fn join_command(
198        &mut self,
199        act: JoinAction,
200        ctx: ProgramContext,
201        store: &mut ProgramStore,
202    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
203        match act {
204            JoinAction::Join => {
205                self.join(store);
206                Ok(vec![])
207            },
208            JoinAction::Knock => {
209                let act = HomeserverAction::KnockSend(self.alias().to_owned(), None);
210
211                Ok(vec![(IambAction::from(act).into(), ctx)])
212            },
213        }
214    }
215}
216
217impl Editable<ProgramContext, ProgramStore, IambInfo> for NotJoinedState {
218    fn editor_command(
219        &mut self,
220        _: &EditorAction,
221        _: &ProgramContext,
222        _: &mut ProgramStore,
223    ) -> EditResult<EditInfo, IambInfo> {
224        Ok(None)
225    }
226}
227
228impl Jumpable<ProgramContext, IambInfo> for NotJoinedState {
229    fn jump(
230        &mut self,
231        _: PositionList,
232        _: MoveDir1D,
233        count: usize,
234        _: &ProgramContext,
235    ) -> IambResult<usize> {
236        Ok(count)
237    }
238}
239
240impl Scrollable<ProgramContext, ProgramStore, IambInfo> for NotJoinedState {
241    fn scroll(
242        &mut self,
243        _: &ScrollStyle,
244        _: &ProgramContext,
245        _: &mut ProgramStore,
246    ) -> EditResult<EditInfo, IambInfo> {
247        Ok(None)
248    }
249}
250
251impl Promptable<ProgramContext, ProgramStore, IambInfo> for NotJoinedState {
252    fn prompt(
253        &mut self,
254        _: &PromptAction,
255        _: &ProgramContext,
256        _: &mut ProgramStore,
257    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
258        Ok(vec![])
259    }
260}
261
262impl TerminalCursor for NotJoinedState {
263    fn get_term_cursor(&self) -> Option<TermOffset> {
264        self.term_cursor.into()
265    }
266
267    fn hide_term_cursor(&self) -> bool {
268        true
269    }
270}
271
272/// [StatefulWidget] for Matrix rooms that haven't been joined.
273pub struct NotJoined<'a> {
274    store: &'a mut ProgramStore,
275}
276
277impl<'a> NotJoined<'a> {
278    pub fn new(store: &'a mut ProgramStore) -> Self {
279        Self { store }
280    }
281}
282
283impl StatefulWidget for NotJoined<'_> {
284    type State = NotJoinedState;
285
286    fn render(self, area: Rect, buffer: &mut Buffer, state: &mut Self::State) {
287        // Ensure the whole window receives the default timeline styling:
288        let theme = &self.store.application.settings.theme;
289        let default_style = theme.timeline.default;
290        let err_style = default_style.fg(Color::Red);
291        buffer.set_style(area, default_style);
292
293        // Save the top-left corner for indicating cursor placement:
294        state.term_cursor = (area.left(), area.top());
295
296        let mut lines = vec![];
297
298        let preview = self.store.application.room_previews.get(state.alias());
299        if let Some((_, fetched)) = &preview &&
300            fetched.elapsed() > ROOM_PREVIEW_DEBOUNCE
301        {
302            self.store.application.need_load.need_preview(state.alias().to_owned());
303        }
304
305        match preview {
306            Some((Ok(preview), _)) => {
307                lines.push(Line::from(room_name_from_preview(preview)));
308
309                let mut info_line = vec![];
310                if let Some(alias) = &preview.canonical_alias {
311                    info_line.push(", ".into());
312                    info_line.push(Span::styled(alias.as_str(), default_style.bold()));
313                }
314                if Some(MatrixRoomType::Space) == preview.room_type {
315                    info_line.push(", ".into());
316                    info_line.push("Space".into());
317                } else if Some(true) == preview.is_direct {
318                    info_line.push(", ".into());
319                    info_line.push("DM".into());
320                }
321
322                if !info_line.is_empty() {
323                    info_line.push(")".into());
324                    info_line[0] = "(".into();
325                    lines.push(Line::from(info_line));
326                }
327
328                if let Some(topic) = &preview.topic {
329                    lines.extend(wrap(topic, area.width.into()).map(|(line, _)| Line::raw(line)));
330                }
331
332                lines.push(Line::raw(""));
333
334                let (status, join_cmd) = preview_state(preview, self.store);
335
336                lines.push(Line::raw(status));
337                if let Some(join_cmd) = join_cmd {
338                    lines.push(Line::from(vec![
339                        Span::raw("Use `"),
340                        Span::styled(join_cmd, StyleModifier::BOLD),
341                        Span::raw("` to join this room"),
342                    ]));
343                }
344            },
345            Some((Err(matrix_sdk::Error::InsufficientData), _)) => {
346                lines.push(Line::from(Span::styled(
347                    "This room doesn't exist or room previews are disabled",
348                    err_style,
349                )));
350            },
351            Some((Err(err), _)) => {
352                lines.push(Line::from(Span::styled(err.to_string(), err_style)));
353            },
354            None => {
355                self.store.application.need_load.need_preview(state.alias().to_owned());
356                lines.push(Line::raw("Loading room preview..."));
357            },
358        }
359
360        if state.joining.is_some() {
361            lines.push(Line::raw(""));
362            lines.push(Line::raw("Joining this room..."));
363        }
364
365        if let Some(err) = &state.err {
366            lines.push(Line::from(Span::styled(err.as_str(), err_style)));
367        }
368
369        Paragraph::new(Text::from(lines))
370            .alignment(Alignment::Center)
371            .render(area, buffer);
372    }
373}