public void LoadNextSlice()
        {
            if (IsWorking ||
                LazyItems.Count > 0 ||
                IsLastSliceLoaded
#if WP8
                || !_isUpdated
#endif
                )
            {
                return;
            }

            IsWorking = true;
            var maxId  = Items.Count == 0 ? 0 : Items.OfType <TLDialog>().Last(x => x.TopMessage != null).TopMessage.Index;
            var offset = _offset;
            var limit  = Constants.DialogsSlice;
            //TLUtils.WriteLine(string.Format("{0} messages.getDialogs offset={1} limit={2}", DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture), offset, limit), LogSeverity.Error);
            MTProtoService.GetDialogsAsync(
#if LAYER_40
                new TLInt(offset), new TLInt(limit),
#else
                new TLInt(0), new TLInt(maxId), new TLInt(limit),
#endif
                result => BeginOnUIThread(() =>
            {
                if (_offset != offset)
                {
                    return;
                }
                _offset += Constants.DialogsSlice;

                foreach (var dialog in result.Dialogs)
                {
                    Items.Add(dialog);
                }
                AddChannels(_channels);

                IsWorking         = false;
                IsLastSliceLoaded = result.Dialogs.Count < limit;
                Status            = LazyItems.Count > 0 || Items.Count > 0 ? string.Empty : Status;
                //TLUtils.WriteLine(string.Format("messages.getDialogs offset={0} limit={1} result={2}", offset, limit, result.Dialogs.Count), LogSeverity.Error);
            }),
                error => BeginOnUIThread(() =>
            {
                IsWorking = false;
                Status    = string.Empty;

                //TLUtils.WriteLine(string.Format("messages.getDialogs offset={0} limit={1} error={2}", offset, limit, error), LogSeverity.Error);
                Execute.ShowDebugMessage("messages.getDialogs error " + error);
            }));
        }
        protected override void OnInitialize()
        {
            BeginOnThreadPool(() =>
            {
                var isAuthorized = SettingsHelper.GetValue <bool>(Constants.IsAuthorizedKey);
                if (!FirstRun)
                {
                    return;
                }
                if (!isAuthorized)
                {
                    return;
                }

                FirstRun = false;

                Status = Items.Count == 0 && LazyItems.Count == 0? AppResources.Loading : string.Empty;
                MTProtoService.GetDialogsAsync(new TLInt(0), new TLInt(0), new TLInt(Constants.DialogsSlice),
                                               dialogs =>
                {
                    foreach (var dialog in dialogs.Dialogs)
                    {
                        LazyItems.Add(dialog);
                    }

                    Status = Items.Count == 0 && LazyItems.Count == 0? string.Format("{0}", AppResources.NoDialogsHere) : string.Empty;
                    if (LazyItems.Count > 0)
                    {
                        BeginOnUIThread(() => PopulateItems(() =>
                        {
                            EventAggregator.Publish(new InvokeImportContacts());
                        }));
                    }
                    else
                    {
                        EventAggregator.Publish(new InvokeImportContacts());
                    }
                },
                                               error =>
                {
                    EventAggregator.Publish(new InvokeImportContacts());
                    Telegram.Api.Helpers.Execute.ShowDebugMessage("messages.getHistory error " + error);
                    Status = string.Empty;
                });
            });



            base.OnInitialize();
        }
Exemple #3
0
        public void LoadNextSlice()
        {
            if (LazyItems.Count > 0 || IsLastSliceLoaded || IsWorking)
            {
                return;
            }

            IsWorking = true;
            var offset = Items.Count;
            var limit  = 30;

            MTProtoService.GetDialogsAsync(
#if LAYER_40
                new TLInt(offset), new TLInt(limit),
#else
                new TLInt(0), new TLInt(_maxId), new TLInt(limit),
#endif
                result => Execute.BeginOnUIThread(() =>
            {
                var lastDialog = result.Dialogs.LastOrDefault(x => x.TopMessageId != null);
                if (lastDialog != null)
                {
                    _maxId = lastDialog.TopMessageId.Value;
                }

                var itemsAdded = 0;
                foreach (var dialog in result.Dialogs)
                {
                    if (!SkipDialog(_bot, dialog))
                    {
                        Items.Add(dialog);
                        itemsAdded++;
                    }
                }

                IsWorking         = false;
                IsLastSliceLoaded = result.Dialogs.Count < limit;
                Status            = LazyItems.Count > 0 || Items.Count > 0 ? string.Empty : Status;

                if (itemsAdded < (Constants.DialogsSlice / 2))
                {
                    LoadNextSlice();
                }
            }),
                error => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;
                Status    = string.Empty;
            }));
        }
Exemple #4
0
        public void LoadNextSlice()
        {
            if (IsWorking ||
                LazyItems.Count > 0 ||
                IsLastSliceLoaded
#if WP8
                || !_isUpdated
#endif
                )
            {
                return;
            }

            var offset = _offset;
            var limit  = Constants.DialogsSlice;
            //TLUtils.WriteLine(string.Format("{0} messages.getDialogs offset={1} limit={2}", DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture), offset, limit), LogSeverity.Error);

            var             offsetDate = 0;
            var             offsetId   = 0;
            TLInputPeerBase offsetPeer = new TLInputPeerEmpty();
            var             lastDialog = GetLastDialog(Items);
            if (lastDialog != null)
            {
                var lastMessage = lastDialog.TopMessage as TLMessageCommon;
                if (lastMessage != null)
                {
                    offsetDate = lastMessage.DateIndex;
                    offsetId   = lastMessage.Index;
                    if (lastMessage.ToId is TLPeerUser)
                    {
                        offsetPeer = !lastMessage.Out.Value
                            ? DialogDetailsViewModel.PeerToInputPeer(new TLPeerUser {
                            Id = lastMessage.FromId
                        })
                            : DialogDetailsViewModel.PeerToInputPeer(lastMessage.ToId);
                    }
                    else
                    {
                        offsetPeer = DialogDetailsViewModel.PeerToInputPeer(lastMessage.ToId);
                    }
                }
            }

            IsWorking = true;
            //TLObject.LogNotify = true;
            //TelegramEventAggregator.LogPublish = true;
            var stopwatch = Stopwatch.StartNew();
            MTProtoService.GetDialogsAsync(stopwatch,
                                           new TLInt(offsetDate),
                                           new TLInt(offsetId),
                                           offsetPeer,
                                           new TLInt(limit),
                                           new TLInt(0),
                                           result =>
            {
                //System.Diagnostics.Debug.WriteLine("messages.getDialogs end sync elapsed=" + stopwatch.Elapsed);

                BeginOnUIThread(() =>
                {
                    //System.Diagnostics.Debug.WriteLine("messages.getDialogs ui elapsed=" + stopwatch.Elapsed);
                    //TelegramEventAggregator.LogPublish = false;
                    //TLObject.LogNotify = false;
                    if (_offset != offset)
                    {
                        return;
                    }
                    _offset += Constants.DialogsSlice;

                    foreach (var dialog in result.Dialogs)
                    {
                        Items.Add(dialog);
                    }

                    ReorderDrafts(Items);

                    IsWorking         = false;
                    IsLastSliceLoaded = result.Dialogs.Count < limit;
                    Status            = LazyItems.Count > 0 || Items.Count > 0 ? string.Empty : Status;
                    //System.Diagnostics.Debug.WriteLine("messages.getDialogs end ui elapsed=" + stopwatch.Elapsed);
                    //TLUtils.WriteLine(string.Format("messages.getDialogs offset={0} limit={1} result={2}", offset, limit, result.Dialogs.Count), LogSeverity.Error);
                });
            },
                                           error => BeginOnUIThread(() =>
            {
                IsWorking = false;
                Status    = string.Empty;
                //TLUtils.WriteLine(string.Format("messages.getDialogs offset={0} limit={1} error={2}", offset, limit, error), LogSeverity.Error);
                Execute.ShowDebugMessage("messages.getDialogs error " + error);
            }));
        }
        protected override void OnInitialize()
        {
            BeginOnThreadPool(() =>
            {
                var isAuthorized = SettingsHelper.GetValue <bool>(Constants.IsAuthorizedKey);
                if (!FirstRun)
                {
                    return;
                }
                if (!isAuthorized)
                {
                    return;
                }

                FirstRun = false;

                Status    = Items.Count == 0 && LazyItems.Count == 0 ? AppResources.Loading : string.Empty;
                var limit = Constants.DialogsSlice;
                MTProtoService.GetDialogsAsync(
#if LAYER_40
                    new TLInt(0), new TLInt(limit),
#else
                    new TLInt(0), new TLInt(0), new TLInt(limit),
#endif
                    dialogs => Execute.BeginOnUIThread(() =>
                {
                    IsLastSliceLoaded = dialogs.Dialogs.Count < limit;
                    _offset           = Constants.DialogsSlice;

                    _isUpdated = true;
                    const int firstSliceCount = 8;
                    var count = 0;
                    for (var i = 0; i < dialogs.Dialogs.Count; i++)
                    {
                        if (count < firstSliceCount)
                        {
                            Items.Add(dialogs.Dialogs[i]);
                            count++;
                        }
                        else
                        {
                            LazyItems.Add(dialogs.Dialogs[i]);
                        }
                    }

                    Status = Items.Count == 0 && LazyItems.Count == 0 ? string.Format("{0}", AppResources.NoDialogsHere) : string.Empty;

                    if (LazyItems.Count > 0)
                    {
                        BeginOnUIThread(() =>
                        {
                            for (var i = 0; i < LazyItems.Count; i++)
                            {
                                Items.Add(LazyItems[i]);
                            }
                            LazyItems.Clear();

                            InvokeImportContacts();
                            UpdateChannels();
                        });
                    }
                    else
                    {
                        InvokeImportContacts();
                        UpdateChannels();
                    }
                }),
                    error => BeginOnUIThread(() =>
                {
                    InvokeImportContacts();
                    UpdateChannels();

                    Execute.ShowDebugMessage("messages.getDialogs error " + error);
                    _isUpdated = true;
                    Status     = string.Empty;
                }));
            });

            base.OnInitialize();
        }
        private void UpdateItemsAsync(int limit)
        {
            IsWorking = true;

            MTProtoService.GetDialogsAsync(
#if LAYER_40
                new TLInt(0), new TLInt(limit),
#else
                new TLInt(0), new TLInt(0), new TLInt(limit),
#endif
                result =>
            {
                UpdateChannels();

                // сортируем, т.к. при синхронизации, если есть отправляющиеся сообщений, то TopMessage будет замещен на них
                // и начальная сортировка сломается
                var orderedDialogs = new TLVector <TLDialogBase>(result.Dialogs.Count);
                foreach (var orderedDialog in result.Dialogs.OrderByDescending(x => x.GetDateIndex()))
                {
                    orderedDialogs.Add(orderedDialog);
                }
                result.Dialogs = orderedDialogs;

                BeginOnUIThread(() =>
                {
                    IsWorking         = false;
                    IsLastSliceLoaded = result.Dialogs.Count < limit;

                    _offset = limit;

                    var needUpdate = false;
                    var itemsCount = Items.Count;
                    int i          = 0, j = 0;
                    for (; i < result.Dialogs.Count && j < Items.Count; i++, j++)
                    {
                        if (itemsCount - 1 < i || result.Dialogs[i] != Items[j])
                        {
                            // skip "User joined Telegram!" message
                            var dialog = Items[j] as TLDialog;
                            if (dialog != null)
                            {
                                var messageService = dialog.TopMessage as TLMessageService;
                                if (messageService != null && messageService.Action is TLMessageActionContactRegistered)
                                {
                                    i--;
                                    continue;
                                }

                                if (dialog.Peer is TLPeerChannel)
                                {
                                    i--;
                                    continue;
                                }
                            }

                            var encryptedDialog = Items[j] as TLEncryptedDialog;
                            if (encryptedDialog != null)
                            {
                                i--;
                                continue;
                            }


                            needUpdate = true;
                            break;
                        }
                    }

                    if (i < j)
                    {
                        for (var k = i; k < j; k++)
                        {
                            if (k < result.Dialogs.Count)
                            {
                                Items.Add(result.Dialogs[k]);
                            }
                        }
                    }

                    // load updated cache
                    Status = Items.Count == 0 && result.Dialogs.Count == 0 ? string.Format("{0}", AppResources.NoDialogsHere) : string.Empty;

                    if (needUpdate)
                    {
                        var encryptedDialogs = Items.OfType <TLEncryptedDialog>();
                        var startIndex       = 0;
                        foreach (var encryptedDialog in encryptedDialogs)
                        {
                            for (var k = startIndex; k < result.Dialogs.Count; k++)
                            {
                                if (encryptedDialog.GetDateIndex() > result.Dialogs[k].GetDateIndex())
                                {
                                    result.Dialogs.Insert(k, encryptedDialog);
                                    startIndex = k;
                                    break;
                                }
                            }
                        }

                        var broadcasts = Items.OfType <TLBroadcastDialog>();
                        startIndex     = 0;
                        foreach (var broadcast in broadcasts)
                        {
                            for (var k = startIndex; k < result.Dialogs.Count; k++)
                            {
                                if (broadcast.GetDateIndex() > result.Dialogs[k].GetDateIndex())
                                {
                                    result.Dialogs.Insert(k, broadcast);
                                    startIndex = k;
                                    break;
                                }
                            }
                        }

                        var channels = Items.Where(x => x.Peer is TLPeerChannel);
                        startIndex   = 0;
                        foreach (var channel in channels)
                        {
                            for (var k = startIndex; k < result.Dialogs.Count; k++)
                            {
                                if (channel.GetDateIndex() > result.Dialogs[k].GetDateIndex())
                                {
                                    result.Dialogs.Insert(k, channel);
                                    startIndex = k;
                                    break;
                                }
                            }
                        }

                        Items.Clear();
                        foreach (var dialog in result.Dialogs)
                        {
                            Items.Add(dialog);
                        }

                        IsLastSliceLoaded = false;
                        _isUpdated        = true;
                    }
                    else
                    {
                        _isUpdated = true;
                    }
                });
            },
                error => BeginOnUIThread(() =>
            {
                _isUpdated = true;
                Status     = string.Empty;
                IsWorking  = false;
            }));
        }
        //protected override void OnPopulateCompleted()
        //{
        //    UpdateItemsAsync(0, 0, Constants.DialogsSlice);

        //    base.OnPopulateCompleted();
        //}

        private void UpdateItemsAsync(int offset, int maxId, int count)
        {
            //IsWorking = true;

            MTProtoService.GetDialogsAsync(new TLInt(offset), new TLInt(maxId), new TLInt(count),
                                           result =>
            {
                // сортируем, т.к. при синхронизации, если есть отправляющиеся сообщений, то TopMessage будет замещен на них
                // и начальная сортировка сломается
                var orderedDialogs = new TLVector <TLDialogBase>(result.Dialogs.Count);
                foreach (var orderedDialog in result.Dialogs.OrderByDescending(x => x.GetDateIndex()))
                {
                    orderedDialogs.Add(orderedDialog);
                }
                result.Dialogs = orderedDialogs;

                //IsWorking = false;
                var needUpdate = false;
                var itemsCount = Items.Count;
                for (var i = 0; i < result.Dialogs.Count; i++)
                {
                    if (itemsCount - 1 < i || result.Dialogs[i] != Items[i])
                    {
                        needUpdate = true;
                        break;
                    }
                }

                // load updated cache
                Status = Items.Count == 0 && result.Dialogs.Count == 0? string.Format("{0}", AppResources.NoDialogsHere) : string.Empty;

                if (needUpdate)
                {
                    BeginOnUIThread(() =>
                    {
                        var encryptedDialogs = Items.OfType <TLEncryptedDialog>();
                        var startIndex       = 0;
                        foreach (var encryptedDialog in encryptedDialogs)
                        {
                            for (var i = startIndex; i < result.Dialogs.Count; i++)
                            {
                                if (encryptedDialog.GetDateIndex() > result.Dialogs[i].GetDateIndex())
                                {
                                    result.Dialogs.Insert(i, encryptedDialog);
                                    startIndex = i;
                                    break;
                                }
                            }
                        }

                        var broadcasts = Items.OfType <TLBroadcastDialog>();
                        startIndex     = 0;
                        foreach (var broadcast in broadcasts)
                        {
                            for (var i = startIndex; i < result.Dialogs.Count; i++)
                            {
                                if (broadcast.GetDateIndex() > result.Dialogs[i].GetDateIndex())
                                {
                                    result.Dialogs.Insert(i, broadcast);
                                    startIndex = i;
                                    break;
                                }
                            }
                        }

                        Items.Clear();
                        foreach (var dialog in result.Dialogs)
                        {
                            Items.Add(dialog);
                        }
                    });
                }
            },
                                           error =>
            {
                Status = string.Empty;
                //IsWorking = false;
            });
        }
        public void LoadNextSlice()
        {
            if (LazyItems.Count > 0 || IsLastSliceLoaded || IsWorking)
            {
                return;
            }

            var             offsetDate = 0;
            var             offsetId   = 0;
            TLInputPeerBase offsetPeer = new TLInputPeerEmpty();
            var             lastDialog = Items.OfType <TLDialog>().Last(x => x.TopMessage != null && x.TopMessage.Index > 0);

            if (lastDialog != null)
            {
                var lastMessage = lastDialog.TopMessage as TLMessageCommon;
                if (lastMessage != null)
                {
                    offsetDate = lastMessage.DateIndex;
                    offsetId   = lastMessage.Index;
                    if (lastMessage.ToId is TLPeerUser)
                    {
                        offsetPeer = !lastMessage.Out.Value
                            ? DialogDetailsViewModel.PeerToInputPeer(new TLPeerUser {
                            Id = lastMessage.FromId
                        })
                            : DialogDetailsViewModel.PeerToInputPeer(lastMessage.ToId);
                    }
                    else
                    {
                        offsetPeer = DialogDetailsViewModel.PeerToInputPeer(lastMessage.ToId);
                    }
                }
            }

            IsWorking = true;
            var offset = Items.Count;
            var limit  = 30;

            MTProtoService.GetDialogsAsync(Stopwatch.StartNew(),
                                           new TLInt(offsetDate),
                                           new TLInt(offsetId),
                                           offsetPeer,
                                           new TLInt(limit),
                                           new TLInt(0),
                                           result => Execute.BeginOnUIThread(() =>
            {
                lastDialog = result.Dialogs.LastOrDefault(x => x.TopMessageId != null) as TLDialog;
                if (lastDialog != null)
                {
                    _maxId = lastDialog.TopMessageId.Value;
                }

                var itemsAdded = 0;
                foreach (var dialog in result.Dialogs)
                {
                    if (!SkipDialogForBot(_bot, dialog))
                    {
                        Items.Add(dialog);
                        itemsAdded++;
                    }
                }

                IsWorking         = false;
                IsLastSliceLoaded = result.Dialogs.Count < limit;
                Status            = LazyItems.Count > 0 || Items.Count > 0 ? string.Empty : Status;

                if (itemsAdded < (Constants.DialogsSlice / 2))
                {
                    LoadNextSlice();
                }
            }),
                                           error => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;
                Status    = string.Empty;
            }));
        }
        static void Main(string[] args)
        {
            var manualResetEvent = new ManualResetEvent(false);

            ////var transport = new HttpTransport(string.Empty);
            ////transport.SetAddress("http://95.142.192.65/api", 80, () => manualResetEvent.Set());
            //var transport = new TcpTransport();
            //transport.SetAddress("95.142.192.65", 80, () => manualResetEvent.Set());
            //manualResetEvent.WaitOne();


            //IAuthorizationHelper authHelper = new AuthorizationHelper(Transport);
            //authHelper.InitAsync(res =>{});
            manualResetEvent.Reset();

            var cacheService   = new InMemoryCacheService(null);
            var updatesService = new UpdatesService(cacheService, null);

            MTProtoService.Salt = new TLLong(0);
            var service = new MTProtoService(updatesService, cacheService, new TransportService());

            service.Initialized += (o, e) => manualResetEvent.Set();

            manualResetEvent.WaitOne();
            var phoneNumber = new TLString("79996610000");

            service.SendCodeAsync(phoneNumber, TLSmsType.Code,
                                  sentCode =>
            {
                var phoneCodeHash = sentCode.PhoneCodeHash;
                service.SignInAsync(phoneNumber, phoneCodeHash, new TLString("11111"),
                                    authorization =>
                {
                    //TLUtils.WriteLine("Auth: " + TLUtils.MessageIdString(authorization.Expires));
                    service.GetDialogsAsync(new TLInt(0), new TLInt(0), new TLInt(int.MaxValue),
                                            dialogs =>
                    {
                    },
                                            er2 =>
                    {
                    });

                    //service.GetContactsAsync(
                    //    new TLString(""),
                    //    contactsResult =>
                    //    {
                    //        var contacts = contactsResult as TLContacts;
                    //        if (contacts != null)
                    //        {
                    //            var contact = contacts.Contacts[0];

                    //            service.GetHistoryAsync(new TLInputPeerContact{UserId = contact.UserId}, new TLInt(0), new TLInt(0), new TLInt(int.MaxValue),
                    //                messagesResult =>
                    //                {

                    //                },
                    //                er2 => { });
                    //        }
                    //    },
                    //    er =>
                    //    {
                    //    });
                });
            });

            Console.ReadKey();
        }