public void Read_Correct_FB2_ZIP_File()
        {
            FB2File file = new FB2File(@"TestFiles\Макиавелли Николо - Государь.fb2.zip");

            Assert.AreEqual("Государь", file.BookTitle, "Book title must be 'Государь'");

            Assert.AreEqual("Николо", file.BookAuthorFirstName, "Author first name must be 'Николо'");
            Assert.AreEqual(string.Empty, file.BookAuthorMiddleName, "Author middle name must be empty string");
            Assert.AreEqual("Макиавелли", file.BookAuthorLastName, "Author last name must be 'Макиавелли'");

            Assert.AreEqual(string.Empty, file.BookSequenceName, "Sequence Name must be empty string");
            Assert.IsNull(file.BookSequenceNr, "Sequence Number must be null");

            Assert.AreEqual("Европейская старинная литература", file.BookGenre, "Genre must be 'Европейская старинная литература'");

            Assert.AreEqual("1.1", file.BookVersion, "Book version must be '1.1'");

            Assert.AreEqual("ru", file.BookLang, "Book language must be 'ru'");

            Encoding win1251 = Encoding.GetEncoding(1251);

            Assert.AreEqual(win1251.EncodingName, file.BookEncoding, string.Format("Book encoding must be '{0}'", win1251.EncodingName));

            Assert.AreEqual("210 Кб", file.BookSizeText, "Book size text must be '210 Кб'");
        }
        private List <FB2File> ReadListOfFiles(string[] fileNames)
        {
            List <FB2File> containers = new List <FB2File>();

            foreach (string fileName in fileNames)
            {
                try
                {
                    FB2File fc = new FB2File(fileName);
                    containers.Add(fc);
                    UpdateStatus(String.Format(Properties.Resources.ProgressFileLoaded, fc.FileInformation.Name));
                    if (CheckCancel())
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    AddErrorRN(String.Format(Properties.Resources.ProgressFileLoadError, fileName, ex.Message));
                }
                if (CheckCancel())
                {
                    break;
                }
            }
            return(containers);
        }
        /// <summary>
        /// Создание файла обложки
        /// </summary>
        /// <param name="file">Файл fb2</param>
        /// <param name="temp">Директория для сохранения</param>
        /// <returns></returns>
        private string CreateCover(FB2File file, string temp)
        {
            var coverImagePath = string.Empty;

            var coverImage = file.TitleInfo.Cover.CoverpageImages.FirstOrDefault();

            if (coverImage != null)
            {
                coverImagePath = coverImage.HRef.Replace("#", string.Empty);
            }

            if (string.IsNullOrEmpty(coverImagePath))
            {
                var(key, _) = file.Images.FirstOrDefault(i => i.Key.Contains("cover"));
                if (key == null)
                {
                    return(string.Empty);
                }

                coverImagePath = key;
            }

            var covertPath = Path.Combine(temp, "cover.html");

            File.WriteAllText(covertPath, File.ReadAllText(_htmlPatternsConfig.CoverPath).Replace("{cover}", coverImagePath), Encoding.UTF8);
            return(covertPath);
        }
Exemple #4
0
 private static void PrepareTextItems(IEnumerable <IFb2TextItem> textItems, FB2File file, List <ILine> lines, string bodyName, int headerLevel)
 {
     foreach (var textItem in textItems)
     {
         PrepareTextItem(textItem, file, lines, bodyName, headerLevel);
     }
 }
        private void ExtractFile(ListViewItem item)
        {
            string fileName = String.Empty;

            try
            {
                FB2File fc = item.Tag as FB2File;
                fileName = fc.FileInformation.Name;
                if (fileName.ToLower().EndsWith(FB2Config.Current.FB2Extension))
                {
                    AddMessageRN(String.Format(Properties.Resources.ProgressExtractFileAlreadyExtracted, fileName));
                }
                else
                {
                    string oldFileSize = fc.BookSizeText;
                    AddMessage(String.Format(Properties.Resources.ProgressExtractFile, fileName));
                    fc.Extract();
                    UpdateItem(item);
                    AddMessageRN(String.Format(Properties.Resources.ProgressFileSizeChange, oldFileSize, fc.BookSizeText));
                }
            }
            catch (Exception ex)
            {
                AddErrorRN(String.Format(Properties.Resources.ProgressExtractFileError, fileName, ex.Message));
            }
        }
Exemple #6
0
        /// <summary>
        /// Конвертация файла fb2 в плоский список
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static IEnumerable <ILine> Convert(FB2File file)
        {
            var lines = new List <ILine>();

            if (file.MainBody != null)
            {
                foreach (var bodyItem in file.Bodies)
                {
                    if (bodyItem.Name == "notes")
                    {
                        AddTitle(bodyItem.Title, lines, string.Empty, 1);
                    }

                    foreach (var sectionItem in bodyItem.Epigraphs)
                    {
                        PrepareTextItem(sectionItem, file, lines, bodyItem.Name, 1);
                    }

                    foreach (var sectionItem in bodyItem.Sections)
                    {
                        PrepareTextItem(sectionItem, file, lines, bodyItem.Name, 1);
                    }
                }
            }

            return(lines);
        }
 /// <summary>
 /// Сохранение все картинок на диск
 /// </summary>
 /// <param name="file"></param>
 /// <param name="temp"></param>
 private static void SaveImages(FB2File file, string temp)
 {
     foreach (var(key, value) in file.Images)
     {
         File.WriteAllBytes(Path.Combine(temp, key), value.BinaryData);
     }
 }
Exemple #8
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();
        }
        private async void ReadFB2File(string path)
        {
            string fileName = FileBrowserHelpers.GetFilename(path);
            string text     = FileBrowserHelpers.ReadTextFromFile(path);

            FB2File file  = await new FB2Reader().ReadAsync(text);
            var     lines = await _fB2SampleConverter.ConvertAsync(file);

            string finalText = _fB2SampleConverter.GetLinesAsText();

            byte[] imageData = _fB2SampleConverter.GetCoverImageData();

            string imagePath = Application.persistentDataPath + _targetFolder + fileName + ".jpg";;

            try
            {
                File.WriteAllBytes(imagePath, imageData);

                Debug.Log("Image is saved. Path: " + imagePath);
            }
            catch
            {
                Debug.LogError("Loading image is error!");
            }

            imagePath = imagePath.Replace("/", "\\");

            string filePath = (Application.persistentDataPath + _targetFolder + fileName).Replace("/", "\\");

            FileData newBook = new FileData(fileName, filePath, imagePath, FileData.FileType.Book);

            SaveFile(newBook, finalText);
        }
        private void toolStripEditBooks_Click(object sender, EventArgs e)
        {
            var     dialog = new ChangeProperties();
            FB2File fc     = null;

            if (filesView.FocusedItem != null)
            {
                fc = filesView.FocusedItem.Tag as FB2File;
            }
            dialog.LoadFileProperties(fc, filesView.CheckedItems.Count);
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                InProgress = true;
                var fp = dialog.GetFileProperties();
                foreach (ListViewItem item in filesView.CheckedItems)
                {
                    FB2File fi = item.Tag as FB2File;
                    try
                    {
                        UpdateFileProperties(item, fp);
                        UpdateItem(item);
                        AddMessageRN(String.Format(Properties.Resources.ProgressEditFile, fi.FileInformation.FullName));
                        if (CheckCancel())
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        AddErrorRN(String.Format(Properties.Resources.ProgressEditFileError, fi.FileInformation.FullName, ex.Message));
                    }
                }
                InProgress = false;
            }
        }
        private string GetGroupName(FB2File item, int typeGroup = 0)
        {
            string seq = string.Empty;

            if (typeGroup == 0)
            {
                seq = String.IsNullOrEmpty(item.BookSequenceName) ? Properties.Resources.DisplayNoSerie : item.BookSequenceName;
                seq = String.IsNullOrEmpty(item.BookAuthorLastName) ? seq : item.BookAuthorLastName + ": " + seq;
                return(seq);
            }
            else
            if (typeGroup == 1)
            {
                seq = item.BookTitle;
                seq = String.IsNullOrEmpty(item.BookAuthorLastName) ? seq : item.BookAuthorLastName + ": " + seq;
                return(seq);
            }
            else
            if (typeGroup == 2)
            {
                seq = String.IsNullOrEmpty(item.BookSequenceName) ? Properties.Resources.DisplayNoSerie : item.BookSequenceName;
                seq = String.IsNullOrEmpty(item.BookAuthorLastName) ? seq : seq + ": " + item.BookAuthorLastName;
                return(seq);
            }
            else
            if (typeGroup == 3)
            {
                seq = String.IsNullOrEmpty(item.BookSequenceName) ? Properties.Resources.DisplayNoSerie : item.BookSequenceName;
                seq = seq + ": " + item.BookTitle;
                return(seq);
            }
            return(seq);
        }
 private void viewDescriptionToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (filesView.FocusedItem != null)
     {
         try
         {
             FB2File fc = filesView.FocusedItem.Tag as FB2File;
             AddMessageRN(string.Format(Properties.Resources.FileDescriptionView, fc.FileInformation.FullName));
             string      temp   = string.Empty;
             XmlDocument xmlDoc = new XmlDocument();
             xmlDoc.LoadXml(fc.Metadata.Description);
             using (var stringWriter = new StringWriter())
             {
                 var xmlTextWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings()
                 {
                     Indent = true, NewLineChars = "\r\n", CloseOutput = true, OmitXmlDeclaration = true
                 });
                 xmlDoc.WriteTo(xmlTextWriter);
                 xmlTextWriter.Flush();
                 temp = stringWriter.ToString();
             }
             AddMessageRN(temp);
         }
         catch (Exception ex)
         {
             AddErrorRN(ex.Message);
         }
     }
 }
        /// <summary>
        /// Passes FB2 info to the EPub file to be added at the end of the book
        /// </summary>
        /// <param name="epubFile">destination epub object</param>
        /// <param name="fb2File">source fb2 object</param>
        private void PassFb2InfoToEpub(EPubFileV2 epubFile, FB2File fb2File)
        {
            if (!Settings.ConversionSettings.Fb2Info)
            {
                return;
            }
            var infoDocument = new BaseXHTMLFileV2
            {
                Id   = "FB2 Info",
                Type = SectionTypeEnum.Text,
                FileEPubInternalPath = EPubInternalPath.GetDefaultLocation(DefaultLocations.DefaultTextFolder),
                FileName             = "fb2info.xhtml",
                GuideRole            = GuideTypeEnum.Notes,
                NotPartOfNavigation  = true
            };

            var converterSettings = new ConverterOptionsV2
            {
                CapitalDrop       = false,
                Images            = Images,
                MaxSize           = Settings.V2Settings.HTMLFileMaxSize,
                ReferencesManager = _referencesManager,
            };
            var infoConverter = new Fb2EpubInfoConverterV2();

            infoDocument.Content = infoConverter.Convert(fb2File, converterSettings);

            StructureManager.AddAboutPage(infoDocument);
        }
        private void ValidateSchema(ListViewItem item)
        {
            string fileName = String.Empty;

            try
            {
                FB2File fc = item.Tag as FB2File;
                fileName = fc.FileInformation.Name;
                AddMessage(string.Format(Properties.Resources.ProgressValidation, fc.FileInformation.Name));
                List <string> errors = fc.ValidateSchema();
                if (errors.Count > 0)
                {
                    AddMessageRN(string.Empty);
                    foreach (string s in errors)
                    {
                        AddErrorRN(s);
                    }
                }
                else
                {
                    AddMessageRN(Properties.Resources.ValidationOk);
                }
                errors.Clear();
            }
            catch (Exception ex)
            {
                AddErrorRN(String.Format(Properties.Resources.ValidationFileError, fileName, ex.Message));
            }
        }
Exemple #15
0
        public MainPage()
        {
            InitializeComponent();

            _file = new FB2File();

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        }
Exemple #16
0
 public void Convert(FB2File fb2File, IBookInformationData titleInformation)
 {
     _titleInfoConverter.Convert(fb2File.TitleInfo, titleInformation);
     _bookIDConverter.Convert(fb2File, titleInformation);
     _sourceInfoConverter.Convert(fb2File, titleInformation);
     _publisherInfoConverter.Convert(fb2File, titleInformation);
     _seriesDataConverter.Convert(fb2File, titleInformation);
 }
Exemple #17
0
        private void Close_Click(object sender, RoutedEventArgs e)
        {
            bookInfo.Text  = string.Empty;
            textBlock.Text = "Closed";
            _file          = null;

            GC.Collect();
        }
 private void reloadToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (filesView.FocusedItem != null)
     {
         FB2File fc = filesView.FocusedItem.Tag as FB2File;
         fc.Reload();
         UpdateItem(filesView.FocusedItem);
     }
 }
        private void PassPublisherInfoFromFB2(FB2File fb2File, IBookInformationData titleInformation, IEPubConversionSettings settings)
        {
            if (fb2File.PublishInfo.BookTitle != null)
            {
                var bookTitle = new Title
                {
                    TitleName =
                        Rus2Lat.Instance.Translate(fb2File.PublishInfo.BookTitle.Text, settings.TransliterationSettings),
                    Language =
                        !string.IsNullOrEmpty(fb2File.PublishInfo.BookTitle.Language)
                            ? fb2File.PublishInfo.BookTitle.Language
                            : fb2File.TitleInfo.Language
                };
                if ((Settings.ConversionSettings.IgnoreTitle != IgnoreInfoSourceOptions.IgnorePublishTitle) && (Settings.ConversionSettings.IgnoreTitle != IgnoreInfoSourceOptions.IgnoreMainAndPublish) &&
                    Settings.ConversionSettings.IgnoreTitle != IgnoreInfoSourceOptions.IgnoreSourceAndPublish)
                {
                    bookTitle.TitleType = TitleType.PublishInfo;
                    titleInformation.BookTitles.Add(bookTitle);
                }
            }


            if (fb2File.PublishInfo.ISBN != null)
            {
                var bookId = new Identifier
                {
                    IdentifierName = "BookISBN",
                    ID             = fb2File.PublishInfo.ISBN.Text,
                    Scheme         = "ISBN"
                };
                titleInformation.Identifiers.Add(bookId);
            }


            if (fb2File.PublishInfo.Publisher != null)
            {
                titleInformation.Publisher.PublisherName = Rus2Lat.Instance.Translate(fb2File.PublishInfo.Publisher.Text, settings.TransliterationSettings);
            }


            try
            {
                if (fb2File.PublishInfo.Year.HasValue)
                {
                    var date = new DateTime(fb2File.PublishInfo.Year.Value, 1, 1);
                    titleInformation.DatePublished = date;
                }
            }
            catch (FormatException ex)
            {
                Logger.Log.DebugFormat("Date reading format exception: {0}", ex);
            }
            catch (Exception exAll)
            {
                Logger.Log.ErrorFormat("Date reading exception: {0}", exAll);
            }
        }
        public void Validate_Correct_FB2_File()
        {
            FB2File file = new FB2File(@"TestFiles\Макиавелли Николо - Государь.fb2");

            var errors = file.ValidateSchema();

            Assert.IsNotNull(errors);
            Assert.AreEqual(0, errors.Count);
        }
 public void Convert(FB2File fb2File, IBookInformationData titleInformation, ICalibreMetadata metadata)
 {
     _titleInfoConverter.Convert(fb2File.TitleInfo, titleInformation);
     _bookIDConverter.Convert(fb2File, titleInformation);
     _sourceInfoConverter.Convert(fb2File, titleInformation);
     _publisherInfoConverter.Convert(fb2File, titleInformation);
     _calibreMetadataConverter.Convert(fb2File, metadata);
     _seriesDataConverter.Convert(fb2File, titleInformation);
 }
        public void Convert(FB2File fb2File, IBookInformationData titleInformation)
        {
            if (fb2File.PublishInfo.BookTitle != null)
            {
                var bookTitle = new Title
                {
                    TitleName =
                        Rus2Lat.Instance.Translate(fb2File.PublishInfo.BookTitle.Text, _conversionSettings.TransliterationSettings),
                    Language =
                        !string.IsNullOrEmpty(fb2File.PublishInfo.BookTitle.Language)
                            ? fb2File.PublishInfo.BookTitle.Language
                            : fb2File.TitleInfo.Language
                };
                if (!SourceDataInclusionControl.Instance.IsIgnoreInfoSource(SourceDataInclusionControl.DataTypes.Publish, _conversionSettings.IgnoreTitle))
                {
                    bookTitle.TitleType = TitleType.PublishInfo;
                    titleInformation.BookTitles.Add(bookTitle);
                }
            }


            if (fb2File.PublishInfo.ISBN != null)
            {
                var bookId = new Identifier
                {
                    IdentifierName = "BookISBN",
                    ID             = fb2File.PublishInfo.ISBN.Text,
                    Scheme         = "ISBN"
                };
                titleInformation.Identifiers.Add(bookId);
            }

            titleInformation.Publisher = new Publisher();
            if (fb2File.PublishInfo.Publisher != null)
            {
                titleInformation.Publisher.PublisherName = Rus2Lat.Instance.Translate(fb2File.PublishInfo.Publisher.Text, _conversionSettings.TransliterationSettings);
            }


            try
            {
                if (fb2File.PublishInfo.Year.HasValue)
                {
                    var date = new DateTime(fb2File.PublishInfo.Year.Value, 1, 1);
                    titleInformation.DatePublished = date;
                }
            }
            catch (FormatException ex)
            {
                Logger.Log.DebugFormat("Date reading format exception: {0}", ex);
            }
            catch (Exception exAll)
            {
                Logger.Log.ErrorFormat("Date reading exception: {0}", exAll);
            }
        }
 private void openFolderMenuItem_Click(object sender, EventArgs e)
 {
     if (filesView.FocusedItem != null)
     {
         FB2File fc = filesView.FocusedItem.Tag as FB2File;
         if (fc != null)
         {
             System.Diagnostics.Process.Start("explorer.exe", "/select,\"" + fc.FileInformation.DirectoryName + "\"");
         }
     }
 }
        private void PassHeaderDataFromFb2ToEpub(FB2File fb2File, IBookInformationData titleInformation)
        {
            Logger.Log.Debug("Passing header data from FB2 to EPUB");

            if (fb2File.MainBody == null)
            {
                throw new NullReferenceException("MainBody section of the file passed is null");
            }
            var headerDataConverter = new HeaderDataConverterV3(Settings.ConversionSettings, Settings.V3Settings);

            headerDataConverter.Convert(fb2File, titleInformation);
        }
        private void PassHeaderDataFromFb2ToEpub(FB2File fb2File, EPubFileV2 epubFile)
        {
            Logger.Log.Debug("Passing header data from FB2 to EPUB");

            if (fb2File.MainBody == null)
            {
                throw new NullReferenceException("MainBody section of the file passed is null");
            }

            var headerDataConverter = new HeaderDataConverterV2(Settings.ConversionSettings, Settings.V2Settings);

            headerDataConverter.Convert(fb2File, epubFile.BookInformation, epubFile.CalibreMetadata);
        }
Exemple #26
0
        public void Convert(FB2File fb2File, IBookInformationData titleInformation)
        {
            // Getting information from FB2 document section
            var bookId = new Identifier
            {
                ID =
                    !string.IsNullOrEmpty(fb2File.DocumentInfo.ID) ? fb2File.DocumentInfo.ID : Guid.NewGuid().ToString(),
                IdentifierName = "FB2BookID",
                Scheme         = "URI"
            };

            titleInformation.Identifiers.Add(bookId);
        }
        private void UpdateGroup(ListViewItem item)
        {
            FB2File fc        = item.Tag as FB2File;
            var     groupName = GetGroupName(fc, GetGroupType());

            ListViewGroup group = filesView.Groups[groupName.ToUpper()];

            if (group == null)
            {
                group = filesView.Groups.Add(groupName.ToUpper(), groupName);
            }
            item.Group = group;
        }
Exemple #28
0
        //Open book


        //Open book
        public async Task OpenBook()
        {
            var openDialog = new OpenFileDialog
            {
                InitialDirectory = "c:\\Projects\\MyLibReader\\MyLibReader\\Solution\\Books",
            };

            openDialog.ShowDialog();
            var path = openDialog.FileName;

            Book = await ReadFb2FileStreamAsync(File.OpenRead(path));

            //return file;  Task<FB2File>
        }
        private void copyToToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OverwriteDialog.Reset();
            RenameProfileElement pe = (sender as ToolStripMenuItem).Tag as RenameProfileElement;
            bool useTranslit        = (sender as ToolStripMenuItem).Text.StartsWith(Properties.Resources.TranslitMenuText);

            if (pe != null)
            {
                folderBrowserDialog.SelectedPath = Properties.Settings.Default.DefaultCopyToPath;
                if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    InProgress = true;
                    Properties.Settings.Default.DefaultCopyToPath = folderBrowserDialog.SelectedPath;
                    Properties.Settings.Default.Save();
                    foreach (ListViewItem item in filesView.CheckedItems)
                    {
                        FB2File fc      = item.Tag as FB2File;
                        string  oldName = fc.FileInformation.FullName;
                        try
                        {
                            var processed = fc.CopyTo(folderBrowserDialog.SelectedPath, pe, useTranslit);
                            if (!processed.Skipped)
                            {
                                LoadedFileIDs.Remove(oldName);
                                if (!LoadedFileIDs.ContainsKey(fc.FileInformation.FullName))
                                {
                                    LoadedFileIDs.Add(fc.FileInformation.FullName, string.Empty);
                                }
                                AddMessageRN(String.Format(Properties.Resources.CopyFileSuccess, oldName, fc.FileInformation.FullName));
                            }
                            else
                            {
                                AddErrorRN(String.Format(Properties.Resources.CopyFileSkipped, oldName, processed.NewFullName));
                            }
                        }
                        catch (Exception ex)
                        {
                            AddErrorRN(String.Format(Properties.Resources.CopyFileError, oldName, ex.Message));
                        }
                        UpdateItem(item);
                        if (CheckCancel())
                        {
                            break;
                        }
                    }
                    InProgress = false;
                }
            }
        }
        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);
            }
        }