Ejemplo n.º 1
0
        public void CanWriteTest()
        {
            var book   = EpubReader.Read(@"Samples/epub-assorted/afrique_du_sud_2016_carnet_petit_fute.epub", null);
            var writer = new EpubWriter(book);

            writer.Write(new MemoryStream());
        }
Ejemplo n.º 2
0
        public void CanWriteTest()
        {
            var book   = EpubReader.Read(@"Samples/epub-assorted/Inversions - Iain M. Banks.epub");
            var writer = new EpubWriter(book);

            writer.Write(new MemoryStream());
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Refresh the selected book
        /// </summary>
        /// <param name="file">the selected book</param>
        /// <returns></returns>
        public async Task RefreshBook(Book file)
        {
            if (!DI.FileManager.PathExists(file.BookFilePath))
            {
                // TODO:
                MessageBox.Show("Not Found");
            }

            // Read an epub file
            EpubBook book = EpubReader.Read(file.BookFilePath);

            file.BookName = book.Title;

            file.IsDisabled = false;

            await DI.ClientDataStore.AddBook(file);

            if (!DI.FileManager.PathExists(file.BookCoverPath))
            {
                file.BookCoverPath = DI.FileManager.ResolvePath($"{CoverPath}{file.Id}.png");

                DI.FileManager.EnsurePathExist(DI.FileManager.ResolvePath(CoverPath));

                if (book.CoverImage != null)
                {
                    File.WriteAllBytes(file.BookCoverPath, book.CoverImage);
                }
                else
                {
                    file.BookCoverPath = string.Empty;
                }
            }

            await DI.ClientDataStore.AddBook(file);
        }
Ejemplo n.º 4
0
        public void EpubAsPlainTextTest2()
        {
            var book = EpubReader.Read(@"Samples/epub-assorted/iOS Hackers Handbook.epub");
            //File.WriteAllText("Samples/epub-assorted/iOS Hackers Handbook.txt", book.ToPlainText());

            Func <string, string> normalize = text => text.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            var expected = File.ReadAllText(@"Samples/epub-assorted/iOS Hackers Handbook.txt");
            var actual   = book.ToPlainText();

            Assert.AreEqual(normalize(expected), normalize(actual));

            var trimmed = string.Join("\n", actual.Split('\n').Select(str => str.Trim()));

            Assert.AreEqual(1, Regex.Matches(trimmed, "Chapter 1\niOS Security Basics").Count);
            Assert.AreEqual(1, Regex.Matches(trimmed, "Chapter 2\niOS in the Enterprise").Count);
            Assert.AreEqual(1, Regex.Matches(trimmed, "Chapter 3\nEncryption").Count);
            Assert.AreEqual(1, Regex.Matches(trimmed, "Chapter 4\nCode Signing and Memory Protections").Count);
            Assert.AreEqual(1, Regex.Matches(trimmed, "Chapter 5\nSandboxing").Count);
            Assert.AreEqual(1, Regex.Matches(trimmed, "Chapter 6\nFuzzing iOS Applications").Count);
            Assert.AreEqual(1, Regex.Matches(trimmed, "Chapter 7\nExploitation").Count);
            Assert.AreEqual(1, Regex.Matches(trimmed, "Chapter 8\nReturn-Oriented Programming").Count);
            Assert.AreEqual(1, Regex.Matches(trimmed, "Chapter 9\nKernel Debugging and Exploitation").Count);
            Assert.AreEqual(1, Regex.Matches(trimmed, "Chapter 10\nJailbreaking").Count);
            Assert.AreEqual(1, Regex.Matches(trimmed, "Chapter 11\nBaseband Attacks").Count);
            Assert.AreEqual(1, Regex.Matches(trimmed, "How This Book Is Organized").Count);
            Assert.AreEqual(2, Regex.Matches(trimmed, "Appendix: Resources").Count);
            Assert.AreEqual(2, Regex.Matches(trimmed, "Case Study: Pwn2Own 2010").Count);
        }
Ejemplo n.º 5
0
        public void EpubAsPlainTextTest1()
        {
            var book = EpubReader.Read(@"Samples/epub-assorted/boothbyg3249432494-8epub.epub");
            //File.WriteAllText("Samples/epub-assorted/boothbyg3249432494-8epub.txt", book.ToPlainText());

            Func <string, string> normalize = text => text.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            var expected = File.ReadAllText(@"Samples/epub-assorted/boothbyg3249432494-8epub.txt");
            var actual   = book.ToPlainText();

            Assert.AreEqual(normalize(expected), normalize(actual));

            var lines = actual.Split('\n').Select(str => str.Trim()).ToList();

            Assert.IsNotNull(lines.SingleOrDefault(e => e == "I. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "II. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "III. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "IV. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "V. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "VI. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "VII. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "VIII. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "IX. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "X. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "XI. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "XII. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "XIII. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "XIV. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "XV. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "XVI. KAPITEL."));
            Assert.IsNotNull(lines.SingleOrDefault(e => e == "XVII. KAPITEL."));
        }
Ejemplo n.º 6
0
        public void SetsChapterPreviousNext()
        {
            var book = EpubReader.Read(Cwd.Combine(@"Samples/epub-assorted/iOS Hackers Handbook.epub"));

            EpubChapter previousChapter = null;
            var         currentChapter  = book.TableOfContents[0];

            currentChapter.Previous.Should().Be(previousChapter);

            for (var i = 1; i <= 77; ++i)
            {
                previousChapter = currentChapter;
                currentChapter  = currentChapter.Next;

                previousChapter.Next.Should().Be(currentChapter);
                currentChapter.Previous.Should().Be(previousChapter);
            }

            EpubChapter nextChapter = null;

            currentChapter.Next.Should().Be(nextChapter);

            for (var i = 1; i <= 77; ++i)
            {
                nextChapter    = currentChapter;
                currentChapter = currentChapter.Previous;

                currentChapter.Next.Should().Be(nextChapter);
                nextChapter.Previous.Should().Be(currentChapter);
            }

            currentChapter.Previous.Should().BeNull();
        }
Ejemplo n.º 7
0
 public async Task <Ebook> OpenBook(string filePath, BookInfo info = null)
 {
     return(await Task.Run(() => {
         var book = EpubReader.Read(_fileService.LoadFileStreamAsync(filePath).Result, false);
         var epub = new EpubEbook(book, filePath, info);
         return epub;
     }));
 }
Ejemplo n.º 8
0
        }     //syncStart end

        /*
         * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
         * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
         * @@@@                              Method                                                                @@@@
         * @@@@****************************ProcessHtmlFiles      ******************************************************@@@@
         * @@@@                                                                                                    @@@@
         * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
         * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
         */
        //------------method geeting ProcessHtmlFiles -----------
        public void ProcessHtmlFiles(string filePath)

        {
            string EpubNummerOnly = Path.GetFileNameWithoutExtension(filePath);
            // Read an epub file
            EpubBook book = EpubReader.Read(filePath);

            try
            {
                ICollection <EpubTextFile> html = book.Resources.Html;
                foreach (var eachFile in html)
                {
                    // HTML of current text content file
                    string htmlContent = eachFile.TextContent;
                    try
                    {
                        XDocument xmlFile = XDocument.Parse(eachFile.TextContent);
                        readContent(xmlFile, EpubNummerOnly, eachFile.FileName);
                    }
                    catch
                    {
                        var ll = htmlContent[0];
                        if (ll != '<')
                        {
                            htmlContent = htmlContent.Remove(0, 1);
                        }
                        try
                        {
                            //string ChangedHtml = DecodeHtmlSymbols(htmlContent);
                            XDocument xmlFile = XDocument.Parse(htmlContent);
                            readContent(xmlFile, EpubNummerOnly, eachFile.FileName);
                        }
                        catch (Exception j)
                        {
                            string error = "\n Error in xml praser  " + EpubNummerOnly + "\t " + eachFile.FileName;
                            Console.WriteLine(error);
                            Program.Global_error = Program.Global_error + error;
                            break;
                        }
                    }
                }    //loop all files end
                //***********saving file*********

                string languageTag = String.Join(" , ", BookLanguagesTag.ToArray());
                FinalReportlist.Add("\n**************Spell Check*************");
                FinalReportlist.Add("Whole File Treated;  Total words in book=  " + BookTotalWords + "\t total Unique words " + UniqueWord_with_language_tag_list.Count + "  languages= " + BookLanguagesTag.Count + " " + languageTag);

                spellCheck(UniqueWord_with_language_tag_list);   // **************call spell check program****************

                Console.WriteLine("Stage 3: Spell Check Completed");
            }// try end
            catch (Exception e)
            {
                string error = "\n Error in ProcessHtmlFiles " + Program.Current_bookPath;
                Console.WriteLine(error + e);
                Program.Global_error = Program.Global_error + error;
            } // catch end
        }     //ProcessFiles
Ejemplo n.º 9
0
        /// <summary>
        /// 打开书籍文件
        /// </summary>
        /// <param name="bookFile">书籍文件</param>
        /// <param name="style">阅读器样式</param>
        /// <param name="chapters">外部导入的目录(通常是前一次生成的目录,以避免重复生成目录),为<c>null</c>或空列表将重新生成目录</param>
        /// <returns></returns>
        public async Task OpenAsync(StorageFile bookFile, ReaderStyle style, List <Chapter> chapters = null)
        {
            if (bookFile == null)
            {
                throw new ArgumentNullException();
            }

            string extension = Path.GetExtension(bookFile.Path).ToLower();

            if (extension != ".epub" && extension != ".txt")
            {
                throw new NotSupportedException("File type not support (Currently only support txt and epub file)");
            }
            OpenStarting?.Invoke(this, EventArgs.Empty);
            if (_tempSpeechStream != null)
            {
                _tempSpeechStream.Dispose();
                _tempSpeechStream = null;
            }
            bool hasExternalChapters = chapters != null && chapters.Count > 0;

            if (hasExternalChapters)
            {
                Chapters = chapters;
                ChapterLoaded?.Invoke(this, Chapters);
            }
            _readerView.ViewStyle = style;
            UpdateBackground(style);
            if (extension.ToLower() == ".txt")
            {
                ReaderType = _readerView.ReaderType = ReaderType.Txt;
                _readerView.SetVirtualMode(true);
                if (!hasExternalChapters)
                {
                    Chapters = await GetTxtChapters(bookFile);

                    ChapterLoaded?.Invoke(this, Chapters);
                }
                _txtContent = await GetTxtContent(bookFile);
            }
            else
            {
                _readerView.SetVirtualMode(false);
                ReaderType   = _readerView.ReaderType = ReaderType.Epub;
                _epubContent = await EpubReader.Read(bookFile, Encoding.Default);

                if (!hasExternalChapters)
                {
                    Chapters = GetEpubChapters(_epubContent);
                    ChapterLoaded?.Invoke(this, Chapters);
                }
                _readerView.EpubInit(_epubContent, style);
            }

            OpenCompleted?.Invoke(this, EventArgs.Empty);
        }
Ejemplo n.º 10
0
        public void SetsChapterParents()
        {
            var book = EpubReader.Read(Cwd.Combine(@"Samples/epub-assorted/iOS Hackers Handbook.epub"));

            foreach (var chapter in book.TableOfContents)
            {
                chapter.Parent.Should().BeNull();
                chapter.SubChapters.All(e => e.Parent == chapter).Should().BeTrue();
            }
        }
Ejemplo n.º 11
0
        public void ClearBogtyvenChaptersTest()
        {
            var writer = new EpubWriter(EpubReader.Read(@"Samples/epub-assorted/bogtyven.epub"));

            writer.ClearChapters();

            var epub = WriteAndRead(writer);

            Assert.AreEqual(0, epub.TableOfContents.Count);
        }
Ejemplo n.º 12
0
        private EpubBook WriteAndRead(EpubWriter writer)
        {
            var stream = new MemoryStream();

            writer.Write(stream);
            stream.Seek(0, SeekOrigin.Begin);
            var epub = EpubReader.Read(stream, false);

            return(epub);
        }
Ejemplo n.º 13
0
        public void ClearBogtyvenChaptersTest()
        {
            var writer = new EpubWriter(EpubReader.Read(@"Samples/epub-assorted/afrique_du_sud_2016_carnet_petit_fute.epub", null));

            writer.ClearChapters();

            var epub = WriteAndRead(writer);

            Assert.AreEqual(0, epub.TableOfContents.EpubChapters.Count());
        }
Ejemplo n.º 14
0
        public void ReadIOSHackersHandbookTest()
        {
            var book = EpubReader.Read(Cwd.Combine(@"Samples/epub-assorted/iOS Hackers Handbook.epub"));

            book.TableOfContents.Should().HaveCount(14);
            book.TableOfContents.SelectMany(e => e.SubChapters).Concat(book.TableOfContents).Should().HaveCount(78);
            book.TableOfContents[0].AbsolutePath.Should().Be("/OEBPS/9781118240755cover.xhtml");
            book.TableOfContents[1].AbsolutePath.Should().Be("/OEBPS/9781118240755c01.xhtml");
            book.TableOfContents[1].SubChapters.Should().HaveCount(6);
            book.TableOfContents[1].SubChapters[0].AbsolutePath.Should().Be("/OEBPS/9781118240755c01.xhtml");
        }
Ejemplo n.º 15
0
        public override BookatHome GetPocoBook(string filepath)
        {
            EpubBook book = EpubReader.Read(filepath);

            if (string.IsNullOrEmpty(book.Title))
            {
                return(base.GetPocoBook(filepath));
            }

            return(new PocoBook(filepath, book.Title, book.Authors.ToArray(), string.Empty, book.Title));
        }
Ejemplo n.º 16
0
        public static void Main(string[] args)
        {
            //var filePath = @"C:\ebooks\afrique_du_sud_2016_carnet_petit_fute.epub";
            //var epubBook = EpubReader.Read(filePath, null);

            var filePath     = @"C:\ebooks\all_in_3_under_the_gun.epub";
            var epubBook     = EpubReader.Read(filePath, null);
            var test         = epubBook.GetTocLinks();
            var prepaginated = epubBook.IsPrePaginated();
            var wordCount    = WordCountService.CountWords(epubBook, filePath, string.Empty);
        }
Ejemplo n.º 17
0
        public override BookAtHome GetPocoBook(string filepath)
        {
            EpubBook book = EpubReader.Read(filepath);

            if (string.IsNullOrEmpty(book.Title))
            {
                return(base.GetPocoBook(filepath));
            }

            return(new PocoBook(filepath, book.Title, new Collection <string>(book.Authors.ToList()), string.Empty, book.Title));
        }
Ejemplo n.º 18
0
        private void ReadWriteTest(List <string> archives)
        {
            foreach (var archive in archives)
            {
                var originalEpub = EpubReader.Read(archive);

                var stream = new MemoryStream();
                EpubWriter.Write(originalEpub, stream);
                stream.Seek(0, SeekOrigin.Begin);
                var savedEpub = EpubReader.Read(stream, false);

                AssertEpub(originalEpub, savedEpub);
            }
        }
Ejemplo n.º 19
0
        public void RemoveCoverTest()
        {
            var epub1 = EpubReader.Read(@"Samples/epub-assorted/Inversions - Iain M. Banks.epub");

            var writer = new EpubWriter(EpubWriter.MakeCopy(epub1));

            writer.RemoveCover();

            var epub2 = WriteAndRead(writer);

            Assert.IsNotNull(epub1.CoverImage);
            Assert.IsNull(epub2.CoverImage);
            Assert.AreEqual(epub1.Resources.Images.Count - 1, epub2.Resources.Images.Count);
        }
Ejemplo n.º 20
0
        public void RemoveCoverTest()
        {
            var epub1 = EpubReader.Read(@"Samples/epub-assorted/afrique_du_sud_2016_carnet_petit_fute.epub", null);

            var writer = new EpubWriter(EpubWriter.MakeCopy(epub1));

            writer.RemoveCover();

            var epub2 = WriteAndRead(writer);

            Assert.IsNotNull(epub1.CoverImage);
            Assert.IsNull(epub2.CoverImage);
            Assert.AreEqual(epub1.Resources.Images.Count - 1, epub2.Resources.Images.Count);
        }
Ejemplo n.º 21
0
        public void Analy()
        {
            var path = @"D:\MyBook\平凡的世界(全三部)2.Epub";

            path = @"D:\MyBook\薛兆丰经济学讲义_-_薛兆丰.epub";
            EpubBook book    = EpubReader.Read(path);
            string   title   = book.Title;
            var      authors = book.Authors;
            var      cover   = book.CoverImage;

            var chapters = book.TableOfContents;

            var html = book.Resources.Html;
        }
Ejemplo n.º 22
0
 static Book2 LoadEpub(string path)
 {
     try
     {
         EpubBook epub = EpubReader.Read(path);
         var      book = new Book2
         {
             Authors = string.Join(", ", epub.Authors.ToArray()),
             Title   = epub.Title,
             Path    = path
         };
         return(book);
     }
     catch
     {
         return(null);
     }
 }
Ejemplo n.º 23
0
    // Use this for initialization
    void Start()
    {
        using (var client = new WebClient())
        {
            //TODO: Next step - allow the user to choose what book to read (input url? search? browse?)
            Stream stream = client.OpenRead("http://www.gutenberg.org/ebooks/135.epub.noimages");
            book = EpubReader.Read(stream, false);
        }

        chapterTexts = new LinkedList <string>();

        foreach (EpubTextFile chapter in book.SpecialResources.HtmlInReadingOrder)
        {
            string newText = chapter.TextContent + '\n';
            newText = Regex.Replace(newText, "<br[^>]*>", "\n");
            newText = Regex.Replace(newText, "<p[^>]*>", "\n");
            newText = Regex.Replace(newText, "</p>", "");

            newText = Regex.Replace(newText, "<h5[^>]*>", "<size=+1>");
            newText = Regex.Replace(newText, "</h5>", "</size>");
            newText = Regex.Replace(newText, "<h4[^>]*>", "<size=+2>");
            newText = Regex.Replace(newText, "</h4>", "</size>");
            newText = Regex.Replace(newText, "<h3[^>]*>", "<size=+3>");
            newText = Regex.Replace(newText, "</h3>", "</size>");
            newText = Regex.Replace(newText, "<h2[^>]*>", "<size=+4>");
            newText = Regex.Replace(newText, "</h2>", "</size>");
            newText = Regex.Replace(newText, "<h1[^>]*>", "<size=+5>");
            newText = Regex.Replace(newText, "</h1>", "</size>");
            newText = Regex.Replace(newText, "<div[^>]*>", "\n");
            newText = Regex.Replace(newText, "</div>", "\n");

            // Replace anything not matched above, or italics/bold/underline, with blank
            newText = Regex.Replace(newText, "</?(((p|size|i|br|u|b)[^ r=>][^>]*)|((?!(p|br|size|i|b|u|/))[^>]*))>", "");

            chapterTexts.AddLast(new LinkedListNode <string>(newText));
        }

        curText = chapterTexts.First;

        pageOne.text = curText.Value;
        pageTwo.text = curText.Value;
    }
Ejemplo n.º 24
0
        private void OpenEpubButton_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "epub file|*.epub"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                this.fileStream?.Dispose();
                this.epubReader?.Dispose();

                var filePath = openFileDialog.FileName;
                fileStream = File.OpenRead(filePath);
                {
                    epubReader = new EpubReader(fileStream);
                    {
                        var epub = epubReader.Read();
                        this.listView.ItemsSource = epub.ReadingFiles;
                    }
                }
            }
        }
Ejemplo n.º 25
0
        private string GetCoverPath()
        {
            Random rnd = new Random();

            EpubSharp.EpubBook book = EpubReader.Read(FullPath);
            if (book.CoverImage != null)
            {
                var    cover     = book.CoverImage;
                Image  image     = ByteArrayToImage(cover);
                string coverName = string.Format("{0} {1}.jpg", Title, Convert.ToString(rnd.Next(50)));
                string coverPath = AppDomain.CurrentDomain.BaseDirectory + "Library\\Covers\\" + coverName;
                image.Save(coverPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                return(coverPath);
            }
            else
            {
                if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Library\\Covers\\defoltCover.jpg"))
                {
                    File.Copy(AppDomain.CurrentDomain.BaseDirectory + "images\\defoltCover.jpg", AppDomain.CurrentDomain.BaseDirectory + "Library\\Covers\\defoltCover.jpg");
                }
                return(AppDomain.CurrentDomain.BaseDirectory + "Library\\Covers\\defoltCover.jpg");
            }
        }
Ejemplo n.º 26
0
        private void ImportEPUB()
        {
            // clear children
            foreach (var slotChild in Slot.Children)
            {
                slotChild.Destroy();
            }

            var filesToImport  = new List <string>();
            var fileAttributes = File.GetAttributes(EBookPath.Value);

            if (fileAttributes.HasFlag(FileAttributes.Directory))
            {
                var files = Directory.GetFiles(EBookPath.Value, "*.epub",
                                               Recursive.Value ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                filesToImport.AddRange(files);
            }
            else
            {
                filesToImport.Add(EBookPath.Value);
            }

            Message("Starting import...");
            //World.AddSlot(this.Slot, "EPUB");
            foreach (var file in filesToImport)
            {
                try
                {
                    if (!File.Exists(file))
                    {
                        Message("File could not be found!");
                        Slot.AddSlot("Error message in tag").Tag = file + " could not be found!";
                        return;
                    }

                    EpubBook book = EpubReader.Read(file);

                    if (book == null)
                    {
                        Message("Book could not be loaded for an unknown reason!");
                        Slot.AddSlot("Error message in tag").Tag = file + " could not not be loaded for an unknown reason!";
                    }

                    var bookSlot = Slot.AddSlot(book.Title);

                    if (AddSimpleAvatarProtection.Value)
                    {
                        var protection = bookSlot.AttachComponent <SimpleAvatarProtection>();
                        protection.User.Target = this.LocalUser;
                    }

                    var grabbable = bookSlot.AttachComponent <Grabbable>();
                    grabbable.Scalable.Value = true;
                    bookSlot.AttachComponent <ObjectRoot>();
                    var license = bookSlot.AttachComponent <License>();
                    license.CreditString.Value = "Imported using the NeosVREBookImporter plugin";
                    bookSlot.Tag = "ebook";

                    var snapper = bookSlot.AttachComponent <Snapper>();
                    snapper.Keywords.Add("ebook");

                    var dynVarsSlot = bookSlot.AddSlot("Dynamic Variables");
                    AttachDynVar(dynVarsSlot, DynVarTitleName, book.Title);
                    AttachDynVar <int>(dynVarsSlot, DynVarCurrentPosition, 0);
                    AttachDynVar <int>(dynVarsSlot, DynVarCurrentChapter, -1);

                    int authorCount = book.Authors.Count();
                    AttachDynVar(dynVarsSlot, DynVarAuthorCountName, authorCount);


                    int i = 0;
                    foreach (var bookAuthor in book.Authors)
                    {
                        AttachDynVar(dynVarsSlot, DynVarAuthorName + i, bookAuthor);
                        i++;
                    }

                    // Add chapters
                    var chaptersSlot = bookSlot.AddSlot("Chapters");
                    var chapterCount = AddChapters(book, chaptersSlot, book.TableOfContents);

                    AttachDynVar(chaptersSlot, DynVarChapterCountName, chapterCount);

                    CreateVisual(bookSlot, book.Title);

                    Message("Yay done!");
                }
                catch (FileNotFoundException e)
                {
                    LogError("EPUB could not be found!", e);
                }
                catch (IOException e)
                {
                    LogError("EPUB could not be read!", e);
                }
                catch (XmlException e)
                {
                    LogError("Error occurred while parsing chapter html!", e);
                }
                catch (Exception e)
                {
                    LogError("An unknown error occurred while importing", e);
                }
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Open the selected book
        /// </summary>
        /// <param name="file">the selected book</param>
        /// <returns></returns>
        public void OpenBook(Book file)
        {
            //await RefreshBook(file);

            Loading = true;

            if (!DI.FileManager.PathExists(file.BookFilePath))
            {
                // TODO:
                MessageBox.Show("Not Found");

                Loading = false;
                return;
            }

            // Read an epub file
            EpubBook book = EpubReader.Read(file.BookFilePath);

            ICollection <EpubTextFile> html = book.Resources.Html;

            var bookVM = new BookViewModel()
            {
                Title = file.BookName,
            };

            var i = 0;

            foreach (EpubTextFile text in html)
            {
                var chapter = book.TableOfContents.FirstOrDefault(tof => tof.FileName == text.FileName);

                if (chapter == null)
                {
                    continue;
                }

                // TODO: out of index
                var pageVM = new PageViewModel()
                {
                    Index = i,
                    Title = chapter.Title
                };

                var j = 0;
                foreach (string paragraph in text.ToParagraphs())
                {
                    var paragraphVM = new ParagraphViewModel()
                    {
                        Index         = j++,
                        ParagraphText = paragraph,
                    };

                    pageVM.AddParagraph(paragraphVM);
                }
                if (pageVM.ParagraphViewModels.Count > 0)
                {
                    bookVM.AddPage(pageVM);
                    i++;
                }
            }

            file.LastOpenDate = DateTime.Now;

            DI.ClientDataStore.AddBook(file);

            ViewModelLocator.ApplicationViewModel.CurrentBook = file;

            ViewModelLocator.ApplicationViewModel.CurrentBookViewModel = bookVM;

            ViewModelLocator.ApplicationViewModel.CurrentBookViewModel.Initialize(file);

            ViewModelLocator.ApplicationViewModel.GoToPage(ApplicationPage.Book);

            Loading = false;
        }
Ejemplo n.º 28
0
        //[Test]
        public void ReadBogtyvenFormatTest()
        {
            var book   = EpubReader.Read(@"Samples/epub-assorted/20140802-demo.epub", null);
            var format = book.Format;

            Assert.IsNotNull(format, nameof(format));

            Assert.IsNotNull(format.Ocf, nameof(format.Ocf));
            Assert.AreEqual(1, format.Ocf.RootFiles.Count);
            Assert.AreEqual("OEBPS/content.opf", format.Ocf.RootFiles.ElementAt(0).FullPath);
            Assert.AreEqual("application/oebps-package+xml", format.Ocf.RootFiles.ElementAt(0).MediaType);
            Assert.AreEqual("OEBPS/content.opf", format.Ocf.RootFilePath, nameof(format.Ocf.RootFilePath));

            Assert.IsNotNull(format.Opf, nameof(format.Opf));
            Assert.AreEqual(EpubVersion.Epub3, format.Opf.EpubVersion);

            /*
             * <guide>
             *  <reference type="cover" href="xhtml/cover.xhtml"/>
             *  <reference type="title-page" href="xhtml/title.xhtml"/>
             *  <reference type="chapter" href="xhtml/prologue.xhtml"/>
             *  <reference type="copyright-page" href="xhtml/copyright.xhtml"/>
             * </guide>
             */
            Assert.IsNotNull(format.Opf.Guide, nameof(format.Opf.Guide));
            Assert.AreEqual(4, format.Opf.Guide.References.Count);

            Assert.AreEqual("xhtml/cover.xhtml", format.Opf.Guide.References.ElementAt(0).Href);
            Assert.AreEqual(null, format.Opf.Guide.References.ElementAt(0).Title);
            Assert.AreEqual("cover", format.Opf.Guide.References.ElementAt(0).Type);

            Assert.AreEqual("xhtml/title.xhtml", format.Opf.Guide.References.ElementAt(1).Href);
            Assert.AreEqual(null, format.Opf.Guide.References.ElementAt(1).Title);
            Assert.AreEqual("title-page", format.Opf.Guide.References.ElementAt(1).Type);

            Assert.AreEqual("xhtml/prologue.xhtml", format.Opf.Guide.References.ElementAt(2).Href);
            Assert.AreEqual(null, format.Opf.Guide.References.ElementAt(2).Title);
            Assert.AreEqual("chapter", format.Opf.Guide.References.ElementAt(2).Type);

            Assert.AreEqual("xhtml/copyright.xhtml", format.Opf.Guide.References.ElementAt(3).Href);
            Assert.AreEqual(null, format.Opf.Guide.References.ElementAt(3).Title);
            Assert.AreEqual("copyright-page", format.Opf.Guide.References.ElementAt(3).Type);

            Assert.IsNotNull(format.Opf.Manifest, nameof(format.Opf.Manifest));
            Assert.AreEqual(150, format.Opf.Manifest.Items.Count);

            // <item id="body097" href="xhtml/chapter_083.xhtml" media-type="application/xhtml+xml" properties="svg"/>
            var item = format.Opf.Manifest.Items.First(e => e.Id == "body097");

            Assert.AreEqual("xhtml/chapter_083.xhtml", item.Href);
            Assert.AreEqual("application/xhtml+xml", item.MediaType);
            Assert.AreEqual(1, item.Properties.Count);
            Assert.AreEqual("svg", item.Properties.ElementAt(0));
            Assert.IsNull(item.Fallback);
            Assert.IsNull(item.FallbackStyle);
            Assert.IsNull(item.RequiredModules);
            Assert.IsNull(item.RequiredNamespace);

            // <item id="css2" href="styles/big.css" media-type="text/css"/>
            item = format.Opf.Manifest.Items.First(e => e.Id == "css2");
            Assert.AreEqual("styles/big.css", item.Href);
            Assert.AreEqual("text/css", item.MediaType);
            Assert.AreEqual(0, item.Properties.Count);
            Assert.IsNull(item.Fallback);
            Assert.IsNull(item.FallbackStyle);
            Assert.IsNull(item.RequiredModules);
            Assert.IsNull(item.RequiredNamespace);

            /*
             * <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
             *  <dc:title>Bogtyven</dc:title>
             *  <dc:creator id="creator_01">Markus Zusak</dc:creator>
             *  <dc:publisher>Lindhardt og Ringhof</dc:publisher>
             *  <dc:rights>All rights reserved Lindhardt og Ringhof Forlag A/S</dc:rights>
             *  <dc:identifier id="ISBN9788711332412">9788711332412</dc:identifier>
             *  <dc:source>urn:isbn:9788711359327</dc:source>
             *  <dc:language>da</dc:language>
             *  <dc:date>2014-04-01</dc:date>
             *  <meta refines="#creator_01" property="role">aut</meta>
             *  <meta refines="#creator_01" property="file-as">Zusak, Markus</meta>
             *  <meta property="dcterms:modified">2014-03-19T02:42:00Z</meta>
             *  <meta property="ibooks:version">1.0.0</meta>
             *  <meta name="cover" content="cover-image"/>
             *  <meta property="rendition:layout">reflowable</meta>
             *  <meta property="ibooks:respect-image-size-class">img_ibooks</meta>
             *  <meta property="ibooks:specified-fonts">true</meta>
             * </metadata>
             */
            Assert.IsNotNull(format.Opf.Metadata);
            Assert.AreEqual(0, format.Opf.Metadata.Contributors.Count);
            Assert.AreEqual(0, format.Opf.Metadata.Coverages.Count);
            Assert.AreEqual(1, format.Opf.Metadata.Creators.Count);
            Assert.AreEqual("Markus Zusak", format.Opf.Metadata.Creators.ElementAt(0).Text);
            Assert.AreEqual(1, format.Opf.Metadata.Dates.Count);
            Assert.AreEqual("2014-04-01", format.Opf.Metadata.Dates.ElementAt(0).Text);
            Assert.AreEqual(0, format.Opf.Metadata.Descriptions.Count);
            Assert.AreEqual(0, format.Opf.Metadata.Formats.Count);

            Assert.AreEqual(1, format.Opf.Metadata.Identifiers.Count);
            Assert.AreEqual("9788711332412", format.Opf.Metadata.Identifiers.ElementAt(0).Text);
            Assert.AreEqual("ISBN9788711332412", format.Opf.Metadata.Identifiers.ElementAt(0).Id);

            Assert.AreEqual(1, format.Opf.Metadata.Languages.Count);
            Assert.AreEqual("da", format.Opf.Metadata.Languages.ElementAt(0));

            Assert.AreEqual(8, format.Opf.Metadata.Metas.Count);
            Assert.IsTrue(format.Opf.Metadata.Metas.All(e => e.Id == null));
            Assert.IsTrue(format.Opf.Metadata.Metas.All(e => e.Scheme == null));

            var meta = format.Opf.Metadata.Metas.Single(e => e.Property == "dcterms:modified");

            Assert.AreEqual("2014-03-19T02:42:00Z", meta.Text);
            Assert.IsNull(meta.Id);
            Assert.IsNull(meta.Name);
            Assert.IsNull(meta.Refines);
            Assert.IsNull(meta.Scheme);

            meta = format.Opf.Metadata.Metas.Single(e => e.Property == "ibooks:version");
            Assert.AreEqual("1.0.0", meta.Text);
            Assert.IsNull(meta.Id);
            Assert.IsNull(meta.Name);
            Assert.IsNull(meta.Refines);
            Assert.IsNull(meta.Scheme);

            meta = format.Opf.Metadata.Metas.Single(e => e.Property == "rendition:layout");
            Assert.AreEqual("reflowable", meta.Text);
            Assert.IsNull(meta.Id);
            Assert.IsNull(meta.Name);
            Assert.IsNull(meta.Refines);
            Assert.IsNull(meta.Scheme);

            meta = format.Opf.Metadata.Metas.Single(e => e.Property == "ibooks:respect-image-size-class");
            Assert.AreEqual("img_ibooks", meta.Text);
            Assert.IsNull(meta.Id);
            Assert.IsNull(meta.Name);
            Assert.IsNull(meta.Refines);
            Assert.IsNull(meta.Scheme);

            meta = format.Opf.Metadata.Metas.Single(e => e.Property == "ibooks:specified-fonts");
            Assert.AreEqual("true", meta.Text);
            Assert.IsNull(meta.Id);
            Assert.IsNull(meta.Name);
            Assert.IsNull(meta.Refines);
            Assert.IsNull(meta.Scheme);

            meta = format.Opf.Metadata.Metas.Single(e => e.Property == "role");
            Assert.AreEqual("aut", meta.Text);
            Assert.AreEqual("#creator_01", meta.Refines);
            Assert.IsNull(meta.Id);
            Assert.IsNull(meta.Name);
            Assert.IsNull(meta.Scheme);

            meta = format.Opf.Metadata.Metas.Single(e => e.Property == "file-as");
            Assert.AreEqual("Zusak, Markus", meta.Text);
            Assert.AreEqual("#creator_01", meta.Refines);
            Assert.IsNull(meta.Id);
            Assert.IsNull(meta.Name);
            Assert.IsNull(meta.Scheme);

            Assert.AreEqual(1, format.Opf.Metadata.Publishers.Count);
            Assert.AreEqual("Lindhardt og Ringhof", format.Opf.Metadata.Publishers.ElementAt(0));

            Assert.AreEqual(0, format.Opf.Metadata.Relations.Count);

            Assert.AreEqual(1, format.Opf.Metadata.Rights.Count);
            Assert.AreEqual("All rights reserved Lindhardt og Ringhof Forlag A/S", format.Opf.Metadata.Rights.ElementAt(0));

            Assert.AreEqual(1, format.Opf.Metadata.Sources.Count);
            Assert.AreEqual("urn:isbn:9788711359327", format.Opf.Metadata.Sources.ElementAt(0));

            Assert.AreEqual(0, format.Opf.Metadata.Subjects.Count);
            Assert.AreEqual(0, format.Opf.Metadata.Types.Count);

            Assert.AreEqual(1, format.Opf.Metadata.Titles.Count);
            Assert.AreEqual("Bogtyven", format.Opf.Metadata.Titles.ElementAt(0));

            Assert.AreEqual("ncx", format.Opf.Spine.Toc);
            Assert.AreEqual(108, format.Opf.Spine.ItemRefs.Count);
            Assert.AreEqual(6, format.Opf.Spine.ItemRefs.Count(e => e.Properties.Contains("page-spread-right")));
            Assert.AreEqual(1, format.Opf.Spine.ItemRefs.Count(e => e.IdRef == "body044_01"));

            Assert.IsNull(format.Ncx.DocAuthor);
            Assert.AreEqual("Bogtyven", format.Ncx.DocTitle);

            /*
             * <head>
             *  <meta name="dtb:uid" content="9788711332412"/>
             *  <meta name="dtb:depth" content="1"/>
             *  <meta name="dtb:totalPageCount" content="568"/>
             * </head>
             */
            Assert.AreEqual(3, format.Ncx.Meta.Count);

            Assert.AreEqual("dtb:uid", format.Ncx.Meta.ElementAt(0).Name);
            Assert.AreEqual("9788711332412", format.Ncx.Meta.ElementAt(0).Content);
            Assert.IsNull(format.Ncx.Meta.ElementAt(0).Scheme);

            Assert.AreEqual("dtb:depth", format.Ncx.Meta.ElementAt(1).Name);
            Assert.AreEqual("1", format.Ncx.Meta.ElementAt(1).Content);
            Assert.IsNull(format.Ncx.Meta.ElementAt(1).Scheme);

            Assert.AreEqual("dtb:totalPageCount", format.Ncx.Meta.ElementAt(2).Name);
            Assert.AreEqual("568", format.Ncx.Meta.ElementAt(2).Content);
            Assert.IsNull(format.Ncx.Meta.ElementAt(2).Scheme);

            Assert.IsNull(format.Ncx.NavList);
            Assert.IsNull(format.Ncx.PageList);

            Assert.IsNotNull(format.Ncx.NavMap);
            Assert.IsNotNull(format.Ncx.NavMap.Dom);
            Assert.AreEqual(111, format.Ncx.NavMap.NavPoints.Count);
            foreach (var point in format.Ncx.NavMap.NavPoints)
            {
                Assert.IsNotNull(point.Id);
                Assert.IsNotNull(point.PlayOrder);
                Assert.IsNotNull(point.ContentSrc);
                Assert.IsNotNull(point.NavLabelText);
                Assert.IsNull(point.Class);
                Assert.IsFalse(point.NavPoints.Any());
            }

            // <navPoint id="navPoint-38" playOrder="38"><navLabel><text>– Rosas vrede</text></navLabel><content src="chapter_032.xhtml"/></navPoint>
            var navPoint = format.Ncx.NavMap.NavPoints.Single(e => e.Id == "navPoint-38");

            Assert.AreEqual(38, navPoint.PlayOrder);
            Assert.AreEqual("– Rosas vrede", navPoint.NavLabelText);
            Assert.AreEqual("chapter_032.xhtml", navPoint.ContentSrc);

            Assert.AreEqual("Bogtyven", format.Nav.Head.Title);

            /*
             *  <link rel="stylesheet" href="../styles/general.css" type="text/css"/>
             *  <link rel="stylesheet" media="(min-width:550px) and (orientation:portrait)" href="../styles/big.css" type="text/css"/>
             */
            Assert.AreEqual(2, format.Nav.Head.Links.Count);

            Assert.AreEqual(null, format.Nav.Head.Links.ElementAt(0).Class);
            Assert.AreEqual(null, format.Nav.Head.Links.ElementAt(0).Title);
            Assert.AreEqual("../styles/general.css", format.Nav.Head.Links.ElementAt(0).Href);
            Assert.AreEqual("stylesheet", format.Nav.Head.Links.ElementAt(0).Rel);
            Assert.AreEqual("text/css", format.Nav.Head.Links.ElementAt(0).Type);
            Assert.AreEqual(null, format.Nav.Head.Links.ElementAt(0).Media);

            Assert.AreEqual(null, format.Nav.Head.Links.ElementAt(1).Class);
            Assert.AreEqual(null, format.Nav.Head.Links.ElementAt(1).Title);
            Assert.AreEqual("../styles/big.css", format.Nav.Head.Links.ElementAt(1).Href);
            Assert.AreEqual("stylesheet", format.Nav.Head.Links.ElementAt(1).Rel);
            Assert.AreEqual("text/css", format.Nav.Head.Links.ElementAt(1).Type);
            Assert.AreEqual("(min-width:550px) and (orientation:portrait)", format.Nav.Head.Links.ElementAt(1).Media);

            Assert.AreEqual(1, format.Nav.Head.Metas.Count);
            Assert.AreEqual("utf-8", format.Nav.Head.Metas.ElementAt(0).Charset);
            Assert.IsNull(format.Nav.Head.Metas.ElementAt(0).Name);
            Assert.IsNull(format.Nav.Head.Metas.ElementAt(0).Content);

            Assert.IsNotNull(format.Nav.Body);

            /*
             * <nav epub:type="toc" id="toc"></nav>
             * <nav epub:type="landmarks" class="hide"></nav>
             * <nav epub:type="page-list" class="hide"></nav>
             */
            Assert.AreEqual(3, format.Nav.Body.Navs.Count);

            Assert.IsNotNull(format.Nav.Body.Navs.ElementAt(0).Dom);
            Assert.AreEqual("toc", format.Nav.Body.Navs.ElementAt(0).Type);
            Assert.AreEqual("toc", format.Nav.Body.Navs.ElementAt(0).Id);
            Assert.IsNull(format.Nav.Body.Navs.ElementAt(0).Class);
            Assert.IsNull(format.Nav.Body.Navs.ElementAt(0).Hidden);

            Assert.IsNotNull(format.Nav.Body.Navs.ElementAt(1).Dom);
            Assert.AreEqual("landmarks", format.Nav.Body.Navs.ElementAt(1).Type);
            Assert.AreEqual("hide", format.Nav.Body.Navs.ElementAt(1).Class);
            Assert.IsNull(format.Nav.Body.Navs.ElementAt(1).Id);
            Assert.IsNull(format.Nav.Body.Navs.ElementAt(1).Hidden);

            Assert.IsNotNull(format.Nav.Body.Navs.ElementAt(2).Dom);
            Assert.AreEqual("page-list", format.Nav.Body.Navs.ElementAt(2).Type);
            Assert.AreEqual("hide", format.Nav.Body.Navs.ElementAt(2).Class);
            Assert.IsNull(format.Nav.Body.Navs.ElementAt(2).Id);
            Assert.IsNull(format.Nav.Body.Navs.ElementAt(2).Hidden);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 打开书籍文件
        /// </summary>
        /// <param name="bookFile">书籍文件</param>
        /// <param name="style">阅读器样式</param>
        /// <returns></returns>
        public async Task OpenAsync(StorageFile bookFile, ReaderStyle style)
        {
            if (bookFile == null)
            {
                throw new ArgumentNullException();
            }

            string extension = Path.GetExtension(bookFile.Path).ToLower();

            if (extension != ".epub" && extension != ".txt")
            {
                throw new NotSupportedException("File type not support (Currently only support txt and epub file)");
            }
            OpenStarting?.Invoke(this, EventArgs.Empty);
            if (extension == ".txt")
            {
                if (!(style is TxtViewStyle))
                {
                    throw new ArgumentException("Open txt file need TxtViewStyle argument");
                }
                ReaderType = Enums.ReaderType.Txt;
                Chapters   = await GetTxtChapters(bookFile);

                ChapterLoaded?.Invoke(this, Chapters);
                if (_mainPresenter.Content == null || !(_mainPresenter.Content is TxtView))
                {
                    if (_txtView == null)
                    {
                        _txtView = new TxtView();
                        _txtView.PrevPageSelected     += OnPrevPageSelected;
                        _txtView.NextPageSelected     += OnNextPageSelected;
                        _txtView.LoadingStatusChanged += OnLoad;
                        _txtView.ProgressChanged      += OnProgressChanged;
                        _txtView.TouchHolding         += OnTouchHolding;
                        _txtView.TouchTapped          += (_s, _e) => { TouchTapped?.Invoke(_s, _e); };
                        _txtView.Loaded += (_s, _e) =>
                        {
                            _txtView.SingleColumnMaxWidth = SingleColumnMaxWidth;
                            _txtView.ReaderFlyout         = ReaderFlyout;
                            ViewLoaded?.Invoke(this, EventArgs.Empty);
                        };
                    }
                    _mainPresenter.Content = _txtView;
                }
                _txtContent = await GetTxtContent(bookFile);

                _txtView.ViewStyle = style as TxtViewStyle;
            }
            else
            {
                if (!(style is EpubViewStyle))
                {
                    throw new ArgumentException("Open epub file need EpubViewStyle argument");
                }
                ReaderType   = Enums.ReaderType.Epub;
                _epubContent = await EpubReader.Read(bookFile, Encoding.Default);

                Chapters = GetEpubChapters(_epubContent);
                ChapterLoaded?.Invoke(this, Chapters);
                if (_mainPresenter.Content == null || !(_mainPresenter.Content is EpubView))
                {
                    if (_epubView == null)
                    {
                        _epubView = new EpubView();
                        _epubView.PrevPageSelected     += OnPrevPageSelected;
                        _epubView.NextPageSelected     += OnNextPageSelected;
                        _epubView.LoadingStatusChanged += OnLoad;
                        _epubView.ProgressChanged      += OnProgressChanged;
                        _epubView.TouchHolding         += OnTouchHolding;
                        _epubView.TouchTapped          += (_s, _e) => { TouchTapped?.Invoke(_s, _e); };
                        _epubView.Loaded += (_s, _e) =>
                        {
                            _epubView.SingleColumnMaxWidth = SingleColumnMaxWidth;
                            _epubView.ReaderFlyout         = ReaderFlyout;
                            ViewLoaded?.Invoke(this, EventArgs.Empty);
                        };
                        _epubView.LinkTapped  += (_s, _e) => { LinkTapped?.Invoke(this, _e); };
                        _epubView.ImageTapped += (_s, _e) => { ImageTapped?.Invoke(this, _e); };
                    }

                    _mainPresenter.Content = _epubView;
                }
                _epubView.Init(_epubContent, style as EpubViewStyle);
            }
            OpenCompleted?.Invoke(this, EventArgs.Empty);
        }
Ejemplo n.º 30
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);
        }