System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication()

Here are the examples of the csharp api System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

81 Examples 7

19 Source : IsolatedStorageUtility.cs
with MIT License
from CalciumFramework

public async Task CopyApplicationResourceToIsolatedStorageAsync(
							string inResourceName, string outFilename)
		{
			replacedertArg.IsNotNull(inResourceName, nameof(inResourceName));
			replacedertArg.IsNotNull(outFilename, nameof(outFilename));

			Uri uri = new Uri(inResourceName, UriKind.Relative);

			using (Stream resourceStream = await GetApplicationResourceStreamAsync(uri))//Application.GetResourceStream(uri).Stream)
			{
				using (IsolatedStorageFile isolatedStorageFile
							= IsolatedStorageFile.GetUserStoreForApplication())
				{
					using (IsolatedStorageFileStream outStream
						= isolatedStorageFile.CreateFile(outFilename))
					{
						resourceStream.CopyTo(outStream);
					}
				}
			}
		}

19 Source : IsolatedStorageUtility.cs
with MIT License
from CalciumFramework

public bool FileExists(string path)
		{
			replacedertArg.IsNotNull(path, nameof(path));

			using (IsolatedStorageFile isolatedStorageFile 
				= IsolatedStorageFile.GetUserStoreForApplication())
			{
				return isolatedStorageFile.FileExists(path);
			}
		}

19 Source : IsolatedStorageUtility.cs
with MIT License
from CalciumFramework

public async Task CopyApplicationResourcesToIsolatedStorageAsync(
							IEnumerable<KeyValuePair<string, string>> sourceToDestinationList)
		{
			replacedertArg.IsNotNull(sourceToDestinationList, nameof(sourceToDestinationList));

			using (IsolatedStorageFile isolatedStorageFile
						= IsolatedStorageFile.GetUserStoreForApplication())
			{
				foreach (var sourceAndDestination in sourceToDestinationList)
				{
					Uri uri = new Uri(sourceAndDestination.Key, UriKind.Relative);
					using (Stream resourceStream = await GetApplicationResourceStreamAsync(uri))//Application.GetResourceStream(uri).Stream)
					{
						string destination = sourceAndDestination.Value;
						if (string.IsNullOrWhiteSpace(destination))
						{
							throw new ArgumentException($"Key '{sourceAndDestination.Key}' has null pair Value. A destination must be specified.");
						}

						int separatorIndex = destination.LastIndexOf("/");
						if (separatorIndex == destination.Length - 1)
						{
							throw new InvalidOperationException(
								$"Destination '{destination}' should not end with '/'");
						}
						string directory = null;
						if (separatorIndex != -1)
						{
							directory = destination.Substring(0, separatorIndex);
						}

						if (!string.IsNullOrWhiteSpace(directory)
							&& !isolatedStorageFile.DirectoryExists(directory))
						{
							isolatedStorageFile.CreateDirectory(directory);
						}

						//						if (isolatedStorageFile.FileExists(destination))
						//						{
						//							isolatedStorageFile.DeleteFile(destination);
						//						}

						using (IsolatedStorageFileStream outStream
									= isolatedStorageFile.CreateFile(destination))
						{
							resourceStream.CopyTo(outStream);
						}
					}
				}
			}
		}

19 Source : IsolatedStorageService.cs
with GNU General Public License v2.0
from digital-jellyfish

[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        protected virtual IsolatedStorageFile GetStore()
        {
            return IsolatedStorageFile.GetUserStoreForApplication();
        }

19 Source : WpfStorageService.cs
with GNU General Public License v2.0
from digital-jellyfish

protected override IsolatedStorageFile GetStore()
        {
            return ApplicationDeployment.IsNetworkDeployed ? // clickonce
                IsolatedStorageFile.GetUserStoreForApplication() : IsolatedStorageFile.GetUserStoreForreplacedembly();
        }

19 Source : WindowsProtectedStorage.cs
with MIT License
from dotnet

private async Task Write()
        {
            try
            {
                using var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                using var stream = isolatedStorage.OpenFile(ProtectedStorageFileName, FileMode.Create, FileAccess.Write, FileShare.None);
                using var dataProtectionStream = new DataProtectionStream(stream, System.Security.Cryptography.DataProtectionScope.CurrentUser);
                await JsonSerializer.SerializeAsync(dataProtectionStream, _values).ConfigureAwait(false);
                dataProtectionStream.FlushFinalBlock();
                dataProtectionStream.Close();
                stream.Close();
            }
            finally
            {
                _writeTask = null;
            }
        }

19 Source : WindowsProtectedStorage.cs
with MIT License
from dotnet

private async Task Read()
        {
            try
            {
                using var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                if (isolatedStorage.FileExists(ProtectedStorageFileName))
                {
                    using var stream = isolatedStorage.OpenFile(ProtectedStorageFileName, FileMode.Open, FileAccess.Read, FileShare.None);
                    using var dataProtectionStream = new DataProtectionStream(stream, System.Security.Cryptography.DataProtectionScope.CurrentUser);
                    _values = await JsonSerializer.DeserializeAsync<ConcurrentDictionary<string, string>>(dataProtectionStream).ConfigureAwait(false);
                    dataProtectionStream.Close();
                    stream.Close();
                }

                if (_values == null)
                {
                    _values = new ConcurrentDictionary<string, string>();
                }
            }
            finally
            {
                _readTask = null;
            }
        }

19 Source : EmojiData.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static void LoadRecents()
        {

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists("EmojiRecents")) return;
                using (var stream = new IsolatedStorageFileStream("EmojiRecents", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite, store))
                {
                    if (stream.Length <= 0) return;

                    using (var br = new BinaryReader(stream))
                    {
                        var count = br.ReadInt32();

                        Recents = new List<EmojiDataItem>();

                        for (var i = 0; i < count; i++)
                        {
                            var emoji = new EmojiDataItem(br.ReadString(), br.ReadUInt64());
                            Recents.Add(emoji);
                        }
                    }
                }
            }
        }

19 Source : EmojiData.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static void SaveRecents()
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var stream = new IsolatedStorageFileStream("EmojiRecents", FileMode.Create, FileAccess.Write, FileShare.ReadWrite, store))
                {
                    using (var bw = new BinaryWriter(stream))
                    {
                        var emojies = Recents.ToList();

                        bw.Write(emojies.Count);

                        foreach (var item in emojies)
                        {
                            bw.Write(item.String);
                            bw.Write(item.Code);
                        }
                    }
                }
            }
        }

19 Source : BackgroundImageConverter.cs
with GNU General Public License v2.0
from evgeny-nadymov

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var bagroundItem = value as BackgroundItem;
            if (bagroundItem == null) return null;

            if (string.Equals(bagroundItem.Name, Constants.LibraryBackgroundString))
            {
                var fileName = bagroundItem.IsoFileName;
                if (!string.IsNullOrEmpty(fileName))
                {
                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!store.FileExists(fileName))
                        {
                            return null;
                        }

                        BitmapImage imageSource;

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

                        return imageSource;
                    }
                }

                return bagroundItem.SourceString;
            }

            if (bagroundItem.Name.StartsWith("telegram", StringComparison.OrdinalIgnoreCase))
            {
                var fileName = bagroundItem.IsoFileName;
                if (!string.IsNullOrEmpty(fileName))
                {
                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (store.FileExists(fileName))
                        {
                            BitmapImage imageSource;

                            try
                            {
                                using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                {
                                    stream.Seek(0, SeekOrigin.Begin);
                                    var b = new BitmapImage();
                                    b.CreateOptions = CreateOptions;
                                    b.SetSource(stream);
                                    imageSource = b;
                                }

                                return imageSource;
                            }
                            catch (Exception)
                            {
                                return null;
                            }
                        }
                    }
                }
            }

            if (bagroundItem.Wallpaper != null)
            {
                var width = 99.0;
                double result;
                if (Double.TryParse((string)parameter, out result))
                {
                    width = result;
                }

                var size = GetPhotoSize(bagroundItem.Wallpaper.Sizes, width);

                if (size != null)
                {
                    var location = size.Location as TLFileLocation;
                    if (location != null)
                    {
                        return DefaultPhotoConverter.ReturnOrEnqueueImage(null, false, location, bagroundItem.Wallpaper, size.Size, null);
                    }
                }
            }

            var isLightTheme = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"] == Visibility.Visible;
            var image = new BitmapImage();
            image.CreateOptions = CreateOptions;
            image.UriSource = isLightTheme? new Uri("/Images/W10M/default.png", UriKind.Relative) : null;
            return image;
        }

19 Source : ExtendedImageConverter.cs
with GNU General Public License v2.0
from evgeny-nadymov

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var imageSource = value as string;
            if (imageSource != null)
            {
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (store.FileExists(imageSource))
                    {
                        var file = store.OpenFile(imageSource, FileMode.Open, FileAccess.Read);
                        {

                            var image = new ExtendedImage();
                            image.LoadingCompleted += (sender, args) =>
                            {
                                var count = image.Frames.Count;
                            };
                            image.LoadingFailed += (sender, args) =>
                            {

                            };
                            image.SetSource(file);
                            return image;
                        }
                    }
                }
            }

            return null;
        }

19 Source : GeoPointToStaticGoogleMapsConverter.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static BitmapSource ReturnOrEnqueueGeoPointImage(TLGeoPoint geoPoint, int width, int height, TLObject owner)
        {
            var destFileName = geoPoint.GetFileName();

            BitmapSource imageSource;
            WeakReference weakImageSource;
            if (_cachedSources.TryGetValue(destFileName, out weakImageSource))
            {
                if (weakImageSource.IsAlive)
                {
                    imageSource = weakImageSource.Target as BitmapSource;

                    return imageSource;
                }
            }

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists(destFileName))
                {
                    var sourceUri = string.Format(Constants.StaticGoogleMap, geoPoint.Lat.Value.ToString(new CultureInfo("en-US")), geoPoint.Long.Value.ToString(new CultureInfo("en-US")), width, height);

                    var fileManager = IoC.Get<IHttpDoreplacedentFileManager>();

                    fileManager.DownloadFileAsync(sourceUri, destFileName, owner, item =>
                    {
                        var messageMediaGeoPoint = owner as IMessageMediaGeoPoint;
                        if (messageMediaGeoPoint != null)
                        {
                            var newGeoPoint = messageMediaGeoPoint.Geo as TLGeoPoint;
                            if (newGeoPoint != null)
                            {
                                var newFileName = newGeoPoint.GetFileName();
                                var oldFileName = destFileName;

                                using (var store2 = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store2.FileExists(oldFileName))
                                    {
                                        if (!string.IsNullOrEmpty(oldFileName) && !string.Equals(oldFileName, newFileName, StringComparison.OrdinalIgnoreCase))
                                        {
                                            store2.CopyFile(oldFileName, newFileName, true);
                                            store2.DeleteFile(oldFileName);
                                        }
                                    }
                                }
                            }

                            Telegram.Api.Helpers.Execute.BeginOnUIThread(() =>
                            {
                                var messageMediaBase = owner as TLMessageMediaBase;
                                if (messageMediaBase != null)
                                {
                                    messageMediaBase.NotifyOfPropertyChange(() => messageMediaBase.Self);
                                }
                                var decryptedMessageMediaBase = owner as TLDecryptedMessageMediaBase;
                                if (decryptedMessageMediaBase != null)
                                {
                                    decryptedMessageMediaBase.NotifyOfPropertyChange(() => decryptedMessageMediaBase.Self);
                                }
                            });
                        }
                    });
                }
                else
                {
                    try
                    {
                        using (var stream = store.OpenFile(destFileName, FileMode.Open, FileAccess.Read))
                        {
                            stream.Seek(0, SeekOrigin.Begin);
                            var image = new BitmapImage();
                            image.SetSource(stream);
                            imageSource = image;
                        }

                        _cachedSources[destFileName] = new WeakReference(imageSource);
                    }
                    catch (Exception)
                    {
                        return null;
                    }

                    return imageSource;
                }
            }

            return null;
        }

19 Source : MediaEmptyToVisibilityConverter.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static bool MediaFileExists(TLMessageMediaBase value)
        {
            var mediaDoreplacedent = value as TLMessageMediaDoreplacedent;
            if (mediaDoreplacedent == null)
            {
                return true;
            }

            if (!string.IsNullOrEmpty(mediaDoreplacedent.IsoFileName))
            {
                return true;
            }

            var doreplacedent = mediaDoreplacedent.Doreplacedent as TLDoreplacedent;
            if (doreplacedent == null)
            {
                return true;
            }

            if (doreplacedent.Size.Value == 0)
            {
                return true;
            }

            var fileName = doreplacedent.GetFileName();

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (store.FileExists(fileName))
                {
                    return true;
                }
            }

            return false;
        }

19 Source : PhotoToThumbConverter.cs
with GNU General Public License v2.0
from evgeny-nadymov

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var isBlurEnabled = parameter == null || !string.Equals(parameter.ToString(), "noblur", StringComparison.OrdinalIgnoreCase);

            var options = BitmapCreateOptions.DelayCreation | BitmapCreateOptions.BackgroundCreation;

            var decryptedMediaPhoto = value as TLDecryptedMessageThumbMediaBase;
            if (decryptedMediaPhoto != null)
            {
                var buffer = decryptedMediaPhoto.Thumb.Data;

                if (buffer.Length > 0
                    && decryptedMediaPhoto.ThumbW.Value > 0
                    && decryptedMediaPhoto.ThumbH.Value > 0)
                {
                    if (!isBlurEnabled)
                    {
                        return ImageUtils.CreateImage(buffer, options);
                    }
                    else
                    {
                        try
                        {
                            var memoryStream = new MemoryStream(buffer);
                            var bitmap = PictureDecoder.DecodeJpeg(memoryStream);

                            BlurBitmap(bitmap, Secret);

                            var blurredStream = new MemoryStream();
                            bitmap.SaveJpeg(blurredStream, decryptedMediaPhoto.ThumbW.Value, decryptedMediaPhoto.ThumbH.Value, 0, 100);

                            return ImageUtils.CreateImage(blurredStream, options);
                        }
                        catch (Exception ex)
                        {
                            
                        }
                    }
                }

                return null;
            }

            var mediaDoreplacedent = value as TLMessageMediaDoreplacedent;
            if (mediaDoreplacedent != null)
            {
                var doreplacedent = mediaDoreplacedent.Doreplacedent as TLDoreplacedent;
                if (doreplacedent != null)
                {
                    var size = doreplacedent.Thumb as TLPhotoSize;
                    if (size != null)
                    {
                        if (!string.IsNullOrEmpty(size.TempUrl))
                        {
                            return size.TempUrl;
                        }

                        var location = size.Location as TLFileLocation;
                        if (location != null)
                        {
                            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                location.VolumeId,
                                location.LocalId,
                                location.Secret);

                            if (!isBlurEnabled)
                            {
                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                return ImageUtils.CreateImage(stream, options);
                                            }
                                        }
                                        catch (Exception ex)
                                        {

                                        }
                                    }
                                    else
                                    {
                                        var fileManager = IoC.Get<IFileManager>();
                                        fileManager.DownloadFile(location, doreplacedent, size.Size,
                                            item =>
                                            {
                                                mediaDoreplacedent.NotifyOfPropertyChange(() => mediaDoreplacedent.ThumbSelf);
                                            });
                                    }
                                }
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetDoreplacedentPreview(doreplacedent.Id, out preview, options))
                                {
                                    return preview;
                                }

                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                BlurBitmap(bitmap, Secret);

                                                var blurredStream = new MemoryStream();
                                                bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                return bitmap;
                                            }
                                        }
                                        catch (Exception ex)
                                        {

                                        }
                                    }
                                }

                                var fileManager = IoC.Get<IFileManager>();
                                fileManager.DownloadFile(location, doreplacedent, size.Size,
                                    item =>
                                    {
                                        Execute.BeginOnUIThread(() =>
                                        {
                                            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                            {
                                                if (store.FileExists(fileName))
                                                {
                                                    try
                                                    {
                                                        using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                                        {
                                                            var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                            BlurBitmap(bitmap, Secret);

                                                            var blurredStream = new MemoryStream();
                                                            bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                            var previewfileName = string.Format("preview_doreplacedent{0}.jpg", doreplacedent.Id);
                                                            SaveFile(previewfileName, blurredStream);

                                                            mediaDoreplacedent.NotifyOfPropertyChange(() => mediaDoreplacedent.ThumbSelf);
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {

                                                    }
                                                }
                                            }
                                        });
                                    });
                            }
                        }
                    }

                    var cachedSize = doreplacedent.Thumb as TLPhotoCachedSize;
                    if (cachedSize != null)
                    {
                        if (!string.IsNullOrEmpty(cachedSize.TempUrl))
                        {
                            return cachedSize.TempUrl;
                        }

                        var buffer = cachedSize.Bytes.Data;

                        if (buffer != null && buffer.Length > 0)
                        {
                            if (!isBlurEnabled)
                            {
                                return ImageUtils.CreateImage(buffer, options);
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetDoreplacedentPreview(doreplacedent.Id, out preview, options))
                                {
                                    return preview;
                                }

                                try
                                {
                                    var bitmap = PictureDecoder.DecodeJpeg(new MemoryStream(buffer));

                                    BlurBitmap(bitmap, Secret);

                                    var blurredStream = new MemoryStream();
                                    bitmap.SaveJpeg(blurredStream, cachedSize.W.Value, cachedSize.H.Value, 0, 100);

                                    var fileName = string.Format("preview_doreplacedent{0}.jpg", doreplacedent.Id);

                                    Telegram.Api.Helpers.Execute.BeginOnThreadPool(() => SaveFile(fileName, blurredStream));

                                    return ImageUtils.CreateImage(blurredStream, options);
                                }
                                catch (Exception ex)
                                {

                                }
                            }
                        }

                        return null;
                    }

                    return null;
                }
            }

            var mediaPhoto = value as TLMessageMediaPhoto;
            if (mediaPhoto != null)
            {
                var photo = mediaPhoto.Photo as TLPhoto;
                if (photo != null)
                {
                    var size = photo.Sizes.FirstOrDefault(x => TLString.Equals(x.Type, new TLString("s"), StringComparison.OrdinalIgnoreCase)) as TLPhotoSize;
                    if (size != null)
                    {
                        if (!string.IsNullOrEmpty(size.TempUrl))
                        {
                            return size.TempUrl;
                        }

                        var location = size.Location as TLFileLocation;
                        if (location != null)
                        {
                            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                location.VolumeId,
                                location.LocalId,
                                location.Secret);

                            if (!isBlurEnabled)
                            {
                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                return ImageUtils.CreateImage(stream, options);
                                            }
                                        }
                                        catch (Exception ex)
                                        {

                                        }
                                    }
                                    else
                                    {
                                        var fileManager = IoC.Get<IFileManager>();
                                        fileManager.DownloadFile(location, photo, size.Size,
                                            item =>
                                            {
                                                mediaPhoto.NotifyOfPropertyChange(() => mediaPhoto.ThumbSelf);
                                            });
                                    }
                                }
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetPhotoPreview(photo.Id, out preview, options))
                                {
                                    return preview;
                                }

                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                BlurBitmap(bitmap, Secret);

                                                var blurredStream = new MemoryStream();
                                                bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                return bitmap;
                                            }
                                        }
                                        catch (Exception ex)
                                        {

                                        }
                                    }
                                }

                                if (location.DCId.Value == 0) return null;

                                var fileManager = IoC.Get<IFileManager>();
                                fileManager.DownloadFile(location, photo, size.Size,
                                    item =>
                                    {
                                        Execute.BeginOnUIThread(() =>
                                        {
                                            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                            {
                                                if (store.FileExists(fileName))
                                                {
                                                    try
                                                    {
                                                        using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                                        {
                                                            var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                            BlurBitmap(bitmap, Secret);

                                                            var blurredStream = new MemoryStream();
                                                            bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                            var previewfileName = string.Format("preview{0}.jpg", photo.Id);
                                                            SaveFile(previewfileName, blurredStream);

                                                            mediaPhoto.NotifyOfPropertyChange(() => mediaPhoto.ThumbSelf);
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {

                                                    }
                                                }
                                            }
                                        });
                                    });
                            }
                        }
                    }

                    var cachedSize = (TLPhotoCachedSize)photo.Sizes.FirstOrDefault(x => x is TLPhotoCachedSize);
                    if (cachedSize != null)
                    {
                        if (!string.IsNullOrEmpty(cachedSize.TempUrl))
                        {
                            return cachedSize.TempUrl;
                        }

                        var buffer = cachedSize.Bytes.Data;

                        if (buffer != null && buffer.Length > 0)
                        {
                            if (!isBlurEnabled)
                            {
                                return ImageUtils.CreateImage(buffer, options);
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetPhotoPreview(photo.Id, out preview, options))
                                {
                                    return preview;
                                }

                                try
                                {
                                    var bitmap = PictureDecoder.DecodeJpeg(new MemoryStream(buffer));

                                    BlurBitmap(bitmap, Secret);

                                    var blurredStream = new MemoryStream();
                                    bitmap.SaveJpeg(blurredStream, cachedSize.W.Value, cachedSize.H.Value, 0, 100);

                                    var fileName = string.Format("preview{0}.jpg", photo.Id);

                                    Telegram.Api.Helpers.Execute.BeginOnThreadPool(() => SaveFile(fileName, blurredStream));

                                    return ImageUtils.CreateImage(blurredStream, options);
                                }
                                catch (Exception ex)
                                {

                                }
                            }
                        }

                        return null;
                    }

                    return null;
                }
            }

            var mediaGame = value as TLMessageMediaGame;
            if (mediaGame != null)
            {
                var photo = mediaGame.Photo as TLPhoto;
                if (photo != null)
                {
                    var size = photo.Sizes.FirstOrDefault(x => TLString.Equals(x.Type, new TLString("s"), StringComparison.OrdinalIgnoreCase)) as TLPhotoSize;
                    if (size != null)
                    {
                        if (!string.IsNullOrEmpty(size.TempUrl))
                        {
                            return size.TempUrl;
                        }

                        var location = size.Location as TLFileLocation;
                        if (location != null)
                        {
                            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                location.VolumeId,
                                location.LocalId,
                                location.Secret);

                            if (!isBlurEnabled)
                            {
                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                return ImageUtils.CreateImage(stream, options);
                                            }
                                        }
                                        catch (Exception ex)
                                        {

                                        }
                                    }
                                    else
                                    {
                                        var fileManager = IoC.Get<IFileManager>();
                                        fileManager.DownloadFile(location, photo, size.Size,
                                            item =>
                                            {
                                                mediaGame.NotifyOfPropertyChange(() => mediaGame.ThumbSelf);
                                            });
                                    }
                                }
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetPhotoPreview(photo.Id, out preview, options))
                                {
                                    return preview;
                                }

                                var fileManager = IoC.Get<IFileManager>();
                                fileManager.DownloadFile(location, photo, size.Size,
                                    item =>
                                    {
                                        Execute.BeginOnUIThread(() =>
                                        {
                                            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                            {
                                                if (store.FileExists(fileName))
                                                {
                                                    try
                                                    {
                                                        using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                                        {
                                                            var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                            BlurBitmap(bitmap, Secret);

                                                            var blurredStream = new MemoryStream();
                                                            bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                            var previewfileName = string.Format("preview{0}.jpg", photo.Id);
                                                            SaveFile(previewfileName, blurredStream);

                                                            mediaGame.NotifyOfPropertyChange(() => mediaGame.ThumbSelf);
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {

                                                    }
                                                }
                                            }
                                        });
                                    });
                            }
                        }
                    }

                    var cachedSize = (TLPhotoCachedSize) photo.Sizes.FirstOrDefault(x => x is TLPhotoCachedSize);
                    if (cachedSize != null)
                    {
                        if (!string.IsNullOrEmpty(cachedSize.TempUrl))
                        {
                            return cachedSize.TempUrl;
                        }

                        var buffer = cachedSize.Bytes.Data;

                        if (buffer != null && buffer.Length > 0)
                        {
                            if (!isBlurEnabled)
                            {
                                return ImageUtils.CreateImage(buffer, options);
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetPhotoPreview(photo.Id, out preview, options))
                                {
                                    return preview;
                                }

                                try
                                {
                                    var bitmap = PictureDecoder.DecodeJpeg(new MemoryStream(buffer));

                                    BlurBitmap(bitmap, Secret);

                                    var blurredStream = new MemoryStream();
                                    bitmap.SaveJpeg(blurredStream, cachedSize.W.Value, cachedSize.H.Value, 0, 100);

                                    var fileName = string.Format("preview{0}.jpg", photo.Id);

                                    Telegram.Api.Helpers.Execute.BeginOnThreadPool(() => SaveFile(fileName, blurredStream));

                                    return ImageUtils.CreateImage(blurredStream);
                                }
                                catch (Exception ex)
                                {

                                }
                            }
                        }

                        return null;
                    }

                    return null;
                }
            }

            return null;
        }

19 Source : PhotoToThumbConverter.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static bool TryGetDoreplacedentPreview(TLLong doreplacedentId, out BitmapImage preview, BitmapCreateOptions options)
        {
            preview = null;

            var fileName = string.Format("preview_doreplacedent{0}.jpg", doreplacedentId);
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (store.FileExists(fileName))
                {
                    try
                    {
                        using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                        {
                            preview = ImageUtils.CreateImage(stream, options);
                            return true;
                        }
                    }
                    catch (Exception)
                    {

                    }
                }
            }

            return false;
        }

19 Source : EmojiData.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static void LoadRecents()
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists("EmojiRecents")) return;
                using (var stream = new IsolatedStorageFileStream("EmojiRecents", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite, store))
                {
                    if (stream.Length <= 0) return;

                    using (var br = new BinaryReader(stream))
                    {
                        var count = br.ReadInt32();

                        Recents = new List<EmojiDataItem>();

                        for (var i = 0; i < count; i++)
                        {
                            var emoji = new EmojiDataItem(br.ReadString(), br.ReadUInt64());
                            emoji.Uri = EmojiDataItem.BuildUri(emoji.String);
                            Recents.Add(emoji);
                        }
                    }
                }
            }
        }

19 Source : SnapshotsViewModel.cs
with GNU General Public License v2.0
from evgeny-nadymov

public void CreateTemp()
        {
            Execute.BeginOnThreadPool(() =>
            {
                var newSnapshotDirectoryName = DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss.fff", CultureInfo.InvariantCulture);
                var newSnapshotDirectoryFullName = Path.Combine(Constants.SnapshotsDirectoryName, newSnapshotDirectoryName);
                var stateFullFileName = Path.Combine(newSnapshotDirectoryFullName, Telegram.Api.Constants.StateFileName);
                var differenceFullFileName = Path.Combine(newSnapshotDirectoryFullName, Telegram.Api.Constants.DifferenceFileName);
                try
                {
                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!store.DirectoryExists(Constants.SnapshotsDirectoryName))
                        {
                            store.CreateDirectory(Constants.SnapshotsDirectoryName);
                        }
                        store.CreateDirectory(newSnapshotDirectoryFullName);
                    }

                    _updateService.SaveStateSnapshot(newSnapshotDirectoryFullName);
                    _cacheService.SaveTempSnapshot(newSnapshotDirectoryFullName);

                    var state = TLUtils.OpenObjectFromMTProtoFile<TLState>(new object(), stateFullFileName);

                    long length;
                    var difference = TLUtils.OpenObjectFromMTProtoFile<TLVector<TLDifferenceBase>>(new object(), differenceFullFileName, out length);

                    Execute.ShowDebugMessage("Snapshot has been successfully created");
                    Execute.BeginOnUIThread(() => Items.Add(new Snapshoreplacedem { Name = newSnapshotDirectoryName, State = state, Difference = difference, DifferenceLength = length }));
                }
                catch (Exception ex)
                {
                    DeleteDirectory(newSnapshotDirectoryFullName);
                }
            });
        }

19 Source : GeoPointToStaticGoogleMapsConverter.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static BitmapSource ReturnOrEnqueueGeoPointImage(TLGeoPoint geoPoint, int width, int height, TLObject owner)
        {

            var destFileName = geoPoint.GetFileName();

            BitmapSource imageSource;
            WeakReference weakImageSource;
            if (_cachedSources.TryGetValue(destFileName, out weakImageSource))
            {
                if (weakImageSource.IsAlive)
                {
                    imageSource = weakImageSource.Target as BitmapSource;

                    return imageSource;
                }
            }

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists(destFileName))
                {
                    var config = IoC.Get<ICacheService>().GetConfig() as TLConfig82;
                    if (config == null) return null;

                    var fileManager = IoC.Get<IWebFileManager>();

                    var geoPoint82 = geoPoint as TLGeoPoint82;
                    var accessHash = geoPoint82 != null ? geoPoint82.AccessHash : new TLLong(0); 

                    var inputLocation = new TLInputWebFileGeoPointLocation
                    {
                        GeoPoint = new TLInputGeoPoint { Long = geoPoint.Long, Lat = geoPoint.Lat },
                        AccessHash = accessHash,
                        W = new TLInt(width),
                        H = new TLInt(height),
                        Zoom = new TLInt(15),
                        Scale = new TLInt(2)
                    };

                    fileManager.DownloadFile(config.WebfileDCId, inputLocation, destFileName, owner, item =>
                    {
                        var messageMediaGeoPoint = owner as IMessageMediaGeoPoint;
                        if (messageMediaGeoPoint != null)
                        {
                            var newGeoPoint = messageMediaGeoPoint.Geo as TLGeoPoint;
                            if (newGeoPoint != null)
                            {
                                var newFileName = newGeoPoint.GetFileName();
                                var oldFileName = destFileName;

                                using (var store2 = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store2.FileExists(oldFileName))
                                    {
                                        if (!string.IsNullOrEmpty(oldFileName) && !string.Equals(oldFileName, newFileName, StringComparison.OrdinalIgnoreCase))
                                        {
                                            store2.CopyFile(oldFileName, newFileName, true);
                                            store2.DeleteFile(oldFileName);
                                        }
                                    }
                                }
                            }

                            Telegram.Api.Helpers.Execute.BeginOnUIThread(() =>
                            {
                                var messageMediaBase = owner as TLMessageMediaBase;
                                if (messageMediaBase != null)
                                {
                                    messageMediaBase.NotifyOfPropertyChange(() => messageMediaBase.Self);
                                }
                                var decryptedMessageMediaBase = owner as TLDecryptedMessageMediaBase;
                                if (decryptedMessageMediaBase != null)
                                {
                                    decryptedMessageMediaBase.NotifyOfPropertyChange(() => decryptedMessageMediaBase.Self);
                                }
                            });
                        }
                    });
                }
                else
                {
                    try
                    {
                        using (var stream = store.OpenFile(destFileName, FileMode.Open, FileAccess.Read))
                        {
                            stream.Seek(0, SeekOrigin.Begin);
                            var image = new BitmapImage();
                            image.SetSource(stream);
                            imageSource = image;
                        }

                        _cachedSources[destFileName] = new WeakReference(imageSource);
                    }
                    catch (Exception)
                    {
                        return null;
                    }

                    return imageSource;
                }
            }

            return null;
        }

19 Source : Log.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static void Write(string str)
        {
            if (!IsEnabled)
            {
                return;
            }

            Execute.BeginOnThreadPool(() =>
            {
                var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);

                lock (_fileSyncRoot)
                {
                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!store.DirectoryExists(DirectoryName))
                        {
                            store.CreateDirectory(DirectoryName);
                        }

                        using (var file = store.OpenFile(Path.Combine(DirectoryName, FileName), FileMode.Append))
                        {
                            var bytes = Encoding.UTF8.GetBytes(string.Format("{0} {1}{2}", timestamp, str, Environment.NewLine));
                            file.Write(bytes, 0, bytes.Length);
                        }
                    }
                }
            });
        }

19 Source : Log.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static void CopyTo(string fileName, Action<string> callback)
        {
            Execute.BeginOnThreadPool(() =>
            {
                lock (_fileSyncRoot)
                {
                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (store.FileExists(Path.Combine(DirectoryName, FileName)))
                        {
                            store.CopyFile(Path.Combine(DirectoryName, FileName), fileName);
                        }
                    }
                }

                callback.SafeInvoke(fileName);
            });
        }

19 Source : CacheViewModel.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void CalculateCacheSizeAsync(Action<long, long> callback)
        {
            BeginOnThreadPool(() =>
            {
                _isCalculating = true;

                var length1 = 0L;
                var length2 = 0L;
                var files = new List<TelegramFileInfo>();
                _settings.Clear();
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    var fileNames = store.GetFileNames();

                    foreach (var fileName in fileNames)
                    {
                        if (fileName.StartsWith("staticmap"))
                        {
                            
                        }

                        try
                        {
                            var fileInfo = new TelegramFileInfo {Name = fileName};
                            if (store.FileExists(fileName))
                            {
                                using (var file = new IsolatedStorageFileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, store))
                                {
                                    fileInfo.Length = file.Length;
                                    if (IsValidCacheFileName(fileName))
                                    {
                                        if (IsValidPhotoFileName(fileName))
                                        {
                                            _settings.PhotosLength += file.Length;
                                        }
                                        else if (IsValidMusicFileName(fileName))
                                        {
                                            _settings.MusicLength += file.Length;
                                        }
                                        else if (IsValidVideoFileName(fileName))
                                        {
                                            _settings.VideoLength += file.Length;
                                        }
                                        else if (IsValidVoiceMessageFileName(fileName))
                                        {
                                            _settings.VoiceMessagesLength += file.Length;
                                        }
                                        else if (IsValidDoreplacedentFileName(fileName))
                                        {
                                            _settings.DoreplacedentsLength += file.Length;
                                        }
                                        else if (IsValidOtherFileName(fileName))
                                        {
                                            _settings.OtherFilesLength += file.Length;
                                        }

                                        length1 += file.Length;
                                        fileInfo.IsValidCacheFileName = true;
                                    }
                                }
                            }
                            files.Add(fileInfo);
                        }
                        catch (Exception ex)
                        {
                            TLUtils.WriteException("CalculateCacheSizeAsync OpenFile: " + fileName, ex);
                        }
                    }

                    var directoryNames = store.GetDirectoryNames();
                    foreach (var fileName in directoryNames)
                    {
                        try
                        {
                            var fileInfo = new TelegramFileInfo { Name = fileName, Length = -1};
                            files.Add(fileInfo);
                        }
                        catch (Exception ex)
                        {
                            TLUtils.WriteException("CalculateCacheSizeAsync OpenFile: " + fileName, ex);
                        }
                    }

                    length2 = GetDatabaseLength(store, files);
                }

                _isCalculating = false; 

                callback.SafeInvoke(length1, length2);

                BeginOnUIThread(() =>
                {
                    Files.Clear();
                    foreach (var file in files)
                    {
                        Files.Add(file);
                    }
                });
            });
        }

19 Source : CreateChannelViewModel.cs
with GNU General Public License v2.0
from evgeny-nadymov

public void ChoosePhoto()
        {
            EditChatActions.EditPhoto(photo =>
            {
                var volumeId = TLLong.Random();
                var localId = TLInt.Random();
                var secret = TLLong.Random();

                var fileLocation = new TLFileLocation
                {
                    VolumeId = volumeId,
                    LocalId = localId,
                    Secret = secret,
                    DCId = new TLInt(0),
                    //Buffer = p.Bytes
                };

                var fileName = String.Format("{0}_{1}_{2}.jpg",
                    fileLocation.VolumeId,
                    fileLocation.LocalId,
                    fileLocation.Secret);

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

                Photo = new TLChatPhoto
                {
                    PhotoSmall = new TLFileLocation
                    {
                        DCId = fileLocation.DCId,
                        VolumeId = fileLocation.VolumeId,
                        LocalId = fileLocation.LocalId,
                        Secret = fileLocation.Secret
                    },
                    PhotoBig = new TLFileLocation
                    {
                        DCId = fileLocation.DCId,
                        VolumeId = fileLocation.VolumeId,
                        LocalId = fileLocation.LocalId,
                        Secret = fileLocation.Secret
                    }
                };
                NotifyOfPropertyChange(() => Photo);
            });
        }

19 Source : DialogDetailsViewModel.Document.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void SendDoreplacedent(string fileName)
        {
            //create thumb
            byte[] bytes;

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var fileStream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    bytes = new byte[fileStream.Length];
                    fileStream.Read(bytes, 0, bytes.Length);
                }
            }

            if (!CheckDoreplacedentSize((ulong)bytes.Length))
            {
                MessageBox.Show(string.Format(AppResources.MaximumFileSizeExceeded, MediaSizeConverter.Convert((int)Telegram.Api.Constants.MaximumUploadedFileSize)), AppResources.Error, MessageBoxButton.OK);
                return;
            }

            //create doreplacedent
            var doreplacedent = new TLDoreplacedent54
            {
                Buffer = bytes,

                Id = new TLLong(0),
                AccessHash = new TLLong(0),
                Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now),
                FileName = new TLString(Path.GetFileName(fileName)),
                MimeType = new TLString("text/plain"),
                Size = new TLInt(bytes.Length),
                Thumb = new TLPhotoSizeEmpty { Type = TLString.Empty },
                DCId = new TLInt(0),
                Version = new TLInt(0)
            };

            var media = new TLMessageMediaDoreplacedent75 { Flags = new TLInt(0), FileId = TLLong.Random(), Doreplacedent = doreplacedent, Caption = TLString.Empty };

            var message = GetMessage(TLString.Empty, media);

            BeginOnUIThread(() =>
            {
                var previousMessage = InsertSendingMessage(message);
                IsEmptyDialog = Items.Count == 0 && (_messages == null || _messages.Count == 0) && LazyItems.Count == 0;

                BeginOnThreadPool(() =>
                    CacheService.SyncSendingMessage(
                        message, previousMessage,
                        m => SendDoreplacedentInternal(message, null)));
            });
        }

19 Source : DialogDetailsViewModel.Document.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void SendDoreplacedent(Photo d)
        {
            //create thumb
            var bytes = d.PreviewBytes;

            if (!CheckDoreplacedentSize((ulong)d.Bytes.Length))
            {
                MessageBox.Show(string.Format(AppResources.MaximumFileSizeExceeded, MediaSizeConverter.Convert((int)Telegram.Api.Constants.MaximumUploadedFileSize)), AppResources.Error, MessageBoxButton.OK);
                return;
            }

            var volumeId = TLLong.Random();
            var localId = TLInt.Random();
            var secret = TLLong.Random();

            var thumbLocation = new TLFileLocation //TODO: replace with TLFileLocationUnavailable
            {
                DCId = new TLInt(0),
                VolumeId = volumeId,
                LocalId = localId,
                Secret = secret,
                //Buffer = bytes
            };

            var fileName = String.Format("{0}_{1}_{2}.jpg",
                thumbLocation.VolumeId,
                thumbLocation.LocalId,
                thumbLocation.Secret);

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

            var thumbSize = new TLPhotoSize
            {
                W = new TLInt(d.Width),
                H = new TLInt(d.Height),
                Size = new TLInt(bytes.Length),
                Type = new TLString(""),
                Location = thumbLocation,
            };

            //create doreplacedent
            var doreplacedent = new TLDoreplacedent54
            {
                Buffer = d.Bytes,

                Id = new TLLong(0),
                AccessHash = new TLLong(0),
                Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now),
                FileName = new TLString(Path.GetFileName(d.FileName)),
                MimeType = new TLString("image/jpeg"),
                Size = new TLInt(d.Bytes.Length),
                Thumb = thumbSize,
                DCId = new TLInt(0),
                Version = new TLInt(0)
            };

            var media = new TLMessageMediaDoreplacedent75 { Flags = new TLInt(0), FileId = TLLong.Random(), Doreplacedent = doreplacedent, Caption = TLString.Empty };

            var message = GetMessage(TLString.Empty, media);

            BeginOnUIThread(() =>
            {
                var previousMessage = InsertSendingMessage(message);
                IsEmptyDialog = Items.Count == 0 && (_messages == null || _messages.Count == 0) && LazyItems.Count == 0;

                BeginOnThreadPool(() =>
                    CacheService.SyncSendingMessage(
                        message, previousMessage,
                        m => SendDoreplacedentInternal(message, null)));
            });
        }

19 Source : DialogDetailsViewModel.InlineBots.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void ProcessBotInlineResult(TLMessage45 message, TLBotInlineResultBase resultBase, TLInt botId)
        {
            message.InlineBotResultId = resultBase.Id;
            message.InlineBotResultQueryId = resultBase.QueryId;
            message.ViaBotId = botId;

            var botInlineMessageMediaVenue = resultBase.SendMessage as TLBotInlineMessageMediaVenue;
            var botInlineMessageMediaGeo = resultBase.SendMessage as TLBotInlineMessageMediaGeo;
            if (botInlineMessageMediaVenue != null)
            {
                message._media = new TLMessageMediaVenue72
                {
                    replacedle = botInlineMessageMediaVenue.replacedle,
                    Address = botInlineMessageMediaVenue.Address,
                    Provider = botInlineMessageMediaVenue.Provider,
                    VenueId = botInlineMessageMediaVenue.VenueId,
                    VenueType = TLString.Empty,
                    Geo = botInlineMessageMediaVenue.Geo
                };
            }
            else if (botInlineMessageMediaGeo != null)
            {
                message._media = new TLMessageMediaGeo { Geo = botInlineMessageMediaGeo.Geo };
            }

            var botInlineMessageMediaContact = resultBase.SendMessage as TLBotInlineMessageMediaContact;
            if (botInlineMessageMediaContact != null)
            {
                message._media = new TLMessageMediaContact82
                {
                    PhoneNumber = botInlineMessageMediaContact.PhoneNumber,
                    FirstName = botInlineMessageMediaContact.FirstName,
                    LastName = botInlineMessageMediaContact.LastName,
                    UserId = new TLInt(0),
                    VCard = TLString.Empty
                };
            }

            var mediaResult = resultBase as TLBotInlineMediaResult;
            if (mediaResult != null)
            {
                if (TLString.Equals(mediaResult.Type, new TLString("voice"), StringComparison.OrdinalIgnoreCase)
                    && mediaResult.Doreplacedent != null)
                {
                    message._media = new TLMessageMediaDoreplacedent75 { Flags = new TLInt(0), Doreplacedent = mediaResult.Doreplacedent, Caption = TLString.Empty, NotListened = !(With is TLChannel) };

                    message.NotListened = !(With is TLChannel);
                }
                else if (TLString.Equals(mediaResult.Type, new TLString("audio"), StringComparison.OrdinalIgnoreCase)
                    && mediaResult.Doreplacedent != null)
                {
                    message._media = new TLMessageMediaDoreplacedent75 { Flags = new TLInt(0), Doreplacedent = mediaResult.Doreplacedent, Caption = TLString.Empty };
                }
                else if (TLString.Equals(mediaResult.Type, new TLString("sticker"), StringComparison.OrdinalIgnoreCase)
                    && mediaResult.Doreplacedent != null)
                {
                    message._media = new TLMessageMediaDoreplacedent75 { Flags = new TLInt(0), Doreplacedent = mediaResult.Doreplacedent, Caption = TLString.Empty };
                }
                else if (TLString.Equals(mediaResult.Type, new TLString("file"), StringComparison.OrdinalIgnoreCase)
                    && mediaResult.Doreplacedent != null)
                {
                    message._media = new TLMessageMediaDoreplacedent75 { Flags = new TLInt(0), Doreplacedent = mediaResult.Doreplacedent, Caption = TLString.Empty };
                }
                else if (TLString.Equals(mediaResult.Type, new TLString("gif"), StringComparison.OrdinalIgnoreCase)
                    && mediaResult.Doreplacedent != null)
                {
                    message._media = new TLMessageMediaDoreplacedent75 { Flags = new TLInt(0), Doreplacedent = mediaResult.Doreplacedent, Caption = TLString.Empty };
                }
                else if (TLString.Equals(mediaResult.Type, new TLString("photo"), StringComparison.OrdinalIgnoreCase)
                    && mediaResult.Photo != null)
                {
                    message._media = new TLMessageMediaPhoto75 { Flags = new TLInt(0), Photo = mediaResult.Photo, Caption = TLString.Empty };
                }
                else if (TLString.Equals(mediaResult.Type, new TLString("game"), StringComparison.OrdinalIgnoreCase))
                {
                    var game = new TLGame
                    {
                        Flags = new TLInt(0),
                        Id = new TLLong(0),
                        AccessHash = new TLLong(0),
                        ShortName = mediaResult.Id,
                        replacedle = mediaResult.replacedle ?? TLString.Empty,
                        Description = mediaResult.Description ?? TLString.Empty,
                        Photo = mediaResult.Photo ?? new TLPhotoEmpty {Id = new TLLong(0)},
                        Doreplacedent = mediaResult.Doreplacedent
                    };

                    message._media = new TLMessageMediaGame { Game = game, SourceMessage = message };
                }
            }

            var result = resultBase as TLBotInlineResult;
            if (result != null)
            {
                var isVoice = TLString.Equals(result.Type, new TLString("voice"), StringComparison.OrdinalIgnoreCase);
                var isAudio = TLString.Equals(result.Type, new TLString("audio"), StringComparison.OrdinalIgnoreCase);
                var isFile = TLString.Equals(result.Type, new TLString("file"), StringComparison.OrdinalIgnoreCase);

                if (isFile
                    || isAudio
                    || isVoice)
                {
                    var doreplacedent = result.Doreplacedent as TLDoreplacedent22;
                    if (doreplacedent == null)
                    {
                        string fileName = null;
                        if (result.ContentUrl != null)
                        {
                            var fileUri = new Uri(result.ContentUrlString);
                            try
                            {
                                fileName = Path.GetFileName(fileUri.LocalPath);
                            }
                            catch (Exception ex)
                            {
                                
                            }

                            if (fileName == null)
                            {
                                fileName = "file.ext";
                            }
                        }

                        doreplacedent = new TLDoreplacedent54
                        {
                            Id = new TLLong(0),
                            AccessHash = new TLLong(0),
                            Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now),
                            FileName = new TLString(fileName),
                            MimeType = result.ContentType ?? TLString.Empty,
                            Size = new TLInt(0),
                            Thumb = new TLPhotoSizeEmpty { Type = TLString.Empty },
                            DCId = new TLInt(0),
                            Version = new TLInt(0)
                        };

                        if (isVoice || isAudio)
                        {
                            var doreplacedentAttributeAudio = new TLDoreplacedentAttributeAudio46
                            {
                                Duration = result.Duration ?? new TLInt(0),
                                replacedle = result.replacedle ?? TLString.Empty,
                                Performer = null,
                                Voice = isVoice
                            };
                            doreplacedent.Attributes.Add(doreplacedentAttributeAudio);
                        }

                        //message._status = MessageStatus.Failed;
                    }
                    var mediaDoreplacedent = new TLMessageMediaDoreplacedent75 { Flags = new TLInt(0), Doreplacedent = doreplacedent, Caption = TLString.Empty };

                    message._media = mediaDoreplacedent;

                    mediaDoreplacedent.NotListened = isVoice && !(With is TLChannel);
                    message.NotListened = isVoice && !(With is TLChannel);
                }
                else if (TLString.Equals(result.Type, new TLString("gif"), StringComparison.OrdinalIgnoreCase))
                {
                    var doreplacedent = result.Doreplacedent;
                    if (doreplacedent != null)
                    {
                        var mediaDoreplacedent = new TLMessageMediaDoreplacedent75 { Flags = new TLInt(0), Doreplacedent = doreplacedent, Caption = TLString.Empty };

                        message._media = mediaDoreplacedent;
                    }
                }
                else if (TLString.Equals(result.Type, new TLString("photo"), StringComparison.OrdinalIgnoreCase))
                {
                    Telegram.Api.Helpers.Execute.ShowDebugMessage(string.Format("w={0} h={1}\nthumb_url={2}\ncontent_url={3}", result.W, result.H, result.ThumbUrl, result.ContentUrl));

                    var location = new TLFileLocation{DCId = new TLInt(1), VolumeId = TLLong.Random(), LocalId = TLInt.Random(), Secret = TLLong.Random() };

                    var cachedSize = new TLPhotoCachedSize
                    {
                        Type = new TLString("s"),
                        W = result.W ?? new TLInt(90),
                        H = result.H ?? new TLInt(90),
                        Location = location,
                        Bytes = TLString.Empty,
                        TempUrl = result.ThumbUrlString ?? result.ContentUrlString
                        //Size = new TLInt(0)
                    };

                    var size = new TLPhotoSize
                    {
                        Type = new TLString("m"),
                        W = result.W ?? new TLInt(90),
                        H = result.H ?? new TLInt(90),
                        Location = location,
                        TempUrl = result.ContentUrlString,
                        Size = new TLInt(0)
                    };

                    if (!string.IsNullOrEmpty(result.ThumbUrlString))
                    {
                        //ServicePointManager.ServerCertificateValidationCallback += new 

                        var webClient = new WebClient();
                        webClient.OpenReadAsync(new Uri(result.ThumbUrlString, UriKind.Absolute));
                        webClient.OpenReadCompleted += (sender, args) =>
                        {
                            if (args.Cancelled) return;
                            if (args.Error != null) return;

                            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                location.VolumeId,
                                location.LocalId,
                                location.Secret);

                            using (var stream = args.Result)
                            {
                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName)) return;
                                    using (var file = store.OpenFile(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read))
                                    {
                                        const int BUFFER_SIZE = 128*1024;
                                        var buf = new byte[BUFFER_SIZE];

                                        var bytesread = 0;
                                        while ((bytesread = stream.Read(buf, 0, BUFFER_SIZE)) > 0)
                                        {
                                            var position = stream.Position;
                                            stream.Position = position - 10;
                                            var tempBuffer = new byte[10];
                                            var resultOk = stream.Read(tempBuffer, 0, tempBuffer.Length);
                                            file.Write(buf, 0, bytesread);
                                        }
                                    }
                                }
                            }

                            if (!string.IsNullOrEmpty(result.ContentUrlString))
                            {
                                webClient.OpenReadAsync(new Uri(result.ContentUrlString, UriKind.Absolute));
                                webClient.OpenReadCompleted += (sender2, args2) =>
                                {
                                    if (args2.Cancelled) return;
                                    if (args2.Error != null) return;

                                    using (var stream = args2.Result)
                                    {
                                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                        {
                                            if (store.FileExists(fileName)) return;
                                            using (var file = store.OpenFile(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read))
                                            {
                                                const int BUFFER_SIZE = 128 * 1024;
                                                var buf = new byte[BUFFER_SIZE];

                                                int bytesread = 0;
                                                while ((bytesread = stream.Read(buf, 0, BUFFER_SIZE)) > 0)
                                                {
                                                    file.Write(buf, 0, bytesread);
                                                }
                                            }
                                        }
                                    }
                                };
                            }
                        };
                    }

                    var photo = new TLPhoto56
                    {
                        Flags = new TLInt(0),
                        Id = TLLong.Random(),
                        AccessHash = TLLong.Random(),
                        Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now),
                        Sizes = new TLVector<TLPhotoSizeBase> {cachedSize, size}
                    };

                    var mediaPhoto = new TLMessageMediaPhoto75 { Flags = new TLInt(0), Photo = photo, Caption = TLString.Empty };

                    message._media = mediaPhoto;
                }
            }

            var messageText = resultBase.SendMessage as TLBotInlineMessageText;
            if (messageText != null)
            {
                message.Message = messageText.Message;
                message.Enreplacedies = messageText.Enreplacedies;
                if (messageText.NoWebpage)
                {
                    
                }
            }

            var mediaAuto = resultBase.SendMessage as TLBotInlineMessageMediaAuto75;
            if (mediaAuto != null)
            {
                message.Message = mediaAuto.Caption;
                message.Enreplacedies = mediaAuto.Enreplacedies;
            }

            if (resultBase.SendMessage != null
                && resultBase.SendMessage.ReplyMarkup != null)
            {
                message.ReplyMarkup = resultBase.SendMessage.ReplyMarkup;
            }
        }

19 Source : DialogDetailsViewModel.Media.cs
with GNU General Public License v2.0
from evgeny-nadymov

public void OpenMedia(TLMessageBase messageBase)
#endif
        {
            if (messageBase == null) return;
            if (messageBase.Status == MessageStatus.Failed
                || messageBase.Status == MessageStatus.Sending) return;

            var serviceMessage = messageBase as TLMessageService;
            if (serviceMessage != null)
            {
                var editPhotoAction = serviceMessage.Action as TLMessageActionChatEditPhoto;
                if (editPhotoAction != null)
                {
                    var photo = editPhotoAction.Photo;
                    if (photo != null)
                    {
                        //StateService.CurrentPhoto = photo;
                        //StateService.CurrentChat = With as TLChatBase;
                        //NavigationService.UriFor<ProfilePhotoViewerViewModel>().Navigate();
                    }
                }

                var phoneCallAction = serviceMessage.Action as TLMessageActionPhoneCall;
                if (phoneCallAction != null)
                {
                    TLUser user = null;
                    if (serviceMessage.Out.Value)
                    {
                        user = CacheService.GetUser(serviceMessage.ToId.Id) as TLUser;
                    }
                    else
                    {
                        user = serviceMessage.From as TLUser;
                    }

                    ShellViewModel.StartVoiceCall(user, IoC.Get<IVoIPService>(), IoC.Get<ICacheService>());
                }

                return;
            }

            var message = messageBase as TLMessage;
            if (message == null) return;

            var mediaPhoto = message.Media as TLMessageMediaPhoto;
            if (mediaPhoto != null)
            {
                if (!message.Out.Value && message.HasTTL())
                {
                    var ttlMessageMedia = mediaPhoto as ITTLMessageMedia;
                    if (ttlMessageMedia != null && ttlMessageMedia.TTLParams == null)
                    {
                        ttlMessageMedia.TTLParams = new TTLParams
                        {
                            StartTime = DateTime.Now,
                            IsStarted = true,
                            Total = ttlMessageMedia.TTLSeconds.Value
                        };
                        mediaPhoto.NotifyOfPropertyChange(() => ttlMessageMedia.TTLParams);

                        AddToTTLQueue(message as TLMessage70, ttlMessageMedia.TTLParams,
                            result =>
                            {
                                SplitGroupedMessages(new List<TLInt> { message.Id });
                            });
                    }

                    ReadMessageContents(message as TLMessage25);
                }

                var photo = mediaPhoto.Photo as TLPhoto;
                if (photo != null)
                {
                    var width = 311.0;

                    TLPhotoSize size = null;
                    var sizes = photo.Sizes.OfType<TLPhotoSize>();
                    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)
                    {
                        var location = size.Location as TLFileLocation;
                        if (location != null)
                        {
                            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                location.VolumeId,
                                location.LocalId,
                                location.Secret);

                            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                            {
                                if (!store.FileExists(fileName))
                                {
                                    message.Media.IsCanceled = false;
                                    message.Media.DownloadingProgress = 0.01;
                                    Execute.BeginOnThreadPool(() => DownloadFileManager.DownloadFile(location, photo, size.Size));

                                    return;
                                }
                            }
                        }
                    }
                }

                if (mediaPhoto.IsCanceled)
                {
                    mediaPhoto.IsCanceled = false;
                    mediaPhoto.NotifyOfPropertyChange(() => mediaPhoto.Photo);
                    mediaPhoto.NotifyOfPropertyChange(() => mediaPhoto.Self);

                    return;
                }

                StateService.CurrentPhotoMessage = message;
                StateService.CurrentMediaMessages = message.HasTTL()
                    ? new List<TLMessage> { message }
                    : UngroupEnumerator(Items).OfType<TLMessage>()
                        .Where(x =>
                        {
                            if (TLMessageBase.HasTTL(x.Media))
                            {
                                return false;
                            }

                            return x.Media is TLMessageMediaPhoto || x.Media is TLMessageMediaVideo || x.IsVideo();
                        })
                        .ToList();

                OpenImageViewer();

                return;
            }

            var mediaWebPage = message.Media as TLMessageMediaWebPage;
            if (mediaWebPage != null)
            {
                var webPage = mediaWebPage.WebPage as TLWebPage;
                if (webPage != null && webPage.Type != null)
                {
                    if (webPage.Type != null)
                    {
                        var type = webPage.Type.ToString();
                        if (string.Equals(type, "photo", StringComparison.OrdinalIgnoreCase))
                        {
                            StateService.CurrentPhotoMessage = message;

                            OpenImageViewer();

                            return;
                        }
                        if (string.Equals(type, "video", StringComparison.OrdinalIgnoreCase))
                        {
                            if (!TLString.Equals(webPage.SiteName, new TLString("youtube"), StringComparison.OrdinalIgnoreCase)
                                && !TLString.IsNullOrEmpty(webPage.EmbedUrl))
                            {
                                var launcher = new MediaPlayerLauncher
                                {
                                    Location = MediaLocationType.Data,
                                    Media = new Uri(webPage.EmbedUrl.ToString(), UriKind.Absolute),
                                    Orientation = MediaPlayerOrientation.Portrait
                                };
                                launcher.Show();
                                return;
                            }

                            if (!TLString.IsNullOrEmpty(webPage.Url))
                            {
                                var webBrowserTask = new WebBrowserTask();
                                webBrowserTask.URL = HttpUtility.UrlEncode(webPage.Url.ToString());
                                webBrowserTask.Show();
                            }

                            return;
                        }
                        if (string.Equals(type, "gif", StringComparison.OrdinalIgnoreCase))
                        {
                            var webPage35 = webPage as TLWebPage35;
                            if (webPage35 != null)
                            {
                                var doreplacedent = webPage35.Doreplacedent as TLDoreplacedent;
                                if (doreplacedent == null) return;

                                var doreplacedentLocalFileName = doreplacedent.GetFileName();
                                var store = IsolatedStorageFile.GetUserStoreForApplication();
#if WP81
                                var doreplacedentFile = mediaWebPage.File ?? await GetStorageFile(mediaWebPage);
#endif

                                if (!store.FileExists(doreplacedentLocalFileName)
#if WP81
 && doreplacedentFile == null
#endif
)
                                {
                                    mediaWebPage.IsCanceled = false;
                                    mediaWebPage.DownloadingProgress = mediaWebPage.LastProgress > 0.0 ? mediaWebPage.LastProgress : 0.001;
                                    DownloadDoreplacedentFileManager.DownloadFileAsync(doreplacedent.FileName, doreplacedent.DCId, doreplacedent.ToInputFileLocation(), message, doreplacedent.Size,
                                        progress =>
                                        {
                                            if (progress > 0.0)
                                            {
                                                mediaWebPage.DownloadingProgress = progress;
                                            }
                                        });
                                }
                            }

                            return;
                        }
                    }
                }
            }

            var mediaGame = message.Media as TLMessageMediaGame;
            if (mediaGame != null)
            {
                var game = mediaGame.Game;
                if (game != null)
                {
                    var doreplacedent = game.Doreplacedent as TLDoreplacedent;
                    if (doreplacedent == null) return;

                    var doreplacedentLocalFileName = doreplacedent.GetFileName();
                    var store = IsolatedStorageFile.GetUserStoreForApplication();
#if WP81
                    var doreplacedentFile = mediaGame.File ?? await GetStorageFile(mediaGame);
#endif

                    if (!store.FileExists(doreplacedentLocalFileName)
#if WP81
 && doreplacedentFile == null
#endif
)
                    {
                        mediaGame.IsCanceled = false;
                        mediaGame.DownloadingProgress = mediaGame.LastProgress > 0.0 ? mediaGame.LastProgress : 0.001;
                        DownloadDoreplacedentFileManager.DownloadFileAsync(doreplacedent.FileName, doreplacedent.DCId, doreplacedent.ToInputFileLocation(), message, doreplacedent.Size,
                            progress =>
                            {
                                if (progress > 0.0)
                                {
                                    mediaGame.DownloadingProgress = progress;
                                }
                            });
                    }
                }

                return;
            }

            var mediaGeo = message.Media as TLMessageMediaGeo;
            if (mediaGeo != null)
            {
                OpenLocation(message);

                return;
            }

            var mediaContact = message.Media as TLMessageMediaContact;
            if (mediaContact != null)
            {
                var phoneNumber = mediaContact.PhoneNumber.ToString();

                if (mediaContact.UserId.Value == 0)
                {
                    OpenPhoneContact(mediaContact);
                }
                else
                {
                    var user = mediaContact.User;

                    OpenMediaContact(mediaContact.UserId, user, new TLString(phoneNumber));
                }
                return;
            }

            var mediaVideo = message.Media as TLMessageMediaVideo;
            if (mediaVideo != null)
            {
                var video = mediaVideo.Video as TLVideo;
                if (video == null) return;

                var videoFileName = video.GetFileName();
                var store = IsolatedStorageFile.GetUserStoreForApplication();
#if WP81
                var file = mediaVideo.File ?? await GetStorageFile(mediaVideo);
#endif


                if (!store.FileExists(videoFileName)
#if WP81
 && file == null
#endif
)
                {
                    mediaVideo.IsCanceled = false;
                    mediaVideo.DownloadingProgress = mediaVideo.LastProgress > 0.0 ? mediaVideo.LastProgress : 0.001;
                    DownloadVideoFileManager.DownloadFileAsync(
                        video.DCId, video.ToInputFileLocation(), message, video.Size,
                        progress =>
                        {
                            if (progress > 0.0)
                            {
                                mediaVideo.DownloadingProgress = progress;
                            }
                        });
                }
                else
                {
                    //ReadMessageContents(message);

#if WP81

                    //var localFile = await GetFileFromLocalFolder(videoFileName);
                    var videoProperties = await file.Properties.GetVideoPropertiesAsync();
                    var musicProperties = await file.Properties.GetMusicPropertiesAsync();

                    if (file != null)
                    {
                        Launcher.LaunchFileAsync(file);
                        return;
                    }


#endif

                    var launcher = new MediaPlayerLauncher
                    {
                        Location = MediaLocationType.Data,
                        Media = new Uri(videoFileName, UriKind.Relative)
                    };
                    launcher.Show();
                }
                return;
            }

            var mediaAudio = message.Media as TLMessageMediaAudio;
            if (mediaAudio != null)
            {
                var audio = mediaAudio.Audio as TLAudio;
                if (audio == null) return;

                var store = IsolatedStorageFile.GetUserStoreForApplication();
                var audioFileName = audio.GetFileName();
                if (TLString.Equals(audio.MimeType, new TLString("audio/mpeg"), StringComparison.OrdinalIgnoreCase))
                {
                    if (!store.FileExists(audioFileName))
                    {
                        mediaAudio.IsCanceled = false;
                        mediaAudio.DownloadingProgress = mediaAudio.LastProgress > 0.0 ? mediaAudio.LastProgress : 0.001;
                        BeginOnThreadPool(() =>
                        {
                            DownloadAudioFileManager.DownloadFile(audio.DCId, audio.ToInputFileLocation(), message, audio.Size);
                        });
                    }
                    else
                    {
                        ReadMessageContents(message as TLMessage25);
                    }

                    return;
                }

                var wavFileName = Path.GetFileNameWithoutExtension(audioFileName) + ".wav";

                if (!store.FileExists(wavFileName))
                {
                    mediaAudio.IsCanceled = false;
                    mediaAudio.DownloadingProgress = mediaAudio.LastProgress > 0.0 ? mediaAudio.LastProgress : 0.001;
                    BeginOnThreadPool(() =>
                    {
                        DownloadAudioFileManager.DownloadFile(audio.DCId, audio.ToInputFileLocation(), message, audio.Size);
                    });
                }
                else
                {
                    ReadMessageContents(message as TLMessage25);
                }

                if (mediaAudio.IsCanceled)
                {
                    mediaAudio.IsCanceled = false;
                    mediaAudio.NotifyOfPropertyChange(() => mediaPhoto.ThumbSelf);

                    return;
                }

                return;
            }

            var mediaDoreplacedent = message.Media as TLMessageMediaDoreplacedent;
            if (mediaDoreplacedent != null)
            {
                var doreplacedent = mediaDoreplacedent.Doreplacedent as TLDoreplacedent22;
                if (doreplacedent != null)
                {
                    if (TLMessageBase.IsSticker(doreplacedent))
                    {
                        var inputStickerSet = doreplacedent.StickerSet;
                        if (inputStickerSet != null && !(inputStickerSet is TLInputStickerSetEmpty))
                        {
                            AddToStickers(message);
                        }
                    }
                    else if (TLMessageBase.IsVoice(doreplacedent))
                    {
                        var store = IsolatedStorageFile.GetUserStoreForApplication();
                        var audioFileName = string.Format("audio{0}_{1}.mp3", doreplacedent.Id, doreplacedent.AccessHash);
                        if (TLString.Equals(doreplacedent.MimeType, new TLString("audio/mpeg"), StringComparison.OrdinalIgnoreCase))
                        {
                            if (!store.FileExists(audioFileName))
                            {
                                mediaDoreplacedent.IsCanceled = false;
                                mediaDoreplacedent.DownloadingProgress = mediaDoreplacedent.LastProgress > 0.0 ? mediaDoreplacedent.LastProgress : 0.001;
                                BeginOnThreadPool(() =>
                                {
                                    DownloadAudioFileManager.DownloadFile(doreplacedent.DCId, doreplacedent.ToInputFileLocation(), message, doreplacedent.Size);
                                });
                            }
                            else
                            {
                                ReadMessageContents(message as TLMessage25);
                            }

                            return;
                        }

                        var wavFileName = Path.GetFileNameWithoutExtension(audioFileName) + ".wav";

                        if (!store.FileExists(wavFileName))
                        {
                            mediaDoreplacedent.IsCanceled = false;
                            mediaDoreplacedent.DownloadingProgress = mediaDoreplacedent.LastProgress > 0.0 ? mediaDoreplacedent.LastProgress : 0.001;
                            BeginOnThreadPool(() =>
                            {
                                DownloadAudioFileManager.DownloadFile(doreplacedent.DCId, doreplacedent.ToInputFileLocation(), message, doreplacedent.Size);
                            });
                        }
                        else
                        {
                            ReadMessageContents(message as TLMessage25);
                        }

                        if (mediaDoreplacedent.IsCanceled)
                        {
                            mediaDoreplacedent.IsCanceled = false;
                            mediaDoreplacedent.NotifyOfPropertyChange(() => mediaDoreplacedent.ThumbSelf);

                            return;
                        }
                    }
                    else if (TLMessageBase.IsVideo(doreplacedent))
                    {
                        var video = mediaDoreplacedent.Doreplacedent as TLDoreplacedent;
                        if (video == null) return;

                        var videoFileName = video.GetFileName();
                        var store = IsolatedStorageFile.GetUserStoreForApplication();
#if WP81
                        var file = mediaDoreplacedent.File ?? await GetStorageFile(mediaDoreplacedent);
#endif


                        if (!store.FileExists(videoFileName)
#if WP81
 && file == null
#endif
)
                        {
                            mediaDoreplacedent.IsCanceled = false;
                            mediaDoreplacedent.DownloadingProgress = mediaDoreplacedent.LastProgress > 0.0
                                ? mediaDoreplacedent.LastProgress
                                : 0.001;
                            DownloadVideoFileManager.DownloadFileAsync(
                                video.DCId, video.ToInputFileLocation(), message, video.Size,
                                progress =>
                                {
                                    if (progress > 0.0)
                                    {
                                        mediaDoreplacedent.DownloadingProgress = progress;
                                    }
                                });
                        }
                        else
                        {
                            if (!message.Out.Value && message.HasTTL())
                            {
                                var ttlMessageMedia = mediaDoreplacedent as ITTLMessageMedia;
                                if (ttlMessageMedia != null && ttlMessageMedia.TTLParams == null)
                                {
                                    ttlMessageMedia.TTLParams = new TTLParams
                                    {
                                        StartTime = DateTime.Now,
                                        IsStarted = true,
                                        Total = ttlMessageMedia.TTLSeconds.Value
                                    };
                                    mediaDoreplacedent.NotifyOfPropertyChange(() => ttlMessageMedia.TTLParams);

                                    AddToTTLQueue(message as TLMessage70, ttlMessageMedia.TTLParams,
                                    result =>
                                    {
                                        SplitGroupedMessages(new List<TLInt> { message.Id });
                                    });
                                }

                                ReadMessageContents(message as TLMessage25);
                            }
                            else if (message.IsRoundVideo())
                            {
                                ReadMessageContents(message as TLMessage25);
                            }
#if WP81
                            if (file != null)
                            {
                                Launcher.LaunchFileAsync(file);
                                return;
                            }
#endif

                            var launcher = new MediaPlayerLauncher
                            {
                                Location = MediaLocationType.Data,
                                Media = new Uri(videoFileName, UriKind.Relative)
                            };
                            launcher.Show();
                        }
                        return;
                    }
                    else
                    {
                        OpenDoreplacedentCommon(message, StateService, DownloadDoreplacedentFileManager,
                            () =>
                            {
                                StateService.CurrentPhotoMessage = message;

                                if (AnimatedImageViewer == null)
                                {
                                    AnimatedImageViewer = new AnimatedImageViewerViewModel(StateService);
                                    NotifyOfPropertyChange(() => AnimatedImageViewer);
                                }

                                Execute.BeginOnUIThread(() => AnimatedImageViewer.OpenViewer());
                            });
                    }
                }
                else
                {
                    OpenDoreplacedentCommon(message, StateService, DownloadDoreplacedentFileManager,
                        () =>
                        {
                            StateService.CurrentPhotoMessage = message;

                            if (AnimatedImageViewer == null)
                            {
                                AnimatedImageViewer = new AnimatedImageViewerViewModel(StateService);
                                NotifyOfPropertyChange(() => AnimatedImageViewer);
                            }

                            Execute.BeginOnUIThread(() => AnimatedImageViewer.OpenViewer());
                        });
                }

                return;
            }

            Execute.ShowDebugMessage("tap on media");
        }

19 Source : DialogDetailsViewModel.Media.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static void OpenDoreplacedentCommon(TLMessage message, IStateService stateService, IDoreplacedentFileManager doreplacedentFileManager, System.Action openGifCallback)
#endif
        {
            var mediaDoreplacedent = message.Media as TLMessageMediaDoreplacedent;
            if (mediaDoreplacedent != null)
            {
                if (!string.IsNullOrEmpty(mediaDoreplacedent.IsoFileName))
                {

                }

                var doreplacedent = mediaDoreplacedent.Doreplacedent as TLDoreplacedent;
                if (doreplacedent == null) return;

                var doreplacedentLocalFileName = doreplacedent.GetFileName();
                var store = IsolatedStorageFile.GetUserStoreForApplication();
#if WP81
                var doreplacedentFile = mediaDoreplacedent.File ?? await GetStorageFile(mediaDoreplacedent);
#endif

                if (!store.FileExists(doreplacedentLocalFileName)
#if WP81
 && doreplacedentFile == null
#endif
)
                {

                    if (doreplacedent.Size.Value == 0) return;

                    mediaDoreplacedent.IsCanceled = false;
                    mediaDoreplacedent.DownloadingProgress = mediaDoreplacedent.LastProgress > 0.0 ? mediaDoreplacedent.LastProgress : 0.001;
                    //_downloadVideoStopwatch = Stopwatch.StartNew();
                    //return;
                    doreplacedentFileManager.DownloadFileAsync(
                        doreplacedent.FileName, doreplacedent.DCId, doreplacedent.ToInputFileLocation(), message, doreplacedent.Size,
                        progress =>
                        {
                            if (progress > 0.0)
                            {
                                mediaDoreplacedent.DownloadingProgress = progress;
                            }
                        });
                }
                else
                {
                    if (message.IsGif())
                    {
                        if (doreplacedentFile != null && File.Exists(doreplacedentFile.Path))
                        {
                            mediaDoreplacedent.DownloadingProgress = 0.001;
                            await doreplacedentFile.CopyAsync(ApplicationData.Current.LocalFolder, doreplacedentLocalFileName, NameCollisionOption.ReplaceExisting);
                            mediaDoreplacedent.DownloadingProgress = 0.0;
                        }

                        return;
                    }

                    if (doreplacedentLocalFileName.EndsWith(".gif")
                        || string.Equals(doreplacedent.MimeType.ToString(), "image/gif", StringComparison.OrdinalIgnoreCase))
                    {
                        openGifCallback.SafeInvoke();

                        return;
                    }

                    if (doreplacedentLocalFileName.EndsWith(".mp3")
                        || string.Equals(doreplacedent.MimeType.ToString(), "audio/mpeg", StringComparison.OrdinalIgnoreCase))
                    {
                        var url = new Uri(doreplacedentLocalFileName, UriKind.Relative);
                        var replacedle = doreplacedent.FileName.ToString();
                        var performer = "Unknown Artist";
                        var readId3Tags = true;
#if WP81

                        try
                        {
                            var storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(doreplacedentLocalFileName);
                            var audioProperties = await storageFile.Properties.GetMusicPropertiesAsync();
                            replacedle = audioProperties.replacedle;
                            performer = audioProperties.Artist;
                            readId3Tags = false;
                        }
                        catch (Exception ex) { }
#endif
#if WP81
                        if (doreplacedentFile == null)
                        {
                            try
                            {
                                doreplacedentFile = await ApplicationData.Current.LocalFolder.GetFileAsync(doreplacedentLocalFileName);
                            }
                            catch (Exception ex)
                            {
                                Execute.ShowDebugMessage("LocalFolder.GetFileAsync docLocal exception \n" + ex);
                            }
                        }
                        Launcher.LaunchFileAsync(doreplacedentFile);
                        return;
#elif WP8
                        var file = await ApplicationData.Current.LocalFolder.GetFileAsync(doreplacedentLocalFileName);
                        Launcher.LaunchFileAsync(file);
                        return;
#endif

                        //if (readId3Tags)
                        //{
                        //    if (store.FileExists(doreplacedentLocalFileName))
                        //    {
                        //        using (var file = store.OpenFile(doreplacedentLocalFileName, FileMode.Open, FileAccess.Read))
                        //        {
                        //            var mp3Stream = new Mp3Stream(file);
                        //            if (mp3Stream.HasTags)
                        //            {
                        //                var tag = mp3Stream.GetTag(Id3TagFamily.FileStartTag);
                        //                replacedle = tag.replacedle;
                        //                performer = tag.Artists;
                        //            }
                        //        }
                        //    }
                        //}

                        //var track = BackgroundAudioPlayer.Instance.Track;
                        //if (track == null || track.Source != url)
                        //{
                        //    BackgroundAudioPlayer.Instance.Track = new AudioTrack(url, replacedle, performer, null, null);
                        //}
                        //BackgroundAudioPlayer.Instance.Play();

                        return;
                    }
                    else
                    {
#if WP81
                        if (doreplacedentFile == null)
                        {
                            try
                            {
                                doreplacedentFile = await ApplicationData.Current.LocalFolder.GetFileAsync(doreplacedentLocalFileName);
                            }
                            catch (Exception ex)
                            {
                                Execute.ShowDebugMessage("LocalFolder.GetFileAsync docLocal exception \n" + ex);
                            }
                        }
                        Launcher.LaunchFileAsync(doreplacedentFile);
                        return;
#elif WP8
                        var file = await ApplicationData.Current.LocalFolder.GetFileAsync(doreplacedentLocalFileName);
                        Launcher.LaunchFileAsync(file);
                        return;
#endif
                    }
                }
                return;
            }
        }

19 Source : DialogDetailsViewModel.Photo.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void SendPhoto(Photo p)
        {
            var volumeId = TLLong.Random();
            var localId = TLInt.Random();
            var secret = TLLong.Random();

            var fileLocation = new TLFileLocation
            {
                VolumeId = volumeId,
                LocalId = localId,
                Secret = secret,
                DCId = new TLInt(0),        //TODO: remove from here, replace with FileLocationUnavailable
                //Buffer = p.Bytes
            };

            var fileName = String.Format("{0}_{1}_{2}.jpg",
                fileLocation.VolumeId,
                fileLocation.LocalId,
                fileLocation.Secret);

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

            var photoSize = new TLPhotoSize
            {
                Type = TLString.Empty,
                W = new TLInt(p.Width),
                H = new TLInt(p.Height),
                Location = fileLocation,
                Size = new TLInt(p.Bytes.Length)
            };

            var photo = new TLPhoto56
            {
                Flags = new TLInt(0),
                Id = new TLLong(0),
                AccessHash = new TLLong(0),
                Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now),
                Sizes = new TLVector<TLPhotoSizeBase> { photoSize },   
            };

            var media = new TLMessageMediaPhoto75 { Flags = new TLInt(0), Photo = photo, Caption = TLString.Empty };

            var message = GetMessage(TLString.Empty, media);

            if (ImageEditor == null)
            {
                ImageEditor = new ImageEditorViewModel
                {
                    Currenreplacedem = message,
                    ContinueAction = ContinueSendPhoto
                };
                NotifyOfPropertyChange(() => ImageEditor);
            }
            else
            {
                ImageEditor.Currenreplacedem = message;
            }

            BeginOnUIThread(() => ImageEditor.OpenEditor());
        }

19 Source : DialogDetailsViewModel.Photo.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void UploadPhotoInternal(TLMessage34 message)
        {
            var photo = ((TLMessageMediaPhoto)message.Media).Photo as TLPhoto;
            if (photo == null) return;

            var photoSize = photo.Sizes[0] as TLPhotoSize;
            if (photoSize == null) return;

            var fileLocation = photoSize.Location;
            if (fileLocation == null) return;

            byte[] bytes = null;
            var fileName = String.Format("{0}_{1}_{2}.jpg",
                fileLocation.VolumeId,
                fileLocation.LocalId,
                fileLocation.Secret);

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var fileStream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                {
                    if (fileStream.Length > 0)
                    {
                        bytes = new byte[fileStream.Length];
                        fileStream.Read(bytes, 0, bytes.Length);
                    }
                }
            }

            if (bytes == null) return;

            var md5Bytes = Telegram.Api.Helpers.Utils.ComputeMD5(bytes);
            var md5Checksum = BitConverter.ToInt64(md5Bytes, 0);
            
            StateService.GetServerFilesAsync(
                results =>
                {
                    var serverFile = results.FirstOrDefault(result => result.MD5Checksum.Value == md5Checksum);

#if MULTIPLE_PHOTOS
                    serverFile = null;
#endif

                    if (serverFile != null)
                    {
                        var media = serverFile.Media;
                        var captionMedia = media as IInputMediaCaption;
                        if (captionMedia == null)
                        {
                            var inputMediaPhoto = serverFile.Media as TLInputMediaPhoto;
                            if (inputMediaPhoto != null)
                            {
                                var inputMediaPhoto75 = new TLInputMediaPhoto75(inputMediaPhoto);
                                captionMedia = inputMediaPhoto75;
                                media = inputMediaPhoto75;
                                serverFile.Media = inputMediaPhoto75;
                                StateService.SaveServerFilesAsync(results);
                            }
                            var inputMediaUploadedPhoto = serverFile.Media as TLInputMediaUploadedPhoto;
                            if (inputMediaUploadedPhoto != null)
                            {
                                var inputMediaUploadedPhoto75 = new TLInputMediaUploadedPhoto75(inputMediaUploadedPhoto, null);
                                captionMedia = inputMediaUploadedPhoto75;
                                media = inputMediaUploadedPhoto75;
                                serverFile.Media = inputMediaUploadedPhoto75;
                                StateService.SaveServerFilesAsync(results);
                            }
                        }

                        if (captionMedia != null)
                        {
                            captionMedia.Caption = message.Message ?? TLString.Empty;
                        }

                        var ttlMedia = media as IInputTTLMedia;
                        if (ttlMedia != null)
                        {
                            ttlMedia.TTLSeconds = ((TLMessageMediaPhoto70) message.Media).TTLSeconds;
                        }

                        message.InputMedia = media;
                        UploadService.SendMediaInternal(message, MTProtoService, StateService, CacheService);
                    }
                    else
                    {
                        var fileId = TLLong.Random();
                        message.Media.FileId = fileId;
                        message.Media.UploadingProgress = 0.001;
                        UploadFileManager.UploadFile(fileId, message, bytes);
                    }
                });
        }

19 Source : DialogDetailsViewModel.Video.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void SendVideo(RecordedVideo recorderVideo)
        {
            if (recorderVideo == null) return;

            long size = 0;
            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var file = storage.OpenFile(recorderVideo.FileName, FileMode.Open, FileAccess.Read))
                {
                    size = file.Length;
                }
            }

            long photoSize = 0;
            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var file = storage.OpenFile(recorderVideo.FileName + ".jpg", FileMode.Open, FileAccess.Read))
                {
                    photoSize = file.Length;
                }
            }

            var volumeId = TLLong.Random();
            var localId = TLInt.Random();
            var secret = TLLong.Random();

            var thumbLocation = new TLFileLocation //TODO: replace with TLFileLocationUnavailable
            {
                DCId = new TLInt(0),
                VolumeId = volumeId,
                LocalId = localId,
                Secret = secret,
            };

            var fileName = String.Format("{0}_{1}_{2}.jpg",
                thumbLocation.VolumeId,
                thumbLocation.LocalId,
                thumbLocation.Secret);

            // заменяем имя на стандартное для всех каритинок
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                store.CopyFile(recorderVideo.FileName + ".jpg", fileName, true);
                store.DeleteFile(recorderVideo.FileName + ".jpg");
            }

            var thumbSize = new TLPhotoSize
            {
                W = new TLInt(640),
                H = new TLInt(480),
                Size = new TLInt((int) photoSize),
                Type = new TLString(""),
                Location = thumbLocation,
            };

            var doreplacedentAttributeVideo = new TLDoreplacedentAttributeVideo
            {
                Duration = new TLInt((int)recorderVideo.Duration),
                W = new TLInt(640),
                H = new TLInt(480)
            };

            var doreplacedent = new TLDoreplacedent54
            {
                Id = new TLLong(0),
                AccessHash = new TLLong(0),
                Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now),
                MimeType = new TLString("video/mp4"),
                Size = new TLInt((int)size),
                Thumb = thumbSize,
                DCId = new TLInt(0),
                Version = new TLInt(0),
                Attributes = new TLVector<TLDoreplacedentAttributeBase> { doreplacedentAttributeVideo }
            };

            var media = new TLMessageMediaDoreplacedent75
            {
                Flags = new TLInt(0),
                FileId = recorderVideo.FileId ?? TLLong.Random(),
                Doreplacedent = doreplacedent,
                IsoFileName = recorderVideo.FileName,
                Caption = TLString.Empty
            };

            var message = GetMessage(TLString.Empty, media);

            BeginOnUIThread(() =>
            {
                var previousMessage = InsertSendingMessage(message);
                IsEmptyDialog = Items.Count == 0 && (_messages == null || _messages.Count == 0) && LazyItems.Count == 0;

                BeginOnThreadPool(() =>
                    CacheService.SyncSendingMessage(
                        message, previousMessage,
                        m => SendVideoInternal(message, null)));
            });
        }

19 Source : DialogDetailsViewModel.Video.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void SendCompressedVideoInternal(TLMessage message, object o)
#endif
        {
            var doreplacedentMedia = message.Media as TLMessageMediaDoreplacedent45;
            if (doreplacedentMedia != null)
            {
                var fileName = doreplacedentMedia.IsoFileName;
                if (string.IsNullOrEmpty(fileName)) return;

                var video = doreplacedentMedia.Doreplacedent as TLDoreplacedent22;
                if (video == null) return;


                byte[] thumbBytes = null;
                var photoThumb = video.Thumb as TLPhotoSize;
                if (photoThumb != null)
                {
                    var location = photoThumb.Location as TLFileLocation;
                    if (location == null) return;

                    var thumbFileName = String.Format("{0}_{1}_{2}.jpg",
                        location.VolumeId,
                        location.LocalId,
                        location.Secret);

                    using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (var thumbFile = storage.OpenFile(thumbFileName, FileMode.Open, FileAccess.Read))
                        {
                            thumbBytes = new byte[thumbFile.Length];
                            thumbFile.Read(thumbBytes, 0, thumbBytes.Length);
                        }
                    }
                }

                var fileId = message.Media.FileId ?? TLLong.Random();
                message.Media.FileId = fileId;
                message.Media.UploadingProgress = 0.001;
                //return;
#if WP81
                if (file != null)
                {
                    UploadVideoFileManager.UploadFile(fileId, message.IsGif(), message, file);
                }
                else if (!string.IsNullOrEmpty(fileName))
                {
                    UploadVideoFileManager.UploadFile(fileId, message, fileName);
                }
                else
                {
                    return;
                }
#else
                UploadVideoFileManager.UploadFile(fileId, message, fileName);
#endif

                if (thumbBytes != null)
                {
                    var fileId2 = TLLong.Random();
                    UploadFileManager.UploadFile(fileId2, message.Media, thumbBytes);
                }

                return;
            }

            var videoMedia = message.Media as TLMessageMediaVideo;
            if (videoMedia != null)
            {
                var fileName = videoMedia.IsoFileName;
                if (string.IsNullOrEmpty(fileName)) return;

                var video = videoMedia.Video as TLVideo;
                if (video == null) return;


                byte[] thumbBytes = null;
                var photoThumb = video.Thumb as TLPhotoSize;
                if (photoThumb != null)
                {
                    var location = photoThumb.Location as TLFileLocation;
                    if (location == null) return;

                    var thumbFileName = String.Format("{0}_{1}_{2}.jpg",
                        location.VolumeId,
                        location.LocalId,
                        location.Secret);

                    using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (var thumbFile = storage.OpenFile(thumbFileName, FileMode.Open, FileAccess.Read))
                        {
                            thumbBytes = new byte[thumbFile.Length];
                            thumbFile.Read(thumbBytes, 0, thumbBytes.Length);
                        }
                    }
                }

                var fileId = message.Media.FileId ?? TLLong.Random();
                message.Media.FileId = fileId;
                message.Media.UploadingProgress = 0.001;

#if WP81
                if (file != null)
                {
                    UploadVideoFileManager.UploadFile(fileId, message.IsGif(), message, file);
                }
                else if (!string.IsNullOrEmpty(fileName))
                {
                    UploadVideoFileManager.UploadFile(fileId, message, fileName);
                }
                else
                {
                    return;
                }
#else
                UploadVideoFileManager.UploadFile(fileId, message, fileName);
#endif

                if (thumbBytes != null)
                {
                    var fileId2 = TLLong.Random();
                    UploadFileManager.UploadFile(fileId2, message.Media, thumbBytes);
                }

                return;
            }
        }

19 Source : DialogsViewModel.Common.cs
with GNU General Public License v2.0
from evgeny-nadymov

private static Uri GetTileImageUri(TLFileLocation location)
        {
            if (location == null) return null;

            var photoPath = String.Format("{0}_{1}_{2}.jpg", location.VolumeId, location.LocalId, location.Secret);

            var store = IsolatedStorageFile.GetUserStoreForApplication();
            if (!string.IsNullOrEmpty(photoPath)
                && store.FileExists(photoPath))
            {
                const string imageFolder = @"\Shared\ShellContent";
                if (!store.DirectoryExists(imageFolder))
                {
                    store.CreateDirectory(imageFolder);
                }
                if (!store.FileExists(Path.Combine(imageFolder, photoPath)))
                {
                    store.CopyFile(photoPath, Path.Combine(imageFolder, photoPath));
                }

                return new Uri(@"isostore:" + Path.Combine(imageFolder, photoPath), UriKind.Absolute);
            }

            return null;
        }

19 Source : SecretDialogDetailsViewModel.Handle.cs
with GNU General Public License v2.0
from evgeny-nadymov

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

            var decryptedMessage = item.Owner as TLDecryptedMessage;
            if (decryptedMessage != null)
            {
                var mediaExternalDoreplacedent = decryptedMessage.Media as TLDecryptedMessageMediaExternalDoreplacedent;
                if (mediaExternalDoreplacedent != null)
                {
                    decryptedMessage.NotifyOfPropertyChange(() => decryptedMessage.Self);
                }
            }

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

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

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

                            store.DeleteFile(fileName);
                        }

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

                    }

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

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

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

                            store.DeleteFile(fileName);
                        }
                    }

                    var mediaDoreplacedent = decryptedMessage.Media as TLDecryptedMessageMediaDoreplacedent;
                    if (mediaDoreplacedent != null)
                    {
                        if (decryptedMessage.IsVoice())
                        {
                            var fileLocation = decryptedMessage.Media.File as TLEncryptedFile;
                            if (fileLocation == null) return;

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

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

                                store.DeleteFile(fileName);

                            }

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

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

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

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

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

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

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

                                store.DeleteFile(fileName);
                            }
                        }
                    }

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

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

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

                            store.DeleteFile(fileName);

                        }

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

                            mediaAudio.DownloadingProgress = 1.0;
                        });
                    }

                }
            }
        }

19 Source : SecretDialogDetailsViewModel.Media.cs
with GNU General Public License v2.0
from evgeny-nadymov

public void OpenMedia(TLDecryptedMessage message)
#endif
        {
            if (message == null) return;
            if (message.Status == MessageStatus.Sending) return;
            if (message.Media.UploadingProgress > 0.0 && message.Media.UploadingProgress < 1.0) return;

            var mediaPhoto = message.Media as TLDecryptedMessageMediaPhoto;
            if (mediaPhoto != null)
            {

                var location = mediaPhoto.File as TLEncryptedFile;
                if (location != null)
                {
                    var fileName = String.Format("{0}_{1}_{2}.jpg",
                        location.Id,
                        location.DCId,
                        location.AccessHash);

                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!store.FileExists(fileName))
                        {
                            message.Media.IsCanceled = false;
                            message.Media.DownloadingProgress = 0.01;
                            var fileManager = IoC.Get<IEncryptedFileManager>();
                            fileManager.DownloadFile(location, mediaPhoto);

                            return;
                        }
                    }
                }

                if (!message.Out.Value
                    && message.TTL != null
                    && message.TTL.Value > 0
                    && message.TTL.Value <= 60.0
                    && mediaPhoto.TTLParams == null)
                {
                    message.IsTTLStarted = true;
                    message.DeleteDate = new TLLong(DateTime.Now.Ticks + message.TTL.Value * TimeSpan.TicksPerSecond);
                    mediaPhoto.TTLParams = new TTLParams
                    {
                        StartTime = DateTime.Now,
                        IsStarted = true,
                        Total = message.TTL.Value
                    };

                    AddToTTLQueue(message, mediaPhoto.TTLParams,
                        result =>
                        {
                            DeleteMessage(false, message);
                            SplitGroupedMessages(new List<TLLong> { message.RandomId });
                        });

                    CacheService.SyncDecryptedMessage(message, Chat, r =>
                    {
                        var chat = Chat as TLEncryptedChat;
                        if (chat == null) return;

                        var action = new TLDecryptedMessageActionReadMessages();
                        action.RandomIds = new TLVector<TLLong> { message.RandomId };

                        var decryptedTuple = GetDecryptedServiceMessageAndObject(action, chat, MTProtoService.CurrentUserId, CacheService);
#if DEBUG
                        Execute.BeginOnUIThread(() => Items.Insert(0, decryptedTuple.Item1));
#endif
                        SendEncryptedService(chat, decryptedTuple.Item2, MTProtoService, CacheService,
                            sentEncryptedMessage =>
                            {

                            });
                    });
                }

                message.Unread = new TLBool(false);
                message.Status = MessageStatus.Read;
                CacheService.SyncDecryptedMessage(message, Chat, r => { });

                if (mediaPhoto.IsCanceled)
                {
                    mediaPhoto.IsCanceled = false;
                    mediaPhoto.NotifyOfPropertyChange(() => mediaPhoto.Photo);
                    mediaPhoto.NotifyOfPropertyChange(() => mediaPhoto.Self);

                    return;
                }

                StateService.CurrentDecryptedPhotoMessage = message;
                StateService.CurrentDecryptedMediaMessages = message.TTL.Value > 0? new List<TLDecryptedMessage>() :
                    UngroupEnumerator(Items)
                    .OfType<TLDecryptedMessage>()
                    .Where(x => x.TTL.Value == 0 && (x.Media is TLDecryptedMessageMediaPhoto || x.IsVideo()))
                    .ToList();

                OpenImageViewer();

                return;
            }

            var mediaGeo = message.Media as TLDecryptedMessageMediaGeoPoint;
            if (mediaGeo != null)
            {
                OpenLocation(message);

                return;
            }

            var mediaVideo = message.Media 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);

                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (store.FileExists(fileName))
                    {
                        var mediaVideo17 = mediaVideo as TLDecryptedMessageMediaVideo17;
                        if (mediaVideo17 != null)
                        {
                            if (!message.Out.Value)
                            {
                                if (message.TTL != null && message.TTL.Value > 0 && message.TTL.Value <= 60.0)
                                {
                                    if (mediaVideo17.TTLParams == null)
                                    {
                                        message.IsTTLStarted = true;
                                        message.DeleteDate = new TLLong(DateTime.Now.Ticks + Math.Max(mediaVideo17.Duration.Value + 1, message.TTL.Value) * TimeSpan.TicksPerSecond);
                                        mediaVideo17.TTLParams = new TTLParams
                                        {
                                            StartTime = DateTime.Now,
                                            IsStarted = true,
                                            Total = message.TTL.Value
                                        };
                                        message.Unread = new TLBool(false);
                                        message.Status = MessageStatus.Read;

                                        AddToTTLQueue(message, mediaVideo17.TTLParams,
                                            result =>
                                            {
                                                DeleteMessage(false, message);
                                                SplitGroupedMessages(new List<TLLong> { message.RandomId });
                                            });

                                        CacheService.SyncDecryptedMessage(message, Chat, r =>
                                        {
                                            var chat = Chat as TLEncryptedChat;
                                            if (chat == null) return;

                                            var action = new TLDecryptedMessageActionReadMessages();
                                            action.RandomIds = new TLVector<TLLong>{ message.RandomId };

                                            var decryptedTuple = GetDecryptedServiceMessageAndObject(action, chat, MTProtoService.CurrentUserId, CacheService);

#if DEBUG
                                            Execute.BeginOnUIThread(() => Items.Insert(0, decryptedTuple.Item1));
#endif
                                            SendEncryptedService(chat, decryptedTuple.Item2, MTProtoService, CacheService,
                                                sentEncryptedMessage =>
                                                {

                                                });

                                        });
                                    }
                                }
                            }
                        }

                        var launcher = new MediaPlayerLauncher();
                        launcher.Location = MediaLocationType.Data;
                        launcher.Media = new Uri(fileName, UriKind.Relative);
                        launcher.Show();
                    }
                    else
                    {
                        mediaVideo.DownloadingProgress = 0.001;
                        var fileManager = IoC.Get<IEncryptedFileManager>();
                        fileManager.DownloadFile(fileLocation, mediaVideo);
                    }
                }

                return;
            }

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

                var fileName = String.Format("audio{0}_{1}.wav",
                    fileLocation.Id,
                    fileLocation.AccessHash);

                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!store.FileExists(fileName))
                    {
                        mediaAudio.DownloadingProgress = 0.001;
                        var fileManager = IoC.Get<IEncryptedFileManager>();
                        fileManager.DownloadFile(fileLocation, mediaAudio);
                    }
                    else
                    {
                        if (mediaAudio.IsCanceled)
                        {
                            mediaAudio.IsCanceled = false;
                            mediaAudio.NotifyOfPropertyChange(() => mediaAudio.ThumbSelf);

                            return;
                        }

                        var mediaAudio17 = mediaAudio as TLDecryptedMessageMediaAudio17;
                        if (mediaAudio17 != null)
                        {
                            if (!message.Out.Value)
                            {
                                if (message.TTL != null && message.TTL.Value > 0 && message.TTL.Value <= 60.0)
                                {
                                    if (mediaAudio17.TTLParams == null)
                                    {
                                        message.IsTTLStarted = true;
                                        message.DeleteDate = new TLLong(DateTime.Now.Ticks + Math.Max(mediaAudio17.Duration.Value + 1, message.TTL.Value) * TimeSpan.TicksPerSecond);
                                        mediaAudio17.TTLParams = new TTLParams
                                        {
                                            StartTime = DateTime.Now,
                                            IsStarted = true,
                                            Total = message.TTL.Value
                                        };
                                        message.Unread = new TLBool(false);
                                        message.Status = MessageStatus.Read;

                                        CacheService.SyncDecryptedMessage(message, Chat, r =>
                                        {
                                            var chat = Chat as TLEncryptedChat;
                                            if (chat == null) return;

                                            var action = new TLDecryptedMessageActionReadMessages();
                                            action.RandomIds = new TLVector<TLLong> { message.RandomId };

                                            var decryptedTuple = GetDecryptedServiceMessageAndObject(action, chat, MTProtoService.CurrentUserId, CacheService);

#if DEBUG
                                            Execute.BeginOnUIThread(() => Items.Insert(0, decryptedTuple.Item1));
#endif
                                            SendEncryptedService(chat, decryptedTuple.Item2, MTProtoService, CacheService,
                                                sentEncryptedMessage =>
                                                {

                                                });

                                        });
                                    }
                                }
                            }
                        }     
                    }
                }

                return;
            }

            var mediaDoreplacedent = message.Media as TLDecryptedMessageMediaDoreplacedent;
            if (mediaDoreplacedent != null)
            {
                if (message.IsVoice())
                {
                    var fileLocation = mediaDoreplacedent.File as TLEncryptedFile;
                    if (fileLocation == null) return;

                    var fileName = String.Format("audio{0}_{1}.wav",
                        fileLocation.Id,
                        fileLocation.AccessHash);

                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!store.FileExists(fileName))
                        {
                            mediaDoreplacedent.DownloadingProgress = 0.001;
                            var fileManager = IoC.Get<IEncryptedFileManager>();
                            fileManager.DownloadFile(fileLocation, mediaDoreplacedent);
                        }
                        else
                        {
                            if (mediaDoreplacedent.IsCanceled)
                            {
                                mediaDoreplacedent.IsCanceled = false;
                                mediaDoreplacedent.NotifyOfPropertyChange(() => mediaDoreplacedent.ThumbSelf);

                                return;
                            }

                            var mediaDoreplacedent45 = mediaDoreplacedent as TLDecryptedMessageMediaDoreplacedent45;
                            if (mediaDoreplacedent45 != null)
                            {
                                if (!message.Out.Value)
                                {
                                    var message45 = message as TLDecryptedMessage45;
                                    if (message.TTL != null && message.TTL.Value > 0 && message.TTL.Value <= 60.0)
                                    {
                                        if (mediaDoreplacedent45.TTLParams == null)
                                        {
                                            message.IsTTLStarted = true;
                                            message.DeleteDate = new TLLong(DateTime.Now.Ticks + Math.Max(mediaDoreplacedent45.Duration.Value + 1, message.TTL.Value) * TimeSpan.TicksPerSecond);
                                            mediaDoreplacedent45.TTLParams = new TTLParams
                                            {
                                                StartTime = DateTime.Now,
                                                IsStarted = true,
                                                Total = message.TTL.Value
                                            };
                                            message.Unread = new TLBool(false);
                                            message.Status = MessageStatus.Read;

                                            CacheService.SyncDecryptedMessage(message, Chat, r =>
                                            {
                                                var chat = Chat as TLEncryptedChat;
                                                if (chat == null) return;

                                                var action = new TLDecryptedMessageActionReadMessages();
                                                action.RandomIds = new TLVector<TLLong> { message.RandomId };

                                                var decryptedTuple = GetDecryptedServiceMessageAndObject(action, chat, MTProtoService.CurrentUserId, CacheService);

#if DEBUG
                                                Execute.BeginOnUIThread(() => Items.Insert(0, decryptedTuple.Item1));
#endif
                                                SendEncryptedService(chat, decryptedTuple.Item2, MTProtoService, CacheService,
                                                    sentEncryptedMessage =>
                                                    {
                                                        if (message45 != null)
                                                        {
                                                            message45.SetListened();
                                                            message45.Media.NotListened = false;
                                                            message45.Media.NotifyOfPropertyChange(() => message45.Media.NotListened);

                                                            CacheService.Commit();
                                                        }
                                                    });

                                            });
                                        }
                                    }
                                    else
                                    {
                                        ReadMessageContents(message45);
                                    }
                                }
                            }
                        }
                    }

                    return;
                }
                else if (message.IsVideo())
                {
                    var fileLocation = mediaDoreplacedent.File as TLEncryptedFile;
                    if (fileLocation == null) return;

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

                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (store.FileExists(fileName))
                        {
                            var mediaVideo17 = mediaDoreplacedent as TLDecryptedMessageMediaDoreplacedent45;
                            if (mediaVideo17 != null)
                            {
                                if (!message.Out.Value)
                                {
                                    if (message.TTL != null && message.TTL.Value > 0 && message.TTL.Value <= 60.0)
                                    {
                                        if (mediaVideo17.TTLParams == null)
                                        {
                                            message.IsTTLStarted = true;
                                            message.DeleteDate = new TLLong(DateTime.Now.Ticks + Math.Max(mediaVideo17.Duration.Value + 1, message.TTL.Value) * TimeSpan.TicksPerSecond);
                                            mediaVideo17.TTLParams = new TTLParams
                                            {
                                                StartTime = DateTime.Now,
                                                IsStarted = true,
                                                Total = message.TTL.Value
                                            };
                                            message.Unread = new TLBool(false);
                                            message.Status = MessageStatus.Read;

                                            AddToTTLQueue(message, mediaVideo17.TTLParams,
                                                result =>
                                                {
                                                    DeleteMessage(false, message);
                                                    SplitGroupedMessages(new List<TLLong> { message.RandomId });
                                                });

                                            CacheService.SyncDecryptedMessage(message, Chat, r =>
                                            {
                                                var chat = Chat as TLEncryptedChat;
                                                if (chat == null) return;

                                                var action = new TLDecryptedMessageActionReadMessages();
                                                action.RandomIds = new TLVector<TLLong> { message.RandomId };

                                                var decryptedTuple = GetDecryptedServiceMessageAndObject(action, chat, MTProtoService.CurrentUserId, CacheService);

#if DEBUG
                                                Execute.BeginOnUIThread(() => Items.Insert(0, decryptedTuple.Item1));
#endif
                                                SendEncryptedService(chat, decryptedTuple.Item2, MTProtoService, CacheService,
                                                    sentEncryptedMessage =>
                                                    {

                                                    });

                                            });
                                        }
                                    }
                                }
                            }

                            var launcher = new MediaPlayerLauncher();
                            launcher.Location = MediaLocationType.Data;
                            launcher.Media = new Uri(fileName, UriKind.Relative);
                            launcher.Show();
                        }
                        else
                        {
                            mediaDoreplacedent.DownloadingProgress = 0.001;
                            var fileManager = IoC.Get<IEncryptedFileManager>();
                            fileManager.DownloadFile(fileLocation, mediaDoreplacedent);
                        }
                    }

                    return;
                }
                else
                {
                    var fileLocation = mediaDoreplacedent.File as TLEncryptedFile;
                    if (fileLocation == null) return;

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

                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (store.FileExists(fileName))
                        {
#if WP8
                            StorageFile pdfFile = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
                            Windows.System.Launcher.LaunchFileAsync(pdfFile);
#endif
                        }
                        else
                        {
                            mediaDoreplacedent.DownloadingProgress = 0.001;
                            var fileManager = IoC.Get<IEncryptedFileManager>();
                            fileManager.DownloadFile(fileLocation, mediaDoreplacedent);
                        }
                    }
                }

                return;
            }
#if DEBUG
            MessageBox.Show("Tap on media");
#endif
        }

19 Source : SecretDialogDetailsViewModel.Photo.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void UploadPhotoInternal(byte[] data, TLObject obj)
        {
            var message = GetDecryptedMessage(obj);
            if (message == null) return;

            var media = message.Media as TLDecryptedMessageMediaPhoto;
            if (media == null) return;
            var file = media.File as TLEncryptedFile;
            if (file == null) return;

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

                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (var fileStream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                    {
                        data = new byte[fileStream.Length];
                        fileStream.Read(data, 0, data.Length);
                    }
                }
            }

            var encryptedBytes = Telegram.Api.Helpers.Utils.AesIge(data, media.Key.Data, media.IV.Data, true);

            UploadFileManager.UploadFile(file.Id, obj, encryptedBytes);
        }

19 Source : SecretDialogDetailsViewModel.Photo.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void SendPhoto(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)
            };

            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.PhotoPreviewMaxSize, Constants.PhotoPreviewQuality, out thumbHeight, out thumbWidth);

            var decryptedMediaPhoto = new TLDecryptedMessageMediaPhoto
            {
                Thumb = TLString.FromBigEndianData(thumb),
                ThumbW = new TLInt(thumbWidth),
                ThumbH = new TLInt(thumbHeight),
                Key = keyIV.Item1,
                IV = keyIV.Item2,
                W = new TLInt(p.Width),
                H = new TLInt(p.Height),
                Size = new TLInt(p.Bytes.Length),

                File = fileLocation,

                UploadingProgress = 0.001
            };

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

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

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

19 Source : SecretDialogDetailsViewModel.Text.cs
with GNU General Public License v2.0
from evgeny-nadymov

private static void ProcessSentEncryptedFile(TLDecryptedMessage message, TLSentEncryptedFile result)
        {
            var media = message.Media;
            if (media != null)
            {
                var oldFile = media.File as TLEncryptedFile;

                media.File = result.EncryptedFile;
                if (oldFile != null)
                {
                    var newFile = media.File as TLEncryptedFile;
                    if (newFile != null)
                    {
                        newFile.FileName = oldFile.FileName;
                        newFile.Duration = oldFile.Duration;

                        var mediaPhoto = media as TLDecryptedMessageMediaPhoto;
                        if (mediaPhoto != null)
                        {
                            var sourceFileName = String.Format("{0}_{1}_{2}.jpg",
                                oldFile.Id,
                                oldFile.DCId,
                                oldFile.AccessHash);

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

                            try
                            {
                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(sourceFileName))
                                    {
                                        store.CopyFile(sourceFileName, destinationFileName);
                                        store.DeleteFile(sourceFileName);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        }

                        var mediaDoreplacedent = media as TLDecryptedMessageMediaDoreplacedent45;
                        if (mediaDoreplacedent != null)
                        {
                            if (message.IsVoice())
                            {
                                var originalFileName = String.Format("audio{0}_{1}.mp3",
                                    oldFile.Id,
                                    oldFile.AccessHash);

                                var sourceFileName = String.Format("audio{0}_{1}.wav",
                                    oldFile.Id,
                                    oldFile.AccessHash);

                                var destinationFileName = String.Format("audio{0}_{1}.wav",
                                    newFile.Id,
                                    newFile.AccessHash);

                                try
                                {
                                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                    {
                                        if (store.FileExists(sourceFileName))
                                        {
                                            store.CopyFile(sourceFileName, destinationFileName);
                                            store.DeleteFile(sourceFileName);
                                        }

                                        if (store.FileExists(originalFileName))
                                        {
                                            store.DeleteFile(originalFileName);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                            else
                            {
                                var sourceFileName = String.Format("{0}_{1}_{2}.{3}",
                                    oldFile.Id,
                                    oldFile.DCId,
                                    oldFile.AccessHash,
                                    oldFile.FileExt ?? mediaDoreplacedent.FileExt);

                                var destinationFileName = String.Format("{0}_{1}_{2}.{3}",
                                    newFile.Id,
                                    newFile.DCId,
                                    newFile.AccessHash,
                                    newFile.FileExt ?? mediaDoreplacedent.FileExt);

                                try
                                {
                                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                    {
                                        if (store.FileExists(sourceFileName))
                                        {
                                            store.CopyFile(sourceFileName, destinationFileName);
                                            store.DeleteFile(sourceFileName);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                        }

                        var mediaAudio = media as TLDecryptedMessageMediaAudio;
                        if (mediaAudio != null)
                        {
                            var originalFileName = String.Format("audio{0}_{1}.mp3",
                                oldFile.Id,
                                oldFile.AccessHash);

                            var sourceFileName = String.Format("audio{0}_{1}.wav",
                                oldFile.Id,
                                oldFile.AccessHash);

                            var destinationFileName = String.Format("audio{0}_{1}.wav",
                                newFile.Id,
                                newFile.AccessHash);

                            try
                            {
                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(sourceFileName))
                                    {
                                        store.CopyFile(sourceFileName, destinationFileName);
                                        store.DeleteFile(sourceFileName);
                                    }

                                    if (store.FileExists(originalFileName))
                                    {
                                        store.DeleteFile(originalFileName);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                }
            }
        }

19 Source : SecretDialogDetailsViewModel.Video.cs
with GNU General Public License v2.0
from evgeny-nadymov

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)
            {
                if (encryptedChat17.Layer.Value >= Constants.MinSecretChatWithAudioAsDoreplacedentsLayer)
                {
                    decryptedMediaVideo = new TLDecryptedMessageMediaVideo45
                    {
                        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,
                        Caption = TLString.Empty,

                        File = fileLocation,

                        UploadingProgress = 0.001
                    };
                }
                else
                {
                    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);

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

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

19 Source : DecryptedImageViewerViewModel.cs
with GNU General Public License v2.0
from evgeny-nadymov

public void OpenMedia()
        {
            var message = Currenreplacedem as TLDecryptedMessage;
            if (message == null) return;

            var mediaVideo = message.Media 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);

                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (store.FileExists(fileName))
                    {
                        var launcher = new MediaPlayerLauncher();
                        launcher.Location = MediaLocationType.Data;
                        launcher.Media = new Uri(fileName, UriKind.Relative);
                        launcher.Show();
                    }
                    else
                    {
                        mediaVideo.DownloadingProgress = 0.001;
                        var fileManager = IoC.Get<IEncryptedFileManager>();
                        fileManager.DownloadFile(fileLocation, mediaVideo);

                        //DownloadVideoFileManager.DownloadFileAsync(mediaVideo.ToInputFileLocation(), message, mediaVideo.Size);
                    }
                }
            }
        }

19 Source : EmojiData.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static void LoadRecents()
        {

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists("EmojiRecents")) return;
                using (var stream = new IsolatedStorageFileStream("EmojiRecents", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite, store))
                {
                    if (stream.Length <= 0) return;

                    using (var br = new BinaryReader(stream))
                    {
                        var count = br.ReadInt32();

                        Recents = new List<EmojiDataItem>();

                        for (var i = 0; i < count; i++)
                        {
                            var emoji = new EmojiDataItem(br.ReadString(), br.ReadUInt64());
                            emoji.Uri = EmojiDataItem.BuildUri(emoji.String);
                            Recents.Add(emoji);
                        }
                    }
                }
            }
        }

19 Source : PhotoToThumbConverter.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static bool TryGetPhotoPreview(TLLong photoId, out BitmapImage preview, BitmapCreateOptions options)
        {
            preview = null;

            var fileName = string.Format("preview{0}.jpg", photoId);
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (store.FileExists(fileName))
                {
                    try
                    {
                        using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                        {
                            preview = ImageUtils.CreateImage(stream, options);
                            return true;
                        }
                    }
                    catch (Exception)
                    {
                        
                    }
                }
            }

            return false;
        }

19 Source : HttpDocumentFileManager.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void OnDownloading(object state)
        {
            DownloadablePart part = null;
            lock (_itemsSyncRoot)
            {
                for (var i = 0; i < _items.Count; i++)
                {
                    var item = _items[i];
                    if (item.Canceled)
                    {
                        _items.RemoveAt(i--);
                    }
                }

                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 currentWorker = (Worker)state;
                currentWorker.Stop();
                return;
            }


            var fileName = part.Parenreplacedem.DestFileName;
            var manualResetEvent = new ManualResetEvent(false);
            long? length = null;

            var webClient = new WebClient();
            webClient.OpenReadAsync(new Uri(part.Parenreplacedem.SourceUri, UriKind.Absolute));
            webClient.OpenReadCompleted += (sender, args) =>
            {
                if (args.Cancelled)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(part.Parenreplacedem.Timeout));
                    part.Parenreplacedem.IncreaseTimeout();
                    part.Status = PartStatus.Ready;
                    manualResetEvent.Set();

                    return;
                }

                if (args.Error != null)
                {
                    var webException = args.Error as WebException;
                    if (webException != null)
                    {
                        var response = webException.Response as HttpWebResponse;
                        if (response != null)
                        {
                            if (response.StatusCode == HttpStatusCode.Forbidden 
                                || response.StatusCode == HttpStatusCode.NotFound)
                            {
                                part.HttpErrorsCount++;
                                if (part.HttpErrorsCount >= 5)
                                {
                                    lock (_itemsSyncRoot)
                                    {
                                        part.Parenreplacedem.Canceled = true;
                                    }
                                }
                                else
                                {
                                    Thread.Sleep(TimeSpan.FromSeconds(part.Parenreplacedem.Timeout));
                                    part.Parenreplacedem.IncreaseTimeout();
                                    part.Status = PartStatus.Ready;

                                }
                            }
                            else
                            {
                                lock (_itemsSyncRoot)
                                {
                                    part.Parenreplacedem.Canceled = true;
                                }
                            }
                        }
                    }

                    manualResetEvent.Set();
                    return;
                }

                try
                {
                    length = args.Result.Length;
                    using (var stream = args.Result)
                    {
                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            using (var file = store.OpenFile(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read))
                            {
                                if (store.FileExists(fileName))
                                {
                                    //if (file.Position > file.Position)
                                    //{
                                    //    stream.Seek(file.Position, SeekOrigin.Begin);
                                    //}
                                    //else
                                    {
                                        file.Seek(0, SeekOrigin.Begin);
                                        stream.Seek(0, SeekOrigin.Begin);
                                    }
                                }

                                const int BUFFER_SIZE = 128 * 1024;
                                var buf = new byte[BUFFER_SIZE];

                                int bytesRead;
                                while ((bytesRead = stream.Read(buf, 0, BUFFER_SIZE)) > 0)
                                {
                                    file.Seek(0, SeekOrigin.End);
                                    file.Write(buf, 0, bytesRead);

                                    lock (_itemsSyncRoot)
                                    {
                                        if (part.Parenreplacedem.Canceled)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    manualResetEvent.Set();
                }
                catch (Exception ex)
                {
                    manualResetEvent.Set();
                }
            };

            manualResetEvent.WaitOne();

            // indicate progress
            // indicate complete
            bool isComplete;
            bool isCanceled;
            lock (_itemsSyncRoot)
            {
                long? fileLength = null;
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (store.FileExists(fileName))
                    {
                        using (var file = store.OpenFile(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            fileLength = file.Length;
                        }
                    }
                }

                isCanceled = part.Parenreplacedem.Canceled;
                isComplete = length.HasValue && fileLength.HasValue && fileLength == length;

                if (isComplete)
                {
                    part.Status = PartStatus.Processed;
                    _items.Remove(part.Parenreplacedem);
                }
            }

            if (!isCanceled)
            {
                if (isComplete)
                {
                    part.Parenreplacedem.IsoFileName = fileName;
                    if (part.Parenreplacedem.Callback != null)
                    {
                        Execute.BeginOnThreadPool(() =>
                        {
                            part.Parenreplacedem.Callback(part.Parenreplacedem);
                            if (part.Parenreplacedem.Callbacks != null)
                            {
                                foreach (var callback in part.Parenreplacedem.Callbacks)
                                {
                                    callback.SafeInvoke(part.Parenreplacedem);
                                }
                            }
                        });
                    }
                }
            }
            else
            {
                if (part.Parenreplacedem.FaultCallback != null)
                {
                    Execute.BeginOnThreadPool(() =>
                    {
                        part.Parenreplacedem.FaultCallback(part.Parenreplacedem);
                        if (part.Parenreplacedem.FaultCallbacks != null)
                        {
                            foreach (var callback in part.Parenreplacedem.FaultCallbacks)
                            {
                                callback.SafeInvoke(part.Parenreplacedem);
                            }
                        }
                    });
                }
            }
        }

19 Source : CacheViewModel.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void ClearCacheInternal()
        {
            if (_isCalculating) return;
            if (_settings == null) return;
            if (IsWorking) return;

            IsWorking = true;
            BeginOnThreadPool(() =>
            {

                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    var fileNames = store.GetFileNames();
                    foreach (var fileName in fileNames)
                    {
                        if (IsValidCacheFileName(fileName))
                        {
                            if (_settings.Photos && IsValidPhotoFileName(fileName))
                            {
                                DeleteFile(store, fileName);
                            }
                            else if (_settings.Music && IsValidMusicFileName(fileName))
                            {
                                DeleteFile(store, fileName);
                            }
                            else if (_settings.Video && IsValidVideoFileName(fileName))
                            {
                                DeleteFile(store, fileName);
                            }
                            else if (_settings.VoiceMessages && IsValidVoiceMessageFileName(fileName))
                            {
                                DeleteFile(store, fileName);
                            }
                            else if (_settings.Doreplacedents && IsValidDoreplacedentFileName(fileName))
                            {
                                DeleteFile(store, fileName);
                            }
                            else if (_settings.OtherFiles && IsValidOtherFileName(fileName))
                            {
                                DeleteFile(store, fileName);
                            }
                        }
                    }
                }

                if (_settings.Music 
                    || _settings.Video 
                    || _settings.VoiceMessages 
                    || _settings.Doreplacedents 
                    || _settings.OtherFiles)
                {
                    CacheService.ClearLocalFileNames();
                }


                EventAggregator.Publish(new ClearCacheEventArgs());
                var length = _settings.RecalculateLength();                
                Status = FileSizeConverter.Convert(length);
                IsWorking = false;
            });
        }

19 Source : CreateChannelStep1ViewModel.cs
with GNU General Public License v2.0
from evgeny-nadymov

public void SetChannelPhoto()
        {
            EditChatActions.EditPhoto(photo =>
            {
                var volumeId = TLLong.Random();
                var localId = TLInt.Random();
                var secret = TLLong.Random();

                var fileLocation = new TLFileLocation
                {
                    VolumeId = volumeId,
                    LocalId = localId,
                    Secret = secret,
                    DCId = new TLInt(0),
                    //Buffer = p.Bytes
                };

                var fileName = String.Format("{0}_{1}_{2}.jpg",
                    fileLocation.VolumeId,
                    fileLocation.LocalId,
                    fileLocation.Secret);

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

                Photo = new TLChatPhoto
                {
                    PhotoSmall = new TLFileLocation
                    {
                        DCId = fileLocation.DCId,
                        VolumeId = fileLocation.VolumeId,
                        LocalId = fileLocation.LocalId,
                        Secret = fileLocation.Secret
                    },
                    PhotoBig = new TLFileLocation
                    {
                        DCId = fileLocation.DCId,
                        VolumeId = fileLocation.VolumeId,
                        LocalId = fileLocation.LocalId,
                        Secret = fileLocation.Secret
                    }
                };
                NotifyOfPropertyChange(() => Photo);

                _uploadingPhoto = true;

                var fileId = TLLong.Random();
                _uploadManager.UploadFile(fileId, new TLChannel68(), photo);
            });
        }

19 Source : DialogDetailsViewModel.Document.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void SendDoreplacedentInternal(TLMessage34 message, object o)
#endif
        {
            var doreplacedent = ((TLMessageMediaDoreplacedent)message.Media).Doreplacedent as TLDoreplacedent;
            if (doreplacedent == null) return;

            byte[] thumbBytes = null;
            var thumb = doreplacedent.Thumb as TLPhotoSize;
            if (thumb != null)
            {
                var thumbLocation = thumb.Location as TLFileLocation;
                if (thumbLocation != null)
                {
                    var fileName = String.Format("{0}_{1}_{2}.jpg",
                        thumbLocation.VolumeId,
                        thumbLocation.LocalId,
                        thumbLocation.Secret);

                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (var fileStream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                        {
                            thumbBytes = new byte[fileStream.Length];
                            fileStream.Read(thumbBytes, 0, thumbBytes.Length);
                        }
                    }
                }
            }

            var bytes = doreplacedent.Buffer;
            var md5Bytes = Telegram.Api.Helpers.Utils.ComputeMD5(bytes ?? new byte[0]);
            var md5Checksum = BitConverter.ToInt64(md5Bytes, 0);

            StateService.GetServerFilesAsync(
                results =>
                {
                    var serverFile = results.FirstOrDefault(result => result.MD5Checksum.Value == md5Checksum);

                    if (serverFile != null)
                    {
                        message.InputMedia = serverFile.Media;
                        UploadService.SendMediaInternal(message, MTProtoService, StateService, CacheService);
                    }
                    else
                    {
                        if (thumbBytes != null)
                        {
                            var thumbFileId = TLLong.Random();
                            UploadFileManager.UploadFile(thumbFileId, message.Media, thumbBytes);

                            Thread.Sleep(100); //NOTE: без этой строки не работает. Почему???
                        }

                        var fileId = TLLong.Random();
                        message.Media.FileId = fileId;
                        message.Media.UploadingProgress = 0.001;
#if WP81
                        if (file == null)
                        {
                            UploadDoreplacedentFileManager.UploadFile(fileId, message, bytes);
                        }
                        else
                        {
                            UploadDoreplacedentFileManager.UploadFile(fileId, message, file);
                        }
#else
                        UploadDoreplacedentFileManager.UploadFile(fileId, message, bytes);
#endif
                    }
                });
        }

19 Source : SecretDialogDetailsViewModel.Document.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void SendDoreplacedentInternal(byte[] data, TLObject obj)
        {
            var message = GetDecryptedMessage(obj);
            if (message == null) return;

            var media = message.Media as TLDecryptedMessageMediaDoreplacedent;
            if (media == null) return;
            var file = media.File as TLEncryptedFile;
            if (file == null) return;

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

                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (var fileStream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                    {
                        data = new byte[fileStream.Length];
                        fileStream.Read(data, 0, data.Length);
                    }
                }
            }

            var encryptedBytes = Telegram.Api.Helpers.Utils.AesIge(data, media.Key.Data, media.IV.Data, true);
            UploadDoreplacedentFileManager.UploadFile(file.Id, obj, encryptedBytes);
        }

19 Source : PhotoToThumbConverter.cs
with GNU General Public License v2.0
from evgeny-nadymov

public static void SaveFile(string fileName, MemoryStream blurredStream)
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                try
                {
                    using (var stream = store.OpenFile(fileName, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        var buffer = blurredStream.ToArray();
                        stream.Seek(0, SeekOrigin.Begin);
                        stream.Write(buffer, 0, buffer.Length);
                    }
                }
                catch (Exception)
                {
                }
            }
        }

19 Source : SecretDialogDetailsViewModel.Video.cs
with GNU General Public License v2.0
from evgeny-nadymov

private void SendVideoInternal(byte[] data, TLObject obj)
        {
            var message = GetDecryptedMessage(obj);
            if (message == null) return;

            var mediaVideo = message.Media as TLDecryptedMessageMediaVideo;
            if (mediaVideo == null) return;

            var fileLocation = mediaVideo.File as TLEncryptedFile;
            if (fileLocation == null) return;

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

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

            var encryptedBytes = Telegram.Api.Helpers.Utils.AesIge(data, mediaVideo.Key.Data, mediaVideo.IV.Data, true);
            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var file = storage.OpenFile("encrypted." + fileName, FileMode.Create, FileAccess.Write))
                {
                    file.Write(encryptedBytes, 0, encryptedBytes.Length);
                }
            }

            UploadVideoFileManager.UploadFile(fileLocation.Id, obj, "encrypted." + fileName);
        }

19 Source : CacheViewModel.cs
with GNU General Public License v2.0
from evgeny-nadymov

public void ClearLocalDatabase()
        {
            var result = MessageBox.Show(AppResources.ClearLocalDatabaseConfirmation, AppResources.Confirm, MessageBoxButton.OKCancel);

            if (result == MessageBoxResult.OK)
            {
                IsWorking = true;
                CacheService.CompressAsync(() =>
                {
                    long newLength;
                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        var files = new List<TelegramFileInfo>();
                        newLength = GetDatabaseLength(store, files);
                            
                    }

                    BeginOnUIThread(() =>
                    {
                        IsWorking = false;
                        LocalDatabaseStatus = FileSizeConverter.Convert(newLength);

                        EventAggregator.Publish(new ClearLocalDatabaseEventArgs());
                    });
                });
            }
        }

19 Source : ChooseBackgroundViewModel.cs
with GNU General Public License v2.0
from evgeny-nadymov

public void Choose(BackgroundItem item)
        {
            if (item == null)
            {
                return;
            }

            if (item == _libraryBackground)
            {
                var task = new PhotoChooserTask
                {
                    PixelHeight = 800, 
                    PixelWidth = 480, 
                    ShowCamera = true
                };
                task.Completed += (sender, result) =>
                {
                    if (result.TaskResult != TaskResult.OK)
                    {
                        return;
                    }

                    byte[] bytes;
                    var sourceStream = result.ChosenPhoto;
                    var fileName = Path.GetFileName(result.OriginalFileName);

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

                    using (var memoryStream = new MemoryStream())
                    {
                        sourceStream.CopyTo(memoryStream);
                        bytes = memoryStream.ToArray();
                    }

                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (var file = store.OpenFile(fileName, FileMode.CreateNew))
                        {
                            file.Write(bytes, 0, bytes.Length);
                        }
                    }

                    _libraryBackground.IsoFileName = fileName;

                    ReplaceBackgroundItem(_libraryBackground);
                };
                task.Show();

                return;
            }

            if (item == AnimatedBackground1)
            {
                MessageBox.Show(AppResources.PleaseNoteThatAnimatedBackgroundConsumesMoreBatteryResources);
            }

            ReplaceBackgroundItem(item);
        }

See More Examples