1+ from encryption .crypto import Encryptor , Decryptor
2+ from config import secret , telegram_ips , mtproto_footprint , obf_footprint
3+ from exceptions import WrongServerID
4+ from protocols .telegram import TelegramProtocol
5+
6+
7+ class Dispatcher :
8+ def __init__ (self , loop , real_protocol ):
9+ self .loop = loop
10+ self .real_protocol = real_protocol
11+ self .telegram_protocol = None
12+ self .telegram_transport = None
13+ self .encryptor = None
14+ self .decryptor = None
15+
16+ async def handle (self , raw_data : bytes ):
17+ if not self .encryptor or not self .decryptor :
18+ self .decryptor = Decryptor (raw_data , secret )
19+ self .encryptor = Encryptor (raw_data , secret )
20+ self .decoded_data = await self .decryptor (raw_data )
21+ server_id = int .from_bytes (self .decoded_data [60 :62 ], 'little' ) - 1
22+ if server_id < 0 or server_id > len (telegram_ips ):
23+ raise WrongServerID (f'Got id { server_id } ' )
24+ self .telegram_server_ip = telegram_ips [server_id ]
25+ assert self .decoded_data [56 :60 ] == mtproto_footprint or self .decoded_data [56 :60 ] == obf_footprint , self .decoded_data [56 :60 ]
26+ if not self .telegram_protocol or not self .telegram_transport :
27+ self .telegram_transport , self .telegram_protocol = await self .loop .create_connection (lambda : TelegramProtocol (self .loop , self ),
28+ self .telegram_server_ip , 443 )
29+ self .telegram_transport .write (self .decoded_data )
30+ return
31+ self .telegram_transport .write (await self .decryptor (raw_data ))
32+
33+ async def reverse_handle (self , raw_data ):
34+ self .real_protocol .transport .write (await self .encryptor (raw_data ))
0 commit comments