Esempio n. 1
0
        public void EditAdminAsync(TLChannel channel, TLInputUserBase userId, TLChannelAdminRights rights, Action <TLUpdatesBase> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLChannelsEditAdmin {
                Channel = channel.ToInputChannel(), UserId = userId, AdminRights = rights
            };

            const string caption = "channels.editAdmin";

            SendInformativeMessage <TLUpdatesBase>(caption, obj,
                                                   result =>
            {
                var multiPts = result as ITLMultiPts;
                if (multiPts != null)
                {
                    _updatesService.SetState(multiPts, caption);
                }
                else
                {
                    ProcessUpdates(result, null);
                }

                GetFullChannelAsync(channel.ToInputChannel(),
                                    messagesChatFull => callback?.Invoke(result),
                                    faultCallback);
            },
                                                   faultCallback);
        }
Esempio n. 2
0
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            Item = null;

            var channel = parameter as TLChannel;
            var peer    = parameter as TLPeerChannel;

            if (peer != null)
            {
                channel = CacheService.GetChat(peer.ChannelId) as TLChannel;
            }

            if (channel != null)
            {
                Item     = channel;
                IsPublic = _item.HasUsername;

                var response = await ProtoService.CheckUsernameAsync(_item.ToInputChannel(), "username");

                if (response.IsSucceeded)
                {
                    HasTooMuchUsernames = false;
                }
                else
                {
                    if (response.Error.TypeEquals(TLErrorType.CHANNELS_ADMIN_PUBLIC_TOO_MUCH))
                    {
                        HasTooMuchUsernames = true;
                        LoadAdminedPublicChannels();
                    }
                }
            }
        }
Esempio n. 3
0
        public void KickFromChannelAsync(TLChannel channel, TLInputUserBase userId, TLBool kicked, Action <TLUpdatesBase> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLKickFromChannel {
                Channel = channel.ToInputChannel(), UserId = userId, Kicked = kicked
            };

            const string caption = "channels.kickFromChannel";

            SendInformativeMessage <TLUpdatesBase>(caption, obj,
                                                   result =>
            {
                var multiPts = result as IMultiPts;
                if (multiPts != null)
                {
                    _updatesService.SetState(multiPts, caption);
                }
                else
                {
                    ProcessUpdates(result, null);
                }

                GetFullChannelAsync(channel.ToInputChannel(),
                                    messagesChatFull => callback.SafeInvoke(result),
                                    faultCallback.SafeInvoke);
            },
                                                   faultCallback);
        }
Esempio n. 4
0
        private async void RevokeLinkExecute(TLChannel channel)
        {
            var dialog = new TLMessageDialog();

            dialog.Title               = Strings.Android.AppName;
            dialog.Message             = string.Format(Strings.Android.RevokeLinkAlert, channel.Username, channel.DisplayName);
            dialog.PrimaryButtonText   = Strings.Android.RevokeButton;
            dialog.SecondaryButtonText = Strings.Android.Cancel;

            var confirm = await dialog.ShowQueuedAsync();

            if (confirm == ContentDialogResult.Primary)
            {
                var response = await ProtoService.UpdateUsernameAsync(channel.ToInputChannel(), string.Empty);

                if (response.IsSucceeded)
                {
                    channel.HasUsername = false;
                    channel.Username    = null;
                    channel.RaisePropertyChanged(() => channel.HasUsername);
                    channel.RaisePropertyChanged(() => channel.Username);

                    HasTooMuchUsernames = false;
                    AdminedPublicChannels.Clear();
                }
            }
        }
        public void EditAboutAsync(TLChannel channel, TLString about, Action<TLBool> callback, Action<TLRPCError> faultCallback = null)
        {
            var obj = new TLEditAbout { Channel = channel.ToInputChannel(), About = about };

            const string caption = "channels.editAbout";
            SendInformativeMessage<TLBool>(caption, obj, callback.SafeInvoke, faultCallback);
        }
Esempio n. 6
0
        public void DeleteChannelAsync(TLChannel channel, Action <TLUpdatesBase> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLChannelsDeleteChannel {
                Channel = channel.ToInputChannel()
            };

            const string caption = "channels.deleteChannel";

            SendInformativeMessage <TLUpdatesBase>(caption, obj,
                                                   result =>
            {
                var multiPts = result as ITLMultiPts;
                if (multiPts != null)
                {
                    _updatesService.SetState(multiPts, caption);
                }
                else
                {
                    ProcessUpdates(result, null);
                }

                callback?.Invoke(result);
            },
                                                   faultCallback);
        }
        public void EditTitleAsync(TLChannel channel, string title, Action <TLUpdatesBase> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLChannelsEditTitle {
                Channel = channel.ToInputChannel(), Title = title
            };

            const string caption = "channels.editTitle";

            SendInformativeMessage <TLUpdatesBase>(caption, obj,
                                                   result =>
            {
                var multiPts = result as ITLMultiPts;
                if (multiPts != null)
                {
                    _updatesService.SetState(multiPts, caption);
                }
                else
                {
                    ProcessUpdates(result, null);
                }

                callback?.Invoke(result);
            },
                                                   faultCallback, flags: RequestFlag.InvokeAfter);
        }
Esempio n. 8
0
        public void EditPhotoAsync(TLChannel channel, TLInputChatPhotoBase photo, Action <TLUpdatesBase> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLChannelsEditPhoto {
                Channel = channel.ToInputChannel(), Photo = photo
            };

            const string caption = "channels.editPhoto";

            SendInformativeMessage <TLUpdatesBase>(caption, obj,
                                                   result =>
            {
                var multiPts = result as ITLMultiPts;
                if (multiPts != null)
                {
                    _updatesService.SetState(multiPts, caption);
                }
                else
                {
                    ProcessUpdates(result, null, true);
                }

                callback?.Invoke(result);
            },
                                                   faultCallback);
        }
Esempio n. 9
0
        public void DeleteUserHistoryAsync(TLChannel channel, TLInputUserBase userId, Action <TLMessagesAffectedHistory> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLChannelsDeleteUserHistory {
                Channel = channel.ToInputChannel(), UserId = userId
            };

            const string caption = "channels.deleteUserHistory";

            SendInformativeMessage <TLMessagesAffectedHistory>(caption, obj,
                                                               result =>
            {
                var multiChannelPts = result as ITLMultiChannelPts;
                if (multiChannelPts != null)
                {
                    if (channel.Pts == null || channel.Pts.Value + multiChannelPts.PtsCount != multiChannelPts.Pts)
                    {
                        Execute.ShowDebugMessage(string.Format("channel_id={0} channel_pts={1} affectedHistory24[channel_pts={2} channel_pts_count={3}]", channel.Id, channel.Pts, multiChannelPts.Pts, multiChannelPts.PtsCount));
                    }
                    channel.Pts = multiChannelPts.Pts;
                }

                callback?.Invoke(result);
            },
                                                               faultCallback);
        }
        public void EditAdminAsync(TLChannel channel, TLInputUserBase userId, TLChannelParticipantRoleBase role, Action <TLBool> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLEditAdmin {
                Channel = channel.ToInputChannel(), UserId = userId, Role = role
            };

            const string caption = "channels.editAdmin";

            SendInformativeMessage <TLBool>(caption, obj,
                                            result =>
            {
                if (result.Value)
                {
                    if (channel.AdminsCount != null)
                    {
                        if (role is TLChannelRoleEmpty)
                        {
                            channel.AdminsCount = new TLInt(channel.AdminsCount.Value - 1);
                        }
                        else
                        {
                            channel.AdminsCount = new TLInt(channel.AdminsCount.Value + 1);
                        }

                        _cacheService.Commit();
                    }
                }

                callback.SafeInvoke(result);
            },
                                            faultCallback);
        }
        public void KickFromChannelAsync(TLChannel channel, TLInputUserBase userId, TLBool kicked, Action <TLUpdatesBase> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLKickFromChannel {
                Channel = channel.ToInputChannel(), UserId = userId, Kicked = kicked
            };

            const string caption = "channels.kickFromChannel";

            SendInformativeMessage <TLUpdatesBase>(caption, obj,
                                                   result =>
            {
                if (channel.ParticipantsCount != null)
                {
                    channel.ParticipantsCount = new TLInt(channel.ParticipantsCount.Value - 1);
                }
                _cacheService.Commit();

                var multiPts = result as IMultiPts;
                if (multiPts != null)
                {
                    _updatesService.SetState(multiPts, caption);
                }
                else
                {
                    ProcessUpdates(result, null);
                }

                callback.SafeInvoke(result);
            },
                                                   faultCallback);
        }
Esempio n. 12
0
        private async void RevokeLinkExecute(TLChannel channel)
        {
            var dialog = new TLMessageDialog();

            dialog.Title               = "Revoke link";
            dialog.Message             = string.Format("Are you sure you want to revoke the link t.me/{0}?\r\n\r\nThe channel \"{1}\" will become private.", channel.Username, channel.DisplayName);
            dialog.PrimaryButtonText   = "Revoke";
            dialog.SecondaryButtonText = "Cancel";

            var confirm = await dialog.ShowAsync();

            if (confirm == ContentDialogResult.Primary)
            {
                var response = await ProtoService.UpdateUsernameAsync(channel.ToInputChannel(), string.Empty);

                if (response.IsSucceeded)
                {
                    channel.HasUsername = false;
                    channel.Username    = null;
                    channel.RaisePropertyChanged(() => channel.HasUsername);
                    channel.RaisePropertyChanged(() => channel.Username);

                    HasTooMuchUsernames = false;
                    AdminedPublicChannels.Clear();
                }
            }
        }
Esempio n. 13
0
        public void LeaveChannelAsync(TLChannel channel, Action <TLUpdatesBase> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLChannelsLeaveChannel {
                Channel = channel.ToInputChannel()
            };

            const string caption = "channels.leaveChannel";

            SendInformativeMessage <TLUpdatesBase>(caption, obj,
                                                   result =>
            {
                channel.IsLeft = true;
                if (channel.ParticipantsCount != null)
                {
                    channel.ParticipantsCount = new int?(channel.ParticipantsCount.Value - 1);
                }
                _cacheService.Commit();

                var multiPts = result as ITLMultiPts;
                if (multiPts != null)
                {
                    _updatesService.SetState(multiPts, caption);
                }
                else
                {
                    ProcessUpdates(result, null);
                }

                callback?.Invoke(result);
            },
                                                   faultCallback);
        }
Esempio n. 14
0
 public ItemsCollection(IMTProtoService protoService, ChannelAdminLogViewModel viewModel, TLChannel channel)
 {
     _protoService = protoService;
     _viewModel    = viewModel;
     _inputChannel = channel.ToInputChannel();
     _channel      = channel;
     //_filter = filter;
     _hasMore = true;
 }
Esempio n. 15
0
        public void EditAboutAsync(TLChannel channel, string about, Action <bool> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLChannelsEditAbout {
                Channel = channel.ToInputChannel(), About = about
            };

            const string caption = "channels.editAbout";

            SendInformativeMessage(caption, obj, callback, faultCallback, flags: RequestFlag.InvokeAfter);
        }
        private async void SendExecute()
        {
            if (_shortName != _selectedItem?.Set.ShortName && !string.IsNullOrWhiteSpace(_shortName))
            {
                var stickerSet = _stickersService.GetStickerSetByName(_shortName);
                if (stickerSet == null)
                {
                    var stickerResponse = await ProtoService.GetStickerSetAsync(new TLInputStickerSetShortName { ShortName = _shortName });

                    if (stickerResponse.IsSucceeded)
                    {
                        stickerSet = stickerResponse.Result;
                    }
                }

                if (stickerSet != null)
                {
                    SelectedItem = Items.FirstOrDefault(x => x.Set.Id == stickerSet.Set.Id) ?? stickerSet;
                }
                else
                {
                    // TODO
                    return;
                }
            }

            var set      = SelectedItem?.Set;
            var inputSet = set != null ? new TLInputStickerSetID {
                Id = set.Id, AccessHash = set.AccessHash
            } : (TLInputStickerSetBase) new TLInputStickerSetEmpty();

            var response = await ProtoService.SetStickersAsync(_item.ToInputChannel(), inputSet);

            if (response.IsSucceeded)
            {
                if (set != null)
                {
                    _stickersService.GetGroupStickerSetById(set);
                }

                Full.StickerSet    = set;
                Full.HasStickerSet = set != null;
                Full.RaisePropertyChanged(() => Full.StickerSet);
                Full.RaisePropertyChanged(() => Full.HasStickerSet);

                NavigationService.GoBack();
            }
            else
            {
                // TODO
            }
        }
        public void ReadHistoryAsync(TLChannel channel, TLInt maxId, Action<TLBool> callback, Action<TLRPCError> faultCallback = null)
        {
            var obj = new TLReadChannelHistory { Channel = channel.ToInputChannel(), MaxId = maxId };

            SendInformativeMessage<TLBool>("channels.readHistory", obj,
                result =>
                {
                    channel.ReadInboxMaxId = maxId;

                    _cacheService.Commit();

                    callback.SafeInvoke(result);
                },
                faultCallback);
        }
Esempio n. 18
0
        public void ReadHistoryAsync(TLChannel channel, TLInt maxId, Action <TLBool> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLReadChannelHistory {
                Channel = channel.ToInputChannel(), MaxId = maxId
            };

            ReadChannelHistoryAsyncInternal(obj,
                                            result =>
            {
                channel.ReadInboxMaxId = maxId;

                _cacheService.Commit();

                callback.SafeInvoke(result);
            },
                                            () => { },
                                            faultCallback.SafeInvoke);
        }
Esempio n. 19
0
        private async void ExportInvite()
        {
            var response = await ProtoService.ExportInviteAsync(_channel.ToInputChannel());

            if (response.IsSucceeded)
            {
                _exportedInvite = response.Result;

                var invite = response.Result as TLChatInviteExported;
                if (invite != null && !string.IsNullOrEmpty(invite.Link))
                {
                    InviteLink = invite.Link;
                }
            }
            else
            {
                Execute.ShowDebugMessage("channels.exportInvite error " + response.Error);
            }
        }
Esempio n. 20
0
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            _channel = (TLChannel)parameter;

            var response = await ProtoService.CheckUsernameAsync(_channel.ToInputChannel(), "username");

            if (response.IsSucceeded)
            {
                HasTooMuchUsernames = false;
            }
            else
            {
                if (response.Error.TypeEquals(TLErrorType.CHANNELS_ADMIN_PUBLIC_TOO_MUCH))
                {
                    HasTooMuchUsernames = true;
                    LoadAdminedPublicChannels();
                }
            }
        }
Esempio n. 21
0
        public void ReadHistoryAsync(TLChannel channel, int maxId, Action <bool> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLChannelsReadHistory {
                Channel = channel.ToInputChannel(), MaxId = maxId
            };

            const string caption = "channels.readHistory";

            SendInformativeMessage <bool>(caption, obj,
                                          result =>
            {
                channel.ReadInboxMaxId = maxId;

                _cacheService.Commit();

                callback?.Invoke(result);
            },
                                          faultCallback);
        }
Esempio n. 22
0
        private void UpdateChannelItems(TLChannel channel)
        {
            IsWorking = true;
            MTProtoService.GetParticipantsAsync(channel.ToInputChannel(), new TLChannelParticipantsRecent(), new TLInt(0), new TLInt(32),
                                                result => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;
                Items.Clear();
                foreach (var user in result.Users)
                {
                    Items.Add(user);
                }
                Status = Items.Count > 0 ? string.Empty : AppResources.NoUsersHere;
            }),
                                                error => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;
                Status    = string.Empty;

                Execute.ShowDebugMessage("channels.getParticipants error " + error);
            }));
        }
        public void Done()
        {
            if (_currentItem == null)
            {
                return;
            }

            if (IsWorking)
            {
                return;
            }

            var username = Username;

            if (username != null &&
                username.StartsWith("@"))
            {
                username = username.Substring(1, username.Length - 1);
            }

            IsWorking = true;
            MTProtoService.UpdateUsernameAsync(_currentItem.ToInputChannel(), new TLString(username),
                                               user => BeginOnUIThread(() =>
            {
                var userName = _currentItem as IUserName;
                if (userName != null)
                {
                    userName.UserName = new TLString(username);
                    CacheService.Commit();

                    EventAggregator.Publish(new ChannelNameChangedEventArgs(_currentItem));
                }

                IsWorking = false;
                NavigationService.GoBack();
            }),
                                               error => BeginOnUIThread(() =>
            {
                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: account.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))
                    {
                        HasError = false;
                        Error    = " ";
                        NavigationService.GoBack();
                    }
                    else if (TLRPCError.TypeEquals(error, ErrorType.CHANNELS_ADMIN_PUBLIC_TOO_MUCH))
                    {
                        var message = AppResources.ChannelsAdminPublicTooMuchShort;
                        HasError    = true;
                        Error       = message;
                        MessageBox.Show(message, AppResources.Error, MessageBoxButton.OK);
                    }
                    else if (TLRPCError.TypeEquals(error, ErrorType.USERNAME_INVALID))
                    {
                        var message = IsMegaGroup
                                ? AppResources.SupergroupNameInvalid
                                : AppResources.ChannelNameInvalid;
                        HasError = true;
                        Error    = message;
                        MessageBox.Show(message, AppResources.Error, MessageBoxButton.OK);
                    }
                    else if (TLRPCError.TypeEquals(error, ErrorType.USERNAME_OCCUPIED))
                    {
                        var message = IsMegaGroup
                                ? AppResources.SupergroupNameOccupied
                                : AppResources.ChannelNameOccupied;
                        HasError = true;
                        Error    = message;
                        MessageBox.Show(message, AppResources.Error, MessageBoxButton.OK);
                    }
                    else
                    {
                        HasError = true;
                        Error    = error.ToString();
                        //Execute.BeginOnUIThread(() => NavigationService.GoBack());
                    }
                }
                else
                {
                    HasError = true;
                    Error    = string.Empty;
                    Execute.ShowDebugMessage("channel.updateUsername error " + error);
                }

                IsWorking = false;
            }));
        }
Esempio n. 24
0
        public override void Create()
        {
            if (IsWorking)
            {
                return;
            }
            if (_newChannel == null)
            {
                return;
            }

            var participants = new TLVector <TLInputUserBase>();

            foreach (var item in SelectedUsers)
            {
                participants.Add(item.ToInputUser());
            }
            participants.Add(new TLInputUserContact {
                UserId = new TLInt(StateService.CurrentUserId)
            });

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

            _newChannel.ParticipantIds = new TLVector <TLInt> {
                Items = SelectedUsers.Select(x => x.Id).ToList()
            };

#if LAYER_40
            IsWorking = true;
            MTProtoService.InviteToChannelAsync(_newChannel.ToInputChannel(), participants,
                                                result => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;

                StateService.With = _newChannel;
                StateService.RemoveBackEntries = true;
                NavigationService.UriFor <DialogDetailsViewModel>().Navigate();
            }),
                                                error => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;
                Execute.ShowDebugMessage("channels.inviteToChannel error " + error);
            }));
#else
            CacheService.SyncBroadcast(_newChannel, result =>
            {
                var broadcastPeer = new TLPeerBroadcast {
                    Id = _newChannel.Id
                };
                var serviceMessage = new TLMessageService17
                {
                    FromId = new TLInt(StateService.CurrentUserId),
                    ToId   = broadcastPeer,
                    Status = MessageStatus.Confirmed,
                    Out    = TLBool.True,
                    Date   = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now),
                    //IsAnimated = true,
                    RandomId = TLLong.Random(),
                    Action   = new TLMessageActionChannelCreate
                    {
                        Title = _newChannel.Title,
                    }
                };
                serviceMessage.SetUnread(TLBool.False);

                CacheService.SyncMessage(serviceMessage, broadcastPeer,
                                         message =>
                {
                    if (_newChannel.Photo is TLChatPhoto)
                    {
                        var serviceMessage2 = new TLMessageService17
                        {
                            FromId = new TLInt(StateService.CurrentUserId),
                            ToId   = broadcastPeer,
                            Status = MessageStatus.Confirmed,
                            Out    = TLBool.True,
                            Date   = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now),
                            //IsAnimated = true,
                            RandomId = TLLong.Random(),
                            Action   = new TLMessageActionChatEditPhoto
                            {
                                Photo = _newChannel.Photo,
                            }
                        };
                        serviceMessage2.SetUnread(TLBool.False);

                        CacheService.SyncMessage(serviceMessage2, broadcastPeer, message2 =>
                        {
                            StateService.With = _newChannel;
                            StateService.RemoveBackEntries = true;
                            NavigationService.UriFor <DialogDetailsViewModel>().Navigate();
                        });
                        return;
                    }
                    StateService.With = _newChannel;
                    StateService.RemoveBackEntries = true;
                    NavigationService.UriFor <DialogDetailsViewModel>().Navigate();
                });
            });
#endif
        }
Esempio n. 25
0
        public override void Create()
        {
            if (IsWorking)
            {
                return;
            }
            if (_newChannel == null)
            {
                return;
            }

            var participants = new TLVector <TLInputUserBase>();

            foreach (var item in SelectedUsers)
            {
                participants.Add(item.ToInputUser());
            }
            participants.Add(new TLInputUser {
                UserId = new TLInt(StateService.CurrentUserId), AccessHash = new TLLong(0)
            });

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

            _newChannel.ParticipantIds = new TLVector <TLInt> {
                Items = SelectedUsers.Select(x => x.Id).ToList()
            };

            IsWorking = true;
            MTProtoService.InviteToChannelAsync(_newChannel.ToInputChannel(), participants,
                                                result => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;

                StateService.With = _newChannel;
                StateService.RemoveBackEntries = true;
                NavigationService.UriFor <DialogDetailsViewModel>().Navigate();
            }),
                                                error => Execute.BeginOnUIThread(() =>
            {
                if (error.TypeEquals(ErrorType.PEER_FLOOD))
                {
                    //MessageBox.Show(AppResources.PeerFloodAddContact, AppResources.Error, MessageBoxButton.OK);
                    ShellViewModel.ShowCustomMessageBox(AppResources.PeerFloodAddContact, AppResources.Error, AppResources.MoreInfo.ToLowerInvariant(), AppResources.Ok.ToLowerInvariant(),
                                                        result =>
                    {
                        if (result == CustomMessageBoxResult.RightButton)
                        {
                            TelegramViewBase.NavigateToUsername(MTProtoService, Constants.SpambotUsername, null, null, null);
                        }
                    });
                }
                else if (error.TypeEquals(ErrorType.USERS_TOO_MUCH))
                {
                    MessageBox.Show(AppResources.UsersTooMuch, AppResources.Error, MessageBoxButton.OK);
                }
                else if (error.TypeEquals(ErrorType.USER_CHANNELS_TOO_MUCH))
                {
                    MessageBox.Show(AppResources.UserChannelsTooMuch, AppResources.Error, MessageBoxButton.OK);
                }
                else if (error.TypeEquals(ErrorType.BOTS_TOO_MUCH))
                {
                    MessageBox.Show(AppResources.BotsTooMuch, AppResources.Error, MessageBoxButton.OK);
                }
                else if (error.TypeEquals(ErrorType.USER_NOT_MUTUAL_CONTACT))
                {
                    MessageBox.Show(AppResources.UserNotMutualContact, AppResources.Error, MessageBoxButton.OK);
                }

                IsWorking = false;
                Execute.ShowDebugMessage("channels.inviteToChannel error " + error);
            }));
        }
Esempio n. 26
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);
            }
        }
        public void Check()
        {
            var checkedUsername = UserName;

            var username = UserName;

            if (username != null &&
                username.StartsWith("@"))
            {
                username = username.Substring(1, username.Length - 1);
            }

            if (string.IsNullOrEmpty(username))
            {
                HasError            = false;
                IsUsernameAvailable = false;
                //Error = string.Empty;
                return;
            }

            var isValidSymbols = username.All(IsValidSymbol);

            if (!isValidSymbols)
            {
                HasError = true;
                Error    = AppResources.ChannelNameInvalid;
                return;
            }

            if (username[0] >= '0' && username[0] <= '9')
            {
                HasError = true;
                Error    = AppResources.ChannelNameStartsWithNumber;
                return;
            }

            if (username.Length < Constants.UsernameMinLength)
            {
                HasError = true;
                Error    = AppResources.ChannelNameShort;
                return;
            }

            HasError            = false;
            IsUsernameAvailable = false;

            MTProtoService.CheckUsernameAsync(_newChannel.ToInputChannel(), new TLString(username),
                                              result => BeginOnUIThread(() =>
            {
                HasError = !result.Value;
                if (HasError)
                {
                    Error = AppResources.ChannelNameOccupied;
                }

                if (string.Equals(checkedUsername, UserName) && result.Value)
                {
                    IsUsernameAvailable     = true;
                    UsernameAvailableString = string.Format(AppResources.NameIsAvailable, checkedUsername);
                }
            }),
                                              error => BeginOnUIThread(() =>
            {
                HasError = true;
                if (TLRPCError.CodeEquals(error, ErrorCode.FLOOD))
                {
                    Error = AppResources.FloodWaitString;
                }
                else if (TLRPCError.CodeEquals(error, ErrorCode.INTERNAL))
                {
                    var messageBuilder = new StringBuilder();
                    messageBuilder.AppendLine(AppResources.ServerErrorMessage);
                    messageBuilder.AppendLine();
                    messageBuilder.AppendLine("Method: channels.checkUsername");
                    messageBuilder.AppendLine("Result: " + error);

                    Error = AppResources.ServerError;
                }
                else if (TLRPCError.CodeEquals(error, ErrorCode.BAD_REQUEST))
                {
                    if (TLRPCError.TypeEquals(error, ErrorType.USERNAME_INVALID))
                    {
                        Error = AppResources.ChannelNameInvalid;
                    }
                    else if (TLRPCError.TypeEquals(error, ErrorType.USERNAME_OCCUPIED))
                    {
                        Error = AppResources.ChannelNameOccupied;
                    }
                    else if (TLRPCError.TypeEquals(error, ErrorType.CHANNELS_ADMIN_PUBLIC_TOO_MUCH))
                    {
                        MessageBox.Show(AppResources.ChannelsAdminPublicTooMuch, AppResources.Error, MessageBoxButton.OK);

                        Error            = AppResources.ChannelsAdminPublicTooMuchShort;
                        TooMuchUsernames = true;
                        GetAdminedPublichChannelsAsync();
                    }
                    else
                    {
                        Error = error.ToString();
                    }
                }
                else
                {
                    Error = string.Empty;
                    Execute.ShowDebugMessage("channels.checkUsername error " + error);
                }
            }));
        }