From 8c2cab48f4d2e73d50f29119bf86424a8ef8676d Mon Sep 17 00:00:00 2001 From: Afshin Arani Date: Wed, 26 Oct 2016 20:13:19 +0330 Subject: [PATCH 01/26] Change TLDialogs to TLAbsDialogs --- TLSharp.Core/TelegramClient.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TLSharp.Core/TelegramClient.cs b/TLSharp.Core/TelegramClient.cs index eeb72b5..816c053 100644 --- a/TLSharp.Core/TelegramClient.cs +++ b/TLSharp.Core/TelegramClient.cs @@ -196,10 +196,10 @@ namespace TLSharp.Core return await SendRequestAsync(req); } - public async Task GetUserDialogsAsync() + public async Task GetUserDialogsAsync() { var peer = new TLInputPeerSelf(); - return await SendRequestAsync( + return await SendRequestAsync( new TLRequestGetDialogs() { offset_date = 0, offset_peer = peer, limit = 100 }); } From bc24dbfd6541e6065e6c010257ed770bbb038e3b Mon Sep 17 00:00:00 2001 From: Afshin Arani Date: Wed, 26 Oct 2016 20:15:33 +0330 Subject: [PATCH 02/26] Update TLSharpTests.cs --- TLSharp.Tests/TLSharpTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TLSharp.Tests/TLSharpTests.cs b/TLSharp.Tests/TLSharpTests.cs index ccd88f1..5da31bb 100644 --- a/TLSharp.Tests/TLSharpTests.cs +++ b/TLSharp.Tests/TLSharpTests.cs @@ -141,7 +141,7 @@ namespace TLSharp.Tests await client.ConnectAsync(); - var dialogs = await client.GetUserDialogsAsync(); + var dialogs = (TLDialogs) await client.GetUserDialogsAsync(); var chat = dialogs.chats.lists .Where(c => c.GetType() == typeof(TLChannel)) .Cast() From df66bfb6e30e88a8cfa84124053a14cd814cde81 Mon Sep 17 00:00:00 2001 From: Ilya P Date: Sat, 29 Oct 2016 09:53:45 +0300 Subject: [PATCH 03/26] bug-fix --- TeleSharp.TL/TLVector.cs | 47 ++++++++++++++++++++++++++++++---------- 1 file changed, 36 insertions(+), 11 deletions(-) diff --git a/TeleSharp.TL/TLVector.cs b/TeleSharp.TL/TLVector.cs index 8f35b7d..bf3d025 100644 --- a/TeleSharp.TL/TLVector.cs +++ b/TeleSharp.TL/TLVector.cs @@ -10,7 +10,7 @@ namespace TeleSharp.TL public class TLVector : TLObject { [TLObject(481674261)] - public List lists = new List() ; + public List lists = new List(); public override int Constructor { get @@ -22,21 +22,21 @@ namespace TeleSharp.TL public override void DeserializeBody(BinaryReader br) { int count = br.ReadInt32(); - for(int i= 0;i< count;i++) + for (var i = 0; i < count; i++) { if (typeof(T) == typeof(int)) { - lists.Add((T)Convert.ChangeType(br.ReadInt32(),typeof(T))); + lists.Add((T)Convert.ChangeType(br.ReadInt32(), typeof(T))); } - else if (typeof(T)==typeof(long)) + else if (typeof(T) == typeof(long)) { lists.Add((T)Convert.ChangeType(br.ReadInt64(), typeof(T))); } - else if (typeof(T) ==typeof(string)) + else if (typeof(T) == typeof(string)) { lists.Add((T)Convert.ChangeType(StringUtil.Deserialize(br), typeof(T))); } - else if(typeof(T)==typeof(double)) + else if (typeof(T) == typeof(double)) { lists.Add((T)Convert.ChangeType(br.ReadDouble(), typeof(T))); } @@ -53,13 +53,38 @@ namespace TeleSharp.TL public override void SerializeBody(BinaryWriter bw) { - bw.Write(Constructor); + bw.Write(Constructor); bw.Write(lists.Count()); - foreach (var item in lists.Cast()) - { - item.SerializeBody(bw); - } + foreach (var item in lists) + { + if (typeof(T) == typeof(int)) + { + var res = (int)Convert.ChangeType(item, typeof(int)); + + bw.Write(res); + } + else if (typeof(T) == typeof(long)) + { + var res = (long)Convert.ChangeType(item, typeof(long)); + bw.Write(res); + } + else if (typeof(T) == typeof(string)) + { + var res = (string)(Convert.ChangeType(item, typeof(string))); + StringUtil.Serialize(res, bw); + } + else if (typeof(T) == typeof(double)) + { + var res = (double)Convert.ChangeType(item, typeof(double)); + bw.Write(res); + } + else if (typeof(T).BaseType == typeof(TLObject)) + { + var res = (TLObject) (Convert.ChangeType(item, typeof (TLObject))); + res.SerializeBody(bw); + } + } } } } From b06f8a8e1174f0d2580f36039054adb25d62403e Mon Sep 17 00:00:00 2001 From: Ilya P Date: Sat, 29 Oct 2016 11:47:18 +0300 Subject: [PATCH 04/26] Added File-Migrate feature --- TLSharp.Core/Network/MtProtoSender.cs | 34 +++++++++++++++ TLSharp.Core/TelegramClient.cs | 59 +++++++++++++++++++++------ TLSharp.Tests/TLSharpTests.cs | 30 ++++++++++++++ 3 files changed, 110 insertions(+), 13 deletions(-) diff --git a/TLSharp.Core/Network/MtProtoSender.cs b/TLSharp.Core/Network/MtProtoSender.cs index a8fd1ed..1f22aeb 100644 --- a/TLSharp.Core/Network/MtProtoSender.cs +++ b/TLSharp.Core/Network/MtProtoSender.cs @@ -281,6 +281,18 @@ namespace TLSharp.Core.Network var dcIdx = int.Parse(resultString); throw new MigrationNeededException(dcIdx); } + else if (errorMessage.StartsWith("FILE_MIGRATE_")) + { + var resultString = Regex.Match(errorMessage, @"\d+").Value; + var dcIdx = int.Parse(resultString); + throw new FileMigrationException(dcIdx); + } + else if (errorMessage.StartsWith("USER_MIGRATE_")) + { + var resultString = Regex.Match(errorMessage, @"\d+").Value; + var dcIdx = int.Parse(resultString); + throw new UserMigrationException(dcIdx); + } else { throw new InvalidOperationException(errorMessage); @@ -493,4 +505,26 @@ namespace TLSharp.Core.Network DC = dc; } } + + internal class FileMigrationException : Exception + { + internal int DC { get; private set; } + + internal FileMigrationException(int dc) + : base ($"File is located on a different DC: {dc}. Please migrate.") + { + DC = dc; + } + } + + internal class UserMigrationException : Exception + { + internal int DC { get; private set; } + + internal UserMigrationException(int dc) + : base($"User is located on a different DC: {dc}. Please migrate.") + { + DC = dc; + } + } } \ No newline at end of file diff --git a/TLSharp.Core/TelegramClient.cs b/TLSharp.Core/TelegramClient.cs index 816c053..0c6f3c7 100644 --- a/TLSharp.Core/TelegramClient.cs +++ b/TLSharp.Core/TelegramClient.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Threading.Tasks; using System.Web; using TeleSharp.TL; +using TeleSharp.TL.Account; using TeleSharp.TL.Auth; using TeleSharp.TL.Contacts; using TeleSharp.TL.Help; @@ -14,6 +15,7 @@ using TLSharp.Core.MTProto.Crypto; using TLSharp.Core.Network; using TLSharp.Core.Requests; using TLSharp.Core.Utils; +using TLAuthorization = TeleSharp.TL.Auth.TLAuthorization; namespace TLSharp.Core { @@ -152,12 +154,12 @@ namespace TLSharp.Core return ((TLUser)request.Response.user); } - public async Task SendRequestAsync(TLMethod methodtoExceute) + public async Task SendRequestAsync(TLMethod methodToExecute) { - await _sender.Send(methodtoExceute); - await _sender.Receive(methodtoExceute); - - var result = methodtoExceute.GetType().GetProperty("Response").GetValue(methodtoExceute); + await _sender.Send(methodToExecute); + await _sender.Receive(methodToExecute); + + var result = methodToExecute.GetType().GetProperty("Response").GetValue(methodToExecute); return (T)result; } @@ -204,7 +206,7 @@ namespace TLSharp.Core } public async Task SendUploadedPhoto(TLAbsInputPeer peer, TLAbsInputFile file, string caption) - { + { return await SendRequestAsync(new TLRequestSendMedia() { random_id = Helpers.GenerateRandomLong(), @@ -218,7 +220,7 @@ namespace TLSharp.Core public async Task SendUploadedDocument( TLAbsInputPeer peer, TLAbsInputFile file, string caption, string mimeType, TLVector attributes) { - return await SendRequestAsync(new TLRequestSendMedia() + return await SendRequestAsync(new TLRequestSendMedia() { random_id = Helpers.GenerateRandomLong(), background = false, @@ -236,12 +238,43 @@ namespace TLSharp.Core public async Task GetFile(TLAbsInputFileLocation location, int filePartSize) { - return await SendRequestAsync(new TLRequestGetFile() + TLFile result = null; + try { - location = location, - limit = filePartSize - }); - } + result = await SendRequestAsync(new TLRequestGetFile() + { + location = location, + limit = filePartSize + }); + } + catch (FileMigrationException ex) + { + var exportedAuth = await SendRequestAsync(new TLRequestExportAuthorization() { dc_id = ex.DC }); + + var authKey = _session.AuthKey; + var timeOffset = _session.TimeOffset; + var serverAddress = _session.ServerAddress; + var serverPort = _session.Port; + + await ReconnectToDcAsync(ex.DC); + var auth = await SendRequestAsync(new TLRequestImportAuthorization + { + bytes = exportedAuth.bytes, + id = exportedAuth.id + }); + result = await GetFile(location, filePartSize); + + _session.AuthKey = authKey; + _session.TimeOffset = timeOffset; + _transport = new TcpTransport(serverAddress, serverPort); + _session.ServerAddress =serverAddress; + _session.Port = serverPort; + await ConnectAsync(); + + } + + return result; + } private void OnUserAuthenticated(TLUser TLUser) { @@ -256,7 +289,7 @@ namespace TLSharp.Core { public const string InfoUrl = "https://github.com/sochix/TLSharp#quick-configuration"; - internal MissingApiConfigurationException(string invalidParamName): + internal MissingApiConfigurationException(string invalidParamName) : base($"Your {invalidParamName} setting is missing. Adjust the configuration first, see {InfoUrl}") { } diff --git a/TLSharp.Tests/TLSharpTests.cs b/TLSharp.Tests/TLSharpTests.cs index 5da31bb..bb3284d 100644 --- a/TLSharp.Tests/TLSharpTests.cs +++ b/TLSharp.Tests/TLSharpTests.cs @@ -231,6 +231,36 @@ namespace TLSharp.Tests Assert.IsTrue(resFile.bytes.Length > 0); } + + [TestMethod] + public async Task DownloadFileFromWrongLocationTest() + { + var client = NewClient(); + + await client.ConnectAsync(); + + var result = await client.GetContactsAsync(); + + var user = result.users.lists + .Where(x => x.GetType() == typeof(TLUser)) + .Cast() + .FirstOrDefault(x => x.id == 5880094); + + var photo = ((TLUserProfilePhoto)user.photo); + var photoLocation = (TLFileLocation) photo.photo_big; + + var resFile = await client.GetFile(new TLInputFileLocation() + { + local_id = photoLocation.local_id, + secret = photoLocation.secret, + volume_id = photoLocation.volume_id + }, 1024); + + var res = await client.GetUserDialogsAsync(); + + Assert.IsTrue(resFile.bytes.Length > 0); + } + [TestMethod] public async Task SignUpNewUser() { From 0d078132993919c0807198503e8df2bcf8ec2252 Mon Sep 17 00:00:00 2001 From: Ilya Pirozhenko Date: Sat, 29 Oct 2016 11:48:22 +0300 Subject: [PATCH 05/26] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bc3ff4c..72e687c 100644 --- a/README.md +++ b/README.md @@ -187,7 +187,7 @@ Contributing is highly appreciated! ### Release 1.0.0 * [DONE] Add PHONE_MIGRATE handling -* Add FILE_MIGRATE handling +* [DONE]Add FILE_MIGRATE handling * Add Updates handling * Add NuGet package * [DONE] Add wrappers for media uploading and downloading From f1ea21c5b69395f7425613564c9faef407cb1be9 Mon Sep 17 00:00:00 2001 From: Ilya P Date: Sat, 29 Oct 2016 15:02:00 +0300 Subject: [PATCH 06/26] Added nuspec --- TLSharp.nuspec | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 TLSharp.nuspec diff --git a/TLSharp.nuspec b/TLSharp.nuspec new file mode 100644 index 0000000..705d441 --- /dev/null +++ b/TLSharp.nuspec @@ -0,0 +1,25 @@ + + + + TLSharp + 0.$APPVEYOR_BUILD_VERSION$ + Telegram client library implemented in C# + Ilya P + Ilya P + http://sochix.github.io/TLSharp/ + https://core.telegram.org/favicon.ico + false + Unofficial Telegram (http://telegram.org) client library implemented in C#. Latest TL scheme supported. + +Consider donation to speed up development process. + +Bitcoin wallet: 3K1ocweFgaHnAibJ3n6hX7RNZWFTFcJjUe + +It's a perfect fit for any developer who would like to send data directly to Telegram users or write own custom Telegram client. + telegram client, telegram API + Copyright 2016 + + + + + \ No newline at end of file From d6ecbd6653cf4696ccc70866e411b30d91525047 Mon Sep 17 00:00:00 2001 From: Ilya P Date: Sat, 29 Oct 2016 15:29:03 +0300 Subject: [PATCH 07/26] Update nuspec --- TLSharp.nuspec | 3 +++ 1 file changed, 3 insertions(+) diff --git a/TLSharp.nuspec b/TLSharp.nuspec index 705d441..fa9c455 100644 --- a/TLSharp.nuspec +++ b/TLSharp.nuspec @@ -20,6 +20,9 @@ It's a perfect fit for any developer who would like to send data directly to Tel Copyright 2016 + + + \ No newline at end of file From 46694e2406cfe643fb0a6cca457a36f30ffbb8a2 Mon Sep 17 00:00:00 2001 From: Ilya P Date: Sat, 29 Oct 2016 15:34:01 +0300 Subject: [PATCH 08/26] Moved nuspec to a proper place --- TLSharp.nuspec => TLSharp.Core/TLSharp.Core.nuspec | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename TLSharp.nuspec => TLSharp.Core/TLSharp.Core.nuspec (100%) diff --git a/TLSharp.nuspec b/TLSharp.Core/TLSharp.Core.nuspec similarity index 100% rename from TLSharp.nuspec rename to TLSharp.Core/TLSharp.Core.nuspec From 58d83cfcfeed2b2421c0a4f2e46d0952c9affa5f Mon Sep 17 00:00:00 2001 From: Ilya P Date: Sat, 29 Oct 2016 17:05:40 +0300 Subject: [PATCH 09/26] Path fix --- TLSharp.Core/TLSharp.Core.nuspec | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TLSharp.Core/TLSharp.Core.nuspec b/TLSharp.Core/TLSharp.Core.nuspec index fa9c455..a39bcde 100644 --- a/TLSharp.Core/TLSharp.Core.nuspec +++ b/TLSharp.Core/TLSharp.Core.nuspec @@ -20,9 +20,9 @@ It's a perfect fit for any developer who would like to send data directly to Tel Copyright 2016 - + - + \ No newline at end of file From d692196dce355dd5ed3486054d81db41dae8a0e8 Mon Sep 17 00:00:00 2001 From: Ilya P Date: Sat, 29 Oct 2016 17:13:28 +0300 Subject: [PATCH 10/26] another fix --- TLSharp.Core/TLSharp.Core.nuspec | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/TLSharp.Core/TLSharp.Core.nuspec b/TLSharp.Core/TLSharp.Core.nuspec index a39bcde..921a4e2 100644 --- a/TLSharp.Core/TLSharp.Core.nuspec +++ b/TLSharp.Core/TLSharp.Core.nuspec @@ -20,9 +20,9 @@ It's a perfect fit for any developer who would like to send data directly to Tel Copyright 2016 - - - - + + + + \ No newline at end of file From 8c0ce7ac39aba3fce0efac95d648baca45361a20 Mon Sep 17 00:00:00 2001 From: Ilya Pirozhenko Date: Sat, 29 Oct 2016 17:31:08 +0300 Subject: [PATCH 11/26] Update README.md --- README.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 72e687c..bdde200 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ [![Join the chat at https://gitter.im/TLSharp/Lobby](https://badges.gitter.im/TLSharp/Lobby.svg)](https://gitter.im/TLSharp/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build status](https://ci.appveyor.com/api/projects/status/95rl618ch5c4h2fa?svg=true)](https://ci.appveyor.com/project/sochix/tlsharp) +[![NuGet version](https://badge.fury.io/nu/TLSharp.svg)](https://badge.fury.io/nu/TLSharp) _Unofficial_ Telegram (http://telegram.org) client library implemented in C#. Latest TL scheme supported, thanks to Afshin Arani @@ -29,9 +30,13 @@ It's a perfect fit for any developer who would like to send data directly to Tel # How do I add this to my project? -Library _almost_ ready for production usage. We need contributors to make 1.0.0 release. +Install via NuGet -To use TLSharp follow next steps: +``` + Install-Package TLSharp +``` + +or build from source 1. Clone TLSharp from GitHub 1. Compile source with VS2015 or MonoDevelop @@ -187,9 +192,9 @@ Contributing is highly appreciated! ### Release 1.0.0 * [DONE] Add PHONE_MIGRATE handling -* [DONE]Add FILE_MIGRATE handling +* [DONE] Add FILE_MIGRATE handling * Add Updates handling -* Add NuGet package +* [DONE] Add NuGet package * [DONE] Add wrappers for media uploading and downloading * Store user session as JSON From c1305ada65f337c18eda5437f16f8e3af714e44c Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Sun, 30 Oct 2016 15:57:45 +0800 Subject: [PATCH 12/26] Rename MigrationNeededException to PhoneMigrationException There are different kind of MIGRATE errors that could be thrown by the Telegram API, as evidenced by this recent change: https://github.com/sochix/TLSharp/commit/b06f8a8e1174f0d2580f36039054adb25d62403e So this rename tries to make it consistent to the new exception names: * FILE_MIGRATE_x -> FileMigrationException * USER_MIGRATE_y -> UserMigrationException * PHONE_MIGRATE_z -> PhoneMigrationException --- TLSharp.Core/Network/MtProtoSender.cs | 6 +++--- TLSharp.Core/TelegramClient.cs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/TLSharp.Core/Network/MtProtoSender.cs b/TLSharp.Core/Network/MtProtoSender.cs index 1f22aeb..108baf1 100644 --- a/TLSharp.Core/Network/MtProtoSender.cs +++ b/TLSharp.Core/Network/MtProtoSender.cs @@ -279,7 +279,7 @@ namespace TLSharp.Core.Network { var resultString = Regex.Match(errorMessage, @"\d+").Value; var dcIdx = int.Parse(resultString); - throw new MigrationNeededException(dcIdx); + throw new PhoneMigrationException(dcIdx); } else if (errorMessage.StartsWith("FILE_MIGRATE_")) { @@ -495,11 +495,11 @@ namespace TLSharp.Core.Network } } - internal class MigrationNeededException : Exception + internal class PhoneMigrationException : Exception { internal int DC { get; private set; } - internal MigrationNeededException(int dc) + internal PhoneMigrationException(int dc) : base ($"Your phone number is registered to a different DC: {dc}. Please migrate.") { DC = dc; diff --git a/TLSharp.Core/TelegramClient.cs b/TLSharp.Core/TelegramClient.cs index 0c6f3c7..03083f4 100644 --- a/TLSharp.Core/TelegramClient.cs +++ b/TLSharp.Core/TelegramClient.cs @@ -124,7 +124,7 @@ namespace TLSharp.Core completed = true; } - catch (MigrationNeededException ex) + catch (PhoneMigrationException ex) { await ReconnectToDcAsync(ex.DC); } From a521466bb02c97eac845240e59511248aff8886e Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Sun, 30 Oct 2016 16:04:32 +0800 Subject: [PATCH 13/26] Create common abstract DataCenterMigrationException We can abstract the DC property to a common abstract class so have a bit of less code and we join these 3 classes together semantically. --- TLSharp.Core/Network/MtProtoSender.cs | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/TLSharp.Core/Network/MtProtoSender.cs b/TLSharp.Core/Network/MtProtoSender.cs index 108baf1..6966028 100644 --- a/TLSharp.Core/Network/MtProtoSender.cs +++ b/TLSharp.Core/Network/MtProtoSender.cs @@ -495,36 +495,37 @@ namespace TLSharp.Core.Network } } - internal class PhoneMigrationException : Exception + internal abstract class DataCenterMigrationException : Exception { internal int DC { get; private set; } + protected DataCenterMigrationException(string msg, int dc) : base (msg) + { + DC = dc; + } + } + + internal class PhoneMigrationException : DataCenterMigrationException + { internal PhoneMigrationException(int dc) - : base ($"Your phone number is registered to a different DC: {dc}. Please migrate.") + : base ($"Your phone number is registered to a different DC: {dc}. Please migrate.", dc) { - DC = dc; } } - internal class FileMigrationException : Exception + internal class FileMigrationException : DataCenterMigrationException { - internal int DC { get; private set; } - internal FileMigrationException(int dc) - : base ($"File is located on a different DC: {dc}. Please migrate.") + : base ($"File is located on a different DC: {dc}. Please migrate.", dc) { - DC = dc; } } - internal class UserMigrationException : Exception + internal class UserMigrationException : DataCenterMigrationException { - internal int DC { get; private set; } - internal UserMigrationException(int dc) - : base($"User is located on a different DC: {dc}. Please migrate.") + : base($"User is located on a different DC: {dc}. Please migrate.", dc) { - DC = dc; } } } \ No newline at end of file From e1ff4bb75b8d418d0c65fd165542b5bd452becad Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Sun, 30 Oct 2016 16:16:55 +0800 Subject: [PATCH 14/26] Bring back report message to Migration exceptions When refactoring recently the PHONE_MIGRATE_X error wrt exception handling [1] I removed the dubious/obsolete "settings" part, but I mistakenly removed the URL which tells library consumers that if they face this exception, it's actually a bug of the library that they should report. [1] https://github.com/sochix/TLSharp/commit/77867b44e626aedfba58cf9729100e3cc1a808a8 --- README.md | 4 ++-- TLSharp.Core/Network/MtProtoSender.cs | 11 +++++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index bdde200..301a0a2 100644 --- a/README.md +++ b/README.md @@ -203,9 +203,9 @@ Contributing is highly appreciated! #### What API layer is supported? The latest one - 57. Thanks to Afshin Arani for his TLGenerator -#### I get an error MIGRATE_X? +#### I get a xxxMigrationException or a MIGRATE_X error! -TLSharp library should automatically handle this errors. If you see such errors, pls create a new issue. +TLSharp library should automatically handle these errors. If you see such errors, please open a new Github issue with the details (include a stacktrace, etc.). #### I get an exception: System.IO.EndOfStreamException: Unable to read beyond the end of the stream. All test methos except that AuthenticationWorks and TestConnection return same error. I did every thing including setting api id and hash, and setting server address.- diff --git a/TLSharp.Core/Network/MtProtoSender.cs b/TLSharp.Core/Network/MtProtoSender.cs index 6966028..cadaad4 100644 --- a/TLSharp.Core/Network/MtProtoSender.cs +++ b/TLSharp.Core/Network/MtProtoSender.cs @@ -499,7 +499,10 @@ namespace TLSharp.Core.Network { internal int DC { get; private set; } - protected DataCenterMigrationException(string msg, int dc) : base (msg) + private const string REPORT_MESSAGE = + " See: https://github.com/sochix/TLSharp#i-get-an-error-migrate_x"; + + protected DataCenterMigrationException(string msg, int dc) : base (msg + REPORT_MESSAGE) { DC = dc; } @@ -508,7 +511,7 @@ namespace TLSharp.Core.Network internal class PhoneMigrationException : DataCenterMigrationException { internal PhoneMigrationException(int dc) - : base ($"Your phone number is registered to a different DC: {dc}. Please migrate.", dc) + : base ($"Phone number registered to a different DC: {dc}.", dc) { } } @@ -516,7 +519,7 @@ namespace TLSharp.Core.Network internal class FileMigrationException : DataCenterMigrationException { internal FileMigrationException(int dc) - : base ($"File is located on a different DC: {dc}. Please migrate.", dc) + : base ($"File located on a different DC: {dc}.", dc) { } } @@ -524,7 +527,7 @@ namespace TLSharp.Core.Network internal class UserMigrationException : DataCenterMigrationException { internal UserMigrationException(int dc) - : base($"User is located on a different DC: {dc}. Please migrate.", dc) + : base($"User located on a different DC: {dc}.", dc) { } } From 5161d38456104c48fc468a4d636f96b51519e605 Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Sun, 30 Oct 2016 16:33:29 +0800 Subject: [PATCH 15/26] MigrationExceptions: update URL Previous commit[1] made the anchor change its name due to changing slightly the content of the README around the MIGRATE problem. [1] e1ff4bb75b8d418d0c65fd165542b5bd452becad --- TLSharp.Core/Network/MtProtoSender.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TLSharp.Core/Network/MtProtoSender.cs b/TLSharp.Core/Network/MtProtoSender.cs index cadaad4..d46a68e 100644 --- a/TLSharp.Core/Network/MtProtoSender.cs +++ b/TLSharp.Core/Network/MtProtoSender.cs @@ -500,7 +500,7 @@ namespace TLSharp.Core.Network internal int DC { get; private set; } private const string REPORT_MESSAGE = - " See: https://github.com/sochix/TLSharp#i-get-an-error-migrate_x"; + " See: https://github.com/sochix/TLSharp#i-get-a-xxxmigrationexception-or-a-migrate_x-error"; protected DataCenterMigrationException(string msg, int dc) : base (msg + REPORT_MESSAGE) { From a029c33e3469bf3d78f4a91ac5b5039c6ea48a90 Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Sun, 30 Oct 2016 22:31:00 +0800 Subject: [PATCH 16/26] TelegramClient ctor: move null checks earlier This way we avoid creating a FileSessionStore object or initializing the TLContext if API credentials are not supplied, to be on the safe side. --- TLSharp.Core/TelegramClient.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/TLSharp.Core/TelegramClient.cs b/TLSharp.Core/TelegramClient.cs index 03083f4..2fa8c3a 100644 --- a/TLSharp.Core/TelegramClient.cs +++ b/TLSharp.Core/TelegramClient.cs @@ -31,16 +31,17 @@ namespace TLSharp.Core public TelegramClient(int apiId, string apiHash, ISessionStore store = null, string sessionUserId = "session") { + if (apiId == default(int)) + throw new MissingApiConfigurationException("API_ID"); + if (string.IsNullOrEmpty(apiHash)) + throw new MissingApiConfigurationException("API_HASH"); + if (store == null) store = new FileSessionStore(); TLContext.Init(); _apiHash = apiHash; _apiId = apiId; - if (_apiId == default(int)) - throw new MissingApiConfigurationException("API_ID"); - if (string.IsNullOrEmpty(_apiHash)) - throw new MissingApiConfigurationException("API_HASH"); _session = Session.TryLoadOrCreateNew(store, sessionUserId); _transport = new TcpTransport(_session.ServerAddress, _session.Port); From 34e89f3f3708ad692b2ddf101c98346ea785ca91 Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Sun, 30 Oct 2016 23:34:12 +0800 Subject: [PATCH 17/26] Require some parameters as non empty & not null before proceeding --- TLSharp.Core/TelegramClient.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/TLSharp.Core/TelegramClient.cs b/TLSharp.Core/TelegramClient.cs index 2fa8c3a..85561ad 100644 --- a/TLSharp.Core/TelegramClient.cs +++ b/TLSharp.Core/TelegramClient.cs @@ -99,6 +99,9 @@ namespace TLSharp.Core public async Task IsPhoneRegisteredAsync(string phoneNumber) { + if (String.IsNullOrWhiteSpace(phoneNumber)) + throw new ArgumentNullException(nameof(phoneNumber)); + if (_sender == null) throw new InvalidOperationException("Not connected!"); @@ -111,6 +114,9 @@ namespace TLSharp.Core public async Task SendCodeRequestAsync(string phoneNumber) { + if (String.IsNullOrWhiteSpace(phoneNumber)) + throw new ArgumentNullException(nameof(phoneNumber)); + var completed = false; TLRequestSendCode request = null; @@ -136,6 +142,15 @@ namespace TLSharp.Core public async Task MakeAuthAsync(string phoneNumber, string phoneCodeHash, string code) { + if (String.IsNullOrWhiteSpace(phoneNumber)) + throw new ArgumentNullException(nameof(phoneNumber)); + + if (String.IsNullOrWhiteSpace(phoneCodeHash)) + throw new ArgumentNullException(nameof(phoneCodeHash)); + + if (String.IsNullOrWhiteSpace(code)) + throw new ArgumentNullException(nameof(code)); + var request = new TLRequestSignIn() { phone_number = phoneNumber, phone_code_hash = phoneCodeHash, phone_code = code }; await _sender.Send(request); await _sender.Receive(request); From f062c0a7a173362992ec8fb0b32478f185c73001 Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Mon, 31 Oct 2016 00:15:10 +0800 Subject: [PATCH 18/26] Friendlier exceptions for Auth testing This change also lets you write the auth code in the app.config file without the need to recompile/debug. --- TLSharp.Core/Network/MtProtoSender.cs | 4 ++++ TLSharp.Core/TelegramClient.cs | 5 +++++ TLSharp.Tests/TLSharpTests.cs | 24 ++++++++++++++++++++++-- TLSharp.Tests/app.config | 1 + 4 files changed, 32 insertions(+), 2 deletions(-) diff --git a/TLSharp.Core/Network/MtProtoSender.cs b/TLSharp.Core/Network/MtProtoSender.cs index d46a68e..8929760 100644 --- a/TLSharp.Core/Network/MtProtoSender.cs +++ b/TLSharp.Core/Network/MtProtoSender.cs @@ -293,6 +293,10 @@ namespace TLSharp.Core.Network var dcIdx = int.Parse(resultString); throw new UserMigrationException(dcIdx); } + else if (errorMessage == "PHONE_CODE_INVALID") + { + throw new InvalidPhoneCodeException("The numeric code used to authenticate does not match the numeric code sent by SMS/Telegram"); + } else { throw new InvalidOperationException(errorMessage); diff --git a/TLSharp.Core/TelegramClient.cs b/TLSharp.Core/TelegramClient.cs index 03083f4..f06dfea 100644 --- a/TLSharp.Core/TelegramClient.cs +++ b/TLSharp.Core/TelegramClient.cs @@ -294,4 +294,9 @@ namespace TLSharp.Core { } } + + public class InvalidPhoneCodeException : Exception + { + internal InvalidPhoneCodeException(string msg) : base(msg) { } + } } diff --git a/TLSharp.Tests/TLSharpTests.cs b/TLSharp.Tests/TLSharpTests.cs index bb3284d..2e2ba0e 100644 --- a/TLSharp.Tests/TLSharpTests.cs +++ b/TLSharp.Tests/TLSharpTests.cs @@ -24,6 +24,8 @@ namespace TLSharp.Tests private string NumberToAuthenticate { get; set; } + private string CodeToAuthenticate { get; set; } + private string NotRegisteredNumberToSignUp { get; set; } private string UserNameToSendMessage { get; set; } @@ -72,6 +74,10 @@ namespace TLSharp.Tests if (string.IsNullOrEmpty(NumberToAuthenticate)) Debug.WriteLine("NumberToAuthenticate not configured in app.config! Some tests may fail."); + CodeToAuthenticate = ConfigurationManager.AppSettings[nameof(CodeToAuthenticate)]; + if (string.IsNullOrEmpty(CodeToAuthenticate)) + Debug.WriteLine("CpdeToAuthenticate not configured in app.config! Some tests may fail."); + NotRegisteredNumberToSignUp = ConfigurationManager.AppSettings[nameof(NotRegisteredNumberToSignUp)]; if (string.IsNullOrEmpty(NotRegisteredNumberToSignUp)) Debug.WriteLine("NotRegisteredNumberToSignUp not configured in app.config! Some tests may fail."); @@ -101,9 +107,23 @@ namespace TLSharp.Tests await client.ConnectAsync(); var hash = await client.SendCodeRequestAsync(NumberToAuthenticate); - var code = "93463"; // you can change code in debugger + var code = CodeToAuthenticate; // you can change code in debugger too - var user = await client.MakeAuthAsync(NumberToAuthenticate, hash, code); + if (String.IsNullOrWhiteSpace(code)) + { + throw new Exception("CodeToAuthenticate is empty in the app.config file, fill it with the code you just got now by SMS/Telegram"); + } + + TLUser user = null; + try + { + user = await client.MakeAuthAsync(NumberToAuthenticate, hash, code); + } + catch (InvalidPhoneCodeException ex) + { + throw new Exception("CodeToAuthenticate is wrong in the app.config file, fill it with the code you just got now by SMS/Telegram", + ex); + } Assert.IsNotNull(user); Assert.IsTrue(client.IsUserAuthorized()); diff --git a/TLSharp.Tests/app.config b/TLSharp.Tests/app.config index 6fc79b3..941fdda 100644 --- a/TLSharp.Tests/app.config +++ b/TLSharp.Tests/app.config @@ -4,6 +4,7 @@ + From a0cdc2ae1ad5dcad989ca49101feefeff395e796 Mon Sep 17 00:00:00 2001 From: Eugene Timokhov Date: Sun, 30 Oct 2016 20:26:17 +0300 Subject: [PATCH 19/26] Fix TLVector serialization with TLObject --- TeleSharp.TL/TLVector.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TeleSharp.TL/TLVector.cs b/TeleSharp.TL/TLVector.cs index bf3d025..08e8ae5 100644 --- a/TeleSharp.TL/TLVector.cs +++ b/TeleSharp.TL/TLVector.cs @@ -81,9 +81,9 @@ namespace TeleSharp.TL } else if (typeof(T).BaseType == typeof(TLObject)) { - var res = (TLObject) (Convert.ChangeType(item, typeof (TLObject))); + var res = (TLObject)(object)item; res.SerializeBody(bw); - } + } } } } From 054bbe88f337de25eea02d8125b690e32bfdced3 Mon Sep 17 00:00:00 2001 From: Ilya Pirozhenko Date: Mon, 31 Oct 2016 09:08:38 +0300 Subject: [PATCH 20/26] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 301a0a2..1811330 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ It's a perfect fit for any developer who would like to send data directly to Tel Install via NuGet ``` - Install-Package TLSharp + > Install-Package TLSharp ``` or build from source From 9986270bed71dac3205d337a9ba4c82b6c6b617c Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Tue, 1 Nov 2016 01:33:26 +0800 Subject: [PATCH 21/26] Fix typo "CpdeToAuthenticate" -> CodeToAuthenticate And let's use nameof() in all cases so this doesn't happen again. --- TLSharp.Tests/TLSharpTests.cs | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/TLSharp.Tests/TLSharpTests.cs b/TLSharp.Tests/TLSharpTests.cs index 2e2ba0e..8e6a604 100644 --- a/TLSharp.Tests/TLSharpTests.cs +++ b/TLSharp.Tests/TLSharpTests.cs @@ -60,43 +60,45 @@ namespace TLSharp.Tests private void GatherTestConfiguration() { + string appConfigMsgWarning = "{0} not configured in app.config! Some tests may fail."; + ApiHash = ConfigurationManager.AppSettings[nameof(ApiHash)]; if (string.IsNullOrEmpty(ApiHash)) - Debug.WriteLine("ApiHash not configured in app.config! Some tests may fail."); + Debug.WriteLine(appConfigMsgWarning, nameof(ApiHash)); var apiId = ConfigurationManager.AppSettings[nameof(ApiId)]; if (string.IsNullOrEmpty(apiId)) - Debug.WriteLine("ApiId not configured in app.config! Some tests may fail."); + Debug.WriteLine(appConfigMsgWarning, nameof(ApiId)); else ApiId = int.Parse(apiId); NumberToAuthenticate = ConfigurationManager.AppSettings[nameof(NumberToAuthenticate)]; if (string.IsNullOrEmpty(NumberToAuthenticate)) - Debug.WriteLine("NumberToAuthenticate not configured in app.config! Some tests may fail."); + Debug.WriteLine(appConfigMsgWarning, nameof(NumberToAuthenticate)); CodeToAuthenticate = ConfigurationManager.AppSettings[nameof(CodeToAuthenticate)]; if (string.IsNullOrEmpty(CodeToAuthenticate)) - Debug.WriteLine("CpdeToAuthenticate not configured in app.config! Some tests may fail."); + Debug.WriteLine(appConfigMsgWarning, nameof(CodeToAuthenticate)); NotRegisteredNumberToSignUp = ConfigurationManager.AppSettings[nameof(NotRegisteredNumberToSignUp)]; if (string.IsNullOrEmpty(NotRegisteredNumberToSignUp)) - Debug.WriteLine("NotRegisteredNumberToSignUp not configured in app.config! Some tests may fail."); + Debug.WriteLine(appConfigMsgWarning, nameof(NotRegisteredNumberToSignUp)); NumberToSendMessage = ConfigurationManager.AppSettings[nameof(NumberToSendMessage)]; if (string.IsNullOrEmpty(NumberToSendMessage)) - Debug.WriteLine("NumberToSendMessage not configured in app.config! Some tests may fail."); + Debug.WriteLine(appConfigMsgWarning, nameof(NumberToSendMessage)); UserNameToSendMessage = ConfigurationManager.AppSettings[nameof(UserNameToSendMessage)]; if (string.IsNullOrEmpty(UserNameToSendMessage)) - Debug.WriteLine("UserNameToSendMessage not configured in app.config! Some tests may fail."); + Debug.WriteLine(appConfigMsgWarning, nameof(UserNameToSendMessage)); NumberToGetUserFull = ConfigurationManager.AppSettings[nameof(NumberToGetUserFull)]; if (string.IsNullOrEmpty(NumberToGetUserFull)) - Debug.WriteLine("NumberToGetUserFull not configured in app.config! Some tests may fail."); + Debug.WriteLine(appConfigMsgWarning, nameof(NumberToGetUserFull)); NumberToAddToChat = ConfigurationManager.AppSettings[nameof(NumberToAddToChat)]; if (string.IsNullOrEmpty(NumberToAddToChat)) - Debug.WriteLine("NumberToAddToChat not configured in app.config! Some tests may fail."); + Debug.WriteLine(appConfigMsgWarning, nameof(NumberToAddToChat)); } [TestMethod] From 5e9bb6163f46eb195d95ebc7ce7268ca0a8829c9 Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Tue, 1 Nov 2016 23:38:28 +0800 Subject: [PATCH 22/26] Throw FloodException instead of calling Thread.Sleep() Doing this is better when looking at the problem from at least these 2 points of view: a) You're working on TLSharp itself: You might be testing some new things or running TLSharp's tests. Suddenly, if a FLOOD_WAIT response happens, there's no clear way to know. You just see the tests taking forever. But if a test has reached a situation in which Telegram has returned a FLOOD_WAIT error, it's very likely that what happens is that the TLSharp operation being tested is actually buggy, which means that the test should FAIL FAST and show a stacktrace of the problem so that you can see where in the code was the FLOOD_WAIT received/caused. You shouldn't need to kill the run of the test suite and hope to hit the problem again only when you were using the debugger (to be able to pause execution and examine a stacktrace of where the execution flow is). b) You're using TLSharp: if you hit a FLOOD_WAIT problem it may happen because: b1) TLSharp has a bug: in this case it's better to throw an exception so that the user can copy the stacktrace and paste it into a new Github issue. b2) Your program uses TLSharp sending excessive requests: you want to have your program know when you hit the limit, to be able to fix your program to not be so floody. But a call to Thread.Sleep() doesn't help you to know this, you just know that suddenly your program has hung, and you don't know why. You cannot react to the problem, however with an exception you can react to the problem (for example by examining the time that the exception provides, as a TimeSpan property, to know how much your program needs to wait to be able to use TLSharp again). --- README.md | 4 ++-- TLSharp.Core/Network/MtProtoSender.cs | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1811330..b8e8b11 100644 --- a/README.md +++ b/README.md @@ -211,8 +211,8 @@ TLSharp library should automatically handle these errors. If you see such errors You should create a Telegram session. See [configuration guide](#sending-messages-set-up) -#### Why I get FLOOD_WAIT error? -[It's Telegram restrictions](https://core.telegram.org/api/errors#420-flood) +#### Why do I get a FloodException/FLOOD_WAIT error? +It's likely [Telegram restrictions](https://core.telegram.org/api/errors#420-flood), or a bug in TLSharp (if you feel it's the latter, please open a Github issue). You can know the time to wait by accessing the FloodException::TimeToWait property. #### Why does TLSharp lacks feature XXXX? diff --git a/TLSharp.Core/Network/MtProtoSender.cs b/TLSharp.Core/Network/MtProtoSender.cs index 8929760..9cb7061 100644 --- a/TLSharp.Core/Network/MtProtoSender.cs +++ b/TLSharp.Core/Network/MtProtoSender.cs @@ -272,8 +272,7 @@ namespace TLSharp.Core.Network { var resultString = Regex.Match(errorMessage, @"\d+").Value; var seconds = int.Parse(resultString); - Debug.WriteLine($"Should wait {seconds} sec."); - Thread.Sleep(1000 * seconds); + throw new FloodException(TimeSpan.FromSeconds(seconds)); } else if (errorMessage.StartsWith("PHONE_MIGRATE_")) { @@ -499,6 +498,18 @@ namespace TLSharp.Core.Network } } + public class FloodException : Exception + { + public TimeSpan TimeToWait { get; private set; } + + internal FloodException(TimeSpan timeToWait) + : base($"Flood prevention. Telegram now requires your program to do requests again only after {timeToWait.TotalSeconds} seconds have passed ({nameof(TimeToWait)} property)." + + " If you think the culprit of this problem may lie in TLSharp's implementation, open a Github issue please.") + { + TimeToWait = timeToWait; + } + } + internal abstract class DataCenterMigrationException : Exception { internal int DC { get; private set; } From 738a84937e6d9edb56727ee36ad6344aae5f1b86 Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Thu, 3 Nov 2016 01:31:47 +0800 Subject: [PATCH 23/26] SendMessageTest: rather crash with meaningful exception Rather crash with meaningful exception than not passing the test and only giving a hint when debugging. --- TLSharp.Tests/TLSharpTests.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/TLSharp.Tests/TLSharpTests.cs b/TLSharp.Tests/TLSharpTests.cs index 8e6a604..2d93942 100644 --- a/TLSharp.Tests/TLSharpTests.cs +++ b/TLSharp.Tests/TLSharpTests.cs @@ -84,10 +84,6 @@ namespace TLSharp.Tests if (string.IsNullOrEmpty(NotRegisteredNumberToSignUp)) Debug.WriteLine(appConfigMsgWarning, nameof(NotRegisteredNumberToSignUp)); - NumberToSendMessage = ConfigurationManager.AppSettings[nameof(NumberToSendMessage)]; - if (string.IsNullOrEmpty(NumberToSendMessage)) - Debug.WriteLine(appConfigMsgWarning, nameof(NumberToSendMessage)); - UserNameToSendMessage = ConfigurationManager.AppSettings[nameof(UserNameToSendMessage)]; if (string.IsNullOrEmpty(UserNameToSendMessage)) Debug.WriteLine(appConfigMsgWarning, nameof(UserNameToSendMessage)); @@ -134,6 +130,10 @@ namespace TLSharp.Tests [TestMethod] public async Task SendMessageTest() { + NumberToSendMessage = ConfigurationManager.AppSettings[nameof(NumberToSendMessage)]; + if (string.IsNullOrWhiteSpace(NumberToSendMessage)) + throw new Exception($"Please fill the '{nameof(NumberToSendMessage)}' setting in app.config file first"); + var client = NewClient(); await client.ConnectAsync(); From adef68b7475014393424ea2f13e88bec4b373690 Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Thu, 3 Nov 2016 01:33:56 +0800 Subject: [PATCH 24/26] SendNumberTest: remove the + from the phone number in app.config NumberToAuthenticate works fine for the AuthTest if we put a "+" before our international prefix when writing the number, but because this test compares the numbers we got from the Contacts List with the one in app.config, it could not find it due to this prefix. Let's rather be prepared for that. --- TLSharp.Tests/TLSharpTests.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/TLSharp.Tests/TLSharpTests.cs b/TLSharp.Tests/TLSharpTests.cs index 2d93942..3f7b594 100644 --- a/TLSharp.Tests/TLSharpTests.cs +++ b/TLSharp.Tests/TLSharpTests.cs @@ -134,6 +134,11 @@ namespace TLSharp.Tests if (string.IsNullOrWhiteSpace(NumberToSendMessage)) throw new Exception($"Please fill the '{nameof(NumberToSendMessage)}' setting in app.config file first"); + // this is because the contacts in the address come without the "+" prefix + var normalizedNumber = NumberToSendMessage.StartsWith("+") ? + NumberToSendMessage.Substring(1, NumberToSendMessage.Length - 1) : + NumberToSendMessage; + var client = NewClient(); await client.ConnectAsync(); @@ -143,7 +148,7 @@ namespace TLSharp.Tests var user = result.users.lists .Where(x => x.GetType() == typeof(TLUser)) .Cast() - .FirstOrDefault(x => x.phone == NumberToSendMessage); + .FirstOrDefault(x => x.phone == normalizedNumber); if (user == null) { @@ -153,7 +158,6 @@ namespace TLSharp.Tests await client.SendTypingAsync(new TLInputPeerUser() { user_id = user.id }); Thread.Sleep(3000); await client.SendMessageAsync(new TLInputPeerUser() { user_id = user.id }, "TEST"); - } [TestMethod] From 8b2f2271422bd1870a680abc0dd9998397591e15 Mon Sep 17 00:00:00 2001 From: Eugene Timokhov Date: Mon, 7 Nov 2016 02:40:19 +0300 Subject: [PATCH 25/26] Added possibility to do ping request (SendPingAsync method) --- README.md | 1 + TLSharp.Core/Network/MtProtoSender.cs | 25 +++++++++++++++-- TLSharp.Core/Requests/PingRequest.cs | 39 +++++++++++++++++++++++++++ TLSharp.Core/TLSharp.Core.csproj | 1 + TLSharp.Core/TelegramClient.cs | 7 ++++- 5 files changed, 70 insertions(+), 3 deletions(-) create mode 100644 TLSharp.Core/Requests/PingRequest.cs diff --git a/README.md b/README.md index b8e8b11..8cdba23 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ For your convenience TLSharp have wrappers for several Telegram API methods. You 1. SendUploadedDocument 1. GetFile 1. UploadFile +1. SendPingAsync **What if you can't find needed method at the list?** diff --git a/TLSharp.Core/Network/MtProtoSender.cs b/TLSharp.Core/Network/MtProtoSender.cs index 9cb7061..352e527 100644 --- a/TLSharp.Core/Network/MtProtoSender.cs +++ b/TLSharp.Core/Network/MtProtoSender.cs @@ -148,6 +148,19 @@ namespace TLSharp.Core.Network return null; } + public async Task SendPingAsync() + { + var pingRequest = new PingRequest(); + using (var memory = new MemoryStream()) + using (var writer = new BinaryWriter(memory)) + { + pingRequest.SerializeBody(writer); + await Send(memory.ToArray(), pingRequest); + } + + await Receive(pingRequest); + } + private bool processMessage(ulong messageId, int sequence, BinaryReader messageReader, TeleSharp.TL.TLMethod request) { // TODO: check salt @@ -169,7 +182,7 @@ namespace TLSharp.Core.Network return HandlePing(messageId, sequence, messageReader); case 0x347773c5: // pong //logger.debug("MSG pong"); - return HandlePong(messageId, sequence, messageReader); + return HandlePong(messageId, sequence, messageReader, request); case 0xae500895: // future_salts //logger.debug("MSG future_salts"); return HandleFutureSalts(messageId, sequence, messageReader); @@ -455,8 +468,16 @@ namespace TLSharp.Core.Network return true; } - private bool HandlePong(ulong messageId, int sequence, BinaryReader messageReader) + private bool HandlePong(ulong messageId, int sequence, BinaryReader messageReader, TeleSharp.TL.TLMethod request) { + uint code = messageReader.ReadUInt32(); + ulong msgId = messageReader.ReadUInt64(); + + if (msgId == (ulong)request.MessageId) + { + request.ConfirmReceived = true; + } + return false; } diff --git a/TLSharp.Core/Requests/PingRequest.cs b/TLSharp.Core/Requests/PingRequest.cs new file mode 100644 index 0000000..48aa61b --- /dev/null +++ b/TLSharp.Core/Requests/PingRequest.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.IO; +using TeleSharp.TL; +using TLSharp.Core.Utils; + +namespace TLSharp.Core.Requests +{ + public class PingRequest : TeleSharp.TL.TLMethod + { + public PingRequest() + { + } + + public override void SerializeBody(BinaryWriter writer) + { + writer.Write(Constructor); + writer.Write(Helpers.GenerateRandomLong()); + } + + public override void DeserializeBody(BinaryReader reader) + { + throw new NotImplementedException(); + } + + public override void deserializeResponse(BinaryReader stream) + { + throw new NotImplementedException(); + } + + public override int Constructor + { + get + { + return 0x7abe77ec; + } + } + } +} diff --git a/TLSharp.Core/TLSharp.Core.csproj b/TLSharp.Core/TLSharp.Core.csproj index 0b8ac8d..fbef942 100644 --- a/TLSharp.Core/TLSharp.Core.csproj +++ b/TLSharp.Core/TLSharp.Core.csproj @@ -63,6 +63,7 @@ + diff --git a/TLSharp.Core/TelegramClient.cs b/TLSharp.Core/TelegramClient.cs index 49a78ae..ea4dd8c 100644 --- a/TLSharp.Core/TelegramClient.cs +++ b/TLSharp.Core/TelegramClient.cs @@ -174,7 +174,7 @@ namespace TLSharp.Core { await _sender.Send(methodToExecute); await _sender.Receive(methodToExecute); - + var result = methodToExecute.GetType().GetProperty("Response").GetValue(methodToExecute); return (T)result; @@ -292,6 +292,11 @@ namespace TLSharp.Core return result; } + public async Task SendPingAsync() + { + await _sender.SendPingAsync(); + } + private void OnUserAuthenticated(TLUser TLUser) { _session.TLUser = TLUser; From cc0ca3bcd4380337769f67db3eb6bc8d59c60bbf Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Wed, 9 Nov 2016 00:49:07 +0800 Subject: [PATCH 26/26] Add C# style policy to SLN file This helps MonoDevelop know that the solution will default to spaces instead of tabs, etc. This doesn't disrupt the solution in VisualStudio at all. --- TLSharp.sln | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/TLSharp.sln b/TLSharp.sln index 504f779..3c9edb4 100644 --- a/TLSharp.sln +++ b/TLSharp.sln @@ -34,6 +34,41 @@ Global {DE5C0467-EE99-4734-95F2-EFF7A0B99924}.Release|Any CPU.ActiveCfg = Release|Any CPU {DE5C0467-EE99-4734-95F2-EFF7A0B99924}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection + GlobalSection(MonoDevelopProperties) = preSolution + Policies = $0 + $0.TextStylePolicy = $1 + $1.inheritsSet = VisualStudio + $1.inheritsScope = text/plain + $1.scope = text/x-csharp + $0.CSharpFormattingPolicy = $2 + $2.IndentSwitchBody = True + $2.IndentBlocksInsideExpressions = True + $2.AnonymousMethodBraceStyle = NextLine + $2.PropertyBraceStyle = NextLine + $2.PropertyGetBraceStyle = NextLine + $2.PropertySetBraceStyle = NextLine + $2.EventBraceStyle = NextLine + $2.EventAddBraceStyle = NextLine + $2.EventRemoveBraceStyle = NextLine + $2.StatementBraceStyle = NextLine + $2.ElseNewLinePlacement = NewLine + $2.CatchNewLinePlacement = NewLine + $2.FinallyNewLinePlacement = NewLine + $2.WhileNewLinePlacement = DoNotCare + $2.ArrayInitializerWrapping = DoNotChange + $2.ArrayInitializerBraceStyle = NextLine + $2.BeforeMethodDeclarationParentheses = False + $2.BeforeMethodCallParentheses = False + $2.BeforeConstructorDeclarationParentheses = False + $2.NewLineBeforeConstructorInitializerColon = NewLine + $2.NewLineAfterConstructorInitializerColon = SameLine + $2.BeforeDelegateDeclarationParentheses = False + $2.NewParentheses = False + $2.SpacesBeforeBrackets = False + $2.inheritsSet = Mono + $2.inheritsScope = text/x-csharp + $2.scope = text/x-csharp + EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection