예제 #1
0
        private void PingMainTransportAsync(TLProxyBase item, ITransport transport)
        {
            MTProtoService.PingAsync(TLLong.Random(),
                                     pong => Execute.BeginOnUIThread(() =>
            {
                item.Ping = transport.Ping > 0
                        ? new TLInt((int)transport.Ping)
                        : null;

                Set(_proxyConfig);
            }));
        }
 public void DeletePhoto()
 {
     MTProtoService.UpdateProfilePhotoAsync(new TLInputPhotoEmpty(),
                                            result =>
     {
         Execute.ShowDebugMessage("photos.updateProfilePhoto result " + result);
     },
                                            error =>
     {
         Execute.ShowDebugMessage("photos.updateProfilePhoto error " + error);
     });
 }
예제 #3
0
        public void DeleteContact(TLUserBase user)
        {
            if (user == null)
            {
                return;
            }

            MTProtoService.DeleteContactAsync(
                user.ToInputUser(),
                link => BeginOnUIThread(() => Items.Remove(user)),
                error => Execute.ShowDebugMessage("contacts.deleteContact error: " + error));
        }
예제 #4
0
        public void Archive(TLStickerSet set)
        {
            var set32 = set as TLStickerSet32;

            if (set32 == null)
            {
                return;
            }

            var inputStickerSet = new TLInputStickerSetId {
                Id = set32.Id, AccessHash = set32.AccessHash
            };

            IsWorking = true;
            MTProtoService.InstallStickerSetAsync(inputStickerSet, TLBool.True,
                                                  result => BeginOnUIThread(() =>
            {
                IsWorking      = false;
                set32.Archived = true;
                Items.Remove(set32);

                var masks43 = StateService.GetMasks() as TLAllStickers43;
                TLMessagesStickerSet messagesSet = null;
                if (masks43 != null)
                {
                    messagesSet = TLUtils.RemoveStickerSet(masks43, set32);
                    StateService.SaveMasksAsync(masks43);
                }

                if (messagesSet != null)
                {
                    var archivedStickers = StateService.GetArchivedStickers();
                    if (archivedStickers != null)
                    {
                        TLUtils.AddStickerSetCovered(archivedStickers, messagesSet, archivedStickers.SetsCovered, new TLStickerSetCovered {
                            Cover = messagesSet.Documents.FirstOrDefault() ?? new TLDocumentEmpty {
                                Id = new TLLong(0)
                            }, StickerSet = messagesSet.Set
                        });
                        archivedStickers.Count.Value = archivedStickers.Sets.Count;

                        StateService.SaveArchivedStickersAsync(archivedStickers);
                    }
                }

                //EventAggregator.Publish(new UpdateStickerSetsEventArgs(allStickers43));
            }),
                                                  error => BeginOnUIThread(() =>
            {
                IsWorking = false;
                Execute.ShowDebugMessage("messages.installStickerSet error " + error);
            }));
        }
예제 #5
0
        public void DeleteAndStop(TLDialogBase dialog)
        {
            if (dialog == null)
            {
                return;
            }

            var user = dialog.With as TLUser;

            if (user == null || !user.IsBot)
            {
                return;
            }

            var confirmation = MessageBox.Show(AppResources.DeleteChatConfirmation, AppResources.Confirm, MessageBoxButton.OKCancel);

            if (confirmation != MessageBoxResult.OK)
            {
                return;
            }

            IsWorking = true;
            MTProtoService.BlockAsync(user.ToInputUser(),
                                      blocked =>
            {
                user.Blocked = TLBool.True;
                CacheService.Commit();

                DeleteHistoryAsync(false, user.ToInputPeer(),
                                   result => BeginOnUIThread(() =>
                {
                    IsWorking = false;
                    CacheService.DeleteDialog(dialog);         // TODO : move this line to MTProtoService

                    if (dialog.With != null)
                    {
                        dialog.With.Bitmap = null;
                    }
                    Items.Remove(dialog);
                }),
                                   error => BeginOnUIThread(() =>
                {
                    IsWorking = false;
                    Execute.ShowDebugMessage("messages.deleteHistory error " + error);
                }));
            },
                                      error => BeginOnUIThread(() =>
            {
                IsWorking = false;
                Execute.ShowDebugMessage("contacts.Block error " + error);
            }));
        }
        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);
            }));
        }
예제 #7
0
        public void Resend()
        {
            if (_isResending)
            {
                return;
            }

            if (_nextType == null)
            {
                return;
            }

            _isResending = true;
            IsWorking    = true;
            MTProtoService.ResendCodeAsync(StateService.PhoneNumber, StateService.PhoneCodeHash,
                                           sentCode => BeginOnUIThread(() =>
            {
                _isResending = false;
                IsWorking    = false;

                StateService.PhoneCodeHash   = sentCode.PhoneCodeHash;
                StateService.PhoneRegistered = sentCode.PhoneRegistered;

                Timeout = sentCode.SendCallTimeout;
                ResendCodeVisibility = Timeout != null && Timeout.Value > 0
                        ? Visibility.Collapsed
                        : Visibility.Visible;

                var sentCode50 = sentCode as TLSentCode50;
                if (sentCode50 != null)
                {
                    _type     = sentCode50.Type;
                    _nextType = sentCode50.NextType;

                    Subtitle = GetSubtitle();
                    NotifyOfPropertyChange(() => Subtitle);

                    var length = _type as ILength;
                    CodeLength = length != null ? length.Length.Value : Constants.DefaultCodeLength;
                    NotifyOfPropertyChange(() => CodeLength);
                }

                _startTime = DateTime.Now;
                _callTimer.Start();
            }),
                                           error => BeginOnUIThread(() =>
            {
                _isResending = false;
                IsWorking    = false;
                Telegram.Api.Helpers.Execute.ShowDebugMessage("auth.resendCode error " + error);
            }));
        }
예제 #8
0
        private void UpdateNotifySettingsAsync()
        {
            if (CurrentContact == null)
            {
                return;
            }

            var notifySettings = new TLInputPeerNotifySettings78
            {
                Flags        = new TLInt(0),
                MuteUntil    = new TLInt(MuteUntil),
                ShowPreviews = TLBool.True,
                Sound        = string.IsNullOrEmpty(SelectedSound) ? new TLString("default") : new TLString(SelectedSound)
            };

            IsWorking = true;
            MTProtoService.UpdateNotifySettingsAsync(
                CurrentContact.ToInputNotifyPeer(), notifySettings,
                result =>
            {
                IsWorking = false;
                CurrentContact.NotifySettings = new TLPeerNotifySettings78
                {
                    Flags        = new TLInt(0),
                    MuteUntil    = new TLInt(MuteUntil),
                    ShowPreviews = notifySettings.ShowPreviews,
                    Sound        = notifySettings.Sound
                };

                var dialog = CacheService.GetDialog(new TLPeerUser {
                    Id = CurrentContact.Id
                });
                if (dialog != null)
                {
                    dialog.NotifySettings = CurrentContact.NotifySettings;
                    dialog.NotifyOfPropertyChange(() => dialog.NotifySettings);
                    dialog.NotifyOfPropertyChange(() => dialog.Self);
                    var settings = dialog.With as INotifySettings;
                    if (settings != null)
                    {
                        settings.NotifySettings = CurrentContact.NotifySettings;
                    }
                }

                CacheService.Commit();
            },
                error =>
            {
                IsWorking = false;
                Execute.ShowDebugMessage("account.updateNotifySettings error: " + error);
            });
        }
예제 #9
0
        public void GetDHConfig()
        {
            if (_dhConfig != null)
            {
                return;
            }

            _isGettingConfig = true;
            MTProtoService.GetDHConfigAsync(new TLInt(0), new TLInt(0),
                                            result =>
            {
                var dhConfig = result as TLDHConfig;
                if (dhConfig == null)
                {
                    return;
                }
                if (!TLUtils.CheckPrime(dhConfig.P.Data, dhConfig.G.Value))
                {
                    return;
                }

                var aBytes = new byte[256];
                var random = new SecureRandom();
                random.NextBytes(aBytes);

                var gaBytes = Telegram.Api.Services.MTProtoService.GetGB(aBytes, dhConfig.G, dhConfig.P);

                dhConfig.A  = TLString.FromBigEndianData(aBytes);
                dhConfig.GA = TLString.FromBigEndianData(gaBytes);

                _isGettingConfig = false;

                Execute.BeginOnUIThread(() =>
                {
                    _dhConfig = dhConfig;

                    if (_contact != null)
                    {
                        UserAction(_contact);
                    }
                });
            },
                                            error =>
            {
                _isGettingConfig = false;

                IsWorking = false;
                NotifyOfPropertyChange(() => IsNotWorking);
                NotifyOfPropertyChange(() => ProgressVisibility);
                Execute.ShowDebugMessage("messages.getDhConfig error: " + error);
            });
        }
        public void Next()
        {
            if (!CanCreateChannel)
            {
                return;
            }

            IsWorking = true;
            NotifyOfPropertyChange(() => CanCreateChannel);

#if LAYER_41
            // 1 broadcast
            // 2 mega group
            MTProtoService.CreateChannelAsync(new TLInt(2), new TLString(Title), new TLString(About),
#else
            MTProtoService.CreateChannelAsync(new TLInt(1), new TLString(Title), new TLString(About), new TLVector <TLInputUserBase>(),
#endif
                                              result => Execute.BeginOnUIThread(() =>
            {
                var updates = result as TLUpdates;
                if (updates != null)
                {
                    var channel = updates.Chats.FirstOrDefault() as TLChannel;
                    if (channel != null)
                    {
                        if (_photo != null)
                        {
                            ContinueUploadingPhoto(channel);
                        }
                        else
                        {
                            if (_uploadingPhoto)
                            {
                                _uploadingCallback = () => ContinueUploadingPhoto(channel);
                            }
                            else
                            {
                                ContinueNextStep(channel);
                            }
                        }
                    }
                }
            }),
                                              error => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;
                NotifyOfPropertyChange(() => CanCreateChannel);

                Execute.ShowDebugMessage("channels.createChannel error " + error);
            }));
        }
예제 #11
0
        public SettingsViewModel(ICacheService cacheService, ICommonErrorHandler errorHandler, IStateService stateService, INavigationService navigationService, IMTProtoService mtProtoService, ITelegramEventAggregator eventAggregator)
            : base(cacheService, errorHandler, stateService, navigationService, mtProtoService, eventAggregator)
        {
            eventAggregator.Subscribe(this);

            SuppressUpdateStatus = true;

            //tombstoning
            if (stateService.CurrentContact == null)
            {
                stateService.ClearNavigationStack = true;
                navigationService.UriFor <ShellViewModel>().Navigate();
                return;
            }

            CurrentItem = stateService.CurrentContact;
            stateService.CurrentContact = null;

            StateService.GetNotifySettingsAsync(
                settings =>
            {
                _locationServices   = settings.LocationServices;
                _peopleHub          = settings.PeopleHub;
                _saveIncomingPhotos = settings.SaveIncomingPhotos;
                _invisibleMode      = settings.InvisibleMode;
#if DISABLE_INVISIBLEMODE
                _invisibleMode = false;
#endif

                BeginOnUIThread(() =>
                {
                    NotifyOfPropertyChange(() => LocationServices);
                    NotifyOfPropertyChange(() => SaveIncomingPhotos);
                    NotifyOfPropertyChange(() => InvisibleMode);
                });
            });

            if (CurrentItem == null)
            {
                BeginOnThreadPool(() =>
                {
                    MTProtoService.GetFullUserAsync(new TLInputUserSelf(),
                                                    userFull =>
                    {
                        CurrentItem = userFull.User;
                    });
                });
            }

            PropertyChanged += OnPropertyChanged;
        }
예제 #12
0
        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();
        }
예제 #13
0
        public void DeleteContact(TLUserBase user)
        {
            if (user == null)
            {
                return;
            }

            MTProtoService.DeleteContactAsync(
                user.ToInputUser(),
                link => Items.Remove(user),
                error =>
            {
            });
        }
 public void OpenMediaContact(TLInt userId, TLUserBase user, TLString phoneNumber)
 {
     if (user == null)
     {
         MTProtoService.GetFullUserAsync(new TLInputUserContact {
             UserId = userId
         },
                                         userFull => OpenContactInternal(userFull.User, phoneNumber));
     }
     else
     {
         OpenContactInternal(user, phoneNumber);
     }
 }
예제 #15
0
        public void Handle(InvokeDeleteContacts message)
        {
            var id = new TLVector <TLInputUserBase>(CacheService.GetContacts().Where(x => x.IsContact).Select(x => x.ToInputUser()).ToList());

            MTProtoService.DeleteContactsAsync(id,
                                               result => Execute.BeginOnUIThread(() =>
            {
                Handle(Commands.LogOutCommand);
                Handle(new InvokeImportContacts());
            }),
                                               error => Execute.BeginOnUIThread(() =>
            {
            }));
        }
예제 #16
0
        private void SetTypingInternal()
        {
            var chat = Chat as TLEncryptedChatCommon;

            if (chat == null)
            {
                return;
            }

            _lastTypingTime = DateTime.Now;
            MTProtoService.SetEncryptedTypingAsync(new TLInputEncryptedChat {
                AccessHash = chat.AccessHash, ChatId = chat.Id
            }, new TLBool(true), result => { });
        }
예제 #17
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;
            }));
        }
 public void Handle(TLUpdatePrivacy privacy)
 {
     if (privacy.Key is TLPrivacyKeyStatusTimestamp)
     {
         MTProtoService.GetFullUserAsync((With).ToInputUser(),
                                         userFull =>
         {
             With = userFull.User;
             NotifyOfPropertyChange(() => With);
             Subtitle = GetSubtitle(With);
             NotifyOfPropertyChange(() => Subtitle);
         });
     }
 }
예제 #19
0
        private void UpdateLiveLocations(Action <TLMessagesBase> callback, Action <TLRPCError> faultCallback = null)
        {
            MTProtoService.GetRecentLocationsAsync(Peer, new TLInt(int.MaxValue), new TLInt(0),
                                                   result => Execute.BeginOnUIThread(() =>
            {
                if (LiveLocationBadge != null)
                {
                    LiveLocationBadge.UpdateLiveLocations(result.Messages);
                }

                callback.SafeInvoke(result);
            }),
                                                   faultCallback);
        }
예제 #20
0
        public void Initialize(BackgroundTaskDeferral deferral)
        {
            if (_connection == null & _protoService == null)
            {
                VoIPCallTask.Log("Mediator initialized", "Creating proto service");

                var deviceInfoService = new DeviceInfoService();
                var eventAggregator   = new TelegramEventAggregator();
                var cacheService      = new InMemoryCacheService(eventAggregator);
                var updatesService    = new UpdatesService(cacheService, eventAggregator);
                var transportService  = new TransportService();
                var connectionService = new ConnectionService(deviceInfoService);
                var statsService      = new StatsService();
                var protoService      = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, statsService);

                protoService.Initialized += (s, args) =>
                {
                    VoIPCallTask.Log("ProtoService initialized", "waiting for updates");

                    updatesService.LoadStateAndUpdate(() =>
                    {
                        VoIPCallTask.Log("Difference processed", "Difference processed");

                        if (_phoneCall == null)
                        {
                            VoIPCallTask.Log("Difference processed", "No call found in difference");

                            if (_systemCall != null)
                            {
                                _systemCall.NotifyCallEnded();
                            }
                        }
                    });
                };

                eventAggregator.Subscribe(this);
                protoService.Initialize();
                _protoService     = protoService;
                _transportService = transportService;
            }
            else
            {
                VoIPCallTask.Log("Mediator initialized", "_connection is null: " + (_connection == null));
            }

            _deferral    = deferral;
            _initialized = true;

            ProcessUpdates();
        }
        public void ResetAccount()
        {
            BeginOnUIThread(TimeSpan.FromSeconds(0.1), () =>
            {
                var r = MessageBox.Show(AppResources.ResetMyAccountConfirmation, AppResources.Warning, MessageBoxButton.OKCancel);
                if (r != MessageBoxResult.OK)
                {
                    return;
                }

                IsWorking = true;
                MTProtoService.DeleteAccountAsync(
                    new TLString("Forgot password"),
                    result => BeginOnUIThread(() =>
                {
                    IsWorking = false;

                    StateService.RemoveBackEntry = true;
                    StateService.SentCode        = _sentCode;
                    NavigationService.UriFor <SignUpViewModel>().Navigate();
                }),
                    error => BeginOnUIThread(() =>
                {
                    IsWorking = false;

                    if (error.TypeEquals("2FA_RECENT_CONFIRM"))
                    {
                        MessageBox.Show(AppResources.ResetAccountError, AppResources.Error, MessageBoxButton.OK);
                    }
                    else if (error.TypeStarsWith("2FA_CONFIRM_WAIT"))
                    {
                        var message = error.Message.ToString().Replace("2FA_CONFIRM_WAIT_", string.Empty);
                        try
                        {
                            var confirmWait          = Convert.ToInt32(message);
                            StateService.ConfirmWait = confirmWait;
                            StateService.SentCode    = _sentCode;
                            NavigationService.UriFor <ResetAccountViewModel>().Navigate();
                        }
                        catch (Exception e)
                        {
                        }
                    }
                    else
                    {
                        Execute.ShowDebugMessage("account.deleteAccount error " + error);
                    }
                }));
            });
        }
예제 #22
0
        private void ChangePhoneNumber()
        {
            IsWorking = true;
            NotifyOfPropertyChange(() => CanSignIn);
            var phoneNumber = PhoneCode + PhoneNumber;

            _startTime = DateTime.Now;
            _showHelpTimer.Start();
            MTProtoService.SendChangePhoneCodeAsync(new TLString(phoneNumber),
                                                    sentCode => BeginOnUIThread(() =>
            {
                _showHelpTimer.Stop();
                StateService.PhoneNumber       = new TLString(phoneNumber);
                StateService.PhoneNumberString = string.Format(AppResources.ConfirmMessage, PhoneNumberConverter.Convert(StateService.PhoneNumber));

                StateService.PhoneCodeHash     = sentCode.PhoneCodeHash;
                StateService.PhoneRegistered   = new TLBool(false);
                StateService.SendCallTimeout   = sentCode.SendCodeTimeout;
                StateService.ChangePhoneNumber = true;

                NavigationService.UriFor <ConfirmViewModel>().Navigate();

                IsWorking = false;
                NotifyOfPropertyChange(() => CanSignIn);
            }),
                                                    error => BeginOnUIThread(() =>
            {
                _lastError = error;

                IsWorking = false;
                NotifyOfPropertyChange(() => CanSignIn);

                if (error.TypeEquals(ErrorType.PHONE_NUMBER_INVALID))
                {
                    MessageBox.Show(AppResources.PhoneNumberInvalidString, AppResources.Error, MessageBoxButton.OK);
                }
                else if (error.TypeEquals(ErrorType.PHONE_NUMBER_OCCUPIED))
                {
                    MessageBox.Show(string.Format(AppResources.NewNumberTaken, "+" + phoneNumber), AppResources.Error, MessageBoxButton.OK);
                }
                else if (error.CodeEquals(ErrorCode.FLOOD))
                {
                    MessageBox.Show(AppResources.FloodWaitString + Environment.NewLine + "(" + error.Message + ")", AppResources.Error, MessageBoxButton.OK);
                }
                else
                {
                    Execute.ShowDebugMessage("account.sendChangePhoneCode error " + error);
                }
            }));
        }
        private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (Property.NameEquals(e.PropertyName, () => PeopleHub))
            {
#if WP8
                if (PreviousToken != null)
                {
                    PreviousToken.IsCanceled = true;
                }

                if (PeopleHub)
                {
                    var contacts = CacheService.GetContacts().Where(x => x != null && x.IsContact).ToList();
                    var token    = new ContactsOperationToken();

                    PreviousToken = token;
                    ContactsHelper.ImportContactsAsync(DownloadManager, token, contacts,
                                                       tuple =>
                    {
                        var importedCount = tuple.Item1;
                        var totalCount    = tuple.Item2;

                        var isComplete = importedCount == totalCount;
                        if (isComplete)
                        {
                            PreviousToken = null;
                        }

                        var duration = isComplete ? 0.5 : 2.0;
                        MTProtoService.SetMessageOnTime(duration,
                                                        string.Format(AppResources.SyncContactsProgress, importedCount, totalCount));
                    },
                                                       () =>
                    {
                        MTProtoService.SetMessageOnTime(0.0, string.Empty);
                    });
                }
                else
                {
                    IsPeopleHubEnabled = false;
                    MTProtoService.SetMessageOnTime(25.0, AppResources.DeletingContacts);
                    ContactsHelper.DeleteContactsAsync(() =>
                    {
                        IsPeopleHubEnabled = true;
                        MTProtoService.SetMessageOnTime(0.0, string.Empty);
                    });
                }
#endif
            }
        }
        public virtual void Create()
        {
            if (string.IsNullOrEmpty(Title))
            {
                MessageBox.Show(AppResources.PleaseEnterGroupSubject, AppResources.Error, MessageBoxButton.OK);
                return;
            }

            var participants = new TLVector <TLInputUserBase>();

            foreach (var item in SelectedUsers)
            {
                participants.Add(item.ToInputUser());
            }

            if (participants.Count == 0)
            {
                MessageBox.Show(AppResources.PleaseChooseAtLeastOneParticipant, AppResources.Error, MessageBoxButton.OK);
                return;
            }

            IsWorking = true;
            MTProtoService.CreateChatAsync(participants, new TLString(Title),
                                           statedMessage =>
            {
                IsWorking = false;
                foreach (var item in Items)
                {
                    item.IsSelected = false;
                }

                var updates = statedMessage as TLUpdates;
                if (updates != null)
                {
                    StateService.With            = updates.Chats.First();
                    StateService.RemoveBackEntry = true;
                    BeginOnUIThread(() => NavigationService.UriFor <DialogDetailsViewModel>().Navigate());
                }
            },
                                           error => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;

                if (error.CodeEquals(ErrorCode.FLOOD))
                {
                    MessageBox.Show(AppResources.FloodWaitString + Environment.NewLine + "(" + error.Message + ")", AppResources.Error, MessageBoxButton.OK);
                }
            }));
        }
예제 #25
0
        public void OnBackKeyPressed(CancelEventArgs args)
        {
#if LOG_REGISTRATION
            TLUtils.WriteLog("SignInViewModel.OnBackKeyPressed");
#endif

            if (IsWorking)
            {
                args.Cancel = true;
                IsWorking   = false;
                MTProtoService.CancelSignInAsync();
                MTProtoService.ClearHistory("SignInViewModel", false);
                NotifyOfPropertyChange(() => CanSignIn);
            }
        }
        public CreateChannelStep2ViewModel(ICacheService cacheService, ICommonErrorHandler errorHandler, IStateService stateService, INavigationService navigationService, IMTProtoService mtProtoService, ITelegramEventAggregator eventAggregator)
            : base(cacheService, errorHandler, stateService, navigationService, mtProtoService, eventAggregator)
        {
            AdminedPublicChannels = new ObservableCollection <TLChatBase>();

            InviteLink = AppResources.Loading;

            _newChannel             = StateService.NewChannel;
            StateService.NewChannel = null;

            MTProtoService.CheckUsernameAsync(new TLInputChannelEmpty(), new TLString("username"),
                                              result => BeginOnUIThread(() =>
            {
                TooMuchUsernames = false;
            }),
                                              error => BeginOnUIThread(() =>
            {
                if (TLRPCError.TypeEquals(error, ErrorType.CHANNELS_ADMIN_PUBLIC_TOO_MUCH))
                {
                    HasError         = true;
                    Error            = AppResources.ChannelsAdminPublicTooMuchShort;
                    TooMuchUsernames = true;
                    GetAdminedPublichChannelsAsync();
                }
            }));

            PropertyChanged += (sender, args) =>
            {
                if (Property.NameEquals(args.PropertyName, () => IsPublic))
                {
                    if (!IsPublic && Invite == null)
                    {
                        ExportInvite();
                    }
                }
                else if (Property.NameEquals(args.PropertyName, () => UserName))
                {
                    var userName = UserName;
                    BeginOnUIThread(TimeSpan.FromSeconds(0.3), () =>
                    {
                        if (string.Equals(userName, UserName))
                        {
                            Check();
                        }
                    });
                }
            };
        }
예제 #27
0
        protected override void OnActivate()
        {
            base.OnActivate();

            if (StateService.Participant != null)
            {
                var blockedUser = StateService.Participant;
                StateService.Participant = null;

                MTProtoService.BlockAsync(blockedUser.ToInputUser(),
                                          result =>
                {
                    Items.Add(blockedUser);
                    Status = Items.Count > 0 || LazyItems.Count > 0 ? string.Empty : string.Format("{0}", AppResources.NoUsersHere);
                });
            }
        }
예제 #28
0
        public void Handle(TLUpdateUserBlocked update)
        {
            var user = CacheService.GetUser(update.UserId);

            if (user != null)
            {
                UpdateBlockedList(user, update);
            }
            else
            {
                MTProtoService.GetFullUserAsync(
                    new TLInputUserContact {
                    UserId = update.UserId
                },
                    fullUser => UpdateBlockedList(fullUser.User, update));
            }
        }
예제 #29
0
        public void DeletePhoto()
        {
            if (_currentContact == null || !_currentContact.IsSelf)
            {
                return;
            }
            if (CurrentItem == null)
            {
                return;
            }

            var currentItem = CurrentItem;

            IsWorking = true;
            MTProtoService.UpdateProfilePhotoAsync(new TLInputPhotoEmpty(),
                                                   result =>
            {
                Execute.BeginOnUIThread(TimeSpan.FromSeconds(0.1), () =>
                {
                    IsWorking = false;

                    if (CanSlideLeft)
                    {
                        var view = GetView() as ProfilePhotoViewerView;
                        if (view != null)
                        {
                            _items.RemoveAt(_currentIndex--);
                            view.SlideLeft(0.0, () =>
                            {
                                view.SetControlContent(0, PreviousItem);
                                GroupedItems.Remove(currentItem);
                            });
                        }
                    }
                    else
                    {
                        Execute.BeginOnUIThread(TimeSpan.FromSeconds(0.25), CloseViewer);
                    }
                });
            },
                                                   error =>
            {
                IsWorking = false;
                Execute.ShowDebugMessage("photos.updateProfilePhoto error " + error);
            });
        }
예제 #30
0
        public ChannelAdministratorsViewModel(ICacheService cacheService, ICommonErrorHandler errorHandler, IStateService stateService, INavigationService navigationService, IMTProtoService mtProtoService, ITelegramEventAggregator eventAggregator)
            : base(cacheService, errorHandler, stateService, navigationService, mtProtoService, eventAggregator)
        {
            EventAggregator.Subscribe(this);

            CurrentItem = StateService.CurrentChat;
            StateService.CurrentChat = null;

            ChatInviteItems = new List <string>
            {
                AppResources.AllMembers.ToLowerInvariant(),
                    AppResources.OnlyAdmins.ToLowerInvariant()
            };
            var channel = CurrentItem as TLChannel44;

            _selectedChatInviteItem = channel != null && channel.IsDemocracy? ChatInviteItems[0] : ChatInviteItems[1];

            Items = new ObservableCollection <TLUserBase>();

            Status = AppResources.Loading;

            PropertyChanged += (sender, e) =>
            {
                if (Property.NameEquals(e.PropertyName, () => SelectedChatInviteItem))
                {
                    channel = CurrentItem as TLChannel44;
                    if (channel == null)
                    {
                        return;
                    }
                    var enabled = SelectedChatInviteItem == ChatInviteItems[0];
                    IsWorking = true;
                    MTProtoService.ToggleInvitesAsync(channel.ToInputChannel(), new TLBool(enabled),
                                                      result => Execute.BeginOnUIThread(() =>
                    {
                        IsWorking = false;
                    }),
                                                      error => Execute.BeginOnUIThread(() =>
                    {
                        IsWorking = false;
                        Execute.ShowDebugMessage("channels.toggleInvites error " + error);
                    }));
                }
            };
        }