public void Done() { Execute.BeginOnUIThread(TimeSpan.FromSeconds(0.1), () => { if (!PasscodeUtils.Check(Passcode)) { Passcode = string.Empty; RaisePasscodeIncorrect(); return; } var frame = Application.Current.RootVisual as TelegramTransitionFrame; if (frame != null) { Execute.BeginOnUIThread(() => { frame.CloseLockscreen(); PasscodeUtils.Unlock(); // will not invoke here ShellViewModel.UpdateDeviceLockedAsync() var shellViewModel = IoC.Get <ShellViewModel>(); if (shellViewModel != null) { shellViewModel.NotifyOfPropertyChange(() => shellViewModel.PasscodeImageBrush); shellViewModel.NotifyOfPropertyChange(() => shellViewModel.PasscodeImageSource); shellViewModel.UpdateDeviceLockedAsync(); } Passcode = string.Empty; }); } }); }
public void Handle(TLUpdateUserName userName) { Execute.BeginOnUIThread(() => { for (var i = 0; i < Items.Count; i++) { if (Items[i].WithId == userName.UserId.Value && Items[i].With is TLUserBase) { var user = (TLUserBase)Items[i].With; user.FirstName = userName.FirstName; user.LastName = userName.LastName; var userWithUserName = user as IUserName; if (userWithUserName != null) { userWithUserName.UserName = userName.UserName; } Items[i].NotifyOfPropertyChange(() => Items[i].With); break; } } }); }
public void ShowMessagesInfo(int limit = 15, Action <string> callback = null) { MTProtoService.GetSendingQueueInfoAsync(queueInfo => { var info = new StringBuilder(); info.AppendLine("Queue: "); info.AppendLine(queueInfo); var dialogMessages = Items.Take(limit); info.AppendLine("Dialog: "); var count = 0; foreach (var dialogMessage in dialogMessages) { info.AppendLine(" " + count++ + " " + dialogMessage); } //dialogMessages = CacheService.GetHistory(new TLInt(StateService.CurrentUserId), TLUtils.InputPeerToPeer(Peer, StateService.CurrentUserId), limit); dialogMessages = CacheService.GetDecryptedHistory(Chat.Index); info.AppendLine(); info.AppendLine("Database: "); count = 0; foreach (var dialogMessage in dialogMessages) { info.AppendLine(" " + count++ + " " + dialogMessage); } var infoString = info.ToString(); Execute.BeginOnUIThread(() => MessageBox.Show(infoString)); callback.SafeInvoke(infoString); }); }
public void GetContactsAsync(System.Action callback) { var savedCount = TLUtils.OpenObjectFromMTProtoFile <TLInt>(_savedCountSyncRoot, Constants.SavedCountFileName); var hash = TLUtils.GetContactsHash(savedCount, CacheService.GetContacts().Where(x => x.IsContact).OrderBy(x => x.Index).ToList()); IsWorking = true; MTProtoService.GetContactsAsync(new TLInt(hash), result => Execute.BeginOnUIThread(() => { Execute.ShowDebugMessage(result.ToString()); IsWorking = false; var contacts = result as TLContacts71; if (contacts != null) { TLUtils.SaveObjectToMTProtoFile(_savedCountSyncRoot, Constants.SavedCountFileName, contacts.SavedCount); InsertContacts(contacts.Users); } var contactsNotModified = result as TLContactsNotModified; if (contactsNotModified != null) { } callback.SafeInvoke(); }), error => Execute.BeginOnUIThread(() => { IsWorking = false; Execute.ShowDebugMessage("contacts.getContacts error: " + error); callback.SafeInvoke(); })); }
public void Handle(TLUpdatePrivacy update) { if (update.Key is TLPrivacyKeyStatusTimestamp) { Execute.ShowDebugMessage("update privacy"); MTProtoService.GetStatusesAsync( statuses => Execute.BeginOnUIThread(() => { try { for (var i = 0; i < Items.Count; i++) { Items[i].NotifyOfPropertyChange(() => Items[i].StatusCommon); } _lastUpdateStatusesTime = DateTime.Now; } catch (Exception e) { Execute.ShowDebugMessage("UpdateStatuses ex " + e); } }), error => { Execute.ShowDebugMessage("contacts.getStatuses error " + error); }); } }
private void UpdateChannels() { MTProtoService.GetChannelDialogsAsync(new TLInt(0), new TLInt(100), results => Execute.BeginOnUIThread(() => { AddChannels(results); }), error => Execute.BeginOnUIThread(() => { Execute.ShowDebugMessage("channels.getDialogs error " + error); })); }
public void Delete() { if (CurrentItem == null) { return; } if (DialogDetails == null) { return; } var currentItem = CurrentItem; DialogDetails.DeleteMessageById( currentItem, () => { Execute.BeginOnUIThread(TimeSpan.FromSeconds(0.1), () => { if (CanSlideRight) { var view = GetView() as ImageViewerView; if (view != null) { _items.RemoveAt(_currentIndex--); view.SlideRight(0.0, () => { view.SetControlContent(2, NextItem); GroupedItems.Remove(currentItem); }); } } else if (CanSlideLeft) { var view = GetView() as ImageViewerView; if (view != null) { _items.RemoveAt(_currentIndex); view.SlideLeft(0.0, () => { view.SetControlContent(0, PreviousItem); GroupedItems.Remove(currentItem); }); } } else { Execute.BeginOnUIThread(TimeSpan.FromSeconds(0.25), CloseViewer); } }); }); }
public void GetDHConfig() { if (_dhConfig != null) { return; } _isGettingConfig = true; MTProtoService.GetDHConfigAsync(new TLInt(0), new TLInt(0), result => { var dhConfig = result as TLDHConfig; if (dhConfig == null) { return; } if (!TLUtils.CheckPrime(dhConfig.P.Data, dhConfig.G.Value)) { return; } var aBytes = new byte[256]; var random = new SecureRandom(); random.NextBytes(aBytes); var gaBytes = Telegram.Api.Services.MTProtoService.GetGB(aBytes, dhConfig.G, dhConfig.P); dhConfig.A = TLString.FromBigEndianData(aBytes); dhConfig.GA = TLString.FromBigEndianData(gaBytes); _isGettingConfig = false; Execute.BeginOnUIThread(() => { _dhConfig = dhConfig; if (_contact != null) { UserAction(_contact); } }); }, error => { _isGettingConfig = false; IsWorking = false; NotifyOfPropertyChange(() => IsNotWorking); NotifyOfPropertyChange(() => ProgressVisibility); Execute.ShowDebugMessage("messages.getDhConfig error: " + error); }); }
public void Handle(UpdateCompletedEventArgs args) { var dialogs = CacheService.GetDialogs(); Execute.BeginOnUIThread(() => { Items.Clear(); foreach (var dialog in dialogs) { Items.Add(dialog); } }); }
public void Handle(UploadableItem item) { var userBase = item.Owner as TLUserBase; if (userBase != null && userBase.IsSelf) { Execute.BeginOnUIThread(() => { IsWorking = false; CurrentItem.NotifyOfPropertyChange(() => CurrentItem.Photo); }); } }
private void SetRead(params TLDecryptedMessageBase[] messages) { var dialog = CacheService.GetEncryptedDialog(Chat.Id) as TLEncryptedDialog; // input messages, no need to update UI messages.ForEach(x => { if (x.TTL != null && x.TTL.Value > 0) { var decryptedMessage = x as TLDecryptedMessage17; if (decryptedMessage != null) { var decryptedPhoto = decryptedMessage.Media as TLDecryptedMessageMediaPhoto; if (decryptedPhoto != null && x.TTL.Value <= 60.0) { return; } var decryptedVideo17 = decryptedMessage.Media as TLDecryptedMessageMediaVideo17; if (decryptedVideo17 != null && x.TTL.Value <= 60.0) { return; } var decryptedAudio17 = decryptedMessage.Media as TLDecryptedMessageMediaAudio17; if (decryptedAudio17 != null && x.TTL.Value <= 60.0) { return; } } x.DeleteDate = new TLLong(DateTime.Now.Ticks + Chat.MessageTTL.Value * TimeSpan.TicksPerSecond); } x.Unread = TLBool.False; x.Status = MessageStatus.Read; CacheService.SyncDecryptedMessage(x, Chat, r => { }); }); Execute.BeginOnUIThread(() => { if (dialog != null) { dialog.UnreadCount = new TLInt(0); dialog.NotifyOfPropertyChange(() => dialog.UnreadCount); dialog.NotifyOfPropertyChange(() => dialog.TopMessage); dialog.NotifyOfPropertyChange(() => dialog.Self); CacheService.Commit(); } }); }
private static async void SaveFileAsync(string fileName, string fileExt, Action <string> callback = null) { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { if (store.FileExists(fileName)) { using (var fileStream = store.OpenFile(fileName, FileMode.Open)) { var telegramFolder = await KnownFolders.PicturesLibrary.CreateFolderAsync(Constants.TelegramFolderName, CreationCollisionOption.OpenIfExists); if (telegramFolder == null) { return; } var ext = fileExt.StartsWith(".") ? fileExt : "." + fileExt; var storageFile = await telegramFolder.CreateFileAsync(Guid.NewGuid() + ext, CreationCollisionOption.ReplaceExisting); var stopwatch1 = Stopwatch.StartNew(); using (var storageStream = await storageFile.OpenStreamForWriteAsync()) { fileStream.CopyTo(storageStream); } if (callback != null) { callback.Invoke(storageFile.Path); } else { var elapsed1 = stopwatch1.Elapsed; //var stopwatch2 = Stopwatch.StartNew(); ////using (var storageStream = await storageFile.OpenStreamForWriteAsync()) //using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) //{ // await RandomAccessStream.CopyAndCloseAsync(fileStream.AsInputStream(), storageStream.GetOutputStreamAt(0)); //} //var elapsed2 = stopwatch2.Elapsed; Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.SaveFileMessage #if DEBUG + "\n Time: " + elapsed1 //+ "\n Time2: " + elapsed2 #endif )); } } } } }
public void LoadNextSlice() { if (LazyItems.Count > 0 || IsLastSliceLoaded || IsWorking) { return; } IsWorking = true; var offset = Items.Count; var limit = 30; MTProtoService.GetDialogsAsync( #if LAYER_40 new TLInt(offset), new TLInt(limit), #else new TLInt(0), new TLInt(_maxId), new TLInt(limit), #endif result => Execute.BeginOnUIThread(() => { var lastDialog = result.Dialogs.LastOrDefault(x => x.TopMessageId != null); if (lastDialog != null) { _maxId = lastDialog.TopMessageId.Value; } var itemsAdded = 0; foreach (var dialog in result.Dialogs) { if (!SkipDialog(_bot, dialog)) { Items.Add(dialog); itemsAdded++; } } IsWorking = false; IsLastSliceLoaded = result.Dialogs.Count < limit; Status = LazyItems.Count > 0 || Items.Count > 0 ? string.Empty : Status; if (itemsAdded < (Constants.DialogsSlice / 2)) { LoadNextSlice(); } }), error => Execute.BeginOnUIThread(() => { IsWorking = false; Status = string.Empty; })); }
public void Handle(InvokeDeleteContacts message) { var id = new TLVector <TLInputUserBase>(CacheService.GetContacts().Where(x => x.IsContact).Select(x => x.ToInputUser()).ToList()); MTProtoService.DeleteContactsAsync(id, result => Execute.BeginOnUIThread(() => { Handle(Commands.LogOutCommand); Handle(new InvokeImportContacts()); }), error => Execute.BeginOnUIThread(() => { })); }
private void RestoreConnectionAsync() { Execute.BeginOnThreadPool(() => { var isAuthorized = SettingsHelper.GetValue <bool>(Constants.IsAuthorizedKey); if (!isAuthorized) { return; } Execute.BeginOnUIThread(() => { var mtProtoService = IoC.Get <IMTProtoService>(); //mtProtoService.PingAsync(TLLong.Random(), result => { }, error => { }); mtProtoService.UpdateStatusAsync(TLBool.False, result => { }, error => { }); }); }); }
public void LogOut() { var result = MessageBox.Show(AppResources.LogOutConfirmation, AppResources.Confirm, MessageBoxButton.OKCancel); if (result != MessageBoxResult.OK) { return; } Telegram.Logs.Log.Write("SettingsViewModel.LogOut"); PushService.UnregisterDeviceAsync(() => MTProtoService.LogOutAsync(logOutResult => { ContactsHelper.DeleteContactsAsync(null); Execute.BeginOnUIThread(() => { foreach (var activeTile in ShellTile.ActiveTiles) { if (activeTile.NavigationUri.ToString().Contains("Action=SecondaryTile")) { activeTile.Delete(); } } }); //MTProtoService.LogOutTransportsAsync( // () => // { // }, // errors => // { // }); }, error => { Execute.ShowDebugMessage("account.logOut error " + error); })); LogOutCommon(EventAggregator, MTProtoService, UpdateService, CacheService, StateService, PushService, NavigationService); }
private void LoadStateAndUpdateAsync() { Execute.BeginOnThreadPool(() => { var isAuthorized = SettingsHelper.GetValue <bool>(Constants.IsAuthorizedKey); if (!isAuthorized) { return; } Execute.BeginOnUIThread(() => { var mtProtoService = IoC.Get <IMTProtoService>(); var stateService = IoC.Get <IStateService>(); var updatesService = IoC.Get <IUpdatesService>(); updatesService.GetCurrentUserId = () => mtProtoService.CurrentUserId; updatesService.GetStateAsync = mtProtoService.GetStateAsync; updatesService.GetDHConfigAsync = mtProtoService.GetDHConfigAsync; updatesService.GetDifferenceAsync = mtProtoService.GetDifferenceAsync; updatesService.AcceptEncryptionAsync = mtProtoService.AcceptEncryptionAsync; updatesService.SendEncryptedServiceAsync = mtProtoService.SendEncryptedServiceAsync; updatesService.SetMessageOnTimeAsync = mtProtoService.SetMessageOnTime; //updatesService.RemoveFromQueue = mtProtoService.RemoveFromQueue; updatesService.UpdateChannelAsync = mtProtoService.UpdateChannelAsync; updatesService.GetParticipantAsync = mtProtoService.GetParticipantAsync; updatesService.GetFullChatAsync = mtProtoService.GetFullChatAsync; stateService.SuppressNotifications = true; var timer = Stopwatch.StartNew(); TLUtils.WritePerformance(">>UpdateService.LoadStateAndUpdate start"); //mtProtoService.SetMessageOnTime(60.0 * 5, AppResources.Updating + "..."); updatesService.LoadStateAndUpdate( () => { //mtProtoService.SetMessageOnTime(0.0, string.Empty); TLUtils.WritePerformance(">>UpdateService.LoadStateAndUpdate stop " + timer.Elapsed); stateService.SuppressNotifications = false; }); }); }); }
public void Search() { var text = Text; if (string.IsNullOrEmpty(text.Trim())) { Items.Clear(); Status = string.IsNullOrEmpty(text.Trim()) ? AppResources.SearchAmongYourDialogsAndMessages : AppResources.NoResults; return; } Execute.BeginOnUIThread(TimeSpan.FromSeconds(0.5), () => { if (!string.Equals(text, Text, StringComparison.OrdinalIgnoreCase)) { return; } Search(Text); }); }
private void ReportAsync(TLInputPeerBase inputPeer, TLVector <TLInt> id, TLInputReportReasonBase reason) { if (inputPeer == null) { return; } if (reason == null) { return; } if (id == null) { IsWorking = true; MTProtoService.ReportPeerAsync(inputPeer, reason, result => Execute.BeginOnUIThread(() => { IsWorking = false; MessageBox.Show(AppResources.ReportSpamNotification, AppResources.AppName, MessageBoxButton.OK); }), error => Execute.BeginOnUIThread(() => { IsWorking = false; })); } else { IsWorking = true; MTProtoService.ReportAsync(inputPeer, id, reason, result => Execute.BeginOnUIThread(() => { IsWorking = false; MessageBox.Show(AppResources.ReportSpamNotification, AppResources.AppName, MessageBoxButton.OK); }), error => Execute.BeginOnUIThread(() => { IsWorking = false; })); } }
private bool CheckBatterySaverState() { #if WP8 // The minimum phone version that supports the PowerSavingModeEnabled property var targetVersion = new Version(8, 0, 10492); //if (Environment.OSVersion.Version >= targetVersion) { // Use reflection to get the PowerSavingModeEnabled value //var powerSaveEnabled = (bool) typeof(PowerManager).GetProperty("PowerSavingModeEnabled").GetValue(null, null); var powerSaveOn = PowerManager.PowerSavingMode == PowerSavingMode.On; if (powerSaveOn) { Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.BatterySaverModeAlert, AppResources.Warning, MessageBoxButton.OK)); return(true); } return(false); } #endif return(true); }
public void Handle(TLEncryptedChatBase chat) { Execute.BeginOnUIThread(() => { int index = -1; TLDialogBase dialog = null; for (int i = 0; i < Items.Count; i++) { if (Items[i].Peer is TLPeerEncryptedChat && Items[i].Peer.Id.Value == chat.Id.Value) { index = i; dialog = Items[i]; break; } } if (index != -1 && dialog != null) { dialog.NotifyOfPropertyChange(() => dialog.Self); } }); }
public static void SavePhoto(string photoFileName, Action <string> callback = null) { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { if (store.FileExists(photoFileName)) { using (var fileStream = store.OpenFile(photoFileName, FileMode.Open)) { var photoUrl = Guid.NewGuid().ToString(); //.jpg will be added automatically var mediaLibrary = new MediaLibrary(); var photoFile = mediaLibrary.SavePicture(photoUrl, fileStream); if (callback != null) { } else { Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.SavePhotoMessage)); } } } } }
public static void SendEncrypted(TLEncryptedChat chat, TLObject obj, IMTProtoService mtProtoService, ICacheService cacheService) { var message = GetDecryptedMessage(obj); if (message == null) { return; } cacheService.SyncDecryptedMessage(message, chat, cachedMessage => { mtProtoService.SendEncryptedAsync(new TLInputEncryptedChat { AccessHash = chat.AccessHash, ChatId = chat.Id }, message.RandomId, TLUtils.EncryptMessage(obj, mtProtoService.CurrentUserId, chat), result => Execute.BeginOnUIThread(() => { message.Status = MessageStatus.Confirmed; message.NotifyOfPropertyChange(() => message.Status); cacheService.SyncSendingDecryptedMessage(chat.Id, result.Date, message.RandomId, m => { }); }), () => { //message.Date = result.Date; message.Status = MessageStatus.Confirmed; message.NotifyOfPropertyChange(() => message.Status); }, error => { message.Status = MessageStatus.Failed; message.NotifyOfPropertyChange(() => message.Status); Execute.ShowDebugMessage("messages.sendEncrypted error " + error); }); }); }
public void RecoverPassword() { if (_passwordBase == null) { return; } if (IsWorking) { return; } HasError = false; Error = string.Empty; IsWorking = true; MTProtoService.RecoverPasswordAsync(new TLString(Code), auth => BeginOnUIThread(() => { IsWorking = false; if (!_passwordBase.IsAuthRecovery) { MTProtoService.GetPasswordAsync( passwordResult => BeginOnUIThread(() => { MessageBox.Show(AppResources.PasswordDeactivated, AppResources.AppName, MessageBoxButton.OK); StateService.RemoveBackEntry = true; StateService.Password = passwordResult; NavigationService.UriFor <PasswordViewModel>().Navigate(); }), error2 => { Execute.ShowDebugMessage("account.getPassword error " + error2); }); } else { _passwordBase.IsAuthRecovery = false; #if LOG_REGISTRATION TLUtils.WriteLog("auth.recoverPassword result " + auth); TLUtils.WriteLog("TLUtils.IsLogEnabled=false"); #endif TLUtils.IsLogEnabled = false; TLUtils.LogItems.Clear(); var result = MessageBox.Show( AppResources.ConfirmPushMessage, AppResources.ConfirmPushTitle, MessageBoxButton.OKCancel); if (result != MessageBoxResult.OK) { Notifications.Disable(); } else { Notifications.Enable(); } ConfirmViewModel.UpdateNotificationsAsync(MTProtoService, StateService); MTProtoService.SetInitState(); StateService.CurrentUserId = auth.User.Index; StateService.FirstRun = true; SettingsHelper.SetValue(Constants.IsAuthorizedKey, true); ShellViewModel.Navigate(NavigationService); } }), error => BeginOnUIThread(() => { IsWorking = false; var messageBuilder = new StringBuilder(); //messageBuilder.AppendLine(AppResources.Error); //messageBuilder.AppendLine(); messageBuilder.AppendLine("Method: account.recoveryPassword"); messageBuilder.AppendLine("Result: " + error); if (TLRPCError.CodeEquals(error, ErrorCode.FLOOD)) { HasError = true; Error = AppResources.FloodWaitString; Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.FloodWaitString, AppResources.Error, MessageBoxButton.OK)); } else if (TLRPCError.CodeEquals(error, ErrorCode.INTERNAL)) { HasError = true; Error = AppResources.ServerError; Execute.BeginOnUIThread(() => MessageBox.Show(messageBuilder.ToString(), AppResources.ServerError, MessageBoxButton.OK)); } else if (TLRPCError.CodeEquals(error, ErrorCode.BAD_REQUEST)) { if (TLRPCError.TypeEquals(error, ErrorType.CODE_EMPTY)) { HasError = true; Error = string.Format("{0} {1}", error.Code, error.Message); Execute.BeginOnUIThread(() => MessageBox.Show(messageBuilder.ToString(), AppResources.Error, MessageBoxButton.OK)); } else if (TLRPCError.TypeEquals(error, ErrorType.CODE_INVALID)) { HasError = true; Error = string.Format("{0} {1}", error.Code, error.Message); Execute.BeginOnUIThread(() => MessageBox.Show(messageBuilder.ToString(), AppResources.Error, MessageBoxButton.OK)); } else if (TLRPCError.TypeEquals(error, ErrorType.PASSWORD_EMPTY)) { HasError = true; Error = string.Format("{0} {1}", error.Code, error.Message); Execute.BeginOnUIThread(() => MessageBox.Show(messageBuilder.ToString(), AppResources.Error, MessageBoxButton.OK)); } else if (TLRPCError.TypeEquals(error, ErrorType.PASSWORD_RECOVERY_NA)) { HasError = true; Error = AppResources.EmailInvalid; Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.EmailInvalid, AppResources.Error, MessageBoxButton.OK)); } else if (TLRPCError.TypeEquals(error, ErrorType.PASSWORD_RECOVERY_EXPIRED)) { HasError = true; Error = string.Format("{0} {1}", error.Code, error.Message); Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.EmailInvalid, AppResources.Error, MessageBoxButton.OK)); } else { HasError = true; Error = string.Format("{0} {1}", error.Code, error.Message); Execute.BeginOnUIThread(() => MessageBox.Show(messageBuilder.ToString(), AppResources.Error, MessageBoxButton.OK)); } } else { HasError = true; Error = string.Empty; Execute.ShowDebugMessage("account.recoveryPassword error " + error); } })); }
private void RecordButton_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (!IsHitTestVisible) { return; } var microphoneState = _microphone != null ? _microphone.State : (MicrophoneState?)null; if (microphoneState == MicrophoneState.Started) { return; } if (_isHintStoryboardPlaying) { return; } Log(string.Format("microphone_state={0} storyboard_state={1}", microphoneState, _isHintStoryboardPlaying)); if (Component == null) { return; } if (_asyncDispatcher == null) { _asyncDispatcher = new XnaAsyncDispatcher(TimeSpan.FromMilliseconds(33), OnTimerTick); } if (SliderPanel == null) { SliderPanel = CreateSliderPanel(); LayoutRoot.Children.Add(SliderPanel); } if (TimerPanel == null) { TimerPanel = CreateTimerPanel(); LayoutRoot.Children.Add(TimerPanel); } if (_microphone == null) { _microphone = Microphone.Default; ShellViewModel.WriteTimer("AudioRecorderControl ctor microphone"); if (_microphone == null) { RecordButton.Visibility = Visibility.Collapsed; Visibility = Visibility.Collapsed; IsHitTestVisible = false; return; } try { _microphone.BufferDuration = TimeSpan.FromMilliseconds(240); _duration = _microphone.BufferDuration; _buffer = new byte[_microphone.GetSampleSizeInBytes(_microphone.BufferDuration)]; } catch (Exception ex) { TLUtils.WriteException(ex); RecordButton.Visibility = Visibility.Collapsed; Visibility = Visibility.Collapsed; IsHitTestVisible = false; return; } _microphone.BufferReady += Microphone_OnBufferReady; } _skipBuffersCount = 0; _fileId = TLLong.Random(); _fileName = _fileId.Value + ".mp3"; _isPartReady = true; _uploadingLength = 0; _uploadableParts.Clear(); _isSliding = true; _stopRequested = false; _cancelRequested = false; RaiseRecordStarted(); if (Duration != null) { Duration.Text = "00:00.00"; } if (Slider != null) { ((TranslateTransform)Slider.RenderTransform).X = 0.0; } Component.StartRecord(ApplicationData.Current.LocalFolder.Path + "\\" + _fileName); _stream = new MemoryStream(); _startTime = DateTime.Now; VibrateController.Default.Start(TimeSpan.FromMilliseconds(25)); Execute.BeginOnUIThread(TimeSpan.FromMilliseconds(25.0), () => { if (!_isSliding) { if (_stopRequested) { _stopRequested = false; _cancelRequested = false; _isHintStoryboardPlaying = true; HintStoryboard.Begin(); return; } Log("_isSliding=false return"); return; } if (Slider != null) { Slider.Visibility = Visibility.Visible; } if (TimerPanel != null) { TimerPanel.Visibility = Visibility.Visible; } _asyncDispatcher.StartService(null); _microphone.Start(); StartRecordingStoryboard(); }); }
public static void SendEncryptedMediaInternal(TLEncryptedChat chat, TLObject obj, IMTProtoService mtProtoService, ICacheService cacheService) { Execute.BeginOnUIThread(() => { var message = GetDecryptedMessage(obj); if (message == null) { return; } var message17 = message as TLDecryptedMessage17; var messageLayer17 = obj as TLDecryptedMessageLayer17; var chat17 = chat as TLEncryptedChat17; if (chat17 != null && messageLayer17 != null && message17 != null && message17.InSeqNo.Value == -1 && message17.OutSeqNo.Value == -1) { var inSeqNo = TLUtils.GetInSeqNo(mtProtoService.CurrentUserId, chat17); var outSeqNo = TLUtils.GetOutSeqNo(mtProtoService.CurrentUserId, chat17); message17.InSeqNo = inSeqNo; message17.OutSeqNo = outSeqNo; message17.NotifyOfPropertyChange(() => message17.InSeqNo); message17.NotifyOfPropertyChange(() => message17.OutSeqNo); messageLayer17.InSeqNo = inSeqNo; messageLayer17.OutSeqNo = outSeqNo; chat17.RawOutSeqNo = new TLInt(chat17.RawOutSeqNo.Value + 1); //Execute.ShowDebugMessage(string.Format("SendEncryptedMediaInternal set inSeqNo={0}, outSeqNo={1}", inSeqNo, outSeqNo)); } System.Diagnostics.Debug.WriteLine("Send photo random_id={0} in_seq_no={1} out_seq_no={2}", message17.RandomId, message17.InSeqNo, message17.OutSeqNo); //message.Media.UploadingProgress = 0.0; mtProtoService.SendEncryptedFileAsync( new TLInputEncryptedChat { AccessHash = chat.AccessHash, ChatId = chat.Id }, message.RandomId, TLUtils.EncryptMessage(obj, mtProtoService.CurrentUserId, chat), message.InputFile, result => { message.Media.UploadingProgress = 0.0; message.Status = MessageStatus.Confirmed; message.NotifyOfPropertyChange(() => message.Status); ProcessSentEncryptedFile(message, result); cacheService.SyncSendingDecryptedMessage(chat.Id, result.Date, message.RandomId, m => { }); }, () => { message.Status = MessageStatus.Confirmed; message.NotifyOfPropertyChange(() => message.Status); }, error => { message.Status = MessageStatus.Failed; message.NotifyOfPropertyChange(() => message.Status); Execute.ShowDebugMessage("messages.sendEncryptedFile error " + error); }); }); }
public static void SendEncryptedMultiMediaInternal(TLEncryptedChat chat, TLDecryptedMessage message, IMTProtoService mtProtoService, ICacheService cacheService) { Execute.BeginOnUIThread(() => { var chat17 = chat as TLEncryptedChat17; if (chat17 == null) { return; } var randomId = new TLVector <TLLong>(); var data = new TLVector <TLString>(); var inputFile = new TLVector <TLInputEncryptedFileBase>(); var mediaGroup = message.Media as TLDecryptedMessageMediaGroup; if (mediaGroup != null) { for (var i = 0; i < mediaGroup.Group.Count; i++) { var message73 = mediaGroup.Group[i] as TLDecryptedMessage73; if (message73 == null) { return; } if (message73.InputFile == null) { return; } randomId.Add(message73.RandomId); var messageLayer = TLUtils.GetDecryptedMessageLayer(chat17.Layer, message73.InSeqNo, message73.OutSeqNo, message73) as TLDecryptedMessageLayer17; if (message73.InSeqNo.Value == -1 && message73.OutSeqNo.Value == -1) { var inSeqNo = TLUtils.GetInSeqNo(mtProtoService.CurrentUserId, chat17); var outSeqNo = TLUtils.GetOutSeqNo(mtProtoService.CurrentUserId, chat17); message73.InSeqNo = inSeqNo; message73.OutSeqNo = outSeqNo; message73.NotifyOfPropertyChange(() => message73.InSeqNo); message73.NotifyOfPropertyChange(() => message73.OutSeqNo); messageLayer.InSeqNo = inSeqNo; messageLayer.OutSeqNo = outSeqNo; chat17.RawOutSeqNo = new TLInt(chat17.RawOutSeqNo.Value + 1); } data.Add(TLUtils.EncryptMessage(messageLayer, mtProtoService.CurrentUserId, chat)); inputFile.Add(message73.InputFile); System.Diagnostics.Debug.WriteLine("Send photo random_id={0} in_seq_no={1} out_seq_no={2}", message73.RandomId, message73.InSeqNo, message73.OutSeqNo); } } if (randomId.Count == 0) { return; } System.Diagnostics.Debug.WriteLine("Send photo random_id=[{0}]", string.Join(",", randomId)); mtProtoService.SendEncryptedMultiMediaAsync( new TLInputEncryptedChat { AccessHash = chat.AccessHash, ChatId = chat.Id }, randomId, data, inputFile, result => Execute.BeginOnUIThread(() => { message.Media.UploadingProgress = 0.0; message.Status = MessageStatus.Confirmed; message.NotifyOfPropertyChange(() => message.Status); if (mediaGroup != null) { for (var i = mediaGroup.Group.Count - 1; i >= 0; i--) { var item = mediaGroup.Group[i] as TLDecryptedMessage; if (item != null) { item.Media.UploadingProgress = 0.0; item.Status = MessageStatus.Confirmed; item.NotifyOfPropertyChange(() => message.Status); ProcessSentEncryptedFile(item, result[i]); cacheService.SyncSendingDecryptedMessage(chat.Id, result[i].Date, mediaGroup.Group[i].RandomId, m => { }); } } } }), () => { message.Status = MessageStatus.Confirmed; message.NotifyOfPropertyChange(() => message.Status); }, error => { message.Status = MessageStatus.Failed; message.NotifyOfPropertyChange(() => message.Status); Execute.ShowDebugMessage("messages.sendEncryptedFile error " + error); }); }); }
private bool ProcessSpecialCommands(string text) { //if (string.Equals(text, "/tlg_msgs_err", StringComparison.OrdinalIgnoreCase)) //{ // ShowLastSyncErrors(info => // { // try // { // Clipboard.SetText(info); // } // catch (Exception ex) // { // } // }); // Text = string.Empty; // return true; //} if (text != null && text.StartsWith("/tlg_msgs", StringComparison.OrdinalIgnoreCase)) { try { var parameters = text.Split(' '); var limit = 15; if (parameters.Length > 1) { limit = Convert.ToInt32(parameters[1]); } ShowMessagesInfo(limit, info => { try { Clipboard.SetText(info); } catch (Exception ex) { } }); Text = string.Empty; } catch (Exception ex) { Execute.BeginOnUIThread(() => MessageBox.Show("Unknown command")); } return(true); } //if (string.Equals(text, "/tlg_cfg", StringComparison.OrdinalIgnoreCase)) //{ // ShowConfigInfo(info => // { // Execute.BeginOnUIThread(() => // { // try // { // MessageBox.Show(info); // Clipboard.SetText(info); // } // catch (Exception ex) // { // } // }); // }); // Text = string.Empty; // return true; //} //if (string.Equals(text, "/tlg_tr", StringComparison.OrdinalIgnoreCase)) //{ // ShowTransportInfo(info => // { // Execute.BeginOnUIThread(() => // { // try // { // MessageBox.Show(info); // Clipboard.SetText(info); // } // catch (Exception ex) // { // } // }); // }); // Text = string.Empty; // return true; //} //if (text != null // && text.StartsWith("/tlg_up_tr", StringComparison.OrdinalIgnoreCase)) //{ // try // { // var parameters = text.Split(' '); // var dcId = Convert.ToInt32(parameters[1]); // var dcIpAddress = parameters[2]; // var dcPort = Convert.ToInt32(parameters[3]); // MTProtoService.UpdateTransportInfoAsync(dcId, dcIpAddress, dcPort, // result => // { // Execute.BeginOnUIThread(() => MessageBox.Show("Complete /tlg_up_tr")); // }); // Text = string.Empty; // //ShowTransportInfo(info => // //{ // // Execute.BeginOnUIThread(() => // // { // // try // // { // // MessageBox.Show(info); // // Clipboard.SetText(info); // // } // // catch (Exception ex) // // { // // } // // Text = string.Empty; // // }); // //}); // } // catch (Exception ex) // { // Execute.BeginOnUIThread(() => MessageBox.Show("Unknown command")); // } // return true; //} return(false); }
public void ForgotPassword() { if (_password == null) { return; } BeginOnUIThread(() => { if (_password.HasRecovery.Value) { IsWorking = true; MTProtoService.RequestPasswordRecoveryAsync( result => BeginOnUIThread(() => { IsWorking = false; _password.EmailUnconfirmedPattern = result.EmailPattern; _password.IsAuthRecovery = true; MessageBox.Show(string.Format(AppResources.SentRecoveryCodeMessage, result.EmailPattern), AppResources.AppName, MessageBoxButton.OK); StateService.Password = _password; StateService.RemoveBackEntry = true; NavigationService.UriFor <PasswordRecoveryViewModel>().Navigate(); ResetAccountVisibility = Visibility.Visible; }), error => BeginOnUIThread(() => { IsWorking = false; var messageBuilder = new StringBuilder(); messageBuilder.AppendLine(AppResources.Error); messageBuilder.AppendLine(); messageBuilder.AppendLine("Method: account.requestPasswordRecovery"); messageBuilder.AppendLine("Result: " + error); if (TLRPCError.CodeEquals(error, ErrorCode.FLOOD)) { Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.FloodWaitString + Environment.NewLine + "(" + error.Message + ")", AppResources.Error, MessageBoxButton.OK)); } else if (TLRPCError.CodeEquals(error, ErrorCode.INTERNAL)) { Execute.BeginOnUIThread(() => MessageBox.Show(messageBuilder.ToString(), AppResources.ServerError, MessageBoxButton.OK)); } else if (TLRPCError.CodeEquals(error, ErrorCode.BAD_REQUEST)) { if (TLRPCError.TypeEquals(error, ErrorType.PASSWORD_EMPTY)) { Execute.BeginOnUIThread(() => MessageBox.Show(messageBuilder.ToString(), AppResources.Error, MessageBoxButton.OK)); } else if (TLRPCError.TypeEquals(error, ErrorType.PASSWORD_RECOVERY_NA)) { Execute.BeginOnUIThread(() => MessageBox.Show(messageBuilder.ToString(), AppResources.Error, MessageBoxButton.OK)); } else { Execute.BeginOnUIThread(() => MessageBox.Show(messageBuilder.ToString(), AppResources.Error, MessageBoxButton.OK)); } } else { Execute.ShowDebugMessage("account.requestPasswordRecovery error " + error); } ResetAccountVisibility = Visibility.Visible; })); } else { MessageBox.Show(AppResources.NoRecoveryEmailMessage, AppResources.Sorry, MessageBoxButton.OK); ResetAccountVisibility = Visibility.Visible; } }); }
public void ProcessAsync(Action <IList <TLObject> > callback) { if (Results != null) { IsCanceled = false; callback.SafeInvoke(Results); return; } var usersSource = UsersSource; var chatsSource = ChatsSource; Execute.BeginOnThreadPool(() => { var useFastSearch = !Text.Contains(" "); var userResults = new List <TLUserBase>(usersSource.Count); foreach (var contact in usersSource) { if (IsUserValid(contact, Text) || IsUserValid(contact, TransliterateText) || IsUsernameValid(contact as IUserName, Text)) { userResults.Add(contact); } } var chatsResults = new List <TLChatBase>(chatsSource.Count); foreach (var chat in chatsSource) { if (IsChatValid(chat, Text, useFastSearch) || IsChatValid(chat, TransliterateText, useFastSearch) || IsUsernameValid(chat as IUserName, Text)) { chatsResults.Add(chat); } } Results = new List <TLObject>(userResults.Count + chatsResults.Count); UserResultsIndex = new Dictionary <int, TLUserBase>(); ChatResultsIndex = new Dictionary <int, TLChatBase>(); foreach (var userResult in userResults) { Results.Add(userResult); UserResultsIndex[userResult.Index] = userResult; if (userResult.Dialog == null) { userResult.Dialog = _cacheService.GetDialog(new TLPeerUser { Id = userResult.Id }); } } foreach (var chatResult in chatsResults) { Results.Add(chatResult); ChatResultsIndex[chatResult.Index] = chatResult; if (chatResult.Dialog == null) { TLDialogBase dialog = _cacheService.GetDialog(new TLPeerChat { Id = chatResult.Id }); if (dialog == null) { if (chatResult is TLChannel) { dialog = DialogsViewModel.GetChannel(chatResult.Id); } } chatResult.Dialog = dialog; } } Execute.BeginOnUIThread(() => callback.SafeInvoke(Results)); }); }