Example #1
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();
            }
        }
Example #2
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();
 }
Example #3
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();
        }
Example #4
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();
 }
        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());
        }
Example #6
0
        private ParsedTrackInfo ReadEpub(string file)
        {
            _logger.Trace($"Reading {file}");
            var result = new ParsedTrackInfo
            {
                Quality = new QualityModel
                {
                    Quality = Quality.EPUB,
                    QualityDetectionSource = QualityDetectionSource.TagLib
                }
            };

            try
            {
                using (var bookRef = EpubReader.OpenBook(file))
                {
                    result.AuthorTitle = bookRef.AuthorList.FirstOrDefault();
                    result.BookTitle   = bookRef.Title;

                    var meta = bookRef.Schema.Package.Metadata;

                    _logger.Trace(meta.ToJson());

                    result.Isbn           = GetIsbn(meta?.Identifiers);
                    result.Asin           = meta?.Identifiers?.FirstOrDefault(x => x.Scheme?.ToLower().Contains("asin") ?? false)?.Identifier;
                    result.Language       = meta?.Languages?.FirstOrDefault();
                    result.Publisher      = meta?.Publishers?.FirstOrDefault();
                    result.Disambiguation = meta?.Description;

                    result.SeriesTitle = meta?.MetaItems?.FirstOrDefault(x => x.Name == "calibre:series")?.Content;
                    result.SeriesIndex = meta?.MetaItems?.FirstOrDefault(x => x.Name == "calibre:series_index")?.Content;
                }
            }
            catch (Exception e)
            {
                _logger.Error(e, "Error reading epub");
                result.Quality.QualityDetectionSource = QualityDetectionSource.Extension;
            }

            _logger.Trace($"Got:\n{result.ToJson()}");

            return(result);
        }
Example #7
0
        public EpubBook OpenBook(int bookId)
        {
            EpubBook epubBook = EpubReader.OpenBook(settings.Books.First(book => book.Id == bookId).FilePath);

            return(epubBook);
        }
Example #8
0
        public bool ProcessEpub()
        {
            ePubDisplayModel = new EpubDisplayModel();

            // Opens a book and reads all of its content into memory
            var epubBookRef = EpubReader.OpenBook(_ePubFilePath); // not using ReadBook as that loads the whole epub book in memory

            if (epubBookRef != null)
            {
                // get file date
                var fileDateStamp = new FileInfo(_ePubFilePath).LastWriteTime;

                var bookContent = epubBookRef.Content;

                var requestIsForXhtml = false; // a whole epub xhtml file has been requested - this happens when a link in the html is selected as it could be a link anywhere in the whole book

                // *************************************************************************
                // check if this request is for a chapter or a file asset i.e. image or font
                // *************************************************************************

                var extension = Path.GetExtension(_processAction);

                if (!string.IsNullOrEmpty(extension))                                                           // this might be a request for a file ie. font or image
                {
                    if (SafeFileTypes.Contains(extension))                                                      // this filetype is in the SafeFileTypes list
                    {
                        Dictionary <string, EpubContentFileRef> allFiles = bookContent.AllFiles;                // would use bookContent.css/fonts/images but fonts have missing mime-types in the EpubReader package, and so are noth being selected as fonts
                        foreach (var item in allFiles)                                                          // loop all the files in the epub archive
                        {
                            if (item.Key.EndsWith(_processAction, StringComparison.InvariantCultureIgnoreCase)) // this filename matches the requested action (_processAction)
                            {
                                switch (item.Value)                                                             // switch based on the class of the EpubContentFileRef type
                                {
                                case EpubByteContentFileRef itemValue:

                                    FileToServe = new FileToServe(itemValue.ReadContentAsBytes(), itemValue.ContentMimeType, itemValue.FileName, fileDateStamp);

                                    return(false);    // return ProcessEPub()

                                case EpubContentFileRef textItem:

                                    if (textItem.ContentType == EpubContentType.XHTML_1_1)
                                    {
                                        requestIsForXhtml = true;        // we want to process this file as it is not a 'File' to serve, it is an HTML document to process
                                    }
                                    else                                 // stop any other text file from being processed or served
                                    {
                                        FileToServe = new FileToServe(); // this will stop this file being served
                                        return(false);                   // return ProcessEPub()
                                    }
                                    break;

                                default:
                                    FileToServe = new FileToServe(); // this will stop this file being served
                                    return(false);                   // return ProcessEPub()
                                }
                            }
                        }
                    }
                    else // disallow filetype
                    {
                        FileToServe = new FileToServe(); // this will stop this file being served
                        return(false);  // return ProcessEPub()
                    }
                }

                // check if this chapter has been cached in Application memory. If so then return that without continuing.
                if (_isToCache)
                {
                    _cacheHash = GetMd5Hash(_ePubFilePath + _processAction); // create unique hash of this chapter in this book
                    var cachedItem = HttpContext.Current.Cache.Get(_cacheHash);
                    if (cachedItem != null)                                  // cached chapter found
                    {
                        ePubDisplayModel = (EpubDisplayModel)cachedItem;
                        return(true);
                    }
                }

                // Book's title
                ePubDisplayModel.Title = epubBookRef.Title;

                // Book's authors (comma separated list)
                ePubDisplayModel.Authors = epubBookRef.Author;

                // try and find the requested chapter or xhtml file
                if (requestIsForXhtml)
                {
                    FindAndProcessXHTML(ref ePubDisplayModel, epubBookRef); // updates ePubDisplayModel by reference with content
                }
                else
                {
                    FindAndProcessChapter(ref ePubDisplayModel, epubBookRef); // updates ePubDisplayModel by reference with content
                }

                if (!string.IsNullOrEmpty(ePubDisplayModel.RedirectToChapter)) // we need to redirect to a chapter so exit this method
                {
                    return(false);
                }

                // All fonts in the book (file name is the key)
                //Dictionary<string, EpubByteContentFileRef> fonts = bookContent.Fonts; // Note: VersOne.Epub is missing some font mime-types so be aware that all/some the fonts will not be in this object. They will, however, be in the .AllFiles() object

                // All CSS files in the book (file name is the key)
                Dictionary <string, EpubTextContentFileRef> cssFiles = bookContent.Css;
                string cssContent = string.Empty;

                foreach (var cssFile in cssFiles.Values)
                {
                    cssContent += cssFile.ReadContentAsText();
                }

                // using dotless (css preprocessor) we will add '.epub' to all the book styles in order to keep the book styles restricted to the book and not affect the rest of the browser page.
                string finalCss = string.Format(".epub {{{0}}}", cssContent); // add '.epub' class to all css elements, so we can contain all the book styles to just to book div (which should have a .epub class added to it)

                var dotlessConfig = new dotless.Core.configuration.DotlessConfiguration
                {
                    MinifyOutput = true
                };

                var resultCss = Less.Parse(finalCss, dotlessConfig);

                // FOR REFERENCE IF NEEDED - <base href="'. $this->base_link. '/" target="_self"> // need to include <base> as some cms's adds a trailing '/' to all requests which brakes the relative links in the epub html
                ePubDisplayModel.ChapterHtml = string.Format("<html><head><style>{0}</style></head><body><div class='epub'>{1}</div></body></html>", resultCss, ePubDisplayModel.ChapterHtml);

                if (_isToCache) // if using application cache
                {
                    try
                    {
                        HttpContext.Current.Cache.Insert(_cacheHash, ePubDisplayModel, null, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }

            return(true);
        }