public async void SearchShow()
        {
            IsSearchCompleted = false;
            IsWorking         = true;

            var query = ShowName;
            var shows = await Task <List <Show> > .Factory.StartNew(() =>
            {
                try
                {
                    return(informationProvider.GetShows(query));
                }
                catch
                {
                    return(null);
                }
            });

            IsWorking = false;

            Execute.BeginOnUIThread(() =>
            {
                Shows.Clear();
                IsSearchCompleted = true;

                if (shows == null)
                {
                    Error = "Provider failed to return information.";
                    return;
                }

                Error = null;

                foreach (var show in shows)
                {
                    Shows.Add(show);
                }
            });
        }
        public static async void LoadImageWithTextPlaceholder(this ASImageNode imageView,
                                                              string url,
                                                              string name,
                                                              AvatarStyles styles)
        {
            Execute.BeginOnUIThread(() =>
            {
                imageView.Image = CreateAvatarWithTextPlaceholder(name, styles);
            });

            if (string.IsNullOrEmpty(url))
            {
                return;
            }

            var expr = ImageService.Instance
                       .LoadUrl(url)
                       .DownSampleInDip(styles.Size.Width, styles.Size.Height);

            UIImage image = null;

            try
            {
                image = await expr.AsUIImageAsync().ConfigureAwait(false);
            }
            catch
            {
                // do nothing
            }

            if (image != null)
            {
                Execute.BeginOnUIThread(() =>
                {
                    imageView.Image = image;
                });
            }
        }
Example #3
0
        public static BitmapSource ReturnOrEnqueueProfileImage(TLFileLocation location, TLObject owner, int fileSize)
        {
            var fileName = string.Format("{0}_{1}_{2}.jpg", location.VolumeId, location.LocalId, location.Secret);

            if (_cachedSources.TryGetValue(fileName, out WeakReference weakReference) && weakReference.IsAlive)
            {
                return(weakReference.Target as BitmapSource);
            }

            if (File.Exists(FileUtils.GetTempFileName(fileName)))
            {
                var bitmap = new BitmapImage();
                bitmap.UriSource         = FileUtils.GetTempFileUri(fileName);
                _cachedSources[fileName] = new WeakReference(bitmap);

                return(bitmap);
            }

            if (fileSize >= 0)
            {
                var manager = UnigramContainer.Current.ResolveType <IDownloadFileManager>();
                var bitmap  = new BitmapImage();
                _cachedSources[fileName] = new WeakReference(bitmap);

                Execute.BeginOnThreadPool(async() =>
                {
                    await manager.DownloadFileAsync(location, fileSize);
                    Execute.BeginOnUIThread(() =>
                    {
                        bitmap.UriSource = FileUtils.GetTempFileUri(fileName);
                    });
                });

                return(bitmap);
            }

            return(null);
        }
        public Task <string> ShowAsync()
        {
            var dialogResult = new TaskCompletionSource <string>();

            Execute.BeginOnUIThread(() =>
            {
                var builder = GetBuilder()
                              .SetTitle(_config.Title);

                builder.SetItems(_config.OptionButtons, (sender, args) =>
                {
                    dialogResult.TrySetResult(_config.OptionButtons[args.Which]);
                });

                if (_config.DestructButtonText != null)
                {
                    SetNegativeButton(builder, _config.DestructButtonText, dialogResult, _config.DestructButtonText);
                }

                if (_config.CancelButtonText != null)
                {
                    builder.SetCancelable(true);

                    SetPositiveButton(builder, _config.CancelButtonText, dialogResult, _config.CancelButtonText);
                }

                var dialog = builder.Create();

                if (_config.CancelButtonText != null)
                {
                    HandleDismiss(dialog, dialogResult, _config.CancelButtonText);
                }

                dialog.Show();
            });

            return(dialogResult.Task);
        }
        private void ProcessStickers()
        {
            _stickers = true;

            var stickers = _stickersService.GetStickerSets(StickerType.Image);

            Execute.BeginOnUIThread(() =>
            {
                SavedStickers.ReplaceWith(stickers);

                //if (_groupSet.Documents != null && _groupSet.Documents.Count > 0)
                //{
                //    SavedStickers.Add(_groupSet);
                //}
                //else
                //{
                //    SavedStickers.Remove(_groupSet);
                //}

                //if (_recentSet.Documents != null && _recentSet.Documents.Count > 0)
                //{
                //    SavedStickers.Add(_recentSet);
                //}
                //else
                //{
                //    SavedStickers.Remove(_recentSet);
                //}

                //if (_favedSet.Documents != null && _favedSet.Documents.Count > 0)
                //{
                //    SavedStickers.Add(_favedSet);
                //}
                //else
                //{
                //    SavedStickers.Remove(_favedSet);
                //}
            });
        }
        private async void FetchShowDetails()
        {
            try
            {
                using (this.ShowProgress())
                {
                    var connection = await this.connectionService.GetConnectionAsync();

                    this.Show = await connection.GetShowContentDetails(this.ShowContentID);

                    if (!string.IsNullOrEmpty(this.ShowOfferID))
                    {
                        this.Offer = await connection.GetOfferDetails(this.ShowOfferID);
                    }

                    if (!string.IsNullOrEmpty(this.ShowRecordingID))
                    {
                        this.Recording = await connection.GetRecordingDetails(this.ShowRecordingID);
                    }
                }
            }
            catch (Exception ex)
            {
                Execute.BeginOnUIThread(() =>
                {
                    var toast = new ToastPrompt()
                    {
                        Title           = "Failed to fetch show details",
                        Message         = ex.Message,
                        TextOrientation = Orientation.Vertical,
                        TextWrapping    = TextWrapping.Wrap,
                        Background      = new SolidColorBrush(Colors.Red),
                    };

                    toast.Show();
                });
            }
        }
        public async void CancelRecording()
        {
            this.analyticsService.CancelSingleRecording();

            try
            {
                using (this.ShowProgress())
                {
                    var connection = await this.connectionService.GetConnectionAsync();

                    await connection.CancelRecording(this.ShowRecordingID);
                }

                var toast = new ToastPrompt()
                {
                    Title           = "Recording Cancelled",
                    TextOrientation = Orientation.Vertical,
                };

                toast.Show();
            }
            catch (Exception ex)
            {
                Execute.BeginOnUIThread(() =>
                {
                    var toast = new ToastPrompt()
                    {
                        Title           = "Cancel Recording Failed",
                        Message         = ex.Message,
                        TextOrientation = Orientation.Vertical,
                        TextWrapping    = TextWrapping.Wrap,
                        Background      = new SolidColorBrush(Colors.Red),
                    };

                    toast.Show();
                });
            }
        }
Example #8
0
        public static void GetShowImage(Show show)
        {
            if (string.IsNullOrWhiteSpace(show.ImageUrl))
            {
                return;
            }

            show.IsLoading = true;

            Task.Factory.StartNew(() =>
            {
                var extension = Path.GetExtension(show.ImageUrl);
                var file      = string.Format("{0}{1}", show.ShowId, extension);
                var folder    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                             ConfigurationManager.AppSettings["IMAGE_CACHE"]);

                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                var filename = Path.Combine(folder, file);

                if (!File.Exists(filename))
                {
                    using (var web = new WebClient())
                    {
                        web.DownloadFile(show.ImageUrl, filename);
                    }
                }

                Execute.BeginOnUIThread(() =>
                {
                    show.ImageSource = new BitmapImage(new Uri(filename));
                    show.IsLoading   = false;
                });
            });
        }
Example #9
0
        public async void Handle(TLUpdateUserBlocked message)
        {
            var user = CacheService.GetUser(message.UserId) as TLUser;

            if (user != null)
            {
                Execute.BeginOnUIThread(() =>
                {
                    if (message.Blocked)
                    {
                        Items.Insert(0, user);
                    }
                    else
                    {
                        Items.Remove(user);
                    }
                });
            }
            else
            {
                var response = await ProtoService.GetFullUserAsync(new TLInputUser { UserId = message.UserId, AccessHash = 0 });

                if (response.IsSucceeded)
                {
                    Execute.BeginOnUIThread(() =>
                    {
                        if (message.Blocked)
                        {
                            Items.Insert(0, response.Result.User as TLUser);
                        }
                        else
                        {
                            Items.Remove(response.Result.User as TLUser);
                        }
                    });
                }
            }
        }
        /// <summary>
        /// The vm_ log message received.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void Vm_LogMessageReceived(object sender, LogEventArgs e)
        {
            try
            {
                if (e == null)
                {
                    Caliburn.Micro.Execute.OnUIThread(
                        () =>
                    {
                        LogViewModel vm = this.DataContext as LogViewModel;
                        if (vm != null)
                        {
                            this.logText.Clear();
                            this.logText.AppendText(vm.ActivityLog);
                        }
                        else
                        {
                            Debug.WriteLine("Failed to Reset Log correctly.");
                        }
                    });
                }
                else
                {
                    // This works better than Data Binding because of the scroll.
                    this.logText.AppendText(Environment.NewLine + e.Log.Content);

                    if (this.AutoScroll.IsChecked)
                    {
                        delayProcessor.PerformTask(() => Execute.BeginOnUIThread(() => this.logText.ScrollToEnd()), 100);
                    }
                }
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc);
            }
        }
Example #11
0
        public void ToggleChatAdmins()
        {
            if (IsWorking)
            {
                return;
            }

            Telegram.Api.Helpers.Execute.ShowDebugMessage(string.Format("messages.toggleChatAdmins chat_id={0} enabled={1}", _currentChat.Id, AdminsEnabled));
            IsWorking = true;
            NotifyOfPropertyChange(() => IsEnabled);
            MTProtoService.ToggleChatAdminsAsync(_currentChat.Id, new TLBool(AdminsEnabled),
                                                 result => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;
                NotifyOfPropertyChange(() => IsEnabled);
            }),
                                                 error => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;
                NotifyOfPropertyChange(() => IsEnabled);

                Telegram.Api.Helpers.Execute.ShowDebugMessage("messages.toggleChatAdmins error " + error);
            }));
        }
Example #12
0
        public void Handle(DialogAddedEventArgs args)
        {
            if (args.Dialog == null)
            {
                return;
            }

            Execute.BeginOnUIThread(() =>
            {
                var index = -1;
                for (int i = 0; i < Count; i++)
                {
                    if (this[i] == args.Dialog)
                    {
                        return;
                    }

                    if (this[i].GetDateIndex() < args.Dialog.GetDateIndex())
                    {
                        index = i;
                        break;
                    }
                }

                if (index == -1)
                {
                    Add(args.Dialog);
                }
                else
                {
                    Insert(index, args.Dialog);
                }

                //this.Status = ((this.Items.get_Count() == 0 || this.LazyItems.get_Count() == 0) ? string.Empty : this.Status);
            });
        }
Example #13
0
        public void Receive(string message)
        {
            string[] commands = message.Split(' ');

            Process(commands);

            string methodName = commands[MethodNameIndex];

            MethodInfo targetMethod = _methods.Single(method => method.Name == methodName);

            ParameterInfo[] parameters = targetMethod.GetParameters();
            object[]        arguments  = new object[parameters.Length];

            for (int parameterIndex = 0; parameterIndex < parameters.Length; ++parameterIndex)
            {
                Type parameterType = parameters[parameterIndex].ParameterType;

                TypeConverter converter = TypeDescriptor.GetConverter(parameterType);

                arguments[parameterIndex] = converter.ConvertFromString(commands[MethodNameIndex + 1 + parameterIndex]);
            }

            Execute.BeginOnUIThread(() => targetMethod.Invoke(this, arguments));
        }
Example #14
0
        public override Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            Task.Run(() => _pushService.RegisterAsync());

            Execute.BeginOnUIThread(() => Calls.OnNavigatedToAsync(parameter, mode, state));
            //Execute.BeginOnUIThread(() => Dialogs.LoadFirstSlice());
            //Execute.BeginOnUIThread(() => Contacts.getTLContacts());
            //Execute.BeginOnUIThread(() => Contacts.GetSelfAsync());

            //ProtoService.SendRequestAsync<TLUpdatesBase>("help.getAppChangelog", new TLHelpGetAppChangelog { PrevAppVersion = "4.2.2" }, result =>
            //{
            //    _updatesService.ProcessUpdates(result, true);
            //},
            //fault =>
            //{
            //    Debugger.Break();
            //});

            if (Refresh)
            {
                Refresh = false;
                Dialogs.Items.Clear();
                Execute.BeginOnThreadPool(() => Dialogs.LoadFirstSlice());
            }

            //ProtoService.GetTopPeersAsync(TLContactsGetTopPeers.Flag.BotsInline, 0, 0, 0, result =>
            //{
            //    var topPeers = result as TLContactsTopPeers;
            //    if (topPeers != null)
            //    {
            //        TopPeers = topPeers.Categories;
            //    }
            //});

            return(Task.CompletedTask);
        }
Example #15
0
 public void OnPositionChanged(GeoPosition <GeoCoordinate> position)
 {
     if (!position.Location.IsUnknown)
     {
         var message = MessageGeoLive as TLMessage70;
         if (message != null)
         {
             var mediaGeoLive = message.Media as TLMessageMediaGeoLive;
             if (mediaGeoLive != null && mediaGeoLive.Active)
             {
                 var geoPoint = mediaGeoLive.Geo as TLGeoPoint;
                 if (geoPoint != null)
                 {
                     var oldLocation = new GeoCoordinate(geoPoint.Lat.Value, geoPoint.Long.Value);
                     if (oldLocation.GetDistanceTo(position.Location) >= Constants.MinDistanceToUpdateLiveLocation)
                     {
                         var liveLocationService = IoC.Get <ILiveLocationService>();
                         liveLocationService.UpdateAsync(message,
                                                         new TLGeoPoint
                         {
                             Lat  = new TLDouble(position.Location.Latitude),
                             Long = new TLDouble(position.Location.Longitude)
                         },
                                                         result => Execute.BeginOnUIThread(() =>
                         {
                             mediaGeoLive.EditDate = message.EditDate;
                             mediaGeoLive.NotifyOfPropertyChange(() => mediaGeoLive.Geo);
                             mediaGeoLive.NotifyOfPropertyChange(() => mediaGeoLive.EditDate);
                             mediaGeoLive.NotifyOfPropertyChange(() => mediaGeoLive.Active);
                         }));
                     }
                 }
             }
         }
     }
 }
Example #16
0
        private void OpenAttachPanel()
        {
            Execute.BeginOnUIThread(() =>
            {
                var key = _simpleImagePicker.ViewModel.ImageCacheKey;
                if (key == _previewImageKey)
                {
                    return;
                }

                EditImageContainerHeightConstraint.Constant = 72;
                EditImageContainer.Hidden = false;
                InputTextView.BecomeFirstResponder();
                InvokeTopContainersHeightChangedIfNeeded();
                InvalidateIntrinsicContentSize();

                _previewImageKey = key;

                ImageService.Instance
                .LoadFile(key)
                .DownSampleInDip(60, 60)
                .IntoAsync(AttachedImageView);
            });
        }
Example #17
0
        protected override Task ExecuteEvent <T>(T eventObject, IEventHandler <T> @event, CancellationToken token)
        {
            var taskCompletionSource = new TaskCompletionSource <bool>();

            Execute.BeginOnUIThread(async() =>
            {
                try
                {
                    await base.ExecuteEvent(eventObject, @event, token);

                    taskCompletionSource.SetResult(true);
                }
                catch (OperationCanceledException)
                {
                    taskCompletionSource.SetCanceled();
                }
                catch (Exception ex)
                {
                    taskCompletionSource.SetException(ex);
                }
            });

            return(taskCompletionSource.Task);
        }
Example #18
0
        private void OnAuthorizationRequired(object sender, AuthorizationRequiredEventArgs e)
        {
            DeleteIfExists("database.sqlite");

            SettingsHelper.IsAuthorized          = false;
            SettingsHelper.UserId                = 0;
            SettingsHelper.ChannelUri            = null;
            MTProtoService.Current.CurrentUserId = 0;

            ApplicationSettings.Current.AddOrUpdateValue("lastGifLoadTime", 0L);
            ApplicationSettings.Current.AddOrUpdateValue("lastStickersLoadTime", 0L);
            ApplicationSettings.Current.AddOrUpdateValue("lastStickersLoadTimeMask", 0L);
            ApplicationSettings.Current.AddOrUpdateValue("lastStickersLoadTimeFavs", 0L);

            Debug.WriteLine("!!! UNAUTHORIZED !!!");
            Telegram.Logs.Log.Write(string.Format("Unauthorized method={0} error={1} authKeyId={2}", e.MethodName, e.Error ?? (object)"null", e.AuthKeyId));

            Execute.BeginOnUIThread(() =>
            {
                var type = App.Current.NavigationService.CurrentPageType;
                if (type.Name.StartsWith("SignIn") || type.Name.StartsWith("SignUp"))
                {
                }
                else
                {
                    try
                    {
                        UnigramContainer.Current.ResolveType <MainViewModel>().Refresh = true;
                    }
                    catch { }

                    App.Current.NavigationService.Navigate(typeof(IntroPage));
                    App.Current.NavigationService.Frame.BackStack.Clear();
                }
            });
        }
        public void Validate()
        {
            if (PaymentInfo == null)
            {
                return;
            }
            if (PaymentInfo.Message == null)
            {
                return;
            }
            if (PaymentInfo.Form == null)
            {
                return;
            }

            var info = new TLPaymentRequestedInfo
            {
                Flags = new TLInt(0)
            };

            if (PaymentInfo.Form.Invoice.NameRequested)
            {
                info.Name = new TLString(Name);
            }
            if (PaymentInfo.Form.Invoice.PhoneRequested)
            {
                info.Phone = new TLString(PhoneCode + PhoneNumber);
            }
            if (PaymentInfo.Form.Invoice.EmailRequested)
            {
                info.Email = new TLString(Email);
            }
            if (PaymentInfo.Form.Invoice.ShippingAddressRequested)
            {
                info.ShippingAddress = new TLPostAddress
                {
                    StreetLine1 = new TLString(StreetLine1),
                    StreetLine2 = new TLString(StreetLine2),
                    City        = new TLString(City),
                    State       = new TLString(State),
                    CountryIso2 = new TLString(SelectedCountry != null ? SelectedCountry.Code : string.Empty),
                    PostCode    = new TLString(PostCode)
                };
            }

            IsWorking = true;
            MTProtoService.ValidateRequestedInfoAsync(
                SaveShippingInformation,
                PaymentInfo.Message.Id,
                info,
                result => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;
                PaymentInfo.ValidatedInfo  = result;
                PaymentInfo.Form.SavedInfo = info;

                if (!SaveShippingInformation &&
                    PaymentInfo != null &&
                    PaymentInfo.Form != null &&
                    PaymentInfo.Form.SavedInfo != null)
                {
                    IsWorking = true;
                    MTProtoService.ClearSavedInfoAsync(false, true,
                                                       result2 => Execute.BeginOnUIThread(() =>
                    {
                        IsWorking = false;
                        NavigateToNextStep();
                    }),
                                                       error2 => Execute.BeginOnUIThread(() =>
                    {
                        IsWorking = false;
                        Telegram.Api.Helpers.Execute.ShowDebugMessage("payments.clearInfo error " + error2);
                    }));
                }
                else
                {
                    NavigateToNextStep();
                }
            }),
                error => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;
                Error     = error;
                NotifyOfPropertyChange(() => Error);
                Telegram.Api.Helpers.Execute.ShowDebugMessage("payments.validateRequestedInfo error " + error);
            }));
        }
Example #20
0
 public void Clear()
 {
     Execute.BeginOnUIThread(() => CurrentItem = null);
     Dispose();
 }
Example #21
0
        private void Stop()
        {
            Task.Run(async() =>
            {
                _stopReset.WaitOne();
                _stopReset.Reset();

                _recording = false;

                Execute.BeginOnUIThread(() =>
                {
                    if (_video)
                    {
                        _roundView.IsOpen = false;
                    }

                    RecordingStopped?.Invoke(this, EventArgs.Empty);
                });

                //_startReset.Set();
                //return;

                var now     = DateTime.Now;
                var elapsed = now - _start;

                Debug.WriteLine("Stop reached");
                Debug.WriteLine("Stop: " + now);

                if (_recorder == null)
                {
                    _startReset.Set();
                    return;
                }

                if (_recorder.IsRecording)
                {
                    await _recorder.StopAsync();
                }

                if (_cancelOnRelease || elapsed < TimeSpan.FromSeconds(1))
                {
                    await _file.DeleteAsync();
                }
                else if (_file != null)
                {
                    Debug.WriteLine("Sending voice message");

                    Execute.BeginOnUIThread(async() =>
                    {
                        if (_video)
                        {
                            var props  = await _file.Properties.GetVideoPropertiesAsync();
                            var width  = props.Width;
                            var height = props.Height;
                            var x      = 0d;
                            var y      = 0d;

                            if (width > height)
                            {
                                x     = (width - height) / 2;
                                width = height;
                            }

                            if (height > width)
                            {
                                y      = (height - width) / 2;
                                height = width;
                            }

                            var transform           = new VideoTransformEffectDefinition();
                            transform.CropRectangle = new Windows.Foundation.Rect(x, y, width, height);
                            transform.OutputSize    = new Windows.Foundation.Size(240, 240);

                            var profile           = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga);
                            profile.Video.Width   = 240;
                            profile.Video.Height  = 240;
                            profile.Video.Bitrate = 300000;

                            await ViewModel.SendVideoAsync(_file, null, true, profile, transform);
                        }
                        else
                        {
                            await ViewModel.SendAudioAsync(_file, (int)elapsed.TotalSeconds, true, null, null, null);
                        }
                    });
                }

                _startReset.Set();
            });
        }
Example #22
0
 private void ColorValuesChanged(UISettings sender, object args)
 {
     Execute.BeginOnUIThread(() => UpdateBars());
 }
        public bool OpenDialogDetails(TLObject with)
        {
            if (with == null)
            {
                return(false);
            }

            if (_forwardMessages != null)
            {
                var channel = with as TLChannel;
                if (channel != null && channel.IsBroadcast && !channel.Creator && !channel.IsEditor)
                {
                    MessageBox.Show(AppResources.PostToChannelError, AppResources.Error, MessageBoxButton.OK);

                    return(false);
                }
            }

            var result = MessageBoxResult.OK;

            if (_logFileName != null)
            {
                result = MessageBox.Show(AppResources.ForwardMessagesToThisChat, AppResources.Confirm, MessageBoxButton.OKCancel);
            }

            if (_webLink != null || _storageItems != null || _gameString != null)
            {
                var fullName = string.Empty;
                var chat     = with as TLChatBase;
                var user     = with as TLUserBase;
                if (chat != null)
                {
                    fullName = chat.FullName2;
                }
                if (user != null)
                {
                    fullName = user.FullName2;
                }

                if (_gameString != null)
                {
                    result = MessageBox.Show(string.Format(AppResources.ShareGameWith, fullName), AppResources.Confirm, MessageBoxButton.OKCancel);
                }
                else
                {
                    result = MessageBox.Show(string.Format(AppResources.ShareWith, fullName), AppResources.Confirm, MessageBoxButton.OKCancel);
                }
            }

            if (_bot != null)
            {
                var chat    = with as TLChat;
                var channel = with as TLChannel;
                if (chat == null && (channel == null || !channel.IsMegaGroup))
                {
                    return(false);
                }

                var chatName = chat != null ? chat.FullName : channel.FullName;
                result = MessageBox.Show(string.Format(AppResources.AddBotToTheGroup, chatName), AppResources.Confirm, MessageBoxButton.OKCancel);
            }

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

            if (_gameString != null)
            {
                var inputPeer = with as IInputPeer;
                if (inputPeer == null)
                {
                    return(false);
                }

                var mediaGame = new TLMessageMediaGame
                {
                    Game = new TLGame
                    {
                        Flags       = new TLInt(0),
                        Id          = new TLLong(0),
                        AccessHash  = new TLLong(0),
                        ShortName   = new TLString(_gameString),
                        Title       = new TLString(_gameString),
                        Description = TLString.Empty,
                        Photo       = new TLPhotoEmpty {
                            Id = new TLLong(0)
                        }
                    }
                };
                var message = GetMessage(with, inputPeer.ToInputPeer(), TLString.Empty, mediaGame);
                mediaGame.SourceMessage = message;
                IoC.Get <ICacheService>().SyncSendingMessage(message, null, m =>
                {
                    //IsWorking = true;
                    IoC.Get <IMTProtoService>().SendMediaAsync(inputPeer.ToInputPeer(), new TLInputMediaGame {
                        Id = new TLInputGameShortName {
                            ShortName = new TLString(_gameString), BotId = _sharedContact.ToInputUser()
                        }
                    }, message,
                                                               updatesBase => Execute.BeginOnUIThread(() =>
                    {
                        var updates = updatesBase as TLUpdates;
                        if (updates != null)
                        {
                            var newChannelMessageUpdate = updates.Updates.FirstOrDefault(x => x is TLUpdateNewChannelMessage) as TLUpdateNewChannelMessage;
                            if (newChannelMessageUpdate != null)
                            {
                                var messageCommon = newChannelMessageUpdate.Message as TLMessageCommon;
                                if (messageCommon != null)
                                {
                                    var dialog = IoC.Get <ICacheService>().GetDialog(messageCommon);
                                    if (dialog != null)
                                    {
                                        IoC.Get <ITelegramEventAggregator>().Publish(new TopMessageUpdatedEventArgs(dialog, messageCommon));
                                    }
                                }
                            }

                            var newMessageUpdate = updates.Updates.FirstOrDefault(x => x is TLUpdateNewMessage) as TLUpdateNewMessage;
                            if (newMessageUpdate != null)
                            {
                                var messageCommon = newMessageUpdate.Message as TLMessageCommon;
                                if (messageCommon != null)
                                {
                                    var dialog = IoC.Get <ICacheService>().GetDialog(messageCommon);
                                    if (dialog != null)
                                    {
                                        IoC.Get <ITelegramEventAggregator>().Publish(new TopMessageUpdatedEventArgs(dialog, messageCommon));
                                    }
                                }
                            }
                        }

                        //IsWorking = false;
                        IoC.Get <INavigationService>().RemoveBackEntry();
                        IoC.Get <INavigationService>().GoBack();
                    }),
                                                               error => Execute.BeginOnUIThread(() =>
                    {
                        //IsWorking = false;
                        Telegram.Api.Helpers.Execute.ShowDebugMessage("messages.sendMedia error=" + error);
                    }));
                });

                return(false);
            }

            _stateService.RemoveBackEntry   = true;
            _stateService.With              = with;
            _stateService.ForwardMessages   = _forwardMessages;
            _stateService.RemoveBackEntries = true;
            _stateService.LogFileName       = _logFileName;
            _stateService.SharedContact     = _sharedContact;
            _stateService.AccessToken       = _accessToken;
            _stateService.Bot                = _bot;
            _stateService.WebLink            = _webLink;
            _stateService.StorageItems       = _storageItems;
            _stateService.Url                = _url;
            _stateService.UrlText            = _urlText;
            _stateService.SwitchInlineButton = _switchInlineButton;
            _stateService.AnimateTitle       = true;
            _navigationService.UriFor <DialogDetailsViewModel>().Navigate();

            SaveRecent(with);
            return(true);
        }
        public void Validate()
        {
            if (PaymentInfo == null)
            {
                return;
            }
            if (PaymentInfo.Form == null)
            {
                return;
            }
            if (PaymentInfo.Message == null)
            {
                return;
            }
            if (PaymentInfo.Credentials == null)
            {
                return;
            }

            var      paymentCredentials = PaymentInfo.Credentials;
            TLString validatedInfoId    = null;
            TLString shippingOptionId   = null;

            if (PaymentInfo.ValidatedInfo != null)
            {
                validatedInfoId = PaymentInfo.ValidatedInfo.Id;

                if (PaymentInfo.ValidatedInfo.ShippingOptions != null)
                {
                    foreach (var shippingOption in PaymentInfo.ValidatedInfo.ShippingOptions)
                    {
                        if (shippingOption.IsSelected)
                        {
                            shippingOptionId = shippingOption.Id;
                            break;
                        }
                    }
                }
            }

            var mediaInvoice = PaymentInfo.Message.Media as TLMessageMediaInvoice;

            if (mediaInvoice == null)
            {
                return;
            }

            var bot = CacheService.GetUser(PaymentInfo.Form.BotId) as TLUser45;

            if (bot == null)
            {
                return;
            }

            if (!bot.IsVerified && !bot.BotPaymentsPermission)
            {
                MessageBox.Show(string.Format(AppResources.PaymentsWarning, bot.FullName), string.Empty, MessageBoxButton.OK);
                bot.BotPaymentsPermission = true;
            }

            var confirmation = MessageBox.Show(string.Format(AppResources.TransactionConfirmation, Currency.GetString(TotalAmount, PaymentInfo.Form.Invoice.Currency.ToString()), bot.FullName, mediaInvoice.Title), AppResources.TransactionReview, MessageBoxButton.OKCancel);

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

            IsWorking = true;
            MTProtoService.SendPaymentFormAsync(PaymentInfo.Message.Id, validatedInfoId, shippingOptionId, paymentCredentials,
                                                result => Execute.BeginOnUIThread(() =>
            {
                IsWorking          = false;
                PaymentInfo.Result = result;
                NavigateToNextStep();
            }),
                                                error => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;
            }));
        }
        public void Handle(DownloadableItem item)
        {
            var webPage = item.Owner as TLWebPage;

            if (webPage != null)
            {
                Execute.BeginOnUIThread(() =>
                {
                    var messages = UngroupEnumerator(Items).OfType <TLDecryptedMessage>();
                    foreach (var m in messages)
                    {
                        var media = m.Media as TLDecryptedMessageMediaWebPage;
                        if (media != null && media.WebPage == webPage)
                        {
                            media.NotifyOfPropertyChange(() => media.Photo);
                            media.NotifyOfPropertyChange(() => media.Self);
                            break;
                        }
                    }
                });
            }

            var decryptedMessage = item.Owner as TLDecryptedMessage;

            if (decryptedMessage != null)
            {
                var mediaExternalDocument = decryptedMessage.Media as TLDecryptedMessageMediaExternalDocument;
                if (mediaExternalDocument != null)
                {
                    decryptedMessage.NotifyOfPropertyChange(() => decryptedMessage.Self);
                }
            }

            var decryptedMedia = item.Owner as TLDecryptedMessageMediaBase;

            if (decryptedMedia != null)
            {
                decryptedMessage = UngroupEnumerator(Items).OfType <TLDecryptedMessage>().FirstOrDefault(x => x.Media == decryptedMedia);
                if (decryptedMessage != null)
                {
                    var mediaPhoto = decryptedMessage.Media as TLDecryptedMessageMediaPhoto;
                    if (mediaPhoto != null)
                    {
                        mediaPhoto.DownloadingProgress = 1.0;
                        var fileName = item.IsoFileName;
                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            byte[] buffer;
                            using (var file = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                            {
                                buffer = new byte[file.Length];
                                file.Read(buffer, 0, buffer.Length);
                            }
                            var fileLocation = decryptedMessage.Media.File as TLEncryptedFile;
                            if (fileLocation == null)
                            {
                                return;
                            }
                            var decryptedBuffer = Telegram.Api.Helpers.Utils.AesIge(buffer, mediaPhoto.Key.Data,
                                                                                    mediaPhoto.IV.Data, false);

                            var newFileName = String.Format("{0}_{1}_{2}.jpg",
                                                            fileLocation.Id,
                                                            fileLocation.DCId,
                                                            fileLocation.AccessHash);

                            using (var file = store.OpenFile(newFileName, FileMode.OpenOrCreate, FileAccess.Write))
                            {
                                file.Write(decryptedBuffer, 0, decryptedBuffer.Length);
                            }

                            store.DeleteFile(fileName);
                        }

                        if (!decryptedMedia.IsCanceled)
                        {
                            decryptedMedia.NotifyOfPropertyChange(() => decryptedMedia.Self);
                        }
                    }

                    var mediaVideo = decryptedMessage.Media as TLDecryptedMessageMediaVideo;
                    if (mediaVideo != null)
                    {
                        mediaVideo.DownloadingProgress = 1.0;
                        var fileName = item.IsoFileName;
                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            byte[] buffer;
                            using (var file = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                            {
                                buffer = new byte[file.Length];
                                file.Read(buffer, 0, buffer.Length);
                            }
                            var fileLocation = decryptedMessage.Media.File as TLEncryptedFile;
                            if (fileLocation == null)
                            {
                                return;
                            }
                            var decryptedBuffer = Telegram.Api.Helpers.Utils.AesIge(buffer, mediaVideo.Key.Data, mediaVideo.IV.Data, false);

                            var newFileName = String.Format("{0}_{1}_{2}.mp4",
                                                            fileLocation.Id,
                                                            fileLocation.DCId,
                                                            fileLocation.AccessHash);

                            using (var file = store.OpenFile(newFileName, FileMode.OpenOrCreate, FileAccess.Write))
                            {
                                file.Write(decryptedBuffer, 0, decryptedBuffer.Length);
                            }

                            store.DeleteFile(fileName);
                        }
                    }

                    var mediaDocument = decryptedMessage.Media as TLDecryptedMessageMediaDocument;
                    if (mediaDocument != null)
                    {
                        if (decryptedMessage.IsVoice())
                        {
                            var fileLocation = decryptedMessage.Media.File as TLEncryptedFile;
                            if (fileLocation == null)
                            {
                                return;
                            }

                            var fileName          = item.IsoFileName;
                            var decryptedFileName = String.Format("audio{0}_{1}.mp3",
                                                                  fileLocation.Id,
                                                                  fileLocation.AccessHash);
                            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                            {
                                byte[] buffer;
                                using (var file = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                {
                                    buffer = new byte[file.Length];
                                    file.Read(buffer, 0, buffer.Length);
                                }
                                var decryptedBuffer = Telegram.Api.Helpers.Utils.AesIge(buffer, mediaDocument.Key.Data, mediaDocument.IV.Data, false);

                                using (var file = store.OpenFile(decryptedFileName, FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    file.Write(decryptedBuffer, 0, decryptedBuffer.Length);
                                }

                                store.DeleteFile(fileName);
                            }

                            Telegram.Api.Helpers.Execute.BeginOnUIThread(() =>
                            {
                                MessagePlayerControl.ConvertAndSaveOpusToWav(mediaDocument);

                                mediaDocument.DownloadingProgress = 1.0;
                            });
                        }
                        else if (decryptedMessage.IsVideo())
                        {
                            mediaDocument.DownloadingProgress = 1.0;
                            var fileName = item.IsoFileName;
                            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                            {
                                byte[] buffer;
                                using (var file = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                {
                                    buffer = new byte[file.Length];
                                    file.Read(buffer, 0, buffer.Length);
                                }
                                var fileLocation = decryptedMessage.Media.File as TLEncryptedFile;
                                if (fileLocation == null)
                                {
                                    return;
                                }
                                var decryptedBuffer = Telegram.Api.Helpers.Utils.AesIge(buffer, mediaDocument.Key.Data, mediaDocument.IV.Data, false);

                                var newFileName = String.Format("{0}_{1}_{2}.mp4",
                                                                fileLocation.Id,
                                                                fileLocation.DCId,
                                                                fileLocation.AccessHash);

                                using (var file = store.OpenFile(newFileName, FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    file.Write(decryptedBuffer, 0, decryptedBuffer.Length);
                                }

                                store.DeleteFile(fileName);
                            }
                        }
                        else
                        {
                            mediaDocument.DownloadingProgress = 1.0;
                            var fileName = item.IsoFileName;
                            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                            {
                                byte[] buffer;
                                using (var file = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                {
                                    buffer = new byte[file.Length];
                                    file.Read(buffer, 0, buffer.Length);
                                }
                                var fileLocation = decryptedMessage.Media.File as TLEncryptedFile;
                                if (fileLocation == null)
                                {
                                    return;
                                }
                                var decryptedBuffer = Telegram.Api.Helpers.Utils.AesIge(buffer, mediaDocument.Key.Data, mediaDocument.IV.Data, false);

                                var newFileName = String.Format("{0}_{1}_{2}.{3}",
                                                                fileLocation.Id,
                                                                fileLocation.DCId,
                                                                fileLocation.AccessHash,
                                                                fileLocation.FileExt ?? mediaDocument.FileExt);

                                using (var file = store.OpenFile(newFileName, FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    file.Write(decryptedBuffer, 0, decryptedBuffer.Length);
                                }

                                store.DeleteFile(fileName);
                            }
                        }
                    }

                    var mediaAudio = decryptedMessage.Media as TLDecryptedMessageMediaAudio;
                    if (mediaAudio != null)
                    {
                        var fileLocation = decryptedMessage.Media.File as TLEncryptedFile;
                        if (fileLocation == null)
                        {
                            return;
                        }

                        var fileName          = item.IsoFileName;
                        var decryptedFileName = String.Format("audio{0}_{1}.mp3",
                                                              fileLocation.Id,
                                                              fileLocation.AccessHash);
                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            byte[] buffer;
                            using (var file = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                            {
                                buffer = new byte[file.Length];
                                file.Read(buffer, 0, buffer.Length);
                            }
                            var decryptedBuffer = Telegram.Api.Helpers.Utils.AesIge(buffer, mediaAudio.Key.Data, mediaAudio.IV.Data, false);

                            using (var file = store.OpenFile(decryptedFileName, FileMode.OpenOrCreate, FileAccess.Write))
                            {
                                file.Write(decryptedBuffer, 0, decryptedBuffer.Length);
                            }

                            store.DeleteFile(fileName);
                        }

                        Telegram.Api.Helpers.Execute.BeginOnUIThread(() =>
                        {
                            MessagePlayerControl.ConvertAndSaveOpusToWav(mediaAudio);

                            mediaAudio.DownloadingProgress = 1.0;
                        });
                    }
                }
            }
        }
Example #26
0
        public void Confirm()
        {
            IsWorking = true;
            StateService.PhoneCode = new TLString(Code);
            MTProtoService.VerifyPhoneAsync(
                StateService.PhoneNumber,
                StateService.PhoneCodeHash,
                StateService.PhoneCode,
                auth => BeginOnUIThread(() =>
            {
                TimeCounterString = string.Empty;
                HelpVisibility    = Visibility.Collapsed;
                _callTimer.Stop();

                _isProcessing = false;

                var phoneNumberValue = _phoneNumberValue;
                if (phoneNumberValue == null)
                {
                    var secureRequiredType = _secureRequiredType != null ? _secureRequiredType.DataRequiredType as TLSecureRequiredType : null;
                    var secureType         = secureRequiredType != null && PhoneNumberViewModel.IsValidType(secureRequiredType.Type)
                            ? secureRequiredType.Type
                            : null;

                    // add new phone number from passport settings
                    if (_secureType != null && PhoneNumberViewModel.IsValidType(_secureType))
                    {
                        phoneNumberValue = new TLSecureValue85
                        {
                            Flags = new TLInt(0),
                            Type  = _secureType
                        };
                    }
                    // add new phone number from authorization form
                    else if (secureType != null)
                    {
                        phoneNumberValue = new TLSecureValue85
                        {
                            Flags = new TLInt(0),
                            Type  = secureType
                        };
                    }
                    else
                    {
                        return;
                    }
                }

                IsWorking =
                    PhoneNumberViewModel.SavePhoneAsync(
                        StateService.PhoneNumber, _passwordBase as TLPassword, MTProtoService,
                        result => Execute.BeginOnUIThread(() =>
                {
                    IsWorking = false;
                    if (_authorizationForm != null)
                    {
                        _authorizationForm.Values.Remove(_phoneNumberValue);
                        _authorizationForm.Values.Add(result);
                    }

                    phoneNumberValue.Update(result);
                    phoneNumberValue.NotifyOfPropertyChange(() => phoneNumberValue.Self);

                    if (_secureType != null)
                    {
                        EventAggregator.Publish(new AddSecureValueEventArgs {
                            Values = new List <TLSecureValue> {
                                phoneNumberValue
                            }
                        });
                    }

                    if (_secureRequiredType != null)
                    {
                        _secureRequiredType.UpdateValue();
                    }

                    NavigationService.RemoveBackEntry();
                    NavigationService.GoBack();
                }),
                        error => Execute.BeginOnUIThread(() =>
                {
                    IsWorking = false;

                    if (error.CodeEquals(ErrorCode.BAD_REQUEST) &&
                        error.TypeEquals(ErrorType.PHONE_VERIFICATION_NEEDED))
                    {
                        MTProtoService.SendVerifyPhoneCodeAsync(StateService.PhoneNumber, null,
                                                                sentCode => BeginOnUIThread(() =>
                        {
                            StateService.PhoneCodeHash   = sentCode.PhoneCodeHash;
                            StateService.PhoneRegistered = sentCode.PhoneRegistered;

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

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

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

                                var length = _type as ILength;
                                CodeLength = length != null ? length.Length.Value : Constants.DefaultCodeLength;
                                NotifyOfPropertyChange(() => CodeLength);
                            }
                        }),
                                                                error2 => BeginOnUIThread(() =>
                        {
                            if (error.TypeEquals(ErrorType.PHONE_NUMBER_INVALID))
                            {
                                ShellViewModel.ShowCustomMessageBox(AppResources.PhoneNumberInvalidString, AppResources.Error, AppResources.Ok);
                            }
                            else if (error.CodeEquals(ErrorCode.FLOOD))
                            {
                                ShellViewModel.ShowCustomMessageBox(AppResources.FloodWaitString + Environment.NewLine + "(" + error.Message + ")", AppResources.Error, AppResources.Ok);
                            }
                            else
                            {
                                Telegram.Api.Helpers.Execute.ShowDebugMessage("account.sendVerifyPhoneCode error " + error);
                            }
                        }));
                    }
                }));
            }),
                error => BeginOnUIThread(() =>
            {
                IsWorking = false;
                if (error.TypeEquals(ErrorType.PHONE_CODE_INVALID))
                {
                    ShellViewModel.ShowCustomMessageBox(AppResources.PhoneCodeInvalidString, AppResources.Error, AppResources.Ok);
                }
                else if (error.TypeEquals(ErrorType.PHONE_CODE_EMPTY))
                {
                    ShellViewModel.ShowCustomMessageBox(AppResources.PhoneCodeEmpty, AppResources.Error, AppResources.Ok);
                }
                else if (error.TypeEquals(ErrorType.PHONE_NUMBER_INVALID))
                {
                    ShellViewModel.ShowCustomMessageBox(AppResources.PhoneNumberInvalidString, AppResources.Error, AppResources.Ok);
                }
                else if (error.CodeEquals(ErrorCode.FLOOD))
                {
                    ShellViewModel.ShowCustomMessageBox(AppResources.FloodWaitString + Environment.NewLine + "(" + error.Message + ")", AppResources.Error, AppResources.Ok);
                }
                else
                {
                    Telegram.Api.Helpers.Execute.ShowDebugMessage("account.verifyPhone error " + error);
                }
            }));
        }
        public void Handle(TLUpdateEncryptedMessagesRead update)
        {
            return; //UpdatesService.ProcessUpdateInternal уже обработали там

            if (update != null &&
                Chat != null &&
                update.ChatId.Value == Chat.Id.Value)
            {
                Execute.BeginOnUIThread(() =>
                {
                    for (var i = 0; i < Items.Count; i++)
                    {
                        if (Items[i].Out.Value)
                        {
                            if (Items[i].Status == MessageStatus.Confirmed)
                            //&& Items[i].Date.Value <= update.MaxDate.Value) // здесь надо учитывать смещение по времени
                            {
                                Items[i].Status = MessageStatus.Read;
                                Items[i].NotifyOfPropertyChange("Status");
                                if (Items[i].TTL != null && Items[i].TTL.Value > 0)
                                {
                                    var decryptedMessage = Items[i] as TLDecryptedMessage17;
                                    if (decryptedMessage != null)
                                    {
                                        var decryptedPhoto = decryptedMessage.Media as TLDecryptedMessageMediaPhoto;
                                        if (decryptedPhoto != null && Items[i].TTL.Value <= 60.0)
                                        {
                                            continue;
                                        }

                                        var decryptedVideo17 = decryptedMessage.Media as TLDecryptedMessageMediaVideo17;
                                        if (decryptedVideo17 != null && Items[i].TTL.Value <= 60.0)
                                        {
                                            continue;
                                        }

                                        var decryptedAudio17 = decryptedMessage.Media as TLDecryptedMessageMediaAudio17;
                                        if (decryptedAudio17 != null && Items[i].TTL.Value <= 60.0)
                                        {
                                            continue;
                                        }

                                        var decryptedDocument45 = decryptedMessage.Media as TLDecryptedMessageMediaDocument45;
                                        if (decryptedDocument45 != null && (Items[i].IsVoice() || Items[i].IsVideo()) && Items[i].TTL.Value <= 60.0)
                                        {
                                            continue;
                                        }
                                    }

                                    Items[i].DeleteDate = new TLLong(DateTime.Now.Ticks + Chat.MessageTTL.Value * TimeSpan.TicksPerSecond);
                                }
                            }
                            else if (Items[i].Status == MessageStatus.Read)
                            {
                                break;
                            }
                        }
                    }
                });
            }
        }
        public void Handle(TLDecryptedMessageBase decryptedMessage)
        {
            if (Chat != null &&
                decryptedMessage.ChatId.Value == Chat.Id.Value)
            {
                System.Diagnostics.Debug.WriteLine("Handle random_id={0} date={1} qts={2}", decryptedMessage.RandomId, decryptedMessage.Date, decryptedMessage.Qts);

                var serviceMessage = decryptedMessage as TLDecryptedMessageService;
                if (serviceMessage != null)
                {
                    var action = serviceMessage.Action;

                    var typingAction = action as TLDecryptedMessageActionTyping;
                    if (typingAction != null)
                    {
                        var cancelAction = typingAction.Action as TLSendMessageCancelAction;
                        if (cancelAction != null)
                        {
                            InputTypingManager.RemoveTypingUser(With.Index);
                        }
                        else
                        {
                            InputTypingManager.AddTypingUser(With.Index, typingAction.Action);
                        }
                    }

                    var setMessageTTLAction = action as TLDecryptedMessageActionSetMessageTTL;
                    if (setMessageTTLAction != null)
                    {
                        Chat.MessageTTL = setMessageTTLAction.TTLSeconds;
                    }

                    var flushHistoryAction = action as TLDecryptedMessageActionFlushHistory;
                    if (flushHistoryAction != null)
                    {
                        Execute.BeginOnUIThread(() => Items.Clear());
                        CacheService.ClearDecryptedHistoryAsync(Chat.Id);
                    }

                    var readMessagesAction = action as TLDecryptedMessageActionReadMessages;
                    if (readMessagesAction != null)
                    {
                        Execute.BeginOnUIThread(() =>
                        {
                            foreach (var randomId in readMessagesAction.RandomIds)
                            {
                                foreach (var item in UngroupEnumerator(Items))
                                {
                                    if (item.RandomId.Value == randomId.Value)
                                    {
                                        item.Status = MessageStatus.Read;
                                        if (item.TTL != null && item.TTL.Value > 0)
                                        {
                                            item.DeleteDate = new TLLong(DateTime.Now.Ticks + Chat.MessageTTL.Value * TimeSpan.TicksPerSecond);
                                        }

                                        var decryptedMessage17 = item as TLDecryptedMessage17;
                                        if (decryptedMessage17 != null)
                                        {
                                            var decryptedMediaPhoto = decryptedMessage17.Media as TLDecryptedMessageMediaPhoto;
                                            if (decryptedMediaPhoto != null)
                                            {
                                                if (decryptedMediaPhoto.TTLParams == null)
                                                {
                                                    var ttlParams       = new TTLParams();
                                                    ttlParams.IsStarted = true;
                                                    ttlParams.Total     = decryptedMessage17.TTL.Value;
                                                    ttlParams.StartTime = DateTime.Now;
                                                    ttlParams.Out       = decryptedMessage17.Out.Value;

                                                    decryptedMediaPhoto.TTLParams = ttlParams;
                                                }
                                            }

                                            var decryptedMediaVideo17 = decryptedMessage17.Media as TLDecryptedMessageMediaVideo17;
                                            if (decryptedMediaVideo17 != null)
                                            {
                                                if (decryptedMediaVideo17.TTLParams == null)
                                                {
                                                    var ttlParams       = new TTLParams();
                                                    ttlParams.IsStarted = true;
                                                    ttlParams.Total     = decryptedMessage17.TTL.Value;
                                                    ttlParams.StartTime = DateTime.Now;
                                                    ttlParams.Out       = decryptedMessage17.Out.Value;

                                                    decryptedMediaVideo17.TTLParams = ttlParams;
                                                }
                                            }

                                            var decryptedMediaAudio17 = decryptedMessage17.Media as TLDecryptedMessageMediaAudio17;
                                            if (decryptedMediaAudio17 != null)
                                            {
                                                if (decryptedMediaAudio17.TTLParams == null)
                                                {
                                                    var ttlParams       = new TTLParams();
                                                    ttlParams.IsStarted = true;
                                                    ttlParams.Total     = decryptedMessage17.TTL.Value;
                                                    ttlParams.StartTime = DateTime.Now;
                                                    ttlParams.Out       = decryptedMessage17.Out.Value;

                                                    decryptedMediaAudio17.TTLParams = ttlParams;
                                                }
                                            }

                                            var decryptedMediaDocument45 = decryptedMessage17.Media as TLDecryptedMessageMediaDocument45;
                                            if (decryptedMediaDocument45 != null && (decryptedMessage17.IsVoice() || decryptedMessage17.IsVideo()))
                                            {
                                                if (decryptedMediaDocument45.TTLParams == null)
                                                {
                                                    var ttlParams       = new TTLParams();
                                                    ttlParams.IsStarted = true;
                                                    ttlParams.Total     = decryptedMessage17.TTL.Value;
                                                    ttlParams.StartTime = DateTime.Now;
                                                    ttlParams.Out       = decryptedMessage17.Out.Value;

                                                    decryptedMediaDocument45.TTLParams = ttlParams;
                                                }

                                                var message45 = decryptedMessage17 as TLDecryptedMessage45;
                                                if (message45 != null)
                                                {
                                                    message45.SetListened();
                                                }
                                                decryptedMediaDocument45.NotListened = false;
                                                decryptedMediaDocument45.NotifyOfPropertyChange(() => decryptedMediaDocument45.NotListened);
                                            }
                                        }

                                        item.NotifyOfPropertyChange(() => item.Status);
                                        break;
                                    }
                                }
                            }
                        });
                    }

                    var deleteMessagesAction = action as TLDecryptedMessageActionDeleteMessages;
                    if (deleteMessagesAction != null)
                    {
                        Execute.BeginOnUIThread(() =>
                        {
                            var group = new Dictionary <long, TLDecryptedMessageMediaGroup>();
                            foreach (var randomId in deleteMessagesAction.RandomIds)
                            {
                                for (var i = 0; i < Items.Count; i++)
                                {
                                    var groupedMessage = false;
                                    var message73      = Items[i] as TLDecryptedMessage73;
                                    if (message73 != null && message73.GroupedId != null)
                                    {
                                        var mediaGroup = message73.Media as TLDecryptedMessageMediaGroup;
                                        if (mediaGroup != null)
                                        {
                                            groupedMessage = true;
                                            for (var k = 0; k < mediaGroup.Group.Count; k++)
                                            {
                                                if (mediaGroup.Group[k].RandomId.Value == randomId.Value)
                                                {
                                                    mediaGroup.Group.RemoveAt(k);
                                                    if (mediaGroup.Group.Count == 0)
                                                    {
                                                        Items.Remove(message73);
                                                    }
                                                    else
                                                    {
                                                        group[message73.GroupedId.Value] = mediaGroup;
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                    }

                                    if (!groupedMessage && Items[i].RandomId.Value == randomId.Value)
                                    {
                                        Items.RemoveAt(i);
                                        break;
                                    }
                                }
                            }

                            foreach (var mediaGroup in group.Values)
                            {
                                mediaGroup.RaiseCalculate();
                            }

                            CacheService.DeleteDecryptedMessages(deleteMessagesAction.RandomIds);
                        });
                    }
                }

                if (!TLUtils.IsDisplayedDecryptedMessage(decryptedMessage))
                {
                    return;
                }

                ProcessMessages(new List <TLDecryptedMessageBase> {
                    decryptedMessage
                });

                Execute.OnUIThread(() =>
                {
                    var addedGrouped = false;
                    var message73    = decryptedMessage as TLDecryptedMessage73;
                    if (message73 != null && message73.GroupedId != null && Items.Count > 0)
                    {
                        var previousMessage = Items[0] as TLDecryptedMessage73;
                        if (previousMessage != null &&
                            previousMessage.GroupedId != null &&
                            previousMessage.GroupedId.Value == message73.GroupedId.Value)
                        {
                            Items.RemoveAt(0);
                            var items      = new List <TLDecryptedMessageBase>();
                            var mediaGroup = previousMessage.Media as TLDecryptedMessageMediaGroup;
                            if (mediaGroup != null)
                            {
                                items.Add(message73);

                                for (var i = mediaGroup.Group.Count - 1; i >= 0; i--)
                                {
                                    items.Add(mediaGroup.Group[i]);
                                }
                            }
                            else
                            {
                                items.Add(message73);
                                items.Add(previousMessage);
                            }

                            ProcessGroupedMessages(items);

                            for (var j = 0; j < items.Count; j++)
                            {
                                InsertMessageInOrder(items[j]);
                            }

                            addedGrouped = true;
                        }
                    }

                    var position = -1;
                    if (!addedGrouped)
                    {
                        position = InsertMessageInOrder(decryptedMessage);
                        System.Diagnostics.Debug.WriteLine("Handle.Insert random_id={0} date={1} position={2}", decryptedMessage.RandomId, decryptedMessage.Date, position);
                    }
                    else
                    {
                        position = 0;
                    }
                    NotifyOfPropertyChange(() => DescriptionVisibility);

                    if (position != -1)
                    {
                        ReadMessages(decryptedMessage);
                        if (decryptedMessage is TLDecryptedMessage)
                        {
                            InputTypingManager.RemoveTypingUser(With.Index);
                        }
                    }
                });
            }
        }
 protected override void BeginOnUIThread(Action action)
 {
     // This is somehow needed because this viewmodel requires a Dispatcher
     // in some situations where base one might be null.
     Execute.BeginOnUIThread(action);
 }
Example #30
0
        public async Task LoadContactsAsync()
        {
            //var contacts = CacheService.GetContacts();
            //foreach (var item in contacts.OfType<TLUser>())
            //{
            //    var user = item as TLUser;
            //    if (user.IsSelf)
            //    {
            //        continue;
            //    }

            //    //var status = LastSeenHelper.GetLastSeen(user);
            //    //var listItem = new UsersPanelListItem(user as TLUser);
            //    //listItem.fullName = user.FullName;
            //    //listItem.lastSeen = status.Item1;
            //    //listItem.lastSeenEpoch = status.Item2;
            //    //listItem.Photo = listItem._parent.Photo;
            //    //listItem.PlaceHolderColor = BindConvert.Current.Bubble(listItem._parent.Id);

            //    Items.Add(user);
            //}

            var contacts = new TLUser[0];

            var input = string.Join(",", contacts.Select(x => x.Id).Union(new[] { SettingsHelper.UserId }).OrderBy(x => x));
            var hash  = Utils.ComputeMD5(input);
            var hex   = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();

            var response = await ProtoService.GetContactsAsync(hex);

            if (response.IsSucceeded)
            {
                var result = response.Result as TLContactsContacts;
                if (result != null)
                {
                    Execute.BeginOnUIThread(() =>
                    {
                        foreach (var item in result.Users.OfType <TLUser>())
                        {
                            var user = item as TLUser;
                            if (user.IsSelf)
                            {
                                continue;
                            }

                            //var status = LastSeenHelper.GetLastSeen(user);
                            //var listItem = new UsersPanelListItem(user as TLUser);
                            //listItem.fullName = user.FullName;
                            //listItem.lastSeen = status.Item1;
                            //listItem.lastSeenEpoch = status.Item2;
                            //listItem.Photo = listItem._parent.Photo;
                            //listItem.PlaceHolderColor = BindConvert.Current.Bubble(listItem._parent.Id);

                            Items.Add(user);
                        }
                    });

                    if (ApplicationSettings.Current.IsContactsSyncEnabled)
                    {
                        await _contactsService.SyncContactsAsync(response.Result);
                    }
                }
            }

            Aggregator.Subscribe(this);
        }