src/message/poll.rs

546 lines · 18203 bytes

43 symbols in this file
  1use std::borrow::Cow;
  2use std::collections::{BTreeMap, BTreeSet};
  3use std::fmt::Write as _;
  4
  5use indexmap::IndexMap;
  6use matrix_sdk::ruma::events::poll::end::{OriginalPollEndEvent, PollEndEventContent};
  7use matrix_sdk::ruma::events::poll::response::OriginalPollResponseEvent;
  8use matrix_sdk::ruma::events::poll::start::{
  9    PollContentBlock,
 10    PollKind,
 11    PollStartEventContent,
 12    PollStartEventContentWithoutRelation,
 13};
 14use matrix_sdk::ruma::events::poll::unstable_end::{
 15    OriginalUnstablePollEndEvent,
 16    UnstablePollEndEventContent,
 17};
 18use matrix_sdk::ruma::events::poll::unstable_response::OriginalUnstablePollResponseEvent;
 19use matrix_sdk::ruma::events::poll::unstable_start::{
 20    NewUnstablePollStartEventContent,
 21    ReplacementUnstablePollStartEventContent,
 22    UnstablePollStartContentBlock,
 23};
 24use matrix_sdk::ruma::events::relation::Thread;
 25use matrix_sdk::ruma::events::room::message::{Relation, RelationWithoutReplacement};
 26use matrix_sdk::ruma::events::{OriginalMessageLikeEvent, poll};
 27use matrix_sdk::ruma::{EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedUserId, UserId};
 28
 29use crate::message::{MessageKey, MessageTimeStamp};
 30
 31const PLAINTEXT_FALLBACK: &str = "(Answer is missing plain text description)";
 32
 33/// Indicates where an [EventId] lives in the poll.
 34#[derive(Clone, Debug)]
 35pub enum PollEventLocation {
 36    /// The [EventId] belongs to a replacement and has key [MessageKey].
 37    Replacement(MessageKey),
 38    /// The [EventId] belongs to a response and has key [MessageKey].
 39    Response(MessageKey),
 40    /// The [EventId] belongs to the end event.
 41    End,
 42}
 43
 44/// The first entry in the tuples produced by the iterators is the answer id.
 45fn body_cow<'a>(
 46    kind: &'a PollKind,
 47    own_user_id: &'a UserId,
 48    question: &'a str,
 49    answers: impl IntoIterator<Item = (&'a str, &'a str)>,
 50    results: impl IntoIterator<Item = (&'a str, BTreeSet<&'a UserId>)>,
 51    ended: Option<MilliSecondsSinceUnixEpoch>,
 52) -> String {
 53    // map answer id to answer text and the char `'X'` if the user has selected this option or `' '`
 54    // otherwise
 55    let mut answers: IndexMap<_, _> = answers.into_iter().map(|(k, v)| (k, (v, ' '))).collect();
 56
 57    let mut text = "Poll: ".to_string();
 58    text.push_str(question);
 59
 60    let show_user_count = ended.is_some() || *kind == PollKind::Disclosed;
 61    for (id, users) in results {
 62        let Some((answer_text, selection_char)) = answers.get_mut(id) else {
 63            continue;
 64        };
 65
 66        if users.contains(own_user_id) {
 67            *selection_char = 'X';
 68        }
 69
 70        if show_user_count {
 71            write!(&mut text, "\n[{selection_char}] ({}) {answer_text}", users.len())
 72                .expect("writing to a String cannot return an error");
 73        }
 74    }
 75
 76    if !show_user_count {
 77        for (answer_text, selection_char) in answers.values() {
 78            write!(&mut text, "\n[{selection_char}] {answer_text}")
 79                .expect("writing to a String cannot return an error");
 80        }
 81    }
 82
 83    if let Some(ended_ts) = ended {
 84        let ended_time = MessageTimeStamp(ended_ts).as_datetime();
 85
 86        write!(&mut text, "\nEnded: {}", ended_time.format("%c"))
 87            .expect("writing to a String cannot return an error");
 88    }
 89
 90    text
 91}
 92
 93/// All data related to a poll in an unsupported room version.
 94#[derive(Debug, Clone)]
 95pub struct Poll {
 96    event_id: OwnedEventId,
 97    own_user_id: OwnedUserId,
 98    pub start: PollStartEventContent,
 99    pub replacements: BTreeMap<MessageKey, PollStartEventContentWithoutRelation>,
100
101    pub responses: BTreeMap<MessageKey, OriginalPollResponseEvent>,
102
103    pub end: Option<OriginalMessageLikeEvent<PollEndEventContent>>,
104}
105
106impl Poll {
107    pub fn new(
108        event_id: OwnedEventId,
109        own_user_id: OwnedUserId,
110        start: PollStartEventContent,
111        unloaded: UnloadedPoll,
112    ) -> Self {
113        Self {
114            event_id,
115            own_user_id,
116            start,
117            replacements: unloaded.replacements,
118            responses: unloaded.responses,
119            end: unloaded.end,
120        }
121    }
122
123    fn content(&self) -> &PollContentBlock {
124        self.replacements
125            .iter()
126            .rev()
127            .map(|(_, v)| &v.poll)
128            .next()
129            .unwrap_or(&self.start.poll)
130    }
131
132    fn results(&self) -> impl IntoIterator<Item = (&str, BTreeSet<&UserId>)> {
133        let poll = self.content();
134        let responses = self.responses.values().map(OriginalPollResponseEvent::data);
135        let end_timestamp = self.end.as_ref().map(|end| end.origin_server_ts);
136
137        poll::compile_poll_results(poll, responses, end_timestamp)
138    }
139
140    pub fn event_id(&self) -> &EventId {
141        self.event_id.as_ref()
142    }
143
144    /// The message this poll replied to if it is a reply.
145    pub fn reply_to(&self) -> Option<&EventId> {
146        match &self.start.relates_to {
147            Some(Relation::Reply(reply)) => Some(reply.in_reply_to.event_id.as_ref()),
148            Some(Relation::Thread(Thread {
149                in_reply_to: Some(in_reply_to),
150                is_falling_back: false,
151                ..
152            })) => Some(in_reply_to.event_id.as_ref()),
153            _ => None,
154        }
155    }
156
157    /// Return the thread root if this is the first message in the thread.
158    pub fn thread_root(&self) -> Option<&EventId> {
159        match &self.start.relates_to {
160            Some(Relation::Thread(Thread {
161                event_id,
162                in_reply_to: Some(in_reply_to),
163                is_falling_back: true,
164                ..
165            })) if event_id == &in_reply_to.event_id => Some(event_id.as_ref()),
166            _ => None,
167        }
168    }
169
170    pub fn redact(&mut self, loc: &PollEventLocation) {
171        match loc {
172            PollEventLocation::Replacement(key) => {
173                self.replacements.remove(key);
174            },
175            PollEventLocation::Response(key) => {
176                self.responses.remove(key);
177            },
178            PollEventLocation::End => self.end = None,
179        }
180    }
181
182    pub fn insert_relation(&mut self, value: PollRelation) -> PollEventLocation {
183        match value {
184            PollRelation::Response(ev) => {
185                let key = MessageKey {
186                    ts: ev.origin_server_ts.into(),
187                    id: ev.event_id.clone().into(),
188                };
189
190                self.responses.insert(key.clone(), ev);
191
192                PollEventLocation::Response(key)
193            },
194            PollRelation::End(ev) => {
195                self.end = Some(ev);
196                PollEventLocation::End
197            },
198        }
199    }
200
201    pub fn body_cow(&self) -> Cow<'_, str> {
202        let start = self.content();
203
204        let question = start.question.text.find_plain().unwrap_or("Question not found");
205        let answers = start.answers.iter().map(|answer| {
206            // Only show the plaintext representation for now:
207            (answer.id.as_str(), answer.text.find_plain().unwrap_or(PLAINTEXT_FALLBACK))
208        });
209        let results = self.results();
210        let ended = self.end.as_ref().map(|ev| ev.origin_server_ts);
211
212        body_cow(&start.kind, &self.own_user_id, question, answers, results, ended).into()
213    }
214}
215
216/// All data accumulated for a [`Poll`] before the start event was loaded.
217#[derive(Debug, Clone, Default)]
218pub struct UnloadedPoll {
219    pub replacements: BTreeMap<MessageKey, PollStartEventContentWithoutRelation>,
220
221    pub responses: BTreeMap<MessageKey, OriginalPollResponseEvent>,
222
223    pub end: Option<OriginalMessageLikeEvent<PollEndEventContent>>,
224}
225
226impl UnloadedPoll {
227    pub fn redact(&mut self, loc: &PollEventLocation) {
228        match loc {
229            PollEventLocation::Replacement(key) => {
230                self.replacements.remove(key);
231            },
232            PollEventLocation::Response(key) => {
233                self.responses.remove(key);
234            },
235            PollEventLocation::End => self.end = None,
236        }
237    }
238
239    pub fn insert_relation(&mut self, value: PollRelation) -> PollEventLocation {
240        match value {
241            PollRelation::Response(ev) => {
242                let key = MessageKey {
243                    ts: ev.origin_server_ts.into(),
244                    id: ev.event_id.clone().into(),
245                };
246
247                self.responses.insert(key.clone(), ev);
248
249                PollEventLocation::Response(key)
250            },
251            PollRelation::End(ev) => {
252                self.end = Some(ev);
253                PollEventLocation::End
254            },
255        }
256    }
257}
258
259/// A response or end event that is stored with the poll. Used for more unified
260/// insertion logic.
261pub enum PollRelation {
262    Response(OriginalPollResponseEvent),
263    End(OriginalPollEndEvent),
264}
265
266impl PollRelation {
267    pub fn event_id(&self) -> &EventId {
268        match self {
269            PollRelation::Response(ev) => &ev.event_id,
270            PollRelation::End(ev) => &ev.event_id,
271        }
272    }
273
274    /// The [`EventId`] of the poll start this event relates to.
275    pub fn poll_event_id(&self) -> &EventId {
276        match self {
277            PollRelation::Response(ev) => &ev.content.relates_to.event_id,
278            PollRelation::End(ev) => &ev.content.relates_to.event_id,
279        }
280    }
281}
282
283impl From<OriginalPollResponseEvent> for PollRelation {
284    fn from(value: OriginalPollResponseEvent) -> Self {
285        Self::Response(value)
286    }
287}
288impl From<OriginalPollEndEvent> for PollRelation {
289    fn from(value: OriginalPollEndEvent) -> Self {
290        Self::End(value)
291    }
292}
293
294/// All data related to a poll in an unsupported room version.
295#[derive(Debug, Clone)]
296pub struct UnstablePoll {
297    event_id: OwnedEventId,
298    own_user_id: OwnedUserId,
299    pub start: NewUnstablePollStartEventContent,
300    pub replacements: BTreeMap<MessageKey, ReplacementUnstablePollStartEventContent>,
301
302    pub responses: BTreeMap<MessageKey, OriginalUnstablePollResponseEvent>,
303
304    pub end: Option<OriginalMessageLikeEvent<UnstablePollEndEventContent>>,
305}
306
307impl UnstablePoll {
308    pub fn new(
309        event_id: OwnedEventId,
310        own_user_id: OwnedUserId,
311        start: NewUnstablePollStartEventContent,
312        unloaded: UnloadedUnstablePoll,
313    ) -> Self {
314        Self {
315            event_id,
316            own_user_id,
317            start,
318            replacements: unloaded.replacements,
319            responses: unloaded.responses,
320            end: unloaded.end,
321        }
322    }
323
324    fn content(&self) -> &UnstablePollStartContentBlock {
325        self.replacements
326            .iter()
327            .rev()
328            .map(|(_, v)| &v.relates_to.new_content.poll_start)
329            .next()
330            .unwrap_or(&self.start.poll_start)
331    }
332
333    fn results(&self) -> impl IntoIterator<Item = (&str, BTreeSet<&UserId>)> {
334        let poll = self.content();
335        let responses = self.responses.values().map(OriginalUnstablePollResponseEvent::data);
336        let end_timestamp = self.end.as_ref().map(|end| end.origin_server_ts);
337
338        poll::compile_unstable_poll_results(poll, responses, end_timestamp)
339    }
340
341    pub fn event_id(&self) -> &EventId {
342        self.event_id.as_ref()
343    }
344
345    /// The message this poll replied to if it is a reply.
346    pub fn reply_to(&self) -> Option<&EventId> {
347        match &self.start.relates_to {
348            Some(RelationWithoutReplacement::Reply(reply)) => {
349                Some(reply.in_reply_to.event_id.as_ref())
350            },
351            Some(RelationWithoutReplacement::Thread(Thread {
352                in_reply_to: Some(in_reply_to),
353                is_falling_back: false,
354                ..
355            })) => Some(in_reply_to.event_id.as_ref()),
356            _ => None,
357        }
358    }
359
360    /// Return the thread root if this is the first message in the thread.
361    pub fn thread_root(&self) -> Option<&EventId> {
362        match &self.start.relates_to {
363            Some(RelationWithoutReplacement::Thread(Thread {
364                event_id,
365                in_reply_to: Some(in_reply_to),
366                is_falling_back: true,
367                ..
368            })) if event_id == &in_reply_to.event_id => Some(event_id.as_ref()),
369            _ => None,
370        }
371    }
372
373    pub fn redact(&mut self, loc: &PollEventLocation) {
374        match loc {
375            PollEventLocation::Replacement(key) => {
376                self.replacements.remove(key);
377            },
378            PollEventLocation::Response(key) => {
379                self.responses.remove(key);
380            },
381            PollEventLocation::End => self.end = None,
382        }
383    }
384
385    pub fn insert_relation(&mut self, value: UnstablePollRelation) -> PollEventLocation {
386        match value {
387            UnstablePollRelation::Response(ev) => {
388                let key = MessageKey {
389                    ts: ev.origin_server_ts.into(),
390                    id: ev.event_id.clone().into(),
391                };
392
393                self.responses.insert(key.clone(), ev);
394
395                PollEventLocation::Response(key)
396            },
397            UnstablePollRelation::End(ev) => {
398                self.end = Some(ev);
399                PollEventLocation::End
400            },
401        }
402    }
403
404    pub fn body_cow(&self) -> Cow<'_, str> {
405        let start = self.content();
406
407        let question = &start.question.text;
408        let answers = start
409            .answers
410            .iter()
411            .map(|answer| (answer.id.as_str(), answer.text.as_str()));
412        let results = self.results();
413        let ended = self.end.as_ref().map(|ev| ev.origin_server_ts);
414
415        body_cow(&start.kind, &self.own_user_id, question, answers, results, ended).into()
416    }
417}
418
419/// All data accumulated for a [`UnstablePoll`] before the start event was loaded.
420#[derive(Debug, Clone, Default)]
421pub struct UnloadedUnstablePoll {
422    pub replacements: BTreeMap<MessageKey, ReplacementUnstablePollStartEventContent>,
423
424    pub responses: BTreeMap<MessageKey, OriginalUnstablePollResponseEvent>,
425
426    pub end: Option<OriginalMessageLikeEvent<UnstablePollEndEventContent>>,
427}
428
429impl UnloadedUnstablePoll {
430    pub fn redact(&mut self, loc: &PollEventLocation) {
431        match loc {
432            PollEventLocation::Replacement(key) => {
433                self.replacements.remove(key);
434            },
435            PollEventLocation::Response(key) => {
436                self.responses.remove(key);
437            },
438            PollEventLocation::End => self.end = None,
439        }
440    }
441
442    pub fn insert_relation(&mut self, value: UnstablePollRelation) -> PollEventLocation {
443        match value {
444            UnstablePollRelation::Response(ev) => {
445                let key = MessageKey {
446                    ts: ev.origin_server_ts.into(),
447                    id: ev.event_id.clone().into(),
448                };
449
450                self.responses.insert(key.clone(), ev);
451
452                PollEventLocation::Response(key)
453            },
454            UnstablePollRelation::End(ev) => {
455                self.end = Some(ev);
456                PollEventLocation::End
457            },
458        }
459    }
460}
461
462/// A response or end event that is stored with the poll. Used for more unified
463/// insertion logic.
464pub enum UnstablePollRelation {
465    Response(OriginalUnstablePollResponseEvent),
466    End(OriginalUnstablePollEndEvent),
467}
468
469impl UnstablePollRelation {
470    pub fn event_id(&self) -> &EventId {
471        match self {
472            UnstablePollRelation::Response(ev) => &ev.event_id,
473            UnstablePollRelation::End(ev) => &ev.event_id,
474        }
475    }
476
477    /// The [`EventId`] of the poll start this event relates to.
478    pub fn poll_event_id(&self) -> &EventId {
479        match self {
480            UnstablePollRelation::Response(ev) => &ev.content.relates_to.event_id,
481            UnstablePollRelation::End(ev) => &ev.content.relates_to.event_id,
482        }
483    }
484}
485
486impl From<OriginalUnstablePollResponseEvent> for UnstablePollRelation {
487    fn from(value: OriginalUnstablePollResponseEvent) -> Self {
488        Self::Response(value)
489    }
490}
491impl From<OriginalUnstablePollEndEvent> for UnstablePollRelation {
492    fn from(value: OriginalUnstablePollEndEvent) -> Self {
493        Self::End(value)
494    }
495}
496
497#[cfg(test)]
498mod tests {
499    use super::*;
500
501    use matrix_sdk::ruma::events::message::{TextContentBlock, TextRepresentation};
502    use matrix_sdk::ruma::events::poll::start::{PollAnswer, PollAnswers};
503    use matrix_sdk::ruma::{owned_event_id, owned_user_id};
504
505    fn poll_from(answers: Vec<PollAnswer>) -> Poll {
506        let answers = PollAnswers::try_from(answers).unwrap();
507        let block = PollContentBlock::new(TextContentBlock::plain("Pick one"), answers);
508        let start = PollStartEventContent::new(TextContentBlock::plain("Pick one"), block);
509
510        Poll::new(
511            owned_event_id!("$poll:example.com"),
512            owned_user_id!("@user:example.com"),
513            start,
514            UnloadedPoll::default(),
515        )
516    }
517
518    #[test]
519    fn test_body_cow_answer_html() {
520        let html_only = TextContentBlock::from(vec![TextRepresentation::html("<b>Yes</b>")]);
521        let answer1 = PollAnswer::new("a1".to_owned(), html_only);
522        let answer2 = PollAnswer::new("a2".to_owned(), TextContentBlock::plain("No"));
523        let poll = poll_from(vec![answer1, answer2]);
524
525        // Verify that we show a fallback message when we don't show HTML answers:
526        let body = poll.body_cow();
527        assert!(body.contains("Poll: Pick one"), "{body:?}");
528        assert!(body.contains(PLAINTEXT_FALLBACK), "{body:?}");
529        assert!(body.contains("No"), "{body:?}");
530        assert!(!body.contains("Yes"), "{body:?}");
531        assert_eq!(body.lines().count(), 3, "{body:?}");
532    }
533
534    #[test]
535    fn test_body_cow_answer_plaintext_only() {
536        let answer1 = PollAnswer::new("a1".to_owned(), TextContentBlock::plain("Yes"));
537        let answer2 = PollAnswer::new("a2".to_owned(), TextContentBlock::plain("No"));
538        let poll = poll_from(vec![answer1, answer2]);
539
540        let body = poll.body_cow();
541        assert!(body.contains("Poll: Pick one"), "{body:?}");
542        assert!(body.contains("Yes"), "{body:?}");
543        assert!(body.contains("No"), "{body:?}");
544        assert!(!body.contains(PLAINTEXT_FALLBACK), "{body:?}");
545    }
546}