From f081731eb1a5db225e4524d1cb9f1fcaf9dcb582 Mon Sep 17 00:00:00 2001 From: SmaGMan Date: Tue, 2 Nov 2021 09:42:53 +0100 Subject: [PATCH 1/3] use cached auth when returning to previously used dc --- src/TgSharp.Core/TelegramClient.cs | 51 ++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 10 deletions(-) diff --git a/src/TgSharp.Core/TelegramClient.cs b/src/TgSharp.Core/TelegramClient.cs index ceae05e0..05025b7c 100644 --- a/src/TgSharp.Core/TelegramClient.cs +++ b/src/TgSharp.Core/TelegramClient.cs @@ -37,6 +37,8 @@ public class TelegramClient : IDisposable public Session Session { get; private set; } + private Dictionary> authCache; + /// /// Creates a new TelegramClient /// @@ -68,6 +70,8 @@ public TelegramClient(int apiId, string apiHash, this.dcIpVersion = dcIpVersion; this.sessionUserId = sessionUserId; + + this.authCache = new Dictionary>(); } public async Task ConnectAsync (CancellationToken token = default (CancellationToken)) @@ -79,7 +83,9 @@ public TelegramClient(int apiId, string apiHash, { token.ThrowIfCancellationRequested(); - Session = SessionFactory.TryLoadOrCreateNew (store, sessionUserId); + if (Session == null) { + Session = SessionFactory.TryLoadOrCreateNew (store, sessionUserId); + } transport = new TcpTransport (Session.DataCenter.Address, Session.DataCenter.Port, this.handler); if (Session.AuthKey == null || reconnect) @@ -109,6 +115,15 @@ public TelegramClient(int apiId, string apiHash, await sender.Receive(invokewithLayer, token).ConfigureAwait(false); dcOptions = ((TLConfig)invokewithLayer.Response).DcOptions.ToList(); + + // determine the current dc id + if (Session.DataCenter.DataCenterId == null) { + var currDc = dcOptions.FirstOrDefault(d => d.IpAddress == Session.DataCenter.Address && d.Port == Session.DataCenter.Port); + if (currDc != null) { + Session.DataCenter = new DataCenter(currDc.Id, Session.DataCenter.Address, Session.DataCenter.Port); + this.store.Save(Session); + } + } } private async Task ReconnectToDcAsync(int dcId, CancellationToken token = default(CancellationToken)) @@ -118,8 +133,15 @@ public TelegramClient(int apiId, string apiHash, if (dcOptions == null || !dcOptions.Any()) throw new InvalidOperationException($"Can't reconnect. Establish initial connection first."); + // cache the current auth + if (Session.DataCenter.DataCenterId.HasValue) { + authCache[Session.DataCenter.DataCenterId.Value] = + new Tuple(Session.TLUser, Session.AuthKey, Session.TimeOffset); + } + + // export auth only if there is no cached one TLExportedAuthorization exported = null; - if (Session.TLUser != null) + if (Session.TLUser != null && !authCache.ContainsKey(dcId)) { TLRequestExportAuthorization exportAuthorization = new TLRequestExportAuthorization() { DcId = dcId }; exported = await SendRequestAsync(exportAuthorization, token).ConfigureAwait(false); @@ -148,15 +170,24 @@ public TelegramClient(int apiId, string apiHash, var dataCenter = new DataCenter (dcId, dc.IpAddress, dc.Port); Session.DataCenter = dataCenter; - this.store.Save (Session); - await ConnectInternalAsync(true, token).ConfigureAwait(false); - - if (Session.TLUser != null) - { - TLRequestImportAuthorization importAuthorization = new TLRequestImportAuthorization() { Id = exported.Id, Bytes = exported.Bytes }; - var imported = await SendRequestAsync(importAuthorization, token).ConfigureAwait(false); - OnUserAuthenticated((TLUser)imported.User); + Tuple cachedAuth; + if (authCache.TryGetValue(dcId, out cachedAuth)) { + // use cached auth if exists + Session.AuthKey = cachedAuth.Item2; + Session.TimeOffset = cachedAuth.Item3; + await ConnectInternalAsync(false, token).ConfigureAwait(false); + OnUserAuthenticated(cachedAuth.Item1); + + } else { + await ConnectInternalAsync(true, token).ConfigureAwait(false); + + // otherwise import the previously exported auth + if (Session.TLUser != null) { + TLRequestImportAuthorization importAuthorization = new TLRequestImportAuthorization() { Id = exported.Id, Bytes = exported.Bytes }; + var imported = await SendRequestAsync(importAuthorization, token).ConfigureAwait(false); + OnUserAuthenticated((TLUser)imported.User); + } } } From 155e4a59bd33bf6fe7a1ffbba3bc03f9949d0998 Mon Sep 17 00:00:00 2001 From: SmaGMan Date: Tue, 2 Nov 2021 09:58:38 +0100 Subject: [PATCH 2/3] added the message param to the SendUploadedDocument method --- README.md | 14 ++++++++++++++ src/TgSharp.Core/TelegramClient.cs | 3 ++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4e58ce11..a64fa9f1 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,7 @@ TgSharp provides two wrappers for sending photo and document: await client.SendUploadedDocument(new TLInputPeerUser() { UserId = user.Id }, fileResult, "application/zip", //mime-type + "kitty", // message text //document attributes, such as file name new TLVector()); @@ -134,6 +135,7 @@ You can see the Full code at [SendPhotoToContactTest](https://github.com/nblockc To download a file you should call the **GetFile** method: ```csharp + // get documnet await client.GetFile(new TLInputDocumentFileLocation() { AccessHash = document.AccessHash, @@ -144,6 +146,18 @@ To download a file you should call the **GetFile** method: //size of fileChunk you want to retrieve document.Size); + // get photo + TLPhotoSize photoSize = photo.Sizes.ToList().OfType().Last(); + await client.GetFile(new TLInputPhotoFileLocation() + { + AccessHash = photo.AccessHash, + Id = photo.Id, + FileReference = photo.FileReference, + ThumbSize = photoSize.Type, + }, + + //size of fileChunk you want to retrieve + photoSize.Size); ``` You can see the Full code at [DownloadFileFromContactTest](https://github.com/nblockchain/TgSharp/blob/master/src/TgSharp.Tests/TgSharpTests.cs#L167) diff --git a/src/TgSharp.Core/TelegramClient.cs b/src/TgSharp.Core/TelegramClient.cs index 05025b7c..b37617bb 100644 --- a/src/TgSharp.Core/TelegramClient.cs +++ b/src/TgSharp.Core/TelegramClient.cs @@ -382,7 +382,7 @@ public bool IsUserAuthorized() } public async Task SendUploadedDocument( - TLAbsInputPeer peer, TLAbsInputFile file, string mimeType, TLVector attributes, CancellationToken token = default(CancellationToken)) + TLAbsInputPeer peer, TLAbsInputFile file, string message, string mimeType, TLVector attributes, CancellationToken token = default(CancellationToken)) { return await SendAuthenticatedRequestAsync(new TLRequestSendMedia() { @@ -395,6 +395,7 @@ public async Task SendUploadedDocument( MimeType = mimeType, Attributes = attributes }, + Message = message, Peer = peer }, token) .ConfigureAwait(false); From 0805f8cb192d9f3c3e3a9832ad67d0d56ed35c4c Mon Sep 17 00:00:00 2001 From: SmaGMan Date: Tue, 2 Nov 2021 10:06:05 +0100 Subject: [PATCH 3/3] fixed tests --- src/TgSharp.Tests/TgSharpTests.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/TgSharp.Tests/TgSharpTests.cs b/src/TgSharp.Tests/TgSharpTests.cs index 2212cdeb..e3bcd729 100644 --- a/src/TgSharp.Tests/TgSharpTests.cs +++ b/src/TgSharp.Tests/TgSharpTests.cs @@ -226,6 +226,7 @@ public virtual async Task SendBigFileToContactTest() await client.SendUploadedDocument( new TLInputPeerUser() { UserId = user.Id }, fileResult, + "some file", "application/zip", new TLVector()); }