diff --git a/README.md b/README.md index 727af52..0046d2b 100644 --- a/README.md +++ b/README.md @@ -161,149 +161,143 @@ Full code you can see at [DownloadFileFromContactTest](https://github.com/sochix private async Task MainAsync(string[] args) { - TelegramClient client = null; - try - { - // -- if necessary, IP can be changed so the client can connect to the test network. - Session session = null; - // new Session(new FileSessionStore(), "session") - //{ - // ServerAddress = "149.154.175.10", - // Port = 443 - //}; - //Console.WriteLine($"{session.ServerAddress}:{session.Port} {phone}"); - client = new TelegramClient(APIId, APIHash, session); - // subscribe an event to receive live messages - client.Updates += Client_Updates; - await client.ConnectAsync(); - Console.WriteLine($"Authorised: {client.IsUserAuthorized()}"); - TLUser user = null; - // -- If the user has already authenticated, this step will prevent account from being blocked as it - // -- reuses the data from last authorisation. - if (client.IsUserAuthorized()) - user = client.Session.TLUser; - else - { - var registered = await client.IsPhoneRegisteredAsync(phone); - var hash = await client.SendCodeRequestAsync(phone); - Console.Write("Code: "); - var code = Console.ReadLine(); - if (!registered) - { - Console.WriteLine($"Sign up {phone}"); - user = await client.SignUpAsync(phone, hash, code, "First", "Last"); - } - Console.WriteLine($"Sign in {phone}"); - user = await client.MakeAuthAsync(phone, hash, code); - } + TelegramClient client = null; + + // -- if necessary, IP can be changed so the client can connect to the test network. + Session session = null; + // new Session(new FileSessionStore(), "session") + //{ + // ServerAddress = "149.154.175.10", + // Port = 443 + //}; + //Console.WriteLine($"{session.ServerAddress}:{session.Port} {phone}"); + client = new TelegramClient(APIId, APIHash, session); + // subscribe an event to receive live messages + client.Updates += Client_Updates; + await client.ConnectAsync(); + Console.WriteLine($"Authorised: {client.IsUserAuthorized()}"); + TLUser user = null; + // -- If the user has already authenticated, this step will prevent account from being blocked as it + // -- reuses the data from last authorisation. + if (client.IsUserAuthorized()) + user = client.Session.TLUser; + else + { + var registered = await client.IsPhoneRegisteredAsync(phone); + var hash = await client.SendCodeRequestAsync(phone); + Console.Write("Code: "); + var code = Console.ReadLine(); + if (!registered) + { + Console.WriteLine($"Sign up {phone}"); + user = await client.SignUpAsync(phone, hash, code, "First", "Last"); + } + Console.WriteLine($"Sign in {phone}"); + user = await client.MakeAuthAsync(phone, hash, code); + } - var contacts = await client.GetContactsAsync(); - Console.WriteLine("Contacts:"); - foreach (var contact in contacts.Users.OfType()) - { - var contactUser = contact as TLUser; - Console.WriteLine($"\t{contact.Id} {contact.Phone} {contact.FirstName} {contact.LastName}"); - } + var contacts = await client.GetContactsAsync(); + Console.WriteLine("Contacts:"); + foreach (var contact in contacts.Users.OfType()) + { + var contactUser = contact as TLUser; + Console.WriteLine($"\t{contact.Id} {contact.Phone} {contact.FirstName} {contact.LastName}"); + } - var dialogs = (TLDialogs) await client.GetUserDialogsAsync(); - Console.WriteLine("Channels: "); - foreach (var channelObj in dialogs.Chats.OfType()) - { - var channel = channelObj as TLChannel; - Console.WriteLine($"\tChat: {channel.Title}"); - } + var dialogs = (TLDialogs) await client.GetUserDialogsAsync(); + Console.WriteLine("Channels: "); + foreach (var channelObj in dialogs.Chats.OfType()) + { + var channel = channelObj as TLChannel; + Console.WriteLine($"\tChat: {channel.Title}"); + } - Console.WriteLine("Groups:"); - TLChat chat = null; - foreach (var chatObj in dialogs.Chats.OfType()) - { - chat = chatObj as TLChat; - Console.WriteLine($"Chat name: {chat.Title}"); - var request = new TLRequestGetFullChat() { ChatId = chat.Id }; - var fullChat = await client.SendRequestAsync(request); + Console.WriteLine("Groups:"); + TLChat chat = null; + foreach (var chatObj in dialogs.Chats.OfType()) + { + chat = chatObj as TLChat; + Console.WriteLine($"Chat name: {chat.Title}"); + var request = new TLRequestGetFullChat() { ChatId = chat.Id }; + var fullChat = await client.SendRequestAsync(request); - var participants = (fullChat.FullChat as TeleSharp.TL.TLChatFull).Participants as TLChatParticipants; - foreach (var p in participants.Participants) - { - if (p is TLChatParticipant) - { - var participant = p as TLChatParticipant; - Console.WriteLine($"\t{participant.UserId}"); - } - else if (p is TLChatParticipantAdmin) - { - var participant = p as TLChatParticipantAdmin; - Console.WriteLine($"\t{participant.UserId}**"); - } - else if (p is TLChatParticipantCreator) - { - var participant = p as TLChatParticipantCreator; - Console.WriteLine($"\t{participant.UserId}**"); - } - } + var participants = (fullChat.FullChat as TeleSharp.TL.TLChatFull).Participants as TLChatParticipants; + foreach (var p in participants.Participants) + { + if (p is TLChatParticipant) + { + var participant = p as TLChatParticipant; + Console.WriteLine($"\t{participant.UserId}"); + } + else if (p is TLChatParticipantAdmin) + { + var participant = p as TLChatParticipantAdmin; + Console.WriteLine($"\t{participant.UserId}**"); + } + else if (p is TLChatParticipantCreator) + { + var participant = p as TLChatParticipantCreator; + Console.WriteLine($"\t{participant.UserId}**"); + } + } - var peer = new TLInputPeerChat() { ChatId = chat.Id }; - var m = await client.GetHistoryAsync(peer, 0, 0, 0); - Console.WriteLine(m); - if (m is TLMessages) - { - var messages = m as TLMessages; + var peer = new TLInputPeerChat() { ChatId = chat.Id }; + var m = await client.GetHistoryAsync(peer, 0, 0, 0); + Console.WriteLine(m); + if (m is TLMessages) + { + var messages = m as TLMessages; - foreach (var message in messages.Messages) - { - if (message is TLMessage) - { - var m1 = message as TLMessage; - Console.WriteLine($"\t\t{m1.Id} {m1.Message}"); - } - else if (message is TLMessageService) - { - var m1 = message as TLMessageService; - Console.WriteLine($"\t\t{m1.Id} {m1.Action}"); - } - } - } - else if (m is TLMessagesSlice) - { - bool done = false; - int total = 0; - while (!done) - { - var messages = m as TLMessagesSlice; + foreach (var message in messages.Messages) + { + if (message is TLMessage) + { + var m1 = message as TLMessage; + Console.WriteLine($"\t\t{m1.Id} {m1.Message}"); + } + else if (message is TLMessageService) + { + var m1 = message as TLMessageService; + Console.WriteLine($"\t\t{m1.Id} {m1.Action}"); + } + } + } + else if (m is TLMessagesSlice) + { + bool done = false; + int total = 0; + while (!done) + { + var messages = m as TLMessagesSlice; - foreach (var m1 in messages.Messages) - { - if (m1 is TLMessage) - { - var message = m1 as TLMessage; - Console.WriteLine($"\t\t{message.Id} {message.Message}"); - ++total; - } - else if (m1 is TLMessageService) - { - var message = m1 as TLMessageService; - Console.WriteLine($"\t\t{message.Id} {message.Action}"); - ++total; - done = message.Action is TLMessageActionChatCreate; - } - } - m = await client.GetHistoryAsync(peer, total, 0, 0); - } - } - } - - // -- Wait in a loop to handle incoming updates. No need to poll. - for (;;) - { - await client.WaitEventAsync(); - } - } - catch (Exception e) - { - Console.WriteLine(e); - } + foreach (var m1 in messages.Messages) + { + if (m1 is TLMessage) + { + var message = m1 as TLMessage; + Console.WriteLine($"\t\t{message.Id} {message.Message}"); + ++total; + } + else if (m1 is TLMessageService) + { + var message = m1 as TLMessageService; + Console.WriteLine($"\t\t{message.Id} {message.Action}"); + ++total; + done = message.Action is TLMessageActionChatCreate; + } + } + m = await client.GetHistoryAsync(peer, total, 0, 0); + } + } + } + + // -- Wait in a loop to handle incoming updates. No need to poll. + for (;;) + { + await client.WaitEventAsync(); + } } private void Client_Updates(TelegramClient client, TLAbsUpdates updates) @@ -323,7 +317,11 @@ Full code you can see at [DownloadFileFromContactTest](https://github.com/sochix { var peer = new TLInputPeerUser() { UserId = status.UserId }; client.SendMessageAsync(peer, "Você está online.").Wait(); - } catch {} + } + catch (Exception e) + { + Console.WriteLine(e); + } } } } @@ -371,7 +369,7 @@ Full code you can see at [DownloadFileFromContactTest](https://github.com/sochix private void MarkMessageRead(TelegramClient client, TLAbsInputPeer peer, int id) { - // An exception happens here but it's not fatal. + // An exception happens here but it's not fatal. try { var request = new TLRequestReadHistory(); diff --git a/TLSharp.Core/Network/Exceptions.cs b/TLSharp.Core/Network/Exceptions.cs deleted file mode 100644 index 878e64e..0000000 --- a/TLSharp.Core/Network/Exceptions.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -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; - } - } - - public class BadMessageException : Exception - { - internal BadMessageException(string description) : base(description) - { - } - } - - internal abstract class DataCenterMigrationException : Exception - { - internal int DC { get; private set; } - - private const string REPORT_MESSAGE = - " 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) - { - DC = dc; - } - } - - internal class PhoneMigrationException : DataCenterMigrationException - { - internal PhoneMigrationException(int dc) - : base($"Phone number registered to a different DC: {dc}.", dc) - { - } - } - - internal class FileMigrationException : DataCenterMigrationException - { - internal FileMigrationException(int dc) - : base($"File located on a different DC: {dc}.", dc) - { - } - } - - internal class UserMigrationException : DataCenterMigrationException - { - internal UserMigrationException(int dc) - : base($"User located on a different DC: {dc}.", dc) - { - } - } - - internal class NetworkMigrationException : DataCenterMigrationException - { - internal NetworkMigrationException(int dc) - : base($"Network located on a different DC: {dc}.", dc) - { - } - } - - -} diff --git a/TLSharp.Core/Network/MtProtoSender.cs b/TLSharp.Core/Network/MtProtoSender.cs index cd010e9..a2de927 100644 --- a/TLSharp.Core/Network/MtProtoSender.cs +++ b/TLSharp.Core/Network/MtProtoSender.cs @@ -10,6 +10,7 @@ using TeleSharp.TL; using TLSharp.Core.Exceptions; using TLSharp.Core.MTProto; using TLSharp.Core.MTProto.Crypto; +using TLSharp.Core.Network.Exceptions; using TLSharp.Core.Network.Requests; using TLSharp.Core.Utils; @@ -157,14 +158,14 @@ namespace TLSharp.Core.Network public async Task Receive(TLMethod request, CancellationToken token = default(CancellationToken)) { - while (!request.ConfirmReceived) + while (!request.ConfirmReceived) { var result = DecodeMessage((await transport.Receive(token).ConfigureAwait(false)).Body); - using (var messageStream = new MemoryStream (result.Item1, false)) - using (var messageReader = new BinaryReader (messageStream)) + using (var messageStream = new MemoryStream(result.Item1, false)) + using (var messageReader = new BinaryReader(messageStream)) { - await processMessageAsync(result.Item2, result.Item3, messageReader, request, token); + await ProcessMessageAsync(result.Item2, result.Item3, messageReader, request, token); } token.ThrowIfCancellationRequested(); @@ -173,14 +174,14 @@ namespace TLSharp.Core.Network return null; } - public async Task Receive(int timeoutms, CancellationToken token = default(CancellationToken)) + public async Task Receive(TimeSpan timeToWait, CancellationToken token = default(CancellationToken)) { - var result = DecodeMessage((await transport.Receieve(timeoutms)).Body); + var result = DecodeMessage((await transport.Receive(timeToWait)).Body); using (var messageStream = new MemoryStream(result.Item1, false)) using (var messageReader = new BinaryReader(messageStream)) { - await processMessageAsync(result.Item2, result.Item3, messageReader, null); + await ProcessMessageAsync(result.Item2, result.Item3, messageReader, null); } token.ThrowIfCancellationRequested(); @@ -203,7 +204,7 @@ namespace TLSharp.Core.Network await Receive(pingRequest, token).ConfigureAwait(false); } - private async Task processMessageAsync(ulong messageId, int sequence, BinaryReader messageReader, TeleSharp.TL.TLMethod request, CancellationToken token = default(CancellationToken)) + private async Task ProcessMessageAsync(ulong messageId, int sequence, BinaryReader messageReader, TeleSharp.TL.TLMethod request, CancellationToken token = default(CancellationToken)) { token.ThrowIfCancellationRequested(); @@ -330,7 +331,7 @@ namespace TLSharp.Core.Network } using (BinaryReader compressedReader = new BinaryReader(ms)) { - await processMessageAsync(messageId, sequence, compressedReader, request, token); + await ProcessMessageAsync(messageId, sequence, compressedReader, request, token); } } @@ -592,7 +593,7 @@ namespace TLSharp.Core.Network long beginPosition = messageReader.BaseStream.Position; try { - var processedMessage = await processMessageAsync(innerMessageId, sequence, messageReader, request, token); + var processedMessage = await ProcessMessageAsync(innerMessageId, sequence, messageReader, request, token); if (!processedMessage) { messageReader.BaseStream.Position = beginPosition + innerLength; @@ -600,7 +601,7 @@ namespace TLSharp.Core.Network } catch (InvalidOperationException e) { - throw e; + throw; } catch (Exception e) { diff --git a/TLSharp.Core/Network/TcpTransport.cs b/TLSharp.Core/Network/TcpTransport.cs index 306501e..5cac252 100644 --- a/TLSharp.Core/Network/TcpTransport.cs +++ b/TLSharp.Core/Network/TcpTransport.cs @@ -102,13 +102,13 @@ namespace TLSharp.Core.Network return new TcpMessage(seq, body); } - public async Task Receieve(int timeoutms) + public async Task Receive(TimeSpan timeToWait) { var stream = tcpClient.GetStream(); var packetLengthBytes = new byte[4]; var token = tokenSource.Token; - stream.ReadTimeout = timeoutms; + stream.ReadTimeout = (int)timeToWait.TotalMilliseconds; int bytes = 0; try { @@ -118,7 +118,7 @@ namespace TLSharp.Core.Network var socketError = io.InnerException as SocketException; if (socketError != null && socketError.SocketErrorCode == SocketError.TimedOut) throw new OperationCanceledException(); - throw io; + throw; } if (bytes != 4) throw new InvalidOperationException("Couldn't read the packet length"); diff --git a/TLSharp.Core/TLSharp.Core.csproj b/TLSharp.Core/TLSharp.Core.csproj index 52d1966..62bdc6c 100644 --- a/TLSharp.Core/TLSharp.Core.csproj +++ b/TLSharp.Core/TLSharp.Core.csproj @@ -76,7 +76,6 @@ - diff --git a/TLSharp.Core/TelegramClient.cs b/TLSharp.Core/TelegramClient.cs index 13b76ba..6a23399 100644 --- a/TLSharp.Core/TelegramClient.cs +++ b/TLSharp.Core/TelegramClient.cs @@ -16,6 +16,7 @@ using TLSharp.Core.Auth; using TLSharp.Core.Exceptions; using TLSharp.Core.MTProto.Crypto; using TLSharp.Core.Network; +using TLSharp.Core.Network.Exceptions; using TLSharp.Core.Utils; using TLAuthorization = TeleSharp.TL.Auth.TLAuthorization; @@ -164,7 +165,7 @@ namespace TLSharp.Core _looping = false; } - public async Task MainLoopAsync(int timeslicems, CancellationToken token = default(CancellationToken)) + public async Task MainLoopAsync(TimeSpan timeToWait, CancellationToken token = default(CancellationToken)) { var lastPing = DateTime.UtcNow; await SendPingAsync(); @@ -172,7 +173,7 @@ namespace TLSharp.Core { try { - await WaitEventAsync(timeslicems, token); + await WaitEventAsync(timeToWait, token); } catch (OperationCanceledException) { @@ -232,9 +233,9 @@ namespace TLSharp.Core } } - public async Task WaitEventAsync(int timeoutms, CancellationToken token = default(CancellationToken)) + public async Task WaitEventAsync(TimeSpan timeToWait, CancellationToken token = default(CancellationToken)) { - await sender.Receive (timeoutms, token); + await sender.Receive (timeToWait, token); } public bool IsUserAuthorized() diff --git a/TLSharp.Core/packages.config b/TLSharp.Core/packages.config index 518c7dc..6b8deb9 100644 --- a/TLSharp.Core/packages.config +++ b/TLSharp.Core/packages.config @@ -1,5 +1,3 @@  - - \ No newline at end of file diff --git a/TLSharp.Tests/TLSharpTests.cs b/TLSharp.Tests/TLSharpTests.cs index e54c131..c73bcec 100644 --- a/TLSharp.Tests/TLSharpTests.cs +++ b/TLSharp.Tests/TLSharpTests.cs @@ -128,7 +128,7 @@ namespace TLSharp.Tests var hash = await client.SendCodeRequestAsync(NumberToAuthenticate); var code = CodeToAuthenticate; // you can change code in debugger too - if (string.IsNullOrWhiteSpace(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"); } @@ -177,7 +177,7 @@ namespace TLSharp.Tests if (user == null) { - throw new Exception("Number was not found in Contacts List of user: " + NumberToSendMessage); + throw new System.Exception("Number was not found in Contacts List of user: " + NumberToSendMessage); } await client.SendTypingAsync(new TLInputPeerUser() { UserId = user.Id }); @@ -191,7 +191,7 @@ namespace TLSharp.Tests await client.ConnectAsync(); - var dialogs = (TLDialogs)await client.GetUserDialogsAsync(); + var dialogs = (TLDialogs) await client.GetUserDialogsAsync(); var chat = dialogs.Chats .OfType() .FirstOrDefault(c => c.Title == "TestGroup"); @@ -294,7 +294,7 @@ namespace TLSharp.Tests VolumeId = photoLocation.VolumeId }, 1024); - var res = await client.GetUserDialogsAsync(); + var res = await client.GetUserDialogsAsync(); Assert.IsTrue(resFile.Bytes.Length > 0); } @@ -431,7 +431,7 @@ namespace TLSharp.Tests } }; - await client.MainLoopAsync(1000); + await client.MainLoopAsync(new TimeSpan(0, 0, 1)); // At this point you would send yourself a UPDATE_1 message to trigger update