private void btnEpub_Click(object sender, EventArgs e)
 {
     using (OpenFileDialog ofd = new OpenFileDialog()
     {
         Filter = "EPUB files|*.epub", ValidateNames = true, Multiselect = false
     })
     {
         if (ofd.ShowDialog() == DialogResult.OK)
         {
             try
             {
                 EpubBook      ebook = EpubReader.ReadBook(ofd.FileName);
                 StringBuilder sb    = new StringBuilder();
                 foreach (EpubChapter chapter in ebook.Chapters)
                 {
                     sb.Append(MainAppForm.PrintChapter(chapter));
                 }
                 rtbxText.Text = sb.ToString();
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
     }
 }
 private static void TestEpubFile(string epubFilePath, Dictionary <string, int> filesByVersion, List <string> filesWithErrors)
 {
     Console.WriteLine($"File: {epubFilePath}");
     Console.WriteLine("-----------------------------------");
     try
     {
         using (EpubBookRef bookRef = EpubReader.OpenBook(epubFilePath))
         {
             string epubVersionString = bookRef.Schema.Package.GetVersionString();
             if (filesByVersion.ContainsKey(epubVersionString))
             {
                 filesByVersion[epubVersionString]++;
             }
             else
             {
                 filesByVersion[epubVersionString] = 1;
             }
             Console.WriteLine($"EPUB version: {epubVersionString}");
             Console.WriteLine($"Total files: {bookRef.Content.AllFiles.Count}, HTML files: {bookRef.Content.Html.Count}," +
                               $" CSS files: {bookRef.Content.Css.Count}, image files: {bookRef.Content.Images.Count}, font files: {bookRef.Content.Fonts.Count}.");
             Console.WriteLine($"Reading order: {bookRef.GetReadingOrder().Count} file(s).");
             Console.WriteLine("Navigation:");
             foreach (EpubNavigationItemRef navigationItemRef in bookRef.GetNavigation())
             {
                 PrintNavigationItem(navigationItemRef, 0);
             }
         }
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception.ToString());
         filesWithErrors.Add(epubFilePath);
     }
     Console.WriteLine();
 }
Exemple #3
0
        public void View(string path, ContextObject context)
        {
            _epubControl          = new EpubViewerControl(context);
            context.ViewerContent = _epubControl;
            Exception exception = null;

            _epubControl.Dispatcher.BeginInvoke(new Action(() =>
            {
                try
                {
                    // Opens a book
                    var epubBook  = EpubReader.OpenBook(path);
                    context.Title = epubBook.Title;
                    _epubControl.SetContent(epubBook);
                    context.IsBusy = false;
                }
                catch (Exception e)
                {
                    exception = e;
                }
            }), DispatcherPriority.Loaded).Wait();

            if (exception != null)
            {
                ExceptionDispatchInfo.Capture(exception).Throw();
            }
        }
Exemple #4
0
        private async void OpenEpubButton_Click(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.ComputerFolder
            };

            picker.FileTypeFilter.Add(".epub");
            var file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                this.fileStream = await file.OpenStreamForReadAsync();

                {
                    epubReader = new EpubReader(fileStream);
                    {
                        if (epubReader.TryRead(out Epub epub))
                        {
                            this.listView.ItemsSource = epub.ReadingFiles;
                        }
                    }
                }
            }
        }
        public static bool FindTextInEpubFile(string fileFullPath, string text, ref CancellationTokenSource cts)
        {
            try
            {
                // Opens a book and reads all of its content into memory
                var epubBook = EpubReader.ReadBook(fileFullPath);

                // Enumerating the whole text content of the book in the order of reading
                foreach (var textContentFile in epubBook.ReadingOrder)
                {
                    if (cts.IsCancellationRequested)
                    {
                        break;
                    }

                    // HTML of current text content file
                    string htmlContent = textContentFile.Content;

                    if (htmlContent.Contains(text))
                    {
                        return(true);
                    }
                }
            }
            catch (Exception)
            {
                return(false);
            }

            return(false);
        }
Exemple #6
0
        public ReadEpubFile(string fileName)
        {
            FileName = fileName;
            epubBook = EpubReader.ReadBook(fileName);
            Title    = epubBook.Title;
            Author   = epubBook.Author;
            var cntList = new List <Content>();

            foreach (var chapter in epubBook.Chapters)
            {
                var cnt = new Content();
                cnt.Title       = chapter.Title;
                cnt.HtmlContent = chapter.HtmlContent;
                var cntSubChapterList = new List <Content>();
                //TODO: more than 2  - recursive
                foreach (var item in chapter.SubChapters)
                {
                    var cntSubChapter = new Content();
                    cntSubChapter.Title       = item.Title;
                    cntSubChapter.HtmlContent = item.HtmlContent;
                    cntSubChapterList.Add(cntSubChapter);
                }
                cntList.Add(cnt);
            }
            content = cntList.ToArray();
        }
Exemple #7
0
        public bool ReadFile(string filePath)
        {
            //getEpubFileName();

            if (File.Exists(filePath))
            {
                _filePath = filePath;
                _fileName = Path.GetFileNameWithoutExtension(_filePath);

                if (!Directory.Exists(_library))
                {
                    Directory.CreateDirectory(_library);
                }
                _tempPath = Path.Combine(_library, _fileName);

                unZipFile();
                Clear();

                epubBook             = EpubReader.ReadBook(_filePath);
                _baseMenuXmlDiretory = epubBook.Schema.ContentDirectoryPath;
                //get menu
                foreach (EpubContentFile epubContent in epubBook.ReadingOrder)
                {
                    _menuItems.Add(GetPath(epubContent.FileName));
                }
                //get table of contents
                getTableContent(epubBook.Navigation);
            }
            else
            {
                return(false);
            }
            return(true);
        }
        public void CanWriteTest()
        {
            var book   = EpubReader.Read(@"Samples/epub-assorted/Inversions - Iain M. Banks.epub");
            var writer = new EpubWriter(book);

            writer.Write(new MemoryStream());
        }
Exemple #9
0
        public void AddBookToLibrary(string bookFilePath)
        {
            int bookId;

            if (settings.Books.Any())
            {
                bookId = settings.Books.Max(bookItem => bookItem.Id) + 1;
            }
            else
            {
                bookId = 1;
            }
            EpubBookRef epubBookRef = EpubReader.OpenBook(bookFilePath);
            Image       coverImage  = epubBookRef.ReadCover();

            if (coverImage != null)
            {
                if (!Directory.Exists(Constants.COVER_IMAGES_FOLDER))
                {
                    Directory.CreateDirectory(Constants.COVER_IMAGES_FOLDER);
                }
                using (Image resizedCoverImage = ResizeCover(coverImage))
                    resizedCoverImage.Save(GetBookCoverImageFilePath(bookId), ImageFormat.Png);
            }
            Book book = new Book
            {
                Id       = bookId,
                FilePath = bookFilePath,
                Title    = epubBookRef.Title,
                HasCover = coverImage != null
            };

            settings.Books.Add(book);
            applicationContext.SaveSettings();
        }
        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();
        }
Exemple #11
0
 public override void Update()
 {
     Thread.Sleep(3000);
     System.Diagnostics.Debug.WriteLine(string.Format("kitap ebook ekleme başlıyor.... ID : {0}", EbookNo));
     try
     {
         string path = string.Format("~/Files/{0}/epub_{0}.epub", EbookNo);
         using (var fs = new FileStream(HostingEnvironment.MapPath(path), FileMode.Open))
         {
             EpubBook epubBook = EpubReader.ReadBook(fs);
             foreach (EpubTextContentFile textContentFile in epubBook.ReadingOrder)
             {
                 // HTML of current text content file
                 string htmlContent = textContentFile.Content;
                 HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();
                 htmlDocument.LoadHtml(htmlContent);
                 // Insert to db
                 using (VBSContext db = new VBSContext())
                 {
                     BookPage bp = new BookPage();
                     bp.BookId      = BookId;
                     bp.HtmlContent = htmlContent;
                     bp.Description = htmlDocument.DocumentNode.InnerText.Replace("\n", "<br/>");
                     db.BookPages.Add(bp);
                     db.SaveChanges();
                 }
             }
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.InnerException.Message);
     }
 }
Exemple #12
0
        public bool ReadFile()
        {
            getEpubFileName();

            if (_filePath != "")
            {
                unZipFile();
                Clear();

                epubBook             = EpubReader.ReadBook(_filePath);
                _baseMenuXmlDiretory = epubBook.Schema.ContentDirectoryPath;
                //get menu
                foreach (EpubContentFile epubContent in epubBook.ReadingOrder)
                {
                    _menuItems.Add(GetPath(epubContent.FileName));
                }
                //get table of contents
                getTableContent(epubBook.Navigation);
            }
            else
            {
                return(false);
            }
            return(true);
        }
Exemple #13
0
        public async void TestBookParsingAsync(string filePath)
        {
            // Create the book and start testing it
            EpubBook book = await EpubReader.ReadBookAsync(filePath);

            TestBook(book);
        }
Exemple #14
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);
        }
Exemple #15
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."));
        }
Exemple #16
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());
        }
Exemple #17
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);
        }
 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;
     }));
 }
Exemple #19
0
        public void LireLesInfo()
        {
            EpubBook epubBook = EpubReader.ReadBook(chemin); // Lis les informations de base d'un fichier EPUB

            auteur = epubBook.Author;
            titre  = epubBook.Title;
            if (epubBook.AuthorList.Count() != 0)
            {
                auteurs = epubBook.AuthorList[0];
            }
            else
            {
                auteurs = "Pas de plusieurs auteurs.";
            }

            byte[] coverImageContent = epubBook.CoverImage;
            if (coverImageContent != null)
            {
                using (MemoryStream memoryStream = new MemoryStream(coverImageContent))
                {
                    picture = Image.FromStream(memoryStream);
                }
            }

            EpubPackage epubPackage = epubBook.Schema.Package;

            if (epubPackage.Metadata.Dates.Count() != 0)
            {
                date = epubPackage.Metadata.Dates[0].Date;
            }

            if (epubPackage.Metadata.Languages.Count() != 0)
            {
                langage = epubPackage.Metadata.Languages[0];
            }

            if (epubPackage.Metadata.Identifiers.Count() != 0)
            {
                isbn = epubPackage.Metadata.Identifiers[0].Identifier;
                //isbn = epubPackage.Metadata.Identifiers[0].Id;
            }

            if (epubPackage.Metadata.Subjects.Count() != 0)
            {
                genre = epubPackage.Metadata.Subjects[0];
            }

            if (epubPackage.Metadata.Publishers.Count() != 0)
            {
                editeur = epubPackage.Metadata.Publishers[0];
            }
            if (epubPackage.Metadata.Rights.Count() != 0)
            {
                droits = epubPackage.Metadata.Rights[0];
            }

            descri = epubPackage.Metadata.Description;
        }
        }     //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
Exemple #21
0
        public static void MyClassInitialize(TestContext testContext)
        {
            if (!Directory.Exists(Utility.RootFolder))
            {
                Directory.CreateDirectory(Utility.RootFolder);
            }

            _mEpubReader = new EpubReader(TestEpubPath, Utility.RootFolder);
        }
        public static void Run(string filePath)
        {
            EpubBook book = EpubReader.ReadBook(filePath);

            foreach (EpubTextContentFile textContentFile in book.ReadingOrder)
            {
                PrintTextContentFile(textContentFile);
            }
        }
Exemple #23
0
        public static void Run(string filePath)
        {
            EpubBook book = EpubReader.ReadBook(filePath);

            foreach (EpubChapter chapter in book.Chapters)
            {
                PrintChapter(chapter);
            }
        }
        public async Task <IActionResult> Upload(UploadBookViewModel m)
        {
            var f     = m.BookFile;
            var fName = m.BookName;
            var user  = await _userManager.GetUserAsync(User);

            var folder = Path.Combine(_env.WebRootPath, "bookRepo", user.NormalizedUserName);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            var filePath = Path.Combine(folder, f.FileName);

            if (f.Length > 0)
            {
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await f.CopyToAsync(fileStream);
                }
            }

            EpubBook epubBook = EpubReader.ReadBook(filePath);

            byte[] coverImageContent = epubBook.CoverImage;
            var    coverPath         = Path.Combine(_env.WebRootPath, "bookCovers", Guid.NewGuid().ToString() + ".jpg");

            if (coverImageContent != null)
            {
                using (MemoryStream coverImageStream = new MemoryStream(coverImageContent))
                {
                    Image coverImage = Image.FromStream(coverImageStream);
                    coverImage = (Image)(new Bitmap(coverImage, new Size(140, 180)));
                    coverImage.Save(coverPath, ImageFormat.Jpeg);
                }
            }
            else
            {
                coverPath = null;
            }

            Book newBook = new Book
            {
                Id                 = Guid.NewGuid(),
                BookName           = fName,
                BookCoverImagePath = coverPath,
                Path               = filePath,
                UploadedDateTime   = DateTime.Now,
                UploadedByUser     = user,
            };

            _context.BookDbSet.Add(newBook);
            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
        /// <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);
        }
        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();
            }
        }
Exemple #27
0
        public static async Task <bool> SetCurentBookContent(string fileName)
        {
            _currentBook = await EpubReader.OpenBookAsync("fileName");

            if (_currentBook != null)
            {
                return(true);
            }
            return(false);
        }
Exemple #28
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());
        }
        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);
        }
        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);
        }