4040from pyrogram import raw
4141from pyrogram import utils
4242from pyrogram .crypto import aes
43- from pyrogram .errors import CDNFileHashMismatch
43+ from pyrogram .errors import CDNFileHashMismatch , AuthBytesInvalid
4444from pyrogram .errors import (
4545 SessionPasswordNeeded ,
4646 VolumeLocNotFound , ChannelPrivate ,
@@ -820,7 +820,7 @@ async def get_file(
820820 offset : int = 0 ,
821821 progress : Callable = None ,
822822 progress_args : tuple = ()
823- ) -> Optional [ AsyncGenerator [bytes , None ] ]:
823+ ) -> AsyncGenerator [bytes , None ]:
824824 async with self .get_file_semaphore :
825825 file_type = file_id .file_type
826826
@@ -868,31 +868,40 @@ async def get_file(
868868
869869 dc_id = file_id .dc_id
870870
871- session = Session (
872- self , dc_id ,
873- await Auth (self , dc_id , await self .storage .test_mode ()).create ()
874- if dc_id != await self .storage .dc_id ()
875- else await self .storage .auth_key (),
876- await self .storage .test_mode (),
877- is_media = True
878- )
879-
880871 try :
881- await session .start ()
882-
883- if dc_id != await self .storage .dc_id ():
884- exported_auth = await self .invoke (
885- raw .functions .auth .ExportAuthorization (
886- dc_id = dc_id
887- )
872+ session = self .media_sessions .get (dc_id )
873+ if not session :
874+ session = self .media_sessions [dc_id ] = Session (
875+ self , dc_id ,
876+ await Auth (self , dc_id , await self .storage .test_mode ()).create ()
877+ if dc_id != await self .storage .dc_id ()
878+ else await self .storage .auth_key (),
879+ await self .storage .test_mode (),
880+ is_media = True
888881 )
882+ await session .start ()
889883
890- await session .invoke (
891- raw .functions .auth .ImportAuthorization (
892- id = exported_auth .id ,
893- bytes = exported_auth .bytes
894- )
895- )
884+ if dc_id != await self .storage .dc_id ():
885+ for _ in range (3 ):
886+ exported_auth = await self .invoke (
887+ raw .functions .auth .ExportAuthorization (
888+ dc_id = dc_id
889+ )
890+ )
891+
892+ try :
893+ await session .invoke (
894+ raw .functions .auth .ImportAuthorization (
895+ id = exported_auth .id ,
896+ bytes = exported_auth .bytes
897+ )
898+ )
899+ except AuthBytesInvalid :
900+ continue
901+ else :
902+ break
903+ else :
904+ raise AuthBytesInvalid
896905
897906 r = await session .invoke (
898907 raw .functions .upload .GetFile (
@@ -1025,8 +1034,6 @@ async def get_file(
10251034 raise
10261035 except Exception as e :
10271036 log .exception (e )
1028- finally :
1029- await session .stop ()
10301037
10311038 def guess_mime_type (self , filename : str ) -> Optional [str ]:
10321039 return self .mimetypes .guess_type (filename )[0 ]
@@ -1051,4 +1058,4 @@ def __setitem__(self, key, value):
10511058
10521059 if len (self .store ) > self .capacity :
10531060 for _ in range (self .capacity // 2 + 1 ):
1054- del self .store [next (iter (self .store ))]
1061+ del self .store [next (iter (self .store ))]
0 commit comments