public static string unzipEPubAndGetOpfPath(string EPUBFullPath) { //if (RequestCancellation) return; string parentDirectoryFullPath = Directory.GetParent(EPUBFullPath).ToString(); string unzipDirectory = Path.Combine( parentDirectoryFullPath, Path.GetFileNameWithoutExtension(EPUBFullPath) + "_ZIP" ); FileDataProvider.TryDeleteDirectory(unzipDirectory, true); ZipStorer zip = ZipStorer.Open(File.OpenRead(EPUBFullPath), FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { //if (RequestCancellation) return; //reportProgress_Throttle(-1, String.Format(UrakawaSDK_daisy_Lang.Unzipping, entry.FilenameInZip)); string unzippedFilePath = unzipDirectory + Path.DirectorySeparatorChar + entry.FilenameInZip; if (Path.GetExtension(unzippedFilePath).ToLower() == ".opf" || Path.GetExtension(unzippedFilePath).ToLower() == ".xml") { string unzippedFileDir = Path.GetDirectoryName(unzippedFilePath); if (!Directory.Exists(unzippedFileDir)) { FileDataProvider.CreateDirectory(unzippedFileDir); } zip.ExtractFile(entry, unzippedFilePath); } } zip.Dispose(); string containerPath = Path.Combine(unzipDirectory, @"META-INF" + Path.DirectorySeparatorChar + @"container.xml"); string opfFullPath = null; if (!File.Exists(containerPath)) { #if DEBUG Debugger.Break(); #endif DirectoryInfo dirInfo = new DirectoryInfo(unzipDirectory); FileInfo[] opfFiles = dirInfo.GetFiles("*.opf", SearchOption.AllDirectories); foreach (FileInfo fileInfo in opfFiles) { opfFullPath = Path.Combine(unzipDirectory, fileInfo.FullName); //m_OPF_ContainerRelativePath = null; break; } } else { //parseContainerXML(containerPath); XmlDocument containerDoc = XmlReaderWriterHelper.ParseXmlDocument(containerPath, false, false); XmlNode rootFileNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(containerDoc, true, @"rootfile", containerDoc.DocumentElement.NamespaceURI); #if DEBUG XmlNode mediaTypeAttr = rootFileNode.Attributes.GetNamedItem(@"media-type"); DebugFix.Assert(mediaTypeAttr != null && mediaTypeAttr.Value == @"application/oebps-package+xml"); #endif XmlNode fullPathAttr = rootFileNode.Attributes.GetNamedItem(@"full-path"); string rootDirectory = Path.GetDirectoryName(containerPath); rootDirectory = rootDirectory.Substring(0, rootDirectory.IndexOf(@"META-INF")); string OPF_ContainerRelativePath = FileDataProvider.UriDecode(fullPathAttr.Value); if (OPF_ContainerRelativePath.StartsWith(@"./")) { OPF_ContainerRelativePath = OPF_ContainerRelativePath.Substring(2); } opfFullPath = Path.Combine(rootDirectory, OPF_ContainerRelativePath.Replace('/', '\\')); } return(opfFullPath); }
protected virtual void parseContentDocuments(List <string> spineOfContentDocuments, Dictionary <string, string> spineAttributes, List <Dictionary <string, string> > spineItemsAttributes, string coverImagePath, string navDocPath) { if (spineOfContentDocuments == null || spineOfContentDocuments.Count <= 0) { return; } Presentation spinePresentation = m_Project.Presentations.Get(0); spinePresentation.RootNode.GetOrCreateXmlProperty().SetQName("spine", ""); if (!string.IsNullOrEmpty(m_OPF_ContainerRelativePath)) { spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute(OPF_ContainerRelativePath, "", m_OPF_ContainerRelativePath); } foreach (KeyValuePair <string, string> spineAttribute in spineAttributes) { spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute(spineAttribute.Key, "", spineAttribute.Value); } if (m_PackagePrefixAttr != null) { spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute("prefix", "", m_PackagePrefixAttr.Value); } // Audio files may be shared between chapters of a book! m_OriginalAudioFile_FileDataProviderMap.Clear(); Presentation spineItemPresentation = null; int index = -1; foreach (string docPath in spineOfContentDocuments) { index++; reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ReadXMLDoc, docPath)); //DirectoryInfo opfParentDir = Directory.GetParent(m_Book_FilePath); //string dirPath = opfParentDir.ToString(); string fullDocPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), docPath); fullDocPath = FileDataProvider.NormaliseFullFilePath(fullDocPath).Replace('/', '\\'); if (!File.Exists(fullDocPath)) { #if DEBUG Debugger.Break(); #endif //DEBUG continue; } addOPF_GlobalAssetPath(fullDocPath); TreeNode spineChild = spinePresentation.TreeNodeFactory.Create(); TextMedia txt = spinePresentation.MediaFactory.CreateTextMedia(); txt.Text = docPath; // Path.GetFileName(fullDocPath); spineChild.GetOrCreateChannelsProperty().SetMedia(spinePresentation.ChannelsManager.GetOrCreateTextChannel(), txt); spinePresentation.RootNode.AppendChild(spineChild); spineChild.GetOrCreateXmlProperty().SetQName("metadata", ""); foreach (KeyValuePair <string, string> spineItemAttribute in spineItemsAttributes[index]) { spineChild.GetOrCreateXmlProperty().SetAttribute(spineItemAttribute.Key, "", spineItemAttribute.Value); } string ext = Path.GetExtension(fullDocPath); if (docPath == coverImagePath) { DebugFix.Assert(ext.Equals(DataProviderFactory.IMAGE_SVG_EXTENSION, StringComparison.OrdinalIgnoreCase)); spineChild.GetOrCreateXmlProperty().SetAttribute("cover-image", "", "true"); } if (docPath == navDocPath) { DebugFix.Assert( ext.Equals(DataProviderFactory.XHTML_EXTENSION, StringComparison.OrdinalIgnoreCase) || ext.Equals(DataProviderFactory.HTML_EXTENSION, StringComparison.OrdinalIgnoreCase)); spineChild.GetOrCreateXmlProperty().SetAttribute("nav", "", "true"); } if ( !ext.Equals(DataProviderFactory.XHTML_EXTENSION, StringComparison.OrdinalIgnoreCase) && !ext.Equals(DataProviderFactory.HTML_EXTENSION, StringComparison.OrdinalIgnoreCase) && !ext.Equals(DataProviderFactory.DTBOOK_EXTENSION, StringComparison.OrdinalIgnoreCase) && !ext.Equals(DataProviderFactory.XML_EXTENSION, StringComparison.OrdinalIgnoreCase) ) { DebugFix.Assert(ext.Equals(DataProviderFactory.IMAGE_SVG_EXTENSION, StringComparison.OrdinalIgnoreCase)); bool notExistYet = true; foreach (ExternalFiles.ExternalFileData externalFileData in m_Project.Presentations.Get(0).ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable) { if (!string.IsNullOrEmpty(externalFileData.OriginalRelativePath)) { bool notExist = docPath != externalFileData.OriginalRelativePath; notExistYet = notExistYet && notExist; if (!notExist) { break; } } } DebugFix.Assert(notExistYet); if (notExistYet) { ExternalFiles.ExternalFileData externalData = null; if (docPath == coverImagePath) { externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.CoverImageExternalFileData>(); } else { externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.GenericExternalFileData>(); } if (externalData != null) { externalData.InitializeWithData(fullDocPath, docPath, true, null); addOPF_GlobalAssetPath(fullDocPath); } } continue; } spineChild.GetOrCreateXmlProperty().SetAttribute("xuk", "", "true"); XmlDocument xmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullDocPath, true, true); if (RequestCancellation) { return; } m_PublicationUniqueIdentifier = null; m_PublicationUniqueIdentifierNode = null; Project spineItemProject = new Project(); spineItemProject.PrettyFormat = m_XukPrettyFormat; string dataFolderPrefix = FileDataProvider.EliminateForbiddenFileNameCharacters(docPath); spineItemPresentation = spineItemProject.AddNewPresentation(new Uri(m_outDirectory), //Path.GetFileName(fullDocPath) dataFolderPrefix ); PCMFormatInfo pcmFormat = spineItemPresentation.MediaDataManager.DefaultPCMFormat; //.Copy(); pcmFormat.Data.SampleRate = (ushort)m_audioProjectSampleRate; pcmFormat.Data.NumberOfChannels = m_audioStereo ? (ushort)2 : (ushort)1; spineItemPresentation.MediaDataManager.DefaultPCMFormat = pcmFormat; //presentation.MediaDataManager.EnforceSinglePCMFormat = true; //presentation.MediaDataFactory.DefaultAudioMediaDataType = typeof(WavAudioMediaData); TextChannel textChannel = spineItemPresentation.ChannelFactory.CreateTextChannel(); textChannel.Name = "The Text Channel"; DebugFix.Assert(textChannel == spineItemPresentation.ChannelsManager.GetOrCreateTextChannel()); AudioChannel audioChannel = spineItemPresentation.ChannelFactory.CreateAudioChannel(); audioChannel.Name = "The Audio Channel"; DebugFix.Assert(audioChannel == spineItemPresentation.ChannelsManager.GetOrCreateAudioChannel()); ImageChannel imageChannel = spineItemPresentation.ChannelFactory.CreateImageChannel(); imageChannel.Name = "The Image Channel"; DebugFix.Assert(imageChannel == spineItemPresentation.ChannelsManager.GetOrCreateImageChannel()); VideoChannel videoChannel = spineItemPresentation.ChannelFactory.CreateVideoChannel(); videoChannel.Name = "The Video Channel"; DebugFix.Assert(videoChannel == spineItemPresentation.ChannelsManager.GetOrCreateVideoChannel()); /*string dataPath = presentation.DataProviderManager.DataFileDirectoryFullPath; * if (Directory.Exists(dataPath)) * { * Directory.Delete(dataPath, true); * }*/ //AudioLibPCMFormat previousPcm = null; if (m_AudioConversionSession != null) { //previousPcm = m_AudioConversionSession.FirstDiscoveredPCMFormat; RemoveSubCancellable(m_AudioConversionSession); m_AudioConversionSession = null; } m_AudioConversionSession = new AudioFormatConvertorSession( //AudioFormatConvertorSession.TEMP_AUDIO_DIRECTORY, spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath, spineItemPresentation.MediaDataManager.DefaultPCMFormat, m_autoDetectPcmFormat, m_SkipACM); //if (previousPcm != null) //{ // m_AudioConversionSession.FirstDiscoveredPCMFormat = previousPcm; //} AddSubCancellable(m_AudioConversionSession); TreenodesWithoutManagedAudioMediaData = new List <TreeNode>(); //foreach (var key in m_OriginalAudioFile_FileDataProviderMap.Keys) //{ // FileDataProvider dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); //VERSUS// // FileDataProvider dataProv = new FileDataProvider(); // dataProv.MimeType = DataProviderFactory.AUDIO_WAV_MIME_TYPE; //} //m_Project.Presentations.Get(0).ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable if (RequestCancellation) { return; } if (parseContentDocParts(fullDocPath, spineItemProject, xmlDoc, docPath, DocumentMarkupType.NA)) { return; // user cancel } //if (RequestCancellation) return; //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMetadata, docPath)); //parseMetadata(fullDocPath, project, xmlDoc); //if (RequestCancellation) return; //ParseHeadLinks(fullDocPath, project, xmlDoc); //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingContent, docPath)); //parseContentDocument(fullDocPath, project, xmlDoc, null, fullDocPath, null, DocumentMarkupType.NA); string title = GetTitle(spineItemPresentation); if (!string.IsNullOrEmpty(title)) { spineChild.GetOrCreateXmlProperty().SetAttribute("title", "", title); } if (false) // do not copy metadata from project to individual chapter { foreach (Metadata metadata in m_Project.Presentations.Get(0).Metadatas.ContentsAs_Enumerable) { Metadata md = spineItemPresentation.MetadataFactory.CreateMetadata(); md.NameContentAttribute = metadata.NameContentAttribute.Copy(); foreach (MetadataAttribute metadataAttribute in metadata.OtherAttributes.ContentsAs_Enumerable) { MetadataAttribute mdAttr = metadataAttribute.Copy(); md.OtherAttributes.Insert(md.OtherAttributes.Count, mdAttr); } spineItemPresentation.Metadatas.Insert(spineItemPresentation.Metadatas.Count, md); } } //XmlNodeList listOfBodies = xmlDoc.GetElementsByTagName("body"); //if (listOfBodies.Count == 0) //{ // listOfBodies = xmlDoc.GetElementsByTagName("book"); //} //XmlNode bodyElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc, true, "body", null); //if (bodyElement == null) //{ // bodyElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc, true, "book", null); //} //if (bodyElement == null) //{ // continue; //} // TODO: return hierarchical outline where each node points to a XUK relative path, + XukAble.Uid (TreeNode are not corrupted during XukAbleManager.RegenerateUids(); foreach (KeyValuePair <string, string> spineItemAttribute in spineItemsAttributes[index]) { if (spineItemAttribute.Key == "media-overlay") { string opfDirPath = Path.GetDirectoryName(m_Book_FilePath); string overlayPath = spineItemAttribute.Value; reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMediaOverlay, overlayPath)); string fullOverlayPath = Path.Combine(opfDirPath, overlayPath); if (!File.Exists(fullOverlayPath)) { continue; } XmlDocument overlayXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullOverlayPath, false, false); IEnumerable <XmlNode> audioElements = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(overlayXmlDoc, true, "audio", null, false); if (audioElements == null) { continue; } foreach (XmlNode audioNode in audioElements) { XmlAttributeCollection attrs = audioNode.Attributes; if (attrs == null) { continue; } XmlNode attrSrc = attrs.GetNamedItem("src"); if (attrSrc == null) { continue; } //XmlNode attrBegin = attrs.GetNamedItem("clipBegin"); //XmlNode attrEnd = attrs.GetNamedItem("clipEnd"); //string overlayDirPath = Path.GetDirectoryName(fullOverlayPath); //string fullAudioPath = Path.Combine(overlayDirPath, attrSrc.Value); //if (!File.Exists(fullAudioPath)) //{ // continue; //} //if (RequestCancellation) return; //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.DecodingAudio, Path.GetFileName(fullAudioPath))); TreeNode textTreeNode = null; XmlNodeList children = audioNode.ParentNode.ChildNodes; foreach (XmlNode child in children) { if (child == audioNode) { continue; } if (child.LocalName != "text") { continue; } XmlAttributeCollection textAttrs = child.Attributes; if (textAttrs == null) { continue; } XmlNode textSrc = textAttrs.GetNamedItem("src"); if (textSrc == null) { continue; } string urlDecoded = FileDataProvider.UriDecode(textSrc.Value); if (urlDecoded.IndexOf('#') > 0) { string[] srcParts = urlDecoded.Split('#'); if (srcParts.Length != 2) { continue; } string fullTextRefPath = Path.Combine(Path.GetDirectoryName(fullOverlayPath), srcParts[0]); fullTextRefPath = FileDataProvider.NormaliseFullFilePath(fullTextRefPath).Replace('/', '\\'); if (!fullTextRefPath.Equals(fullDocPath, StringComparison.OrdinalIgnoreCase)) { //#if DEBUG // Debugger.Break(); //#endif //DEBUG continue; } string txtId = srcParts[1]; textTreeNode = spineItemPresentation.RootNode.GetFirstDescendantWithXmlID(txtId); } else { string fullTextRefPath = Path.Combine(Path.GetDirectoryName(fullOverlayPath), urlDecoded); fullTextRefPath = FileDataProvider.NormaliseFullFilePath(fullTextRefPath).Replace('/', '\\'); if (!fullTextRefPath.Equals(fullDocPath, StringComparison.OrdinalIgnoreCase)) { //#if DEBUG // Debugger.Break(); //#endif //DEBUG continue; } textTreeNode = spineItemPresentation.RootNode; } } if (textTreeNode != null) { addAudio(textTreeNode, audioNode, false, fullOverlayPath); } } } } spinePresentation.MediaDataManager.DefaultPCMFormat = spineItemPresentation.MediaDataManager.DefaultPCMFormat; //copied! string xuk_FilePath = GetXukFilePath_SpineItem(m_outDirectory, docPath, title, index); string xukFileName = Path.GetFileName(xuk_FilePath); spineChild.GetOrCreateXmlProperty().SetAttribute("xukFileName", "", xukFileName); //deleteDataDirectoryIfEmpty(); string dataFolderPath = spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath; spineItemPresentation.DataProviderManager.SetCustomDataFileDirectory(Path.GetFileNameWithoutExtension(xuk_FilePath)); string newDataFolderPath = spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath; DebugFix.Assert(Directory.Exists(newDataFolderPath)); if (newDataFolderPath != dataFolderPath) { try { if (Directory.Exists(newDataFolderPath)) { FileDataProvider.TryDeleteDirectory(newDataFolderPath, false); } Directory.Move(dataFolderPath, newDataFolderPath); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif // DEBUG Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); spineItemPresentation.DataProviderManager.SetCustomDataFileDirectory(dataFolderPrefix); } } spineItemProject.PrettyFormat = m_XukPrettyFormat; SaveXukAction action = new SaveXukAction(spineItemProject, spineItemProject, new Uri(xuk_FilePath), true); action.ShortDescription = UrakawaSDK_daisy_Lang.SavingXUKFile; action.LongDescription = UrakawaSDK_daisy_Lang.SerializeDOMIntoXUKFile; action.Progress += new EventHandler <ProgressEventArgs>( delegate(object sender, ProgressEventArgs e) { double val = e.Current; double max = e.Total; int percent = -1; if (val != max) { percent = (int)((val / max) * 100); } reportProgress_Throttle(percent, val + "/" + max); //reportProgress(-1, action.LongDescription); if (RequestCancellation) { e.Cancel(); } } ); action.Finished += new EventHandler <FinishedEventArgs>( delegate(object sender, FinishedEventArgs e) { reportProgress(100, UrakawaSDK_daisy_Lang.XUKSaved); } ); action.Cancelled += new EventHandler <CancelledEventArgs>( delegate(object sender, CancelledEventArgs e) { reportProgress(0, UrakawaSDK_daisy_Lang.CancelledXUKSaving); } ); action.DoWork(); //if (first) //{ // Presentation presentation = m_Project.Presentations.Get(0); // XmlProperty xmlProp = presentation.PropertyFactory.CreateXmlProperty(); // xmlProp.LocalName = "book"; // presentation.PropertyFactory.DefaultXmlNamespaceUri = bodyElement.NamespaceURI; // xmlProp.NamespaceUri = presentation.PropertyFactory.DefaultXmlNamespaceUri; // TreeNode treeNode = presentation.TreeNodeFactory.Create(); // treeNode.AddProperty(xmlProp); // presentation.RootNode = treeNode; // first = false; //} //foreach (XmlNode childOfBody in bodyElement.ChildNodes) //{ // parseContentDocument(childOfBody, m_Project.Presentations.Get(0).RootNode, fullDocPath); //} } }
private void unzipEPubAndParseOpf() { if (RequestCancellation) { return; } /*string directoryName = Path.GetTempPath(); * if (!directoryName.EndsWith("" + Path.DirectorySeparatorChar)) * { * directoryName += Path.DirectorySeparatorChar; * }*/ string unzipDirectory = Path.Combine( Path.GetDirectoryName(m_Book_FilePath), //m_outDirectory, //FileDataProvider.EliminateForbiddenFileNameCharacters(m_Book_FilePath) //m_Book_FilePath.Replace('.', '_') m_Book_FilePath + "_ZIP" ); FileDataProvider.TryDeleteDirectory(unzipDirectory, true); #if ENABLE_SHARPZIP ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(m_Book_FilePath)); ZipEntry zipEntry; while ((zipEntry = zipInputStream.GetNextEntry()) != null) { if (RequestCancellation) { return; } string zipEntryName = Path.GetFileName(zipEntry.Name); if (!String.IsNullOrEmpty(zipEntryName)) // || zipEntryName.IndexOf(".ini") >= 0 { // string unzippedFilePath = Path.Combine(unzipDirectory, zipEntryName); string unzippedFilePath = unzipDirectory + Path.DirectorySeparatorChar + zipEntry.Name; string unzippedFileDir = Path.GetDirectoryName(unzippedFilePath); if (!Directory.Exists(unzippedFileDir)) { FileDataProvider.CreateDirectory(unzippedFileDir); } FileStream fileStream = File.Create(unzippedFilePath); //byte[] data = new byte[2 * 1024]; // 2 KB buffer //int bytesRead = 0; try { const uint BUFFER_SIZE = 1024 * 2; // 2 KB MAX BUFFER StreamUtils.Copy(zipInputStream, 0, fileStream, BUFFER_SIZE); //while ((bytesRead = zipInputStream.Read(data, 0, data.Length)) > 0) //{ // fileStream.Write(data, 0, bytesRead); //} } finally { fileStream.Close(); } } } zipInputStream.Close(); #else //ENABLE_SHARPZIP ZipStorer zip = ZipStorer.Open(File.OpenRead(m_Book_FilePath), FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { if (RequestCancellation) { return; } reportProgress_Throttle(-1, String.Format(UrakawaSDK_daisy_Lang.Unzipping, entry.FilenameInZip)); string unzippedFilePath = unzipDirectory + Path.DirectorySeparatorChar + entry.FilenameInZip; string unzippedFileDir = Path.GetDirectoryName(unzippedFilePath); if (!Directory.Exists(unzippedFileDir)) { FileDataProvider.CreateDirectory(unzippedFileDir); } zip.ExtractFile(entry, unzippedFilePath); } //zip.Close(); zip.Dispose(); #endif //ENABLE_SHARPZIP string containerPath = Path.Combine(unzipDirectory, @"META-INF" + Path.DirectorySeparatorChar + @"container.xml"); if (!File.Exists(containerPath)) { #if DEBUG Debugger.Break(); #endif DirectoryInfo dirInfo = new DirectoryInfo(unzipDirectory); #if NET40 IEnumerable <FileInfo> opfFiles = dirInfo.EnumerateFiles("*.opf", SearchOption.AllDirectories); #else FileInfo[] opfFiles = dirInfo.GetFiles("*.opf", SearchOption.AllDirectories); #endif // string[] fileNames = Directory.GetFiles(unzipDirectory, "*.opf", //#if NET40 // SearchOption.AllDirectories //#endif // ); foreach (FileInfo fileInfo in opfFiles) { if (RequestCancellation) { return; } m_Book_FilePath = Path.Combine(unzipDirectory, fileInfo.FullName); m_OPF_ContainerRelativePath = null; openAndParseOPF(m_Book_FilePath); break; } } else { parseContainerXML(containerPath); } // string opfPath = ""; // string parentDir = Path.GetDirectoryName(opfPath); // while (!string.IsNullOrEmpty(parentDir)) // { // DirectoryInfo dirInfo = new DirectoryInfo(parentDir); // DirectoryInfo[] metaInfDirs = dirInfo.GetDirectories(@"META-INF", SearchOption.TopDirectoryOnly); // if (RequestCancellation) return; // foreach (DirectoryInfo dirInfo in metaInfDirs) // { // string containerPath = Path.Combine(parentDir, dirInfo.FullName + Path.DirectorySeparatorChar + @"container.xml"); // if (!File.Exists(containerPath)) // { //#if DEBUG // Debugger.Break(); //#endif // } // else // { // if (!parseContainerXML(containerPath)) // { // openAndParseOPF(opfPath); // } // } // break; // } // DirectoryInfo parentDirInfo = dirInfo.Parent; // if (parentDirInfo != null) // { // parentDir = parentDirInfo.FullName; // } // else // { // parentDir = null; // } // } // // final fallback // openAndParseOPF(opfPath); }
private bool doImport() { m_Logger.Log(String.Format(@"UrakawaSession.doImport() [{0}]", DocumentFilePath), Category.Debug, Priority.Medium); string ext = Path.GetExtension(DocumentFilePath); if (".opf".Equals(ext, StringComparison.OrdinalIgnoreCase)) { int levelsUp = 0; string parentDir = Path.GetDirectoryName(DocumentFilePath); DirectoryInfo parentDirInfo = new DirectoryInfo(parentDir); tryAgain: levelsUp++; #if NET40 IEnumerable <DirectoryInfo> metaInfDirs = parentDirInfo.EnumerateDirectories("META-INF", SearchOption.TopDirectoryOnly); #else DirectoryInfo[] metaInfDirs = parentDirInfo.GetDirectories("META-INF", SearchOption.TopDirectoryOnly); #endif bool found = false; foreach (DirectoryInfo dirInfo in metaInfDirs) { string containerXml = Path.Combine(dirInfo.FullName, "container.xml"); if (File.Exists(containerXml)) { DocumentFilePath = containerXml; ext = Path.GetExtension(DocumentFilePath); found = true; break; } } if (!found && levelsUp <= 2 && parentDirInfo.Parent != null) { parentDirInfo = parentDirInfo.Parent; goto tryAgain; } } if (DataProviderFactory.EPUB_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase)) { checkEpub(DocumentFilePath, null); } else if (DataProviderFactory.XML_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase) && FileDataProvider.NormaliseFullFilePath(DocumentFilePath).IndexOf( @"META-INF" //+ Path.DirectorySeparatorChar + '/' + @"container.xml" , StringComparison.OrdinalIgnoreCase) >= 0 //DocumentFilePath.IndexOf("container.xml", StringComparison.OrdinalIgnoreCase) >= 0 ) { string parentDir = Path.GetDirectoryName(DocumentFilePath); DirectoryInfo dirInfo = new DirectoryInfo(parentDir); if (dirInfo.Parent != null) { string checkEpubPath = dirInfo.Parent.FullName; checkEpub(checkEpubPath, "exp"); } } else if (".opf".Equals(ext, StringComparison.OrdinalIgnoreCase)) { if (!checkDAISY(DocumentFilePath)) { //checkEpub(DocumentFilePath, "opf"); assume container.xml was found (see above) } } else if (DataProviderFactory.HTML_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase) || DataProviderFactory.XHTML_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase)) { //MessageBox.Show messageBoxAlert("WARNING: single HTML import is an experimental and incomplete EPUB feature!", null); checkEpub(DocumentFilePath, "xhtml"); } else if (DataProviderFactory.XML_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase)) { //checkDAISY(DocumentFilePath); if (false && // TODO: Pipeline 2 with better support for DTBOOK validation (currently skips metadata values) askUser("DAISY Check?", DocumentFilePath)) { string pipeline_ExePath = obtainPipelineExe(); if (!string.IsNullOrEmpty(pipeline_ExePath)) { string outDir = Path.GetDirectoryName(DocumentFilePath); outDir = Path.Combine(outDir, Path.GetFileName(DocumentFilePath) + "_PIPEVAL"); bool success = false; Func <String, String> checkErrorsOrWarning = (string report) => { if (report.IndexOf("[DP2] DONE", StringComparison.Ordinal) < 0) { return("Pipeline job doesn't appear to have completed?"); } string reportFile = Path.Combine(outDir, "report.xhtml"); if (File.Exists(reportFile)) { string reportXmlSource = File.ReadAllText(reportFile); if (!string.IsNullOrEmpty(reportXmlSource)) { string xmlInfo = ""; XmlDocument xmlDoc = XmlReaderWriterHelper.ParseXmlDocumentFromString(reportXmlSource, false, false); IEnumerable <XmlNode> lis = XmlDocumentHelper.GetChildrenElementsOrSelfWithName( xmlDoc.DocumentElement, true, "li", null, false); foreach (XmlNode li in lis) { if (li.Attributes == null) { continue; } XmlNode classAttr = li.Attributes.GetNamedItem("class"); if (classAttr == null || classAttr.Value != "error") { continue; } xmlInfo += li.InnerText; xmlInfo += Environment.NewLine; } if (string.IsNullOrEmpty(xmlInfo)) { success = true; return(null); } return(xmlInfo); } } success = true; return(null); }; try { string workingDir = Path.GetDirectoryName(pipeline_ExePath); //Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); executeProcess( workingDir, "DAISY Pipeline (validation)", //"\"" + pipeline_ExePath //+ "\"" , "dtbook-validator " + "--i-source \"" + DocumentFilePath + "\" " + "--x-output-dir \"" + outDir + "\" ", checkErrorsOrWarning); } catch (Exception ex) { messageBoxText("Oops :(", "Problem running DAISY Pipeline (validation)!", ex.Message + Environment.NewLine + ex.StackTrace); } if (Directory.Exists(outDir)) { //m_ShellView.ExecuteShellProcess(outDir); FileDataProvider.TryDeleteDirectory(outDir, false); } } } } string outputDirectory = Path.Combine( Path.GetDirectoryName(DocumentFilePath), Daisy3_Import.GetXukDirectory(DocumentFilePath)); //string xukPath = Daisy3_Import.GetXukFilePath(outputDirectory, DocumentFilePath); //if (File.Exists(xukPath)) if (Directory.Exists(outputDirectory)) { if (!askUserConfirmOverwriteFileFolder(outputDirectory, true, null)) { return(false); } FileDataProvider.TryDeleteDirectory(outputDirectory, true); } var combo = new ComboBox { Margin = new Thickness(0, 0, 0, 0), HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Center, }; ComboBoxItem item1 = new ComboBoxItem(); item1.Content = AudioLib.SampleRate.Hz11025.ToString(); combo.Items.Add(item1); ComboBoxItem item2 = new ComboBoxItem(); item2.Content = AudioLib.SampleRate.Hz22050.ToString(); combo.Items.Add(item2); ComboBoxItem item3 = new ComboBoxItem(); item3.Content = AudioLib.SampleRate.Hz44100.ToString(); combo.Items.Add(item3); switch (Settings.Default.AudioProjectSampleRate) { case AudioLib.SampleRate.Hz11025: { combo.SelectedItem = item1; combo.Text = item1.Content.ToString(); break; } case AudioLib.SampleRate.Hz22050: { combo.SelectedItem = item2; combo.Text = item2.Content.ToString(); break; } case AudioLib.SampleRate.Hz44100: { combo.SelectedItem = item3; combo.Text = item3.Content.ToString(); break; } } var label_ = new TextBlock { Text = Tobi_Plugin_Urakawa_Lang.Stereo, Margin = new Thickness(0, 0, 8, 0), HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Focusable = true, TextWrapping = TextWrapping.Wrap }; var checkBox = new CheckBox { IsThreeState = false, IsChecked = Settings.Default.AudioProjectStereo, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, }; var panel__ = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 8, 0, 22), }; panel__.Children.Add(label_); panel__.Children.Add(checkBox); var label = new TextBlock { Text = Tobi_Plugin_Urakawa_Lang.UseSourceAudioFormat, Margin = new Thickness(0, 0, 8, 0), HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Focusable = true, TextWrapping = TextWrapping.Wrap }; var checkAuto = new CheckBox { IsThreeState = false, IsChecked = false, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, }; var panel_ = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 0, 12), }; panel_.Children.Add(label); panel_.Children.Add(checkAuto); var panel = new StackPanel { Orientation = Orientation.Vertical, HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Center, }; panel.Children.Add(combo); panel.Children.Add(panel__); panel.Children.Add(panel_); //var line = new Separator() //{ // Margin = new Thickness(0, 8, 0, 8), //}; //line.HorizontalAlignment = HorizontalAlignment.Stretch; //line.VerticalAlignment = VerticalAlignment.Center; //panel.Children.Add(line); var details = new TextBoxReadOnlyCaretVisible { FocusVisualStyle = (Style)Application.Current.Resources["MyFocusVisualStyle"], BorderThickness = new Thickness(1), Padding = new Thickness(6), TextReadOnly = Tobi_Plugin_Urakawa_Lang.UseSourceAudioFormatTip }; var windowPopup = new PopupModalWindow(m_ShellView, UserInterfaceStrings.EscapeMnemonic(Tobi_Plugin_Urakawa_Lang.ProjectAudioFormat), panel, PopupModalWindow.DialogButtonsSet.OkCancel, PopupModalWindow.DialogButton.Ok, false, 320, 200, details, 40, null); windowPopup.EnableEnterKeyDefault = true; windowPopup.ShowModal(); if (!PopupModalWindow.IsButtonOkYesApply(windowPopup.ClickedDialogButton)) { return(false); } Settings.Default.AudioProjectStereo = checkBox.IsChecked.Value; if (combo.SelectedItem == item1) { Settings.Default.AudioProjectSampleRate = SampleRate.Hz11025; } else if (combo.SelectedItem == item2) { Settings.Default.AudioProjectSampleRate = SampleRate.Hz22050; } else if (combo.SelectedItem == item3) { Settings.Default.AudioProjectSampleRate = SampleRate.Hz44100; } var converter = new Daisy3_Import(DocumentFilePath, outputDirectory, IsAcmCodecsDisabled, Settings.Default.AudioProjectSampleRate, Settings.Default.AudioProjectStereo, checkAuto.IsChecked.Value, Settings.Default.XUK_PrettyFormat ); //Directory.GetParent(bookfile).FullName //converter.VerifyHtml5OutliningAlgorithmUsingPipelineTestSuite(); bool cancelled = false; bool error = m_ShellView.RunModalCancellableProgressTask(true, Tobi_Plugin_Urakawa_Lang.Importing, converter, () => { cancelled = true; DocumentFilePath = null; DocumentProject = null; }, () => { cancelled = false; if (string.IsNullOrEmpty(converter.XukPath)) { return; } //DocumentFilePath = converter.XukPath; //DocumentProject = converter.Project; //AddRecentFile(new Uri(DocumentFilePath, UriKind.Absolute)); }); if (!cancelled) { //DebugFix.Assert(!report); string xukPath = converter.XukPath; if (string.IsNullOrEmpty(xukPath)) { return(false); } string projectDir = Path.GetDirectoryName(xukPath); DebugFix.Assert(outputDirectory == projectDir); string title = converter.GetTitle(); if (!string.IsNullOrEmpty(title)) { string fileName = Daisy3_Import.GetXukFilePath(projectDir, DocumentFilePath, title, false); fileName = Path.GetFileNameWithoutExtension(fileName); string parent = Path.GetDirectoryName(projectDir); //string fileName = Path.GetFileNameWithoutExtension(xukPath); ////while (fileName.StartsWith("_")) ////{ //// fileName = fileName.Substring(1, fileName.Length - 1); ////} //char[] chars = new char[] { '_' }; //fileName = fileName.TrimStart(chars); string newProjectDir = Path.Combine(parent, fileName); // + Daisy3_Import.XUK_DIR if (newProjectDir != projectDir) { bool okay = true; if (Directory.Exists(newProjectDir)) { if (askUserConfirmOverwriteFileFolder(newProjectDir, true, null)) { try { FileDataProvider.TryDeleteDirectory(newProjectDir, false); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif // DEBUG Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); okay = false; } } else { okay = false; } } if (okay) { Directory.Move(projectDir, newProjectDir); xukPath = Path.Combine(newProjectDir, Path.GetFileName(xukPath)); } } } DocumentFilePath = null; DocumentProject = null; try { OpenFile(xukPath); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, m_ShellView); return(false); } } return(!cancelled); }
private void OnClick_ButtonExport(object sender, RoutedEventArgs e) { m_Logger.Log("DescriptionView.OnClick_ButtonExport", Category.Debug, Priority.Medium); Tuple <TreeNode, TreeNode> selection = m_Session.GetTreeNodeSelection(); TreeNode node = selection.Item2 ?? selection.Item1; if (node == null || node.GetAlternateContentProperty() == null || node.GetImageMedia() == null || !(node.GetImageMedia() is ManagedImageMedia)) { return; } SampleRate sampleRate = SampleRate.Hz22050; sampleRate = Urakawa.Settings.Default.AudioExportSampleRate; bool encodeToMp3 = true; encodeToMp3 = Urakawa.Settings.Default.AudioExportEncodeToMp3; var combo = new ComboBox { Margin = new Thickness(0, 0, 0, 12) }; ComboBoxItem item1 = new ComboBoxItem(); item1.Content = AudioLib.SampleRate.Hz11025.ToString(); combo.Items.Add(item1); ComboBoxItem item2 = new ComboBoxItem(); item2.Content = AudioLib.SampleRate.Hz22050.ToString(); combo.Items.Add(item2); ComboBoxItem item3 = new ComboBoxItem(); item3.Content = AudioLib.SampleRate.Hz44100.ToString(); combo.Items.Add(item3); switch (sampleRate) { case AudioLib.SampleRate.Hz11025: { combo.SelectedItem = item1; combo.Text = item1.Content.ToString(); break; } case AudioLib.SampleRate.Hz22050: { combo.SelectedItem = item2; combo.Text = item2.Content.ToString(); break; } case AudioLib.SampleRate.Hz44100: { combo.SelectedItem = item3; combo.Text = item3.Content.ToString(); break; } } var checkBox = new CheckBox { IsThreeState = false, IsChecked = encodeToMp3, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, }; var label_ = new TextBlock { Text = Tobi_Plugin_Urakawa_Lang.ExportEncodeMp3, Margin = new Thickness(8, 0, 8, 0), HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Focusable = true, TextWrapping = TextWrapping.Wrap }; var panel__ = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, }; panel__.Children.Add(label_); panel__.Children.Add(checkBox); var panel_ = new StackPanel { Orientation = System.Windows.Controls.Orientation.Vertical, HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Center, }; panel_.Children.Add(combo); panel_.Children.Add(panel__); var windowPopup_ = new PopupModalWindow(m_ShellView, UserInterfaceStrings.EscapeMnemonic(Tobi_Plugin_Urakawa_Lang.ExportSettings), panel_, PopupModalWindow.DialogButtonsSet.OkCancel, PopupModalWindow.DialogButton.Ok, false, 300, 180, null, 40, m_DescriptionPopupModalWindow); windowPopup_.EnableEnterKeyDefault = true; windowPopup_.ShowModal(); if (!PopupModalWindow.IsButtonOkYesApply(windowPopup_.ClickedDialogButton)) { return; } encodeToMp3 = checkBox.IsChecked.Value; Urakawa.Settings.Default.AudioExportEncodeToMp3 = checkBox.IsChecked.Value; if (combo.SelectedItem == item1) { sampleRate = SampleRate.Hz11025; Urakawa.Settings.Default.AudioExportSampleRate = sampleRate; } else if (combo.SelectedItem == item2) { sampleRate = SampleRate.Hz22050; Urakawa.Settings.Default.AudioExportSampleRate = sampleRate; } else if (combo.SelectedItem == item3) { sampleRate = SampleRate.Hz44100; Urakawa.Settings.Default.AudioExportSampleRate = sampleRate; } string rootFolder = Path.GetDirectoryName(m_Session.DocumentFilePath); var dlg = new FolderBrowserDialog { RootFolder = Environment.SpecialFolder.MyComputer, SelectedPath = rootFolder, ShowNewFolderButton = true, Description = @"Tobi: " + UserInterfaceStrings.EscapeMnemonic("Export DIAGRAM XML") }; DialogResult result = DialogResult.Abort; m_ShellView.DimBackgroundWhile(() => { result = dlg.ShowDialog(); }); if (result != DialogResult.OK && result != DialogResult.Yes) { return; } if (!Directory.Exists(dlg.SelectedPath)) { return; } ManagedImageMedia managedImage = (ManagedImageMedia)node.GetImageMedia(); string exportImageName = //Path.GetFileName FileDataProvider.EliminateForbiddenFileNameCharacters (managedImage.ImageMediaData.OriginalRelativePath) ; string imageDescriptionDirectoryPath = Daisy3_Export.GetAndCreateImageDescriptionDirectoryPath(false, exportImageName, dlg.SelectedPath); if (Directory.Exists(imageDescriptionDirectoryPath)) { if (!m_Session.askUserConfirmOverwriteFileFolder(imageDescriptionDirectoryPath, true, m_DescriptionPopupModalWindow)) { return; } FileDataProvider.TryDeleteDirectory(imageDescriptionDirectoryPath, true); } FileDataProvider.CreateDirectory(imageDescriptionDirectoryPath); PCMFormatInfo audioFormat = node.Presentation.MediaDataManager.DefaultPCMFormat; AudioLibPCMFormat pcmFormat = audioFormat.Data; if ((ushort)sampleRate != pcmFormat.SampleRate) { pcmFormat.SampleRate = (ushort)sampleRate; } Application.Current.MainWindow.Cursor = Cursors.Wait; this.Cursor = Cursors.Wait; //m_ShellView try { string descriptionFile = Daisy3_Export.CreateImageDescription( Urakawa.Settings.Default.AudioCodecDisableACM, pcmFormat, encodeToMp3, 0, imageDescriptionDirectoryPath, exportImageName, node.GetAlternateContentProperty(), null, null, null); } finally { Application.Current.MainWindow.Cursor = Cursors.Arrow; this.Cursor = Cursors.Arrow; //m_ShellView } m_ShellView.ExecuteShellProcess(imageDescriptionDirectoryPath); }
public override void DoWork() { if (RequestCancellation) { return; } initializeProject(Path.GetFileName(m_Book_FilePath)); try { transformBook(); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif throw new Exception("Import", ex); } reportProgress(-1, UrakawaSDK_daisy_Lang.SaveXUK); if (RequestCancellation) { return; } //m_Project.SaveXuk(new Uri(m_Xuk_FilePath)); if (IsRenameOfProjectFileAndDirsAllowedAfterImport && m_useTitleInFileName) { string title = GetTitle(m_Project.Presentations.Get(0)); if (!string.IsNullOrEmpty(title)) { string originalXukFilePath = m_Xuk_FilePath; m_Xuk_FilePath = GetXukFilePath(m_outDirectory, m_Book_FilePath, title, m_IsSpine); //deleteDataDirectoryIfEmpty(); //m_Project.Presentations.Get(0).DataProviderManager.SetDataFileDirectoryWithPrefix(Path.GetFileNameWithoutExtension(m_Xuk_FilePath)); Presentation presentation = m_Project.Presentations.Get(0); string dataFolderPath = presentation.DataProviderManager.DataFileDirectoryFullPath; presentation.DataProviderManager.SetCustomDataFileDirectory(Path.GetFileNameWithoutExtension(m_Xuk_FilePath)); string newDataFolderPath = presentation.DataProviderManager.DataFileDirectoryFullPath; DebugFix.Assert(Directory.Exists(newDataFolderPath)); if (newDataFolderPath != dataFolderPath) { try { if (Directory.Exists(newDataFolderPath)) { FileDataProvider.TryDeleteDirectory(newDataFolderPath, false); } Directory.Move(dataFolderPath, newDataFolderPath); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif // DEBUG Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); presentation.DataProviderManager.SetCustomDataFileDirectory(m_dataFolderPrefix); } } } }// end of rename code m_Project.PrettyFormat = m_XukPrettyFormat; SaveXukAction action = new SaveXukAction(m_Project, m_Project, new Uri(m_Xuk_FilePath), true); action.ShortDescription = UrakawaSDK_daisy_Lang.SavingXUKFile; action.LongDescription = UrakawaSDK_daisy_Lang.SerializeDOMIntoXUKFile; action.Progress += new EventHandler <urakawa.events.progress.ProgressEventArgs>( delegate(object sender, ProgressEventArgs e) { double val = e.Current; double max = e.Total; int percent = -1; if (val != max) { percent = (int)((val / max) * 100); } reportProgress_Throttle(percent, val + "/" + max); //reportProgress(-1, action.LongDescription); if (RequestCancellation) { e.Cancel(); } } ); action.Finished += new EventHandler <FinishedEventArgs>( delegate(object sender, FinishedEventArgs e) { reportProgress(100, UrakawaSDK_daisy_Lang.XUKSaved); } ); action.Cancelled += new EventHandler <CancelledEventArgs>( delegate(object sender, CancelledEventArgs e) { reportProgress(0, UrakawaSDK_daisy_Lang.CancelledXUKSaving); } ); action.DoWork(); if (RequestCancellation) { m_Xuk_FilePath = null; m_Project = null; } }