public static void SaveDelayedContactsAsync(TLVector <TLInt> contacts) { Execute.BeginOnThreadPool(() => { TLUtils.SaveObjectToMTProtoFile(_delayedContactsSyncRoot, Constants.DelayedContactsFileName, contacts); }); }
public static void DeleteRecentAsync() { Execute.BeginOnThreadPool(() => { _recentResults = new TLVector <TLResultInfo>(); FileUtils.Delete(_recentSyncRoot, Constants.RecentSearchResultsFileName); }); }
public static void CopyTo(string fileName, Action <string> callback) { Execute.BeginOnThreadPool(() => { FileUtils.CopyLog(_fileSyncRoot, DirectoryName, FileName, fileName, IsEnabled); callback?.Invoke(fileName); }); }
public static void Clear(Action callback) { Execute.BeginOnThreadPool(() => { FileUtils.Clear(_fileSyncRoot, DirectoryName); callback?.Invoke(); }); }
private void ShowBatterySaverAlertAsync() { Execute.BeginOnThreadPool(() => { if (!_showBatterySaverOnce) { _showBatterySaverOnce = CheckBatterySaverState(); } }); }
public static void ImportContactsAsync(IFileManager fileManager, ContactsOperationToken token, IList <TLUserBase> contacts, Action <Telegram.Api.WindowsPhone.Tuple <int, int> > progressCallback, System.Action cancelCallback) { #if WP8 Execute.BeginOnThreadPool(async() => { //var contacts = _cacheService.GetContacts(); var totalCount = contacts.Count; if (totalCount == 0) { return; } var store = await ContactStore.CreateOrOpenAsync(); var importedCount = 0; var delayedContacts = new TLVector <TLInt>(); foreach (var contact in contacts) { if (token.IsCanceled) { cancelCallback.SafeInvoke(); return; } try { var delayedContact = await UpdateContactInternalAsync(contact, fileManager, store, true); if (delayedContact != null) { delayedContacts.Add(delayedContact.Id); } } catch (Exception ex) { // continue import after failed contact } //Thread.Sleep(100); importedCount++; progressCallback.SafeInvoke(new Telegram.Api.WindowsPhone.Tuple <int, int>(importedCount, totalCount)); //var duration = importedCount == totalCount ? 0.5 : 2.0; //_mtProtoService.SetMessageOnTime(duration, string.Format("Sync contacts ({0} of {1})...", importedCount, totalCount)); } var result = new TLVector <TLInt>(); foreach (var delayedContact in delayedContacts) { result.Add(delayedContact); } SaveDelayedContactsAsync(result); }); #endif }
public static void GetDelayedContactsAsync(Action <TLVector <TLInt> > callback) { if (_delayedContacts != null) { callback.SafeInvoke(_delayedContacts); } Execute.BeginOnThreadPool(() => { _delayedContacts = TLUtils.OpenObjectFromMTProtoFile <TLVector <TLInt> >(_delayedContactsSyncRoot, Constants.DelayedContactsFileName) ?? new TLVector <TLInt>(); callback.SafeInvoke(_delayedContacts); }); }
public static void Clear(Action callback) { Execute.BeginOnThreadPool(() => { using (var mutex = new Mutex(false, "Telegram.Log")) { mutex.WaitOne(); FileUtils.Clear(_fileSyncRoot, DirectoryName); mutex.ReleaseMutex(); } callback.SafeInvoke(); }); }
public static void CopyTo(string fileName, Action <string> callback) { Execute.BeginOnThreadPool(() => { using (var mutex = new Mutex(false, "Telegram.Log")) { mutex.WaitOne(); FileUtils.CopyLog(_fileSyncRoot, DirectoryName, FileName, fileName, IsEnabled); mutex.ReleaseMutex(); } callback.SafeInvoke(fileName); }); }
public static void DeleteContactAsync(IStateService stateService, TLInt userId) { #if WP8 Execute.BeginOnThreadPool(() => stateService.GetNotifySettingsAsync( async settings => { if (settings.PeopleHub) { var store = await ContactStore.CreateOrOpenAsync(); var phoneContact = await store.FindContactByRemoteIdAsync(userId.ToString()); await store.DeleteContactAsync(phoneContact.Id); } })); #endif }
private static void SavePhotoAsync(TLDecryptedMessageMediaPhoto mediaPhoto, Action <string> callback = null) { var location = mediaPhoto.Photo as TLEncryptedFile; if (location == null) { return; } var fileName = String.Format("{0}_{1}_{2}.jpg", location.Id, location.DCId, location.AccessHash); Execute.BeginOnThreadPool(() => ImageViewerViewModel.SavePhoto(fileName, callback)); }
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 static void Write(string str, Action callback = null) { if (!IsEnabled) { return; } if (WriteSync) { WriteInternal(str, callback); } else { Execute.BeginOnThreadPool(() => { WriteInternal(str, callback); }); } }
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; }); }); }); }
private static void SaveVideoAsync(TLDecryptedMessageMediaBase mediaBase) { var mediaDocument = mediaBase as TLDecryptedMessageMediaDocument45; if (mediaDocument != null && TLDecryptedMessageBase.IsVideo(mediaDocument)) { var fileLocation = mediaDocument.File as TLEncryptedFile; if (fileLocation == null) { return; } var fileName = String.Format("{0}_{1}_{2}.mp4", fileLocation.Id, fileLocation.DCId, fileLocation.AccessHash); Execute.BeginOnThreadPool(() => ImageViewerViewModel.SaveVideo(fileName)); return; } var mediaVideo = mediaBase as TLDecryptedMessageMediaVideo; if (mediaVideo != null) { var fileLocation = mediaVideo.File as TLEncryptedFile; if (fileLocation == null) { return; } var fileName = String.Format("{0}_{1}_{2}.mp4", fileLocation.Id, fileLocation.DCId, fileLocation.AccessHash); Execute.BeginOnThreadPool(() => ImageViewerViewModel.SaveVideo(fileName)); return; } }
private void UploadAudioFileAsync(bool isLastPart) { Execute.BeginOnThreadPool(() => { if (!_isPartReady) { return; } _isPartReady = false; var uploadablePart = GetUploadablePart(_fileName, _uploadingLength, _uploadableParts.Count, isLastPart); if (uploadablePart == null) { _isPartReady = true; return; } _uploadableParts.Add(uploadablePart); _uploadingLength += uploadablePart.Count; //Execute.BeginOnUIThread(() => VibrateController.Default.Start(TimeSpan.FromSeconds(0.02))); if (!isLastPart) { var mtProtoService = IoC.Get <IMTProtoService>(); mtProtoService.SaveFilePartAsync(_fileId, uploadablePart.FilePart, TLString.FromBigEndianData(uploadablePart.Bytes), result => { if (result.Value) { uploadablePart.Status = PartStatus.Processed; } }, error => Execute.ShowDebugMessage("upload.saveFilePart error " + error)); } _isPartReady = true; }); }
private bool PutFile(TLLong fileId, TLInt filePart, byte[] bytes) { var manualResetEvent = new ManualResetEvent(false); var result = false; _mtProtoService.SaveFilePartAsync(fileId, filePart, TLString.FromBigEndianData(bytes), savingResult => { result = true; manualResetEvent.Set(); }, error => Execute.BeginOnThreadPool(TimeSpan.FromSeconds(1.0), () => { Execute.ShowDebugMessage(string.Format("upload.saveBigFilePart part={0}, count={1} error\n", filePart.Value, bytes.Length) + error); manualResetEvent.Set(); })); manualResetEvent.WaitOne(); return(result); }
private bool PutFile(long fileId, int filePart, int fileTotalPars, byte[] bytes) { var manualResetEvent = new ManualResetEvent(false); var result = false; _mtProtoService.SaveFilePartCallback(fileId, filePart, bytes, savingResult => { result = true; manualResetEvent.Set(); }, error => Execute.BeginOnThreadPool(TimeSpan.FromSeconds(1.0), () => { Execute.ShowDebugMessage(string.Format("upload.saveFilePart part={0}, bytesCount={1} error\n", filePart, bytes.Length) + error); manualResetEvent.Set(); })); manualResetEvent.WaitOne(); return(result); }
private static void SavePhotoAsync(TLMessageMediaPhoto mediaPhoto, Action <string> callback = null) { var photo = mediaPhoto.Photo as TLPhoto; if (photo == null) { return; } TLPhotoSize size = null; var sizes = photo.Sizes.OfType <TLPhotoSize>(); const double width = 800.0; foreach (var photoSize in sizes) { if (size == null || Math.Abs(width - size.W.Value) > Math.Abs(width - photoSize.W.Value)) { size = photoSize; } } if (size == null) { return; } var location = size.Location as TLFileLocation; if (location == null) { return; } var fileName = String.Format("{0}_{1}_{2}.jpg", location.VolumeId, location.LocalId, location.Secret); Execute.BeginOnThreadPool(() => SavePhoto(fileName, callback)); }
public static void DeleteContactsAsync(System.Action callback) { #if WP8 Execute.BeginOnThreadPool( async() => { var store = await ContactStore.CreateOrOpenAsync(); try { await store.DeleteAsync(); FileUtils.Delete(_delayedContactsSyncRoot, Constants.DelayedContactsFileName); } catch (Exception ex) { Execute.ShowDebugMessage("store.DeleteAsync ex " + ex); } finally { callback.SafeInvoke(); } }); #endif }
public static void CreateContactAsync(IFileManager fileManager, IStateService stateService, TLUserContact contact) { #if WP8 Execute.BeginOnThreadPool(() => stateService.GetNotifySettingsAsync( async settings => { if (settings.PeopleHub) { var store = await ContactStore.CreateOrOpenAsync(); var delayedContact = await UpdateContactInternalAsync(contact, fileManager, store, true); if (delayedContact != null) { GetDelayedContactsAsync(contacts => { contacts.Add(delayedContact.Id); SaveDelayedContactsAsync(contacts); }); } } })); #endif }
private static void SaveVideoAsync(TLMessageMediaBase mediaBase) { var mediaDocument = mediaBase as TLMessageMediaDocument45; if (mediaDocument != null && TLMessageBase.IsVideo(mediaDocument.Document)) { var video = mediaDocument.Video as TLDocument22; if (video == null) { return; } var fileName = video.GetFileName(); Execute.BeginOnThreadPool(() => SaveVideo(fileName)); return; } var mediaVideo = mediaBase as TLMessageMediaVideo; if (mediaVideo != null) { var video = mediaVideo.Video as TLVideo; if (video == null) { return; } var fileName = video.GetFileName(); Execute.BeginOnThreadPool(() => SaveVideo(fileName)); return; } }
private void LoadStateAndUpdateAsync() { Execute.BeginOnThreadPool(() => { try { BackgroundProcessController.Instance.ConnectUi(); } catch (Exception ex) { TLUtils.WriteException("LoadStateAndUpdateAsync 1", ex); } //BackgroundProcessController.Instance.CallController.StopMTProtoUpdater(); var isAuthorized = SettingsHelper.GetValue <bool>(Constants.IsAuthorizedKey); if (!isAuthorized) { return; } Execute.BeginOnUIThread(() => { //MessageBox.Show("LoadStateAndUpdateAsync"); var mtProtoService = IoC.Get <IMTProtoService>(); var stateService = IoC.Get <IStateService>(); var updatesService = IoC.Get <IUpdatesService>(); var voipService = IoC.Get <IVoIPService>(); var liveLocationsService = IoC.Get <ILiveLocationService>(); mtProtoService.CurrentUserId = new TLInt(stateService.CurrentUserId); 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.GetFullChatAsync = mtProtoService.GetFullChatAsync; updatesService.GetFullUserAsync = mtProtoService.GetFullUserAsync; updatesService.GetChannelMessagesAsync = mtProtoService.GetMessagesAsync; updatesService.GetPinnedDialogsAsync = mtProtoService.GetPinnedDialogsAsync; updatesService.GetMessagesAsync = mtProtoService.GetMessagesAsync; updatesService.GetPeerDialogsAsync = mtProtoService.GetPeerDialogsAsync; updatesService.GetPromoDialogAsync = mtProtoService.GetPromoDialogAsync; stateService.SuppressNotifications = true; long acceptedCallId = -1; try { if (BackgroundProcessController.Instance.CallController != null) { BackgroundProcessController.Instance.CallController.SetStatusCallback((VoIPService)voipService); acceptedCallId = BackgroundProcessController.Instance.CallController.AcceptedCallId; BackgroundProcessController.Instance.CallController.AcceptedCallId = -1; voipService.AcceptedCallId = acceptedCallId; if (acceptedCallId != -1) { BackgroundProcessController.Instance.CallController.EndCall(); } } } catch (Exception ex) { TLUtils.WriteException("LoadStateAndUpdateAsync 2", ex); } liveLocationsService.LoadAndUpdateAllAsync(); var timer = Stopwatch.StartNew(); TLUtils.WritePerformance(">>UpdateService.LoadStateAndUpdate start"); //mtProtoService.SetMessageOnTime(60.0 * 5, AppResources.Updating + "..."); updatesService.LoadStateAndUpdate(acceptedCallId, () => { //mtProtoService.SetMessageOnTime(0.0, string.Empty); TLUtils.WritePerformance(">>UpdateService.LoadStateAndUpdate stop " + timer.Elapsed); stateService.SuppressNotifications = false; }); }); }); }
private void OnUploading(object state) { UploadablePart part = null; lock (_itemsSyncRoot) { for (var i = 0; i < _items.Count; i++) { var item = _items[i]; if (item.Canceled) { _items.RemoveAt(i--); try { _eventAggregator.Publish(new UploadingCanceledEventArgs(item)); } catch (Exception e) { TLUtils.WriteException(e); } } } foreach (var item in _items) { part = item.Parts.FirstOrDefault(x => x.Status == PartStatus.Ready); if (part != null) { part.Status = PartStatus.Processing; break; } } } if (part != null) { var bytes = part.Bytes; #if WP8 if (bytes == null) { var file = part.ParentItem.File; if (file != null) { var task = FileUtils.FillBuffer(file, part); task.Wait(); bytes = task.Result.Item2; } if (bytes == null) { part.Status = PartStatus.Ready; return; } } #endif var result = PutFile(part.ParentItem.FileId, part.FilePart, new TLInt(part.ParentItem.Parts.Count), bytes); while (!result) { if (part.ParentItem.Canceled) { return; } result = PutFile(part.ParentItem.FileId, part.FilePart, new TLInt(part.ParentItem.Parts.Count), bytes); } // indicate progress // indicate complete bool isComplete = false; bool isCanceled; var progress = 0.0; lock (_itemsSyncRoot) { part.Status = PartStatus.Processed; isCanceled = part.ParentItem.Canceled; if (!isCanceled) { isComplete = part.ParentItem.Parts.All(x => x.Status == PartStatus.Processed); if (!isComplete) { double uploadedCount = part.ParentItem.Parts.Count(x => x.Status == PartStatus.Processed); double totalCount = part.ParentItem.Parts.Count; progress = uploadedCount / totalCount; } else { _items.Remove(part.ParentItem); } } } if (!isCanceled) { if (isComplete) { try { Execute.BeginOnThreadPool(() => _eventAggregator.Publish(part.ParentItem)); } catch (Exception e) { TLUtils.WriteLine(e.ToString(), LogSeverity.Error); } } else { try { Execute.BeginOnThreadPool(() => _eventAggregator.Publish(new UploadProgressChangedEventArgs(part.ParentItem, progress))); } catch (Exception e) { TLUtils.WriteLine(e.ToString(), LogSeverity.Error); } } } } else { var currentWorker = (Worker)state; currentWorker.Stop(); } }
public void SaveRecent(TLObject with) { Execute.BeginOnThreadPool(() => { var recentResults = _recentResults ?? new TLVector <TLResultInfo>(); var id = GetId(with); var type = GetType(with); if (id == null || type == null) { return; } var isAdded = false; for (var i = 0; i < recentResults.Count; i++) { var recentResult = recentResults[i]; if (recentResults[i].Id.Value == id.Value && recentResults[i].Type.ToString() == type.ToString()) { recentResults[i].Count = new TLLong(recentResults[i].Count.Value + 1); var newPosition = i; for (var j = i - 1; j >= 0; j--) { if (recentResults[j].Count.Value <= recentResults[i].Count.Value) { newPosition = j; } } if (i != newPosition) { recentResults.RemoveAt(i); recentResults.Insert(newPosition, recentResult); } isAdded = true; break; } } if (!isAdded) { var recentResult = new TLResultInfo { Id = id, Type = type, Count = new TLLong(1) }; for (var i = 0; i < recentResults.Count; i++) { if (recentResults[i].Count.Value <= 1) { recentResults.Insert(i, recentResult); isAdded = true; break; } } if (!isAdded) { recentResults.Add(recentResult); } } _recentResults = recentResults; TLUtils.SaveObjectToMTProtoFile(_recentSyncRoot, Constants.RecentSearchResultsFileName, recentResults); }); }
public void ForwardInAnimationComplete() { Execute.BeginOnThreadPool(() => { _recentResults = _recentResults ?? TLUtils.OpenObjectFromMTProtoFile <TLVector <TLResultInfo> >(_recentSyncRoot, Constants.RecentSearchResultsFileName) ?? new TLVector <TLResultInfo>(); var recent = new List <TLObject>(); foreach (var result in _recentResults) { if (result.Type.ToString() == "user") { var user = CacheService.GetUser(result.Id); if (user != null) { recent.Add(user); if (user.Dialog == null) { user.Dialog = CacheService.GetDialog(new TLPeerUser { Id = user.Id }); } } } if (result.Type.ToString() == "chat") { var chat = CacheService.GetChat(result.Id); if (chat != null) { recent.Add(chat); if (chat.Dialog == null) { TLDialogBase dialog = CacheService.GetDialog(new TLPeerChat { Id = chat.Id }); if (dialog == null) { if (chat is TLChannel) { dialog = DialogsViewModel.GetChannel(chat.Id); } } chat.Dialog = dialog; } } } } Execute.BeginOnUIThread(() => { if (!string.IsNullOrEmpty(Text)) { return; } Recent.Clear(); foreach (var recentItem in recent) { Recent.Add(recentItem); } NotifyOfPropertyChange(() => ShowRecent); }); }); }
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)); }); }