grammers_client/peer/user.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 std::fmt;
10
11use grammers_session::types::{PeerAuth, PeerId, PeerInfo, PeerRef};
12use grammers_tl_types as tl;
13
14use crate::Client;
15
16/// Platform Identifier referenced only by [`RestrictionReason`].
17#[non_exhaustive]
18pub enum Platform {
19 All,
20 Android,
21 Ios,
22 WindowsPhone,
23 Other(String),
24}
25
26/// Reason why a user is globally restricted.
27pub struct RestrictionReason {
28 pub platforms: Vec<Platform>,
29 pub reason: String,
30 pub text: String,
31}
32
33impl RestrictionReason {
34 pub fn from_raw(reason: &tl::enums::RestrictionReason) -> Self {
35 let tl::enums::RestrictionReason::Reason(reason) = reason;
36 Self {
37 platforms: reason
38 .platform
39 .split('-')
40 .map(|p| match p {
41 // Taken from https://core.telegram.org/constructor/restrictionReason
42 "all" => Platform::All,
43 "android" => Platform::Android,
44 "ios" => Platform::Ios,
45 "wp" => Platform::WindowsPhone,
46 o => Platform::Other(o.to_string()),
47 })
48 .collect(),
49 reason: reason.reason.to_string(),
50 text: reason.text.to_string(),
51 }
52 }
53}
54
55/// A user.
56///
57/// Users include your contacts, members of a group, bot accounts created by [@BotFather], or
58/// anyone with a Telegram account.
59///
60/// A "normal" (non-bot) user may also behave like a "bot" without actually being one, for
61/// example, when controlled with a program as opposed to being controlled by a human through
62/// a Telegram application. These are commonly known as "userbots", and some people use them
63/// to enhance their Telegram experience (for example, creating "commands" so that the program
64/// automatically reacts to them, like translating messages).
65///
66/// [@BotFather]: https://t.me/BotFather
67#[derive(Clone)]
68pub struct User {
69 pub raw: tl::enums::User,
70 pub(crate) client: Client,
71}
72
73impl fmt::Debug for User {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 self.raw.fmt(f)
76 }
77}
78
79// TODO: photo
80impl User {
81 pub fn from_raw(client: &Client, user: tl::enums::User) -> Self {
82 Self {
83 raw: user,
84 client: client.clone(),
85 }
86 }
87
88 pub(crate) fn user(&self) -> Option<&tl::types::User> {
89 match &self.raw {
90 tl::enums::User::User(u) => Some(u),
91 tl::enums::User::Empty(_) => None,
92 }
93 }
94
95 /// Return the user presence status (also known as "last seen").
96 pub fn status(&self) -> &grammers_tl_types::enums::UserStatus {
97 self.user()
98 .and_then(|u| u.status.as_ref())
99 .unwrap_or(&grammers_tl_types::enums::UserStatus::Empty)
100 }
101
102 /// Return the unique identifier for this user.
103 pub fn id(&self) -> PeerId {
104 PeerId::user_unchecked(self.raw.id())
105 }
106
107 /// Non-min auth stored in the user, if any.
108 pub(crate) fn auth(&self) -> Option<PeerAuth> {
109 let user = self.user()?;
110 user.access_hash
111 .filter(|_| !user.min)
112 .map(PeerAuth::from_hash)
113 }
114
115 /// Convert the user to its reference.
116 ///
117 /// This is only possible if the peer would be usable on all methods or if it is in the session cache.
118 pub async fn to_ref(
119 &self,
120 ) -> Result<Option<PeerRef>, Box<dyn std::error::Error + Send + Sync>> {
121 super::to_ref(&self.client, self.id(), self.auth()).await
122 }
123
124 /// Return the first name of this user.
125 ///
126 /// The name will be `None` if the account was deleted. It may also be `None` if you received
127 /// it previously.
128 pub fn first_name(&self) -> Option<&str> {
129 self.user().and_then(|u| u.first_name.as_deref())
130 }
131
132 /// Return the last name of this user, if any.
133 pub fn last_name(&self) -> Option<&str> {
134 self.user().and_then(|u| {
135 u.last_name
136 .as_deref()
137 .and_then(|name| if name.is_empty() { None } else { Some(name) })
138 })
139 }
140
141 /// Return the full name of this user.
142 ///
143 /// This is equal to the user's first name concatenated with the user's last name, if this
144 /// is not empty. Otherwise, it equals the user's first name.
145 pub fn full_name(&self) -> String {
146 let first_name = self.first_name().unwrap_or_default();
147 if let Some(last_name) = self.last_name() {
148 let mut name = String::with_capacity(first_name.len() + 1 + last_name.len());
149 name.push_str(first_name);
150 name.push(' ');
151 name.push_str(last_name);
152 name
153 } else {
154 first_name.to_string()
155 }
156 }
157
158 /// Return the public @username of this user, if any.
159 ///
160 /// The returned username does not contain the "@" prefix.
161 ///
162 /// Outside of the application, people may link to this user with one of Telegram's URLs, such
163 /// as https://t.me/username.
164 pub fn username(&self) -> Option<&str> {
165 self.user().and_then(|u| u.username.as_deref())
166 }
167
168 /// Return collectible usernames of this user, if any.
169 ///
170 /// The returned usernames do not contain the "@" prefix.
171 ///
172 /// Outside of the application, people may link to this user with one of its username, such
173 /// as https://t.me/username.
174 pub fn usernames(&self) -> Vec<&str> {
175 self.user()
176 .and_then(|u| u.usernames.as_deref())
177 .map_or(Vec::new(), |usernames| {
178 usernames
179 .iter()
180 .map(|username| match username {
181 tl::enums::Username::Username(username) => username.username.as_ref(),
182 })
183 .collect()
184 })
185 }
186
187 /// Return the phone number of this user, if they are not a bot and their privacy settings
188 /// allow you to see it.
189 pub fn phone(&self) -> Option<&str> {
190 self.user().and_then(|u| u.phone.as_deref())
191 }
192
193 /// Return the photo of this user, if any.
194 pub fn photo(&self) -> Option<&tl::types::UserProfilePhoto> {
195 match self.user().and_then(|u| u.photo.as_ref()) {
196 Some(maybe_photo) => match maybe_photo {
197 tl::enums::UserProfilePhoto::Empty => None,
198 tl::enums::UserProfilePhoto::Photo(photo) => Some(photo),
199 },
200 None => None,
201 }
202 }
203
204 /// Does this user represent the account that's currently logged in?
205 pub fn is_self(&self) -> bool {
206 // TODO if is_self is false, check in peer cache if id == ourself
207 self.user().map(|u| u.is_self).unwrap_or(false)
208 }
209
210 /// Is this user in your account's contact list?
211 pub fn contact(&self) -> bool {
212 self.user().map(|u| u.contact).unwrap_or(false)
213 }
214
215 /// Is this user a mutual contact?
216 ///
217 /// Contacts are mutual if both the user of the current account and this user have eachother
218 /// in their respective contact list.
219 pub fn mutual_contact(&self) -> bool {
220 self.user().map(|u| u.mutual_contact).unwrap_or(false)
221 }
222
223 /// Has the account of this user been deleted?
224 pub fn deleted(&self) -> bool {
225 self.user().map(|u| u.deleted).unwrap_or(false)
226 }
227
228 /// Is the current account a bot?
229 ///
230 /// Bot accounts are those created by [@BotFather](https://t.me/BotFather).
231 pub fn is_bot(&self) -> bool {
232 self.user().map(|u| u.bot).unwrap_or(false)
233 }
234
235 /// If the current user is a bot, does it have [privacy mode] enabled?
236 ///
237 /// * Bots with privacy enabled won't see messages in groups unless they are replied or the
238 /// command includes their name (`/command@bot`).
239 /// * Bots with privacy disabled will be able to see all messages in a group.
240 ///
241 /// [privacy mode]: https://core.telegram.org/bots#privacy-mode
242 pub fn bot_privacy(&self) -> bool {
243 self.user().map(|u| !u.bot_chat_history).unwrap_or(false)
244 }
245
246 /// If the current user is a bot, can it be added to groups?
247 pub fn bot_supports_chats(self) -> bool {
248 self.user().map(|u| u.bot_nochats).unwrap_or(false)
249 }
250
251 /// Has the account of this user been verified?
252 ///
253 /// Verified accounts, such as [@BotFather](https://t.me/BotFather), have a special icon next
254 /// to their names in official applications (commonly a blue starred checkmark).
255 pub fn verified(&self) -> bool {
256 self.user().map(|u| u.verified).unwrap_or(false)
257 }
258
259 /// Does this user have restrictions applied to their account?
260 pub fn restricted(&self) -> bool {
261 self.user().map(|u| u.restricted).unwrap_or(false)
262 }
263
264 /// If the current user is a bot, does it want geolocation information on inline queries?
265 pub fn bot_inline_geo(&self) -> bool {
266 self.user().map(|u| u.bot_inline_geo).unwrap_or(false)
267 }
268
269 /// Is this user an official member of the support team?
270 pub fn support(&self) -> bool {
271 self.user().map(|u| u.support).unwrap_or(false)
272 }
273
274 /// Has this user been flagged for trying to scam other people?
275 pub fn scam(&self) -> bool {
276 self.user().map(|u| u.scam).unwrap_or(false)
277 }
278
279 /// The reason(s) why this user is restricted, could be empty.
280 pub fn restriction_reason(&self) -> Vec<RestrictionReason> {
281 if let Some(reasons) = self.user().and_then(|u| u.restriction_reason.as_ref()) {
282 reasons.iter().map(RestrictionReason::from_raw).collect()
283 } else {
284 Vec::new()
285 }
286 }
287
288 /// Return the placeholder for inline queries if the current user is a bot and has said
289 /// placeholder configured.
290 pub fn bot_inline_placeholder(&self) -> Option<&str> {
291 self.user()
292 .and_then(|u| u.bot_inline_placeholder.as_deref())
293 }
294
295 /// Language code of the user, if any.
296 pub fn lang_code(&self) -> Option<&str> {
297 self.user().and_then(|u| u.lang_code.as_deref())
298 }
299}
300
301impl From<User> for PeerInfo {
302 #[inline]
303 fn from(user: User) -> Self {
304 <Self as From<&User>>::from(&user)
305 }
306}
307impl<'a> From<&'a User> for PeerInfo {
308 fn from(user: &'a User) -> Self {
309 <PeerInfo as From<&'a tl::enums::User>>::from(&user.raw)
310 }
311}