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
// Copyright 2020 - developers of the `grammers` project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::types;
use chrono::{DateTime, NaiveDateTime, Utc};
use grammers_session::{PackedChat, PackedType};
use grammers_tl_types as tl;
use log::trace;
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::SystemTime;

// This atomic isn't for anything critical, just to generate unique IDs without locks.
// The worst that can happen if the load and store orderings are wrong is that the IDs
// are not actually unique which could confuse some of the API results.
static LAST_ID: AtomicI64 = AtomicI64::new(0);

pub(crate) type Date = DateTime<Utc>;

/// Generate a "random" ID suitable for sending messages or media.
pub(crate) fn generate_random_id() -> i64 {
    if LAST_ID.load(Ordering::SeqCst) == 0 {
        let now = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .expect("system time is before epoch")
            .as_nanos() as i64;

        LAST_ID
            .compare_exchange(0, now, Ordering::SeqCst, Ordering::SeqCst)
            .unwrap();
    }

    LAST_ID.fetch_add(1, Ordering::SeqCst)
}

pub(crate) fn generate_random_ids(n: usize) -> Vec<i64> {
    (0..n).map(|_| generate_random_id()).collect()
}

pub(crate) fn date(date: i32) -> Date {
    DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(date as i64, 0), Utc)
}

pub(crate) fn extract_password_parameters(
    current_algo: &tl::enums::PasswordKdfAlgo,
) -> (&Vec<u8>, &Vec<u8>, &i32, &Vec<u8>) {
    let tl::types::PasswordKdfAlgoSha256Sha256Pbkdf2Hmacsha512iter100000Sha256ModPow { salt1, salt2, g, p } = match current_algo {
        tl::enums::PasswordKdfAlgo::Unknown => panic!("Unknown KDF (most likely, the client is outdated and does not support the specified KDF algorithm)"),
        tl::enums::PasswordKdfAlgo::Sha256Sha256Pbkdf2Hmacsha512iter100000Sha256ModPow(alg) => alg,
    };
    (salt1, salt2, g, p)
}

/// Get a `Chat`, no matter what.
///
/// If necessary, `access_hash` of `0` will be returned, but *something* will be returned.
///
/// If the `Chat` is `min`, attempt to update its `access_hash` to the non-`min` version.
pub(crate) fn always_find_entity(
    peer: &tl::enums::Peer,
    map: &types::ChatMap,
    client: &crate::Client,
) -> types::Chat {
    let get_packed = || {
        let (id, ty) = match peer {
            tl::enums::Peer::User(user) => (user.user_id, PackedType::User),
            tl::enums::Peer::Chat(chat) => (chat.chat_id, PackedType::Chat),
            tl::enums::Peer::Channel(channel) => (channel.channel_id, PackedType::Broadcast),
        };
        client
            .0
            .chat_hashes
            .lock("always_find_entity")
            .get(id)
            .unwrap_or(PackedChat {
                ty,
                id,
                access_hash: None,
            })
    };

    match map.get(peer).cloned() {
        Some(mut chat) => {
            // As a best-effort, attempt to replace any `min` `access_hash` with the non-`min`
            // version. The `min` hash is only usable to download profile photos (if the user
            // tried to pack it for later use, like sending a message, it would fail).
            if let Some((min, access_hash)) = chat.get_min_hash_ref() {
                let packed = get_packed();
                if let Some(ah) = packed.access_hash {
                    *access_hash = ah;
                    *min = false;
                }
            }
            chat
        }
        None => types::Chat::unpack(get_packed()),
    }
}

pub(crate) struct Mutex<T: ?Sized> {
    name: &'static str,
    mutex: std::sync::Mutex<T>,
}

pub(crate) struct MutexGuard<'a, T: ?Sized> {
    name: &'static str,
    reason: &'static str,
    guard: std::sync::MutexGuard<'a, T>,
}

impl<T> Mutex<T> {
    pub fn new(name: &'static str, value: T) -> Self {
        Self {
            name,
            mutex: std::sync::Mutex::new(value),
        }
    }

    pub fn lock(&self, reason: &'static str) -> MutexGuard<T> {
        trace!("locking {} for {}", self.name, reason);
        MutexGuard {
            name: self.name,
            reason,
            guard: self.mutex.lock().unwrap(),
        }
    }
}

impl<T: ?Sized + std::fmt::Debug> std::fmt::Debug for Mutex<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.mutex.fmt(f)
    }
}

impl<T: ?Sized> std::ops::Deref for MutexGuard<'_, T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.guard.deref()
    }
}

impl<T: ?Sized> std::ops::DerefMut for MutexGuard<'_, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.guard.deref_mut()
    }
}

impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> {
    fn drop(&mut self) {
        trace!("unlocking {} for {}", self.name, self.reason);
    }
}

pub(crate) struct AsyncMutex<T: ?Sized> {
    name: &'static str,
    mutex: tokio::sync::Mutex<T>,
}

pub(crate) struct AsyncMutexGuard<'a, T: ?Sized> {
    name: &'static str,
    reason: &'static str,
    guard: tokio::sync::MutexGuard<'a, T>,
}

impl<T> AsyncMutex<T> {
    pub fn new(name: &'static str, value: T) -> Self {
        Self {
            name,
            mutex: tokio::sync::Mutex::new(value),
        }
    }

    pub fn try_lock<'a>(
        &'a self,
        reason: &'static str,
    ) -> Result<AsyncMutexGuard<'a, T>, tokio::sync::TryLockError> {
        let guard = self.mutex.try_lock();
        trace!(
            "try-async-locking {} for {} ({})",
            self.name,
            reason,
            if guard.is_ok() { "success" } else { "failure" }
        );
        guard.map(|guard| AsyncMutexGuard {
            name: self.name,
            reason,
            guard,
        })
    }

    pub async fn lock<'a>(&'a self, reason: &'static str) -> AsyncMutexGuard<'a, T> {
        trace!("async-locking {} for {}", self.name, reason);
        AsyncMutexGuard {
            name: self.name,
            reason,
            guard: self.mutex.lock().await,
        }
    }
}

impl<T: ?Sized> std::ops::Deref for AsyncMutexGuard<'_, T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.guard.deref()
    }
}

impl<T: ?Sized> std::ops::DerefMut for AsyncMutexGuard<'_, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.guard.deref_mut()
    }
}

impl<'a, T: ?Sized> Drop for AsyncMutexGuard<'a, T> {
    fn drop(&mut self) {
        trace!("async-unlocking {} for {}", self.name, self.reason);
    }
}