PR review changes

This commit is contained in:
mark 2020-04-26 17:29:26 +01:00
parent 3e0e53bb09
commit 43d9d12167
8 changed files with 159 additions and 231 deletions

270
README.md
View file

@ -161,149 +161,143 @@ Full code you can see at [DownloadFileFromContactTest](https://github.com/sochix
private async Task MainAsync(string[] args) private async Task MainAsync(string[] args)
{ {
TelegramClient client = null; TelegramClient client = null;
try
{ // -- if necessary, IP can be changed so the client can connect to the test network.
// -- if necessary, IP can be changed so the client can connect to the test network. Session session = null;
Session session = null; // new Session(new FileSessionStore(), "session")
// new Session(new FileSessionStore(), "session") //{
//{ // ServerAddress = "149.154.175.10",
// ServerAddress = "149.154.175.10", // Port = 443
// Port = 443 //};
//}; //Console.WriteLine($"{session.ServerAddress}:{session.Port} {phone}");
//Console.WriteLine($"{session.ServerAddress}:{session.Port} {phone}"); client = new TelegramClient(APIId, APIHash, session);
client = new TelegramClient(APIId, APIHash, session); // subscribe an event to receive live messages
// subscribe an event to receive live messages client.Updates += Client_Updates;
client.Updates += Client_Updates; await client.ConnectAsync();
await client.ConnectAsync(); Console.WriteLine($"Authorised: {client.IsUserAuthorized()}");
Console.WriteLine($"Authorised: {client.IsUserAuthorized()}"); TLUser user = null;
TLUser user = null; // -- If the user has already authenticated, this step will prevent account from being blocked as it
// -- If the user has already authenticated, this step will prevent account from being blocked as it // -- reuses the data from last authorisation.
// -- reuses the data from last authorisation. if (client.IsUserAuthorized())
if (client.IsUserAuthorized()) user = client.Session.TLUser;
user = client.Session.TLUser; else
else {
{ var registered = await client.IsPhoneRegisteredAsync(phone);
var registered = await client.IsPhoneRegisteredAsync(phone); var hash = await client.SendCodeRequestAsync(phone);
var hash = await client.SendCodeRequestAsync(phone); Console.Write("Code: ");
Console.Write("Code: "); var code = Console.ReadLine();
var code = Console.ReadLine(); if (!registered)
if (!registered) {
{ Console.WriteLine($"Sign up {phone}");
Console.WriteLine($"Sign up {phone}"); user = await client.SignUpAsync(phone, hash, code, "First", "Last");
user = await client.SignUpAsync(phone, hash, code, "First", "Last"); }
} Console.WriteLine($"Sign in {phone}");
Console.WriteLine($"Sign in {phone}"); user = await client.MakeAuthAsync(phone, hash, code);
user = await client.MakeAuthAsync(phone, hash, code); }
}
var contacts = await client.GetContactsAsync(); var contacts = await client.GetContactsAsync();
Console.WriteLine("Contacts:"); Console.WriteLine("Contacts:");
foreach (var contact in contacts.Users.OfType<TLUser>()) foreach (var contact in contacts.Users.OfType<TLUser>())
{ {
var contactUser = contact as TLUser; var contactUser = contact as TLUser;
Console.WriteLine($"\t{contact.Id} {contact.Phone} {contact.FirstName} {contact.LastName}"); Console.WriteLine($"\t{contact.Id} {contact.Phone} {contact.FirstName} {contact.LastName}");
} }
var dialogs = (TLDialogs) await client.GetUserDialogsAsync(); var dialogs = (TLDialogs) await client.GetUserDialogsAsync();
Console.WriteLine("Channels: "); Console.WriteLine("Channels: ");
foreach (var channelObj in dialogs.Chats.OfType<TLChannel>()) foreach (var channelObj in dialogs.Chats.OfType<TLChannel>())
{ {
var channel = channelObj as TLChannel; var channel = channelObj as TLChannel;
Console.WriteLine($"\tChat: {channel.Title}"); Console.WriteLine($"\tChat: {channel.Title}");
} }
Console.WriteLine("Groups:"); Console.WriteLine("Groups:");
TLChat chat = null; TLChat chat = null;
foreach (var chatObj in dialogs.Chats.OfType<TLChat>()) foreach (var chatObj in dialogs.Chats.OfType<TLChat>())
{ {
chat = chatObj as TLChat; chat = chatObj as TLChat;
Console.WriteLine($"Chat name: {chat.Title}"); Console.WriteLine($"Chat name: {chat.Title}");
var request = new TLRequestGetFullChat() { ChatId = chat.Id }; var request = new TLRequestGetFullChat() { ChatId = chat.Id };
var fullChat = await client.SendRequestAsync<TeleSharp.TL.Messages.TLChatFull>(request); var fullChat = await client.SendRequestAsync<TeleSharp.TL.Messages.TLChatFull>(request);
var participants = (fullChat.FullChat as TeleSharp.TL.TLChatFull).Participants as TLChatParticipants; var participants = (fullChat.FullChat as TeleSharp.TL.TLChatFull).Participants as TLChatParticipants;
foreach (var p in participants.Participants) foreach (var p in participants.Participants)
{ {
if (p is TLChatParticipant) if (p is TLChatParticipant)
{ {
var participant = p as TLChatParticipant; var participant = p as TLChatParticipant;
Console.WriteLine($"\t{participant.UserId}"); Console.WriteLine($"\t{participant.UserId}");
} }
else if (p is TLChatParticipantAdmin) else if (p is TLChatParticipantAdmin)
{ {
var participant = p as TLChatParticipantAdmin; var participant = p as TLChatParticipantAdmin;
Console.WriteLine($"\t{participant.UserId}**"); Console.WriteLine($"\t{participant.UserId}**");
} }
else if (p is TLChatParticipantCreator) else if (p is TLChatParticipantCreator)
{ {
var participant = p as TLChatParticipantCreator; var participant = p as TLChatParticipantCreator;
Console.WriteLine($"\t{participant.UserId}**"); Console.WriteLine($"\t{participant.UserId}**");
} }
} }
var peer = new TLInputPeerChat() { ChatId = chat.Id }; var peer = new TLInputPeerChat() { ChatId = chat.Id };
var m = await client.GetHistoryAsync(peer, 0, 0, 0); var m = await client.GetHistoryAsync(peer, 0, 0, 0);
Console.WriteLine(m); Console.WriteLine(m);
if (m is TLMessages) if (m is TLMessages)
{ {
var messages = m as TLMessages; var messages = m as TLMessages;
foreach (var message in messages.Messages) foreach (var message in messages.Messages)
{ {
if (message is TLMessage) if (message is TLMessage)
{ {
var m1 = message as TLMessage; var m1 = message as TLMessage;
Console.WriteLine($"\t\t{m1.Id} {m1.Message}"); Console.WriteLine($"\t\t{m1.Id} {m1.Message}");
} }
else if (message is TLMessageService) else if (message is TLMessageService)
{ {
var m1 = message as TLMessageService; var m1 = message as TLMessageService;
Console.WriteLine($"\t\t{m1.Id} {m1.Action}"); Console.WriteLine($"\t\t{m1.Id} {m1.Action}");
} }
} }
} }
else if (m is TLMessagesSlice) else if (m is TLMessagesSlice)
{ {
bool done = false; bool done = false;
int total = 0; int total = 0;
while (!done) while (!done)
{ {
var messages = m as TLMessagesSlice; var messages = m as TLMessagesSlice;
foreach (var m1 in messages.Messages) foreach (var m1 in messages.Messages)
{ {
if (m1 is TLMessage) if (m1 is TLMessage)
{ {
var message = m1 as TLMessage; var message = m1 as TLMessage;
Console.WriteLine($"\t\t{message.Id} {message.Message}"); Console.WriteLine($"\t\t{message.Id} {message.Message}");
++total; ++total;
} }
else if (m1 is TLMessageService) else if (m1 is TLMessageService)
{ {
var message = m1 as TLMessageService; var message = m1 as TLMessageService;
Console.WriteLine($"\t\t{message.Id} {message.Action}"); Console.WriteLine($"\t\t{message.Id} {message.Action}");
++total; ++total;
done = message.Action is TLMessageActionChatCreate; done = message.Action is TLMessageActionChatCreate;
} }
} }
m = await client.GetHistoryAsync(peer, total, 0, 0); m = await client.GetHistoryAsync(peer, total, 0, 0);
} }
} }
} }
// -- Wait in a loop to handle incoming updates. No need to poll. // -- Wait in a loop to handle incoming updates. No need to poll.
for (;;) for (;;)
{ {
await client.WaitEventAsync(); await client.WaitEventAsync();
} }
}
catch (Exception e)
{
Console.WriteLine(e);
}
} }
private void Client_Updates(TelegramClient client, TLAbsUpdates updates) 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 }; var peer = new TLInputPeerUser() { UserId = status.UserId };
client.SendMessageAsync(peer, "Você está online.").Wait(); 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) 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 try
{ {
var request = new TLRequestReadHistory(); var request = new TLRequestReadHistory();

View file

@ -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)
{
}
}
}

View file

@ -10,6 +10,7 @@ using TeleSharp.TL;
using TLSharp.Core.Exceptions; using TLSharp.Core.Exceptions;
using TLSharp.Core.MTProto; using TLSharp.Core.MTProto;
using TLSharp.Core.MTProto.Crypto; using TLSharp.Core.MTProto.Crypto;
using TLSharp.Core.Network.Exceptions;
using TLSharp.Core.Network.Requests; using TLSharp.Core.Network.Requests;
using TLSharp.Core.Utils; using TLSharp.Core.Utils;
@ -157,14 +158,14 @@ namespace TLSharp.Core.Network
public async Task<byte[]> Receive(TLMethod request, CancellationToken token = default(CancellationToken)) public async Task<byte[]> Receive(TLMethod request, CancellationToken token = default(CancellationToken))
{ {
while (!request.ConfirmReceived) while (!request.ConfirmReceived)
{ {
var result = DecodeMessage((await transport.Receive(token).ConfigureAwait(false)).Body); var result = DecodeMessage((await transport.Receive(token).ConfigureAwait(false)).Body);
using (var messageStream = new MemoryStream (result.Item1, false)) using (var messageStream = new MemoryStream(result.Item1, false))
using (var messageReader = new BinaryReader (messageStream)) 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(); token.ThrowIfCancellationRequested();
@ -173,14 +174,14 @@ namespace TLSharp.Core.Network
return null; return null;
} }
public async Task<byte[]> Receive(int timeoutms, CancellationToken token = default(CancellationToken)) public async Task<byte[]> 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 messageStream = new MemoryStream(result.Item1, false))
using (var messageReader = new BinaryReader(messageStream)) using (var messageReader = new BinaryReader(messageStream))
{ {
await processMessageAsync(result.Item2, result.Item3, messageReader, null); await ProcessMessageAsync(result.Item2, result.Item3, messageReader, null);
} }
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
@ -203,7 +204,7 @@ namespace TLSharp.Core.Network
await Receive(pingRequest, token).ConfigureAwait(false); await Receive(pingRequest, token).ConfigureAwait(false);
} }
private async Task<bool> processMessageAsync(ulong messageId, int sequence, BinaryReader messageReader, TeleSharp.TL.TLMethod request, CancellationToken token = default(CancellationToken)) private async Task<bool> ProcessMessageAsync(ulong messageId, int sequence, BinaryReader messageReader, TeleSharp.TL.TLMethod request, CancellationToken token = default(CancellationToken))
{ {
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
@ -330,7 +331,7 @@ namespace TLSharp.Core.Network
} }
using (BinaryReader compressedReader = new BinaryReader(ms)) 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; long beginPosition = messageReader.BaseStream.Position;
try try
{ {
var processedMessage = await processMessageAsync(innerMessageId, sequence, messageReader, request, token); var processedMessage = await ProcessMessageAsync(innerMessageId, sequence, messageReader, request, token);
if (!processedMessage) if (!processedMessage)
{ {
messageReader.BaseStream.Position = beginPosition + innerLength; messageReader.BaseStream.Position = beginPosition + innerLength;
@ -600,7 +601,7 @@ namespace TLSharp.Core.Network
} }
catch (InvalidOperationException e) catch (InvalidOperationException e)
{ {
throw e; throw;
} }
catch (Exception e) catch (Exception e)
{ {

View file

@ -102,13 +102,13 @@ namespace TLSharp.Core.Network
return new TcpMessage(seq, body); return new TcpMessage(seq, body);
} }
public async Task<TcpMessage> Receieve(int timeoutms) public async Task<TcpMessage> Receive(TimeSpan timeToWait)
{ {
var stream = tcpClient.GetStream(); var stream = tcpClient.GetStream();
var packetLengthBytes = new byte[4]; var packetLengthBytes = new byte[4];
var token = tokenSource.Token; var token = tokenSource.Token;
stream.ReadTimeout = timeoutms; stream.ReadTimeout = (int)timeToWait.TotalMilliseconds;
int bytes = 0; int bytes = 0;
try try
{ {
@ -118,7 +118,7 @@ namespace TLSharp.Core.Network
var socketError = io.InnerException as SocketException; var socketError = io.InnerException as SocketException;
if (socketError != null && socketError.SocketErrorCode == SocketError.TimedOut) if (socketError != null && socketError.SocketErrorCode == SocketError.TimedOut)
throw new OperationCanceledException(); throw new OperationCanceledException();
throw io; throw;
} }
if (bytes != 4) if (bytes != 4)
throw new InvalidOperationException("Couldn't read the packet length"); throw new InvalidOperationException("Couldn't read the packet length");

View file

@ -76,7 +76,6 @@
<Compile Include="TelegramClient.cs" /> <Compile Include="TelegramClient.cs" />
<Compile Include="Utils\Helpers.cs" /> <Compile Include="Utils\Helpers.cs" />
<Compile Include="Network\Sniffer.cs" /> <Compile Include="Network\Sniffer.cs" />
<Compile Include="Network\Exceptions.cs" />
<Compile Include="DataCenter.cs" /> <Compile Include="DataCenter.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -16,6 +16,7 @@ using TLSharp.Core.Auth;
using TLSharp.Core.Exceptions; using TLSharp.Core.Exceptions;
using TLSharp.Core.MTProto.Crypto; using TLSharp.Core.MTProto.Crypto;
using TLSharp.Core.Network; using TLSharp.Core.Network;
using TLSharp.Core.Network.Exceptions;
using TLSharp.Core.Utils; using TLSharp.Core.Utils;
using TLAuthorization = TeleSharp.TL.Auth.TLAuthorization; using TLAuthorization = TeleSharp.TL.Auth.TLAuthorization;
@ -164,7 +165,7 @@ namespace TLSharp.Core
_looping = false; _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; var lastPing = DateTime.UtcNow;
await SendPingAsync(); await SendPingAsync();
@ -172,7 +173,7 @@ namespace TLSharp.Core
{ {
try try
{ {
await WaitEventAsync(timeslicems, token); await WaitEventAsync(timeToWait, token);
} }
catch (OperationCanceledException) 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() public bool IsUserAuthorized()

View file

@ -1,5 +1,3 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="MarkerMetro.Unity.Ionic.Zlib" version="2.0.0.14" targetFramework="net452" />
<package id="NLog" version="4.4.12" targetFramework="net45" />
</packages> </packages>

View file

@ -128,7 +128,7 @@ namespace TLSharp.Tests
var hash = await client.SendCodeRequestAsync(NumberToAuthenticate); var hash = await client.SendCodeRequestAsync(NumberToAuthenticate);
var code = CodeToAuthenticate; // you can change code in debugger too 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"); 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) 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 }); await client.SendTypingAsync(new TLInputPeerUser() { UserId = user.Id });
@ -191,7 +191,7 @@ namespace TLSharp.Tests
await client.ConnectAsync(); await client.ConnectAsync();
var dialogs = (TLDialogs)await client.GetUserDialogsAsync(); var dialogs = (TLDialogs) await client.GetUserDialogsAsync();
var chat = dialogs.Chats var chat = dialogs.Chats
.OfType<TLChannel>() .OfType<TLChannel>()
.FirstOrDefault(c => c.Title == "TestGroup"); .FirstOrDefault(c => c.Title == "TestGroup");
@ -294,7 +294,7 @@ namespace TLSharp.Tests
VolumeId = photoLocation.VolumeId VolumeId = photoLocation.VolumeId
}, 1024); }, 1024);
var res = await client.GetUserDialogsAsync(); var res = await client.GetUserDialogsAsync();
Assert.IsTrue(resFile.Bytes.Length > 0); 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 // At this point you would send yourself a UPDATE_1 message to trigger update