1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
//
// ferogram: async Telegram MTProto client in Rust
// https://github.com/ankit-chaubey/ferogram
//
// Licensed under either the MIT License or the Apache License 2.0.
// See the LICENSE-MIT or LICENSE-APACHE file in this repository:
// https://github.com/ankit-chaubey/ferogram
//
// Feel free to use, modify, and share this code.
// Please keep this notice when redistributing.
use crate::*;
#[allow(unused_imports)]
use crate::{
InputMessage, InvocationError, PeerRef,
dialog::{Dialog, DialogIter, MessageIter},
inline_iter, media, participants, search, update,
};
use ferogram_tl_types::Deserializable;
use std::collections::{HashMap, VecDeque};
impl Client {
/// Fetch up to `limit` dialogs, most recent first. Populates entity/message.
pub async fn get_dialogs(&self, limit: i32) -> Result<Vec<Dialog>, InvocationError> {
let req = tl::functions::messages::GetDialogs {
exclude_pinned: false,
folder_id: None,
offset_date: 0,
offset_id: 0,
offset_peer: tl::enums::InputPeer::Empty,
limit,
hash: 0,
};
let body: Vec<u8> = self.rpc_call_raw(&req).await?;
let raw = match tl::enums::messages::Dialogs::from_bytes_exact(&body)? {
tl::enums::messages::Dialogs::Dialogs(d) => d,
tl::enums::messages::Dialogs::Slice(d) => tl::types::messages::Dialogs {
dialogs: d.dialogs,
messages: d.messages,
chats: d.chats,
users: d.users,
},
tl::enums::messages::Dialogs::NotModified(_) => return Ok(vec![]),
};
// Build message map
let msg_map: HashMap<i32, tl::enums::Message> = raw
.messages
.into_iter()
.map(|m| {
let id = match &m {
tl::enums::Message::Message(x) => x.id,
tl::enums::Message::Service(x) => x.id,
tl::enums::Message::Empty(x) => x.id,
};
(id, m)
})
.collect();
// Build user map
let user_map: HashMap<i64, tl::enums::User> = raw
.users
.into_iter()
.filter_map(|u| {
if let tl::enums::User::User(ref uu) = u {
Some((uu.id, u))
} else {
None
}
})
.collect();
// Build chat map
let chat_map: HashMap<i64, tl::enums::Chat> = raw
.chats
.into_iter()
.map(|c| {
let id = match &c {
tl::enums::Chat::Chat(x) => x.id,
tl::enums::Chat::Forbidden(x) => x.id,
tl::enums::Chat::Channel(x) => x.id,
tl::enums::Chat::ChannelForbidden(x) => x.id,
tl::enums::Chat::Empty(x) => x.id,
};
(id, c)
})
.collect();
// Cache peers for future access_hash lookups
{
let u_list: Vec<tl::enums::User> = user_map.values().cloned().collect();
let c_list: Vec<tl::enums::Chat> = chat_map.values().cloned().collect();
self.cache_users_and_chats(&u_list, &c_list).await;
}
let result = raw
.dialogs
.into_iter()
.map(|d| {
let top_id = match &d {
tl::enums::Dialog::Dialog(x) => x.top_message,
_ => 0,
};
let peer = match &d {
tl::enums::Dialog::Dialog(x) => Some(&x.peer),
_ => None,
};
let message = msg_map.get(&top_id).cloned();
let entity = peer.and_then(|p| match p {
tl::enums::Peer::User(u) => user_map.get(&u.user_id).cloned(),
_ => None,
});
let chat = peer.and_then(|p| match p {
tl::enums::Peer::Chat(c) => chat_map.get(&c.chat_id).cloned(),
tl::enums::Peer::Channel(c) => chat_map.get(&c.channel_id).cloned(),
_ => None,
});
Dialog {
raw: d,
message,
entity,
chat,
}
})
.collect();
Ok(result)
}
// Internal helper: fetch dialogs with a custom GetDialogs request.
// Like `get_messages` but also returns the total count from `messages.Slice`.
pub async fn delete_dialog(&self, peer: impl Into<PeerRef>) -> Result<(), InvocationError> {
let peer = peer.into().resolve(self).await?;
let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
let req = tl::functions::messages::DeleteHistory {
just_clear: false,
revoke: false,
peer: input_peer,
max_id: 0,
min_date: None,
max_date: None,
};
self.rpc_write(&req).await
}
/// Mark all messages in a chat as read.
pub async fn mark_as_read(&self, peer: impl Into<PeerRef>) -> Result<(), InvocationError> {
let peer = peer.into().resolve(self).await?;
let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
match &input_peer {
tl::enums::InputPeer::Channel(c) => {
let req = tl::functions::channels::ReadHistory {
channel: tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
channel_id: c.channel_id,
access_hash: c.access_hash,
}),
max_id: 0,
};
self.rpc_call_raw(&req).await?;
}
_ => {
let req = tl::functions::messages::ReadHistory {
peer: input_peer,
max_id: 0,
};
self.rpc_call_raw(&req).await?;
}
}
Ok(())
}
/// Clear unread mention markers.
pub async fn clear_mentions(&self, peer: impl Into<PeerRef>) -> Result<(), InvocationError> {
let peer = peer.into().resolve(self).await?;
let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
let req = tl::functions::messages::ReadMentions {
peer: input_peer,
top_msg_id: None,
};
self.rpc_write(&req).await
}
/// Join a public chat or channel by username/peer.
pub async fn join_chat(&self, peer: impl Into<PeerRef>) -> Result<(), InvocationError> {
let peer = peer.into().resolve(self).await?;
let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
match input_peer {
tl::enums::InputPeer::Channel(c) => {
let req = tl::functions::channels::JoinChannel {
channel: tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
channel_id: c.channel_id,
access_hash: c.access_hash,
}),
};
self.rpc_call_raw(&req).await?;
}
tl::enums::InputPeer::Chat(c) => {
let req = tl::functions::messages::AddChatUser {
chat_id: c.chat_id,
user_id: tl::enums::InputUser::UserSelf,
fwd_limit: 0,
};
self.rpc_call_raw(&req).await?;
}
_ => {
return Err(InvocationError::Deserialize(
"cannot join this peer type".into(),
));
}
}
Ok(())
}
/// Accept and join via an invite link.
pub async fn accept_invite_link(&self, link: &str) -> Result<(), InvocationError> {
let hash = Self::parse_invite_hash(link)
.ok_or_else(|| InvocationError::Deserialize(format!("invalid invite link: {link}")))?;
let req = tl::functions::messages::ImportChatInvite {
hash: hash.to_string(),
};
self.rpc_write(&req).await
}
/// Extract hash from `https://t.me/+HASH` or `https://t.me/joinchat/HASH`.
pub fn parse_invite_hash(link: &str) -> Option<&str> {
if let Some(pos) = link.find("/+") {
return Some(&link[pos + 2..]);
}
if let Some(pos) = link.find("/joinchat/") {
return Some(&link[pos + 10..]);
}
None
}
///
/// Returns a [`DialogIter`] that can be advanced with [`DialogIter::next`].
/// Lets you page through all dialogs without loading them all at once.
///
/// # Example
/// ```rust,no_run
/// # async fn f(client: ferogram::Client) -> Result<(), Box<dyn std::error::Error>> {
/// let mut iter = client.iter_dialogs();
/// while let Some(dialog) = iter.next(&client).await? {
/// println!("{}", dialog.title());
/// }
/// # Ok(()) }
/// ```
pub fn iter_dialogs(&self) -> DialogIter {
DialogIter {
offset_date: 0,
offset_id: 0,
offset_peer: tl::enums::InputPeer::Empty,
done: false,
buffer: VecDeque::new(),
total: None,
}
}
/// Fetch messages from a peer, page by page.
///
/// Returns a [`MessageIter`] that can be advanced with [`MessageIter::next`].
///
/// # Example
/// ```rust,no_run
/// # async fn f(client: ferogram::Client, peer: ferogram_tl_types::enums::Peer) -> Result<(), Box<dyn std::error::Error>> {
/// let mut iter = client.iter_messages(peer);
/// while let Some(msg) = iter.next(&client).await? {
/// println!("{:?}", msg.text());
/// }
/// # Ok(()) }
/// ```
pub fn iter_messages(&self, peer: impl Into<PeerRef>) -> MessageIter {
MessageIter {
unresolved: Some(peer.into()),
peer: None,
offset_id: 0,
done: false,
buffer: VecDeque::new(),
total: None,
}
}
/// Fetch all saved drafts across all chats.
///
/// The server responds with an `Updates` containing `updateDraftMessage`
/// entries; this method triggers that push and returns immediately.
pub async fn sync_drafts(&self) -> Result<(), InvocationError> {
let req = tl::functions::messages::GetAllDrafts {};
self.rpc_write(&req).await
}
/// Delete all saved drafts across all chats.
pub async fn clear_all_drafts(&self) -> Result<(), InvocationError> {
let req = tl::functions::messages::ClearAllDrafts {};
self.rpc_write(&req).await
}
/// Pin a dialog to the top of the dialog list.
pub async fn pin_dialog(&self, peer: impl Into<PeerRef>) -> Result<(), InvocationError> {
let peer = peer.into().resolve(self).await?;
let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
let req = tl::functions::messages::ToggleDialogPin {
pinned: true,
peer: tl::enums::InputDialogPeer::InputDialogPeer(tl::types::InputDialogPeer {
peer: input_peer,
}),
};
self.rpc_write(&req).await
}
/// Unpin a previously pinned dialog.
pub async fn unpin_dialog(&self, peer: impl Into<PeerRef>) -> Result<(), InvocationError> {
let peer = peer.into().resolve(self).await?;
let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
let req = tl::functions::messages::ToggleDialogPin {
pinned: false,
peer: tl::enums::InputDialogPeer::InputDialogPeer(tl::types::InputDialogPeer {
peer: input_peer,
}),
};
self.rpc_write(&req).await
}
/// Archive a dialog (move it to folder 1).
///
/// Archived chats are hidden from the main dialog list.
///
/// # Example
/// ```rust,no_run
/// # use ferogram::Client;
/// # async fn ex(client: Client) -> Result<(), Box<dyn std::error::Error>> {
/// client.archive_chat("@somebot").await?;
/// # Ok(()) }
/// ```
pub async fn archive_chat(&self, peer: impl Into<PeerRef>) -> Result<(), InvocationError> {
let peer = peer.into().resolve(self).await?;
let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
let req = tl::functions::folders::EditPeerFolders {
folder_peers: vec![tl::enums::InputFolderPeer::InputFolderPeer(
tl::types::InputFolderPeer {
peer: input_peer,
folder_id: 1,
},
)],
};
self.rpc_write(&req).await
}
/// Unarchive a dialog (move it back to folder 0 - the main list).
///
/// # Example
/// ```rust,no_run
/// # use ferogram::Client;
/// # async fn ex(client: Client) -> Result<(), Box<dyn std::error::Error>> {
/// client.unarchive_chat("@somebot").await?;
/// # Ok(()) }
/// ```
pub async fn unarchive_chat(&self, peer: impl Into<PeerRef>) -> Result<(), InvocationError> {
let peer = peer.into().resolve(self).await?;
let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
let req = tl::functions::folders::EditPeerFolders {
folder_peers: vec![tl::enums::InputFolderPeer::InputFolderPeer(
tl::types::InputFolderPeer {
peer: input_peer,
folder_id: 0,
},
)],
};
self.rpc_write(&req).await
}
/// Mark a dialog as read (clears the unread mark).
pub async fn mark_dialog_read(&self, peer: impl Into<PeerRef>) -> Result<(), InvocationError> {
self.set_dialog_unread_flag(peer, false).await
}
}