pr review updates

This commit is contained in:
mark 2020-05-10 18:19:52 +01:00
parent 43d9d12167
commit f258b6ede8
5 changed files with 228 additions and 257 deletions

113
README.md
View file

@ -145,7 +145,6 @@ Full code you can see at [DownloadFileFromContactTest](https://github.com/sochix
using TLSharp.Core; using TLSharp.Core;
using System.Linq; using System.Linq;
using TeleSharp.TL.Messages; using TeleSharp.TL.Messages;
using System.Collections.Generic;
namespace TLSharpPOC namespace TLSharpPOC
{ {
@ -163,17 +162,9 @@ Full code you can see at [DownloadFileFromContactTest](https://github.com/sochix
{ {
TelegramClient client = null; TelegramClient client = null;
// -- if necessary, IP can be changed so the client can connect to the test network. client = new TelegramClient(APIId, APIHash);
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 // subscribe an event to receive live messages
client.Updates += Client_Updates; client.Updates += ClientUpdates;
await client.ConnectAsync(); await client.ConnectAsync();
Console.WriteLine($"Authorised: {client.IsUserAuthorized()}"); Console.WriteLine($"Authorised: {client.IsUserAuthorized()}");
TLUser user = null; TLUser user = null;
@ -225,70 +216,58 @@ Full code you can see at [DownloadFileFromContactTest](https://github.com/sochix
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 chatParticipant)
{ {
var participant = p as TLChatParticipant; Console.WriteLine($"\t{chatParticipant.UserId}");
Console.WriteLine($"\t{participant.UserId}");
} }
else if (p is TLChatParticipantAdmin) else if (p is TLChatParticipantAdmin chatParticipantAdmin)
{ {
var participant = p as TLChatParticipantAdmin; Console.WriteLine($"\t{chatParticipantAdmin.UserId}**");
Console.WriteLine($"\t{participant.UserId}**");
} }
else if (p is TLChatParticipantCreator) else if (p is TLChatParticipantCreator chatParticipantCreator)
{ {
var participant = p as TLChatParticipantCreator; Console.WriteLine($"\t{chatParticipantCreator.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 msg = await client.GetHistoryAsync(peer, 0, 0, 0);
Console.WriteLine(m); Console.WriteLine(msg);
if (m is TLMessages) if (msg is TLMessages messages)
{ {
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 m1)
{ {
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 msgService)
{ {
var m1 = message as TLMessageService; Console.WriteLine($"\t\t{msgService.Id} {msgService.Action}");
Console.WriteLine($"\t\t{m1.Id} {m1.Action}");
} }
} }
} }
else if (m is TLMessagesSlice) else if (msg is TLMessagesSlice messagesSlice)
{ {
bool done = false; bool done = false;
int total = 0; int total = 0;
while (!done) while (!done)
{ {
var messages = m as TLMessagesSlice; foreach (var m1 in messagesSlice.Messages)
foreach (var m1 in messages.Messages)
{ {
if (m1 is TLMessage) if (m1 is TLMessage message)
{ {
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 messageService)
{ {
var message = m1 as TLMessageService; Console.WriteLine($"\t\t{messageService.Id} {messageService.Action}");
Console.WriteLine($"\t\t{message.Id} {message.Action}");
++total; ++total;
done = message.Action is TLMessageActionChatCreate; done = messageService.Action is TLMessageActionChatCreate;
} }
} }
m = await client.GetHistoryAsync(peer, total, 0, 0); msg = await client.GetHistoryAsync(peer, total, 0, 0);
} }
} }
} }
@ -296,62 +275,49 @@ Full code you can see at [DownloadFileFromContactTest](https://github.com/sochix
// -- 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(TimeSpan.FromSeconds(1));
} }
} }
private void Client_Updates(TelegramClient client, TLAbsUpdates updates) private void ClientUpdates(TelegramClient client, TLAbsUpdates updates)
{ {
Console.WriteLine($"Got update: {updates}"); Console.WriteLine($"Got update: {updates}");
if (updates is TLUpdateShort) if (updates is TLUpdateShort updateShort)
{ {
var updateShort = updates as TLUpdateShort;
Console.WriteLine($"Short: {updateShort.Update}"); Console.WriteLine($"Short: {updateShort.Update}");
if (updateShort.Update is TLUpdateUserStatus) if (updateShort.Update is TLUpdateUserStatus status)
{ {
var status = updateShort.Update as TLUpdateUserStatus;
Console.WriteLine($"User {status.UserId} is {status.Status}"); Console.WriteLine($"User {status.UserId} is {status.Status}");
if (status.Status is TLUserStatusOnline) if (status.Status is TLUserStatusOnline)
{
try
{ {
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 (Exception e) }
}
else if (updates is TLUpdateShortMessage message)
{ {
Console.WriteLine(e);
}
}
}
}
else if (updates is TLUpdateShortMessage)
{
var message = updates as TLUpdateShortMessage;
Console.WriteLine($"Message: {message.Message}"); Console.WriteLine($"Message: {message.Message}");
MarkMessageRead(client, new TLInputPeerUser() { UserId = message.UserId }, message.Id); MarkMessageRead(client, new TLInputPeerUser() { UserId = message.UserId }, message.Id);
} }
else if (updates is TLUpdateShortChatMessage) else if (updates is TLUpdateShortChatMessage shortChatMessage)
{ {
var message = updates as TLUpdateShortChatMessage; Console.WriteLine($"Chat Message: {shortChatMessage.Message}");
Console.WriteLine($"Chat Message: {message.Message}"); MarkMessageRead(client, new TLInputPeerChat() { ChatId = shortChatMessage.ChatId }, shortChatMessage.Id);
MarkMessageRead(client, new TLInputPeerChat() { ChatId = message.ChatId }, message.Id);
} }
else if (updates is TLUpdates) else if (updates is TLUpdates allUpdates)
{ {
var allUpdates = updates as TLUpdates;
foreach (var update in allUpdates.Updates) foreach (var update in allUpdates.Updates)
{ {
Console.WriteLine($"\t{update}"); Console.WriteLine($"\t{update}");
if (update is TLUpdateNewChannelMessage) if (update is TLUpdateNewChannelMessage metaMessage)
{ {
var metaMessage = update as TLUpdateNewChannelMessage; var channelMsg = metaMessage.Message as TLMessage;
var message = metaMessage.Message as TLMessage; Console.WriteLine($"Channel message: {channelMsg.Message}");
Console.WriteLine($"Channel message: {message.Message}");
var channel = allUpdates.Chats[0] as TLChannel; var channel = allUpdates.Chats[0] as TLChannel;
MarkMessageRead(client, MarkMessageRead(client,
new TLInputPeerChannel() { ChannelId = channel.Id, AccessHash = channel.AccessHash.Value }, new TLInputPeerChannel() { ChannelId = channel.Id, AccessHash = channel.AccessHash.Value },
message.Id ); channelMsg.Id);
} }
} }
@ -369,7 +335,6 @@ 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.
try try
{ {
var request = new TLRequestReadHistory(); var request = new TLRequestReadHistory();
@ -377,10 +342,10 @@ Full code you can see at [DownloadFileFromContactTest](https://github.com/sochix
request.Peer = peer; request.Peer = peer;
client.SendRequestAsync<bool>(request).Wait(); client.SendRequestAsync<bool>(request).Wait();
} }
catch (InvalidOperationException e){ catch (InvalidOperationException e)
System.Console.WriteLine($"MarkMessageRead Error: {e.getMessage()}") {
Console.WriteLine($"MarkMessageRead Error: {e.Message}");
} }
} }
} }
} }

View file

@ -42,7 +42,7 @@ namespace TLSharp.Core.Network
return confirmed ? session.Sequence++ * 2 + 1 : session.Sequence * 2; return confirmed ? session.Sequence++ * 2 + 1 : session.Sequence * 2;
} }
public async Task Send(TLMethod request, CancellationToken token = default(CancellationToken)) public async Task Send(TeleSharp.TL.TLMethod request, CancellationToken token = default(CancellationToken))
{ {
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
@ -69,7 +69,7 @@ namespace TLSharp.Core.Network
session.Save(); session.Save();
} }
public async Task Send(byte[] packet, TLMethod request, CancellationToken token = default(CancellationToken)) public async Task Send(byte[] packet, TeleSharp.TL.TLMethod request, CancellationToken token = default(CancellationToken))
{ {
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
@ -156,7 +156,7 @@ namespace TLSharp.Core.Network
return new Tuple<byte[], ulong, int>(message, remoteMessageId, remoteSequence); return new Tuple<byte[], ulong, int>(message, remoteMessageId, remoteSequence);
} }
public async Task<byte[]> Receive(TLMethod request, CancellationToken token = default(CancellationToken)) public async Task<byte[]> Receive(TeleSharp.TL.TLMethod request, CancellationToken token = default(CancellationToken))
{ {
while (!request.ConfirmReceived) while (!request.ConfirmReceived)
{ {
@ -338,7 +338,7 @@ namespace TLSharp.Core.Network
return true; return true;
} }
private bool HandleRpcResult(ulong messageId, int sequence, BinaryReader messageReader, TLMethod request) private bool HandleRpcResult(ulong messageId, int sequence, BinaryReader messageReader, TeleSharp.TL.TLMethod request)
{ {
uint code = messageReader.ReadUInt32(); uint code = messageReader.ReadUInt32();
ulong requestId = messageReader.ReadUInt64(); ulong requestId = messageReader.ReadUInt64();
@ -561,7 +561,7 @@ namespace TLSharp.Core.Network
return true; return true;
} }
private bool HandlePong(ulong messageId, int sequence, BinaryReader messageReader, TLMethod request) private bool HandlePong(ulong messageId, int sequence, BinaryReader messageReader, TeleSharp.TL.TLMethod request)
{ {
uint code = messageReader.ReadUInt32(); uint code = messageReader.ReadUInt32();
ulong msgId = messageReader.ReadUInt64(); ulong msgId = messageReader.ReadUInt64();

View file

@ -113,7 +113,8 @@ namespace TLSharp.Core.Network
try try
{ {
bytes = stream.Read(packetLengthBytes, 0, 4); bytes = stream.Read(packetLengthBytes, 0, 4);
} catch (System.IO.IOException io) }
catch (System.IO.IOException io)
{ {
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)

View file

@ -25,16 +25,16 @@ namespace TLSharp.Core
public class TelegramClient : IDisposable public class TelegramClient : IDisposable
{ {
private MtProtoSender sender; private MtProtoSender sender;
private AuthKey _key; private AuthKey key;
private TcpTransport transport; private TcpTransport transport;
private string apiHash = ""; private string apiHash = String.Empty;
private int apiId = 0; private int apiId = 0;
private Session session; private Session session;
private List<TLDcOption> dcOptions; private List<TLDcOption> dcOptions;
private TcpClientConnectionHandler handler; private TcpClientConnectionHandler handler;
private DataCenterIPVersion dcIpVersion; private DataCenterIPVersion dcIpVersion;
private bool _looping = true; private bool looping = true;
public delegate void UpdatesEvent (TelegramClient source, TLAbsUpdates updates); public delegate void UpdatesEvent (TelegramClient source, TLAbsUpdates updates);
public delegate void ClientEvent(TelegramClient source); public delegate void ClientEvent(TelegramClient source);
@ -162,14 +162,14 @@ namespace TLSharp.Core
public void Close() public void Close()
{ {
_looping = false; looping = false;
} }
public async Task MainLoopAsync(TimeSpan timeToWait, 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();
while (_looping) while (looping)
{ {
try try
{ {

View file

@ -12,6 +12,7 @@ using TeleSharp.TL;
using TeleSharp.TL.Messages; using TeleSharp.TL.Messages;
using TLSharp.Core; using TLSharp.Core;
using TLSharp.Core.Exceptions; using TLSharp.Core.Exceptions;
using TLSharp.Core.Network.Exceptions;
using TLSharp.Core.Utils; using TLSharp.Core.Utils;
namespace TLSharp.Tests namespace TLSharp.Tests
@ -332,7 +333,7 @@ namespace TLSharp.Tests
{ {
await CheckPhones(); await CheckPhones();
} }
catch (Core.Network.Exceptions.FloodException floodException) catch (FloodException floodException)
{ {
Console.WriteLine($"FLOODEXCEPTION: {floodException}"); Console.WriteLine($"FLOODEXCEPTION: {floodException}");
Thread.Sleep(floodException.TimeToWait); Thread.Sleep(floodException.TimeToWait);
@ -369,7 +370,7 @@ namespace TLSharp.Tests
if (user == null) if (user == null)
{ {
throw new Exception("Username was not found: " + UserNameToSendMessage); throw new System.Exception("Username was not found: " + UserNameToSendMessage);
} }
await client.SendTypingAsync(new TLInputPeerUser() { UserId = user.Id }); await client.SendTypingAsync(new TLInputPeerUser() { UserId = user.Id });
@ -413,13 +414,16 @@ namespace TLSharp.Tests
} }
} }
// Things to note:- If the updates are not getting triggered, please re-authenticate the user
// Would trigger the updates on a seperate thread if possible
client.Updates += (TelegramClient tclient, TLAbsUpdates updates) => client.Updates += (TelegramClient tclient, TLAbsUpdates updates) =>
{ {
if (updates is TLUpdates) if (updates is TLUpdates)
{ {
var allupdates = updates as TLUpdates; var allUpdates = updates as TLUpdates;
foreach (var update in allupdates.Updates) foreach (var update in allUpdates.Updates)
{ {
if (update is TLUpdateNewMessage) if (update is TLUpdateNewMessage)
{ {
@ -431,9 +435,10 @@ namespace TLSharp.Tests
} }
}; };
await client.MainLoopAsync(new TimeSpan(0, 0, 1)); Console.WriteLine("Send yourself an UPDATE_1 message to trigger update during loop");
Debug.WriteLine("Send yourself an UPDATE_1 message to trigger update during loop");
// At this point you would send yourself a UPDATE_1 message to trigger update await client.MainLoopAsync(new TimeSpan(0, 0, 1));
Assert.IsTrue(newMsgs.Count == 1); Assert.IsTrue(newMsgs.Count == 1);
Assert.IsTrue(newMsgs.First().Message.Equals("UPDATE_1")); Assert.IsTrue(newMsgs.First().Message.Equals("UPDATE_1"));