forked from RuslanUC/tgnet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tgnet.py
executable file
·335 lines (267 loc) · 10.5 KB
/
tgnet.py
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
from __future__ import annotations
from io import BytesIO
from os import PathLike
from typing import BinaryIO, Union, Optional, Literal
from tgnet import Headers, IP, AuthCredentials
from tgnet.low import TgnetSession, TgnetReader, Datacenter as LowDatacenter
from tgnet.utils import calcKeyId
AuthKeyType = Literal["perm", "temp", "media"]
class Datacenter:
def __init__(self, dc: LowDatacenter):
self._dc = dc
@property
def id(self) -> int:
"""
:return: This datacenter id
"""
return self._dc.datacenterId
@property
def low_datacenter(self) -> LowDatacenter:
"""
Underlying "low-level" datacenter object.
:return: Object of type tgnet.low.Datacenter
"""
return self._dc
def set_auth_key(self, key: Optional[bytes], type_: AuthKeyType = "perm") -> None:
"""
Used to set the authentication key for the datacenter.
:param key: The authentication key to be set. It can be None to reset the key.
:param type_: The type of authentication key to be set. It can be one of the following:
"perm": Permanent (primary) key.
"temp": Temporary key (see https://core.telegram.org/api/pfs).
"media": Media temp key.
:return: None
"""
if key is not None and len(key) != 256:
raise ValueError(f"Invalid auth key provided. Expected key of length 256.")
auth = self._dc.auth
if type_ == "perm":
auth.authKeyPerm = key
auth.authKeyPermId = calcKeyId(key)
auth.authorized = key is not None
elif type_ == "temp":
auth.authKeyTemp = key
auth.authKeyTempId = calcKeyId(key)
elif type_ == "media":
auth.authKeyMediaTemp = key
auth.authKeyMediaTempId = calcKeyId(key)
else:
raise ValueError(
f"Invalid auth key type provided. Expected one of (\"perm\", \"temp\", \"media\"), got {type_}."
)
def get_auth_key(self, type_: AuthKeyType) -> Optional[bytes]:
"""
Used to set the authentication key for the datacenter.
:param type_: The type of authentication key to get. It can be one of the following:
"perm": Permanent (primary) key.
"temp": Temporary key (see https://core.telegram.org/api/pfs).
"media": Media temp key.
:return: Auth key of the provided type if set, otherwise None
"""
auth = self._dc.auth
if type_ == "perm":
return auth.authKeyPerm
elif type_ == "temp":
return auth.authKeyTemp
elif type_ == "media":
return auth.authKeyMediaTemp
else:
raise ValueError(
f"Invalid auth key type provided. Expected one of (\"perm\", \"temp\", \"media\"), got {type_}."
)
def reset(self) -> None:
"""
Resets datacenter: clears all auth keys and salts.
:return: None
"""
auth = self._dc.auth
auth.authKeyPerm = None
auth.authKeyPermId = 0
auth.authKeyTemp = None
auth.authKeyTempId = 0
auth.authKeyMediaTemp = None
auth.authKeyMediaTempId = 0
auth.authorized = False
self._dc.salt = []
self._dc.saltMedia = []
class Tgnet:
__slots__ = ("_session", "_datacenters")
def __init__(self, file: Optional[Union[bytes, bytearray, str, PathLike, BinaryIO]] = None,
session: Optional[TgnetSession] = None):
if file is None and session is None:
raise ValueError(f"You need to pass either \"file\" or \"session\" to {self.__class__.__name__}.")
if session is None:
if isinstance(file, (bytes, bytearray)):
fp = BytesIO(file)
elif isinstance(file, BinaryIO):
fp = file
else:
fp = open(file, "rb")
session = TgnetSession.deserialize(TgnetReader(fp))
if not isinstance(file, (bytes, bytearray, BinaryIO)):
fp.close()
self._session = session
self._datacenters = [Datacenter(dc) for dc in self._session.datacenters]
def get_datacenter(self, dc: int) -> Optional[Datacenter]:
"""
Retrieves the datacenter with the provided dcId.
:param dc: The ID of the datacenter to retrieve.
:return: Datacenter if found, otherwise None
"""
if dc > len(self._datacenters) or dc < 0:
return
return self._datacenters[dc - 1]
@property
def current_datacenter(self) -> Optional[Datacenter]:
"""
Retrieves the current datacenter.
:return: Datacenter if current is set, otherwise None
"""
if (self._session.headers is None or not self._session.headers.full or not self._session.datacenters or
self._session.headers.currentDatacenterId == 0):
return
return self.get_datacenter(self._session.headers.currentDatacenterId)
@property
def auth_key(self) -> Optional[bytes]:
"""
Retrieves the auth key for the current datacenter.
:return: Auth key if the current datacenter is set and an auth key is set in it, otherwise None
"""
if not (dc := self.current_datacenter):
return
return dc.get_auth_key("perm")
def set_auth_key(self, dc: int, key: Optional[bytes], type_: Literal["perm", "temp", "media"] = "perm") -> None:
"""
Sets the authentication key for the datacenter.
:param dc: The id of the datacenter.
:param key: The authentication key to be set. It can be None to reset the key.
:param type_: The type of authentication key to be set. It can be one of the following:
"perm": Permanent (primary) key.
"temp": Temporary key (see https://core.telegram.org/api/pfs).
"media": Media temp key.
:return: None
"""
if (dc := self.get_datacenter(dc)) is None:
return
dc.set_auth_key(key, type_)
def set_current_dc(self, dc: int) -> None:
"""
Sets current datacenter id.
:param dc: The id of the datacenter to set.
:return: None
"""
if self.get_datacenter(dc) is None:
return
self._session.headers.currentDatacenterId = dc
def reset_dc(self, dc: int) -> None:
"""
Resets datacenter with given id: clears all auth keys and salts.
:param dc: The id of the datacenter to reset.
:return: None
"""
if (dc := self.get_datacenter(dc)) is None:
return
dc.reset()
def reset(self, new_current_dc: int = 2) -> None:
"""
Resets all datacenters: clears all auth keys and salts.
:param new_current_dc: The ID of the new current datacenter. Defaults to 2.
:return: None
"""
for dc in self._datacenters:
dc.reset()
headers = self._session.headers
headers.currentDatacenterId = new_current_dc
headers.timeDifference = 0
headers.lastDcUpdateTime = 0
headers.pushSessionId = 0
headers.registeredForInternalPush = False
headers.lastServerTime = 0
headers.currentTime = 0
headers.sessionsToDestroy = []
def save(self, file: Union[str, PathLike, BinaryIO]) -> None:
"""
Saves tgnet session to a file.
:param file: The file or file path to save tgnet session to.
:return: None
"""
if isinstance(file, BinaryIO):
fp = file
else:
fp = open(file, "wb")
self._session.serialize(TgnetReader(fp))
if not isinstance(file, BinaryIO):
fp.close()
@classmethod
def default(cls) -> Tgnet:
"""
:return: An instance of Tgnet with default settings.
"""
def _dc(id_: int, ips: list[list[IP]]) -> LowDatacenter:
while len(ips) < 4:
ips.append([])
return LowDatacenter(
currentVersion=13,
datacenterId=id_,
lastInitVersion=725,
lastInitMediaVersion=725,
ips=ips,
isCdnDatacenter=False,
auth=AuthCredentials(
authKeyPerm=None,
authKeyPermId=0,
authKeyTemp=None,
authKeyTempId=0,
authKeyMediaTemp=None,
authKeyMediaTempId=0,
authorized=0,
),
salt=[],
saltMedia=[],
)
def _ip(address: str, flags: int) -> IP:
return IP(address=address, port=443, flags=flags, secret="")
session = TgnetSession(
headers=Headers(
version=5,
testBackend=False,
clientBlocked=False,
lastInitSystemLangCode="en-us",
full=True,
currentDatacenterId=0,
timeDifference=0,
lastDcUpdateTime=0,
pushSessionId=0,
registeredForInternalPush=False,
lastServerTime=0,
currentTime=0,
sessionsToDestroy=[],
),
datacenters=[
_dc(1, [
[_ip("149.154.175.59", 0), _ip("149.154.175.55", 16)],
[_ip("2001:0b28:f23d:f001:0000:0000:0000:000a", 1)],
]),
_dc(2, [
[_ip("149.154.167.51", 0), _ip("149.154.167.41", 16)],
[_ip("2001:067c:04e8:f002:0000:0000:0000:000a", 1)],
[_ip("149.154.167.151", 2)],
[_ip("2001:067c:04e8:f002:0000:0000:0000:000b", 3)],
]),
_dc(3, [
[_ip("149.154.175.100", 0)],
[_ip("2001:0b28:f23d:f003:0000:0000:0000:000a", 1)],
]),
_dc(4, [
[_ip("149.154.167.92", 0)],
[_ip("2001:067c:04e8:f004:0000:0000:0000:000a", 1)],
[_ip("149.154.166.120", 2)],
[_ip("2001:067c:04e8:f004:0000:0000:0000:000b", 3)],
]),
_dc(5, [
[_ip("91.108.56.183", 0)],
[_ip("2001:0b28:f23f:f005:0000:0000:0000:000a", 1)],
]),
],
)
return cls(session=session)