Ejemplo n.º 1
0
        public void SendBotInlineResult(TLBotInlineResultBase result)
        {
            var currentInlineBot = CurrentInlineBot;

            if (currentInlineBot == null)
            {
                return;
            }

            //var inlineBots = DialogDetailsViewModel.GetInlineBots();
            //if (!inlineBots.Contains(currentInlineBot))
            //{
            //    inlineBots.Insert(0, currentInlineBot);
            //    this._cachedUsernameResults.Clear();
            //}
            //else
            //{
            //    inlineBots.Remove(currentInlineBot);
            //    inlineBots.Insert(0, currentInlineBot);
            //    this._cachedUsernameResults.Clear();
            //}
            //DialogDetailsViewModel.SaveInlineBotsAsync();
            //if (_inlineBotResults == null)
            //{
            //    return;
            //}

            //TLLong arg_74_0 = this._currentInlineBotResults.QueryId;

            var date    = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);
            var message = TLUtils.GetMessage(SettingsHelper.UserId, Peer.ToPeer(), TLMessageState.Sending, true, true, date, string.Empty, new TLMessageMediaEmpty(), TLLong.Random(), null);

            if (message == null)
            {
                return;
            }

            ProcessBotInlineResult(ref message, result, currentInlineBot.Id);

            //if (this.Reply != null && DialogDetailsViewModel.IsWebPagePreview(this.Reply))
            //{
            //    message._media = ((TLMessagesContainter)this.Reply).WebPageMedia;
            //    this.Reply = this._previousReply;
            //}

            if (Reply != null)
            {
                message.HasReplyToMsgId = true;
                message.ReplyToMsgId    = Reply.Id;
                message.Reply           = Reply;
                Reply = null;
            }

            SetText(string.Empty);

            //this.Text = string.Empty;
            var previousMessage = InsertSendingMessage(message, false);
            //this.IsEmptyDialog = (base.Items.get_Count() == 0 && this.LazyItems.get_Count() == 0);
            var user = With as TLUser;

            if (user != null && user.IsBot && Messages.Count == 1)
            {
                RaisePropertyChanged(() => With);
            }

            CurrentInlineBot = null;
            InlineBotResults = null;

            Execute.BeginOnThreadPool(() =>
            {
                CacheService.SyncSendingMessage(message, previousMessage, async(m) =>
                {
                    var response = await ProtoService.SendInlineBotResultAsync(message, () =>
                    {
                        message.State = TLMessageState.Confirmed;
                    });
                    if (response.IsSucceeded)
                    {
                        message.RaisePropertyChanged(() => message.Media);
                    }
                });
            });

            //base.BeginOnUIThread(delegate
            //{
            //    this.ProcessScroll();
            //    this.RaiseStartGifPlayer(new StartGifPlayerEventArgs(message));
            //});
            //base.BeginOnUIThread(delegate
            //{
            //    this.ClearInlineBotResults();
            //    this.CurrentInlineBot = null;
            //    base.NotifyOfPropertyChange<string>(() => this.BotInlinePlaceholder);
            //});
            //this._debugNotifyOfPropertyChanged = false;
            //base.BeginOnThreadPool(delegate
            //{
            //    this.CacheService.SyncSendingMessage(message, previousMessage, delegate (TLMessageCommon m)
            //    {
            //        DialogDetailsViewModel.SendInternal(message, this.MTProtoService, delegate
            //        {
            //        }, delegate
            //        {
            //            this.Status = string.Empty;
            //        });
            //    });
            //});
        }
Ejemplo n.º 2
0
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            //if (mode == NavigationMode.New)
            //{
            //    _dialogs = null;
            //}

            var response = await ProtoService.SendAsync(new GetChats(new ChatListMain(), long.MaxValue, 0, int.MaxValue));

            if (response is Telegram.Td.Api.Chats chats)
            {
                var list = ProtoService.GetChats(chats.ChatIds);
                Items.Clear();

                if (_searchType == SearchChatsType.Post || _searchType == SearchChatsType.All)
                {
                    var myId = CacheService.Options.MyId;
                    var self = list.FirstOrDefault(x => x.Type is ChatTypePrivate privata && privata.UserId == myId);
                    if (self == null)
                    {
                        self = await ProtoService.SendAsync(new CreatePrivateChat(myId, false)) as Chat;
                    }

                    if (self != null)
                    {
                        list.Remove(self);
                        list.Insert(0, self);
                    }
                }

                foreach (var chat in list)
                {
                    if (_searchType == SearchChatsType.BasicAndSupergroups)
                    {
                        if (chat.Type is ChatTypeBasicGroup basic)
                        {
                            var basicGroup = ProtoService.GetBasicGroup(basic.BasicGroupId);
                            if (basicGroup == null)
                            {
                                continue;
                            }

                            if (basicGroup.CanInviteUsers())
                            {
                                Items.Add(chat);
                            }
                        }
                        else if (chat.Type is ChatTypeSupergroup super)
                        {
                            var supergroup = ProtoService.GetSupergroup(super.SupergroupId);
                            if (supergroup == null)
                            {
                                continue;
                            }

                            if (supergroup.CanInviteUsers())
                            {
                                Items.Add(chat);
                            }
                        }
                    }
                    else if (_searchType == SearchChatsType.PrivateAndGroups)
                    {
                        if (chat.Type is ChatTypePrivate || chat.Type is ChatTypeBasicGroup || chat.Type is ChatTypeSupergroup supergroup && !supergroup.IsChannel)
                        {
                            Items.Add(chat);
                        }
                    }
                    else if (_searchType == SearchChatsType.Private)
                    {
                        if (chat.Type is ChatTypePrivate)
                        {
                            Items.Add(chat);
                        }
                    }
                    else if (_searchType == SearchChatsType.Post)
                    {
                        if (CacheService.CanPostMessages(chat))
                        {
                            Items.Add(chat);
                        }
                    }
                    else
                    {
                        Items.Add(chat);
                    }
                }

                var pre = PreSelectedItems;
                if (pre == null)
                {
                    return;
                }

                var items         = Items;
                var selectedItems = SelectedItems;

                foreach (var id in pre)
                {
                    var chat = CacheService.GetChat(id);
                    if (chat == null)
                    {
                        chat = await ProtoService.SendAsync(new GetChat(id)) as Chat;
                    }

                    if (chat == null)
                    {
                        continue;
                    }

                    selectedItems.Add(chat);

                    var index = items.IndexOf(chat);
                    if (index > -1)
                    {
                        if (index > 0)
                        {
                            items.Remove(chat);
                            items.Insert(1, chat);
                        }
                    }
                    else
                    {
                        items.Insert(1, chat);
                    }
                }

                if (PreSelectedItems.Count > 0 && SelectionMode == ListViewSelectionMode.Multiple)
                {
                    RaisePropertyChanged(nameof(PreSelectedItems));
                }
            }
        }
        public bool CanBeDownloaded(MessageViewModel message)
        {
            var content = message.Content as object;

            if (content is MessageAnimation animationMessage)
            {
                content = animationMessage.Animation;
            }
            else if (content is MessageAudio audioMessage)
            {
                content = audioMessage.Audio;
            }
            else if (content is MessageDocument documentMessage)
            {
                content = documentMessage.Document;
            }
            else if (content is MessageGame gameMessage)
            {
                if (gameMessage.Game.Animation != null)
                {
                    content = gameMessage.Game.Animation;
                }
                else if (gameMessage.Game.Photo != null)
                {
                    content = gameMessage.Game.Photo;
                }
            }
            else if (content is MessageInvoice invoiceMessage)
            {
                content = invoiceMessage.Photo;
            }
            else if (content is MessageLocation locationMessage)
            {
                content = locationMessage.Location;
            }
            else if (content is MessagePhoto photoMessage)
            {
                content = photoMessage.Photo;
            }
            else if (content is MessageSticker stickerMessage)
            {
                content = stickerMessage.Sticker;
            }
            else if (content is MessageText textMessage)
            {
                if (textMessage?.WebPage?.Animation != null)
                {
                    content = textMessage?.WebPage?.Animation;
                }
                else if (textMessage?.WebPage?.Document != null)
                {
                    content = textMessage?.WebPage?.Document;
                }
                else if (textMessage?.WebPage?.Sticker != null)
                {
                    content = textMessage?.WebPage?.Sticker;
                }
                else if (textMessage?.WebPage?.Video != null)
                {
                    content = textMessage?.WebPage?.Video;
                }
                else if (textMessage?.WebPage?.VideoNote != null)
                {
                    content = textMessage?.WebPage?.VideoNote;
                }
                // PHOTO SHOULD ALWAYS BE AT THE END!
                else if (textMessage?.WebPage?.Photo != null)
                {
                    content = textMessage?.WebPage?.Photo;
                }
            }
            else if (content is MessageVideo videoMessage)
            {
                content = videoMessage.Video;
            }
            else if (content is MessageVideoNote videoNoteMessage)
            {
                content = videoNoteMessage.VideoNote;
            }
            else if (content is MessageVoiceNote voiceNoteMessage)
            {
                content = voiceNoteMessage.VoiceNote;
            }

            var file = message.GetFile();

            if (file != null && ProtoService.IsDownloadFileCanceled(file.Id))
            {
                return(false);
            }

            var chat = _chat;

            if (chat == null)
            {
                return(false);
            }

            if (content is Animation animation)
            {
                return(Settings.AutoDownload.ShouldDownloadVideo(GetChatType(chat), animation.AnimationValue.Size));
            }
            else if (content is Audio audio)
            {
                return(Settings.AutoDownload.ShouldDownloadDocument(GetChatType(chat), audio.AudioValue.Size));
            }
            else if (content is Document document)
            {
                return(Settings.AutoDownload.ShouldDownloadDocument(GetChatType(chat), document.DocumentValue.Size));
            }
            else if (content is Photo photo)
            {
                var big = photo.GetBig();
                if (big != null && ProtoService.IsDownloadFileCanceled(big.Photo.Id))
                {
                    return(false);
                }

                return(Settings.AutoDownload.ShouldDownloadPhoto(GetChatType(chat)));
            }
            else if (content is Sticker)
            {
                // Stickers aren't part of the deal
                return(true);
            }
            else if (content is Video video)
            {
                return(Settings.AutoDownload.ShouldDownloadVideo(GetChatType(chat), video.VideoValue.Size));
            }
            else if (content is VideoNote videoNote)
            {
                return(Settings.AutoDownload.ShouldDownloadDocument(GetChatType(chat), videoNote.Video.Size));
            }
            else if (content is VoiceNote)
            {
                return(!Settings.AutoDownload.Disabled);
            }

            return(false);
        }
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            state.TryGet("chatId", out long chatId);
            state.TryGet("userId", out int userId);

            Chat = ProtoService.GetChat(chatId);

            var chat = _chat;

            if (chat == null)
            {
                return;
            }

            var response = await ProtoService.SendAsync(new GetChatMember(chat.Id, userId));

            if (response is ChatMember member)
            {
                var item  = ProtoService.GetUser(member.UserId);
                var cache = ProtoService.GetUserFull(member.UserId);

                Delegate?.UpdateMember(chat, item, member);
                Delegate?.UpdateUser(chat, item, false);

                if (cache == null)
                {
                    ProtoService.Send(new GetUserFullInfo(member.UserId));
                }
                else
                {
                    Delegate?.UpdateUserFullInfo(chat, item, cache, false, false);
                }

                Member = member;

                if (member.Status is ChatMemberStatusAdministrator administrator)
                {
                    CanChangeInfo      = administrator.CanChangeInfo;
                    CanDeleteMessages  = administrator.CanDeleteMessages;
                    CanEditMessages    = administrator.CanEditMessages;
                    CanInviteUsers     = administrator.CanInviteUsers;
                    CanPinMessages     = administrator.CanPinMessages;
                    CanPostMessages    = administrator.CanPostMessages;
                    CanPromoteMembers  = administrator.CanPromoteMembers;
                    CanRestrictMembers = administrator.CanRestrictMembers;
                    IsAnonymous        = administrator.IsAnonymous;

                    CustomTitle = administrator.CustomTitle;
                }
                else
                {
                    CanChangeInfo      = true;
                    CanDeleteMessages  = true;
                    CanEditMessages    = true;
                    CanInviteUsers     = true;
                    CanPinMessages     = true;
                    CanPostMessages    = true;
                    CanPromoteMembers  = member.Status is ChatMemberStatusCreator;
                    CanRestrictMembers = true;

                    if (member.Status is ChatMemberStatusCreator creator)
                    {
                        IsAnonymous = creator.IsAnonymous;

                        CustomTitle = creator.CustomTitle;
                    }
                    else
                    {
                        IsAnonymous = false;

                        CustomTitle = string.Empty;
                    }
                }
            }
        }
Ejemplo n.º 5
0
        private async void SendExecute()
        {
            if (_codeInfo == null)
            {
                //...
                return;
            }

            if (string.IsNullOrEmpty(_phoneCode))
            {
                RaisePropertyChanged("SENT_CODE_INVALID");
                return;
            }

            IsLoading = true;


            //CheckChangePhoneNumberCode
            var response = await ProtoService.SendAsync(new CheckChangePhoneNumberCode(_phoneCode));

            if (response is Ok)
            {
                while (NavigationService.Frame.BackStackDepth > 1)
                {
                    NavigationService.Frame.BackStack.RemoveAt(1);
                }

                NavigationService.GoBack();
            }
            else if (response is Error error)
            {
                IsLoading = false;

                if (error.TypeEquals(ErrorType.PHONE_NUMBER_OCCUPIED))
                {
                    //await new MessageDialog(Resources.PhoneCodeInvalidString, Resources.Error).ShowAsync();
                }
                else if (error.TypeEquals(ErrorType.PHONE_CODE_INVALID))
                {
                    //await new MessageDialog(Resources.PhoneCodeInvalidString, Resources.Error).ShowAsync();
                }
                else if (error.TypeEquals(ErrorType.PHONE_CODE_EMPTY))
                {
                    //await new MessageDialog(Resources.PhoneCodeEmpty, Resources.Error).ShowAsync();
                }
                else if (error.TypeEquals(ErrorType.PHONE_CODE_EXPIRED))
                {
                    //await new MessageDialog(Resources.PhoneCodeExpiredString, Resources.Error).ShowAsync();
                }
                else if (error.TypeEquals(ErrorType.SESSION_PASSWORD_NEEDED))
                {
                    ////this.IsWorking = true;
                    //var password = await LegacyService.GetPasswordAsync();
                    //if (password.IsSucceeded && password.Result is TLAccountPassword)
                    //{
                    //    var state = new SignInPasswordPage.NavigationParameters
                    //    {
                    //        PhoneNumber = _phoneNumber,
                    //        PhoneCode = _phoneCode,
                    //        //Result = _sentCode,
                    //        //Password = password.Result as TLAccountPassword
                    //    };

                    //    NavigationService.Navigate(typeof(SignInPasswordPage), state);
                    //}
                    //else
                    //{
                    //    Execute.ShowDebugMessage("account.getPassword error " + password.Error);
                    //}
                }
                else if (error.CodeEquals(ErrorCode.FLOOD))
                {
                    //await new MessageDialog($"{Resources.FloodWaitString}\r\n\r\n({error.Message})", Resources.Error).ShowAsync();
                }

                Execute.ShowDebugMessage("account.signIn error " + error);
            }
        }
Ejemplo n.º 6
0
 private void AnimationDeleteExecute(Animation animation)
 {
     ProtoService.Send(new RemoveSavedAnimation(new InputFileId(animation.AnimationValue.Id)));
 }
Ejemplo n.º 7
0
 private void StickerUnfaveExecute(Sticker sticker)
 {
     ProtoService.Send(new RemoveFavoriteSticker(new InputFileId(sticker.StickerValue.Id)));
 }
Ejemplo n.º 8
0
        private async void MessagesDelete(Chat chat, IList <Message> messages)
        {
            var first = messages.FirstOrDefault();

            if (first == null)
            {
                return;
            }

            var response = await ProtoService.SendAsync(new GetMessages(chat.Id, messages.Select(x => x.Id).ToArray()));

            if (response is Messages updated)
            {
                for (int i = 0; i < updated.MessagesValue.Count; i++)
                {
                    if (updated.MessagesValue[i] != null)
                    {
                        messages[i] = updated.MessagesValue[i];
                    }
                    else
                    {
                        messages.RemoveAt(i);
                        updated.MessagesValue.RemoveAt(i);

                        i--;
                    }
                }
            }

            var firstSender = first.Sender as MessageSenderUser;

            var sameUser = firstSender != null && messages.All(x => x.Sender is MessageSenderUser senderUser && senderUser.UserId == firstSender.UserId);
            var dialog   = new DeleteMessagesPopup(CacheService, messages.Where(x => x != null).ToArray());

            var confirm = await dialog.ShowQueuedAsync();

            if (confirm != ContentDialogResult.Primary)
            {
                return;
            }

            SelectionMode = ListViewSelectionMode.None;

            if (dialog.DeleteAll && sameUser)
            {
                ProtoService.Send(new DeleteChatMessagesFromUser(chat.Id, firstSender.UserId));
            }
            else
            {
                ProtoService.Send(new DeleteMessages(chat.Id, messages.Select(x => x.Id).ToList(), dialog.Revoke));
            }

            if (dialog.BanUser && sameUser)
            {
                ProtoService.Send(new SetChatMemberStatus(chat.Id, firstSender.UserId, new ChatMemberStatusBanned()));
            }

            if (dialog.ReportSpam && sameUser && chat.Type is ChatTypeSupergroup supertype)
            {
                ProtoService.Send(new ReportSupergroupSpam(supertype.SupergroupId, firstSender.UserId, messages.Select(x => x.Id).ToList()));
            }
        }
Ejemplo n.º 9
0
        private void SendExecute()
        {
            var dialogs = SelectedItems.ToList();

            if (dialogs.Count == 0)
            {
                return;
            }

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            if (_message != null)
            {
                foreach (var dialog in dialogs)
                {
                    TLInputPeerBase toPeer     = dialog.ToInputPeer();
                    TLInputPeerBase fromPeer   = null;
                    var             fwdMessage = _message;

                    var msgs   = new TLVector <TLMessage>();
                    var msgIds = new TLVector <int>();

                    var clone = fwdMessage.Clone();
                    clone.Id = 0;
                    clone.HasReplyToMsgId = false;
                    clone.ReplyToMsgId    = null;
                    clone.HasReplyMarkup  = false;
                    clone.ReplyMarkup     = null;
                    clone.Date            = date;
                    clone.ToId            = dialog.Peer;
                    clone.RandomId        = TLLong.Random();
                    clone.IsOut           = true;
                    clone.IsPost          = false;
                    clone.FromId          = SettingsHelper.UserId;
                    clone.IsMediaUnread   = dialog.Peer is TLPeerChannel ? true : false;
                    clone.IsUnread        = true;
                    clone.State           = TLMessageState.Sending;

                    if (clone.Media == null)
                    {
                        clone.HasMedia = true;
                        clone.Media    = new TLMessageMediaEmpty();
                    }

                    if (fwdMessage.Parent is TLChannel channel)
                    {
                        if (channel.IsBroadcast)
                        {
                            if (!channel.IsSignatures)
                            {
                                clone.HasFromId = false;
                                clone.FromId    = null;
                            }

                            // TODO
                            //if (IsSilent)
                            //{
                            //    clone.IsSilent = true;
                            //}

                            clone.HasViews = true;
                            clone.Views    = 1;
                        }
                    }

                    if (clone.Media is TLMessageMediaGame gameMedia)
                    {
                        clone.HasEntities = false;
                        clone.Entities    = null;
                        clone.Message     = null;
                    }

                    if (fromPeer == null)
                    {
                        fromPeer = fwdMessage.Parent.ToInputPeer();
                    }

                    if (clone.FwdFrom == null && !clone.IsGame())
                    {
                        if (fwdMessage.ToId is TLPeerChannel)
                        {
                            var fwdChannel = CacheService.GetChat(fwdMessage.ToId.Id) as TLChannel;
                            if (fwdChannel != null && fwdChannel.IsMegaGroup)
                            {
                                clone.HasFwdFrom = true;
                                clone.FwdFrom    = new TLMessageFwdHeader
                                {
                                    HasFromId = true,
                                    FromId    = fwdMessage.FromId,
                                    Date      = fwdMessage.Date
                                };
                            }
                            else
                            {
                                clone.HasFwdFrom = true;
                                clone.FwdFrom    = new TLMessageFwdHeader
                                {
                                    HasFromId = fwdMessage.HasFromId,
                                    FromId    = fwdMessage.FromId,
                                    Date      = fwdMessage.Date
                                };

                                if (fwdChannel.IsBroadcast)
                                {
                                    clone.FwdFrom.HasChannelId = clone.FwdFrom.HasChannelPost = true;
                                    clone.FwdFrom.ChannelId    = fwdChannel.Id;
                                    clone.FwdFrom.ChannelPost  = fwdMessage.Id;
                                }
                            }
                        }
                        else if (fwdMessage.FromId == SettingsHelper.UserId && fwdMessage.ToId is TLPeerUser peerUser && peerUser.UserId == SettingsHelper.UserId)
                        {
                        }
                        else
                        {
                            clone.HasFwdFrom = true;
                            clone.FwdFrom    = new TLMessageFwdHeader
                            {
                                HasFromId = true,
                                FromId    = fwdMessage.FromId,
                                Date      = fwdMessage.Date
                            };
                        }
                    }

                    msgs.Add(clone);
                    msgIds.Add(fwdMessage.Id);

                    CacheService.SyncSendingMessage(clone, null, async(m) =>
                    {
                        var response = await ProtoService.ForwardMessagesAsync(toPeer, fromPeer, msgIds, msgs, IsWithMyScore);
                        if (response.IsSucceeded)
                        {
                            Aggregator.Publish(m);
                        }
                    });
                }

                NavigationService.GoBack();
            }
Ejemplo n.º 10
0
        public override Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            ProtoService.Send(new GetInstalledStickerSets(false), result =>
            {
                if (result is StickerSets sets)
                {
                    BeginOnUIThread(() => Items.ReplaceWith(sets.Sets));
                }
            });

            var chatId = (long)parameter;

            Chat = ProtoService.GetChat(chatId);

            var chat = _chat;

            if (chat == null)
            {
                return(Task.CompletedTask);
            }

            Aggregator.Subscribe(this);
            //Delegate?.UpdateChat(chat);

            if (chat.Type is ChatTypeSupergroup super)
            {
                var item  = ProtoService.GetSupergroup(super.SupergroupId);
                var cache = ProtoService.GetSupergroupFull(super.SupergroupId);

                //Delegate?.UpdateSupergroup(chat, item);

                if (cache == null)
                {
                    ProtoService.Send(new GetSupergroupFullInfo(super.SupergroupId));
                }
                else
                {
                    UpdateSupergroupFullInfo(chat, item, cache);
                }
            }

            return(Task.CompletedTask);

            //Item = null;
            //Full = null;
            //SelectedItem = 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;

            //    var full = CacheService.GetFullChat(channel.Id) as TLChannelFull;
            //    if (full == null)
            //    {
            //        var response = await LegacyService.GetFullChannelAsync(channel.ToInputChannel());
            //        if (response.IsSucceeded)
            //        {
            //            full = response.Result.FullChat as TLChannelFull;
            //        }
            //    }

            //    if (full != null)
            //    {
            //        Full = full;
            //        SelectedItem = _stickersService.GetGroupStickerSetById(full.StickerSet);
            //    }
            //}
        }
Ejemplo n.º 11
0
        private async void SendExecute()
        {
            if (_shortName != _selectedItem?.Name)
            {
            }

            var chat = _chat;

            if (chat == null)
            {
                return;
            }

            if (chat.Type is ChatTypeSupergroup supergroup)
            {
                var response = await ProtoService.SendAsync(new SetSupergroupStickerSet(supergroup.SupergroupId, 0));
            }


            //if (_shortName != _selectedItem?.Set.ShortName && !string.IsNullOrWhiteSpace(_shortName))
            //{
            //    var stickerSet = _stickersService.GetStickerSetByName(_shortName);
            //    if (stickerSet == null)
            //    {
            //        var stickerResponse = await LegacyService.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 LegacyService.SetStickersAsync(_item.ToInputChannel(), inputSet);
            //if (response.IsSucceeded)
            //{
            //    if (set != null)
            //    {
            //        _stickersService.GetGroupStickerSetById(set);
            //    }

            //    Full.StickerSet = set;
            //    Full.HasStickerSet = set != null;

            //    NavigationService.GoBack();
            //}
            //else
            //{
            //    // TODO
            //}
        }
Ejemplo n.º 12
0
        private async void SendExecute()
        {
            IsLoading = true;

            var save = _isSave ?? false;
            var info = new OrderInfo();

            if (_paymentForm.Invoice.NeedName)
            {
                info.Name = _info.Name;
            }
            if (_paymentForm.Invoice.NeedEmailAddress)
            {
                info.EmailAddress = _info.EmailAddress;
            }
            if (_paymentForm.Invoice.NeedPhoneNumber)
            {
                info.PhoneNumber = _info.PhoneNumber;
            }
            if (_paymentForm.Invoice.NeedShippingAddress)
            {
                info.ShippingAddress             = _info.ShippingAddress;
                info.ShippingAddress.CountryCode = _selectedCountry?.Code?.ToUpper();
            }

            var response = await ProtoService.SendAsync(new ValidateOrderInfo(0, 0, info, save));

            if (response is ValidatedOrderInfo validated)
            {
                IsLoading = false;

                if (_paymentForm.SavedOrderInfo != null && !save)
                {
                    ProtoService.Send(new DeleteSavedOrderInfo());
                }

                if (_paymentForm.Invoice.IsFlexible)
                {
                    //NavigationService.NavigateToPaymentFormStep2(_message, _paymentForm, info, response.Result);
                }
                else if (_paymentForm.SavedCredentials != null)
                {
                    //if (ApplicationSettings.Current.TmpPassword != null)
                    //{
                    //    if (ApplicationSettings.Current.TmpPassword.ValidUntil < TLUtils.Now + 60)
                    //    {
                    //        ApplicationSettings.Current.TmpPassword = null;
                    //    }
                    //}

                    //if (ApplicationSettings.Current.TmpPassword != null)
                    //{
                    //    NavigationService.NavigateToPaymentFormStep5(_message, _paymentForm, info, response.Result, null, null, null, true);
                    //}
                    //else
                    //{
                    //    NavigationService.NavigateToPaymentFormStep4(_message, _paymentForm, info, response.Result, null);
                    //}
                }
                else
                {
                    //NavigationService.NavigateToPaymentFormStep3(_message, _paymentForm, info, response.Result, null);
                }
            }
            else if (response is Error error)
            {
                IsLoading = false;

                switch (error.Message)
                {
                case "REQ_INFO_NAME_INVALID":
                case "REQ_INFO_PHONE_INVALID":
                case "REQ_INFO_EMAIL_INVALID":
                case "ADDRESS_COUNTRY_INVALID":
                case "ADDRESS_CITY_INVALID":
                case "ADDRESS_POSTCODE_INVALID":
                case "ADDRESS_STATE_INVALID":
                case "ADDRESS_STREET_LINE1_INVALID":
                case "ADDRESS_STREET_LINE2_INVALID":
                    RaisePropertyChanged(error.Message);
                    break;

                default:
                    //AlertsCreator.processError(error, PaymentFormActivity.this, req);
                    break;
                }
            }
        }
Ejemplo n.º 13
0
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            ChatFilter filter = null;

            if (parameter is int id)
            {
                var response = await ProtoService.SendAsync(new GetChatFilter(id));

                if (response is ChatFilter result)
                {
                    Id     = id;
                    Filter = result;
                    filter = result;
                }
                else
                {
                    // TODO
                }
            }
            else
            {
                Id     = null;
                Filter = null;
                filter = new ChatFilter();
                filter.PinnedChatIds   = new List <long>();
                filter.IncludedChatIds = new List <long>();
                filter.ExcludedChatIds = new List <long>();
            }

            if (filter == null)
            {
                return;
            }

            if (state != null && state.TryGet("included_chat_id", out long includedChatId))
            {
                filter.IncludedChatIds.Add(includedChatId);
            }

            _pinnedChatIds = filter.PinnedChatIds;

            _iconPicked = !string.IsNullOrEmpty(filter.IconName);

            Title = filter.Title;
            Icon  = Icons.ParseFilter(filter);

            Include.Clear();
            Exclude.Clear();

            if (filter.IncludeContacts)
            {
                Include.Add(new FilterFlag {
                    Flag = ChatListFilterFlags.IncludeContacts
                });
            }
            if (filter.IncludeNonContacts)
            {
                Include.Add(new FilterFlag {
                    Flag = ChatListFilterFlags.IncludeNonContacts
                });
            }
            if (filter.IncludeGroups)
            {
                Include.Add(new FilterFlag {
                    Flag = ChatListFilterFlags.IncludeGroups
                });
            }
            if (filter.IncludeChannels)
            {
                Include.Add(new FilterFlag {
                    Flag = ChatListFilterFlags.IncludeChannels
                });
            }
            if (filter.IncludeBots)
            {
                Include.Add(new FilterFlag {
                    Flag = ChatListFilterFlags.IncludeBots
                });
            }

            if (filter.ExcludeMuted)
            {
                Exclude.Add(new FilterFlag {
                    Flag = ChatListFilterFlags.ExcludeMuted
                });
            }
            if (filter.ExcludeRead)
            {
                Exclude.Add(new FilterFlag {
                    Flag = ChatListFilterFlags.ExcludeRead
                });
            }
            if (filter.ExcludeArchived)
            {
                Exclude.Add(new FilterFlag {
                    Flag = ChatListFilterFlags.ExcludeArchived
                });
            }

            foreach (var chatId in filter.PinnedChatIds.Union(filter.IncludedChatIds))
            {
                var chat = CacheService.GetChat(chatId);
                if (chat == null)
                {
                    continue;
                }

                Include.Add(new FilterChat {
                    Chat = chat
                });
            }

            foreach (var chatId in filter.ExcludedChatIds)
            {
                var chat = CacheService.GetChat(chatId);
                if (chat == null)
                {
                    continue;
                }

                Exclude.Add(new FilterChat {
                    Chat = chat
                });
            }

            UpdateIcon();
        }
Ejemplo n.º 14
0
        public override Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            var chatId = (long)parameter;

            Chat = ProtoService.GetChat(chatId);

            var chat = _chat;

            if (chat == null)
            {
                return(Task.CompletedTask);
            }

            Aggregator.Subscribe(this);
            Delegate?.UpdateChat(chat);

            if (chat.Type is ChatTypePrivate privata)
            {
                var item  = ProtoService.GetUser(privata.UserId);
                var cache = ProtoService.GetUserFull(privata.UserId);

                Delegate?.UpdateUser(chat, item, false);

                if (cache == null)
                {
                    ProtoService.Send(new GetUserFullInfo(privata.UserId));
                }
                else
                {
                    Delegate?.UpdateUserFullInfo(chat, item, cache, false);
                }
            }
            else if (chat.Type is ChatTypeSecret secretType)
            {
                var secret = ProtoService.GetSecretChat(secretType.SecretChatId);
                var item   = ProtoService.GetUser(secretType.UserId);
                var cache  = ProtoService.GetUserFull(secretType.UserId);

                Delegate?.UpdateSecretChat(chat, secret);
                Delegate?.UpdateUser(chat, item, true);

                if (cache == null)
                {
                    ProtoService.Send(new GetUserFullInfo(secret.UserId));
                }
                else
                {
                    Delegate?.UpdateUserFullInfo(chat, item, cache, true);
                }
            }
            else if (chat.Type is ChatTypeBasicGroup basic)
            {
                var item  = ProtoService.GetBasicGroup(basic.BasicGroupId);
                var cache = ProtoService.GetBasicGroupFull(basic.BasicGroupId);

                Delegate?.UpdateBasicGroup(chat, item);

                if (cache == null)
                {
                    ProtoService.Send(new GetBasicGroupFullInfo(basic.BasicGroupId));
                }
                else
                {
                    Delegate?.UpdateBasicGroupFullInfo(chat, item, cache);
                }
            }
            else if (chat.Type is ChatTypeSupergroup super)
            {
                var item  = ProtoService.GetSupergroup(super.SupergroupId);
                var cache = ProtoService.GetSupergroupFull(super.SupergroupId);

                Delegate?.UpdateSupergroup(chat, item);

                if (cache == null)
                {
                    ProtoService.Send(new GetSupergroupFullInfo(super.SupergroupId));
                }
                else
                {
                    Delegate?.UpdateSupergroupFullInfo(chat, item, cache);
                }
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 15
0
        public async void Handle(TLUpdatePhoneCall update)
        {
            await VoIPConnection.Current.SendUpdateAsync(update);

            await Task.Delay(2000);

            //if (update.PhoneCall is TLPhoneCallDiscarded discarded)
            //{
            //    if (discarded.IsNeedRating)
            //    {
            //        Debugger.Break();
            //    }

            //    if (discarded.IsNeedDebug)
            //    {
            //        Debugger.Break();
            //    }
            //}

            return;

            if (update.PhoneCall is TLPhoneCallRequested callRequested)
            {
                var reqReceived = new TLPhoneReceivedCall();
                reqReceived.Peer            = new TLInputPhoneCall();
                reqReceived.Peer.Id         = callRequested.Id;
                reqReceived.Peer.AccessHash = callRequested.AccessHash;

                ProtoService.SendRequestAsync <bool>("phone.receivedCall", reqReceived, null, null);

                var user = CacheService.GetUser(callRequested.AdminId) as TLUser;

                Execute.BeginOnUIThread(async() =>
                {
                    var dialog = await TLMessageDialog.ShowAsync(user.DisplayName, "CAAAALLL", "OK", "Cancel");
                    if (dialog == Windows.UI.Xaml.Controls.ContentDialogResult.Primary)
                    {
                        var config = await ProtoService.GetDHConfigAsync(0, 256);
                        if (config.IsSucceeded)
                        {
                            var dh = config.Result;
                            if (!TLUtils.CheckPrime(dh.P, dh.G))
                            {
                                return;
                            }

                            secretP = dh.P;

                            var salt         = new byte[256];
                            var secureRandom = new SecureRandom();
                            secureRandom.NextBytes(salt);

                            a_or_b = salt;

                            var g_b = MTProtoService.GetGB(salt, dh.G, dh.P);

                            var request = new TLPhoneAcceptCall
                            {
                                GB   = g_b,
                                Peer = new TLInputPhoneCall
                                {
                                    Id         = callRequested.Id,
                                    AccessHash = callRequested.AccessHash
                                },
                                Protocol = new TLPhoneCallProtocol
                                {
                                    IsUdpP2p       = true,
                                    IsUdpReflector = true,
                                    MinLayer       = 65,
                                    MaxLayer       = 65,
                                }
                            };

                            var response = await ProtoService.SendRequestAsync <TLPhonePhoneCall>("phone.acceptCall", request);
                            if (response.IsSucceeded)
                            {
                            }
                        }
                    }
                    else
                    {
                        var req             = new TLPhoneDiscardCall();
                        req.Peer            = new TLInputPhoneCall();
                        req.Peer.Id         = callRequested.Id;
                        req.Peer.AccessHash = callRequested.AccessHash;
                        req.Reason          = new TLPhoneCallDiscardReasonHangup();

                        ProtoService.SendRequestAsync <TLPhonePhoneCall>("phone.acceptCall", req, null, null);
                    }
                });
            }
            else if (update.PhoneCall is TLPhoneCall call)
            {
                var auth_key = computeAuthKey(call);
                var g_a      = call.GAOrB;

                var buffer = TLUtils.Combine(auth_key, g_a);
                var sha256 = Utils.ComputeSHA256(buffer);

                var emoji = EncryptionKeyEmojifier.EmojifyForCall(sha256);

                var user = CacheService.GetUser(call.AdminId) as TLUser;

                Execute.BeginOnUIThread(async() =>
                {
                    var dialog = await TLMessageDialog.ShowAsync(user.DisplayName, string.Join(" ", emoji), "OK");
                });
            }
        }
Ejemplo n.º 16
0
        private async Task <string> GetSubtitle()
        {
            if (With is TLUser user)
            {
                return(LastSeenConverter.GetLabel(user, true));
            }
            else if (With is TLChannel channel && channel.HasAccessHash && channel.AccessHash.HasValue)
            {
                var full = Full as TLChannelFull;
                if (full == null)
                {
                    full = CacheService.GetFullChat(channel.Id) as TLChannelFull;
                }

                if (full == null)
                {
                    var response = await ProtoService.GetFullChannelAsync(new TLInputChannel { ChannelId = channel.Id, AccessHash = channel.AccessHash.Value });

                    if (response.IsSucceeded)
                    {
                        full = response.Result.FullChat as TLChannelFull;
                    }
                }

                if (full == null)
                {
                    return(string.Empty);
                }

                if (channel.IsBroadcast && full.HasParticipantsCount)
                {
                    return(string.Format("{0} members", full.ParticipantsCount ?? 0));
                }
                else if (full.HasParticipantsCount)
                {
                    var config = CacheService.GetConfig();
                    if (config == null)
                    {
                        return(string.Format("{0} members", full.ParticipantsCount ?? 0));
                    }

                    var participants = await ProtoService.GetParticipantsAsync(channel.ToInputChannel(), new TLChannelParticipantsRecent(), 0, config.ChatSizeMax);

                    if (participants.IsSucceeded)
                    {
                        full.Participants = participants.Result;

                        if (full.ParticipantsCount <= config.ChatSizeMax)
                        {
                            var count = 0;
                            foreach (var item in participants.Result.Users.OfType <TLUser>())
                            {
                                if (item.HasStatus && item.Status is TLUserStatusOnline)
                                {
                                    count++;
                                }
                            }

                            if (count > 1)
                            {
                                return(string.Format("{0} members, {1} online", full.ParticipantsCount ?? 0, count));
                            }
                        }
                    }

                    return(string.Format("{0} members", full.ParticipantsCount ?? 0));
                }
            }
Ejemplo n.º 17
0
 public void Handle(UpdatingEventArgs e)
 {
     ProtoService.SetMessageOnTime(5, "Updating...");
 }
        private async Task SendThumbnailFileAsync(StorageFile file, TLFileLocation fileLocation, string fileName, BasicProperties basicProps, TLPhotoSize thumbnail, StorageFile fileCache, string caption)
        {
            var desiredName = string.Format("{0}_{1}_{2}.jpg", thumbnail.Location.VolumeId, thumbnail.Location.LocalId, thumbnail.Location.Secret);

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            var document = new TLDocument
            {
                Id         = 0,
                AccessHash = 0,
                Date       = date,
                Size       = (int)basicProps.Size,
                MimeType   = fileCache.ContentType,
                Thumb      = thumbnail,
                Attributes = new TLVector <TLDocumentAttributeBase>
                {
                    new TLDocumentAttributeFilename
                    {
                        FileName = file.Name
                    }
                }
            };

            var media = new TLMessageMediaDocument
            {
                Document = document,
                Caption  = caption
            };

            var message = TLUtils.GetMessage(SettingsHelper.UserId, Peer.ToPeer(), TLMessageState.Sending, true, true, date, string.Empty, media, TLLong.Random(), null);

            if (Reply != null)
            {
                message.HasReplyToMsgId = true;
                message.ReplyToMsgId    = Reply.Id;
                message.Reply           = Reply;
                Reply = null;
            }

            var previousMessage = InsertSendingMessage(message);

            CacheService.SyncSendingMessage(message, previousMessage, async(m) =>
            {
                var fileId = TLLong.Random();
                var upload = await _uploadDocumentManager.UploadFileAsync(fileId, fileCache.Name, false).AsTask(Upload(media.Document as TLDocument, progress => new TLSendMessageUploadDocumentAction {
                    Progress = progress
                }));
                if (upload != null)
                {
                    var thumbFileId = TLLong.Random();
                    var thumbUpload = await _uploadDocumentManager.UploadFileAsync(thumbFileId, desiredName);
                    if (thumbUpload != null)
                    {
                        var inputMedia = new TLInputMediaUploadedThumbDocument
                        {
                            File       = upload.ToInputFile(),
                            Thumb      = thumbUpload.ToInputFile(),
                            MimeType   = document.MimeType,
                            Caption    = media.Caption,
                            Attributes = document.Attributes
                        };

                        var result = await ProtoService.SendMediaAsync(Peer, inputMedia, message);
                    }
                    //if (result.IsSucceeded)
                    //{
                    //    var update = result.Result as TLUpdates;
                    //    if (update != null)
                    //    {
                    //        var newMessage = update.Updates.OfType<TLUpdateNewMessage>().FirstOrDefault();
                    //        if (newMessage != null)
                    //        {
                    //            var newM = newMessage.Message as TLMessage;
                    //            if (newM != null)
                    //            {
                    //                message.Media = newM.Media;
                    //                message.RaisePropertyChanged(() => message.Media);
                    //            }
                    //        }
                    //    }
                    //}
                }
            });
        }
Ejemplo n.º 19
0
 private void AnimationSaveExecute(Animation animation)
 {
     ProtoService.Send(new AddSavedAnimation(new InputFileId(animation.AnimationValue.Id)));
 }
        public async Task SendVideoAsync(StorageFile file, string caption, bool round, VideoTransformEffectDefinition transform = null, MediaEncodingProfile profile = null)
        {
            var fileLocation = new TLFileLocation
            {
                VolumeId = TLLong.Random(),
                LocalId  = TLInt.Random(),
                Secret   = TLLong.Random(),
                DCId     = 0
            };

            var fileName  = string.Format("{0}_{1}_{2}.mp4", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var fileCache = await FileUtils.CreateTempFileAsync(fileName);

            await file.CopyAndReplaceAsync(fileCache);

            var basicProps = await fileCache.GetBasicPropertiesAsync();

            var videoProps = await fileCache.Properties.GetVideoPropertiesAsync();

            var thumbnailBase = await FileUtils.GetFileThumbnailAsync(file);

            var thumbnail = thumbnailBase as TLPhotoSize;

            var desiredName = string.Format("{0}_{1}_{2}.jpg", thumbnail.Location.VolumeId, thumbnail.Location.LocalId, thumbnail.Location.Secret);

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            var videoWidth  = (int)videoProps.Width;
            var videoHeight = (int)videoProps.Height;

            if (profile != null)
            {
                videoWidth  = (int)profile.Video.Width;
                videoHeight = (int)profile.Video.Height;
            }

            var document = new TLDocument
            {
                Id         = 0,
                AccessHash = 0,
                Date       = date,
                Size       = (int)basicProps.Size,
                MimeType   = fileCache.ContentType,
                Thumb      = thumbnail,
                Attributes = new TLVector <TLDocumentAttributeBase>
                {
                    new TLDocumentAttributeFilename
                    {
                        FileName = file.Name
                    },
                    new TLDocumentAttributeVideo
                    {
                        Duration       = (int)videoProps.Duration.TotalSeconds,
                        W              = videoWidth,
                        H              = videoHeight,
                        IsRoundMessage = round
                    }
                }
            };

            var media = new TLMessageMediaDocument
            {
                Document = document,
                Caption  = caption
            };

            var message = TLUtils.GetMessage(SettingsHelper.UserId, Peer.ToPeer(), TLMessageState.Sending, true, true, date, string.Empty, media, TLLong.Random(), null);

            if (Reply != null)
            {
                message.HasReplyToMsgId = true;
                message.ReplyToMsgId    = Reply.Id;
                message.Reply           = Reply;
                Reply = null;
            }

            var previousMessage = InsertSendingMessage(message);

            CacheService.SyncSendingMessage(message, previousMessage, async(m) =>
            {
                if (transform != null && profile != null)
                {
                    await fileCache.RenameAsync(fileName + ".temp.mp4");
                    var fileResult = await FileUtils.CreateTempFileAsync(fileName);

                    var transcoder = new MediaTranscoder();
                    transcoder.AddVideoEffect(transform.ActivatableClassId, true, transform.Properties);

                    var prepare = await transcoder.PrepareFileTranscodeAsync(fileCache, fileResult, profile);
                    await prepare.TranscodeAsync().AsTask(Upload(media.Document as TLDocument, progress => new TLSendMessageUploadDocumentAction {
                        Progress = progress
                    }, 0, 200.0));

                    //await fileCache.DeleteAsync();
                    fileCache = fileResult;

                    thumbnailBase = await FileUtils.GetFileThumbnailAsync(fileCache);
                    thumbnail     = thumbnailBase as TLPhotoSize;

                    desiredName    = string.Format("{0}_{1}_{2}.jpg", thumbnail.Location.VolumeId, thumbnail.Location.LocalId, thumbnail.Location.Secret);
                    document.Thumb = thumbnail;
                }

                var fileId = TLLong.Random();
                var upload = await _uploadVideoManager.UploadFileAsync(fileId, fileCache.Name, false).AsTask(Upload(media.Document as TLDocument, progress => new TLSendMessageUploadDocumentAction {
                    Progress = progress
                }, 0.5, 2.0));
                if (upload != null)
                {
                    var thumbFileId = TLLong.Random();
                    var thumbUpload = await _uploadDocumentManager.UploadFileAsync(thumbFileId, desiredName);
                    if (thumbUpload != null)
                    {
                        var inputMedia = new TLInputMediaUploadedThumbDocument
                        {
                            File       = upload.ToInputFile(),
                            Thumb      = thumbUpload.ToInputFile(),
                            MimeType   = document.MimeType,
                            Caption    = media.Caption,
                            Attributes = document.Attributes
                        };

                        var result = await ProtoService.SendMediaAsync(Peer, inputMedia, message);
                    }
                    //if (result.IsSucceeded)
                    //{
                    //    var update = result.Result as TLUpdates;
                    //    if (update != null)
                    //    {
                    //        var newMessage = update.Updates.OfType<TLUpdateNewMessage>().FirstOrDefault();
                    //        if (newMessage != null)
                    //        {
                    //            var newM = newMessage.Message as TLMessage;
                    //            if (newM != null)
                    //            {
                    //                message.Media = newM.Media;
                    //                message.RaisePropertyChanged(() => message.Media);
                    //            }
                    //        }
                    //    }
                    //}
                }
            });
        }
        private async void SendExecute()
        {
            var save = _isSave ?? false;

            if (_paymentForm.SavedCredentials != null && !save && _paymentForm.CanSaveCredentials)
            {
                //_paymentForm.HasSavedCredentials = false;
                _paymentForm.SavedCredentials = null;

                ProtoService.Send(new DeleteSavedCredentials());
            }

            var month = 0;
            var year  = 0;

            if (_date != null)
            {
                var args = _date.Split('/');
                if (args.Length == 2)
                {
                    month = int.Parse(args[0]);
                    year  = int.Parse(args[1]);
                }
            }

            var card = new Card(
                _card,
                month,
                year,
                _cvc,
                _cardName,
                null, null, null, null,
                _postcode,
                _selectedCountry?.Code?.ToUpper(),
                null);

            if (!card.ValidateNumber())
            {
                RaisePropertyChanged("CARD_NUMBER_INVALID");
                return;
            }
            if (!card.ValidateExpireDate())
            {
                RaisePropertyChanged("CARD_EXPIRE_DATE_INVALID");
                return;
            }
            if (NeedCardholderName && string.IsNullOrWhiteSpace(_cardName))
            {
                RaisePropertyChanged("CARD_HOLDER_NAME_INVALID");
                return;
            }
            if (!card.ValidateCVC())
            {
                RaisePropertyChanged("CARD_CVC_INVALID");
                return;
            }
            if (NeedCountry && _selectedCountry == null)
            {
                RaisePropertyChanged("CARD_COUNTRY_INVALID");
                return;
            }
            if (NeedZip && string.IsNullOrWhiteSpace(_postcode))
            {
                RaisePropertyChanged("CARD_ZIP_INVALID");
                return;
            }

            IsLoading = true;

            using (var stripe = new StripeClient(_publishableKey))
            {
                var token = await stripe.CreateTokenAsync(card);

                if (token != null)
                {
                    var title       = card.GetBrand() + " *" + card.GetLast4();
                    var credentials = string.Format("{{\"type\":\"{0}\", \"id\":\"{1}\"}}", token.Type, token.Id);

                    NavigateToNextStep(title, credentials, _isSave ?? false);
                }
                else
                {
                    IsLoading = false;
                }
            }

            //var save = _isSave ?? false;
            //var info = new TLPaymentRequestedInfo();
            //if (_paymentForm.Invoice.IsNameRequested)
            //{
            //    info.Name = _info.Name;
            //}
            //if (_paymentForm.Invoice.IsEmailRequested)
            //{
            //    info.Email = _info.Email;
            //}
            //if (_paymentForm.Invoice.IsPhoneRequested)
            //{
            //    info.Phone = _info.Phone;
            //}
            //if (_paymentForm.Invoice.IsShippingAddressRequested)
            //{
            //    info.ShippingAddress = _info.ShippingAddress;
            //    info.ShippingAddress.CountryIso2 = _selectedCountry?.Code;
            //}

            //var response = await ProtoService.ValidateRequestedInfoAsync(save, _message.Id, info);
            //if (response.IsSucceeded)
            //{
            //    IsLoading = false;

            //    if (_paymentForm.HasSavedInfo && !save)
            //    {
            //        ProtoService.ClearSavedInfoAsync(true, false, null, null);
            //    }

            //    if (_paymentForm.Invoice.IsFlexible)
            //    {
            //        NavigationService.Navigate(typeof(PaymentFormStep2Page), TLTuple.Create(_message, _paymentForm, response.Result));
            //    }
            //    else if (_paymentForm.HasSavedCredentials)
            //    {
            //        // TODO: Is password expired?
            //        var expired = true;
            //        if (expired)
            //        {
            //            NavigationService.Navigate(typeof(PaymentFormStep4Page));
            //        }
            //        else
            //        {
            //            NavigationService.Navigate(typeof(PaymentFormStep5Page));
            //        }
            //    }
            //    else
            //    {
            //        NavigationService.Navigate(typeof(PaymentFormStep3Page));
            //    }
            //}
        }
        private async Task SendPhotoAsync(StorageFile file, string caption)
        {
            var fileLocation = new TLFileLocation
            {
                VolumeId = TLLong.Random(),
                LocalId  = TLInt.Random(),
                Secret   = TLLong.Random(),
                DCId     = 0
            };

            var fileName  = string.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var fileCache = await FileUtils.CreateTempFileAsync(fileName);

            StorageFile fileScale;

            try
            {
                fileScale = await ImageHelper.ScaleJpegAsync(file, fileCache, 1280, 0.77);
            }
            catch (InvalidCastException)
            {
                await fileCache.DeleteAsync();
                await SendGifAsync(file, caption);

                return;
            }

            var basicProps = await fileScale.GetBasicPropertiesAsync();

            var imageProps = await fileScale.Properties.GetImagePropertiesAsync();

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            var photoSize = new TLPhotoSize
            {
                Type     = "y",
                W        = (int)imageProps.Width,
                H        = (int)imageProps.Height,
                Location = fileLocation,
                Size     = (int)basicProps.Size
            };

            var photo = new TLPhoto
            {
                Id         = 0,
                AccessHash = 0,
                Date       = date,
                Sizes      = new TLVector <TLPhotoSizeBase> {
                    photoSize
                }
            };

            var media = new TLMessageMediaPhoto
            {
                Photo   = photo,
                Caption = caption
            };

            var message = TLUtils.GetMessage(SettingsHelper.UserId, Peer.ToPeer(), TLMessageState.Sending, true, true, date, string.Empty, media, TLLong.Random(), null);

            if (Reply != null)
            {
                message.HasReplyToMsgId = true;
                message.ReplyToMsgId    = Reply.Id;
                message.Reply           = Reply;
                Reply = null;
            }

            var previousMessage = InsertSendingMessage(message);

            CacheService.SyncSendingMessage(message, previousMessage, async(m) =>
            {
                var fileId = TLLong.Random();
                var upload = await _uploadFileManager.UploadFileAsync(fileId, fileCache.Name, false).AsTask(Upload(photo, progress => new TLSendMessageUploadPhotoAction {
                    Progress = progress
                }));
                if (upload != null)
                {
                    var inputMedia = new TLInputMediaUploadedPhoto
                    {
                        Caption = media.Caption,
                        File    = upload.ToInputFile()
                    };

                    var response = await ProtoService.SendMediaAsync(Peer, inputMedia, message);
                    //if (response.IsSucceeded && response.Result is TLUpdates updates)
                    //{
                    //    TLPhoto newPhoto = null;

                    //    var newMessageUpdate = updates.Updates.FirstOrDefault(x => x is TLUpdateNewMessage) as TLUpdateNewMessage;
                    //    if (newMessageUpdate != null && newMessageUpdate.Message is TLMessage newMessage && newMessage.Media is TLMessageMediaPhoto newPhotoMedia)
                    //    {
                    //        newPhoto = newPhotoMedia.Photo as TLPhoto;
                    //    }

                    //    var newChannelMessageUpdate = updates.Updates.FirstOrDefault(x => x is TLUpdateNewChannelMessage) as TLUpdateNewChannelMessage;
                    //    if (newChannelMessageUpdate != null && newMessageUpdate.Message is TLMessage newChannelMessage && newChannelMessage.Media is TLMessageMediaPhoto newChannelPhotoMedia)
                    //    {
                    //        newPhoto = newChannelPhotoMedia.Photo as TLPhoto;
                    //    }

                    //    if (newPhoto != null && newPhoto.Full is TLPhotoSize newFull && newFull.Location is TLFileLocation newLocation)
                    //    {
                    //        var newFileName = string.Format("{0}_{1}_{2}.jpg", newLocation.VolumeId, newLocation.LocalId, newLocation.Secret);
                    //        var newFile = await FileUtils.CreateTempFileAsync(newFileName);
                    //        await fileCache.CopyAndReplaceAsync(newFile);
                    //    }
                    //}
                }
            });
        }
        private async void SendExecute()
        {
            if (_sentCode == null)
            {
                //...
                return;
            }

            if (_phoneCode == null)
            {
                await TLMessageDialog.ShowAsync("Please enter your code.");

                return;
            }

            var phoneNumber   = _phoneNumber;
            var phoneCodeHash = _sentCode.PhoneCodeHash;

            IsLoading = true;

            var response = await ProtoService.SignInAsync(phoneNumber, phoneCodeHash, _phoneCode);

            if (response.IsSucceeded)
            {
                ProtoService.SetInitState();
                ProtoService.CurrentUserId  = response.Result.User.Id;
                SettingsHelper.IsAuthorized = true;
                SettingsHelper.UserId       = response.Result.User.Id;

                // TODO: maybe ask about notifications?

                NavigationService.Navigate(typeof(MainPage));
            }
            else
            {
                IsLoading = false;

                if (response.Error.TypeEquals(TLErrorType.PHONE_NUMBER_UNOCCUPIED))
                {
                    //var signup = await ProtoService.SignUpAsync(phoneNumber, phoneCodeHash, PhoneCode, "Paolo", "Veneziani");
                    //if (signup.IsSucceeded)
                    //{
                    //    ProtoService.SetInitState();
                    //    ProtoService.CurrentUserId = signup.Value.User.Id;
                    //    SettingsHelper.IsAuthorized = true;
                    //    SettingsHelper.UserId = signup.Value.User.Id;
                    //}

                    //this._callTimer.Stop();
                    //this.StateService.ClearNavigationStack = true;
                    //this.NavigationService.UriFor<SignUpViewModel>().Navigate();
                    var state = new SignUpPage.NavigationParameters
                    {
                        PhoneNumber = _phoneNumber,
                        PhoneCode   = _phoneCode,
                        Result      = _sentCode,
                    };

                    NavigationService.Navigate(typeof(SignUpPage), state);
                }
                else if (response.Error.TypeEquals(TLErrorType.PHONE_CODE_INVALID))
                {
                    //await new MessageDialog(Resources.PhoneCodeInvalidString, Resources.Error).ShowAsync();
                }
                else if (response.Error.TypeEquals(TLErrorType.PHONE_CODE_EMPTY))
                {
                    //await new MessageDialog(Resources.PhoneCodeEmpty, Resources.Error).ShowAsync();
                }
                else if (response.Error.TypeEquals(TLErrorType.PHONE_CODE_EXPIRED))
                {
                    //await new MessageDialog(Resources.PhoneCodeExpiredString, Resources.Error).ShowAsync();
                }
                else if (response.Error.TypeEquals(TLErrorType.SESSION_PASSWORD_NEEDED))
                {
                    //this.IsWorking = true;
                    var password = await ProtoService.GetPasswordAsync();

                    if (password.IsSucceeded && password.Result is TLAccountPassword)
                    {
                        var state = new SignInPasswordPage.NavigationParameters
                        {
                            PhoneNumber = _phoneNumber,
                            PhoneCode   = _phoneCode,
                            Result      = _sentCode,
                            Password    = password.Result as TLAccountPassword
                        };

                        NavigationService.Navigate(typeof(SignInPasswordPage), state);
                    }
                    else
                    {
                        Execute.ShowDebugMessage("account.getPassword error " + password.Error);
                    }
                }
                else if (response.Error.CodeEquals(TLErrorCode.FLOOD))
                {
                    //await new MessageDialog($"{Resources.FloodWaitString}\r\n\r\n({error.Message})", Resources.Error).ShowAsync();
                }

                Execute.ShowDebugMessage("account.signIn error " + response.Error);
            }
        }
        private async Task SendGifAsync(StorageFile file, string caption)
        {
            var fileLocation = new TLFileLocation
            {
                VolumeId = TLLong.Random(),
                LocalId  = TLInt.Random(),
                Secret   = TLLong.Random(),
                DCId     = 0
            };

            var fileName  = string.Format("{0}_{1}_{2}.gif", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var fileCache = await FileUtils.CreateTempFileAsync(fileName);

            await file.CopyAndReplaceAsync(fileCache);

            var basicProps = await fileCache.GetBasicPropertiesAsync();

            var imageProps = await fileCache.Properties.GetImagePropertiesAsync();

            var thumbnailBase = await FileUtils.GetFileThumbnailAsync(file);

            var thumbnail = thumbnailBase as TLPhotoSize;

            var desiredName = string.Format("{0}_{1}_{2}.jpg", thumbnail.Location.VolumeId, thumbnail.Location.LocalId, thumbnail.Location.Secret);

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            var document = new TLDocument
            {
                Id         = 0,
                AccessHash = 0,
                Date       = date,
                Size       = (int)basicProps.Size,
                MimeType   = fileCache.ContentType,
                Thumb      = thumbnail,
                Attributes = new TLVector <TLDocumentAttributeBase>
                {
                    new TLDocumentAttributeAnimated(),
                    new TLDocumentAttributeFilename
                    {
                        FileName = file.Name
                    },
                    new TLDocumentAttributeImageSize
                    {
                        W = (int)imageProps.Width,
                        H = (int)imageProps.Height
                    },
                    new TLDocumentAttributeVideo
                    {
                        W = (int)imageProps.Width,
                        H = (int)imageProps.Height,
                    }
                }
            };

            var media = new TLMessageMediaDocument
            {
                Caption  = caption,
                Document = document
            };

            var message = TLUtils.GetMessage(SettingsHelper.UserId, Peer.ToPeer(), TLMessageState.Sending, true, true, date, string.Empty, media, TLLong.Random(), null);

            if (Reply != null)
            {
                message.HasReplyToMsgId = true;
                message.ReplyToMsgId    = Reply.Id;
                message.Reply           = Reply;
                Reply = null;
            }

            var previousMessage = InsertSendingMessage(message);

            CacheService.SyncSendingMessage(message, previousMessage, async(m) =>
            {
                var fileId = TLLong.Random();
                var upload = await _uploadDocumentManager.UploadFileAsync(fileId, fileName, false).AsTask(media.Document.Upload());
                if (upload != null)
                {
                    var thumbFileId = TLLong.Random();
                    var thumbUpload = await _uploadDocumentManager.UploadFileAsync(thumbFileId, desiredName);
                    if (thumbUpload != null)
                    {
                        var inputMedia = new TLInputMediaUploadedThumbDocument
                        {
                            File       = upload.ToInputFile(),
                            Thumb      = thumbUpload.ToInputFile(),
                            MimeType   = document.MimeType,
                            Caption    = media.Caption,
                            Attributes = document.Attributes
                        };

                        var result = await ProtoService.SendMediaAsync(Peer, inputMedia, message);
                    }
                }
            });
        }
Ejemplo n.º 25
0
        //public void HideGroup(TLChannelFull channelFull)
        //{
        //    var appData = ApplicationData.Current.LocalSettings.CreateContainer("Channels", ApplicationDataCreateDisposition.Always);
        //    appData.Values["Stickers" + channelFull.Id] = channelFull.StickerSet?.Id ?? 0;

        //    SavedStickers.Remove(_groupSet);
        //}

        public void SyncStickers(Chat chat)
        {
            if (_stickers)
            {
                return;
            }

            _stickers = true;

            ProtoService.Send(new GetFavoriteStickers(), result1 =>
            {
                ProtoService.Send(new GetRecentStickers(), result2 =>
                {
                    ProtoService.Send(new GetInstalledStickerSets(false), result3 =>
                    {
                        if (result1 is Stickers favorite && result2 is Stickers recent && result3 is StickerSets sets)
                        {
                            for (int i = 0; i < favorite.StickersValue.Count; i++)
                            {
                                var favSticker = favorite.StickersValue[i];
                                for (int j = 0; j < recent.StickersValue.Count; j++)
                                {
                                    var recSticker = recent.StickersValue[j];
                                    if (recSticker.StickerValue.Id == favSticker.StickerValue.Id)
                                    {
                                        recent.StickersValue.Remove(recSticker);
                                        break;
                                    }
                                }
                            }

                            for (int i = 20; i < recent.StickersValue.Count; i++)
                            {
                                recent.StickersValue.RemoveAt(20);
                                i--;
                            }

                            _favoriteSet.Update(favorite);
                            _recentSet.Update(recent);

                            var stickers = new List <StickerSetViewModel>();
                            if (_favoriteSet.Stickers.Count > 0)
                            {
                                stickers.Add(_favoriteSet);
                            }
                            if (_recentSet.Stickers.Count > 0)
                            {
                                stickers.Add(_recentSet);
                            }
                            if (_groupSet.Stickers.Count > 0 && _groupSet.ChatId == chat?.Id)
                            {
                                stickers.Add(_groupSet);
                            }

                            if (sets.Sets.Count > 0)
                            {
                                ProtoService.Send(new GetStickerSet(sets.Sets[0].Id), result4 =>
                                {
                                    if (result4 is StickerSet set)
                                    {
                                        stickers.Add(new StickerSetViewModel(ProtoService, Aggregator, sets.Sets[0], set));
                                        BeginOnUIThread(() => SavedStickers.ReplaceWith(stickers.Union(sets.Sets.Skip(1).Select(x => new StickerSetViewModel(ProtoService, Aggregator, x)))));
                                    }
                                    else
                                    {
                                        BeginOnUIThread(() => SavedStickers.ReplaceWith(stickers.Union(sets.Sets.Select(x => new StickerSetViewModel(ProtoService, Aggregator, x)))));
                                    }
                                });
                            }
                            else
                            {
                                BeginOnUIThread(() => SavedStickers.ReplaceWith(stickers.Union(sets.Sets.Select(x => new StickerSetViewModel(ProtoService, Aggregator, x)))));
                            }
                        }
                    });
                });
            });
        public async Task SendAudioAsync(StorageFile file, int duration, bool voice, string title, string performer, string caption)
        {
            var fileLocation = new TLFileLocation
            {
                VolumeId = TLLong.Random(),
                LocalId  = TLInt.Random(),
                Secret   = TLLong.Random(),
                DCId     = 0
            };

            var fileName  = string.Format("{0}_{1}_{2}.ogg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var fileCache = await FileUtils.CreateTempFileAsync(fileName);

            await file.CopyAndReplaceAsync(fileCache);

            var basicProps = await fileCache.GetBasicPropertiesAsync();

            var imageProps = await fileCache.Properties.GetImagePropertiesAsync();

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            var media = new TLMessageMediaDocument
            {
                Caption  = caption,
                Document = new TLDocument
                {
                    Id         = TLLong.Random(),
                    AccessHash = TLLong.Random(),
                    Date       = date,
                    MimeType   = "audio/ogg",
                    Size       = (int)basicProps.Size,
                    Thumb      = new TLPhotoSizeEmpty
                    {
                        Type = string.Empty
                    },
                    Version    = 0,
                    DCId       = 0,
                    Attributes = new TLVector <TLDocumentAttributeBase>
                    {
                        new TLDocumentAttributeAudio
                        {
                            IsVoice   = voice,
                            Duration  = duration,
                            Title     = title,
                            Performer = performer
                        }
                    }
                }
            };

            var message = TLUtils.GetMessage(SettingsHelper.UserId, Peer.ToPeer(), TLMessageState.Sending, true, true, date, string.Empty, media, TLLong.Random(), null);

            if (Reply != null)
            {
                message.HasReplyToMsgId = true;
                message.ReplyToMsgId    = Reply.Id;
                message.Reply           = Reply;
                Reply = null;
            }

            var previousMessage = InsertSendingMessage(message);

            CacheService.SyncSendingMessage(message, previousMessage, async(m) =>
            {
                var fileId = TLLong.Random();
                var upload = await _uploadAudioManager.UploadFileAsync(fileId, fileName, false).AsTask(Upload(media.Document as TLDocument, progress => new TLSendMessageUploadAudioAction {
                    Progress = progress
                }));
                if (upload != null)
                {
                    var inputMedia = new TLInputMediaUploadedDocument
                    {
                        File       = upload.ToInputFile(),
                        MimeType   = "audio/ogg",
                        Caption    = media.Caption,
                        Attributes = new TLVector <TLDocumentAttributeBase>
                        {
                            new TLDocumentAttributeAudio
                            {
                                IsVoice   = voice,
                                Duration  = duration,
                                Title     = title,
                                Performer = performer
                            }
                        }
                    };

                    var result = await ProtoService.SendMediaAsync(Peer, inputMedia, message);
                }
            });
        }
Ejemplo n.º 27
0
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            var bundle = parameter as ChatMemberNavigation;

            if (bundle == null)
            {
                return;
            }

            Chat = ProtoService.GetChat(bundle.ChatId);

            var chat = _chat;

            if (chat == null)
            {
                return;
            }

            var response = await ProtoService.SendAsync(new GetChatMember(chat.Id, bundle.UserId));

            if (response is ChatMember member && chat.Type is ChatTypeSupergroup super)
            {
                var item  = ProtoService.GetUser(member.UserId);
                var cache = ProtoService.GetUserFull(member.UserId);

                var group = ProtoService.GetSupergroup(super.SupergroupId);

                Delegate?.UpdateMember(chat, group, item, member);
                Delegate?.UpdateUser(chat, item, false);

                if (cache == null)
                {
                    ProtoService.Send(new GetUserFullInfo(member.UserId));
                }
                else
                {
                    Delegate?.UpdateUserFullInfo(chat, item, cache, false);
                }

                Member = member;

                if (member.Status is ChatMemberStatusAdministrator administrator)
                {
                    CanChangeInfo      = administrator.CanChangeInfo;
                    CanDeleteMessages  = administrator.CanDeleteMessages;
                    CanEditMessages    = administrator.CanEditMessages;
                    CanInviteUsers     = administrator.CanInviteUsers;
                    CanPinMessages     = administrator.CanPinMessages;
                    CanPostMessages    = administrator.CanPostMessages;
                    CanPromoteMembers  = administrator.CanPromoteMembers;
                    CanRestrictMembers = administrator.CanRestrictMembers;
                }
                else
                {
                    CanChangeInfo      = true;
                    CanDeleteMessages  = true;
                    CanEditMessages    = true;
                    CanInviteUsers     = true;
                    CanPinMessages     = true;
                    CanPostMessages    = true;
                    CanPromoteMembers  = false;
                    CanRestrictMembers = true;
                }
            }
        }
Ejemplo n.º 28
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);
            }
        }
Ejemplo n.º 29
0
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            var bundle = parameter as ChatMemberNavigation;

            if (bundle == null)
            {
                return;
            }

            Chat = ProtoService.GetChat(bundle.ChatId);

            var chat = _chat;

            if (chat == null)
            {
                return;
            }

            var response = await ProtoService.SendAsync(new GetChatMember(chat.Id, bundle.UserId));

            if (response is ChatMember member)
            {
                var item  = ProtoService.GetUser(member.UserId);
                var cache = ProtoService.GetUserFull(member.UserId);

                Delegate?.UpdateMember(chat, item, member);
                Delegate?.UpdateUser(chat, item, false);

                if (cache == null)
                {
                    ProtoService.Send(new GetUserFullInfo(member.UserId));
                }
                else
                {
                    Delegate?.UpdateUserFullInfo(chat, item, cache, false, false);
                }

                Member = member;

                if (member.Status is ChatMemberStatusRestricted restricted)
                {
                    CanChangeInfo         = restricted.Permissions.CanChangeInfo;
                    CanPinMessages        = restricted.Permissions.CanPinMessages;
                    CanInviteUsers        = restricted.Permissions.CanInviteUsers;
                    CanSendPolls          = restricted.Permissions.CanSendPolls;
                    CanAddWebPagePreviews = restricted.Permissions.CanAddWebPagePreviews;
                    CanSendOtherMessages  = restricted.Permissions.CanSendOtherMessages;
                    CanSendMediaMessages  = restricted.Permissions.CanSendMediaMessages;
                    CanSendMessages       = restricted.Permissions.CanSendMessages;
                    UntilDate             = restricted.RestrictedUntilDate;
                }
                else if (member.Status is ChatMemberStatusBanned banned)
                {
                    CanChangeInfo         = false;
                    CanPinMessages        = false;
                    CanInviteUsers        = false;
                    CanSendPolls          = false;
                    CanAddWebPagePreviews = false;
                    CanSendOtherMessages  = false;
                    CanSendMediaMessages  = false;
                    CanSendMessages       = false;
                    UntilDate             = banned.BannedUntilDate;
                }
                else
                {
                    CanChangeInfo         = chat.Permissions.CanChangeInfo;
                    CanPinMessages        = chat.Permissions.CanPinMessages;
                    CanInviteUsers        = chat.Permissions.CanInviteUsers;
                    CanSendPolls          = chat.Permissions.CanSendPolls;
                    CanAddWebPagePreviews = chat.Permissions.CanAddWebPagePreviews;
                    CanSendOtherMessages  = chat.Permissions.CanSendOtherMessages;
                    CanSendMediaMessages  = chat.Permissions.CanSendMediaMessages;
                    CanSendMessages       = chat.Permissions.CanSendMessages;
                    UntilDate             = 0;
                }
            }
        }
Ejemplo n.º 30
0
        private async void SendExecute()
        {
            var chat = _chat;

            if (chat == null)
            {
                return;
            }

            var                about      = _about.Format();
            var                title      = _title.Trim();
            string             oldAbout   = null;
            Supergroup         supergroup = null;
            SupergroupFullInfo fullInfo   = null;

            if (chat.Type is ChatTypeSupergroup)
            {
                var item  = ProtoService.GetSupergroup(chat);
                var cache = ProtoService.GetSupergroupFull(chat);

                if (item == null || cache == null)
                {
                    return;
                }

                oldAbout   = cache.Description;
                supergroup = item;
                fullInfo   = cache;

                if (item.IsChannel && _isSignatures != item.SignMessages)
                {
                    var response = await ProtoService.SendAsync(new ToggleSupergroupSignMessages(item.Id, _isSignatures));

                    if (response is Error)
                    {
                        // TODO:
                    }
                }
            }
            else if (chat.Type is ChatTypeBasicGroup basicGroup)
            {
                var item  = ProtoService.GetBasicGroup(basicGroup.BasicGroupId);
                var cache = ProtoService.GetBasicGroupFull(basicGroup.BasicGroupId);

                oldAbout = cache.Description;
            }

            if (!string.Equals(title, chat.Title))
            {
                var response = await ProtoService.SendAsync(new SetChatTitle(chat.Id, title));

                if (response is Error)
                {
                    // TODO:
                }
            }

            if (!string.Equals(about, oldAbout))
            {
                var response = await ProtoService.SendAsync(new SetChatDescription(chat.Id, about));

                if (response is Error)
                {
                    // TODO:
                }
            }

            if (_isAllHistoryAvailable && chat.Type is ChatTypeBasicGroup)
            {
                var response = await ProtoService.SendAsync(new UpgradeBasicGroupChatToSupergroupChat(chat.Id));

                if (response is Chat result && result.Type is ChatTypeSupergroup super)
                {
                    chat       = result;
                    supergroup = await ProtoService.SendAsync(new GetSupergroup(super.SupergroupId)) as Supergroup;

                    fullInfo = await ProtoService.SendAsync(new GetSupergroupFullInfo(super.SupergroupId)) as SupergroupFullInfo;
                }
                else if (response is Error)
                {
                    // TODO:
                }
            }