Пример #1
0
        public static async Task <bool> LoadAsync()
        {
            if (Relations?.Count != 0)
            {
                return(true);
            }

            var fileUri = await StorageSource.GetFileUrlAsync(FirebaseStoragePath);

            if (fileUri == null)
            {
                return(false);
            }

            var outputFile = await ApplicationData.Current.LocalFolder.TryGetItemAsync(FileName);

            if (outputFile != null)
            {
                var json = File.ReadAllText(outputFile.Path);
                Relations = JsonConvert.DeserializeObject <List <ResourceRelation> >(json);
            }
            else
            {
                outputFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);

                using (var webClient = new WebClient())
                {
                    var json = webClient.DownloadString(fileUri);
                    Relations = JsonConvert.DeserializeObject <List <ResourceRelation> >(json);
                }
            }


            return(Relations?.Count != 0);
        }
Пример #2
0
        private static async Task <bool> CreateVersionsFromFirebaseStorageAsync(string localJsonSaveFilePath = null)
        {
            Logger.WriteLine("Loading versions from Firebase Storage...");

            var fileUri = await StorageSource.GetFileUrlAsync(FIREBASE_STORAGE_PATH);

            if (fileUri == null)
            {
                throw new FileNotFoundException("File not found.", FIREBASE_STORAGE_PATH);
            }

            using (var webClient = new WebClient())
            {
                var json = webClient.DownloadString(fileUri);
                if (string.IsNullOrWhiteSpace(json))
                {
                    Logger.WriteLine("The local JSON-file is empty. Can't proceed.");
                    return(false);
                }

                Versions = JsonConvert.DeserializeObject <SortedSet <Version> >(json);

                if (!string.IsNullOrEmpty(localJsonSaveFilePath))
                {
                    SaveVersionsToFileAsync(localJsonSaveFilePath);
                }

                return(true);
            }
        }
Пример #3
0
        internal static async Task SaveFirebaseFileToStorageFolder(FirebaseFile file, string firebaseFolder, StorageFolder storageFolder)
        {
            StorageFile sampleFile = await storageFolder.CreateFileAsync(file.FileName, CreationCollisionOption.GenerateUniqueName);

            using (var client = new WebClient())
            {
                var url = await StorageSource.GetFileUrlAsync($"images/{file.FileName}");

                client.DownloadFileAsync(url, sampleFile.Path);
            }
        }
Пример #4
0
        private async void ImageView_Loaded(object sender, RoutedEventArgs e)
        {
            if (File == null)
            {
                ImageView.Visibility = Visibility.Collapsed;
                return;
            }

            ImageView.Visibility = Visibility.Visible;
            var url = await StorageSource.GetFileUrlAsync($"images/{File.FileName}");

            ImageView.Source = new BitmapImage(url);
        }
Пример #5
0
        public static async Task <ImageSource> WebImageToCroppedImage <T>(T image) where T : FirebaseImage, ICroppableImage
        {
            // Convert start point and size to unsigned integer.
            uint startPointX = (uint)image.Crop.X;
            uint startPointY = (uint)image.Crop.Y;
            uint height      = (uint)image.Crop.Height;
            uint width       = (uint)image.Crop.Width;

            var bitmap = new BitmapImage(await StorageSource.GetFileUrlAsync($"images/{image.FileName}"));
            var randomAccessStreamReference = RandomAccessStreamReference.CreateFromUri(bitmap.UriSour‌​ce);

            using (var stream = await randomAccessStreamReference.OpenReadAsync())
            {
                // Create a decoder from the stream. With the decoder, we can get the properties of the image.
                var decoder = await BitmapDecoder.CreateAsync(stream);

                // Create the bitmap bounds
                var bitmapBounds = new BitmapBounds
                {
                    X      = startPointX,
                    Y      = startPointY,
                    Height = height,
                    Width  = width
                };

                // Create cropping BitmapTransform.
                var bitmapTransform = new BitmapTransform
                {
                    Bounds       = bitmapBounds,
                    ScaledWidth  = width,
                    ScaledHeight = height
                };

                // Get the cropped pixels within the bounds of transform.
                PixelDataProvider pixelDataProvider = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Straight,
                    bitmapTransform,
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.ColorManageToSRgb);

                byte[] pixels = pixelDataProvider.DetachPixelData();

                // Stream the bytes into a WriteableBitmap
                WriteableBitmap cropBmp   = new WriteableBitmap((int)width, (int)height);
                Stream          pixStream = cropBmp.PixelBuffer.AsStream();
                pixStream.Write(pixels, 0, (int)(width * height * 4));

                return(cropBmp);
            }
        }
Пример #6
0
        public static async Task DownloadToFile(ResourcePack resourcePack, Action <DownloadOperation> OnRangeDownloadedChange = null)
        {
            var downloader   = new BackgroundDownloader();
            var outputFolder = await GetResourcePacksInstallFolderAsync() ?? KnownFolders.DocumentsLibrary;

            var outputFile = await outputFolder.CreateFileAsync(resourcePack.FileName, CreationCollisionOption.GenerateUniqueName);

            var progressCallback = new Progress <DownloadOperation>(OnRangeDownloadedChange);

            try
            {
                var source = await StorageSource.GetFileUrlAsync($"{RESOURCE_PACKS_FOLDER_NAME}/{resourcePack.FileName}");

                var d = downloader.CreateDownload(source, outputFile);
                d.Priority = BackgroundTransferPriority.Default;

                await d.StartAsync().AsTask(progressCallback);
            }
            catch (Exception exception)
            {
                Logger.WriteLine("Failed to download file.");
                Logger.WriteLine(exception.Message);
            }
        }
Пример #7
0
        public static async Task Convert(ResourcePack resourcePack, string version, bool quiet = false)
        {
            if (resourcePack == null)
            {
                throw new ArgumentNullException(nameof(resourcePack));
            }
            if (string.IsNullOrWhiteSpace(version))
            {
                throw new ArgumentNullException(nameof(version));
            }

            var outputFolder = await StorageUtilities.PickFolderDestination();

            if (outputFolder == null)
            {
                // User decided to cancel. Return.
                return;
            }

            Logger.WriteLine($"Converting {resourcePack.Name} ({resourcePack.Version}) to Minecraft version {version}.");

            var temporaryOutputFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync($"{resourcePack.Name}_converted_temp", CreationCollisionOption.ReplaceExisting);

            var resourceFileUrl = await StorageSource.GetFileUrlAsync($"{RESOURCE_PACKS_FOLDER_NAME}/{resourcePack.FileName}");

            if (resourceFileUrl == null)
            {
                throw new InvalidOperationException("Could not retrieve resource pack file url.");
            }

            var relations = await ResourceRelationService.GetOrCreateAsync();

            if (relations?.Count == 0)
            {
                throw new InvalidOperationException("Retrieved relation set is empty.");
            }

            using (var webClient = new WebClient())
                using (var stream = new MemoryStream(webClient.DownloadData(resourceFileUrl)))
                    using (var archive = new ZipArchive(stream, ZipArchiveMode.Read))
                    {
                        var index = 0;
                        foreach (var entry in archive.Entries.ToList())
                        {
                            var entryPath = entry.FullName.Replace("/", "\\");
                            foreach (var relation in relations)
                            {
                                // Does it contain both versions?
                                if (!(relation.ContainsKey(resourcePack.Version) && relation.ContainsKey(version)))
                                {
                                    continue;
                                }
                                // Does path match?
                                if (!relation[resourcePack.Version].Equals(entryPath))
                                {
                                    continue;
                                }

                                await ExtractZipEntry(temporaryOutputFolder, entry, relation[version]);

                                break;
                            }

                            if (!quiet)
                            {
                                Logger.WriteLine($"{++index} of {archive.Entries.Count} converted.");
                            }
                        }
                    }

            // Move and rename temporary zip file.
            var temporaryMoveFilePAth = Path.Combine(ApplicationData.Current.LocalFolder.Path, $"{resourcePack.Name}_{version}.zip");

            ZipFile.CreateFromDirectory(temporaryOutputFolder.Path, temporaryMoveFilePAth);
            var temporaryMoveFile = await StorageFile.GetFileFromPathAsync(temporaryMoveFilePAth);

            await temporaryMoveFile.MoveAsync(outputFolder, $"{resourcePack.Name}_{version}.zip", NameCollisionOption.GenerateUniqueName);

            // Delete temporary files
            await temporaryOutputFolder.DeleteAsync();
        }