Ejemplo n.º 1
0
        private TLFile GetFile(TLFileLocation location, TLInt offset, TLInt limit)
        {
            var    manualResetEvent = new ManualResetEvent(false);
            TLFile result           = null;

            _mtProtoService.GetFileAsync(location.DCId, location.ToInputFileLocation(), offset, limit,
                                         file =>
            {
                result = file;
                manualResetEvent.Set();
            },
                                         error =>
            {
                int delay;
                lock (_randomRoot)
                {
                    delay = _random.Next(1000, 3000);
                }

                Execute.BeginOnThreadPool(TimeSpan.FromMilliseconds(delay), () => manualResetEvent.Set());
            });

            manualResetEvent.WaitOne();
            return(result);
        }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
        public void DownloadFile(TLFileLocation file, TLObject owner, TLInt fileSize)
        {
            var downloadableItem = GetDownloadableItem(file, owner, fileSize);

            lock (_itemsSyncRoot)
            {
                bool addFile = true;
                foreach (var item in _items)
                {
                    if (item.Location.VolumeId.Value == file.VolumeId.Value &&
                        item.Location.LocalId.Value == file.LocalId.Value &&
                        item.Owner == owner)
                    {
                        addFile = false;
                        break;
                    }
                }

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

            StartAwaitingWorkers();
        }
Ejemplo n.º 4
0
        public void DownloadFile(TLFileLocation file, int fileSize, Action <DownloadableItem> callback)
        {
            //var tsc = new TaskCompletionSource<string>();

            //FileLoader.Current.LoadFile(file, ".jpg", fileSize, false, tsc);
            //var name = await tsc.Task;
            //callback?.Invoke(new DownloadableItem { DestFileName = name });

            //return;

            var downloadableItem = GetDownloadableItem(file, null, fileSize);

            downloadableItem.Action = callback;

            lock (_itemsSyncRoot)
            {
                bool addFile = true;
                foreach (var item in _items)
                {
                    if (item.Location.VolumeId == file.VolumeId &&
                        item.Location.LocalId == file.LocalId)
                    {
                        addFile = false;
                        break;
                    }
                }

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

            StartAwaitingWorkers();
        }
Ejemplo n.º 5
0
        private async void EditPhotoExecute(StorageFile file)
        {
            var fileLocation = new TLFileLocation
            {
                VolumeId = TLLong.Random(),
                LocalId  = TLInt.Random(),
                Secret   = TLLong.Random(),
                DCId     = 0
            };

            var fileName  = string.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var fileCache = await FileUtils.CreateTempFileAsync(fileName);

            await file.CopyAndReplaceAsync(fileCache);

            var fileScale = fileCache;

            var basicProps = await fileScale.GetBasicPropertiesAsync();

            var imageProps = await fileScale.Properties.GetImagePropertiesAsync();

            var fileId = TLLong.Random();
            var upload = await _uploadFileManager.UploadFileAsync(fileId, fileCache.Name);

            if (upload != null)
            {
                var response = await ProtoService.EditChatPhotoAsync(_item.Id, new TLInputChatUploadedPhoto { File = upload.ToInputFile() });

                if (response.IsSucceeded)
                {
                }
            }
        }
Ejemplo n.º 6
0
        public void DownloadFile(TLFileLocation file, TLObject owner, TLInt fileSize)
        {
            var downloadableItem = GetDownloadableItem(file, owner, fileSize, null);

            lock (_itemsSyncRoot)
            {
                bool addFile           = true;
                var  inputFileLocation = file.ToInputFileLocation();
                foreach (var item in _items)
                {
                    if (item.InputLocation.LocationEquals(inputFileLocation) &&
                        item.Owner == owner)
                    {
                        addFile = false;
                        break;
                    }
                }

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

            StartAwaitingWorkers();
        }
Ejemplo n.º 7
0
        public virtual async Task DownloadFileFromWrongLocationTest()
        {
            TelegramClient client = this.NewClient();

            TelegramAuthModel authModel = new TelegramAuthModel()
            {
                ApiId   = this.ApiId,
                ApiHash = this.ApiHash
            };
            await client.AuthenticateAsync(authModel);

            TeleSharp.TL.Contacts.TLContacts result = await client.GetContactsAsync();

            TLUser user = result.Users
                          .OfType <TLUser>()
                          .FirstOrDefault(x => x.Id == 5880094);

            TLUserProfilePhoto photo         = ((TLUserProfilePhoto)user.Photo);
            TLFileLocation     photoLocation = (TLFileLocation)photo.PhotoBig;

            TeleSharp.TL.Upload.TLFile resFile = await client.GetFile(new TLInputFileLocation()
            {
                LocalId  = photoLocation.LocalId,
                Secret   = photoLocation.Secret,
                VolumeId = photoLocation.VolumeId
            }, 1024);

            TLAbsDialogs res = await client.GetUserDialogsAsync();

            Assert.IsTrue(resFile.Bytes.Length > 0);
        }
Ejemplo n.º 8
0
        private void SetWebPSource(ITLTransferable transferable, TLFileLocation location, int fileSize, int phase)
        {
            if (phase >= Phase && location != null)
            {
                Phase = phase;

                var fileName = string.Format("{0}_{1}_{2}.jpg", location.VolumeId, location.LocalId, location.Secret);
                if (File.Exists(FileUtils.GetTempFileName(fileName)))
                {
                    //Image.UriSource = FileUtils.GetTempFileUri(fileName);
                    _bitmapImage.SetSource(WebPImage.Encode(File.ReadAllBytes(FileUtils.GetTempFileName(fileName))));
                }
                else
                {
                    Execute.BeginOnThreadPool(async() =>
                    {
                        var result = await _downloadManager.DownloadFileAsync(location, fileSize).AsTask(transferable?.Download());
                        if (result != null && Phase <= phase)
                        {
                            Execute.BeginOnUIThread(() =>
                            {
                                if (transferable != null)
                                {
                                    transferable.IsTransferring = false;
                                }

                                //Image.UriSource = FileUtils.GetTempFileUri(fileName);
                                _bitmapImage.SetSource(WebPImage.Encode(File.ReadAllBytes(FileUtils.GetTempFileName(fileName))));
                            });
                        }
                    });
                }
            }
        }
Ejemplo n.º 9
0
        public static BitmapImage ReturnOrEnqueueImage(bool checkChatSettings, TLFileLocation location, TLObject owner, int fileSize, TLMessageMediaPhoto mediaPhoto)
        {
            string fileName = string.Format("{0}_{1}_{2}.jpg", location.VolumeId, location.LocalId, location.Secret);

            if (File.Exists(FileUtils.GetTempFileName(fileName)))
            {
                var bitmap = new BitmapImage();
                bitmap.UriSource = FileUtils.GetTempFileUri(fileName);
                return(bitmap);
            }

            if (fileSize >= 0)
            {
                var manager = UnigramContainer.Current.ResolveType <IDownloadFileManager>();
                var bitmap  = new BitmapImage();

                //Execute.BeginOnThreadPool(() => manager.DownloadFile(location, owner, fileSize));
                Execute.BeginOnThreadPool(async() =>
                {
                    await manager.DownloadFileAsync(location, fileSize, mediaPhoto?.Photo.Download());
                    Execute.BeginOnUIThread(() =>
                    {
                        bitmap.UriSource = FileUtils.GetTempFileUri(fileName);
                    });
                });

                return(bitmap);
            }

            return(null);
        }
Ejemplo n.º 10
0
        private async void EditPhotoExecute(StorageFile file)
        {
            _uploadingPhoto = true;

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

            var fileName  = string.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var fileCache = await FileUtils.CreateTempFileAsync(fileName);

            await file.CopyAndReplaceAsync(fileCache);

            var fileScale = fileCache;

            Preview = new BitmapImage(FileUtils.GetTempFileUri(fileName));

            var fileId = TLLong.Random();
            var upload = await _uploadFileManager.UploadFileAsync(fileId, fileCache.Name);

            if (upload != null)
            {
                _photo          = upload.ToInputFile();
                _uploadingPhoto = false;
                _uploadingCallback?.Invoke();
            }
        }
Ejemplo n.º 11
0
        public string GetPicture(ITLDialogWith with, string group)
        {
            TLFileLocation location = null;

            if (with is TLUser user && user.Photo is TLUserProfilePhoto userPhoto)
            {
                location = userPhoto.PhotoSmall as TLFileLocation;
            }
Ejemplo n.º 12
0
        private string GetPicture(TLMessageCommonBase custom, string group)
        {
            TLFileLocation location = null;

            if (custom.Parent is TLUser user && user.Photo is TLUserProfilePhoto userPhoto)
            {
                location = userPhoto.PhotoSmall as TLFileLocation;
            }
        public static BitmapSource ReturnOrEnqueueProfileImage(Stopwatch timer, TLFileLocation location, TLObject owner, TLInt fileSize)
        {
            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                         location.VolumeId,
                                         location.LocalId,
                                         location.Secret);

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists(fileName))
                {
                    if (fileSize != null)
                    {
                        var fileManager = IoC.Get <IFileManager>();
                        ThreadPool.QueueUserWorkItem(state =>
                        {
                            fileManager.DownloadFile(location, owner, fileSize);
                        });
                    }
                }
                else
                {
                    BitmapSource  imageSource;
                    WeakReference weakImageSource;
                    if (_cachedSources.TryGetValue(fileName, out weakImageSource))
                    {
                        if (weakImageSource.IsAlive)
                        {
                            imageSource = weakImageSource.Target as BitmapSource;

                            return(imageSource);
                        }
                    }

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

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

                    return(imageSource);
                }
            }

            return(null);
        }
        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 TLChannel(), photo);
            });
        }
Ejemplo n.º 15
0
        private DownloadableItem GetDownloadableItem(TLFileLocation location, TLObject owner, TLInt fileSize)
        {
            var item = new DownloadableItem
            {
                Owner    = owner,
                Location = location
            };

            item.Parts = GetItemParts(fileSize, item);

            return(item);
        }
Ejemplo n.º 16
0
        private void SavePhotoAsync(Action <string> callback = null)
        {
            TLFileLocation location     = null;
            var            profilePhoto = CurrentItem as TLUserProfilePhoto;

            if (profilePhoto != null)
            {
                location = profilePhoto.PhotoBig as TLFileLocation;
            }

            var photo = CurrentItem as TLPhoto;

            if (photo != null)
            {
                TLPhotoSize  size  = null;
                var          sizes = photo.Sizes.OfType <TLPhotoSize>();
                const double width = 640.0;
                foreach (var photoSize in sizes)
                {
                    if (size == null ||
                        Math.Abs(width - size.W.Value) > Math.Abs(width - photoSize.W.Value))
                    {
                        size = photoSize;
                    }
                }
                if (size == null)
                {
                    return;
                }

                location = size.Location as TLFileLocation;
            }

            var chatPhoto = CurrentItem as TLChatPhoto;

            if (chatPhoto != null)
            {
                location = chatPhoto.PhotoBig as TLFileLocation;
            }

            if (location == null)
            {
                return;
            }

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

            Execute.BeginOnThreadPool(() => ImageViewerViewModel.SavePhoto(fileName, callback));
        }
Ejemplo n.º 17
0
        private static async Task <TLPhotoSizeBase> GetFileThumbAsync(StorageFile file)
        {
            try
            {
                var thumb = await file.GetThumbnailAsync(ThumbnailMode.PicturesView, 190, ThumbnailOptions.ResizeThumbnail);

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

                var thumbLocation = new TLFileLocation
                {
                    DCId     = new TLInt(0),
                    VolumeId = volumeId,
                    LocalId  = localId,
                    Secret   = secret,
                };

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

                var thumbFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                var thumbBuffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(thumb.Size));
                var iBuf        = await thumb.ReadAsync(thumbBuffer, thumbBuffer.Capacity, InputStreamOptions.None);

                using (var thumbStream = await thumbFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await thumbStream.WriteAsync(iBuf);
                }

                var thumbSize = new TLPhotoSize
                {
                    W        = new TLInt((int)thumb.OriginalWidth),
                    H        = new TLInt((int)thumb.OriginalHeight),
                    Size     = new TLInt((int)thumb.Size),
                    Type     = new TLString(""),
                    Location = thumbLocation,
                };

                return(thumbSize);
            }
            catch (Exception ex)
            {
                Telegram.Api.Helpers.Execute.ShowDebugMessage("GetFileThumbAsync exception " + ex);
            }

            return(null);
        }
Ejemplo n.º 18
0
        protected DownloadableItem GetDownloadableItem(TLFileLocation location, TLObject owner, TLInt fileSize, Action <DownloadableItem> callback)
        {
            var item = new DownloadableItem
            {
                Owner         = owner,
                DCId          = location.DCId,
                Callback      = callback,
                InputLocation = location.ToInputFileLocation()
            };

            item.Parts = GetItemParts(fileSize, item);

            return(item);
        }
Ejemplo n.º 19
0
        private async void EditPhotoExecute(StorageFile file)
        {
            var fileLocation = new TLFileLocation
            {
                VolumeId = TLLong.Random(),
                LocalId  = TLInt.Random(),
                Secret   = TLLong.Random(),
                DCId     = 0
            };

            var fileName  = string.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var fileCache = await FileUtils.CreateTempFileAsync(fileName);

            //var fileScale = await ImageHelper.ScaleJpegAsync(file, fileCache, 640, 0.77);

            await file.CopyAndReplaceAsync(fileCache);

            var fileScale = fileCache;

            var basicProps = await fileScale.GetBasicPropertiesAsync();

            var imageProps = await fileScale.Properties.GetImagePropertiesAsync();

            var fileId = TLLong.Random();
            var upload = await _uploadFileManager.UploadFileAsync(fileId, fileCache.Name);

            if (upload != null)
            {
                var response = await ProtoService.UploadProfilePhotoAsync(upload.ToInputFile() as TLInputFile);

                if (response.IsSucceeded)
                {
                    var user = Self as TLUser;
                    if (user == null)
                    {
                        return;
                    }

                    var userFull = CacheService.GetFullUser(user.Id);
                    if (userFull == null)
                    {
                        return;
                    }

                    userFull.HasProfilePhoto = true;
                    userFull.ProfilePhoto    = response.Result.Photo;
                    userFull.RaisePropertyChanged(() => userFull.ProfilePhoto);
                }
            }
        }
        //Downloading actions:
        public static async Task <byte[]> DownloadPhotoFile(TLPhoto photo)
        {
            var            photoSize = photo.Sizes.ToList().OfType <TLPhotoSize>().Last();
            TLFileLocation tf        = (TLFileLocation)photoSize.Location;

            return(_client.GetFile(new TLInputFileLocation
            {
                LocalId = tf.LocalId,
                Secret = tf.Secret,
                VolumeId = tf.VolumeId
            }
                                   ,
                                   (int)Math.Pow(2, Math.Ceiling(Math.Log(photoSize.Size, 2)))).Result.Bytes);
        }
        public async Task <TLMessage25> GetPhotoMessage(StorageFile file)
        {
            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);

            var stream = await file.OpenReadAsync();

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

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

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

            var media = new TLMessageMediaPhoto28 {
                Photo = photo, Caption = TLString.Empty, File = resizedPhoto.File
            };

            return(GetMessage(TLString.Empty, media));
        }
Ejemplo n.º 22
0
        public void Cancel(TLFileLocation file)
        {
            Execute.BeginOnThreadPool(() =>
            {
                lock (_itemsSyncRoot)
                {
                    var items = _items.Where(x => x.Location.VolumeId == file.VolumeId && x.Location.LocalId == file.LocalId);

                    foreach (var item in items)
                    {
                        item.IsCancelled = true;
                    }
                }
            });
        }
Ejemplo n.º 23
0
        public TLFile GetFile(TLFileLocation fileLocation, int iSize)
        {
            TLAbsInputFileLocation inputFileLocation = new TLInputFileLocation()
            {
                volume_id = fileLocation.volume_id,
                local_id  = fileLocation.local_id,
                secret    = fileLocation.secret,
            };
            TLFile file = (TLFile)AsyncHelpers.RunSync <TLFile>(() => m_client.GetFile(inputFileLocation, iSize));

            if (file.bytes.Length != iSize)
            {
                throw new TLCoreException("The file need to be downloaded in parts");
            }
            return(file);
        }
Ejemplo n.º 24
0
        private bool TrySetSource(TLFileLocation location, int phase)
        {
            if (phase >= Phase && location != null)
            {
                var fileName = string.Format("{0}_{1}_{2}.jpg", location.VolumeId, location.LocalId, location.Secret);
                if (File.Exists(FileUtils.GetTempFileName(fileName)))
                {
                    Phase = phase;

                    _bitmapImage.UriSource = FileUtils.GetTempFileUri(fileName);
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 25
0
        private TLUploadFileBase GetFile(TLFileLocation location, int offset, int limit, out TLRPCError er, out bool isCanceled)
        {
            var manualResetEvent      = new ManualResetEvent(false);
            TLUploadFileBase result   = null;
            TLRPCError       outError = null;
            var outIsCanceled         = false;

            _protoService.GetFileAsync(location.DCId, location.ToInputFileLocation(), offset, limit,
                                       callback =>
            {
                result = callback;
                manualResetEvent.Set();

                if (callback is TLUploadFile file)
                {
                    _statsService.IncrementReceivedBytesCount(_protoService.NetworkType, _dataType, 4 + 4 + file.Bytes.Length + 4);
                }
            },
                                       error =>
            {
                outError = error;

                if (error.CodeEquals(TLErrorCode.INTERNAL) ||
                    (error.CodeEquals(TLErrorCode.BAD_REQUEST) && (error.TypeEquals(TLErrorType.LOCATION_INVALID) || error.TypeEquals(TLErrorType.VOLUME_LOC_NOT_FOUND))) ||
                    (error.CodeEquals(TLErrorCode.NOT_FOUND) && error.ErrorMessage != null && error.ErrorMessage.StartsWith("Incorrect dhGen")))
                {
                    outIsCanceled = true;

                    manualResetEvent.Set();
                    return;
                }

                int delay;
                lock (_randomRoot)
                {
                    delay = _random.Next(1000, 3000);
                }

                Execute.BeginOnThreadPool(TimeSpan.FromMilliseconds(delay), () => manualResetEvent.Set());
            });

            manualResetEvent.WaitOne(20 * 1000);
            er         = outError;
            isCanceled = outIsCanceled;

            return(result);
        }
        public static ImageSource ReturnOrEnqueueStickerPreview(TLFileLocation location, TLObject owner, TLInt fileSize)
        {
            var fileName =
                String.Format("{0}_{1}_{2}.jpg",
                              location.VolumeId,
                              location.LocalId,
                              location.Secret);

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists(fileName))
                {
                    if (fileSize != null)
                    {
                        var fileManager = IoC.Get <IFileManager>();
                        Telegram.Api.Helpers.Execute.BeginOnThreadPool(() =>
                        {
                            fileManager.DownloadFile(location, owner, fileSize);
                        });
                    }
                }
                else
                {
                    byte[] buffer;
                    using (var file = store.OpenFile(fileName, FileMode.Open))
                    {
                        buffer = new byte[file.Length];
                        file.Read(buffer, 0, buffer.Length);
                    }

                    return(DecodeWebPImage(fileName, buffer,
                                           () =>
                    {
                        using (var localStore = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            localStore.DeleteFile(fileName);
                        }
                    }));
                }
            }

            return(null);
        }
        public static BitmapImage ReturnImage(Stopwatch timer, TLFileLocation location)
        {
            //return null;

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

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists(fileName))
                {
                }
                else
                {
                    BitmapImage imageSource;

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


                    //TLUtils.WritePerformance("DefaultPhotoConverter time: " + timer.Elapsed);
                    return(imageSource);
                }
            }

            return(null);
        }
Ejemplo n.º 28
0
        public void DownloadFile(TLFileLocation file, TLObject owner, TLInt fileSize, Action <DownloadableItem> callback)
        {
            var downloadableItem = GetDownloadableItem(file, owner, fileSize, callback);

            lock (_itemsSyncRoot)
            {
                bool addFile           = true;
                var  inputFileLocation = file.ToInputFileLocation();
                foreach (var item in _items)
                {
                    if (item.InputLocation.LocationEquals(inputFileLocation))
                    {
                        if (callback != null)
                        {
                            if (item.Callbacks == null)
                            {
                                item.Callbacks = new List <Action <DownloadableItem> >();
                            }
                            item.Callbacks.Add(callback);

                            addFile = false;
                            break;
                        }

                        if (item.Owner == owner)
                        {
                            addFile = false;
                            break;
                        }
                    }
                }

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

            StartAwaitingWorkers();
        }
Ejemplo n.º 29
0
        public static BitmapSource ReturnOrEnqueueProfileImage(TLFileLocation location, TLObject owner, int fileSize)
        {
            var fileName = string.Format("{0}_{1}_{2}.jpg", location.VolumeId, location.LocalId, location.Secret);

            if (_cachedSources.TryGetValue(fileName, out WeakReference weakReference) && weakReference.IsAlive)
            {
                return(weakReference.Target as BitmapSource);
            }

            if (File.Exists(FileUtils.GetTempFileName(fileName)))
            {
                var bitmap = new BitmapImage();
                bitmap.UriSource         = FileUtils.GetTempFileUri(fileName);
                _cachedSources[fileName] = new WeakReference(bitmap);

                return(bitmap);
            }

            if (fileSize >= 0)
            {
                var manager = UnigramContainer.Current.ResolveType <IDownloadFileManager>();
                var bitmap  = new BitmapImage();
                _cachedSources[fileName] = new WeakReference(bitmap);

                Execute.BeginOnThreadPool(async() =>
                {
                    await manager.DownloadFileAsync(location, fileSize);
                    Execute.BeginOnUIThread(() =>
                    {
                        bitmap.UriSource = FileUtils.GetTempFileUri(fileName);
                    });
                });

                return(bitmap);
            }

            return(null);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 텔레그램 메세지에 있는 사진 파일 저장.
        /// </summary>
        /// <param name="photoMsg"></param>
        /// <returns></returns>
        string SavePhoto(TeleSharp.TL.TLMessageMediaPhoto photoMsg)
        {
            var            photo     = ((TLPhoto)photoMsg.Photo);
            var            photoSize = photo.Sizes.OfType <TLPhotoSize>().OrderByDescending(m => m.Size).FirstOrDefault();
            TLFileLocation tf        = (TLFileLocation)photoSize.Location;
            string         fileName  = $"{photo.Id}.jpg";
            string         path      = Path.Combine(Directory.GetCurrentDirectory(), fileName);

            try
            {
                var mb            = 1048576;
                var upperLimit    = (int)Math.Pow(2, Math.Ceiling(Math.Log(photoSize.Size, 2))) * 4;
                var limit         = Math.Min(mb, upperLimit);
                var currentOffset = 0;

                using (var fs = File.OpenWrite(path))
                {
                    while (currentOffset < photoSize.Size)
                    {
                        TLFile file = Client.GetFile(new TLInputFileLocation {
                            LocalId = tf.LocalId, Secret = tf.Secret, VolumeId = tf.VolumeId
                        }, limit, currentOffset).ConfigureAwait(false).GetAwaiter().GetResult();
                        fs.Write(file.Bytes, currentOffset, file.Bytes.Length);
                        currentOffset += file.Bytes.Length;
                    }

                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($" getFile (size:{photoSize.Size}) : {ex.Message} \n {ex.StackTrace}");
                return("");
            }

            return(fileName);
        }