public void DownloadFile(TLEncryptedFile file, TLObject owner)
        {
            var inputFile = new TLInputEncryptedFileLocation {
                Id = file.Id, AccessHash = file.AccessHash
            };
            var downloadableItem = GetDownloadableItem(file.DCId, inputFile, owner, file.Size);

            lock (_itemsSyncRoot)
            {
                bool addFile = true;
                foreach (var item in _items)
                {
                    if (item.InputEncryptedFileLocation.LocationEquals(inputFile))
                    {
                        addFile = false;
                        break;
                    }
                }

                if (addFile)
                {
                    _items.Add(downloadableItem);
                }
            }

            StartAwaitingWorkers();
        }
        private void SendDocument(Photo p)
        {
            var chat = Chat as TLEncryptedChat;

            if (chat == null)
            {
                return;
            }

            var dcId       = TLInt.Random();
            var id         = TLLong.Random();
            var accessHash = TLLong.Random();

            var fileLocation = new TLEncryptedFile
            {
                Id             = id,
                AccessHash     = accessHash,
                DCId           = dcId,
                Size           = new TLInt(p.Bytes.Length),
                KeyFingerprint = new TLInt(0),
                FileName       = new TLString(Path.GetFileName(p.FileName))
            };

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

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var fileStream = store.CreateFile(fileName))
                {
                    fileStream.Write(p.Bytes, 0, p.Bytes.Length);
                }
            }

            var keyIV = GenerateKeyIV();

            int thumbHeight;
            int thumbWidth;
            var thumb = ImageUtils.CreateThumb(p.Bytes, Constants.DocumentPreviewMaxSize, Constants.DocumentPreviewQuality, out thumbHeight, out thumbWidth);

            var decryptedMediaDocument = GetDecryptedMediaDocument(p, chat, TLString.FromBigEndianData(thumb), new TLInt(thumbWidth), new TLInt(thumbHeight), new TLString("image/jpeg"), keyIV, fileLocation);

            var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaDocument, chat, true);

            InsertSendingMessage(decryptedTuple.Item1);
            RaiseScrollToBottom();
            NotifyOfPropertyChange(() => DescriptionVisibility);

            BeginOnThreadPool(() =>
                              CacheService.SyncDecryptedMessage(decryptedTuple.Item1, chat,
                                                                cachedMessage => SendDocumentInternal(p.Bytes, decryptedTuple.Item2)));
        }
Пример #3
0
        public void DownloadFile(TLEncryptedFile file, TLObject owner, Action <DownloadableItem> callback)
        {
            var inputFile = new TLInputEncryptedFileLocation {
                Id = file.Id, AccessHash = file.AccessHash
            };
            var downloadableItem = GetDownloadableItem(file.DCId, inputFile, owner, file.Size, callback);

            var downloadedCount = downloadableItem.Parts.Count(x => x.Status == PartStatus.Processed);
            var count           = downloadableItem.Parts.Count;
            var isComplete      = downloadedCount == count;

            if (isComplete)
            {
                var fileName = downloadableItem.InputLocation.GetFileName("encrypted");
                Func <DownloadablePart, string> getPartName = x => downloadableItem.InputLocation.GetPartFileName(x.Number, "encrypted");

                FileUtils.MergePartsToFile(getPartName, downloadableItem.Parts, fileName);

                downloadableItem.IsoFileName = fileName;
                if (downloadableItem.Callback != null)
                {
                    downloadableItem.Callback(downloadableItem);
                }
                else
                {
                    _eventAggregator.Publish(downloadableItem);
                }
            }
            else
            {
                lock (_itemsSyncRoot)
                {
                    bool addFile = true;
                    foreach (var item in _items)
                    {
                        if (item.InputLocation.LocationEquals(inputFile))
                        {
                            addFile = false;
                            break;
                        }
                    }

                    if (addFile)
                    {
                        _items.Add(downloadableItem);
                    }
                }

                StartAwaitingWorkers();
            }
        }
        public static BitmapImage ReturnOrEnqueueImage(Stopwatch timer, TLEncryptedFile location, TLObject owner)
        {
            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                         location.Id,
                                         location.DCId,
                                         location.AccessHash);

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists(fileName))
                {
                    var fileManager = IoC.Get <IEncryptedFileManager>();
                    ThreadPool.QueueUserWorkItem(state =>
                    {
                        fileManager.DownloadFile(location, owner);
                    });
                }
                else
                {
                    BitmapImage imageSource;

                    try
                    {
                        using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                        {
                            stream.Seek(0, SeekOrigin.Begin);
                            var image = new BitmapImage();
                            image.SetSource(stream);
                            imageSource = image;
                        }
                    }
                    catch (Exception)
                    {
                        return(null);
                    }

                    return(imageSource);
                }
            }

            return(null);
        }
        public async void SendDocument(StorageFile file)
        {
            var chat = Chat as TLEncryptedChat;

            if (chat == null)
            {
                return;
            }

            if (file == null)
            {
                return;
            }

            var properties = await file.GetBasicPropertiesAsync();

            var size = properties.Size;

            if (!DialogDetailsViewModel.CheckDocumentSize(size))
            {
                MessageBox.Show(string.Format(AppResources.MaximumFileSizeExceeded, MediaSizeConverter.Convert((int)Telegram.Api.Constants.MaximumUploadedFileSize)), AppResources.Error, MessageBoxButton.OK);
                return;
            }

            DialogDetailsViewModel.AddFileToFutureAccessList(file);

            var thumb = await DialogDetailsViewModel.GetFileThumbAsync(file) as TLPhotoSize;

            var dcId       = TLInt.Random();
            var id         = TLLong.Random();
            var accessHash = TLLong.Random();

            var fileLocation = new TLEncryptedFile
            {
                Id             = id,
                AccessHash     = accessHash,
                DCId           = dcId,
                Size           = new TLInt((int)size),
                KeyFingerprint = new TLInt(0),
                FileName       = new TLString(Path.GetFileName(file.Name))
            };

            var keyIV = GenerateKeyIV();

            var decryptedMediaDocumentBase = GetDecryptedMediaDocument(file, chat, thumb, size, keyIV, fileLocation);
            var decryptedMediaDocument45   = decryptedMediaDocumentBase as TLDecryptedMessageMediaDocument45;

            if (decryptedMediaDocument45 != null)
            {
                if (string.Equals(decryptedMediaDocument45.FileExt, "webp", StringComparison.OrdinalIgnoreCase) &&
                    decryptedMediaDocument45.DocumentSize < Telegram.Api.Constants.StickerMaxSize)
                {
                    decryptedMediaDocument45.MimeType = new TLString("image/webp");
                    decryptedMediaDocument45.Attributes.Add(new TLDocumentAttributeSticker29 {
                        Alt = TLString.Empty, Stickerset = new TLInputStickerSetEmpty()
                    });

                    var fileName = decryptedMediaDocument45.GetFileName();
                    await file.CopyAsync(ApplicationData.Current.LocalFolder, fileName, NameCollisionOption.ReplaceExisting);
                }
                else if (string.Equals(decryptedMediaDocument45.FileExt, "mp3", StringComparison.OrdinalIgnoreCase))
                {
                    var musicProperties = await file.Properties.GetMusicPropertiesAsync();

                    if (musicProperties != null)
                    {
                        var documentAttributeAudio = new TLDocumentAttributeAudio32 {
                            Duration = new TLInt(0), Title = TLString.Empty, Performer = TLString.Empty
                        };
                        documentAttributeAudio.Duration = new TLInt((int)musicProperties.Duration.TotalSeconds);
                        if (!string.IsNullOrEmpty(musicProperties.Title))
                        {
                            documentAttributeAudio.Title = new TLString(musicProperties.Title);
                        }
                        if (!string.IsNullOrEmpty(musicProperties.Artist))
                        {
                            documentAttributeAudio.Performer = new TLString(musicProperties.Artist);
                        }
                        decryptedMediaDocument45.Attributes.Add(documentAttributeAudio);
                    }
                }
            }
            var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaDocumentBase, chat, true);

            BeginOnUIThread(() =>
            {
                InsertSendingMessage(decryptedTuple.Item1);
                RaiseScrollToBottom();
                NotifyOfPropertyChange(() => DescriptionVisibility);

                BeginOnThreadPool(() =>
                                  CacheService.SyncDecryptedMessage(decryptedTuple.Item1, chat,
                                                                    cachedMessage => SendDocumentInternal(file, decryptedTuple.Item2)));
            });
        }
        private static TLDecryptedMessageMediaBase GetDecryptedMediaDocument(StorageFile file, TLEncryptedChat chat, TLPhotoSize thumb, ulong size, Telegram.Api.WindowsPhone.Tuple <TLString, TLString> keyIV, TLEncryptedFile fileLocation)
        {
            TLDecryptedMessageMediaBase decryptedMediaDocument;
            var chat17 = chat as TLEncryptedChat17;

            if (chat17 != null)
            {
                if (chat17.Layer.Value >= Constants.MinSecretChatWithCaptionsLayer)
                {
                    decryptedMediaDocument = new TLDecryptedMessageMediaDocument45
                    {
                        Thumb    = thumb != null ? thumb.Bytes : TLString.Empty,
                        ThumbW   = thumb != null ? thumb.W : new TLInt(0),
                        ThumbH   = thumb != null ? thumb.H : new TLInt(0),
                        FileName = new TLString(Path.GetFileName(file.Name)),
                        MimeType = new TLString(file.ContentType),
                        Size     = new TLInt((int)size),
                        Key      = keyIV.Item1,
                        IV       = keyIV.Item2,
                        Caption  = TLString.Empty,

                        File              = fileLocation,
                        StorageFile       = file,
                        UploadingProgress = 0.001
                    };
                }
                else
                {
                    decryptedMediaDocument = new TLDecryptedMessageMediaDocument
                    {
                        Thumb             = thumb != null ? thumb.Bytes : TLString.Empty,
                        ThumbW            = thumb != null ? thumb.W : new TLInt(0),
                        ThumbH            = thumb != null ? thumb.H : new TLInt(0),
                        FileName          = new TLString(Path.GetFileName(file.Name)),
                        MimeType          = new TLString(file.ContentType),
                        Size              = new TLInt((int)size),
                        Key               = keyIV.Item1,
                        IV                = keyIV.Item2,
                        File              = fileLocation,
                        StorageFile       = file,
                        UploadingProgress = 0.001
                    };
                }
            }
            else
            {
                decryptedMediaDocument = new TLDecryptedMessageMediaDocument
                {
                    Thumb             = thumb != null ? thumb.Bytes : TLString.Empty,
                    ThumbW            = thumb != null ? thumb.W : new TLInt(0),
                    ThumbH            = thumb != null ? thumb.H : new TLInt(0),
                    FileName          = new TLString(Path.GetFileName(file.Name)),
                    MimeType          = new TLString(file.ContentType),
                    Size              = new TLInt((int)size),
                    Key               = keyIV.Item1,
                    IV                = keyIV.Item2,
                    File              = fileLocation,
                    StorageFile       = file,
                    UploadingProgress = 0.001
                };
            }
            return(decryptedMediaDocument);
        }
        private static TLDecryptedMessageMediaBase GetDecryptedMediaDocument(Photo p, TLEncryptedChat chat, TLString thumb, TLInt thumbW, TLInt thumbH, TLString mimeType, Telegram.Api.WindowsPhone.Tuple <TLString, TLString> keyIV, TLEncryptedFile fileLocation)
        {
            TLDecryptedMessageMediaBase decryptedMediaDocument;
            var chat17 = chat as TLEncryptedChat17;

            if (chat17 != null)
            {
                if (chat17.Layer.Value >= Constants.MinSecretChatWithCaptionsLayer)
                {
                    decryptedMediaDocument = new TLDecryptedMessageMediaDocument45
                    {
                        Thumb    = thumb,
                        ThumbW   = thumbW,
                        ThumbH   = thumbH,
                        FileName = new TLString(Path.GetFileName(p.FileName)),
                        MimeType = mimeType,
                        Size     = new TLInt(p.Bytes.Length),
                        Key      = keyIV.Item1,
                        IV       = keyIV.Item2,
                        Caption  = TLString.Empty,

                        File = fileLocation,
                        UploadingProgress = 0.001
                    };
                }
                else
                {
                    decryptedMediaDocument = new TLDecryptedMessageMediaDocument
                    {
                        Thumb    = thumb,
                        ThumbW   = thumbW,
                        ThumbH   = thumbH,
                        FileName = new TLString(Path.GetFileName(p.FileName)),
                        MimeType = mimeType,
                        Size     = new TLInt(p.Bytes.Length),
                        Key      = keyIV.Item1,
                        IV       = keyIV.Item2,

                        File = fileLocation,
                        UploadingProgress = 0.001
                    };
                }
            }
            else
            {
                decryptedMediaDocument = new TLDecryptedMessageMediaDocument
                {
                    Thumb    = thumb,
                    ThumbW   = thumbW,
                    ThumbH   = thumbH,
                    FileName = new TLString(Path.GetFileName(p.FileName)),
                    MimeType = mimeType,
                    Size     = new TLInt(p.Bytes.Length),
                    Key      = keyIV.Item1,
                    IV       = keyIV.Item2,

                    File = fileLocation,
                    UploadingProgress = 0.001
                };
            }
            return(decryptedMediaDocument);
        }
        public void SendAudio(AudioEventArgs args)
        {
            var chat = Chat as TLEncryptedChat;

            if (chat == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(args.OggFileName))
            {
                return;
            }

            var dcId       = TLInt.Random();
            var id         = TLLong.Random();
            var accessHash = TLLong.Random();

            var oggFileName = String.Format("audio{0}_{1}.mp3", id, accessHash);
            var wavFileName = Path.GetFileNameWithoutExtension(oggFileName) + ".wav";

            long size = 0;

            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                storage.MoveFile(args.OggFileName, oggFileName);
                using (var file = storage.OpenFile(oggFileName, FileMode.Open, FileAccess.Read))
                {
                    size = file.Length;
                }

                var wavStream = Wav.GetWavAsMemoryStream(args.PcmStream, 16000, 1, 16);
                using (var file = new IsolatedStorageFileStream(wavFileName, FileMode.OpenOrCreate, storage))
                {
                    wavStream.Seek(0, SeekOrigin.Begin);
                    wavStream.CopyTo(file);
                    file.Flush();
                }
            }

            var fileLocation = new TLEncryptedFile
            {
                Id             = id,
                AccessHash     = accessHash,
                DCId           = dcId,
                Size           = new TLInt((int)size),
                KeyFingerprint = new TLInt(0),
                FileName       = new TLString(Path.GetFileName(oggFileName))
            };

            var keyIV = GenerateKeyIV();
            TLDecryptedMessageMediaAudio decryptedMediaAudio;
            var encryptedChat17 = chat as TLEncryptedChat17;

            if (encryptedChat17 != null)
            {
                decryptedMediaAudio = new TLDecryptedMessageMediaAudio17
                {
                    Duration = new TLInt((int)args.Duration),
                    MimeType = new TLString("audio/ogg"),
                    Size     = new TLInt((int)size),
                    Key      = keyIV.Item1,
                    IV       = keyIV.Item2,

                    UserId = new TLInt(StateService.CurrentUserId),
                    File   = fileLocation,

                    UploadingProgress = 0.001
                };
            }
            else
            {
                decryptedMediaAudio = new TLDecryptedMessageMediaAudio
                {
                    Duration = new TLInt((int)args.Duration),
                    //MimeType = new TLString("audio/ogg"),
                    Size = new TLInt((int)size),
                    Key  = keyIV.Item1,
                    IV   = keyIV.Item2,

                    UserId = new TLInt(StateService.CurrentUserId),
                    File   = fileLocation,

                    UploadingProgress = 0.001
                };
            }

            var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaAudio, chat, true);

            BeginOnUIThread(() =>
            {
                Items.Insert(0, decryptedTuple.Item1);
                NotifyOfPropertyChange(() => DescriptionVisibility);
            });

            BeginOnThreadPool(() =>
                              CacheService.SyncDecryptedMessage(decryptedTuple.Item1, chat,
                                                                cachedMessage => SendAudioInternal(decryptedTuple.Item2)));
        }
        private void SendVideo(string videoFileName, long duration)
        {
            var chat = Chat as TLEncryptedChat;

            if (chat == null)
            {
                return;
            }

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

            long size = 0;

            byte[] data;
            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var file = storage.OpenFile(videoFileName, FileMode.Open, FileAccess.Read))
                {
                    size = file.Length;
                    data = new byte[size];
                    file.Read(data, 0, data.Length);
                }
            }

            byte[] thumb;
            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var file = storage.OpenFile(videoFileName + ".jpg", FileMode.Open, FileAccess.Read))
                {
                    thumb = new byte[file.Length];
                    file.Read(thumb, 0, thumb.Length);
                }
            }

            var dcId       = TLInt.Random();
            var id         = TLLong.Random();
            var accessHash = TLLong.Random();

            var fileLocation = new TLEncryptedFile
            {
                Id             = id,
                AccessHash     = accessHash,
                DCId           = dcId,
                Size           = new TLInt((int)size),
                KeyFingerprint = new TLInt(0),
                FileName       = new TLString(""),
                Duration       = new TLInt((int)duration)
            };

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

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                store.CopyFile(videoFileName, fileName, true);
                store.DeleteFile(videoFileName);
            }

            var keyIV = GenerateKeyIV();

            int thumbHeight;
            int thumbWidth;

            thumb = ImageUtils.CreateThumb(thumb, Constants.VideoPreviewMaxSize, Constants.VideoPreviewQuality, out thumbHeight, out thumbWidth);

            TLDecryptedMessageMediaVideo decryptedMediaVideo;
            var encryptedChat17 = chat as TLEncryptedChat17;

            if (encryptedChat17 != null)
            {
                decryptedMediaVideo = new TLDecryptedMessageMediaVideo17
                {
                    Thumb    = TLString.FromBigEndianData(thumb),
                    ThumbW   = new TLInt(thumbWidth),
                    ThumbH   = new TLInt(thumbHeight),
                    Duration = new TLInt((int)duration),
                    MimeType = new TLString("video/mp4"),
                    W        = new TLInt(640),
                    H        = new TLInt(480),
                    Size     = new TLInt((int)size),
                    Key      = keyIV.Item1,
                    IV       = keyIV.Item2,

                    File = fileLocation,

                    UploadingProgress = 0.001
                };
            }
            else
            {
                decryptedMediaVideo = new TLDecryptedMessageMediaVideo
                {
                    Thumb    = TLString.FromBigEndianData(thumb),
                    ThumbW   = new TLInt(thumbWidth),
                    ThumbH   = new TLInt(thumbHeight),
                    Duration = new TLInt((int)duration),
                    //MimeType = new TLString("video/mp4"),
                    W    = new TLInt(640),
                    H    = new TLInt(480),
                    Size = new TLInt((int)size),
                    Key  = keyIV.Item1,
                    IV   = keyIV.Item2,

                    File = fileLocation,

                    UploadingProgress = 0.001
                };
            }

            var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaVideo, chat, true);

            Items.Insert(0, decryptedTuple.Item1);
            RaiseScrollToBottom();
            NotifyOfPropertyChange(() => DescriptionVisibility);

            BeginOnThreadPool(() =>
                              CacheService.SyncDecryptedMessage(decryptedTuple.Item1, chat,
                                                                cachedMessage => SendVideoInternal(data, decryptedTuple.Item2)));
        }
        public async Task <Telegram.Api.WindowsPhone.Tuple <TLDecryptedMessageBase, TLObject> > GetPhotoMessage(StorageFile file)
        {
            var chat = Chat as TLEncryptedChat;

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

            if (file == null)
            {
                return(null);
            }

            var properties = await file.GetBasicPropertiesAsync();

            var size = properties.Size;

            var thumb = await DialogDetailsViewModel.GetFileThumbAsync(file) as TLPhotoSize;

            var dcId       = TLInt.Random();
            var id         = TLLong.Random();
            var accessHash = TLLong.Random();

            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                         id,
                                         dcId,
                                         accessHash);

            var stream = await file.OpenReadAsync();

            var resizedPhoto = await DialogDetailsViewModel.ResizeJpeg(stream, Constants.DefaultImageSize, file.DisplayName, fileName);

            var keyIV = GenerateKeyIV();

            var fileLocation = new TLEncryptedFile
            {
                Id             = id,
                AccessHash     = accessHash,
                DCId           = dcId,
                Size           = new TLInt(resizedPhoto.Bytes.Length),
                KeyFingerprint = new TLInt(0),
                FileName       = new TLString(Path.GetFileName(file.Name))
            };

            TLDecryptedMessageMediaPhoto decryptedMediaPhoto;
            var chat17 = chat as TLEncryptedChat17;

            if (chat17 != null && chat17.Layer.Value >= Constants.MinSecretChatWithCaptionsLayer)
            {
                decryptedMediaPhoto = new TLDecryptedMessageMediaPhoto45
                {
                    Thumb   = thumb != null ? thumb.Bytes : TLString.Empty,
                    ThumbW  = thumb != null ? thumb.W : new TLInt(0),
                    ThumbH  = thumb != null ? thumb.H : new TLInt(0),
                    Size    = new TLInt(resizedPhoto.Bytes.Length),
                    Key     = keyIV.Item1,
                    IV      = keyIV.Item2,
                    W       = new TLInt(resizedPhoto.Width),
                    H       = new TLInt(resizedPhoto.Height),
                    Caption = TLString.Empty,

                    File        = fileLocation,
                    StorageFile = resizedPhoto.File,

                    UploadingProgress = 0.001
                };
            }
            else
            {
                decryptedMediaPhoto = new TLDecryptedMessageMediaPhoto
                {
                    Thumb  = thumb != null ? thumb.Bytes : TLString.Empty,
                    ThumbW = thumb != null ? thumb.W : new TLInt(0),
                    ThumbH = thumb != null ? thumb.H : new TLInt(0),
                    Size   = new TLInt(resizedPhoto.Bytes.Length),
                    Key    = keyIV.Item1,
                    IV     = keyIV.Item2,
                    W      = new TLInt(resizedPhoto.Width),
                    H      = new TLInt(resizedPhoto.Height),

                    File        = fileLocation,
                    StorageFile = resizedPhoto.File,

                    UploadingProgress = 0.001
                };
            }

            var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaPhoto, chat, true);

            return(decryptedTuple);
        }
        public IAsyncOperationWithProgress <DownloadableItem, double> DownloadFileAsync(TLEncryptedFile file)
        {
            return(AsyncInfo.Run <DownloadableItem, double>((token, progress) =>
            {
                var tsc = new TaskCompletionSource <DownloadableItem>();

                var inputFile = new TLInputEncryptedFileLocation {
                    Id = file.Id, AccessHash = file.AccessHash
                };
                var downloadableItem = GetDownloadableItem(file.DCId, inputFile, null, file.Size);
                downloadableItem.Callback = tsc;
                downloadableItem.Progress = progress;

                lock (_itemsSyncRoot)
                {
                    bool addFile = true;
                    foreach (var item in _items)
                    {
                        if (item.InputEncryptedFileLocation.LocationEquals(inputFile))
                        {
                            addFile = false;
                            break;
                        }
                    }

                    if (addFile)
                    {
                        _items.Add(downloadableItem);
                    }
                }

                StartAwaitingWorkers();

                return tsc.Task;
            }));
        }
        public async void SendDocument(StorageFile file)
        {
            var chat = Chat as TLEncryptedChat;

            if (chat == null)
            {
                return;
            }

            if (file == null)
            {
                return;
            }

            var properties = await file.GetBasicPropertiesAsync();

            var size = properties.Size;

            if (!DialogDetailsViewModel.CheckDocumentSize(size))
            {
                MessageBox.Show(string.Format(AppResources.MaximumFileSizeExceeded, MediaSizeConverter.Convert((int)Telegram.Api.Constants.MaximumUploadedFileSize)), AppResources.Error, MessageBoxButton.OK);
                return;
            }

            DialogDetailsViewModel.AddFileToFutureAccessList(file);

            var thumb = await DialogDetailsViewModel.GetFileThumbAsync(file) as TLPhotoSize;

            var dcId       = TLInt.Random();
            var id         = TLLong.Random();
            var accessHash = TLLong.Random();

            var fileLocation = new TLEncryptedFile
            {
                Id             = id,
                AccessHash     = accessHash,
                DCId           = dcId,
                Size           = new TLInt((int)size),
                KeyFingerprint = new TLInt(0),
                FileName       = new TLString(Path.GetFileName(file.Name))
            };

            var keyIV = GenerateKeyIV();

            var decryptedMediaDocument = new TLDecryptedMessageMediaDocument
            {
                Thumb    = thumb != null? thumb.Bytes : TLString.Empty,
                ThumbW   = thumb != null? thumb.W : new TLInt(0),
                ThumbH   = thumb != null? thumb.H : new TLInt(0),
                FileName = new TLString(Path.GetFileName(file.Name)),
                MimeType = new TLString(file.ContentType),
                Size     = new TLInt((int)size),
                Key      = keyIV.Item1,
                IV       = keyIV.Item2,

                File        = fileLocation,
                StorageFile = file,

                UploadingProgress = 0.001
            };

            var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaDocument, chat, true);

            BeginOnUIThread(() =>
            {
                Items.Insert(0, decryptedTuple.Item1);
                RaiseScrollToBottom();
                NotifyOfPropertyChange(() => DescriptionVisibility);

                BeginOnThreadPool(() =>
                                  CacheService.SyncDecryptedMessage(decryptedTuple.Item1, chat,
                                                                    cachedMessage => SendDocumentInternal(file, decryptedTuple.Item2)));
            });
        }
        public void SendAudio(AudioEventArgs args)
        {
            var chat = Chat as TLEncryptedChat;

            if (chat == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(args.OggFileName))
            {
                return;
            }

            var dcId       = TLInt.Random();
            var id         = TLLong.Random();
            var accessHash = TLLong.Random();

            var oggFileName = String.Format("audio{0}_{1}.mp3", id, accessHash);
            var wavFileName = Path.GetFileNameWithoutExtension(oggFileName) + ".wav";

            long size = 0;

            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                storage.MoveFile(args.OggFileName, oggFileName);
                using (var file = storage.OpenFile(oggFileName, FileMode.Open, FileAccess.Read))
                {
                    size = file.Length;
                }

                var wavStream = Wav.GetWavAsMemoryStream(args.PcmStream, 16000, 1, 16);
                using (var file = new IsolatedStorageFileStream(wavFileName, FileMode.OpenOrCreate, storage))
                {
                    wavStream.Seek(0, SeekOrigin.Begin);
                    wavStream.CopyTo(file);
                    file.Flush();
                }
            }

            var fileLocation = new TLEncryptedFile
            {
                Id             = id,
                AccessHash     = accessHash,
                DCId           = dcId,
                Size           = new TLInt((int)size),
                KeyFingerprint = new TLInt(0),
                FileName       = new TLString(Path.GetFileName(oggFileName))
            };

            var keyIV = GenerateKeyIV();
            TLDecryptedMessageMediaBase decryptedMediaAudio;
            var encryptedChat17 = chat as TLEncryptedChat17;

            if (encryptedChat17 != null)
            {
                if (encryptedChat17.Layer.Value >= Constants.MinSecretChatWithAudioAsDocumentsLayer)
                {
                    var opus          = new TelegramClient_Opus.WindowsPhoneRuntimeComponent();
                    var bytes         = opus.GetWaveform(ApplicationData.Current.LocalFolder.Path + "\\" + oggFileName);
                    var resultSamples = bytes.Length;
                    var bites2        = new BitArray(5 * bytes.Length);
                    var count         = 0;
                    for (var i = 0; i < bytes.Length; i++)
                    {
                        var result = bytes[i];
                        var bit1   = result >> 0 & 0x1;
                        var bit2   = result >> 1 & 0x1;
                        var bit3   = result >> 2 & 0x1;
                        var bit4   = result >> 3 & 0x1;
                        var bit5   = result >> 4 & 0x1;
                        bites2[count]     = Convert.ToBoolean(bit1);
                        bites2[count + 1] = Convert.ToBoolean(bit2);
                        bites2[count + 2] = Convert.ToBoolean(bit3);
                        bites2[count + 3] = Convert.ToBoolean(bit4);
                        bites2[count + 4] = Convert.ToBoolean(bit5);
                        count             = count + 5;
                    }

                    var bytesCount    = (resultSamples * 5) / 8 + (((resultSamples * 5) % 8) == 0 ? 0 : 1);
                    var waveformBytes = new byte[bytesCount];
                    bites2.CopyTo(waveformBytes, 0);
                    var waveform = waveformBytes != null?TLString.FromBigEndianData(waveformBytes) : TLString.Empty;

                    var audioAttribute = new TLDocumentAttributeAudio46
                    {
                        Flags    = new TLInt((int)DocumentAttributeAudioFlags.Voice),
                        Duration = new TLInt((int)args.Duration)
                    };

                    if (waveformBytes != null)
                    {
                        audioAttribute.Waveform = waveform;
                    }

                    var attributes = new TLVector <TLDocumentAttributeBase>
                    {
                        audioAttribute
                    };

                    decryptedMediaAudio = new TLDecryptedMessageMediaDocument45
                    {
                        Thumb       = TLString.Empty,
                        ThumbW      = new TLInt(0),
                        ThumbH      = new TLInt(0),
                        MimeType    = new TLString("audio/ogg"),
                        Size        = new TLInt((int)size),
                        Key         = keyIV.Item1,
                        IV          = keyIV.Item2,
                        Attributes  = attributes,
                        Caption     = TLString.Empty,
                        NotListened = true,

                        File = fileLocation,

                        UploadingProgress = 0.001
                    };
                }
                else
                {
                    decryptedMediaAudio = new TLDecryptedMessageMediaAudio17
                    {
                        Duration = new TLInt((int)args.Duration),
                        MimeType = new TLString("audio/ogg"),
                        Size     = new TLInt((int)size),
                        Key      = keyIV.Item1,
                        IV       = keyIV.Item2,

                        UserId = new TLInt(StateService.CurrentUserId),
                        File   = fileLocation,

                        UploadingProgress = 0.001
                    };
                }
            }
            else
            {
                decryptedMediaAudio = new TLDecryptedMessageMediaAudio
                {
                    Duration = new TLInt((int)args.Duration),
                    //MimeType = new TLString("audio/ogg"),
                    Size = new TLInt((int)size),
                    Key  = keyIV.Item1,
                    IV   = keyIV.Item2,

                    UserId = new TLInt(StateService.CurrentUserId),
                    File   = fileLocation,

                    UploadingProgress = 0.001
                };
            }

            var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaAudio, chat, true);

            //var message45 = decryptedTuple.Item1 as TLDecryptedMessage45;
            //if (message45 != null && message45.IsVoice())
            //{
            //    message45.NotListened = true;
            //}

            BeginOnUIThread(() =>
            {
                InsertSendingMessage(decryptedTuple.Item1);
                NotifyOfPropertyChange(() => DescriptionVisibility);
            });

            BeginOnThreadPool(() =>
                              CacheService.SyncDecryptedMessage(decryptedTuple.Item1, chat,
                                                                cachedMessage => SendAudioInternal(decryptedTuple.Item2)));
        }