Beispiel #1
0
        private async Task <OpenResult> OpenFileAsText(string fileString, BookLocation location)
        {
            await Task.Delay(0);

            Logger.Log($"MainEpubReader: file is a text string; convert to html");

            EpubBook = TextWizard.TextToEpub(fileString);

            if (location == null)
            {
                var chapter = EpubWizard.GetFirstChapter(EpubBook.TableOfContents);
                if (chapter != null)
                {
                    location = EpubChapterData.FromChapter(chapter);
                }
            }

            if (location != null)
            {
                Logger.Log($"MainEpubReader: Show Text: About to move to location as needed. {location}");
                UserNavigatedToArgument = location;
                NavigateTo(ControlId, location); // We won't get a hairpin navigation callback
            }

            return(OpenResult.OK);
        }
Beispiel #2
0
        private bool NextScrollGoesToNextSection()
        {
            bool sectionIsDone = (CurrScrollPosition >= (BottomScrollPosition - 0.1)) || CurrPageIsMonoPage;
            var  retval        = sectionIsDone && (CurrHtmlIndex < (EpubWizard.NHtmlIndex(EpubBook) - 1));

            return(retval);
        }
Beispiel #3
0
        private void OnWebResourceRequested(WebView sender, WebViewWebResourceRequestedEventArgs args)
        {
            HttpResponseMessage response = null;
            var str = args.Request.RequestUri.OriginalString;

            if (str.StartsWith(FakeHttpPrefix))
            {
                var requestString = str.Replace(FakeHttpPrefix, "");
                // e.g. =@public@vhost@g@gutenberg@html@files@61533@61533-h@[email protected]
                if (true || requestString.Contains("@images"))
                {
                    var requestedFile = EpubWizard.GetInternalFileByName(EpubBook, requestString);
                    if (requestedFile != null)
                    {
                        if (requestString.EndsWith(".css"))
                        {
                            var changed = CssFixup.FixupCss(requestedFile);
                            if (changed)
                            {
                                ;
                            }
                        }
                        if (Logger.LogAllResourceLoads)
                        {
                            Logger.Log($"MainEpubReader:OnWebResourceRequested: FOUND internal asset request {requestString}");
                        }
                        response = new HttpResponseMessage(HttpStatusCode.Ok)
                        {
                            Content = new HttpBufferContent(requestedFile.Content.AsBuffer()),
                        };
                        //response.Content.Headers.ContentType
                    }
                    else
                    {
                        Logger.Log($"MainEpubReader:OnWebResourceRequested: Can't find request {requestString}");
                    }
                }
            }
            else
            {
                // Is a link in the book. Just jump to it via external browser.
                App.Error($"Weird: HTTP is requesting {str}");
                Logger.Log($"MainEpubReader:WebResourceRequested: External URL URL={str}");
            }
            if (response == null)
            {
                response = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    ReasonPhrase = "Cant find embedded resource",
                };
            }
            args.Response = response;
        }
Beispiel #4
0
        private void NavigateToPercent(BookLocation location)
        {
            var navScript = $"scrollToPercent({location.ScrollPercent});\n";

            uiAllUpPosition.UpdatePosition(location.HtmlIndex, location.HtmlPercent);
            if (CurrHtmlIndex == location.HtmlIndex)
            {
                // Great! just scroll to the place!
                Logger.Log($"Main EBOOK: navigate to SAME html");
                var task = uiHtml.InvokeScriptAsync("scrollToPercent", new List <string>()
                {
                    location.ScrollPercent.ToString()
                });
                DoUserNavigateToAsNeeded();
                return;
            }
            else
            {
                if (Logger.LogExtraTiming)
                {
                    Logger.Log($"Main EBOOK: navigate to other html (htmlindex={location.HtmlIndex})");
                }
                var foundIndex = location.HtmlIndex;
                var foundHtml  = EpubWizard.FindHtmlByIndex(EpubBook, foundIndex);
                if (Logger.LogExtraTiming)
                {
                    Logger.Log($"Main EBOOK: navigate to other html {foundIndex}=len {foundHtml?.Length}");
                }

                var html = HtmlFixup.FixupHtmlAll(foundHtml);
                DeferredNavigation = navScript;
                CurrHtml           = html;
                CurrHtmlIndex      = foundIndex;
                CurrHtmlFileName   = location.HtmlFileName;

                Logger.Log($"Main EBOOK: about to navigate with deferred navigation {DeferredNavigation}");
                uiHtml.NavigateToString(html);
            }
            SavePositionEZ();
        }
Beispiel #5
0
        private void DoLaunch(LaunchActivatedEventArgs e = null)
        {
            int nerror = 0;

            Logger.Log($"App:DoLaunch:about to test parser");
            nerror += SearchParserTest.Test_Parser(); // Run some tests
            Logger.Log($"App:DoLaunch:about to test html");
            nerror += EpubWizard.Test_HtmlStringIdIndexOf();
            nerror += BookMarkFile.TestAsValidFilename();

            Logger.Log($"App:DoLaunch:about to add to resources");

            // SLOW: this is 2 seconds of startup
            Application.Current.Resources["UserCustomization"] = Customization;

            Logger.Log($"App:DoLaunch:about to copy initial database");
            var mustCopy     = InitializeFilesToGet.GetMustCopyInitialDatabase();
            var mainPageType = mustCopy ? typeof(MainInitializationPage) : typeof(MainPage);

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                Logger.Log($"App:DoLaunch:about to make frame");
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e != null && e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (e == null || e.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    // When the navigation stack isn't restored navigate to the first page,
                    // configuring the new page by passing required information as a navigation
                    // parameter
                    Logger.Log($"App:DoLaunch:about to navigate");
                    rootFrame.Navigate(mainPageType, e?.Arguments);
                }
                // Ensure the current window is active
                Logger.Log($"App:DoLaunch:about to activate");
                Window.Current.Activate();
                Logger.Log($"App:DoLaunch:done to navigate and activate");
            }

            //if (WarmUpDataBase == null && !mustCopy)
            //{
            //    WarmUpDataBase = CommonQueries.FirstSearchToWarmUpDatabase();
            //}
        }
Beispiel #6
0
 public string GetChapterContainingId(string id, int preferredHtmlIndex)
 {
     return(EpubWizard.GetChapterContainingId(EpubBook, id, preferredHtmlIndex));
 }
Beispiel #7
0
        private void NavigateToLocation(BookLocation location)
        {
            // Gutenberg: just a location which we have to figure out
            // BAEN: HtmlFileName and (for sub-chapters) a Location, too.
            // Location might have just an id in it
            // OR it might have just an HtmlFileName
            // USPS: the location is an XHTML file that's encoded: Additional%20Resources.xhtml instead of Additional Resources.html
            //
            // OR an id+HtmlIndex.
            // We actually don't need the index!

            if (!string.IsNullOrEmpty(location.HtmlFileName))
            {
                // Jump to percent 0.0 after finding the html by name.
                // navScript is either to an id or just to the top
                var navScript = string.IsNullOrEmpty(location.Location) ? $"scrollToPercent(0.0)" : $"scrollToId('{location.Location}')";
                var(foundHtml, foundIndex, foundHtmlFileName) = EpubWizard.FindHtmlContainingHtmlFileName(EpubBook, location.HtmlFileName);
                if (foundHtml == null)
                {
                    App.Error($"ERROR: unable to navigate to htmlFileName={location.HtmlFileName}");
                    return; // nuts; can't find it.
                }

                // If we're jumping to the current spot, meh, don't bother to optimize.
                // Maybe the user wants to do the full amount of code because of "issues"

                var html = HtmlFixup.FixupHtmlAll(foundHtml);
                DeferredNavigation = navScript;
                uiHtml.NavigateToString(html);

                CurrHtml         = html;
                CurrHtmlIndex    = foundIndex;
                CurrHtmlFileName = foundHtmlFileName;

                return;
            }
            else
            {
                string id = location.Location;

                // Find the html with the tag
                // FAIL: BAEN books only navigate by html name. The name will be found in the TOC because there are links!
                // FAIL: Gutenberg John Thorndyke Cases searching for the shoes.png. The long id @public@vhost@g@gutenberg@html@files@13882@13882-h@[email protected]
                // is found in the first HTML but only because that HTML includes a list of illustrations which point to an HTML file that includes the
                // shoes.png file (but that html file has a name that starts with the png but then adds on .wrap-0.html.html.
                // The code here used to just see if the current HTML includes the id at all; the better code checks to make sure it's a proper href.
                if (CurrHtml != null && EpubWizard.HtmlStringIdIndexOf(CurrHtml, id, true) >= 0 && CurrHtml.Contains("scrollToId"))
                {
                    var task = uiHtml.InvokeScriptAsync("scrollToId", new List <string>()
                    {
                        id
                    });
                    DoUserNavigateToAsNeeded();
                    return;
                }

                var idList = EpubWizard.GetIdVariants(id);
                var(foundHtml, foundIndex, foundHtmlFileName, foundId) = EpubWizard.FindHtmlContainingId(EpubBook, idList, location.HtmlIndex);
                if (foundHtml == null)
                {
                    App.Error($"ERROR: unable to navigate to {id}");
                    return; // nuts; can't find it.
                }
                var navScript = $"scrollToId('{foundId}')";
                var html      = HtmlFixup.FixupHtmlAll(foundHtml);
                DeferredNavigation = navScript;
                uiHtml.NavigateToString(html);

                CurrHtml         = html;
                CurrHtmlIndex    = foundIndex;
                CurrHtmlFileName = foundHtmlFileName;
            }
            SavePositionEZ();
        }
Beispiel #8
0
        private async Task <OpenResult> OpenFile(string fullFilePath, BookLocation location)
        {
            OpenResult retval; // default is = OpenResult.OtherError;

            try
            {
                SetScreenToLoading();
                Logger.Log($"MainEpubReader: about to load book {fullFilePath}");
                var fileContents = await FileMethods.ReadBytesAsync(fullFilePath);

                bool isZip = fullFilePath.ToUpperInvariant().EndsWith(".ZIP");
                if (fileContents == null)
                {
                    // Failure of some sort, but just kind of punt it.
                    retval   = OpenResult.RedownloadableError;
                    EpubBook = null;
                    App.Error($"ERROR: book: unable to load file {fullFilePath}");

                    SetScreenToLoading(LoadFailureScreen);
                    var md = new MessageDialog($"Error: book file is missing: {BookData.Title} ")
                    {
                        Title = "Atttempting to re-download book"
                    };
                    await md.ShowAsync();

                    return(retval);
                }

                Logger.Log($"MainEpubReader: read raw array {fileContents.Length}");

                // There's a chance that the file is really a text file, not an epub.
                // Make sure it's at least pre
                bool      isEpub        = false;
                Exception epubException = null;
                try
                {
                    // All epub files start with PK\3\4 (because they are zip files).
                    // If it's not that, then is must be a text or html file.
                    if (EpubWizard.IsEpub(fileContents) && !isZip)
                    {
                        var inner = EpubReader.Read(fileContents);
                        EpubBook = new EpubBookExt(inner);
                        isEpub   = inner != null;
                    }
                }
                catch (Exception ex)
                {
                    isEpub        = false;
                    epubException = ex;
                }

                if (!isEpub)
                {
                    if (isZip)
                    {
                        throw epubException;
                    }

                    try
                    {
                        var fileString = System.Text.Encoding.UTF8.GetString(fileContents);
                        if (!fileString.ToLower().Contains("<html"))
                        {
                            retval = await OpenFileAsText(fileString, location);
                        }
                        else
                        {
                            // We only understand text file and epub, nothing else.
                            throw epubException;
                        }
                    }
                    catch (Exception)
                    {
                        throw; // Meh
                    }
                }
                Logger.Log($"MainEpubReader: read book length {fileContents.Length}");

                SetChapters?.SetChapters(EpubBook, EpubBook.TableOfContents);
                if (SetChapters == null)
                {
                    App.Error($"ISSUE: got new book but SetChapters is null for {fullFilePath}");
                }
                await SetImages?.SetImagesAsync(EpubBook.Resources.Images);

                await SetImages2?.SetImagesAsync(EpubBook.Resources.Images);

                await SetImages3?.SetImagesAsync(EpubBook.Resources.Images);

                if (SetImages == null)
                {
                    App.Error($"ISSUE: got new book but SetImages is null for {fullFilePath}");
                }

                Logger.Log($"MainEpubReader: about to navigate");

                if (location == null)
                {
                    // Old way: go to the first item in table of contents. New way is to go to file=0 percent=0
                    // but only if there's any actual files
                    //var chapter = EpubWizard.GetFirstChapter(EpubBook.TableOfContents);
                    //if (chapter != null)
                    if (EpubBook.ResourcesHtmlOrdered.Count > 0)
                    {
                        location = new BookLocation(0, 0); // often the first item is the cover page which isn't in the table of contents.
                        //location = EpubChapterData.FromChapter(chapter);
                        // // // location = new BookLocation(chapter.Anchor ?? chapter.FileName); // FAIL: BAEN likes to have file-per-chapter
                    }
                }

                if (location != null)
                {
                    if (Logger.LogExtraTiming)
                    {
                        Logger.Log($"MainEpubReader: OpenFile: About to move to location as needed. {location}");
                    }
                    UserNavigatedToArgument = location;
                    NavigateTo(ControlId, location); // We won't get a hairpin navigation callback
                }
                retval = OpenResult.OK;
            }
            catch (Exception ex)
            {
                // Simple error recovery: keep the downloaded data, but report it as
                // no actually downloaded.
                retval   = OpenResult.OtherError;
                EpubBook = null;
                App.Error($"ERROR: book: exception {ex.Message} unable to load file {fullFilePath}");

                SetScreenToLoading(LoadFailureScreen);
                var md = new MessageDialog($"Error: unable to open that book. Internal error {ex.Message}")
                {
                    Title = "Unable to open book"
                };
                await md.ShowAsync();
            }
            return(retval);
        }
Beispiel #9
0
 public EpubFile GetImageByName(string imageName)
 {
     return(EpubWizard.GetInternalFileByName(EpubBook, imageName));
 }
Beispiel #10
0
        private bool HaveNextPage()
        {
            var retval = (CurrScrollPosition <= BottomScrollPosition) || (CurrHtmlIndex < (EpubWizard.NHtmlIndex(EpubBook) - 1));

            return(retval);
        }