Esempio n. 1
0
 public static TelegramSettings GenerateAuthentication(Service service)
 {
     try
     {
         service.DebugPrint("Fetching nearest DC...");
         var settings = new TelegramSettings();
         var authInfo = TelegramUtils.RunSynchronously(FetchNewAuthentication(DefaultTransportConfig));
         using (var client = new TelegramClient(DefaultTransportConfig, 
             new ConnectionConfig(authInfo.AuthKey, authInfo.Salt), AppInfo))
         {
             TelegramUtils.RunSynchronously(client.Connect());
             var nearestDcId = (NearestDc)TelegramUtils.RunSynchronously(client.Methods.HelpGetNearestDcAsync(new HelpGetNearestDcArgs{}));
             var config = (Config)TelegramUtils.RunSynchronously(client.Methods.HelpGetConfigAsync(new HelpGetConfigArgs{ }));
             var dcOption = config.DcOptions.OfType<DcOption>().FirstOrDefault(x => x.Id == nearestDcId.NearestDcProperty);
             settings.NearestDcId = nearestDcId.NearestDcProperty;
             settings.NearestDcIp = dcOption.IpAddress;
             settings.NearestDcPort = (int)dcOption.Port;
         }
         service.DebugPrint("Generating authentication on nearest DC...");
         var authInfo2 = TelegramUtils.RunSynchronously(FetchNewAuthentication(
             new TcpClientTransportConfig(settings.NearestDcIp, settings.NearestDcPort)));
         settings.AuthKey = authInfo2.AuthKey;
         settings.Salt = authInfo2.Salt;
         service.DebugPrint("Great! Ready for the service to start.");
         return settings;
     }
     catch (Exception ex)
     {
         service.DebugPrint("Error in GenerateAuthentication: " + ex);
     }
     return null;
 }
Esempio n. 2
0
 private async Task RemoveProfilePhoto(TelegramClient client)
 {
     await client.Methods.PhotosUpdateProfilePhotoAsync(new PhotosUpdateProfilePhotoArgs
     {
         Id = new InputPhotoEmpty(),
         Crop = new InputPhotoCropAuto()
     });
 }
Esempio n. 3
0
 public FullClientDisposable(Telegram telegram)
 {
     if (telegram.IsFullClientConnected)
     {
         _client = telegram._fullClient;
         _isFullClient = true;
     }
     else
     {
         var transportConfig =
             new TcpClientTransportConfig(telegram._settings.NearestDcIp, telegram._settings.NearestDcPort);
         var client = new TelegramClient(transportConfig,
             new ConnectionConfig(telegram._settings.AuthKey, telegram._settings.Salt), AppInfo);
         var result = TelegramUtils.RunSynchronously(client.Connect());
         if (result != MTProtoConnectResult.Success)
         {
             throw new Exception("Failed to connect: " + result);
         }
         _client = client;
         _isFullClient = false;
     }
 }
Esempio n. 4
0
 private byte[] FetchDocumentBytes(Document document, uint offset, uint limit)
 {
     if (document.DcId == _settings.NearestDcId)
     {
         using (var clientDisposable = new FullClientDisposable(this))
         {
             return FetchDocumentBytes(clientDisposable.Client, document, offset, limit);
         }
     }
     else
     {
         try
         {
             if (cachedClient == null)
             {
                 cachedClient = GetClient((int) document.DcId);
             }
             return FetchDocumentBytes(cachedClient, document, offset, limit);
         }
         catch (Exception ex)
         {
             DebugPrint("Failed to obtain client from DC manager: " + ex);
             return null;
         }
     }
 }
Esempio n. 5
0
        private void GetConfig(TelegramClient client)
        {
			DebugPrint (">>>>>>>>>>>>>> Getting config!");
            var config = (Config)TelegramUtils.RunSynchronously(client.Methods.HelpGetConfigAsync(new HelpGetConfigArgs
                {
                }));
            _config = config;
			DebugPrint (ObjectDumper.Dump(_config));
        }
Esempio n. 6
0
        private static byte[] FetchFileBytes(TelegramClient client, FileLocation fileLocation)
        {
            try
            {
                var response = (UploadFile)TelegramUtils.RunSynchronously(client.Methods.UploadGetFileAsync(
                    new UploadGetFileArgs
                    {
                        Location = new InputFileLocation
                        {
                            VolumeId = fileLocation.VolumeId,
                            LocalId = fileLocation.LocalId,
                            Secret = fileLocation.Secret
                        },
                        Offset = 0,
                        Limit = uint.MaxValue,
                    }));
                return response.Bytes;
            }
            catch (Exception ex)
            {
                Utils.DebugPrint("Exception while fetching file bytes");
                return null;
            }

        }
Esempio n. 7
0
 private async Task<IUser> GetUser(IInputUser user, TelegramClient client)
 {
     return (await GetUsers(new List<IInputUser> { user }, client)).First();
 }
Esempio n. 8
0
 void SendToResponseDispatcher(IUpdates iUpdate,TelegramClient client)
 {
         var mtProtoClientConnection = client.Connection as MTProtoClientConnection;
         if (mtProtoClientConnection != null)
         {
             var responseDispatcher = mtProtoClientConnection.ResponseDispatcher as ResponseDispatcher;
             if (responseDispatcher != null)
             {
                 SharpMTProto.Schema.IMessage tempMessage = new SharpMTProto.Schema.Message(0,0,iUpdate);
                 responseDispatcher.DispatchAsync(tempMessage).Wait();
             }
         }
 }
Esempio n. 9
0
 private void SendReceivedMessages(TelegramClient optionalClient, uint maxId)
 {
     Task.Factory.StartNew(() =>
     {
         using (var disposable = new OptionalClientDisposable(this, optionalClient))
         {
             var items = TelegramUtils.RunSynchronously(disposable.Client.Methods
                 .MessagesReceivedMessagesAsync(new MessagesReceivedMessagesArgs
             {
                     MaxId = maxId,
             }));
             DebugPrint("items " + ObjectDumper.Dump(items));
         }
     }); 
 }
Esempio n. 10
0
 public OptionalClientDisposable(Telegram telegram, TelegramClient optionalClient = null)
 {
     _optionalClient = optionalClient;
     if (_optionalClient == null)
     {
         _fullClient = new FullClientDisposable(telegram);
     }
 }
Esempio n. 11
0
        private IMessage GetMessage(uint messageId, TelegramClient optionalClient, uint senderId = 0, bool superGroup = false)
        {
            Func<TelegramClient,IMessage> fetch = client =>
            {
                var messagesmessages = FetchMessage(messageId, client, senderId, superGroup);
                var messages = TelegramUtils.GetMessagesFromMessagesMessages(messagesmessages);
                var chats = TelegramUtils.GetChatsFromMessagesMessages(messagesmessages);
                var users = TelegramUtils.GetUsersFromMessagesMessages(messagesmessages);

                _dialogs.AddUsers(users);
                _dialogs.AddChats(chats);

                if (messages != null && messages.Count > 0)
                {
                    return messages[0];
                }
                return null;
            };

            if (optionalClient != null)
            {
                return fetch(optionalClient);
            }
            else
            {
                using (var client = new FullClientDisposable(this))
                {
                    return fetch(client.Client);
                }
            }  
        }
Esempio n. 12
0
 private IMessagesMessages FetchMessage(uint id, TelegramClient client, uint toId, bool superGroup)
 {
     if (superGroup)
     {
         try
         {
             var result = TelegramUtils.RunSynchronously(client.Methods.ChannelsGetMessagesAsync(new ChannelsGetMessagesArgs
             {
                 Channel = new InputChannel
                 {
                     ChannelId = toId,
                     AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(toId))
                 },
                 Id = new List<uint>
                 {
                     id
                 }
             }));
             return result;
         }
         catch (Exception e)
         {
             DebugPrint("Exeption while getting channel message" +  e);
             return MakeMessagesMessages(new List<IChat>(), new List<IUser>(), new List<IMessage>());
         }
     }
     else
     {
         return TelegramUtils.RunSynchronously(client.Methods.MessagesGetMessagesAsync(new MessagesGetMessagesArgs
         {
             Id = new List<uint>
             {
                 id
             }
         }));
     }
 }
Esempio n. 13
0
 private async Task<IUploadFile> FetchFileBytes(TelegramClient client, FileLocation thumbnailLocation)
 {
     return await client.Methods.UploadGetFileAsync(new UploadGetFileArgs
     {
         Location = new InputFileLocation
         {
             VolumeId = thumbnailLocation.VolumeId,
             LocalId = thumbnailLocation.LocalId,
             Secret = thumbnailLocation.Secret
         },
         Offset = 0,
         Limit = uint.MaxValue,
     });
 }
Esempio n. 14
0
            private async Task<IInputFile> UploadProfilePhoto(Telegram service, TelegramClient client,
                byte[] resizedPhoto)
            {
                var fileId = service.GenerateRandomId();
                const int chunkSize = 65536;
                var chunk = new byte[chunkSize];
                uint chunkNumber = 0;
                var offset = 0;
                using (var memoryStream = new MemoryStream(resizedPhoto))
                {
                    int bytesRead;
                    while ((bytesRead = memoryStream.Read(chunk, 0, chunk.Length)) > 0)
                    {
                        //RPC call
                        var uploaded =
                            await client.Methods.UploadSaveFilePartAsync(new UploadSaveFilePartArgs
                            {
                                Bytes = chunk,
                                FileId = fileId,
                                FilePart = chunkNumber
                            });

                        if (!uploaded)
                        {
                            return null;
                        }
                        chunkNumber++;
                        offset += bytesRead;
                    }

                    return new InputFile
                    {
                        Id = fileId,
                        Md5Checksum = "",
                        Name = service.GenerateRandomId() + ".jpeg",
                        Parts = chunkNumber
                    };
                }
            }
Esempio n. 15
0
            private async Task SetProfilePhoto(Telegram service, TelegramClient client, IInputFile inputFile)
            {
                var iPhoto = await client.Methods.PhotosUploadProfilePhotoAsync(new PhotosUploadProfilePhotoArgs
                {
                    Caption = "",
                    Crop = new InputPhotoCropAuto(),
                    File = inputFile,
                    GeoPoint = new InputGeoPointEmpty()
                });

                var photo = iPhoto as PhotosPhoto;
                if (photo != null)
                {
                    service.Dialogs.AddUsers(photo.Users);
                }

                var photoObj = photo.Photo as Photo;

                if (photoObj == null)
                {
                    return;
                }

                await client.Methods.PhotosUpdateProfilePhotoAsync(new PhotosUpdateProfilePhotoArgs
                {
                    Id = new InputPhoto
                    {
                        Id = photoObj.Id,
                    },
                    Crop = new InputPhotoCropAuto()
                });
            }
Esempio n. 16
0
        public override void Connect(WakeLock wakeLock)
        {
            Disconnect();
            var sessionId = GetRandomId();
            var transportConfig = 
                new TcpClientTransportConfig(_settings.NearestDcIp, _settings.NearestDcPort);
            using (var client = new TelegramClient(transportConfig, 
                                    new ConnectionConfig(_settings.AuthKey, _settings.Salt), AppInfo))
            {
                var result = TelegramUtils.RunSynchronously(client.Connect());
                if (result != MTProtoConnectResult.Success)
                {
                    throw new Exception("Failed to connect: " + result);
                }   
                DebugPrint("Registering long poller...");
                var registerDeviceResult = TelegramUtils.RunSynchronously(client.Methods.AccountRegisterDeviceAsync(
                    new AccountRegisterDeviceArgs
                {
                    TokenType = 7,
                    Token = sessionId.ToString(CultureInfo.InvariantCulture),
                }));
                if (!registerDeviceResult)
                {
                    throw new Exception("Failed to register long poller...");
                }

                DebugPrint(">>>>>>>>>>>>>> Fetching state!");
                FetchState(client);
                DebugPrint (">>>>>>>>>>>>>> Fetching dialogs!");
                GetDialogs(client);
                GetConfig(client);
            }

            DebugPrint("Starting long poller...");
            if (_longPollClient != null)
            {
                _longPollClient.OnUpdateTooLong -= OnLongPollClientUpdateTooLong;
                _longPollClient.OnClosedInternally -= OnLongPollClientClosed;
            }
            _longPollerAborted = false;
            _longPollClient = new TelegramClient(transportConfig, 
                new ConnectionConfig(_settings.AuthKey, _settings.Salt) { SessionId = sessionId }, AppInfo);
            var result2 = TelegramUtils.RunSynchronously(_longPollClient.Connect());
            if (result2 != MTProtoConnectResult.Success)
            {
                throw new Exception("Failed to connect long poll client: " + result2);
            } 
            _longPollClient.OnUpdateTooLong += OnLongPollClientUpdateTooLong;
            _longPollClient.OnClosedInternally += OnLongPollClientClosed;
           	ScheduleLongPollPing();
            DebugPrint("Long poller started!");
        }
Esempio n. 17
0
        private void ProcessIncomingPayload(List<object> payloads, bool useCurrentTime, TelegramClient optionalClient = null)
        {
            uint maxMessageId = 0;

            foreach (var payload in AdjustUpdates(payloads))
            {
                var update = NormalizeUpdateIfNeeded(payload);

                var shortMessage = update as UpdateShortMessage;
                var shortChatMessage = update as UpdateShortChatMessage;
                var typing = update as UpdateUserTyping;
                var typingChat = update as UpdateChatUserTyping;
                var userStatus = update as UpdateUserStatus;
                var messageService = update as MessageService;
                var updateChatParticipants = update as UpdateChatParticipants;
                var updateContactRegistered = update as UpdateContactRegistered;
                var updateContactLink = update as UpdateContactLink;
                var updateUserPhoto = update as UpdateUserPhoto;
                var updateReadHistoryInbox = update as UpdateReadHistoryInbox;
                var updateReadHistoryOutbox = update as UpdateReadHistoryOutbox;
                var updateReadChannelInbox = update as UpdateReadChannelInbox;
                var updateReadChannelOutbox = update as UpdateReadChannelOutbox;
                var updateChannelTooLong = update as UpdateChannelTooLong;
                var updateDeleteChannelMessage = update as UpdateDeleteChannelMessages;
                var updateEditChannelMessage = update as UpdateEditChannelMessage;
                var updateChatAdmins = update as UpdateChatAdmins;
                var updateChannel = update as UpdateChannel;
                var message = update as SharpTelegram.Schema.Message;
                var user = update as IUser;
                var chat = update as IChat;

                DebugPrint(">>>>>> The type of object in process incoming payload is " + ObjectDumper.Dump(update));

                if (shortMessage != null)
                {
                    if (!string.IsNullOrWhiteSpace(shortMessage.Message))
                    {
                        var fromId = shortMessage.UserId.ToString(CultureInfo.InvariantCulture);
                        var shortMessageUser = _dialogs.GetUser(shortMessage.UserId);
                        if (shortMessageUser == null)
                        {
                            DebugPrint(">>>>> User is null, fetching user from the server");
                            GetMessage(shortMessage.Id, optionalClient);
                        }

                        EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                            Bubble.BubbleDirection.Incoming,
                            fromId, false, this, false, false));
                        TextBubble textBubble = new TextBubble(
                                            useCurrentTime ? Time.GetNowUnixTimestamp() : (long)shortMessage.Date,
                                            shortMessage.Out != null ? Bubble.BubbleDirection.Outgoing : Bubble.BubbleDirection.Incoming,
                                            fromId, null, false, this, shortMessage.Message,
                                            shortMessage.Id.ToString(CultureInfo.InvariantCulture));

                        if (shortMessage.Out != null)
                        {
                            textBubble.Status = Bubble.BubbleStatus.Sent;
                        }
                        if (textBubble.Direction == Bubble.BubbleDirection.Incoming)
                        {
                            if (shortMessage.ReplyToMsgId != 0)
                            {
                                var iReplyMessage = GetMessage(shortMessage.ReplyToMsgId, optionalClient);
                                DebugPrint(">>> got message " + ObjectDumper.Dump(iReplyMessage));
                                var replyMessage = iReplyMessage as Message;
                                AddQuotedMessageToBubble(replyMessage, textBubble);

                            }
                        }
                        EventBubble(textBubble);
                    }
                    if (shortMessage.Id > maxMessageId)
                    {
                        maxMessageId = shortMessage.Id;
                    }
                }
                else if (updateUserPhoto != null)
                {
                    var iUpdatedUser = _dialogs.GetUser(updateUserPhoto.UserId);
                    var updatedUser = iUpdatedUser as User;
                    if (updatedUser != null)
                    {
                        updatedUser.Photo = updateUserPhoto.Photo;
                        InvalidateThumbnail(updatedUser.Id.ToString(), false, false);
                        InvalidateThumbnail(updatedUser.Id.ToString(), false, true);
                    }
                    _dialogs.AddUser(updatedUser);
                }
                else if (updateChannel != null)
                {
                    var channel = _dialogs.GetChat(updateChannel.ChannelId) as Channel;
                    if (channel != null)
                    {
                        if (channel.Left != null)
                        { 
                            var bubbleGroup = BubbleGroupManager.FindWithAddress(this, updateChannel.ChannelId.ToString());
                            Platform.DeleteBubbleGroup(new BubbleGroup[] { bubbleGroup });
                        }
                    }
                }
                else if (updateChatAdmins != null)
                {
                    var chatToUpdate = _dialogs.GetUser(updateChatAdmins.ChatId) as Chat;
                    if (chatToUpdate != null)
                    {
                        if (updateChatAdmins.Enabled)
                        {
                            chatToUpdate.AdminsEnabled = new True();
                        }
                        else
                        {
                            chatToUpdate.AdminsEnabled = null;
                        }
                    }
                    _dialogs.AddChat(chatToUpdate);
                }
                else if (updateReadHistoryOutbox != null)
                {
                    var iPeer = updateReadHistoryOutbox.Peer;
                    var peerChat = iPeer as PeerChat;
                    var peerUser = iPeer as PeerUser;

                    if (peerUser != null)
                    {
                        BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                            peerUser.UserId.ToString(CultureInfo.InvariantCulture));
                        DebugPrint("Found bubble group " + bubbleGroup);
                        if (bubbleGroup != null)
                        {
                            string idString = bubbleGroup.LastBubbleSafe().IdService;
                            if (idString == updateReadHistoryOutbox.MaxId.ToString(CultureInfo.InvariantCulture))
                            {
                                EventBubble(
                                    new ReadBubble(Time.GetNowUnixTimestamp(),
                                        Bubble.BubbleDirection.Incoming, this,
                                        peerUser.UserId.ToString(CultureInfo.InvariantCulture), null,
                                        Time.GetNowUnixTimestamp(), false, false));
                            }
                        }
                    }
                    else if (peerChat != null)
                    {
                        BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                           peerChat.ChatId.ToString(CultureInfo.InvariantCulture));
                        if (bubbleGroup != null)
                        {
                            string idString = bubbleGroup.LastBubbleSafe().IdService;
                            if (idString == updateReadHistoryOutbox.MaxId.ToString(CultureInfo.InvariantCulture))
                            {
                                EventBubble(
                                    new ReadBubble(
                                        Time.GetNowUnixTimestamp(),
                                        Bubble.BubbleDirection.Incoming, this,
                                        peerChat.ChatId.ToString(CultureInfo.InvariantCulture), DisaReadTime.SingletonPartyParticipantAddress,
                                        Time.GetNowUnixTimestamp(), true, false));
                            }
                        }

                    }

                }
                else if (updateReadChannelOutbox != null)
                {
                    BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                          updateReadChannelOutbox.ChannelId.ToString(CultureInfo.InvariantCulture));
                    if (bubbleGroup != null)
                    {
                        string idString = bubbleGroup.LastBubbleSafe().IdService;
                        if (idString == updateReadChannelOutbox.MaxId.ToString(CultureInfo.InvariantCulture))
                        {
                            EventBubble(
                                new ReadBubble(
                                    Time.GetNowUnixTimestamp(),
                                    Bubble.BubbleDirection.Incoming, this,
                                    updateReadChannelOutbox.ChannelId.ToString(CultureInfo.InvariantCulture), DisaReadTime.SingletonPartyParticipantAddress,
                                    Time.GetNowUnixTimestamp(), true, false));
                        }
                    }
                }
                else if (updateReadHistoryInbox != null)
                {
                    DebugPrint(">>> In update read history inbox");
                    var iPeer = updateReadHistoryInbox.Peer;
                    var peerChat = iPeer as PeerChat;
                    var peerUser = iPeer as PeerUser;

                    if (peerUser != null)
                    {
                        BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                            peerUser.UserId.ToString(CultureInfo.InvariantCulture));

                        if (bubbleGroup == null)
                        {
                            continue;
                        }

                        string idString = bubbleGroup.LastBubbleSafe().IdService;
                        DebugPrint("idstring" + idString);
                        if (idString != null)
                        {
                            if (uint.Parse(idString) <= updateReadHistoryInbox.MaxId)
                            {
                                BubbleGroupManager.SetUnread(this, false, peerUser.UserId.ToString(CultureInfo.InvariantCulture));
                                NotificationManager.Remove(this, peerUser.UserId.ToString(CultureInfo.InvariantCulture));
                            }
                        }

                    }
                    else if (peerChat != null)
                    {
                        BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                            peerChat.ChatId.ToString(CultureInfo.InvariantCulture));
                        if (bubbleGroup == null)
                        {
                            continue;
                        }
                        string idString = bubbleGroup.LastBubbleSafe().IdService;
                        if (idString != null)
                        {
                            if (uint.Parse(idString) == updateReadHistoryInbox.MaxId)
                            {
                                BubbleGroupManager.SetUnread(this, false,
                                    peerChat.ChatId.ToString(CultureInfo.InvariantCulture));
                                NotificationManager.Remove(this, peerChat.ChatId.ToString(CultureInfo.InvariantCulture));
                            }
                        }

                    }

                }
                else if (updateReadChannelInbox != null)
                {
                    BubbleGroup bubbleGroup = BubbleGroupManager.FindWithAddress(this,
                                              updateReadChannelInbox.ChannelId.ToString(CultureInfo.InvariantCulture));
                    if (bubbleGroup == null)
                    {
                        continue;
                    }

                    string idString = bubbleGroup.LastBubbleSafe().IdService;
                    DebugPrint("idstring" + idString);
                    if (idString != null)
                    {
                        if (uint.Parse(idString) <= updateReadChannelInbox.MaxId)
                        {
                            BubbleGroupManager.SetUnread(this, false, updateReadChannelInbox.ChannelId.ToString(CultureInfo.InvariantCulture));
                            NotificationManager.Remove(this, updateReadChannelInbox.ChannelId.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                }
                else if (shortChatMessage != null)
                {
                    if (!string.IsNullOrWhiteSpace(shortChatMessage.Message))
                    {
                        var address = shortChatMessage.ChatId.ToString(CultureInfo.InvariantCulture);
                        var participantAddress = shortChatMessage.FromId.ToString(CultureInfo.InvariantCulture);
                        EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                            Bubble.BubbleDirection.Incoming,
                            address, participantAddress, true, this, false, false));
                        TextBubble textBubble = new TextBubble(
                            useCurrentTime ? Time.GetNowUnixTimestamp() : (long)shortChatMessage.Date,
                            shortChatMessage.Out != null
                                ? Bubble.BubbleDirection.Outgoing
                                : Bubble.BubbleDirection.Incoming,
                            address, participantAddress, true, this, shortChatMessage.Message,
                            shortChatMessage.Id.ToString(CultureInfo.InvariantCulture));
                        if (shortChatMessage.Out != null)
                        {
                            textBubble.Status = Bubble.BubbleStatus.Sent;
                        }
                        if (textBubble.Direction == Bubble.BubbleDirection.Incoming)
                        {
                            if (shortChatMessage.ReplyToMsgId != 0)
                            {
                                var iReplyMessage = GetMessage(shortChatMessage.ReplyToMsgId, optionalClient);
                                DebugPrint(">>> got message " + ObjectDumper.Dump(iReplyMessage));
                                var replyMessage = iReplyMessage as Message;
                                AddQuotedMessageToBubble(replyMessage, textBubble);
                            }
                        }

                        EventBubble(textBubble);
                    }
                    if (shortChatMessage.Id > maxMessageId)
                    {
                        maxMessageId = shortChatMessage.Id;
                    }
                }
                else if (message != null)
                {
                    var bubbles = ProcessFullMessage(message, useCurrentTime);
                    var i = 0;
                    foreach (var bubble in bubbles)
                    {
                        if (bubble != null)
                        {
                            if (bubble.Direction == Bubble.BubbleDirection.Incoming)
                            {
                                var fromId = message.FromId.ToString(CultureInfo.InvariantCulture);
                                var messageUser = _dialogs.GetUser(message.FromId);
                                if (messageUser == null)
                                {
                                    DebugPrint(">>>>> User is null, fetching user from the server");
                                    GetMessage(message.Id, optionalClient, uint.Parse(TelegramUtils.GetPeerId(message.ToId)), message.ToId is PeerChannel);
                                }
                                if (message.ReplyToMsgId != 0 && i == 0)//we should only add quoted message to first bubble if multiple bubbles exist
                                {
                                    var iReplyMessage = GetMessage(message.ReplyToMsgId, optionalClient, uint.Parse(TelegramUtils.GetPeerId(message.ToId)), message.ToId is PeerChannel);
                                    DebugPrint(">>> got message " + ObjectDumper.Dump(iReplyMessage));
                                    var replyMessage = iReplyMessage as Message;
                                    AddQuotedMessageToBubble(replyMessage, bubble);
                                }
                            }
                            EventBubble(bubble);
                        }
                        i++;
                    }
                    if (message.Id > maxMessageId)
                    {
                        maxMessageId = message.Id;
                    }
                }
                else if (updateContactRegistered != null)
                {
                    contactsCache = new List<User>(); //invalidate cache
                }
                else if (updateContactLink != null)
                {
                    contactsCache = new List<User>();
                }
                else if (userStatus != null)
                {
                    var available = TelegramUtils.GetAvailable(userStatus.Status);
                    var userToUpdate = _dialogs.GetUser(userStatus.UserId);
                    if (userToUpdate != null)
                    {
                        var userToUpdateAsUser = userToUpdate as User;
                        if (userToUpdateAsUser != null)
                        {
                            userToUpdateAsUser.Status = userStatus.Status;
                            _dialogs.AddUser(userToUpdateAsUser);
                        }
                    }

                    EventBubble(new PresenceBubble(Time.GetNowUnixTimestamp(),
                        Bubble.BubbleDirection.Incoming,
                        userStatus.UserId.ToString(CultureInfo.InvariantCulture),
                        false, this, available));
                }
                else if (typing != null || typingChat != null)
                {
                    var isAudio = false;
                    var isTyping = false;
                    if (typing != null)
                    {
                        isAudio = typing.Action is SendMessageRecordAudioAction;
                        isTyping = typing.Action is SendMessageTypingAction;
                    }
                    if (typingChat != null)
                    {
                        isAudio = typingChat.Action is SendMessageRecordAudioAction;
                        isTyping = typingChat.Action is SendMessageTypingAction;
                    }
                    var userId = typing != null ? typing.UserId : typingChat.UserId;
                    var party = typingChat != null;
                    var participantAddress = party ? userId.ToString(CultureInfo.InvariantCulture) : null;
                    var address = party
                        ? typingChat.ChatId.ToString(CultureInfo.InvariantCulture)
                        : userId.ToString(CultureInfo.InvariantCulture);
                    var key = address + participantAddress;


                    if (isAudio || isTyping)
                    {
                        EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                            Bubble.BubbleDirection.Incoming,
                            address, participantAddress, party,
                            this, true, isAudio));
                        CancelTypingTimer(key);
                        var newTimer = new Timer(6000) { AutoReset = false };
                        newTimer.Elapsed += (sender2, e2) =>
                        {
                            EventBubble(new TypingBubble(Time.GetNowUnixTimestamp(),
                                Bubble.BubbleDirection.Incoming,
                                address, participantAddress, party,
                                this, false, isAudio));
                            newTimer.Dispose();
                            _typingTimers.Remove(key);
                        };
                        _typingTimers[key] = newTimer;
                        newTimer.Start();
                    }
                    else
                    {
                        //Console.WriteLine("Unknown typing action: " + typing.Action.GetType().Name); //causes null pointer in some cases
                    }
                }
                else if (user != null)
                {
                    _dialogs.AddUser(user);
                }
                else if (chat != null)
                {
                    _dialogs.AddChat(chat);
                }
                else if (updateChatParticipants != null)
                {
                    //do nothing, we just use party options for this
                }
                else if (messageService != null)
                {
                    var partyInformationBubbles = MakePartyInformationBubble(messageService, useCurrentTime);
                    foreach (var partyInformationBubble in partyInformationBubbles)
                    {
                        EventBubble(partyInformationBubble);
                    }
                }
                else if (updateChannelTooLong != null)
                {
                    //this dude gives me a pts of 0, which messes up shit. So we wont do nothin mah man
                    //SaveChannelState(updateChannelTooLong.ChannelId, updateChannelTooLong.Pts);
                }
                else if (updateEditChannelMessage != null)
                {
                    var editChannelMessage = updateEditChannelMessage.Message as Message;
                    if (message == null)
                    {
                        continue;
                    }
                    var peerChannel = editChannelMessage.ToId as PeerChannel;
                    SaveChannelState(peerChannel.ChannelId, updateEditChannelMessage.Pts);
                }
                else if (updateDeleteChannelMessage != null)
                {
                    SaveChannelState(updateDeleteChannelMessage.ChannelId, updateDeleteChannelMessage.Pts);
                }
                else
                {
                    Console.WriteLine("Unknown update: " + ObjectDumper.Dump(update));
                }
            }

            //if (maxMessageId != 0)
            //{
            //    SendReceivedMessages(optionalClient, maxMessageId);
            //}
        }
Esempio n. 18
0
 private void OnLongPollClientUpdateTooLong(object sender, EventArgs e)
 {
     if (IsFullClientConnected)
         return;
     Task.Factory.StartNew(() =>
     {
         var transportConfig = 
             new TcpClientTransportConfig(_settings.NearestDcIp, _settings.NearestDcPort);
         using (var client = new TelegramClient(transportConfig, 
             new ConnectionConfig(_settings.AuthKey, _settings.Salt), AppInfo))
         {
             MTProtoConnectResult result = MTProtoConnectResult.Other;
             try
             {
                 result = TelegramUtils.RunSynchronously(client.Connect());
             }
             catch (Exception ex)
             {
                 DebugPrint("Exception while connecting " + ex);
             }
             if (result != MTProtoConnectResult.Success)
             {
                 throw new Exception("Failed to connect: " + result);
             }  
             FetchState(client);
         }
     });
 }
Esempio n. 19
0
 private async Task<List<IUser>> GetUsers(List<IInputUser> users, TelegramClient client)
 {
     var response = await client.Methods.UsersGetUsersAsync(new UsersGetUsersArgs
     {
         Id = users
     });
     return response;
 }
Esempio n. 20
0
 private void SendPresence(TelegramClient client)
 {
     TelegramUtils.RunSynchronously(client.Methods.AccountUpdateStatusAsync(
         new AccountUpdateStatusArgs
     {
         Offline = !_hasPresence
     }));
 }
Esempio n. 21
0
        private List<IUser> GetUpdatedUsersOfAllDialogs(TelegramClient client)
        {
            var users = new List<IUser>();
            foreach (var userBubbleGroup in BubbleGroupManager.FindAll(this).Where(x => !x.IsParty))
            {
                var user = _dialogs.GetUser(uint.Parse(userBubbleGroup.Address));
                var inputUser = TelegramUtils.CastUserToInputUser(user);
                var updatedUser = GetUser(inputUser, client).Result;
                _dialogs.AddUser(updatedUser);
                if (user != null)
                {
                    users.Add(updatedUser);
                }
            }

            return users;
        }
Esempio n. 22
0
 private void Ping(TelegramClient client, Action<Exception> exception = null)
 {
     try
     {
         Utils.DebugPrint("Sending ping!");
         var pong = (Pong)TelegramUtils.RunSynchronously(client.ProtoMethods.PingAsync(new PingArgs
         {
             PingId = GetRandomId(),
         }));
         Utils.DebugPrint("Got pong (from ping): " + pong.MsgId);
     }
     catch (Exception ex)
     {
         Utils.DebugPrint("Failed to ping client: " + ex);
         if (exception != null)
         {
             exception(ex);
         }
     }
 }
Esempio n. 23
0
 private static byte[] FetchFileBytes(TelegramClient client, FileLocation fileLocation, uint offset, uint limit)
 {
     var response = (UploadFile)TelegramUtils.RunSynchronously(client.Methods.UploadGetFileAsync(
         new UploadGetFileArgs
         {
             Location = new InputFileLocation
             {
                 VolumeId = fileLocation.VolumeId,
                 LocalId = fileLocation.LocalId,
                 Secret = fileLocation.Secret
             },
             Offset = offset,
             Limit = limit,
         }));
     return response.Bytes;
 }
Esempio n. 24
0
 private async void PingDelay(TelegramClient client, uint disconnectDelay, Action<Exception> exception = null)
 {
     try
     {
         Utils.DebugPrint(">>>>>>>>> Sending pingDelay!");
         var pong = (Pong)await client.ProtoMethods.PingDelayDisconnectAsync(new PingDelayDisconnectArgs
         {
             PingId = GetRandomId(),
             DisconnectDelay = disconnectDelay
         });
         Utils.DebugPrint(">>>>>>>>>> Got pong (from pingDelay): " + pong.MsgId);
     }
     catch (Exception ex)
     {
         if (exception != null)
         {
             exception(ex);
         }
     }
 }
Esempio n. 25
0
        private void GetDialogs(TelegramClient client)
        {
            DebugPrint("Fetching conversations");
            var masterDialogs = new CachedDialogs();

            if (!masterDialogs.DatabasesExist())
            {
                DebugPrint("Databases dont exist! creating new ones from data from server");
                var iDialogs =
                    TelegramUtils.RunSynchronously(client.Methods.MessagesGetDialogsAsync(new MessagesGetDialogsArgs
                    {
                        Limit = 100,
                        OffsetPeer = new InputPeerEmpty(),
                    }));
                var messagesDialogs = iDialogs as MessagesDialogs;

                var messagesDialogsSlice = iDialogs as MessagesDialogsSlice;

                if (messagesDialogs != null)
                {
                    masterDialogs.AddChats(messagesDialogs.Chats);
                    masterDialogs.AddUsers(messagesDialogs.Users);
                    if (LoadConversations)
                    {
                        LoadLast10Conversations(messagesDialogs);
                    }
                }
                else if (messagesDialogsSlice != null)
                {
                    //first add whatever we have got until now
                    masterDialogs.AddChats(messagesDialogsSlice.Chats);
                    masterDialogs.AddUsers(messagesDialogsSlice.Users);
                    if (LoadConversations)
                    {
                        LoadLast10Conversations(messagesDialogsSlice);
                    }
                    var numDialogs = 0;
                    do
                    {
                        numDialogs = messagesDialogsSlice.Dialogs.Count;

                        DebugPrint("%%%%%%% Number of Dialogs " + numDialogs);

                        var lastDialog = messagesDialogsSlice.Dialogs.LastOrDefault() as Dialog;

                        DebugPrint("%%%%%%% Last Dialog " + ObjectDumper.Dump(lastDialog));

                        if (lastDialog != null)
                        {
                            var lastPeer = GetInputPeerFromIPeer(lastDialog.Peer);
                            DebugPrint("%%%%%%% Last Peer " + ObjectDumper.Dump(lastPeer));
                            var offsetId = Math.Max(lastDialog.ReadInboxMaxId, lastDialog.TopMessage);
                            DebugPrint("%%%%%%% message offset " + ObjectDumper.Dump(offsetId));
                            var offsetDate = FindDateForMessageId(offsetId,messagesDialogsSlice);
                            DebugPrint("%%%%%%% offset date " + ObjectDumper.Dump(offsetDate));
                            var nextDialogs = TelegramUtils.RunSynchronously(client.Methods.MessagesGetDialogsAsync(new MessagesGetDialogsArgs
                            {
                                Limit = 100,
                                OffsetPeer = lastPeer,
                                OffsetId = offsetId,
                                OffsetDate = offsetDate
                            }));

                            messagesDialogsSlice = nextDialogs as MessagesDialogsSlice;
                            if (messagesDialogsSlice == null)
                            {
                                DebugPrint("%%%%%%% Next messages dialogs null ");
                                break;
                            }

                            DebugPrint("%%%%%%% users " + ObjectDumper.Dump(messagesDialogsSlice.Users));

                            DebugPrint("%%%%%%% chats " + ObjectDumper.Dump(messagesDialogsSlice.Chats));

                            masterDialogs.AddUsers(messagesDialogsSlice.Users);
                            masterDialogs.AddChats(messagesDialogsSlice.Chats);
                        }

                        DebugPrint("%%%%%%% Number of Dialogs At end " + numDialogs);

                    } while (numDialogs >= 100);
                }
            }

            _dialogs = masterDialogs;

            DebugPrint("Obtained conversations.");
        }
Esempio n. 26
0
        private void FetchDifference(TelegramClient client)
        {
            var counter = 0;

            DebugPrint("Fetching difference");

            //sometimes fetchdifference gives new channel message, which updates the state of the channel 
            //which leads to missed messasges, hence we should first fetch difference for the channels, then fetch the total 
            //difference.
            FetchChannelDifference(client);

            Again:

            DebugPrint("Difference Page: " + counter);

            var difference = TelegramUtils.RunSynchronously(
                client.Methods.UpdatesGetDifferenceAsync(new UpdatesGetDifferenceArgs
            {
                Date = _mutableSettings.Date,
                Pts = _mutableSettings.Pts,
                Qts = _mutableSettings.Qts
            }));

            var empty = difference as UpdatesDifferenceEmpty;
            var diff = difference as UpdatesDifference;
            var slice = difference as UpdatesDifferenceSlice;

            Action dispatchUpdates = () =>
            {
                var updates = new List<object>();
                //TODO: encrypyed messages
                if (diff != null)
                {
                    updates.AddRange(diff.NewMessages);
                    updates.AddRange(diff.OtherUpdates);
                }
                else if(slice!=null)
                {
                    updates.AddRange(slice.NewMessages);
                    updates.AddRange(slice.OtherUpdates);
                }
                DebugPrint(ObjectDumper.Dump(updates));
                ProcessIncomingPayload(updates, false, client);
            };

            if (diff != null)
            {
                dispatchUpdates();
                var state = (UpdatesState)diff.State;
                SaveState(state.Date, state.Pts, state.Qts, state.Seq);
                _dialogs.AddUsers(diff.Users);
                _dialogs.AddChats(diff.Chats);
            }
            else if (slice != null)
            {
                dispatchUpdates();
                var state = (UpdatesState)slice.IntermediateState;
                SaveState(state.Date, state.Pts, state.Qts, state.Seq);
                _dialogs.AddUsers(slice.Users);
                _dialogs.AddChats(slice.Chats);
                counter++;
                goto Again;
            }
            else if (empty != null)
            {
                SaveState(empty.Date, 0, 0, empty.Seq);
            }
        }
Esempio n. 27
0
 private byte[] FetchDocumentBytes(TelegramClient client, Document document, uint offset, uint limit)
 {
     var response = (UploadFile)TelegramUtils.RunSynchronously(client.Methods.UploadGetFileAsync(
         new UploadGetFileArgs
         {
             Location = new InputDocumentFileLocation
             {
                 AccessHash = document.AccessHash,
                 Id = document.Id
             },
             Offset = offset,
             Limit = limit,
         }));
     return response.Bytes;
 }
Esempio n. 28
0
 private void FetchChannelDifference(TelegramClient client)
 {
     var extendedBubbleGroups = BubbleGroupManager.FindAll(this).Where(group => group.IsExtendedParty);
     foreach (var bubbleGroup in extendedBubbleGroups)
     {
         try
         {
         Again:
             var channelAddress = uint.Parse(bubbleGroup.Address);
             var channel = _dialogs.GetChat(uint.Parse(bubbleGroup.Address));
             var channelObj = channel as Channel;
             if (channelObj != null)
             {
                 Utils.DebugPrint("Channel name " + (channelObj.Title));
             }
             else
             {
                 Utils.DebugPrint("### There is no channel in the database, we should reconstruct it");
             }
             var channelPts = _dialogs.GetChatPts(channelAddress);
             if (channelPts == 0)
             {
                 uint pts = GetLastPtsForChannel(client, channelAddress.ToString());
                 SaveChannelState(channelAddress, pts);
             }
             Utils.DebugPrint("Channel Pts " + channelPts);
             var result = TelegramUtils.RunSynchronously(
                 client.Methods.UpdatesGetChannelDifferenceAsync(new UpdatesGetChannelDifferenceArgs
                 {
                     Channel = new InputChannel
                     {
                         ChannelId = channelAddress,
                         AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(channelAddress))
                     },
                     Filter = new ChannelMessagesFilterEmpty(),
                     Limit = 100,
                     Pts = channelPts
                 }));
             var updates = ProcessChannelDifferenceResult(channelAddress, result);
             if (updates.Any())
             {
                 ProcessIncomingPayload(updates, false, client);
                 goto Again;
             }
         }
         catch (Exception e)
         {
             DebugPrint("#### Exception getting channels" + e);
             continue;
         }
     }
 }
Esempio n. 29
0
        public async void DoCommand(string[] args)
        {
            var command = args[0].ToLower();

            switch (command)
            {
				case "decrypt":
				{
					try
					{
						var bytes = Convert.FromBase64String("+MW7Btpz31b0gt9WN5d5vAEAAAAVxLUcCwAAAMzG2AUAAAAAAQAAAA4xNDkuMTU0LjE3NS41MAC7AQAAzMbYBQEAAAABAAAAJzIwMDE6MGIyODpmMjNkOmYwMDE6MDAwMDowMDAwOjAwMDA6MDAwYbsBAADMxtgFAAAAAAIAAAAOMTQ5LjE1NC4xNjcuNTEAuwEAAMzG2AUBAAAAAgAAACcyMDAxOjA2N2M6MDRlODpmMDAyOjAwMDA6MDAwMDowMDAwOjAwMGG7AQAAzMbYBQAAAAADAAAADzE0OS4xNTQuMTc1LjEwMLsBAADMxtgFAQAAAAMAAAAnMjAwMTowYjI4OmYyM2Q6ZjAwMzowMDAwOjAwMDA6MDAwMDowMDBhuwEAAMzG2AUAAAAABAAAAA4xNDkuMTU0LjE2Ny45MQC7AQAAzMbYBQEAAAAEAAAAJzIwMDE6MDY3YzowNGU4OmYwMDQ6MDAwMDowMDAwOjAwMDA6MDAwYbsBAADMxtgFAgAAAAQAAAAPMTQ5LjE1NC4xNjUuMTIwuwEAAMzG2AUAAAAABQAAAA05MS4xMDguNTYuMTgwAAC7AQAAzMbYBQEAAAAFAAAAJzIwMDE6MGIyODpmMjNmOmYwMDU6MDAwMDowMDAwOjAwMDA6MDAwYbsBAADIAAAA6AMAAGQAAADA1AEAiBMAADB1AADgkwQAMHUAANwFAAAKAAAAYOoAAAIAAADIAAAAFcS1HAAAAAA=");
						TLRig.Default.PrepareSerializersForAllTLObjectsInAssembly(typeof (IMTProtoAsyncMethods).Assembly);
						using (var streamer = new TLStreamer(bytes))
						{
							var newResult = TLRig.Default.Deserialize(streamer);
							int hi = 5;
						}
					}
					catch (Exception ex)
					{
						Console.WriteLine(ex);
					}
				}
				break;


                case "setup":
                    {
                        DebugPrint("Fetching nearest DC...");
                        var telegramSettings = new TelegramSettings();
                        var authInfo = await FetchNewAuthentication(DefaultTransportConfig);
                        using (var client = new TelegramClient(DefaultTransportConfig, 
                            new ConnectionConfig(authInfo.AuthKey, authInfo.Salt), AppInfo))
                        {
                            await client.Connect();
                            var nearestDcId = (NearestDc)await(client.Methods.HelpGetNearestDcAsync(new HelpGetNearestDcArgs{}));
                            var config = (Config)await(client.Methods.HelpGetConfigAsync(new HelpGetConfigArgs{ }));
                            var dcOption = config.DcOptions.OfType<DcOption>().FirstOrDefault(x => x.Id == nearestDcId.NearestDcProperty);
                            telegramSettings.NearestDcId = nearestDcId.NearestDcProperty;
                            telegramSettings.NearestDcIp = dcOption.IpAddress;
                            telegramSettings.NearestDcPort = (int)dcOption.Port;
                        }
                        DebugPrint("Generating authentication on nearest DC...");
                        var authInfo2 = await FetchNewAuthentication(
                            new TcpClientTransportConfig(telegramSettings.NearestDcIp, telegramSettings.NearestDcPort));
                        telegramSettings.AuthKey = authInfo2.AuthKey;
                        telegramSettings.Salt = authInfo2.Salt;
                        SettingsManager.Save(this, telegramSettings);
                        DebugPrint("Great! Ready for the service to start.");
                    }
                    break;
                case "sendcode":
                    {
                        var number = args[1];
                        var transportConfig = 
                            new TcpClientTransportConfig(_settings.NearestDcIp, _settings.NearestDcPort);
                        using (var client = new TelegramClient(transportConfig, 
                            new ConnectionConfig(_settings.AuthKey, _settings.Salt), AppInfo))
                        {
                            await client.Connect();
                            var result = await client.Methods.AuthSendCodeAsync(new AuthSendCodeArgs
                            {
                                PhoneNumber = number,
                                ApiId = AppInfo.ApiId,
                                ApiHash = "f8f2562579817ddcec76a8aae4cd86f6",
                            });
                            DebugPrint(ObjectDumper.Dump(result));
                        }
                    }
                    break;
                case "signin":
                    {
                        var number = args[1];
                        var hash = args[2];
                        var code = args[3];
                        var transportConfig = 
                            new TcpClientTransportConfig(_settings.NearestDcIp, _settings.NearestDcPort);
                        using (var client = new TelegramClient(transportConfig, 
                            new ConnectionConfig(_settings.AuthKey, _settings.Salt), AppInfo))
                        {
                            await client.Connect();
                            var result = (AuthAuthorization)await client.Methods.AuthSignInAsync(new AuthSignInArgs
                            {
                                PhoneNumber = number,
                                PhoneCodeHash = hash,
                                PhoneCode = code,
                            });
                            DebugPrint(ObjectDumper.Dump(result));
                        }
                    }
                    break;
                case "signup":
                    {
                        var number = args[1];
                        var hash = args[2];
                        var code = args[3];
                        var firstName = args[4];
                        var lastName = args[5];
                        var transportConfig = 
                            new TcpClientTransportConfig(_settings.NearestDcIp, _settings.NearestDcPort);
                        using (var client = new TelegramClient(transportConfig, 
                            new ConnectionConfig(_settings.AuthKey, _settings.Salt), AppInfo))
                        {
                            await client.Connect();
                            var result = (AuthAuthorization)await client.Methods.AuthSignUpAsync(new AuthSignUpArgs
                            {
                                PhoneNumber = number,
                                PhoneCodeHash = hash,
                                PhoneCode = code,
                                FirstName = firstName,
                                LastName = lastName,
                            });
                            DebugPrint(ObjectDumper.Dump(result));
                        }
                    }
                    break;
                case "getcontacts":
                    {
                        var result = await _fullClient.Methods.ContactsGetContactsAsync(new ContactsGetContactsArgs
                        {
                            Hash = string.Empty
                        });
                        DebugPrint(ObjectDumper.Dump(result));
                    }
                    break;
//                case "sendhello":
//                    {
//                        var contacts = (ContactsContacts)await _fullClient.Methods.ContactsGetContactsAsync(new ContactsGetContactsArgs
//                        {
//                            Hash = string.Empty
//                        });
//                        var counter = 0;
//                        Console.WriteLine("Pick a contact:");
//                        foreach (var icontact in contacts.Users)
//                        {
//                            var contact = icontact as UserContact;
//                            if (contact == null)
//                                continue;
//                            Console.WriteLine(counter++ + ") " + contact.FirstName + " " + contact.LastName);
//                        }
//                        var choice = int.Parse(Console.ReadLine());
//                        var chosenContact = (UserContact)contacts.Users[choice];
//                        var result = await _fullClient.Methods.MessagesSendMessageAsync(new MessagesSendMessageArgs
//                        {
//                            Peer = new InputPeerContact
//                            {
//                                UserId = chosenContact.Id,
//                            },
//                            Message = "Hello from Disa!",
//                            RandomId = (ulong)Time.GetNowUnixTimestamp(),
//                        });
//                        Console.WriteLine(ObjectDumper.Dump(result));
//                    }
//                    break;
            }

        }
Esempio n. 30
0
 private void FetchState(TelegramClient client)
 {
     if (_mutableSettings.Date == 0)
     {
         DebugPrint("We need to fetch the state!");
         var state = (UpdatesState)TelegramUtils.RunSynchronously(client.Methods.UpdatesGetStateAsync(new UpdatesGetStateArgs()));
         SaveState(state.Date, state.Pts, state.Qts, state.Seq);
     }
     else
     {
         FetchDifference(client);
     }
 }