Esempio n. 1
0
        public FB2Book(string path, string newPath)
        {
            fB2File = new FB2File();
            File.Copy(path, newPath);
            FullPath = newPath;

            Zoom     = -1;
            LastPage = -1;

            XDocument doc = XDocument.Load(path);

            fB2File.Load(doc, false);
            Date = DateTime.Now;

            var           s      = fB2File.TitleInfo;
            var           author = s.BookAuthors;
            StringBuilder name   = new StringBuilder();

            foreach (var aurho in author)
            {
                name.Append(string.Format("{0} {1}", aurho.FirstName.Text, aurho.LastName.Text));
            }

            Title  = s.BookTitle.Text;
            Author = Convert.ToString(name);

            CoverPath = GetCoverPath();
        }
        public void LoadFB2FileFromXML(XDocument fb2Document)
        {
            _fb2Files.Clear();
            var file = new FB2File();

            try
            {
                file.Load(fb2Document, false);
                _fb2Files.Add(file);
            }
            catch (Exception ex)
            {
                Logger.Log.ErrorFormat("Error loading XML document : {0}", ex);
            }
        }
Esempio n. 3
0
        protected FB2File ReadFb2FileStream(Stream s)
        {
            Logger.Log.Debug("Starting to load FB2 stream");
            var settings = new XmlReaderSettings
            {
                ValidationType  = ValidationType.None,
                DtdProcessing   = DtdProcessing.Prohibit,
                CheckCharacters = false
            };
            XDocument fb2Document;

            try
            {
                using (XmlReader reader = XmlReader.Create(s, settings))
                {
                    fb2Document = XDocument.Load(reader, LoadOptions.PreserveWhitespace);
                    reader.Close();
                }
            }
            catch (XmlException) // we handle this on top
            {
                throw;
            }
            catch (Exception ex)
            {
                Logger.Log.ErrorFormat("Error loading file : {0}", ex);
                throw;
            }

            var file = new FB2File();

            try
            {
                file.Load(fb2Document, false);
            }
            catch (Exception ex)
            {
                Logger.Log.ErrorFormat("Error loading file : {0}", ex);
                throw;
            }
            Logger.Log.Debug("FB2 stream loaded");
            return(file);
        }
Esempio n. 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public override Image GetCoverImage(Stream stream, string fileName)
        {
            Image     image = null;
            XDocument xml   = null;

            try
            {
                FB2File fb2 = new FB2File();
                stream.Position = 0;
                xml             = XDocument.Load(stream);
                fb2.Load(xml, false);

                if (fb2.TitleInfo != null && fb2.TitleInfo.Cover != null && fb2.TitleInfo.Cover.HasImages() && fb2.Images.Count > 0)
                {
                    string coverHRef    = fb2.TitleInfo.Cover.CoverpageImages.First().HRef.Substring(1);
                    var    binaryObject = fb2.Images.First(item => item.Value.Id == coverHRef);
                    if (binaryObject.Value.BinaryData != null && binaryObject.Value.BinaryData.Length > 0)
                    {
                        using (MemoryStream memStream = new MemoryStream(binaryObject.Value.BinaryData))
                        {
                            image = Image.FromStream(memStream);
                            // Convert image to jpeg
                            ImageFormat fmt = binaryObject.Value.ContentType == ContentTypeEnum.ContentTypePng ? ImageFormat.Png : ImageFormat.Gif;
                            if (binaryObject.Value.ContentType != ContentTypeEnum.ContentTypeJpeg)
                            {
                                image = Image.FromStream(image.ToStream(fmt));
                            }
                            image = image.Resize(CoverImage.CoverSize);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.WriteLine(LogLevel.Error, "Book.GetCoverImage() exception {0} on file: {1}", e.Message, fileName);
            }
            // Dispose xml document
            xml = null;
            return(image);
        }
Esempio n. 5
0
        private void ReadFB2FileStream(Stream s)
        {
            XmlReaderSettings settings = new XmlReaderSettings
            {
                ValidationType = ValidationType.None,
                ProhibitDtd    = false
            };
            XDocument fb2Document = null;

            using (XmlReader reader = XmlReader.Create(s, settings))
            {
                fb2Document = XDocument.Load(reader, LoadOptions.PreserveWhitespace);
                reader.Close();
            }
            file = new FB2File();
            try
            {
                file.Load(fb2Document, false);
                Text = file.MainBody.Title.ToString();
                var sc  = file.MainBody.Sections;
                var str = "";
                foreach (var sectionItem in sc)
                {
                    str += Environment.NewLine + sectionItem.Title + Environment.NewLine;

                    foreach (var textItem in sectionItem.Content)
                    {
                        str += Environment.NewLine + textItem.ToString() + Environment.NewLine;
                    }
                }
                tbox.Text = str;
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Error loading file : {0}", ex.Message));
            }
        }
Esempio n. 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public override Book Parse(Stream stream, string fileName)
        {
            Book book = new Book(fileName);

            book.DocumentSize = (UInt32)stream.Length;

            try
            {
                FB2File fb2 = new FB2File();
                // Load header only
                stream.Position = 0;

                // Project Mono has a bug: Xdocument.Load() can't detect encoding
                string encoding = string.Empty;
                if (Utils.IsLinux)
                {
                    using (StreamReader sr = new StreamReader(stream))
                    {
                        encoding = sr.ReadLine();
                        int idx = encoding.ToLower().IndexOf("encoding=\"");
                        if (idx > 0)
                        {
                            encoding        = encoding.Substring(idx + 10);
                            encoding        = encoding.Substring(0, encoding.IndexOf('"'));
                            stream.Position = 0;
                            using (StreamReader esr = new StreamReader(stream, Encoding.GetEncoding(encoding)))
                            {
                                string xmlStr = esr.ReadToEnd();
                                try
                                {
                                    xml = XDocument.Parse(xmlStr, LoadOptions.PreserveWhitespace);
                                }
                                catch
                                {
                                    stream.Position = 0;

                                    using (HtmlStream reader = new HtmlStream(stream, Encoding.Default))
                                    {
                                        using (SgmlReader sgmlReader = new SgmlReader())
                                        {
                                            sgmlReader.InputStream = reader;
                                            sgmlReader.Dtd         = LoadFb2Dtd(sgmlReader);

                                            xml = XDocument.Load(sgmlReader);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (xml == null)
                {
                    try
                    {
                        xml = XDocument.Load(stream);
                    }
                    catch
                    {
                        stream.Position = 0;

                        // This code will try to use the sgml based reader for not well-formed xml files
                        using (HtmlStream reader = new HtmlStream(stream, Encoding.Default))
                        {
                            using (SgmlReader sgmlReader = new SgmlReader())
                            {
                                sgmlReader.InputStream = reader;
                                sgmlReader.Dtd         = LoadFb2Dtd(sgmlReader);

                                xml = XDocument.Load(sgmlReader);
                            }
                        }
                    }
                }

                fb2.Load(xml, true);

                if (fb2.DocumentInfo != null)
                {
                    book.ID = fb2.DocumentInfo.ID;
                    if (fb2.DocumentInfo.DocumentVersion != null)
                    {
                        book.Version = (float)fb2.DocumentInfo.DocumentVersion;
                    }
                    if (fb2.DocumentInfo.DocumentDate != null)
                    {
                        book.DocumentDate = fb2.DocumentInfo.DocumentDate.DateValue;
                    }
                }

                if (fb2.TitleInfo != null)
                {
                    if (fb2.TitleInfo.Cover != null && fb2.TitleInfo.Cover.HasImages())
                    {
                        book.HasCover = true;
                    }
                    if (fb2.TitleInfo.BookTitle != null)
                    {
                        book.Title = fb2.TitleInfo.BookTitle.Text;
                    }
                    if (fb2.TitleInfo.Annotation != null)
                    {
                        book.Annotation = fb2.TitleInfo.Annotation.ToString();
                    }
                    if (fb2.TitleInfo.Sequences != null && fb2.TitleInfo.Sequences.Count > 0)
                    {
                        book.Sequence = fb2.TitleInfo.Sequences.First().Name.Capitalize(true);
                        if (fb2.TitleInfo.Sequences.First().Number != null)
                        {
                            book.NumberInSequence = (UInt32)(fb2.TitleInfo.Sequences.First().Number);
                        }
                    }
                    if (fb2.TitleInfo.Language != null)
                    {
                        book.Language = fb2.TitleInfo.Language;
                    }
                    if (fb2.TitleInfo.BookDate != null)
                    {
                        book.BookDate = fb2.TitleInfo.BookDate.DateValue;
                    }
                    if (fb2.TitleInfo.BookAuthors != null && fb2.TitleInfo.BookAuthors.Any())
                    {
                        book.Authors = new List <string>();
                        book.Authors.AddRange(from ba in fb2.TitleInfo.BookAuthors select string.Concat(ba.LastName, " ", ba.FirstName, " ", ba.MiddleName).Replace("  ", " ").Capitalize());
                    }
                    if (fb2.TitleInfo.Translators != null && fb2.TitleInfo.Translators.Any())
                    {
                        book.Translators = new List <string>();
                        book.Translators.AddRange(from ba in fb2.TitleInfo.Translators select string.Concat(ba.LastName, " ", ba.FirstName, " ", ba.MiddleName).Replace("  ", " ").Capitalize());
                    }
                    if (fb2.TitleInfo.Genres != null && fb2.TitleInfo.Genres.Any())
                    {
                        book.Genres = new List <string>();
                        book.Genres.AddRange((from g in fb2.TitleInfo.Genres select g.Genre).ToList());
                    }
                }
            }
            catch (Exception e)
            {
                Log.WriteLine(LogLevel.Error, "Book.Parse() exception {0} on file: {1}", e.Message, fileName);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }
            }

            return(book);
        }
Esempio n. 7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public override Book Parse(Stream stream, string fileName)
        {
            XDocument xml  = null;
            Book      book = new Book(fileName);

            book.DocumentSize = (UInt32)stream.Length;

            try
            {
                FB2File fb2 = new FB2File();
                // Load header only
                stream.Position = 0;

                // Project Mono has a bug: Xdocument.Load() can't detect encoding
                string encoding = string.Empty;
                if (Utils.IsLinux)
                {
                    using (StreamReader sr = new StreamReader(stream))
                    {
                        encoding = sr.ReadLine();
                        int idx = encoding.ToLower().IndexOf("encoding=\"");
                        if (idx > 0)
                        {
                            encoding        = encoding.Substring(idx + 10);
                            encoding        = encoding.Substring(0, encoding.IndexOf('"'));
                            stream.Position = 0;
                            using (StreamReader esr = new StreamReader(stream, Encoding.GetEncoding(encoding)))
                            {
                                string xmlStr = esr.ReadToEnd();
                                try
                                {
                                    xml = XDocument.Parse(xmlStr, LoadOptions.PreserveWhitespace);
                                }
                                catch (Exception e)
                                {
                                    if (e.Message.IndexOf("nbsp", StringComparison.InvariantCultureIgnoreCase) > 0)
                                    {
                                        xmlStr = xmlStr.Replace("&nbsp;", "&#160;").Replace("&NBSP;", "&#160;");
                                        xml    = XDocument.Parse(xmlStr, LoadOptions.PreserveWhitespace);
                                    }
                                    else if (e.Message.IndexOf("is an invalid character", StringComparison.InvariantCultureIgnoreCase) > 0)
                                    {
                                        xml = XDocument.Parse(this.SanitizeXmlString(xmlStr), LoadOptions.PreserveWhitespace);
                                    }
                                    else
                                    {
                                        throw e;
                                    }
                                }
                            }
                        }
                    }
                }

                if (xml == null)
                {
                    try
                    {
                        xml = XDocument.Load(stream);
                    }
                    // This code will try to improve xml loading
                    catch (Exception e)
                    {
                        stream.Position = 0;
                        if (e.Message.IndexOf("nbsp", StringComparison.InvariantCultureIgnoreCase) > 0)
                        {
                            using (StreamReader sr = new StreamReader(stream))
                            {
                                string xmlStr = sr.ReadToEnd();
                                xmlStr = xmlStr.Replace("&nbsp;", "&#160;").Replace("&NBSP;", "&#160;");
                                xml    = XDocument.Parse(xmlStr, LoadOptions.PreserveWhitespace);
                            }
                        }
                        else if (e.Message.IndexOf("is an invalid character", StringComparison.InvariantCultureIgnoreCase) > 0)
                        {
                            using (StreamReader sr = new StreamReader(stream))
                            {
                                string xmlStr = sr.ReadToEnd();
                                xml = XDocument.Parse(this.SanitizeXmlString(xmlStr), LoadOptions.PreserveWhitespace);
                            }
                        }
                        else
                        {
                            throw e;
                        }
                    }
                }

                if (xml != null)
                {
                    fb2.Load(xml, true);

                    if (fb2.DocumentInfo != null)
                    {
                        book.ID = fb2.DocumentInfo.ID;
                        if (fb2.DocumentInfo.DocumentVersion != null)
                        {
                            book.Version = (float)fb2.DocumentInfo.DocumentVersion;
                        }
                        if (fb2.DocumentInfo.DocumentDate != null)
                        {
                            book.DocumentDate = fb2.DocumentInfo.DocumentDate.DateValue;
                        }
                    }

                    if (fb2.TitleInfo != null)
                    {
                        if (fb2.TitleInfo.Cover != null && fb2.TitleInfo.Cover.HasImages())
                        {
                            book.HasCover = true;
                        }
                        if (fb2.TitleInfo.BookTitle != null)
                        {
                            book.Title = fb2.TitleInfo.BookTitle.Text;
                        }
                        if (fb2.TitleInfo.Annotation != null)
                        {
                            book.Annotation = fb2.TitleInfo.Annotation.ToString();
                        }
                        if (fb2.TitleInfo.Sequences != null && fb2.TitleInfo.Sequences.Count > 0)
                        {
                            book.Sequence = fb2.TitleInfo.Sequences.First().Name.Capitalize(true);
                            if (fb2.TitleInfo.Sequences.First().Number != null)
                            {
                                book.NumberInSequence = (UInt32)(fb2.TitleInfo.Sequences.First().Number);
                            }
                        }
                        if (fb2.TitleInfo.Language != null)
                        {
                            book.Language = fb2.TitleInfo.Language;
                        }
                        if (fb2.TitleInfo.BookDate != null)
                        {
                            book.BookDate = fb2.TitleInfo.BookDate.DateValue;
                        }
                        if (fb2.TitleInfo.BookAuthors != null && fb2.TitleInfo.BookAuthors.Count() > 0)
                        {
                            book.Authors = new List <string>();
                            book.Authors.AddRange(from ba in fb2.TitleInfo.BookAuthors select string.Concat(ba.LastName, " ", ba.FirstName, " ", ba.MiddleName).Replace("  ", " ").Capitalize());
                        }
                        if (fb2.TitleInfo.Translators != null && fb2.TitleInfo.Translators.Count() > 0)
                        {
                            book.Translators = new List <string>();
                            book.Translators.AddRange(from ba in fb2.TitleInfo.Translators select string.Concat(ba.LastName, " ", ba.FirstName, " ", ba.MiddleName).Replace("  ", " ").Capitalize());
                        }
                        if (fb2.TitleInfo.Genres != null && fb2.TitleInfo.Genres.Count() > 0)
                        {
                            book.Genres = new List <string>();
                            book.Genres.AddRange((from g in fb2.TitleInfo.Genres select g.Genre).ToList());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.WriteLine(LogLevel.Error, "Book.Parse() exception {0} on file: {1}", e.Message, fileName);
            }
            finally
            {
                // Dispose xml document
                xml = null;
            }

            return(book);
        }