Skip to main content

grammers_client/peer/
dialog.rs

1// Copyright 2020 - developers of the `grammers` project.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use grammers_session::types::{PeerId, PeerRef};
10use grammers_tl_types as tl;
11
12use super::{Peer, PeerMap};
13use crate::Client;
14use crate::message::Message;
15use crate::utils::peer_from_message;
16
17/// An entry in the list of "chats".
18///
19/// All conversations with history, even if the history has been cleared,
20/// as long as the dialog itself has not been deleted, are present as dialogs.
21///
22/// Bot accounts do not have dialogs per-se and thus cannot fetch them.
23///
24/// Dialogs of users continue to exist even if the user has deleted their account.
25/// The same is true for small group chats, but not of large group chats and channels.
26#[derive(Debug, Clone)]
27pub struct Dialog {
28    pub raw: tl::enums::Dialog,
29    pub peer: Peer,
30    pub last_message: Option<Message>,
31}
32
33impl Dialog {
34    pub(crate) fn new(
35        client: &Client,
36        dialog: tl::enums::Dialog,
37        messages: &mut Vec<tl::enums::Message>,
38        peers: PeerMap,
39    ) -> Self {
40        // TODO helper utils (ext trait?) to extract data from dialogs or messages
41        let peer_id = match dialog {
42            tl::enums::Dialog::Dialog(ref dialog) => dialog.peer.clone().into(),
43            tl::enums::Dialog::Folder(ref dialog) => dialog.peer.clone().into(),
44        };
45
46        let peer = peers
47            .get(peer_id)
48            .expect("dialogs use an unknown peer")
49            .clone();
50
51        let message = messages
52            .iter()
53            .position(|m| peer_from_message(m).is_some_and(|p| PeerId::from(p) == peer_id))
54            .map(|i| messages.swap_remove(i));
55
56        Self {
57            last_message: message.map(|m| {
58                Message::from_raw(
59                    client,
60                    m,
61                    Some(PeerRef {
62                        id: peer.id(),
63                        auth: peer.auth().unwrap(),
64                    }),
65                    peers.handle(),
66                )
67            }),
68            peer,
69            raw: dialog,
70        }
71    }
72
73    /// The [`Self::peer`]'s identifier.
74    pub fn peer_id(&self) -> PeerId {
75        self.peer.id()
76    }
77
78    /// Cached reference to the [`Self::peer`].
79    pub fn peer_ref(&self) -> PeerRef {
80        PeerRef {
81            id: self.peer.id(),
82            auth: self.peer.auth().unwrap(),
83        }
84    }
85
86    /// The peer represented by this dialog.
87    pub fn peer(&self) -> &Peer {
88        &self.peer
89    }
90}