Пример #1
0
        public static List <EpubTextContentFileRef> GetReadingOrder(EpubBookRef bookRef)
        {
            List <EpubTextContentFileRef> result = new List <EpubTextContentFileRef>();

            foreach (EpubSpineItemRef spineItemRef in bookRef.Schema.Package.Spine)
            {
                EpubManifestItem manifestItem = bookRef.Schema.Package.Manifest.FirstOrDefault(item => item.Id == spineItemRef.IdRef);
                if (manifestItem == null)
                {
                    throw new Exception($"Incorrect EPUB spine: item with IdRef = \"{spineItemRef.IdRef}\" is missing in the manifest.");
                }
                if (bookRef.Content.Html.TryGetValue(manifestItem.Href, out EpubTextContentFileRef htmlContentFileRef))
                {
                    result.Add(htmlContentFileRef);
                    continue;
                }

                // 2019-08-21 Fix: some ebooks seem to contain two items with id="cover", one of them is an image, and the other an XHTML file
                // thus, if the first attempt to get the HTML item fails, we try for a second item with the same Id
                manifestItem = bookRef.Schema.Package.Manifest.Where(item => item.Id == spineItemRef.IdRef).Skip(1).FirstOrDefault();
                if (manifestItem == null)
                {
                    throw new Exception($"Incorrect EPUB spine: item with IdRef = \"{spineItemRef.IdRef}\" is not HTML content");
                }
                if (bookRef.Content.Html.TryGetValue(manifestItem.Href, out EpubTextContentFileRef htmlContentFileRef2))
                {
                    result.Add(htmlContentFileRef2);
                    continue;
                }
                throw new Exception($"Incorrect EPUB manifest: item with href = \"{spineItemRef.IdRef}\" is missing in the book.");
            }
            return(result);
        }
Пример #2
0
        private static List <EpubNavigationItemRef> GetNavigationItems(EpubBookRef bookRef, Epub3NavOl epub3NavOl)
        {
            List <EpubNavigationItemRef> result = new List <EpubNavigationItemRef>();

            if (epub3NavOl != null && epub3NavOl.Lis != null)
            {
                foreach (Epub3NavLi epub3NavLi in epub3NavOl.Lis)
                {
                    if (epub3NavLi != null && (epub3NavLi.Anchor != null || epub3NavLi.Span != null))
                    {
                        if (epub3NavLi.Anchor != null)
                        {
                            Epub3NavAnchor        navAnchor         = epub3NavLi.Anchor;
                            EpubNavigationItemRef navigationItemRef = EpubNavigationItemRef.CreateAsLink();
                            navigationItemRef.Title = GetFirstNonEmptyHeader(navAnchor.Text, navAnchor.Title, navAnchor.Alt);
                            navigationItemRef.Link  = new EpubNavigationItemLink(navAnchor.Href);
                            navigationItemRef.HtmlContentFileRef = GetHtmlContentFileRef(bookRef, navigationItemRef.Link.ContentFileName);
                            navigationItemRef.NestedItems        = GetNavigationItems(bookRef, epub3NavLi.ChildOl);
                            result.Add(navigationItemRef);
                        }
                        else if (epub3NavLi.Span != null)
                        {
                            Epub3NavSpan          navSpan           = epub3NavLi.Span;
                            EpubNavigationItemRef navigationItemRef = EpubNavigationItemRef.CreateAsHeader();
                            navigationItemRef.Title       = GetFirstNonEmptyHeader(navSpan.Text, navSpan.Title, navSpan.Alt);
                            navigationItemRef.NestedItems = GetNavigationItems(bookRef, epub3NavLi.ChildOl);
                            result.Add(navigationItemRef);
                        }
                    }
                }
            }
            return(result);
        }
Пример #3
0
 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();
 }
Пример #4
0
        public static List <EpubChapterRef> GetChapters(EpubBookRef bookRef, List <EpubNavigationPoint> navigationPoints)
        {
            List <EpubChapterRef> result = new List <EpubChapterRef>();

            foreach (EpubNavigationPoint navigationPoint in navigationPoints)
            {
                string contentFileName;
                string anchor;
                int    contentSourceAnchorCharIndex = navigationPoint.Content.Source.IndexOf('#');
                if (contentSourceAnchorCharIndex == -1)
                {
                    contentFileName = navigationPoint.Content.Source;
                    anchor          = null;
                }
                else
                {
                    contentFileName = navigationPoint.Content.Source.Substring(0, contentSourceAnchorCharIndex);
                    anchor          = navigationPoint.Content.Source.Substring(contentSourceAnchorCharIndex + 1);
                }
                EpubTextContentFileRef htmlContentFileRef;
                if (!bookRef.Content.Html.TryGetValue(contentFileName, out htmlContentFileRef))
                {
                    throw new Exception(String.Format("Incorrect EPUB manifest: item with href = \"{0}\" is missing.", contentFileName));
                }
                EpubChapterRef chapterRef = new EpubChapterRef(htmlContentFileRef);
                chapterRef.ContentFileName = contentFileName;
                chapterRef.Anchor          = anchor;
                chapterRef.Title           = navigationPoint.NavigationLabels.First().Text;
                chapterRef.SubChapters     = GetChapters(bookRef, navigationPoint.ChildNavigationPoints);
                result.Add(chapterRef);
            }
            return(result);
        }
Пример #5
0
        public static List <EpubNavigationItemRef> GetNavigationItems(EpubBookRef bookRef)
        {
            if (bookRef.Schema.Package.EpubVersion == EpubVersion.EPUB_2)
            {
                if (null != bookRef.Schema.Epub2Ncx)
                {
                    return(GetNavigationItems(bookRef, bookRef.Schema.Epub2Ncx));
                }
                else
                {
                    return(new List <EpubNavigationItemRef>()); // if Ncx is missing, return an empty list
                }
            }
            else
            {
                if (bookRef.Schema.Epub3NavDocument != null)
                {
                    return(GetNavigationItems(bookRef, bookRef.Schema.Epub3NavDocument));
                }

                // otherwise fallback to Epub2Ncx
                if (null != bookRef.Schema.Epub2Ncx)
                {
                    return(GetNavigationItems(bookRef, bookRef.Schema.Epub2Ncx));
                }
                else
                {
                    return(new List <EpubNavigationItemRef>()); // if Ncx is missing, return an empty list
                }
            }
        }
Пример #6
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();
        }
Пример #7
0
        public static async Task <byte[]> ReadBookCoverAsync(EpubBookRef bookRef)
        {
            List <EpubMetadataMeta> metaItems = bookRef.Schema.Package.Metadata.MetaItems;

            if (metaItems == null || !metaItems.Any())
            {
                return(null);
            }
            EpubMetadataMeta coverMetaItem = metaItems.FirstOrDefault(metaItem => String.Compare(metaItem.Name, "cover", StringComparison.OrdinalIgnoreCase) == 0);

            if (coverMetaItem == null)
            {
                return(null);
            }
            if (String.IsNullOrEmpty(coverMetaItem.Content))
            {
                throw new Exception("Incorrect EPUB metadata: cover item content is missing.");
            }
            EpubManifestItem coverManifestItem = bookRef.Schema.Package.Manifest.FirstOrDefault(manifestItem => String.Compare(manifestItem.Id, coverMetaItem.Content, StringComparison.OrdinalIgnoreCase) == 0);

            if (coverManifestItem == null)
            {
                throw new Exception(String.Format("Incorrect EPUB manifest: item with ID = \"{0}\" is missing.", coverMetaItem.Content));
            }
            if (!bookRef.Content.Images.TryGetValue(coverManifestItem.Href, out EpubByteContentFileRef coverImageContentFileRef))
            {
                throw new Exception(String.Format("Incorrect EPUB manifest: item with href = \"{0}\" is missing.", coverManifestItem.Href));
            }
            byte[] coverImageContent = await coverImageContentFileRef.ReadContentAsBytesAsync().ConfigureAwait(false);

            return(coverImageContent);
        }
Пример #8
0
        private static List <EpubNavigationItemRef> GetNavigationItems(EpubBookRef bookRef, Epub3Nav epub3Nav)
        {
            List <EpubNavigationItemRef> result;

            if (epub3Nav != null)
            {
                if (epub3Nav.Head != null)
                {
                    result = new List <EpubNavigationItemRef>();
                    EpubNavigationItemRef navigationItemRef = EpubNavigationItemRef.CreateAsHeader();
                    navigationItemRef.Title       = epub3Nav.Head;
                    navigationItemRef.NestedItems = GetNavigationItems(bookRef, epub3Nav.Ol);
                    result.Add(navigationItemRef);
                }
                else
                {
                    result = GetNavigationItems(bookRef, epub3Nav.Ol);
                }
            }
            else
            {
                result = new List <EpubNavigationItemRef>();
            }
            return(result);
        }
Пример #9
0
 internal void SetContent(EpubBookRef epubBook)
 {
     _epubBook          = epubBook;
     _chapterRefs       = Flatten(epubBook.GetChapters());
     _currChapter       = -1;
     pagePanel.EpubBook = epubBook;
     UpdateChapter();
 }
Пример #10
0
 public static List <EpubNavigationItemRef> GetNavigationItems(EpubBookRef bookRef)
 {
     if (bookRef.Schema.Package.EpubVersion == EpubVersion.EPUB_2)
     {
         return(GetNavigationItems(bookRef, bookRef.Schema.Epub2Ncx));
     }
     else
     {
         return(GetNavigationItems(bookRef, bookRef.Schema.Epub3NavDocument));
     }
 }
Пример #11
0
 private static EpubTextContentFileRef GetHtmlContentFileRef(EpubBookRef bookRef, string contentFileName)
 {
     if (contentFileName == null)
     {
         return(null);
     }
     if (!bookRef.Content.Html.TryGetValue(contentFileName, out EpubTextContentFileRef htmlContentFileRef))
     {
         return(null);
     }
     return(htmlContentFileRef);
 }
Пример #12
0
 public static void Run(string filePath)
 {
     using (EpubBookRef bookRef = EpubReader.OpenBook(filePath))
     {
         Console.WriteLine("Navigation:");
         foreach (EpubNavigationItemRef navigationItemRef in bookRef.GetNavigation())
         {
             PrintNavigationItem(navigationItemRef, 0);
         }
     }
     Console.WriteLine();
 }
Пример #13
0
        /// <summary>
        ///     Opens the book asynchronously without reading its content. Holds the handle to the EPUB file.
        /// </summary>
        /// <param name="stream">Stream of file to be parsed</param>
        /// <returns></returns>
        private static async Task <EpubBookRef> OpenBookAsync(Stream stream)
        {
            var epubArchive = new ZipArchive(stream);
            var bookRef     = new EpubBookRef(epubArchive)
            {
                Schema = await SchemaReader.ReadSchemaAsync(epubArchive).ConfigureAwait(false)
            };

            bookRef.Title      = bookRef.Schema.Package.Metadata.Titles.FirstOrDefault() ?? string.Empty;
            bookRef.AuthorList = bookRef.Schema.Package.Metadata.Creators.Select(creator => creator.Creator).ToList();
            bookRef.Content    = ContentReader.ParseContentMap(bookRef);
            return(bookRef);
        }
Пример #14
0
        private static List <EpubChapterRef> GetChapters(EpubBookRef bookRef, IEnumerable <EpubNavigationPoint> navigationPoints)
        {
            var result = new List <EpubChapterRef>();

            foreach (var navigationPoint in navigationPoints)
            {
                string contentFileName;
                string anchor;
                var    contentSourceAnchorCharIndex = navigationPoint.Content.Source.IndexOf('#');
                if (contentSourceAnchorCharIndex is - 1)
                {
                    contentFileName = navigationPoint.Content.Source;
                    anchor          = null;
                }
        public static string Run(string filePath)
        {
            StringBuilder result = new StringBuilder();

            using (EpubBookRef bookRef = EpubReader.OpenBook(filePath))
            {
                result.AppendLine("Navigation:");
                foreach (EpubNavigationItemRef navigationItemRef in bookRef.GetNavigation())
                {
                    result.Append(PrintNavigationItem(navigationItemRef, 0));
                }
            }
            result.AppendLine();
            return(result.ToString());
        }
        public static async Task <Image> ReadBookCoverAsync(EpubBookRef bookRef)
        {
            List <EpubMetadataMeta> metaItems = bookRef.Schema.Package.Metadata.MetaItems;

            if (metaItems == null || !metaItems.Any())
            {
                return(null);
            }

            EpubMetadataMeta coverMetaItem = metaItems.FirstOrDefault(metaItem => string.Compare(metaItem.Name, "cover", StringComparison.OrdinalIgnoreCase) == 0);

            if (coverMetaItem == null)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(coverMetaItem.Content))
            {
                throw new Exception("Incorrect EPUB metadata: cover item content is missing.");
            }

            EpubManifestItem coverManifestItem = bookRef.Schema.Package.Manifest.FirstOrDefault(manifestItem => String.Compare(manifestItem.Id, coverMetaItem.Content, StringComparison.OrdinalIgnoreCase) == 0);

            if (coverManifestItem == null)
            {
                throw new Exception(string.Format(CultureInfo.InvariantCulture, "Incorrect EPUB manifest: item with ID = \"{0}\" is missing.", coverMetaItem.Content));
            }

            EpubByteContentFileRef coverImageContentFileRef;

            if (!bookRef.Content.Images.TryGetValue(coverManifestItem.Href, out coverImageContentFileRef))
            {
                throw new Exception(string.Format(CultureInfo.InvariantCulture, "Incorrect EPUB manifest: item with href = \"{0}\" is missing.", coverManifestItem.Href));
            }

            byte[] coverImageContent = await coverImageContentFileRef.ReadContentAsBytesAsync().ConfigureAwait(false);

            using (MemoryStream coverImageStream = new MemoryStream(coverImageContent))
            {
                Image image = new Image();
                //return await Task.Run(() => Image.FromStream(coverImageStream)).ConfigureAwait(false);
                Func <Stream> stream = () => coverImageStream;
                image.Source = ImageSource.FromStream(stream);
                return(await Task.Run(() => image).ConfigureAwait(false));
            }
        }
Пример #17
0
        private static List <EpubNavigationItemRef> GetNavigationItems(EpubBookRef bookRef, List <Epub2NcxNavigationPoint> navigationPoints)
        {
            List <EpubNavigationItemRef> result = new List <EpubNavigationItemRef>();

            if (navigationPoints != null)
            {
                foreach (Epub2NcxNavigationPoint navigationPoint in navigationPoints)
                {
                    EpubNavigationItemRef navigationItemRef = EpubNavigationItemRef.CreateAsLink();
                    navigationItemRef.Title = navigationPoint.NavigationLabels.First().Text;
                    navigationItemRef.Link  = new EpubNavigationItemLink(navigationPoint.Content.Source);
                    navigationItemRef.HtmlContentFileRef = GetHtmlContentFileRef(bookRef, navigationItemRef.Link.ContentFileName);
                    navigationItemRef.NestedItems        = GetNavigationItems(bookRef, navigationPoint.ChildNavigationPoints);
                    result.Add(navigationItemRef);
                }
            }
            return(result);
        }
Пример #18
0
        public static List <EpubTextContentFileRef> GetReadingOrder(EpubBookRef bookRef)
        {
            List <EpubTextContentFileRef> result = new List <EpubTextContentFileRef>();

            foreach (EpubSpineItemRef spineItemRef in bookRef.Schema.Package.Spine)
            {
                EpubManifestItem manifestItem = bookRef.Schema.Package.Manifest.FirstOrDefault(item => item.Id == spineItemRef.IdRef);
                if (manifestItem == null)
                {
                    throw new Exception($"Incorrect EPUB spine: item with IdRef = \"{spineItemRef.IdRef}\" is missing in the manifest.");
                }
                if (!bookRef.Content.Html.TryGetValue(manifestItem.Href, out EpubTextContentFileRef htmlContentFileRef))
                {
                    throw new Exception($"Incorrect EPUB manifest: item with href = \"{spineItemRef.IdRef}\" is missing in the book.");
                }
                result.Add(htmlContentFileRef);
            }
            return(result);
        }
Пример #19
0
        /// <summary>
        /// Opens the book asynchronously and reads all of its content into the memory. Does not hold the handle to the EPUB file.
        /// </summary>
        /// <param name="filePath">path to the EPUB file</param>
        /// <returns></returns>
        public static async Task <EpubBook> ReadBookAsync(string filePath)
        {
            EpubBook result = new EpubBook();

            using (EpubBookRef epubBookRef = await OpenBookAsync(filePath).ConfigureAwait(false))
            {
                result.FilePath   = epubBookRef.FilePath;
                result.Schema     = epubBookRef.Schema;
                result.Title      = epubBookRef.Title;
                result.AuthorList = epubBookRef.AuthorList;
                result.Author     = epubBookRef.Author;
                result.Content    = await ReadContent(epubBookRef.Content).ConfigureAwait(false);

                result.CoverImage = await epubBookRef.ReadCoverAsync().ConfigureAwait(false);

                List <EpubChapterRef> chapterRefs = await epubBookRef.GetChaptersAsync().ConfigureAwait(false);

                result.Chapters = await ReadChapters(chapterRefs).ConfigureAwait(false);
            }
            return(result);
        }
Пример #20
0
        public static List <EpubChapterRef> GetChapters(EpubBookRef bookRef, EpubSpine spine,
                                                        List <EpubNavigationPoint> navigationPoints)
        {
            var result = new List <EpubChapterRef>();

            for (var s = 0; s < spine.Count; s++)
            {
                var    itemRef = spine[s];
                string contentFileName;
                string anchor;
                contentFileName = WebUtility.UrlDecode(bookRef.Schema.Package.Manifest
                                                       .FirstOrDefault(e => e.Id == itemRef.IdRef)?.Href);
                anchor = null;
                if (!bookRef.Content.Html.TryGetValue(contentFileName, out var htmlContentFileRef))
                {
                    throw new Exception(string.Format("Incorrect EPUB manifest: item with href = \"{0}\" is missing.",
                                                      contentFileName));
                }
                var chapterRef = new EpubChapterRef(htmlContentFileRef);
                chapterRef.ContentFileName = contentFileName;
                chapterRef.Anchor          = anchor;
                chapterRef.Parent          = null;
                var navPoint = navigationPoints.LastOrDefault(nav =>
                                                              spine.Take(s + 1)
                                                              .Select(sp => bookRef.Schema.Package.Manifest.FirstOrDefault(e => e.Id == sp.IdRef)?.Href)
                                                              .Contains(nav.Content.Source.Split('#')[0]));
                if (navPoint != null)
                {
                    chapterRef.Title = navPoint.NavigationLabels.First().Text;
                }
                else
                {
                    chapterRef.Title = $"Chapter {s + 1}";
                }
                chapterRef.SubChapters = new List <EpubChapterRef>();
                result.Add(chapterRef);
            }

            return(result);
        }
Пример #21
0
        /// <summary>
        /// Opens the book asynchronously without reading its content. Holds the handle to the EPUB file.
        /// </summary>
        /// <param name="filePath">path to the EPUB file</param>
        /// <returns></returns>
        public static async Task <EpubBookRef> OpenBookAsync(string filePath)
        {
            IFiler   filer   = DependencyService.Get <IFiler>();
            IZipFile zipFile = DependencyService.Get <IZipFile>();

            if (!await filer.DoesFileExistAsync(filePath).ConfigureAwait(false))
            {
                throw new FileNotFoundException("Specified epub file not found.", filePath);
            }

            IZipArchive epubArchive = await zipFile.OpenReadAsync(filePath).ConfigureAwait(false);

            EpubBookRef bookRef = new EpubBookRef(epubArchive);

            bookRef.FilePath = filePath;
            bookRef.Schema   = await SchemaReader.ReadSchemaAsync(epubArchive).ConfigureAwait(false);

            bookRef.Title      = bookRef.Schema.Package.Metadata.Titles.FirstOrDefault() ?? String.Empty;
            bookRef.AuthorList = bookRef.Schema.Package.Metadata.Creators.Select(creator => creator.Creator).ToList();
            bookRef.Author     = string.Join(", ", bookRef.AuthorList);
            bookRef.Content    = await Task.Run(() => ContentReader.ParseContentMap(bookRef)).ConfigureAwait(false);

            return(bookRef);
        }
Пример #22
0
        /// <summary>
        /// Display the whole XHTML file (actually just the body innerhtml). This is generally needed to display the whole chapter/book if hyperlinks link to a targets in another chapter - in this case we display the whole book (if the whole book is in one xhtml file)
        /// </summary>
        /// <param name="ePubDisplayModel"></param>
        /// <param name="epubBookRef"></param>
        public void FindAndProcessXHTML(ref EpubDisplayModel ePubDisplayModel, EpubBookRef epubBookRef)
        {
            // build TOC
            foreach (var item in epubBookRef.GetNavigation())//.GetChapters())
            {
                ePubDisplayModel.TOC_Items.Add(new EpubLink()
                {
                    LinkTitle = item.Title
                });                                                                        // add TOC to display model
            }

            var foundContent = epubBookRef.Content.Html.Where(x => x.Key.EndsWith(_processAction, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

            if (!string.IsNullOrEmpty(foundContent.Key))
            {
                var foundHtml = foundContent.Value.ReadContentAsText();

                var doc = new HtmlDocument();
                doc.LoadHtml(foundHtml ?? "");

                var bodyNodes = doc.DocumentNode.SelectSingleNode("//body"); // select everything inside the <body> tag
                ePubDisplayModel.ChapterHtml = bodyNodes.OuterHtml;
            }
        }
Пример #23
0
        public static EpubContentRef ParseContentMap(EpubBookRef bookRef)
        {
            var result = new EpubContentRef
            {
                Html     = new Dictionary <string, EpubTextContentFileRef>(),
                Css      = new Dictionary <string, EpubTextContentFileRef>(),
                Images   = new Dictionary <string, EpubByteContentFileRef>(),
                Fonts    = new Dictionary <string, EpubByteContentFileRef>(),
                AllFiles = new Dictionary <string, EpubContentFileRef>()
            };

            foreach (var manifestItem in bookRef.Schema.Package.Manifest)
            {
                var fileName        = manifestItem.Href;
                var contentMimeType = manifestItem.MediaType;
                var contentType     = GetContentTypeByContentMimeType(contentMimeType);
                switch (contentType)
                {
                case EpubContentType.XHTML_1_1:
                case EpubContentType.CSS:
                case EpubContentType.OEB1_DOCUMENT:
                case EpubContentType.OEB1_CSS:
                case EpubContentType.XML:
                case EpubContentType.DTBOOK:
                case EpubContentType.DTBOOK_NCX:
                    var epubTextContentFile = new EpubTextContentFileRef(bookRef)
                    {
                        FileName        = fileName,
                        ContentMimeType = contentMimeType,
                        ContentType     = contentType
                    };
                    switch (contentType)
                    {
                    case EpubContentType.XHTML_1_1:
                        result.Html[fileName] = epubTextContentFile;
                        break;

                    case EpubContentType.CSS:
                        result.Css[fileName] = epubTextContentFile;
                        break;
                    }

                    result.AllFiles[fileName] = epubTextContentFile;
                    break;

                default:
                    var epubByteContentFile = new EpubByteContentFileRef(bookRef)
                    {
                        FileName        = fileName,
                        ContentMimeType = contentMimeType,
                        ContentType     = contentType
                    };
                    switch (contentType)
                    {
                    case EpubContentType.IMAGE_GIF:
                    case EpubContentType.IMAGE_JPEG:
                    case EpubContentType.IMAGE_PNG:
                    case EpubContentType.IMAGE_SVG:
                        result.Images[fileName] = epubByteContentFile;
                        break;

                    case EpubContentType.FONT_TRUETYPE:
                    case EpubContentType.FONT_OPENTYPE:
                        result.Fonts[fileName] = epubByteContentFile;
                        break;
                    }

                    result.AllFiles[fileName] = epubByteContentFile;
                    break;
                }
            }

            return(result);
        }
Пример #24
0
 public static List <EpubChapterRef> GetChapters(EpubBookRef bookRef)
 {
     return(GetChapters(bookRef, bookRef.Schema.Package.Spine, bookRef.Schema.Navigation.NavMap));
 }
Пример #25
0
 public EpubTextContentFileRef(EpubBookRef epubBookRef)
     : base(epubBookRef)
 {
 }
Пример #26
0
 public static List <EpubNavigationItemRef> GetNavigationItems(EpubBookRef bookRef, Epub2Ncx epub2Ncx)
 {
     return(GetNavigationItems(bookRef, epub2Ncx.NavMap));
 }
Пример #27
0
 public static List <EpubNavigationItemRef> GetNavigationItems(EpubBookRef bookRef, Epub3NavDocument epub3NavDocument)
 {
     return(GetNavigationItems(bookRef, epub3NavDocument.Navs.FirstOrDefault(nav => nav.Type == StructuralSemanticsProperty.TOC)));
 }
Пример #28
0
 public void Dispose()
 {
     _chapterRefs.Clear();
     _epubBook?.Dispose();
     _epubBook = null;
 }
Пример #29
0
        /// <summary>
        /// Display the chapter. This might be a whole xhtml file or a section of an xhtml file between 2 'chapter' id's (or epub navnodes)
        /// </summary>
        /// <param name="ePubDisplayModel"></param>
        /// <param name="epubBookRef"></param>
        public void FindAndProcessChapter(ref EpubDisplayModel ePubDisplayModel, EpubBookRef epubBookRef)
        {
            EpubChapterHolder cHolder = new EpubChapterHolder();

            // Enumerating chapters
            var allChapters = epubBookRef.GetNavigation();//.GetChapters();

            for (int i = 0; i < allChapters.Count(); i++)
            {
                var    _chapter = allChapters[i];
                string encTitle = EpubHelpers.EncodeChapterTitleForUrl(_chapter.Title);

                if (encTitle == _processAction && !cHolder.CurrentChapter.IsValid()) // chapter found! select this chapter to display
                {
                    cHolder.CurrentChapter.ChapterIndex = i;
                    cHolder.CurrentChapter.EpubChapter  = _chapter;
                    cHolder.CurrentChapter.TitleAndLinkUrl.LinkTitle = _chapter.Title;
                }

                ePubDisplayModel.TOC_Items.Add(new EpubLink()
                {
                    LinkTitle = _chapter.Title
                });                                                                            // add TOC to display model
            }

            if (!cHolder.CurrentChapter.IsValid())                             // chapter not found - so get the default chapter and redirect to that
            {
                if (_startAtIndex < 0 || _startAtIndex >= allChapters.Count()) // check if the _startAtIndex property is within valid limits - if not then set the index to 0
                {
                    _startAtIndex = 0;
                }

                var _chapter = allChapters[_startAtIndex];
                cHolder.CurrentChapter.TitleAndLinkUrl.LinkTitle = _chapter.Title;

                ePubDisplayModel.RedirectToChapter = cHolder.CurrentChapter.TitleAndLinkUrl.LinkUrl;
                return; // exit this method as we need to perform a redirect in the calling controller rather than
            }

            ePubDisplayModel.TOC_Items[cHolder.CurrentChapter.ChapterIndex].IsCurrent = true;


            // try and find the previous chapter details
            int previousChapterIndex = cHolder.CurrentChapter.ChapterIndex - 1;

            if (previousChapterIndex >= 0) // check index is valid
            {
                var _chapter = allChapters[previousChapterIndex];
                cHolder.PreviousChapter.ChapterIndex = previousChapterIndex;
                cHolder.PreviousChapter.EpubChapter  = _chapter;
                cHolder.PreviousChapter.TitleAndLinkUrl.LinkTitle = _chapter.Title;

                ePubDisplayModel.Nav_PreviousChapterLink.LinkTitle = _chapter.Title;
            }

            // try and find the next chapter details
            int nextChapterIndex = cHolder.CurrentChapter.ChapterIndex + 1;

            if (nextChapterIndex < allChapters.Count()) // check index is valid
            {
                var _chapter = allChapters[nextChapterIndex];
                cHolder.NextChapter.ChapterIndex = nextChapterIndex;
                cHolder.NextChapter.EpubChapter  = _chapter;
                cHolder.NextChapter.TitleAndLinkUrl.LinkTitle = _chapter.Title;

                ePubDisplayModel.Nav_NextChapterLink.LinkTitle = _chapter.Title;
            }

            ePubDisplayModel.ChapterHtml = BuildChapterHtml(cHolder);
        }
Пример #30
0
        public static EpubContentRef ParseContentMap(EpubBookRef bookRef)
        {
            EpubContentRef result = new EpubContentRef
            {
                Html     = new Dictionary <string, EpubTextContentFileRef>(),
                Css      = new Dictionary <string, EpubTextContentFileRef>(),
                Images   = new Dictionary <string, EpubByteContentFileRef>(System.StringComparer.OrdinalIgnoreCase),
                Fonts    = new Dictionary <string, EpubByteContentFileRef>(),
                AllFiles = new Dictionary <string, EpubContentFileRef>()
            };

            foreach (EpubManifestItem manifestItem in bookRef.Schema.Package.Manifest)
            {
                string          fileName        = manifestItem.Href;
                string          contentMimeType = manifestItem.MediaType;
                EpubContentType contentType     = GetContentTypeByContentMimeType(contentMimeType);
                switch (contentType)
                {
                case EpubContentType.XHTML_1_1:
                case EpubContentType.CSS:
                case EpubContentType.OEB1_DOCUMENT:
                case EpubContentType.OEB1_CSS:
                case EpubContentType.XML:
                case EpubContentType.DTBOOK:
                case EpubContentType.DTBOOK_NCX:
                    EpubTextContentFileRef epubTextContentFile = new EpubTextContentFileRef(bookRef)
                    {
                        FileName        = fileName,
                        ContentMimeType = contentMimeType,
                        ContentType     = contentType
                    };
                    switch (contentType)
                    {
                    case EpubContentType.XHTML_1_1:
                        result.Html[fileName] = epubTextContentFile;
                        break;

                    case EpubContentType.CSS:
                        result.Css[fileName] = epubTextContentFile;
                        break;
                    }
                    result.AllFiles[fileName] = epubTextContentFile;
                    break;

                default:
                    EpubByteContentFileRef epubByteContentFile = new EpubByteContentFileRef(bookRef)
                    {
                        FileName        = fileName,
                        ContentMimeType = contentMimeType,
                        ContentType     = contentType
                    };
                    switch (contentType)
                    {
                    case EpubContentType.IMAGE_GIF:
                    case EpubContentType.IMAGE_JPEG:
                    case EpubContentType.IMAGE_PNG:
                    case EpubContentType.IMAGE_SVG:
                        result.Images[fileName] = epubByteContentFile;
                        break;

                    case EpubContentType.FONT_TRUETYPE:
                    case EpubContentType.FONT_OPENTYPE:
                        result.Fonts[fileName] = epubByteContentFile;
                        break;
                    }
                    result.AllFiles[fileName] = epubByteContentFile;
                    break;
                }
            }
            result.Cover = BookCoverReader.ReadBookCover(bookRef.Schema, result.Images);
            return(result);
        }