public AddChatParticipantViewModel(ICacheService cacheService, ICommonErrorHandler errorHandler, IStateService stateService, INavigationService navigationService, IMTProtoService mtProtoService, ITelegramEventAggregator eventAggregator)
            : base(cacheService, errorHandler, stateService, navigationService, mtProtoService, eventAggregator)
        {
            if (StateService.CurrentRole != null)
            {
                _currentRole             = StateService.CurrentRole;
                StateService.CurrentRole = null;
            }

            if (StateService.CurrentChat != null)
            {
                _currentChat             = StateService.CurrentChat;
                StateService.CurrentChat = null;
            }

            if (StateService.RemovedUsers != null)
            {
                foreach (var user in StateService.RemovedUsers)
                {
                    _removedUsers[user.Index] = user;
                }
                StateService.RemovedUsers = null;
            }

            if (StateService.RequestForwardingCount)
            {
                _requestForwardingCount             = true;
                StateService.RequestForwardingCount = false;
            }

            _inviteVisibility            = StateService.IsInviteVisible ? Visibility.Visible : Visibility.Collapsed;
            StateService.IsInviteVisible = false;

            BeginOnThreadPool(() =>
            {
                var isAuthorized = SettingsHelper.GetValue <bool>(Constants.IsAuthorizedKey);
                if (isAuthorized)
                {
                    var contacts = CacheService.GetContacts();
                    Status       = string.Empty;
                    Items.Clear();
                    foreach (var contact in contacts.OrderBy(x => x.FullName))
                    {
                        if (!(contact is TLUserEmpty) && contact.Index != StateService.CurrentUserId && !_removedUsers.ContainsKey(contact.Index))
                        {
                            Items.Add(contact);
                        }
                    }
                }

                BeginOnUIThread(() =>
                {
                    if (StateService.RemoveBackEntry)
                    {
                        NavigationService.RemoveBackEntry();
                        StateService.RemoveBackEntry = false;
                    }
                });
            });
        }
Beispiel #2
0
        public TLBitmapSource(TLChatBase chatBase)
        {
            _source = chatBase;

            _bitmapImage.DecodePixelWidth  = 64;
            _bitmapImage.DecodePixelHeight = 64;

            TLChatPhotoBase chatPhotoBase = null;

            if (chatBase is TLChannel channel)
            {
                chatPhotoBase = channel.Photo;
            }

            if (chatBase is TLChat chat)
            {
                chatPhotoBase = chat.Photo;
            }

            if (chatPhotoBase is TLChatPhoto chatPhoto)
            {
                if (TrySetSource(chatPhoto.PhotoSmall as TLFileLocation, PHASE_FULL) == false)
                {
                    //SetProfilePlaceholder(chatBase, "c" + chatBase.Id, chatBase.Id, chatBase.DisplayName);
                    SetSource(null, chatPhoto.PhotoSmall as TLFileLocation, 0, PHASE_FULL);
                }
            }
            else
            {
                SetProfilePlaceholder(chatBase, "c" + chatBase.Id, chatBase.Id, chatBase.DisplayName);
            }
        }
        public InviteLinkViewModel(ICacheService cacheService, ICommonErrorHandler errorHandler, IStateService stateService, INavigationService navigationService, IMTProtoService mtProtoService, ITelegramEventAggregator eventAggregator)
            : base(cacheService, errorHandler, stateService, navigationService, mtProtoService, eventAggregator)
        {
            if (StateService.CurrentChat != null)
            {
                _chat = StateService.CurrentChat;
                StateService.CurrentChat = null;
            }

            if (_chat == null)
            {
                return;
            }

            var chatInviteExported = _chat.ExportedInvite as TLChatInviteExported;

            if (chatInviteExported != null)
            {
                _link = chatInviteExported.Link.ToString();
            }
            else
            {
                ExportChatInviteAsync();
            }
        }
Beispiel #4
0
        public AddAdminsViewModel(ICacheService cacheService, ICommonErrorHandler errorHandler, IStateService stateService, INavigationService navigationService, IMTProtoService mtProtoService, ITelegramEventAggregator eventAggregator)
            : base(cacheService, errorHandler, stateService, navigationService, mtProtoService, eventAggregator)
        {
            EventAggregator.Subscribe(this);

            Status = AppResources.Loading;

            _currentChat             = StateService.CurrentChat;
            StateService.CurrentChat = null;

            var chat = _currentChat as TLChat40;

            _adminsEnabled = chat != null && chat.AdminsEnabled.Value;

            PropertyChanged += (sender, args) =>
            {
                if (Property.NameEquals(args.PropertyName, () => AdminsEnabled))
                {
                    if (!AdminsEnabled)
                    {
                        foreach (var item in Items)
                        {
                            item.IsSelected = !AdminsEnabled;
                        }
                    }
                    else
                    {
                        UpdateAdmins(_currentChat.Participants as IChatParticipants);
                    }

                    NotifyOfPropertyChange(() => AddAdminsDescription);
                }
            };
        }
Beispiel #5
0
        public ProfilePhotoViewerViewModel(IStateService stateService, IMTProtoService mtProtoService)
        {
            StateService   = stateService;
            MTProtoService = mtProtoService;

            _currentContact = StateService.CurrentContact;
            _currentChat    = StateService.CurrentChat;

            GroupedItems = new BindableCollection <TLPhotoBase>();
        }
Beispiel #6
0
        public void OpenChatDetails(TLChatBase chat)
        {
            if (chat == null)
            {
                return;
            }

            StateService.With         = chat;
            StateService.AnimateTitle = true;
            NavigationService.UriFor <DialogDetailsViewModel>().Navigate();
        }
Beispiel #7
0
        public static void NavigateToChat(TLChatBase chatBase)
        {
            if (chatBase == null)
            {
                return;
            }

            Execute.BeginOnUIThread(() =>
            {
                IoC.Get <IStateService>().With = chatBase;
                IoC.Get <IStateService>().RemoveBackEntries = true;
                IoC.Get <INavigationService>().Navigate(new Uri("/Views/Dialogs/DialogDetailsView.xaml?rndParam=" + TLInt.Random(), UriKind.Relative));
            });
        }
Beispiel #8
0
        public static void DeleteAndExitDialogCommon(TLChatBase chatBase, IMTProtoService mtProtoService, System.Action callback, Action <TLRPCError> faultCallback = null)
        {
            if (chatBase == null)
            {
                return;
            }

            var inputPeer = chatBase.ToInputPeer();

            if (chatBase is TLChatForbidden)
            {
                DeleteHistoryAsync(
                    mtProtoService,
                    false,
                    inputPeer, new TLInt(0),
                    affectedHistory => callback.SafeInvoke(),
                    faultCallback.SafeInvoke);
            }
            else
            {
                var chat   = chatBase as TLChat;
                var chat41 = chatBase as TLChat41;
                if (chat != null)
                {
                    if (chat.Left.Value || (chat41 != null && chat41.IsMigrated))
                    {
                        DeleteHistoryAsync(
                            mtProtoService,
                            false,
                            inputPeer, new TLInt(0),
                            affectedHistory => callback.SafeInvoke(),
                            faultCallback.SafeInvoke);
                    }
                    else
                    {
                        mtProtoService.DeleteChatUserAsync(
                            chat.Id, new TLInputUserSelf(),
                            statedMessage =>
                            DeleteHistoryAsync(
                                mtProtoService,
                                false,
                                inputPeer, new TLInt(0),
                                affectedHistory => callback.SafeInvoke(),
                                faultCallback.SafeInvoke),
                            faultCallback.SafeInvoke);
                    }
                }
            }
        }
        public void Open(TLUserBase user, TLChatBase chat, Action <AddChatParticipantBoxResult> callback)
        {
            var userName = user.FirstName;

            if (TLString.IsNullOrEmpty(userName))
            {
                userName = user.LastName;
            }

            AddUserToTheGroupString = string.Format(AppResources.AddUserToTheGroup, userName, chat.FullName);
            NotifyOfPropertyChange(() => AddUserToTheGroupString);

            IsOpen    = true;
            _callback = callback;
        }
Beispiel #10
0
        public SearchContactsViewModel(ICacheService cacheService, ICommonErrorHandler errorHandler, IStateService stateService, INavigationService navigationService, IMTProtoService mtProtoService, ITelegramEventAggregator eventAggregator)
            : base(cacheService, errorHandler, stateService, navigationService, mtProtoService, eventAggregator)
        {
            EventAggregator.Subscribe(this);

            Items  = new ObservableCollection <TLObject>();
            Status = string.Empty;

            _currentChat             = StateService.CurrentChat;
            StateService.CurrentChat = null;

            if (StateService.CurrentAdminRights != null)
            {
                _currentAdminRights             = StateService.CurrentAdminRights;
                StateService.CurrentAdminRights = null;
            }

            if (StateService.CurrentRole != null)
            {
                _currentRole             = StateService.CurrentRole;
                StateService.CurrentRole = null;
            }

            if (StateService.RequestForwardingCount)
            {
                RequestForwardingCount = true;
                StateService.RequestForwardingCount = false;
            }

            if (StateService.NavigateToDialogDetails)
            {
                NavigateToDialogDetails = true;
                StateService.NavigateToDialogDetails = false;
            }

            if (StateService.NavigateToSecretChat)
            {
                NavigateToSecretChat = true;
                StateService.NavigateToSecretChat = false;
                _dhConfig             = StateService.DHConfig;
                StateService.DHConfig = null;

                if (_dhConfig == null)
                {
                    Execute.BeginOnThreadPool(GetDHConfig);
                }
            }
        }
Beispiel #11
0
        private static bool IsChatValid(TLChatBase chat, string text, bool useFastSearch)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(false);
            }

            if (!useFastSearch)
            {
                var fullName = chat.FullName;

                var i = fullName.IndexOf(text, StringComparison.OrdinalIgnoreCase);
                if (i != -1)
                {
                    while (i < fullName.Length && i != -1)
                    {
                        if (i == 0 || (i > 0 && fullName[i - 1] == ' '))
                        {
                            return(true);
                        }
                        if (fullName.Length > i + 1)
                        {
                            i = fullName.IndexOf(text, i + 1, StringComparison.OrdinalIgnoreCase);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                if (chat.FullNameWords != null &&
                    chat.FullNameWords.Any(x => x.StartsWith(text, StringComparison.OrdinalIgnoreCase)))
                {
                    return(true);
                }
            }

            return(false);
        }
Beispiel #12
0
 public UpdateChatTitleEventArgs(TLChatBase chat, string title)
 {
     Chat  = chat;
     Title = title;
 }
        public void RevokeLink(TLChatBase chat)
        {
            var channel = chat as TLChannel;

            if (channel == null)
            {
                return;
            }

            var richTextBox = new RichTextBox {
                TextWrapping = TextWrapping.Wrap
            };

            ConvertToSupergroupView.SetFormattedText(richTextBox, string.Format(AppResources.RevokeLinkConfirmation2, "t.me/" + channel.UserName, channel.FullName));
#if WP8
            var isFullHD = Application.Current.Host.Content.ScaleFactor == 225;
            if (isFullHD)
            {
                richTextBox.FontSize = 17.667;
            }
#endif
            ShellViewModel.ShowCustomMessageBox(null, AppResources.RevokeLink,
                                                AppResources.Cancel.ToLowerInvariant(), AppResources.Revoke.ToLowerInvariant(),
                                                dismissed =>
            {
                if (dismissed == CustomMessageBoxResult.LeftButton)
                {
                    IsWorking = true;
                    MTProtoService.UpdateUsernameAsync(channel.ToInputChannel(), TLString.Empty,
                                                       user => Execute.BeginOnUIThread(() =>
                    {
                        IsWorking = false;

                        channel.UserName = TLString.Empty;
                        channel.NotifyOfPropertyChange(() => channel.UserName);

                        TooMuchUsernames = false;
                        HasError         = false;
                        Error            = string.Empty;
                        Check();
                    }),
                                                       error => Execute.BeginOnUIThread(() =>
                    {
                        IsWorking = false;
                        if (TLRPCError.CodeEquals(error, ErrorCode.FLOOD))
                        {
                            //HasError = true;
                            //Error = AppResources.FloodWaitString;
                            MessageBox.Show(AppResources.FloodWaitString, AppResources.Error, MessageBoxButton.OK);
                        }
                        else if (TLRPCError.CodeEquals(error, ErrorCode.INTERNAL))
                        {
                            var messageBuilder = new StringBuilder();
                            messageBuilder.AppendLine(AppResources.ServerErrorMessage);
                            messageBuilder.AppendLine();
                            messageBuilder.AppendLine("Method: channels.updateUsername");
                            messageBuilder.AppendLine("Result: " + error);

                            //HasError = true;
                            //Error = AppResources.ServerError;
                            MessageBox.Show(messageBuilder.ToString(), AppResources.ServerError, MessageBoxButton.OK);
                        }
                        else if (TLRPCError.CodeEquals(error, ErrorCode.BAD_REQUEST))
                        {
                            if (TLRPCError.TypeEquals(error, ErrorType.USERNAME_NOT_MODIFIED))
                            {
                                channel.UserName = TLString.Empty;
                                channel.NotifyOfPropertyChange(() => channel.UserName);

                                HasError = false;
                                Error    = string.Empty;
                                Check();
                                return;
                            }
                            else if (TLRPCError.TypeEquals(error, ErrorType.USERNAME_INVALID))
                            {
                                //HasError = true;
                                //Error = AppResources.ChannelNameInvalid;
                                MessageBox.Show(AppResources.ChannelNameInvalid, AppResources.Error, MessageBoxButton.OK);
                            }
                            else if (TLRPCError.TypeEquals(error, ErrorType.USERNAME_OCCUPIED))
                            {
                                //HasError = true;
                                //Error = AppResources.ChannelNameInvalid;
                                MessageBox.Show(AppResources.ChannelNameOccupied, AppResources.Error, MessageBoxButton.OK);
                            }
                            else if (TLRPCError.TypeEquals(error, ErrorType.CHANNELS_ADMIN_PUBLIC_TOO_MUCH))
                            {
                                //HasError = true;
                                //Error = AppResources.ChannelsAdminPublicTooMuchShort;
                                MessageBox.Show(AppResources.ChannelsAdminPublicTooMuch, AppResources.Error, MessageBoxButton.OK);
                            }
                            else
                            {
                                //HasError = true;
                                //Error = error.ToString();
                                Execute.ShowDebugMessage("channels.updateUsername error " + error);
                            }
                        }
                        else
                        {
                            //HasError = true;
                            //Error = string.Empty;
                            Execute.ShowDebugMessage("channels.updateUsername error " + error);
                        }
                    }));
                }
            },
                                                richTextBox);
        }
Beispiel #14
0
        public ChatPhotosViewModel(IMTProtoService protoService, ICacheService cacheService, TLChatFullBase chatFull, TLChatBase chat, TLMessageService serviceMessage)
            : base(protoService, cacheService, null)
        {
            _peer      = chat.ToInputPeer();
            _lastMaxId = serviceMessage.Id;

            if (serviceMessage.Action is TLMessageActionChatEditPhoto editPhotoAction)
            {
                Items = new MvxObservableCollection <GalleryItem> {
                    new GalleryPhotoItem(editPhotoAction.Photo as TLPhoto, chat)
                };
                SelectedItem = Items[0];
                FirstItem    = Items[0];
            }

            Initialize(serviceMessage.Id);
        }
 public ConvertToSupergroupViewModel(ICacheService cacheService, ICommonErrorHandler errorHandler, IStateService stateService, INavigationService navigationService, IMTProtoService mtProtoService, ITelegramEventAggregator eventAggregator)
     : base(cacheService, errorHandler, stateService, navigationService, mtProtoService, eventAggregator)
 {
     CurrentItem = StateService.CurrentChat;
     StateService.CurrentChat = null;
 }
Beispiel #16
0
        public void Notify(TLMessageCommonBase messageCommon)
        {
            //if (this._stateService.SuppressNotifications)
            //{
            //    return;
            //}
            if (messageCommon.IsOut)
            {
                return;
            }

            if (!messageCommon.IsUnread)
            {
                return;
            }

            if (messageCommon is TLMessage message && message.IsSilent)
            {
                return;
            }

            TLUser from = null;

            if (messageCommon.FromId != null && messageCommon.FromId.Value >= 0)
            {
                from = CacheService.GetUser(messageCommon.FromId) as TLUser;
                if (from == null)
                {
                    return;
                }
            }

            try
            {
                TLObject   activeDialog = CheckActiveDialog();
                TLPeerBase toId         = messageCommon.ToId;
                var        fromId       = messageCommon.FromId;
                var        suppress     = false;
                TLDialog   dialog       = null;
                if (toId is TLPeerChat && activeDialog is TLChat && toId.Id == ((TLChat)activeDialog).Id)
                {
                    suppress = true;
                }
                if (toId is TLPeerChannel && activeDialog is TLChannel && toId.Id == ((TLChannel)activeDialog).Id)
                {
                    suppress = true;
                }
                else if (toId is TLPeerUser && activeDialog is TLUserBase && ((from != null && from.IsSelf) || fromId.Value == ((TLUserBase)activeDialog).Id))
                {
                    suppress = true;
                }

                if (!suppress)
                {
                    TLChatBase chat    = null;
                    TLUser     user    = null;
                    TLChannel  channel = null;
                    if (messageCommon.ToId is TLPeerChat)
                    {
                        chat   = CacheService.GetChat(messageCommon.ToId.Id);
                        dialog = CacheService.GetDialog(new TLPeerChat
                        {
                            Id = messageCommon.ToId.Id
                        });
                    }
                    else if (messageCommon.ToId is TLPeerChannel)
                    {
                        chat    = CacheService.GetChat(messageCommon.ToId.Id);
                        channel = (chat as TLChannel);
                        dialog  = CacheService.GetDialog(new TLPeerChannel {
                            ChannelId = messageCommon.ToId.Id
                        });
                    }
                    else if (messageCommon.IsOut)
                    {
                        user   = CacheService.GetUser(messageCommon.ToId.Id) as TLUser;
                        dialog = CacheService.GetDialog(new TLPeerUser {
                            UserId = messageCommon.ToId.Id
                        });
                    }
                    else
                    {
                        user   = CacheService.GetUser(messageCommon.FromId) as TLUser;
                        dialog = CacheService.GetDialog(new TLPeerUser {
                            UserId = messageCommon.FromId.Value
                        });
                    }

                    var now = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);
                    if (chat != null)
                    {
                        var notifySettingsBase = CacheService.GetFullChat(chat.Id)?.NotifySettings;
                        if (notifySettingsBase == null)
                        {
                            notifySettingsBase = ((dialog != null) ? dialog.NotifySettings : null);
                        }

                        if (notifySettingsBase == null)
                        {
                            if (channel != null)
                            {
                                ProtoService.GetFullChannelAsync(channel.ToInputChannel(), chatFull =>
                                {
                                    //chat.NotifySettings = chatFull.FullChat.NotifySettings;
                                    if (dialog != null)
                                    {
                                        dialog.NotifySettings = chatFull.FullChat.NotifySettings;

                                        Execute.BeginOnUIThread(() =>
                                        {
                                            dialog.RaisePropertyChanged(() => dialog.NotifySettings);
                                            dialog.RaisePropertyChanged(() => dialog.Self);
                                        });
                                    }
                                }, null);
                            }
                            else
                            {
                                ProtoService.GetFullChatAsync(chat.Id, chatFull =>
                                {
                                    //chat.NotifySettings = chatFull.FullChat.NotifySettings;
                                    if (dialog != null)
                                    {
                                        dialog.NotifySettings = chatFull.FullChat.NotifySettings;

                                        Execute.BeginOnUIThread(() =>
                                        {
                                            dialog.RaisePropertyChanged(() => dialog.NotifySettings);
                                            dialog.RaisePropertyChanged(() => dialog.Self);
                                        });
                                    }
                                }, null);
                            }
                        }

                        var notifySettings = notifySettingsBase as TLPeerNotifySettings;
                        suppress = (notifySettings == null || notifySettings.MuteUntil > now);
                    }

                    if (user != null)
                    {
                        var notifySettingsBase = CacheService.GetFullUser(user.Id)?.NotifySettings;
                        if (notifySettingsBase == null)
                        {
                            notifySettingsBase = ((dialog != null) ? dialog.NotifySettings : null);
                        }

                        if (notifySettingsBase == null)
                        {
                            ProtoService.GetFullUserAsync(user.ToInputUser(), userFull =>
                            {
                                //user.NotifySettings = userFull.NotifySettings;
                                if (dialog != null)
                                {
                                    dialog.NotifySettings = userFull.NotifySettings;

                                    Execute.BeginOnUIThread(() =>
                                    {
                                        dialog.RaisePropertyChanged(() => dialog.NotifySettings);
                                        dialog.RaisePropertyChanged(() => dialog.Self);
                                    });
                                }
                            }, null);
                        }

                        var notifySettings = notifySettingsBase as TLPeerNotifySettings;
                        suppress = (notifySettings == null || notifySettings.MuteUntil > now || user.IsSelf);
                    }

                    if (!suppress)
                    {
                        if (dialog != null)
                        {
                            suppress = CheckLastNotificationTime(dialog, now);
                        }

                        if (!suppress)
                        {
                            if (ApplicationSettings.Current.InAppPreview)
                            {
                                // TODO
                            }

                            if (_lastNotificationTime.HasValue)
                            {
                                var totalSeconds = (DateTime.Now - _lastNotificationTime.Value).TotalSeconds;
                                if (totalSeconds > 0.0 && totalSeconds < 2.0)
                                {
                                    suppress = true;
                                }
                            }

                            _lastNotificationTime = DateTime.Now;

                            if (suppress)
                            {
                                Log.Write(string.Format("Cancel notification reason=[lastNotificationTime] msg_id={0} last_notification_time={1}, now={2}", messageCommon.Id, _lastNotificationTime, DateTime.Now), null);
                            }
                            else
                            {
                                if (ApplicationSettings.Current.InAppVibrate)
                                {
                                    _vibrationService.VibrateAsync();
                                }

                                if (ApplicationSettings.Current.InAppSounds)
                                {
                                    //if (_notificationPlayer == null)
                                    //{
                                    //    _notificationPlayer = new MediaPlayer();
                                    //    _notificationPlayer.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/Sounds/Default.wav"));
                                    //}

                                    //_notificationPlayer.Pause();
                                    //_notificationPlayer.PlaybackSession.Position = TimeSpan.Zero;
                                    //_notificationPlayer.Play();



                                    //string text = "Sounds/Default.wav";
                                    //if (toId is TLPeerChat && !string.IsNullOrEmpty(s.GroupSound))
                                    //{
                                    //    text = "Sounds/" + s.GroupSound + ".wav";
                                    //}
                                    //else if (!string.IsNullOrEmpty(s.ContactSound))
                                    //{
                                    //    text = "Sounds/" + s.ContactSound + ".wav";
                                    //}
                                    //if (toId is TLPeerChat && chat != null && chat.NotifySettings is TLPeerNotifySettings)
                                    //{
                                    //    text = "Sounds/" + ((TLPeerNotifySettings)chat.NotifySettings).Sound.Value + ".wav";
                                    //}
                                    //else if (toId is TLPeerUser && user != null && user.NotifySettings is TLPeerNotifySettings)
                                    //{
                                    //    text = "Sounds/" + ((TLPeerNotifySettings)user.NotifySettings).Sound.Value + ".wav";
                                    //}
                                    //if (!Utils.XapContentFileExists(text))
                                    //{
                                    //    text = "Sounds/Default.wav";
                                    //}
                                    //System.IO.Stream stream = TitleContainer.OpenStream(text);
                                    //SoundEffect soundEffect = SoundEffect.FromStream(stream);
                                    //FrameworkDispatcher.Update();
                                    //soundEffect.Play();
                                }
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                TLUtils.WriteLine(ex.ToString(), LogSeverity.Error);
            }
        }
Beispiel #17
0
        private void SetInitState()
        {
            CurrentItem = StateService.CurrentPhoto;
            StateService.CurrentPhoto = null;

            if (StateService.CurrentContact != null)
            {
                _currentContact             = StateService.CurrentContact;
                StateService.CurrentContact = null;

                IsWorking = true;
                MTProtoService.GetUserPhotosAsync(_currentContact.ToInputUser(), new TLInt(0), new TLLong(0),
                                                  new TLInt(0),
                                                  photos => Execute.BeginOnUIThread(() =>
                {
                    _currentIndex = 0;
                    _items.Clear();
                    foreach (var photo in photos.Photos)
                    {
                        _items.Add(photo);
                    }

                    GroupedItems.IsNotifying = false;
                    GroupedItems.Clear();
                    if (_items.Count > 1)
                    {
                        GroupedItems.AddRange(_items);
                    }
                    GroupedItems.IsNotifying = true;
                    GroupedItems.Refresh();

                    PreviousItem = _currentIndex + 1 < _items.Count ? _items[_currentIndex + 1] : null;
                    NextItem     = _currentIndex > 0 ? _items[_currentIndex - 1] : null;

                    var view = GetView() as ProfilePhotoViewerView;
                    if (view != null)
                    {
                        view.SetControlContent(0, NextItem);
                        view.SetControlContent(2, PreviousItem);
                        if (_items.Count > 0)
                        {
                            view.ScrollTo(_items[_currentIndex], 0.25);
                        }
                    }

                    IsWorking = false;
                }),
                                                  error => Execute.BeginOnUIThread(() =>
                {
                    IsWorking = false;
                    Execute.ShowDebugMessage("photos.getUserPhotos error=" + error);
                }));
            }
            else if (StateService.CurrentChat != null)
            {
                _currentChat             = StateService.CurrentChat;
                StateService.CurrentChat = null;

                IsWorking = true;
                MTProtoService.SearchAsync(
                    _currentChat.ToInputPeer(),
                    TLString.Empty,
                    null,
                    new TLInputMessagesFilterChatPhotos(),
                    new TLInt(0),
                    new TLInt(0),
                    new TLInt(0),
                    new TLInt(0),
                    new TLInt(100),
                    new TLInt(0),
                    result => Execute.BeginOnUIThread(() =>
                {
                    _items.Clear();
                    _currentIndex = -1;
                    for (var i = 0; i < result.Messages.Count; i++)
                    {
                        var messageService = result.Messages[i] as TLMessageService;
                        if (messageService != null)
                        {
                            var chatEditPhotoAction = messageService.Action as TLMessageActionChatEditPhoto;
                            if (chatEditPhotoAction != null)
                            {
                                _items.Add(chatEditPhotoAction.Photo);

                                var photo        = chatEditPhotoAction.Photo as TLPhoto;
                                var currentPhoto = CurrentItem as TLPhoto;
                                var chatPhoto    = CurrentItem as TLChatPhoto;
                                if (photo != null &&
                                    currentPhoto != null &&
                                    photo.Id.Value == currentPhoto.Id.Value ||
                                    (chatPhoto != null && ChatPhotoEquals(chatPhoto, photo)))
                                {
                                    _currentIndex = _items.Count - 1;
                                }
                            }
                        }
                    }

                    if (_currentIndex == -1)
                    {
                        if (_items.Count > 0)
                        {
                            _items.Insert(0, CurrentItem);
                            _currentIndex = 0;
                        }
                    }

                    GroupedItems.IsNotifying = false;
                    GroupedItems.Clear();
                    if (_items.Count > 1)
                    {
                        GroupedItems.AddRange(_items);
                    }
                    GroupedItems.IsNotifying = true;
                    GroupedItems.Refresh();

                    PreviousItem = _currentIndex + 1 < _items.Count ? _items[_currentIndex + 1] : null;
                    NextItem     = _currentIndex > 0 ? _items[_currentIndex - 1] : null;

                    var view = GetView() as ProfilePhotoViewerView;
                    if (view != null)
                    {
                        view.SetControlContent(0, NextItem);
                        view.SetControlContent(2, PreviousItem);
                        if (_items.Count > 0)
                        {
                            view.ScrollTo(_items[_currentIndex], 0.25);
                        }
                    }

                    IsWorking = false;
                }),
                    error => Execute.BeginOnUIThread(() =>
                {
                    IsWorking = false;
                    Execute.ShowDebugMessage("messages.search error=" + error);
                }));
            }
        }
        public ChatPhotosViewModel(IMTProtoService protoService, TLChatFullBase chatFull, TLChatBase chat)
            : base(protoService, null, null)
        {
            _peer      = chat.ToInputPeer();
            _lastMaxId = int.MaxValue;

            Items = new MvxObservableCollection <GalleryItem> {
                new GalleryPhotoItem(chatFull.ChatPhoto as TLPhoto, chat)
            };
            SelectedItem = Items[0];
            FirstItem    = Items[0];
            Initialize();
        }
Beispiel #19
0
        public GroupStickersViewModel(ICacheService cacheService, ICommonErrorHandler errorHandler, IStateService stateService, INavigationService navigationService, IMTProtoService mtProtoService, ITelegramEventAggregator eventAggregator)
            : base(cacheService, errorHandler, stateService, navigationService, mtProtoService, eventAggregator)
        {
            _channel = StateService.CurrentChat;
            var channel68 = _channel as TLChannel68;

            if (channel68 != null)
            {
                _stickerSet = channel68.StickerSet;
                _text       = _stickerSet != null && !TLString.IsNullOrEmpty(_stickerSet.ShortName)
                    ? _stickerSet.ShortName.ToString()
                    : null;

                var stickerSet32 = StickerSet as TLStickerSet32;
                if (stickerSet32 != null && stickerSet32.Stickers == null)
                {
                    MTProtoService.GetStickerSetAsync(new TLInputStickerSetShortName {
                        ShortName = stickerSet32.ShortName
                    },
                                                      result => Execute.BeginOnUIThread(() =>
                    {
                        var objects = new TLVector <TLObject>();
                        foreach (var sticker in result.Documents)
                        {
                            objects.Add(new TLStickerItem {
                                Document = sticker
                            });
                        }

                        stickerSet32.Stickers = objects;
                        stickerSet32.NotifyOfPropertyChange(() => stickerSet32.Stickers);
                    }),
                                                      error =>
                    {
                    });
                }
            }
            StateService.CurrentChat = null;

            PropertyChanged += (sender, args) =>
            {
                if (Property.NameEquals(args.PropertyName, () => Text))
                {
                    if (string.IsNullOrEmpty(Text))
                    {
                        Remove(false);
                    }
                    else if (StickerSet is TLStickerSet32 && string.Equals(StickerSet.ShortName.ToString(), Text))
                    {
                    }
                    else if (Text.Contains("/addstickers"))
                    {
                        var shortNameStartIndex = Text.TrimEnd('/').LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
                        if (shortNameStartIndex != -1)
                        {
                            var shortName = Text.Substring(shortNameStartIndex).Replace("/", string.Empty);

                            if (!string.IsNullOrEmpty(shortName))
                            {
                                Text = shortName;
                                var view = GetView() as GroupStickersView;
                                if (view != null)
                                {
                                    view.MoveCursorToEnd();
                                }
                            }
                        }
                    }
                    else
                    {
                        var text = Text;
                        Execute.BeginOnUIThread(TimeSpan.FromSeconds(0.5), () =>
                        {
                            if (string.Equals(text, Text))
                            {
                                SearchStickerSet(text);
                            }
                        });
                    }
                }
            };
        }