public async Task SetupHelpImages(string name = "HelpScreenShots")
        {
            uiImageFlip.Visibility = Visibility.Visible;
            uiMarkdown.Visibility  = Visibility.Collapsed;

            var  lastIndex           = 0;
            bool userMovedHelpImages = false;

            // Start up the help file display
            var screenShotPath = await FolderMethods.GetScreenShotsFolderAsync(name);

            var helpScreenShot = await FileSystem.Current.GetFolderFromPathAsync(screenShotPath);

            var files = await helpScreenShot.GetFilesAsync();

            foreach (var file in files)
            {
                var filename = file.Name;
                if (filename.ToLower().EndsWith(".png"))
                {
                    var uri = new Uri($"ms-appx:///Assets/HelpScreenShots/{filename}");
                    var bmi = new BitmapImage(uri);
                    ImageList.Add(bmi);
                }
            }

            var period        = TimeSpan.FromSeconds(5.0); // Eyeballing it, 5 seconds is a good speed.
            var periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(async(source) =>
            {
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    if (this.Visibility != Visibility.Visible)
                    {
                        return;
                    }
                    if (uiImageFlip.Visibility != Visibility.Visible)
                    {
                        return;                                               // maybe we're looking at a Markdown file
                    }
                    if (uiImageFlip.SelectedIndex != lastIndex)
                    {
                        userMovedHelpImages = true;
                    }
                    if (!userMovedHelpImages)
                    {
                        // If the user wants to see them, let them!
                        var nextIndex = uiImageFlip.SelectedIndex + 1;
                        if (nextIndex >= ImageList.Count)
                        {
                            nextIndex = 0;
                        }
                        uiImageFlip.SelectedIndex = nextIndex;
                        lastIndex = nextIndex;
                    }
                });
            }, period);
        }
Exemple #2
0
        private async void OnDropFile(object sender, DragEventArgs e)
        {
            if (e.DataView.Contains(StandardDataFormats.StorageItems))
            {
                await FolderMethods.EnsureDownloadFolder();

                var items = await e.DataView.GetStorageItemsAsync();

                var bookdb = BookDataContext.Get();
                await DoOpenFilesAsync(bookdb, items);
            }
        }
Exemple #3
0
        private async void OnReadDownloadedFiles(object sender, RoutedEventArgs e)
        {
            BookDataContext bookdb = BookDataContext.Get();

            // Done in the OnCreateDatabase --> CreateDatabaseAsync methods
            //StorageFolder installationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            //var preinstallFolder = await installationFolder.GetFolderAsync(@"Assets\PreinstalledBooks");
            //await MarkAllDownloadedFiles(bookdb, preinstallFolder);

            var downloadFolder = await FolderMethods.EnsureDownloadFolder();

            await MarkAllDownloadedFiles(bookdb, downloadFolder, true);
        }
        /// <summary>
        /// Called just once when the app is first run to move the read-only zipped database into
        /// the final read/write position.
        /// </summary>
        /// <param name="progressBar"></param>
        /// <returns></returns>
        public static async Task CopyAssetDatabaseIfNeededAsync(UwpRangeConverter progressBar)
        {
            var destinationFolder       = FolderMethods.LocalFolder;
            var destinationFolderFolder = await PCLStorage.FileSystem.Current.GetFolderFromPathAsync(destinationFolder);

            var destinationFolderPath = destinationFolder;
            //var bookdbfullpath = destinationFolder + @"\" + BookDataContext.BookDataDatabaseFilename;
            var exists = await destinationFolderFolder.CheckExistsAsync(BookDataContext.BookDataDatabaseFilename);

            var existingFile = await FolderMethods.GetFileAsync(destinationFolderFolder, BookDataContext.BookDataDatabaseFilename);

            bool copyFileAsNeeded = true; // CHECK: this should always be true when shipping!

            // (It's sometimes set FALSE when debugging the asset code)
            if (exists != ExistenceCheckResult.FileExists && copyFileAsNeeded)
            {
                progressBar.Minimum = 0;
                progressBar.Maximum = 1;
                progressBar.Value   = 0;

                var initialFullPath = FolderMethods.InstallationFolder + @"\" + @"Assets\InitialBookData.Zip";
                var zipfile         = await PCLStorage.FileSystem.Current.GetFileFromPathAsync(initialFullPath);

                System.Diagnostics.Debug.WriteLine($"Moving initial db: to={destinationFolder}");

                // Its a zipped copy; grab the inner file and expand it out!
                // Can't just copy the file: await originalInstalledFile.CopyAsync(destinationFolder, BookDataContext.BookDataDatabaseFilename);

                using (var stream = await zipfile.OpenAsync(PCLStorage.FileAccess.Read))
                {
                    using (var reader = ReaderFactory.Open(stream))
                    {
                        while (reader.MoveToNextEntry())
                        {
                            System.Diagnostics.Debug.WriteLine($"INIT ZIPREAD: {reader.Entry.Key} size {reader.Entry.Size}");

                            progressBar.Maximum = reader.Entry.Size;
                            progressBar.Value   = 0;

                            var filestream = reader.OpenEntryStream();
                            var startfile  = reader.Entry.Key;
                            var finalfile  = startfile;
                            if (finalfile == "InitialBookData.Db")
                            {
                                finalfile = "BookData.Db";
                            }
                            var outfile = await destinationFolderFolder.CreateFileAsync(finalfile, CreationCollisionOption.ReplaceExisting);

                            var outstream = await outfile.OpenAsync(PCLStorage.FileAccess.ReadAndWrite);

                            byte[] buffer    = new byte[1_000_000]; // 1 meg at a time
        public async Task SetupMarkdown(string filename = "HelpeBookReader.md")
        {
            uiImageFlip.Visibility = Visibility.Collapsed;
            uiMarkdown.Visibility  = Visibility.Visible;

            // Start up the help file display
            var helpFolder = await FolderMethods.GetHelpFilesFolderAsync();

            var md = await helpFolder.GetFileAsync(filename);

            var text = await FileIO.ReadTextAsync(md);

            uiMarkdownText.Text = text;

            //TODO: handle images
        }
Exemple #6
0
        private async Task DoOpenFilesAsync(BookDataContext bookdb, IReadOnlyList <IStorageItem> items)
        {
            var downloadFolderFolder = await FolderMethods.EnsureDownloadFolder();

            var downloadFolder = await StorageFolder.GetFolderFromPathAsync(downloadFolderFolder.Path);

            bool isFirst = true;

            foreach (var item in items)
            {
                var storageFile = item as StorageFile;
                if (storageFile.Name.ToLower().EndsWith(".epub"))
                {
                    var newfile = await storageFile.CopyAsync(downloadFolder, storageFile.Name, Windows.Storage.NameCollisionOption.ReplaceExisting);

                    if (newfile == null)
                    {
                        App.Error($"ERROR: unable to copy file....");
                        ;
                    }
                    else
                    {
                        var bookdata = await InsertFileIntoDatabase(bookdb, downloadFolderFolder, storageFile.Name, true);

                        if (bookdata != null && isFirst)
                        {
                            // Only display the first book
                            var nav = Navigator.Get();
                            nav.DisplayBook(Navigator.NavigateControlId.DroppedFile, bookdata);
                            uiTabSet.SelectedItem = uiChapterTab;
                            isFirst = false;
                        }
                    }
                }
            }
        }
Exemple #7
0
        private async Task DownloadBookAsync(BookDataContext bookdb, BookData book, FilenameAndFormatData file)
        {
            Uri uri;
            var fileName = FileWizards.UriWizard.FixupUrl(file.FileName);
            var status   = Uri.TryCreate(fileName, UriKind.Absolute, out uri);

            if (!status)
            {
                var md = new MessageDialog($"Internal error: {fileName} is invalid")
                {
                    Title = "Can't download file",
                };
                await md.ShowAsync();

                return;
            }
            // Uri is e.g. http://www.gutenberg.org/ebooks/14.epub.noimages

            var folder = await FolderMethods.EnsureDownloadFolder();

            var(outfilename, ext) = FileWizards.UriWizard.GetUriFilename(uri);
            var preferredFilename = book.GetBestTitleForFilename() + ext;

            var collisionOption = PCLStorage.CreationCollisionOption.FailIfExists;
            var exists          = await folder.CheckExistsAsync(preferredFilename);

            if (exists == PCLStorage.ExistenceCheckResult.FileExists)
            {
                var md = new ContentDialog()
                {
                    Content             = $"Already downloaded file {preferredFilename}",
                    Title               = "File exists",
                    PrimaryButtonText   = "Skip",
                    SecondaryButtonText = "Delete existing file",
                };
                var command = await md.ShowAsync();

                switch (command)
                {
                case ContentDialogResult.Primary:
                    return;

                case ContentDialogResult.Secondary:
                    collisionOption = PCLStorage.CreationCollisionOption.ReplaceExisting;
                    break;
                }
            }
            PCLStorage.IFile outfile;
            try
            {
                outfile = await folder.CreateFileAsync(preferredFilename, collisionOption);
            }
            catch (Exception ex)
            {
                var md = new MessageDialog($"Already downloaded file {preferredFilename} {ex.Message}")
                {
                    Title = "File already exists",
                };
                await md.ShowAsync();

                return;
            }

            // Just do a quick download....
            try
            {
                EnableDownloadProgressPanel(true);
                uiDownloadButton.Visibility       = Visibility.Collapsed;
                uiCancelDownloadButton.Visibility = Visibility.Visible;
                cts = new CancellationTokenSource();

                ulong totalLength = 0;
                uiDownloadProgress.IsIndeterminate = true;
                uiDownloadProgress.ShowError       = false;
                var getTask = hc.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead);
#if NEVER_EVER_DEFINED
                getTask.Progress += async(response, progress) =>
                {
                    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                                   () =>
                    {
                        if (totalLength == 0 && progress.TotalBytesToReceive.HasValue && progress.TotalBytesToReceive.Value > 0)
                        {
                            // Now we know how many bytes we will get!
                            uiDownloadProgress.IsIndeterminate = false;
                            uiDownloadProgress.Minimum         = 0;
                            uiDownloadProgress.Maximum         = progress.TotalBytesToReceive.Value;
                            uiDownloadProgress.Value           = 0;
                            totalLength = progress.TotalBytesToReceive.Value;
                        }
                        if (progress.BytesReceived > 0)
                        {
                            uiDownloadProgress.Value = progress.BytesReceived;
                        }
                        NotifyUser($"GET Progress: stage {progress.Stage} bytes={progress.BytesReceived} of {progress.TotalBytesToReceive}");
                    });
                };
#endif
                // Get some level of progress....
                var responseMessage     = await getTask;
                var contentLengthHeader = responseMessage.Content.Headers.ContentLength;
                if (totalLength == 0 && contentLengthHeader.HasValue && contentLengthHeader.Value > 0)
                {
                    // Now we know how many bytes we will get!
                    uiDownloadProgress.IsIndeterminate = false;
                    uiDownloadProgress.Minimum         = 0;
                    uiDownloadProgress.Maximum         = contentLengthHeader.Value;
                    uiDownloadProgress.Value           = 0;
                    totalLength = (ulong)contentLengthHeader.Value;
                }
                NotifyUser($"GET Progress: stage Got Headers");


                var stream = await responseMessage.Content.ReadAsStreamAsync(); // gest entire buffer at once.

                byte[]      tbuffer  = new byte[8 * 1024];
                List <byte> buffer   = new List <byte>();
                int         nbytes   = 0;
                int         progress = 0;
                while ((nbytes = await stream.ReadAsync(tbuffer, 0, tbuffer.Length)) > 0)
                {
                    for (int i = 0; i < nbytes; i++)
                    {
                        buffer.Add(tbuffer[i]);
                    }
                    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                                   () =>
                    {
                        progress += nbytes;
                        uiDownloadProgress.Value = progress;
                        NotifyUser($"GET Progress: bytes={progress} of {totalLength}\n");
                    });
                }

                //var buffer = await bufferTask.AsTask(cts.Token);
                uiDownloadProgress.Value = buffer.Count;

                bool isOk = responseMessage.IsSuccessStatusCode;
                if (isOk)
                {
                    NotifyUser($"GET complete with {buffer.Count} bytes");

                    if (buffer.Count > 2000)
                    {
                        uiDownloadFinished.Visibility           = Visibility.Visible;
                        uiDownloadFinishedShowButton.Visibility = Visibility.Collapsed;

                        await outfile.WriteBytesAsync(buffer);

                        CommonQueries.DownloadedBookEnsureFileMarkedAsDownloaded(bookdb, book.BookId, folder.Path, outfile.Name);

                        uiDownloadFinishedShowButton.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        var md = new MessageDialog($"Download file error -- too small")
                        {
                            Title = "Corrupt downloaded file",
                        };
                        await md.ShowAsync();
                    }
                    NotifyUser($"Download complete -- file size {buffer.Count} bytes");
                }
                else
                {
                    NotifyUser($"Failed to download file; error {responseMessage.ReasonPhrase} length {buffer.Count}");
                    uiDownloadFinished.Visibility           = Visibility.Visible;
                    uiDownloadFinishedShowButton.Visibility = Visibility.Collapsed;
                }


                uiDownloadProgress.IsIndeterminate = false;
                uiDownloadProgress.Value           = 0;
                EnableDownloadProgressPanel(false);
            }
            catch (Exception ex)
            {
                NotifyUser($"Unable to download file because {ex.Message}");
                await outfile.DeleteAsync();

                uiDownloadProgress.IsIndeterminate = false;
                uiDownloadProgress.ShowError       = true;
                EnableDownloadProgressPanel(false);
            }
            finally
            {
                uiDownloadButton.Visibility       = Visibility.Visible;
                uiCancelDownloadButton.Visibility = Visibility.Collapsed;
            }
        }