Пример #1
0
        public static void Clear(Action callback)
        {
            Execute.BeginOnThreadPool(() =>
            {
                FileUtils.Clear(_fileSyncRoot, DirectoryName);

                callback?.Invoke();
            });
        }
Пример #2
0
        public static void CopyTo(string fileName, Action <string> callback)
        {
            Execute.BeginOnThreadPool(() =>
            {
                FileUtils.CopyLog(_fileSyncRoot, DirectoryName, FileName, fileName, IsEnabled);

                callback?.Invoke(fileName);
            });
        }
Пример #3
0
 private void ShowBatterySaverAlertAsync()
 {
     Execute.BeginOnThreadPool(() =>
     {
         if (!_showBatterySaverOnce)
         {
             _showBatterySaverOnce = CheckBatterySaverState();
         }
     });
 }
Пример #4
0
        protected override void OnActivate()
        {
            if (StateService.DCOption != null)
            {
                var option = StateService.DCOption;
                StateService.DCOption = null;
                Execute.ShowDebugMessage("New DCOption=" + option);
            }

            base.OnActivate();
        }
Пример #5
0
        private void OnDialogAdded(object sender, DialogAddedEventArgs e)
        {
            var dialog = e.Dialog;

            if (dialog == null)
            {
                return;
            }

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

                    if (Items[i].GetDateIndex() < dialog.GetDateIndex())
                    {
                        index = i;
                        break;
                    }
                }

#if LAYER_40
                if (e.Dialog.Peer is TLPeerChannel)
                {
                    for (var i = 0; i < Items.Count; i++)
                    {
                        if (e.Dialog.Peer.GetType() == Items[i].Peer.GetType() &&
                            e.Dialog.Peer.Id.Value == Items[i].Peer.Id.Value)
                        {
                            Items.RemoveAt(i);
                            Execute.ShowDebugMessage("OnDialogAdded RemoveAt=" + i);
                            break;
                        }
                    }
                }
#endif


                if (index == -1)
                {
                    Items.Add(dialog);
                }
                else
                {
                    Items.Insert(index, dialog);
                }
                Status = Items.Count == 0 || LazyItems.Count == 0 ? string.Empty : Status;
            });
        }
Пример #6
0
        public void DeleteContact(TLUserBase user)
        {
            if (user == null)
            {
                return;
            }

            MTProtoService.DeleteContactAsync(
                user.ToInputUser(),
                link => BeginOnUIThread(() => Items.Remove(user)),
                error => Execute.ShowDebugMessage("contacts.deleteContact error: " + error));
        }
Пример #7
0
 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 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
        }
Пример #9
0
        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);
            });
        }
Пример #10
0
        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);
                    }
                });
            });
        }
Пример #11
0
        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);
            });
        }
Пример #12
0
        public void Handle(UpdateCompletedEventArgs args)
        {
            var dialogs = CacheService.GetDialogs();

            Execute.BeginOnUIThread(() =>
            {
                Items.Clear();
                foreach (var dialog in dialogs)
                {
                    Items.Add(dialog);
                }
            });
        }
Пример #13
0
        public void Handle(UploadableItem item)
        {
            var userBase = item.Owner as TLUserBase;

            if (userBase != null && userBase.IsSelf)
            {
                Execute.BeginOnUIThread(() =>
                {
                    IsWorking = false;
                    CurrentItem.NotifyOfPropertyChange(() => CurrentItem.Photo);
                });
            }
        }
Пример #14
0
        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();
                }
            });
        }
        public void ResetAccount()
        {
            BeginOnUIThread(TimeSpan.FromSeconds(0.1), () =>
            {
                var r = MessageBox.Show(AppResources.ResetMyAccountConfirmation, AppResources.Warning, MessageBoxButton.OKCancel);
                if (r != MessageBoxResult.OK)
                {
                    return;
                }

                IsWorking = true;
                MTProtoService.DeleteAccountAsync(
                    new TLString("Forgot password"),
                    result => BeginOnUIThread(() =>
                {
                    IsWorking = false;

                    StateService.RemoveBackEntry = true;
                    StateService.SentCode        = _sentCode;
                    NavigationService.UriFor <SignUpViewModel>().Navigate();
                }),
                    error => BeginOnUIThread(() =>
                {
                    IsWorking = false;

                    if (error.TypeEquals("2FA_RECENT_CONFIRM"))
                    {
                        MessageBox.Show(AppResources.ResetAccountError, AppResources.Error, MessageBoxButton.OK);
                    }
                    else if (error.TypeStarsWith("2FA_CONFIRM_WAIT"))
                    {
                        var message = error.Message.ToString().Replace("2FA_CONFIRM_WAIT_", string.Empty);
                        try
                        {
                            var confirmWait          = Convert.ToInt32(message);
                            StateService.ConfirmWait = confirmWait;
                            StateService.SentCode    = _sentCode;
                            NavigationService.UriFor <ResetAccountViewModel>().Navigate();
                        }
                        catch (Exception e)
                        {
                        }
                    }
                    else
                    {
                        Execute.ShowDebugMessage("account.deleteAccount error " + error);
                    }
                }));
            });
        }
Пример #16
0
        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

                                                                          ));
                        }
                    }
                }
            }
        }
Пример #17
0
        private void ChangePhoneNumber()
        {
            IsWorking = true;
            NotifyOfPropertyChange(() => CanSignIn);
            var phoneNumber = PhoneCode + PhoneNumber;

            _startTime = DateTime.Now;
            _showHelpTimer.Start();
            MTProtoService.SendChangePhoneCodeAsync(new TLString(phoneNumber),
                                                    sentCode => BeginOnUIThread(() =>
            {
                _showHelpTimer.Stop();
                StateService.PhoneNumber       = new TLString(phoneNumber);
                StateService.PhoneNumberString = string.Format(AppResources.ConfirmMessage, PhoneNumberConverter.Convert(StateService.PhoneNumber));

                StateService.PhoneCodeHash     = sentCode.PhoneCodeHash;
                StateService.PhoneRegistered   = new TLBool(false);
                StateService.SendCallTimeout   = sentCode.SendCodeTimeout;
                StateService.ChangePhoneNumber = true;

                NavigationService.UriFor <ConfirmViewModel>().Navigate();

                IsWorking = false;
                NotifyOfPropertyChange(() => CanSignIn);
            }),
                                                    error => BeginOnUIThread(() =>
            {
                _lastError = error;

                IsWorking = false;
                NotifyOfPropertyChange(() => CanSignIn);

                if (error.TypeEquals(ErrorType.PHONE_NUMBER_INVALID))
                {
                    MessageBox.Show(AppResources.PhoneNumberInvalidString, AppResources.Error, MessageBoxButton.OK);
                }
                else if (error.TypeEquals(ErrorType.PHONE_NUMBER_OCCUPIED))
                {
                    MessageBox.Show(string.Format(AppResources.NewNumberTaken, "+" + phoneNumber), AppResources.Error, MessageBoxButton.OK);
                }
                else if (error.CodeEquals(ErrorCode.FLOOD))
                {
                    MessageBox.Show(AppResources.FloodWaitString + Environment.NewLine + "(" + error.Message + ")", AppResources.Error, MessageBoxButton.OK);
                }
                else
                {
                    Execute.ShowDebugMessage("account.sendChangePhoneCode error " + error);
                }
            }));
        }
Пример #18
0
        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(() =>
            {
            }));
        }
Пример #19
0
        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();
            });
        }
Пример #20
0
        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;
            }));
        }
Пример #21
0
        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);
            });
        }
Пример #22
0
        private static void UpdateMainTile()
        {
#if WNS_PUSH_SERVICE
            try
            {
                ToastNotificationManager.History.Clear();
            }
            catch (Exception ex)
            {
                Execute.ShowDebugMessage("Clear notifications history exception\n" + ex);
            }

            try
            {
                BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear();
                TileUpdateManager.CreateTileUpdaterForApplication().Clear();
            }
            catch (Exception ex)
            {
                Execute.ShowDebugMessage("Clear tile exception\n" + ex);
            }
#else
            var tile = ShellTile.ActiveTiles.FirstOrDefault();
            if (tile == null)
            {
                return;
            }

            ShellTileData tileData;
#if WP8
            tileData = new IconicTileData {
                Count = 0, WideContent1 = "", WideContent2 = "", WideContent3 = ""
            };
#else
            tileData = new StandardTileData {
                Count = 0
            };
#endif
            try
            {
                tile.Update(tileData);
            }
            catch (Exception ex)
            {
                Execute.ShowDebugMessage("Tile.Update exception\n" + ex);
            }
#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));
        }
Пример #24
0
        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
        }
Пример #25
0
        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 => { });
                });
            });
        }
Пример #26
0
        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);
        }
Пример #27
0
Файл: Log.cs Проект: Fart03/lau
        public static void Write(string str, Action callback = null)
        {
            if (!IsEnabled)
            {
                return;
            }

            if (WriteSync)
            {
                WriteInternal(str, callback);
            }
            else
            {
                Execute.BeginOnThreadPool(() =>
                {
                    WriteInternal(str, callback);
                });
            }
        }
Пример #28
0
        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;
            }
        }
Пример #30
0
        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;
            });
        }