Пример #1
0
        protected XmlDocument CreateStub_NcxDocument()
        {
            XmlDocument NcxDocument = new XmlDocument();

            NcxDocument.XmlResolver = null;

            NcxDocument.CreateXmlDeclaration("1.0", "utf-8", null);
            NcxDocument.AppendChild(NcxDocument.CreateDocumentType("ncx",
                                                                   "-//NISO//DTD ncx 2005-1//EN",
                                                                   "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd",
                                                                   null));

            XmlNode rootNode = NcxDocument.CreateElement(null,
                                                         "ncx",
                                                         "http://www.daisy.org/z3986/2005/ncx/");

            NcxDocument.AppendChild(rootNode);


            XmlDocumentHelper.CreateAppendXmlAttribute(NcxDocument, rootNode, "version", "2005-1");
            XmlDocumentHelper.CreateAppendXmlAttribute(NcxDocument, rootNode,
                                                       XmlReaderWriterHelper.XmlLang,
                                                       (string.IsNullOrEmpty(m_Presentation.Language)
                ? "en-US"
                : m_Presentation.Language));


            XmlNode headNode = NcxDocument.CreateElement(null, "head", rootNode.NamespaceURI);

            rootNode.AppendChild(headNode);

            XmlNode navMapNode = NcxDocument.CreateElement(null, "navMap", rootNode.NamespaceURI);

            rootNode.AppendChild(navMapNode);

            return(NcxDocument);
        }
Пример #2
0
        protected override TreeNode AddAnchorNode(TreeNode navPointTreeNode, XmlNode smilNode, string fullSmilPath)
        {
            XmlNode seqParent = smilNode != null ? smilNode.ParentNode : null;

            while (seqParent != null)
            {
                if (seqParent.Name == "seq" || seqParent.Attributes.GetNamedItem("customTest") != null)
                {
                    break;
                }
                seqParent = seqParent.ParentNode;
            }
            if (seqParent == null || XmlDocumentHelper.GetFirstChildElementOrSelfWithName(smilNode, true, "audio", smilNode.NamespaceURI) == null)
            {
                return(null);
            }

            EmptyNode anchor = m_Presentation.TreeNodeFactory.Create <EmptyNode>();

            ((SectionNode)navPointTreeNode).AppendChild(anchor);

            if (smilNode != null)
            {
                string strReference = smilNode.Attributes.GetNamedItem("href").Value;
                anchor.SetRole(EmptyNode.Role.Anchor, null);
                if (!m_AnchorNodeSmilRefMap.ContainsKey(anchor))
                {
                    string[] refArray = strReference.Split('#');
                    if (refArray.Length == 1 || string.IsNullOrEmpty(refArray[0]))
                    {
                        strReference = Path.GetFileName(fullSmilPath) + "#" + refArray[refArray.Length - 1];
                    }
                    m_AnchorNodeSmilRefMap.Add(anchor, strReference);
                }
            }
            return(anchor);
        }
        public void MSExcel2003XmlFile_SetColumnWidths_Overwrite()
        {
            //arrange
            string             comparisonFilename = "data/MSExcel2003XmlFile_SetColumnWidths_Overwrite.txt";
            MSExcel2003XmlFile xmlFile            = new MSExcel2003XmlFile();
            string             title   = "title";
            List <int>         widthsA = new List <int>()
            {
                20, 25, 10
            };
            List <int> widthsB = new List <int>()
            {
                45, 15
            };
            //act
            int tableIndex = xmlFile.AddWorksheet(title);

            xmlFile.SetColumnWidths(tableIndex, widthsA);
            xmlFile.SetColumnWidths(tableIndex, widthsB);
            string text = XmlDocumentHelper.XmlToString(xmlFile.XmlDocument);

            //assert
            Assert.AreEqual(Utilities.LoadText(comparisonFilename), text);
        }
Пример #4
0
        protected override TreeNode GetFirstTreeNodeForXmlDocument(Presentation presentation, XmlNode xmlNode)
        {
            int     level = -1;
            XmlNode xNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlNode, true, "section", null);

            if (xNode != null)
            {
                XmlNode headingNode = ParseToFineHtmlHeadingNode(xNode);


                if (headingNode != null)
                {
                    string strLevel = headingNode.LocalName.Replace("h", "");
                    //Console.WriteLine("str level " + strLevel);
                    level = int.Parse(strLevel);
                }
            }

            if (level <= 1)
            {
                return(presentation.RootNode);
            }
            else
            {
                List <SectionNode> sectionsList = new List <SectionNode>(m_XmlIdToSectionNodeMap.Values);

                for (int i = sectionsList.Count - 1; i >= 0; i--)
                {
                    if (sectionsList[i].Level < level)
                    {
                        return(sectionsList[i]);
                    }
                }
                return(presentation.RootNode);
            }
        }
        public XmlDocument Sign(string xmlData, string elementId, string certificateThumbprint, string certificatePassword)
        {
            if (string.IsNullOrEmpty(xmlData))
            {
                throw new ArgumentNullException("xmlData");
            }
            if (string.IsNullOrEmpty(elementId))
            {
                throw new ArgumentNullException("elementId");
            }
            if (string.IsNullOrEmpty(certificateThumbprint))
            {
                throw new ArgumentNullException("certificateThumbprint");
            }

            var originalDoc = XmlDocumentHelper.Create(xmlData);
            var certificate = CertificateHelper.GetCertificateByThumbprint(certificateThumbprint);

            var xadesSignedXml = new XadesBesSignedXml(originalDoc)
            {
                SignedElementId = elementId,
                CryptoProvider  = new GostCryptoProvider()
            };

            var element = xadesSignedXml.FindElement(elementId, originalDoc);

            if (element == null)
            {
                throw new InvalidOperationException(string.Format("Не удалось найти узел c Id {0}", elementId));
            }

            xadesSignedXml.ComputeSignature(certificate, certificatePassword);
            xadesSignedXml.InjectSignatureTo(originalDoc);

            return(originalDoc);
        }
Пример #6
0
        private void PopulateMetadataFromNcc(XmlNode headNode)
        {
            Dictionary <string, string> referenceList = new Dictionary <string, string>();

            foreach (string s in Metadata.DAISY3MetadataNames)
            {
                if (s == Metadata.DC_IDENTIFIER || s == Metadata.DC_TITLE ||
                    s == Metadata.DC_FORMAT || s == Metadata.DC_TYPE || s == Metadata.DTB_AUDIO_FORMAT ||
                    s == Metadata.DTB_MULTIMEDIA_CONTENT || s == Metadata.DTB_MULTIMEDIA_TYPE || s == Metadata.DTB_TOTAL_TIME || s == Metadata.GENERATOR)
                {
                    continue;
                }
                string [] arrayString = s.Split(':');
                string    name        = (arrayString.Length > 1? arrayString[1]: arrayString[0]).ToLower();
                referenceList.Add(name, s);
                //Console.WriteLine(name);
            }
            foreach (XmlNode metaNode in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headNode, true, "meta", headNode.NamespaceURI, false))
            {
                string name = metaNode.Attributes.GetNamedItem("name") != null?metaNode.Attributes.GetNamedItem("name").Value : null;

                string content = metaNode.Attributes.GetNamedItem("content") != null?metaNode.Attributes.GetNamedItem("content").Value : null;

                if (name == null)
                {
                    continue;
                }
                string[] arrayString   = name.Split(':');
                string   truncatedName = (arrayString.Length > 1 ? arrayString[1] : arrayString[0]).ToLower();
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(content) &&
                    referenceList.ContainsKey(truncatedName.ToLower()))
                {
                    m_Presentation.SetSingleMetadataItem(referenceList[truncatedName.ToLower()], content);
                }
            }
        }
Пример #7
0
        protected bool parseContentDocParts(string filePath, Project project, XmlDocument xmlDoc, string displayPath, DocumentMarkupType type)
        {
            if (RequestCancellation)
            {
                return(true);
            }
            reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMetadata, displayPath));

            XmlNode headXmlNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc.DocumentElement, true, "head", null);

            parseMetadata(filePath, project, xmlDoc, headXmlNode);

            if (RequestCancellation)
            {
                return(true);
            }
            parseHeadLinks(filePath, project, xmlDoc);

            if (RequestCancellation)
            {
                return(true);
            }
            reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingContent, displayPath));

            try
            {
                urakawa.core.TreeNode.EnableTextCache = false;
                parseContentDocument(filePath, project, xmlDoc, null, null, type);
            }
            finally
            {
                urakawa.core.TreeNode.EnableTextCache = true;
            }

            return(false);
        }
Пример #8
0
        private static IEnumerable <Tuple <string, string> > ProcessSoapResponse(string response)
        {
            var soapXml = XmlDocumentHelper.Create(response);

            var manager      = soapXml.CreateNamespaceManager();
            var bodyResponse = soapXml.SelectSingleNode(Constants.SoapContentXpathResponce, manager);

            var idAttribute = bodyResponse.Attributes["Id"]?.Value;

            if (!string.IsNullOrEmpty(idAttribute) && bodyResponse.ChildNodes.OfType <XmlNode>().Any(x => x.LocalName == Constants.SignatureName))
            {
                //Info("Проверка подписи ответа...");
                Validate(soapXml, idAttribute);
            }
            else
            {
                //Info("Ответ не содержит подписи");
                //var subj = new Tuple<string, string>("Error", "Ответ не содержит подписи");
                //var error = subj as IEnumerable<Tuple<string, string>>;
                //return error;
            }

            return(FindXmlDataNode(bodyResponse, $"{bodyResponse.Name}/"));
        }
Пример #9
0
        protected override void parseContentDocument(string filePath, Project project, XmlNode xmlNode, TreeNode parentTreeNode, string dtdUniqueResourceId, DocumentMarkupType docMarkupType)
        {
            if (RequestCancellation)
            {
                return;
            }

            XmlNodeType xmlType = xmlNode.NodeType;

            switch (xmlType)
            {
            case XmlNodeType.Attribute:
            {
                System.Diagnostics.Debug.Fail("Calling this method with an XmlAttribute should never happen !!");
                break;
            }

            case XmlNodeType.Document:
            {
                XmlNode bodyElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlNode, true, "body", null);

                if (bodyElement == null)
                {
                    bodyElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlNode, true, "book", null);
                }

                if (bodyElement != null)
                {
                    Presentation presentation = m_Project.Presentations.Get(0);
                    presentation.PropertyFactory.DefaultXmlNamespaceUri = bodyElement.NamespaceURI;

                    parseContentDocument(filePath, project, bodyElement, parentTreeNode, null, docMarkupType);
                }
                //parseContentDocument(((XmlDocument)xmlNode).DocumentElement, parentTreeNode);
                break;
            }

            case XmlNodeType.Element:
            {
                Presentation presentation = m_Project.Presentations.Get(0);

                TreeNode treeNode = null;

                if (parentTreeNode == null)
                {
                    parentTreeNode = GetFirstTreeNodeForXmlDocument(presentation, xmlNode);
                    //parentTreeNode = presentation.RootNode;
                }
                if (parentTreeNode != null)
                {
                    treeNode = CreateAndAddTreeNodeForContentDocument(parentTreeNode,
                                                                      xmlNode,
                                                                      Path.GetFileName(filePath));
                    if (treeNode != null && treeNode is EmptyNode && ((EmptyNode)treeNode).PageNumber != null)
                    {
                        string strfRefID = Path.GetFileName(filePath) + "#" + xmlNode.Attributes.GetNamedItem("id").Value;
                        m_XmlIdToPageNodeMap.Add(strfRefID, (EmptyNode)treeNode);
                    }
                    //parentTreeNode.AppendChild(treeNode);
                }
                if (xmlNode.ParentNode != null && xmlNode.ParentNode.NodeType == XmlNodeType.Document)
                {
                    presentation.PropertyFactory.DefaultXmlNamespaceUri = xmlNode.NamespaceURI;
                }

                XmlProperty xmlProp = null;
                if (treeNode != null)
                {
                    xmlProp = presentation.PropertyFactory.CreateXmlProperty();
                    treeNode.AddProperty(xmlProp);


                    // we get rid of element name prefixes, we use namespace URIs instead.
                    // check inherited NS URI

                    string nsUri = treeNode.Parent != null?
                                   treeNode.Parent.GetXmlNamespaceUri() :
                                       xmlNode.NamespaceURI; //presentation.PropertyFactory.DefaultXmlNamespaceUri

                    if (xmlNode.NamespaceURI != nsUri)
                    {
                        nsUri = xmlNode.NamespaceURI;
                        xmlProp.SetQName(xmlNode.LocalName, nsUri == null ? "" : nsUri);
                    }
                    else
                    {
                        xmlProp.SetQName(xmlNode.LocalName, "");
                    }


                    //string nsUri = treeNode.GetXmlNamespaceUri();
                    // if xmlNode.NamespaceURI != nsUri
                    // => xmlProp.GetNamespaceUri() == xmlNode.NamespaceURI
                }



                if (parentTreeNode is SectionNode &&
                    (xmlNode.LocalName == "h1" || xmlNode.LocalName == "h2" || xmlNode.LocalName == "h3" ||
                     xmlNode.LocalName == "h4" || xmlNode.LocalName == "h5" || xmlNode.LocalName == "h6" || xmlNode.LocalName == "HD"))
                {
                    ((SectionNode)parentTreeNode).Label =
                        xmlNode.InnerText.Replace("\n", "").Replace("\r", "").Replace("\t", "");
                    Console.WriteLine("DTBook: " + ((SectionNode)parentTreeNode).Label);
                    if (xmlNode.Attributes.GetNamedItem("id") != null)
                    {
                        string strfRefID = Path.GetFileName(filePath) + "#" + xmlNode.Attributes.GetNamedItem("id").Value;
                        if (!m_XmlIdToSectionNodeMap.ContainsKey(strfRefID))
                        {
                            m_XmlIdToSectionNodeMap.Add(strfRefID, (SectionNode)parentTreeNode);
                        }
                    }
                }
                if (treeNode != null && treeNode is SectionNode && xmlNode.LocalName == "doctitle")
                {
                    ((SectionNode)treeNode).Label = xmlNode.InnerText.Replace("\n", "").Replace("\r", "").Replace("\t", "");;
                }


                if (RequestCancellation)
                {
                    return;
                }
                foreach (XmlNode childXmlNode in xmlNode.ChildNodes)
                {
                    parseContentDocument(filePath, project, childXmlNode, treeNode != null && treeNode is SectionNode ? treeNode : parentTreeNode, null, docMarkupType);
                }
                break;
            }

            case XmlNodeType.Whitespace:
            case XmlNodeType.CDATA:
            case XmlNodeType.SignificantWhitespace:
            case XmlNodeType.Text:
            {
                /*
                 * Presentation presentation = Project.Presentations.Get(0);
                 *
                 * if (xmlType == XmlNodeType.Whitespace)
                 * {
                 *  bool onlySpaces = true;
                 *  for (int i = 0; i < xmlNode.Value.Length; i++)
                 *  {
                 *      if (xmlNode.Value[i] != ' ')
                 *      {
                 *          onlySpaces = false;
                 *          break;
                 *      }
                 *  }
                 *  if (!onlySpaces)
                 *  {
                 *      break;
                 *  }
                 *  //else
                 *  //{
                 *  //    int l = xmlNode.Value.Length;
                 *  //}
                 * }
                 #if DEBUG
                 * if (xmlType == XmlNodeType.CDATA)
                 * {
                 *  Debugger.Break();
                 * }
                 *
                 * if (xmlType == XmlNodeType.SignificantWhitespace)
                 * {
                 *  Debugger.Break();
                 * }
                 #endif
                 * //string text = xmlNode.Value.Trim();
                 * string text = System.Text.RegularExpressions.Regex.Replace(xmlNode.Value, @"\s+", " ");
                 *
                 * Debug.Assert(!string.IsNullOrEmpty(text));
                 *
                 #if DEBUG
                 * if (text.Length != xmlNode.Value.Length)
                 * {
                 *  int debug = 1;
                 *  //Debugger.Break();
                 * }
                 *
                 * if (string.IsNullOrEmpty(text))
                 * {
                 *  Debugger.Break();
                 * }
                 * if (xmlType != XmlNodeType.Whitespace && text == " ")
                 * {
                 *  int debug = 1;
                 *  //Debugger.Break();
                 * }
                 #endif
                 * if (string.IsNullOrEmpty(text))
                 * {
                 *  break;
                 * }
                 * urakawa.media.TextMedia textMedia = presentation.MediaFactory.CreateTextMedia();
                 * textMedia.Text = text;
                 *
                 * urakawa.property.channel.ChannelsProperty cProp = presentation.PropertyFactory.CreateChannelsProperty();
                 * cProp.SetMedia(m_textChannel, textMedia);
                 *
                 *
                 * int counter = 0;
                 * foreach (XmlNode childXmlNode in xmlNode.ParentNode.ChildNodes)
                 * {
                 *  XmlNodeType childXmlType = childXmlNode.NodeType;
                 *  if (childXmlType == XmlNodeType.Text
                 || childXmlType == XmlNodeType.Element
                 || childXmlType == XmlNodeType.Whitespace
                 || childXmlType == XmlNodeType.SignificantWhitespace
                 || childXmlType == XmlNodeType.CDATA)
                 || {
                 ||     counter++;
                 || }
                 ||}
                 ||if (counter == 1)
                 ||{
                 || parentTreeNode.AddProperty(cProp);
                 ||}
                 ||else
                 ||{
                 || TreeNode txtWrapperNode = presentation.TreeNodeFactory.Create();
                 || txtWrapperNode.AddProperty(cProp);
                 || parentTreeNode.AppendChild(txtWrapperNode);
                 ||}
                 */
                break;
            }

            default:
            {
                return;
            }
            }
        }
Пример #10
0
        protected override TreeNode CreateTreeNodeForAudioNode(TreeNode navPointTreeNode, bool isHeadingNode, XmlNode smilNode, string fullSmilPath)
        {
            PhraseNode audioWrapperNode = m_Presentation.CreatePhraseNode();

            if (smilNode == null || !m_SmilXmlNodeToTreeNodeMap.ContainsKey(smilNode))
            {
                ((SectionNode)navPointTreeNode).AppendChild(audioWrapperNode);

                XmlNode seqParent = smilNode != null ? smilNode.ParentNode : null;
                while (seqParent != null)
                {
                    if ((seqParent.Name == "seq" || seqParent.Name == "par") && (seqParent.Attributes != null && seqParent.Attributes.GetNamedItem("customTest") != null))
                    {
                        break;
                    }
                    seqParent = seqParent.ParentNode;
                }

                string strClass = null;

                if (seqParent != null && seqParent.Attributes.GetNamedItem("class") != null &&
                    (strClass = seqParent.Attributes.GetNamedItem("class").Value) != null &&
                    (strClass == EmptyNode.Annotation || strClass == EmptyNode.EndNote || strClass == EmptyNode.Footnote ||
                     strClass == EmptyNode.ProducerNote || strClass == EmptyNode.Sidebar || strClass == EmptyNode.Note))
                {
                    audioWrapperNode.SetRole(EmptyNode.Role.Custom, strClass);
                    if (!m_Skippable_IdMap.ContainsKey(audioWrapperNode))
                    {
                        ObiNode preceedingNode = audioWrapperNode.PrecedingNode;
                        if (preceedingNode == null || preceedingNode is SectionNode || ((EmptyNode)preceedingNode).CustomRole != audioWrapperNode.CustomRole)
                        {
                            m_Skippable_IdMap.Add(audioWrapperNode, new List <string>());
                            XmlNode seqChild = seqParent;
                            while (seqChild != null && seqChild != smilNode)
                            {
                                if (seqChild.Attributes.GetNamedItem("id") != null)
                                {
                                    m_Skippable_IdMap[audioWrapperNode].Add(Path.GetFileName(fullSmilPath) + "#" + seqChild.Attributes.GetNamedItem("id").Value);
                                }
                                seqChild = seqChild.FirstChild;
                            }


                            AssignSkippableToAnchorNode();
                        }
                    }
                }
                else if (seqParent != null && seqParent.Attributes != null && seqParent.Attributes.GetNamedItem("customTest") != null)
                {
                    XmlNode anchorNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(seqParent, true, "a", seqParent.NamespaceURI);
                    if (anchorNode != null)
                    {
                        string strReference = anchorNode.Attributes.GetNamedItem("href").Value;
                        audioWrapperNode.SetRole(EmptyNode.Role.Anchor, null);
                        if (!m_AnchorNodeSmilRefMap.ContainsKey(audioWrapperNode))
                        {
                            string[] refArray = strReference.Split('#');
                            if (refArray.Length == 1 || string.IsNullOrEmpty(refArray[0]))
                            {
                                strReference = Path.GetFileName(fullSmilPath) + "#" + refArray[refArray.Length - 1];
                            }
                            m_AnchorNodeSmilRefMap.Add(audioWrapperNode, strReference);
                        }
                    }
                }
            }
            else
            {
                ((SectionNode)navPointTreeNode).InsertAfter(audioWrapperNode, m_SmilXmlNodeToTreeNodeMap[smilNode]);
                m_SmilXmlNodeToTreeNodeMap[smilNode] = audioWrapperNode;
            }

            return(audioWrapperNode);
        }
Пример #11
0
        private void parseSmil(string fullSmilPath)
        {
            if (RequestCancellation)
            {
                return;
            }
            XmlDocument smilXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullSmilPath, false, false);

            if (RequestCancellation)
            {
                return;
            }
            //we skip SMIL metadata parsing (we get publication metadata only from OPF and DTBOOK/XHTMLs)
            //parseMetadata(smilXmlDoc);

            //XmlNodeList allTextNodes = smilXmlDoc.GetElementsByTagName("text");
            //if (allTextNodes.Count == 0)
            //{
            //    return;
            //}

            //reportProgress(-1, "Parsing SMIL: [" + Path.GetFileName(fullSmilPath) + "]");

            foreach (XmlNode textNode in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(smilXmlDoc, true, "text", null, false))
            {
                XmlAttributeCollection textNodeAttrs = textNode.Attributes;
                if (textNodeAttrs == null || textNodeAttrs.Count == 0)
                {
                    continue;
                }
                XmlNode textNodeAttrSrc = textNodeAttrs.GetNamedItem("src");
                if (textNodeAttrSrc == null || String.IsNullOrEmpty(textNodeAttrSrc.Value))
                {
                    continue;
                }

                string src = FileDataProvider.UriDecode(textNodeAttrSrc.Value);


                int index = src.LastIndexOf('#');
                if (index == src.Length - 1)
                {
                    return;
                }
                string   srcFragmentId = src.Substring(index + 1);
                TreeNode textTreeNode  = m_Project.Presentations.Get(0).RootNode.GetFirstDescendantOrSelfWithXmlID(srcFragmentId);
                if (textTreeNode == null)
                {
                    continue;
                }

                ManagedAudioMedia textTreeNodeAudio = textTreeNode.GetManagedAudioMedia();
                if (textTreeNodeAudio != null)
                {
                    //Ignore.
                    continue;
                }
                XmlNode parent = textNode.ParentNode;
                if (parent != null && parent.LocalName == "a")
                {
                    parent = parent.ParentNode;
                }
                if (parent == null)
                {
                    continue;
                }
                if (parent.LocalName != "par")
                {
                    //System.Diagnostics.Debug.Fail("Text node in SMIL has no parallel time container as parent ! {0}", parent.Name);
                    continue;
                }
                XmlNodeList textPeers = parent.ChildNodes;
                foreach (XmlNode textPeerNode in textPeers)
                {
                    if (RequestCancellation)
                    {
                        return;
                    }

                    if (textPeerNode.NodeType != XmlNodeType.Element)
                    {
                        continue;
                    }
                    if (textPeerNode.LocalName == "audio")
                    {
                        addAudio(textTreeNode, textPeerNode, false, fullSmilPath);
                        break;
                    }
                    else if (textPeerNode.LocalName == "a")
                    {
                        XmlNodeList aChildren = textPeerNode.ChildNodes;
                        foreach (XmlNode aChild in aChildren)
                        {
                            if (aChild.LocalName == "audio")
                            {
                                addAudio(textTreeNode, aChild, false, fullSmilPath);
                                break;
                            }
                        }
                    }
                    else if (textPeerNode.LocalName == "seq")
                    {
#if DEBUG
                        Debugger.Break();
#endif //DEBUG
                        XmlNodeList seqChildren = textPeerNode.ChildNodes;
                        foreach (XmlNode seqChild in seqChildren)
                        {
                            if (seqChild.LocalName == "audio")
                            {
                                addAudio(textTreeNode, seqChild, true, fullSmilPath);
                            }
                        }
#if ENABLE_SEQ_MEDIA
                        SequenceMedia seqManAudioMedia = textTreeNode.GetManagedAudioSequenceMedia();
                        if (seqManAudioMedia == null)
                        {
                            Debug.Fail("This should never happen !");
                            break;
                        }

                        ManagedAudioMedia managedAudioMedia = textTreeNode.Presentation.MediaFactory.CreateManagedAudioMedia();
                        AudioMediaData    mediaData         = textTreeNode.Presentation.MediaDataFactory.CreateAudioMediaData();
                        managedAudioMedia.AudioMediaData = mediaData;

                        foreach (Media seqChild in seqManAudioMedia.ChildMedias.ContentsAs_Enumerable)
                        {
                            ManagedAudioMedia seqManMedia = (ManagedAudioMedia)seqChild;

                            // WARNING: WavAudioMediaData implementation differs from AudioMediaData:
                            // the latter is naive and performs a stream binary copy, the latter is optimized and re-uses existing WavClips.
                            //  WARNING 2: The audio data from the given parameter gets emptied !
                            mediaData.MergeWith(seqManMedia.AudioMediaData);

                            //Stream stream = seqManMedia.AudioMediaData.OpenPcmInputStream();
                            //try
                            //{
                            //    mediaData.AppendPcmData(stream, null);
                            //}
                            //finally
                            //{
                            //    stream.Close();
                            //}

                            //seqManMedia.AudioMediaData.Delete(); // doesn't actually removes the FileDataProviders (need to call Presentation.Cleanup())
                            ////textTreeNode.Presentation.DataProviderManager.RemoveDataProvider();
                        }

                        ChannelsProperty chProp = textTreeNode.GetChannelsProperty();
                        chProp.SetMedia(m_audioChannel, null);
                        chProp.SetMedia(m_audioChannel, managedAudioMedia);
#endif //ENABLE_SEQ_MEDIA
                        break;
                    }
                }
            }
        }
        private void parseOpfManifest(XmlDocument opfXmlDoc,
                                      out List <string> spine,
                                      out Dictionary <string, string> spineAttributes,
                                      out List <Dictionary <string, string> > spineItemsAttributes,
                                      out string spineMimeType,
                                      out string dtbookPath,
                                      out string ncxPath,
                                      out string navDocPath,
                                      out string coverImagePath,
                                      string idCoverImageFromMetadata)
        {
            spine                = new List <string>();
            spineAttributes      = new Dictionary <string, string>();
            spineItemsAttributes = new List <Dictionary <string, string> >();
            spineMimeType        = null;
            ncxPath              = null;
            dtbookPath           = null;
            navDocPath           = null;
            coverImagePath       = null;

            XmlNode spineNodeRoot = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(opfXmlDoc, true, "spine", null);

            if (spineNodeRoot != null)
            {
                XmlAttributeCollection spineAttrs = spineNodeRoot.Attributes;

                if (spineAttrs != null && spineAttrs.Count > 0)
                {
                    foreach (XmlAttribute spineAttr in spineAttrs)
                    {
                        if (spineAttr.LocalName != "id" && spineAttr.LocalName != "toc")
                        {
                            spineAttributes.Add(spineAttr.Name, spineAttr.Value);
                        }
                    }
                }

                XmlNodeList listOfSpineItemNodes = spineNodeRoot.ChildNodes;
                foreach (XmlNode spineItemNode in listOfSpineItemNodes)
                {
                    if (RequestCancellation)
                    {
                        return;
                    }

                    if (spineItemNode.NodeType != XmlNodeType.Element ||
                        spineItemNode.LocalName != "itemref")
                    {
                        continue;
                    }
                    XmlAttributeCollection spineItemAttributes = spineItemNode.Attributes;

                    if (spineItemAttributes == null || spineItemAttributes.Count <= 0)
                    {
                        continue;
                    }

                    XmlNode attrIdRef = spineItemAttributes.GetNamedItem("idref");
                    if (attrIdRef != null && !string.IsNullOrEmpty(attrIdRef.Value))
                    {
                        spine.Add(attrIdRef.Value);

                        Dictionary <string, string> dict = new Dictionary <string, string>();
                        spineItemsAttributes.Add(dict);
                        foreach (XmlAttribute spineItemAttr in spineItemAttributes)
                        {
                            if (spineItemAttr.LocalName != "id" && spineItemAttr.LocalName != "idref")
                            {
                                if (spineItemAttr.Name == @"properties")
                                {
                                    dict.Add(@"properties_spine", spineItemAttr.Value);
                                }
                                else
                                {
                                    dict.Add(spineItemAttr.Name, spineItemAttr.Value);
                                }
                            }
                        }
                    }
                }
            }

            XmlNode manifNodeRoot = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(opfXmlDoc, true, "manifest", null);

            if (manifNodeRoot == null)
            {
                return;
            }

            XmlNodeList listOfManifestItemNodes = manifNodeRoot.ChildNodes;

            foreach (XmlNode manifItemNode in listOfManifestItemNodes)
            {
                if (RequestCancellation)
                {
                    return;
                }

                if (manifItemNode.NodeType != XmlNodeType.Element ||
                    manifItemNode.LocalName != "item")
                {
                    continue;
                }

                XmlAttributeCollection manifItemAttributes = manifItemNode.Attributes;
                if (manifItemAttributes == null)
                {
                    continue;
                }

                XmlNode attrHref      = manifItemAttributes.GetNamedItem("href");
                XmlNode attrMediaType = manifItemAttributes.GetNamedItem("media-type");
                if (attrHref == null || String.IsNullOrEmpty(attrHref.Value) ||
                    attrMediaType == null || String.IsNullOrEmpty(attrMediaType.Value))
                {
                    continue;
                }

                string href = FileDataProvider.UriDecode(attrHref.Value);

                XmlNode attrProperties = manifItemAttributes.GetNamedItem("properties");

                if (attrProperties != null && attrProperties.Value.Contains("cover-image"))
                {
                    DebugFix.Assert(attrMediaType.Value == DataProviderFactory.IMAGE_SVG_MIME_TYPE ||
                                    attrMediaType.Value == DataProviderFactory.IMAGE_JPG_MIME_TYPE ||
                                    attrMediaType.Value == DataProviderFactory.IMAGE_BMP_MIME_TYPE ||
                                    attrMediaType.Value == DataProviderFactory.IMAGE_PNG_MIME_TYPE ||
                                    attrMediaType.Value == DataProviderFactory.IMAGE_GIF_MIME_TYPE
                                    );

                    coverImagePath = href;
                }

                XmlNode attrId = manifItemAttributes.GetNamedItem("id");
                if (string.IsNullOrEmpty(coverImagePath) &&
                    attrId != null && attrId.Value == idCoverImageFromMetadata)
                {
                    coverImagePath = href;
                }

                if (attrMediaType.Value != DataProviderFactory.SMIL_MIME_TYPE // yep! (EPUB3)
                    &&
                    (attrMediaType.Value == DataProviderFactory.SMIL_MIME_TYPE_ ||
                     attrMediaType.Value == DataProviderFactory.XHTML_MIME_TYPE ||
                     attrMediaType.Value == DataProviderFactory.IMAGE_SVG_MIME_TYPE))
                {
                    if (attrProperties != null && attrProperties.Value.Contains("nav"))
                    {
                        DebugFix.Assert(attrMediaType.Value == DataProviderFactory.XHTML_MIME_TYPE);

                        navDocPath = href;
                    }

                    if (attrId != null)
                    {
                        int i = spine.IndexOf(attrId.Value);
                        if (i >= 0)
                        {
                            spine[i] = href;
                            //if (!string.IsNullOrEmpty(spineMimeType)
                            //    && spineMimeType != attrMediaType.Value)
                            //{
                            //    System.Diagnostics.Debug.Fail(String.Format("Spine contains different mime-types ?! {0} vs {1}", attrMediaType.Value, spineMimeType));
                            //}
                            spineMimeType = attrMediaType.Value;

                            if (attrProperties != null)
                            {
                                Dictionary <string, string> dict = spineItemsAttributes[i];

                                dict.Add(
                                    @"properties_manifest"
                                    //attrProperties.Name
                                    , attrProperties.Value);

                                //string val;
                                //dict.TryGetValue(attrProperties.Name, out val);
                                //if (!string.IsNullOrEmpty(val))
                                //{
                                //    dict.Remove(attrProperties.Name);
                                //    dict.Add(attrProperties.Name, val + @" " + attrProperties.Value);
                                //}
                                //else
                                //{
                                //    dict.Add(attrProperties.Name, attrProperties.Value);
                                //}
                            }

                            XmlNode attrMediaOverlay = manifItemAttributes.GetNamedItem("media-overlay");
                            if (attrMediaOverlay != null && !String.IsNullOrEmpty(attrMediaOverlay.Value))
                            {
                                foreach (XmlNode manifItemNode2 in listOfManifestItemNodes)
                                {
                                    XmlAttributeCollection manifItemAttributes2 = manifItemNode2.Attributes;
                                    if (manifItemAttributes2 == null)
                                    {
                                        continue;
                                    }
                                    XmlNode attrId2   = manifItemAttributes2.GetNamedItem("id");
                                    XmlNode attrHref2 = manifItemAttributes2.GetNamedItem("href");
                                    if (attrId2 != null && attrId2.Value == attrMediaOverlay.Value &&
                                        attrHref2 != null && !string.IsNullOrEmpty(attrHref2.Value))
                                    {
                                        Dictionary <string, string> dict = spineItemsAttributes[i];
                                        dict.Add(attrMediaOverlay.Name, FileDataProvider.UriDecode(attrHref2.Value));
                                    }
                                }
                            }
                        }
                    }
                }
                else if (attrMediaType.Value == DataProviderFactory.DTBOOK_MIME_TYPE ||
                         attrMediaType.Value == DataProviderFactory.XML_MIME_TYPE &&
                         href.EndsWith(DataProviderFactory.XML_EXTENSION))
                {
                    dtbookPath = href;
                }
                else if (attrMediaType.Value == DataProviderFactory.NCX_MIME_TYPE ||
                         attrMediaType.Value == DataProviderFactory.XML_MIME_TYPE &&
                         href.EndsWith(DataProviderFactory.NCX_EXTENSION))
                {
                    ncxPath = href;
                }
                //else if (attrMediaType.Value == DataProviderFactory.STYLE_CSS_MIME_TYPE
                //    || attrMediaType.Value == DataProviderFactory.STYLE_PLS_MIME_TYPE)
                //{
                //    AddExternalFilesToXuk(m_Project.Presentations.Get(0), attrHref.Value);
                //}
                //else if (attrMediaType.Value == "image/jpeg"
                //|| attrMediaType.Value == "audio/mpeg"
                //|| attrMediaType.Value == DataProviderFactory.XML_TEXT_MIME_TYPE
                //|| attrMediaType.Value == "application/vnd.adobe.page-template+xml"
                //|| attrMediaType.Value == "application/oebps-page-map+xml"
                //|| attrMediaType.Value == DataProviderFactory.DTB_RES_MIME_TYPE)
                //{
                //    // Ignore
                //}
            }
        }
Пример #13
0
        public static List <AccountModel> ReadAccountModels(string fileName)
        {
            List <AccountModel> tmpAccountModels = null;

            var tmpImportDocument = new XmlDocument();

            tmpImportDocument.Load(fileName);
            var tmpAccountNodes = tmpImportDocument.SelectNodes("Account//item");

            if (tmpAccountNodes != null)
            {
                tmpAccountModels = new List <AccountModel>();
                foreach (XmlElement tmpAccountNode in tmpAccountNodes)
                {
                    var tmpAccountInfo = new AccountModel();

                    tmpAccountInfo.AccountId   = XmlDocumentHelper.GetAttributeValue(tmpAccountNode, "id", 0);
                    tmpAccountInfo.CatalogId   = XmlDocumentHelper.GetAttributeValue(tmpAccountNode, "CatalogId", 0);
                    tmpAccountInfo.AccountGuid = XmlDocumentHelper.GetAttributeString(tmpAccountNode, "Guid");
                    tmpAccountInfo.Name        = XmlDocumentHelper.GetAttributeString(tmpAccountNode, "Name", null);
                    tmpAccountInfo.Order       = XmlDocumentHelper.GetAttributeValue(tmpAccountNode, "Order", 0);
                    tmpAccountInfo.URL         = XmlDocumentHelper.GetAttributeString(tmpAccountNode, "URL", null);
                    tmpAccountInfo.LoginName   = XmlDocumentHelper.GetAttributeString(tmpAccountNode, "LoginName", null);
                    tmpAccountInfo.Password    = XmlDocumentHelper.GetAttributeString(tmpAccountNode, "Password", null);
                    tmpAccountInfo.Email       = XmlDocumentHelper.GetAttributeString(tmpAccountNode, "Email", null);
                    tmpAccountInfo.Mobile      = XmlDocumentHelper.GetAttributeString(tmpAccountNode, "Mobile", null);
                    tmpAccountInfo.Deleted     = XmlDocumentHelper.GetAttributeValue(tmpAccountNode, "Delete", false);
                    tmpAccountInfo.TopMost     = (short)XmlDocumentHelper.GetAttributeValue(tmpAccountNode, "TopMost", 0);
                    tmpAccountInfo.VersionNo   = XmlDocumentHelper.GetAttributeValue(tmpAccountNode, "Version", 1);
                    tmpAccountInfo.SecretRank  = XmlDocumentHelper.GetAttributeValue(tmpAccountNode, "SecretRank", SecretRank.绝密);
                    tmpAccountInfo.CreateTime  = XmlDocumentHelper.GetAttributeValue(tmpAccountNode, "CreateTime");
                    tmpAccountInfo.UpdateTime  = XmlDocumentHelper.GetAttributeValue(tmpAccountNode, "UpdateTime");

                    var tmpComment = XmlDocumentHelper.GetNodeInnerString(tmpAccountNode, "Comment");
                    if (!string.IsNullOrEmpty(tmpComment))
                    {
                        tmpAccountInfo.Comment = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(tmpComment));
                    }

                    var tmpAttributeNodes = tmpAccountNode.SelectNodes("Attributes/Attribute");
                    if (tmpAttributeNodes != null)
                    {
                        foreach (XmlElement tmpAttributeNode in tmpAttributeNodes)
                        {
                            var tmpAttribute = new AccountAttribute();
                            tmpAttribute.AccountId   = tmpAccountInfo.AccountId;
                            tmpAttribute.AttributeId = XmlDocumentHelper.GetAttributeValue(tmpAttributeNode, "Id", 0);
                            tmpAttribute.Order       = (short)XmlDocumentHelper.GetAttributeValue(tmpAttributeNode, "Order", 0);
                            tmpAttribute.Encrypted   = XmlDocumentHelper.GetAttributeValue(tmpAttributeNode, "Encrypted", false);
                            tmpAttribute.Name        = XmlDocumentHelper.GetAttributeString(tmpAttributeNode, "Name", string.Empty);
                            tmpAttribute.Value       = tmpAttributeNode.InnerText;

                            tmpAccountInfo.Attributes.Add(tmpAttribute);
                        }
                    }

                    tmpAccountModels.Add(tmpAccountInfo);
                }
            }

            return(tmpAccountModels);
        }
Пример #14
0
        public void ImportDiagramXML(string xmlFilePath)
        {
            Tuple <TreeNode, TreeNode> selection = m_UrakawaSession.GetTreeNodeSelection();
            TreeNode treeNode = selection.Item2 ?? selection.Item1;
            var      altProp  = treeNode.GetAlternateContentProperty();



            XmlDocument diagramXML = XmlReaderWriterHelper.ParseXmlDocument(xmlFilePath, false, false);

            XmlNode description = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(diagramXML, false, "description", DiagramContentModelHelper.NS_URL_DIAGRAM);

            if (description == null)
            {
                return;
            }

            XmlAttributeCollection descrAttrs = description.Attributes;

            if (descrAttrs != null)
            {
                for (int i = 0; i < descrAttrs.Count; i++)
                {
                    XmlAttribute attr = descrAttrs[i];

                    if (!attr.Name.StartsWith(XmlReaderWriterHelper.NS_PREFIX_XML + ":"))
                    {
                        continue;
                    }

                    Metadata altContMetadata = treeNode.Presentation.MetadataFactory.CreateMetadata();
                    altContMetadata.NameContentAttribute              = new MetadataAttribute();
                    altContMetadata.NameContentAttribute.Name         = attr.Name;
                    altContMetadata.NameContentAttribute.NamespaceUri = XmlReaderWriterHelper.NS_URL_XML;
                    altContMetadata.NameContentAttribute.Value        = attr.Value;
                    AlternateContentMetadataAddCommand cmd_AltPropMetadata_XML =
                        treeNode.Presentation.CommandFactory.CreateAlternateContentMetadataAddCommand(
                            treeNode,
                            altProp,
                            null,
                            altContMetadata,
                            null
                            );
                    treeNode.Presentation.UndoRedoManager.Execute(cmd_AltPropMetadata_XML);
                }
            }

            XmlNode head = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(description, false, "head", DiagramContentModelHelper.NS_URL_DIAGRAM);

            if (head != null)
            {
                foreach (XmlNode metaNode in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(head, true, "meta", DiagramContentModelHelper.NS_URL_ZAI, false))
                {
                    if (metaNode.NodeType != XmlNodeType.Element || metaNode.LocalName != "meta")
                    {
#if DEBUG
                        Debugger.Break();
#endif // DEBUG
                        continue;
                    }



                    //XmlNode childMetadata = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(node, false, "meta", DiagramContentModelHelper.NS_URL_ZAI);
                    //if (childMetadata != null)
                    //{
                    //    continue;
                    //}
                    bool foundAtLeastOneChildMeta = false;
                    foreach (XmlNode child in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(metaNode, false, "meta", DiagramContentModelHelper.NS_URL_ZAI, false))
                    {
                        if (child == metaNode)
                        {
                            continue;
                        }

                        foundAtLeastOneChildMeta = true;
                        break;
                    }
                    if (foundAtLeastOneChildMeta)
                    {
                        continue;
                    }



                    XmlAttributeCollection mdAttributes = metaNode.Attributes;
                    if (mdAttributes == null || mdAttributes.Count <= 0)
                    {
                        continue;
                    }

                    XmlNode attrName     = mdAttributes.GetNamedItem("name");
                    XmlNode attrProperty = mdAttributes.GetNamedItem("property");

                    string property = (attrName != null && !String.IsNullOrEmpty(attrName.Value))
                                          ? attrName.Value
                                          : (attrProperty != null && !String.IsNullOrEmpty(attrProperty.Value)
                                                 ? attrProperty.Value
                                                 : null);

                    XmlNode attrContent = mdAttributes.GetNamedItem("content");

                    string content = (attrContent != null && !String.IsNullOrEmpty(attrContent.Value))
                                         ? attrContent.Value
                                         : metaNode.InnerText;

                    if (!(
                            String.IsNullOrEmpty(property) && String.IsNullOrEmpty(content)
                            ||
                            !String.IsNullOrEmpty(property) && !String.IsNullOrEmpty(content)
                            ))
                    {
                        continue;
                    }

                    Metadata altContMetadata = treeNode.Presentation.MetadataFactory.CreateMetadata();
                    altContMetadata.NameContentAttribute      = new MetadataAttribute();
                    altContMetadata.NameContentAttribute.Name = String.IsNullOrEmpty(property)
                                                                    ? DiagramContentModelHelper.NA
                                                                    : property;
                    altContMetadata.NameContentAttribute.NamespaceUri =
                        String.IsNullOrEmpty(property)
                            ? null
                            : (
                            property.StartsWith(DiagramContentModelHelper.NS_PREFIX_DIAGRAM_METADATA + ":")
                                      ? DiagramContentModelHelper.NS_URL_DIAGRAM
                                      : (property.StartsWith(SupportedMetadata_Z39862005.NS_PREFIX_DUBLIN_CORE + ":")
                                             ? SupportedMetadata_Z39862005.NS_URL_DUBLIN_CORE
                                             : null)
                            )
                    ;
                    altContMetadata.NameContentAttribute.Value = String.IsNullOrEmpty(content)
                                                                     ? DiagramContentModelHelper.NA
                                                                     : content;
                    AlternateContentMetadataAddCommand cmd_AltPropMetadata =
                        treeNode.Presentation.CommandFactory.CreateAlternateContentMetadataAddCommand(
                            treeNode,
                            altProp,
                            null,
                            altContMetadata,
                            null
                            );
                    treeNode.Presentation.UndoRedoManager.Execute(cmd_AltPropMetadata);

                    bool parentIsMeta = metaNode.ParentNode.LocalName == "meta";

                    var listAttrs = new List <XmlAttribute>(mdAttributes.Count +
                                                            (parentIsMeta && metaNode.ParentNode.Attributes != null ? metaNode.ParentNode.Attributes.Count : 0)
                                                            );

                    for (int i = 0; i < mdAttributes.Count; i++)
                    {
                        XmlAttribute attribute = mdAttributes[i];
                        listAttrs.Add(attribute);
                    }

                    if (parentIsMeta && metaNode.ParentNode.Attributes != null)
                    {
                        for (int i = 0; i < metaNode.ParentNode.Attributes.Count; i++)
                        {
                            XmlAttribute attribute = metaNode.ParentNode.Attributes[i];
                            if (mdAttributes.GetNamedItem(attribute.LocalName, attribute.NamespaceURI) == null)
                            {
                                listAttrs.Add(attribute);
                            }
                        }
                    }

                    foreach (var attribute in listAttrs)
                    {
                        if (attribute.LocalName == DiagramContentModelHelper.Name ||
                            attribute.LocalName == DiagramContentModelHelper.Property ||
                            attribute.LocalName == DiagramContentModelHelper.Content)
                        {
                            continue;
                        }


                        if (attribute.Name.StartsWith(XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":"))
                        {
                            //
                        }
                        else if (attribute.Name == XmlReaderWriterHelper.NS_PREFIX_XMLNS)
                        {
                            //
                        }
                        else
                        {
                            MetadataAttribute metadatattribute = new MetadataAttribute();
                            metadatattribute.Name         = attribute.Name;
                            metadatattribute.NamespaceUri =
                                attribute.Name.IndexOf(':') >= 0
                                //attribute.Name.Contains(":")
                                ? attribute.NamespaceURI : null;
                            metadatattribute.Value = attribute.Value;
                            AlternateContentMetadataAddCommand cmd_AltPropMetadataAttr =
                                treeNode.Presentation.CommandFactory.CreateAlternateContentMetadataAddCommand(
                                    treeNode,
                                    altProp,
                                    null,
                                    altContMetadata,
                                    metadatattribute
                                    );
                            treeNode.Presentation.UndoRedoManager.Execute(cmd_AltPropMetadataAttr);
                        }
                    }
                }
            }

            XmlNode body = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(description, false, "body", DiagramContentModelHelper.NS_URL_DIAGRAM);
            if (body != null)
            {
                diagramXmlParseBodySpecific(xmlFilePath, treeNode, body, DiagramContentModelHelper.D_Summary);
                diagramXmlParseBodySpecific(xmlFilePath, treeNode, body, DiagramContentModelHelper.D_LondDesc);
                diagramXmlParseBodySpecific(xmlFilePath, treeNode, body, DiagramContentModelHelper.D_SimplifiedLanguageDescription);

                diagramXmlParseBodySpecific(xmlFilePath, treeNode, body, DiagramContentModelHelper.D_Tactile);
                diagramXmlParseBodySpecific(xmlFilePath, treeNode, body, DiagramContentModelHelper.D_SimplifiedImage);

                //#if true || SUPPORT_ANNOTATION_ELEMENT
                //                diagramXmlParseBodySpecific(xmlFilePath, treeNode, body, DiagramContentModelHelper.Annotation);
                //#endif //SUPPORT_ANNOTATION_ELEMENT



                diagramXmlParseBody(xmlFilePath, treeNode, body);
            }

            OnPanelLoaded();
        }
        protected DocumentMarkupType parseContentDocument_DTD(Project project, XmlDocument xmlDoc, TreeNode parentTreeNode, string filePath, out string dtdUniqueResourceId)
        {
            dtdUniqueResourceId = null;

            DocumentMarkupType docMarkupType = DocumentMarkupType.NA;

            //xmlNode.OwnerDocument
            string dtdID = xmlDoc.DocumentType == null ? string.Empty
            : !string.IsNullOrEmpty(xmlDoc.DocumentType.SystemId) ? xmlDoc.DocumentType.SystemId
            : !string.IsNullOrEmpty(xmlDoc.DocumentType.PublicId) ? xmlDoc.DocumentType.PublicId
            : xmlDoc.DocumentType.Name;

            string rootElemName = xmlDoc.DocumentElement.LocalName;

            if (dtdID == @"html" &&
                string.IsNullOrEmpty(xmlDoc.DocumentType.SystemId) &&
                string.IsNullOrEmpty(xmlDoc.DocumentType.PublicId))
            {
                dtdID         = @"html5";
                docMarkupType = DocumentMarkupType.XHTML5;
                DebugFix.Assert(rootElemName == @"html");
            }
            else if (dtdID.Contains(@"xhtml1")
                     //systemId.Contains(@"xhtml11.dtd")
                     //|| systemId.Contains(@"xhtml1-strict.dtd")
                     //|| systemId.Contains(@"xhtml1-transitional.dtd")
                     )
            {
                dtdID         = @"http://www.w3.org/xhtml-math-svg-flat.dtd";
                docMarkupType = DocumentMarkupType.XHTML;
                DebugFix.Assert(rootElemName == @"html");
            }
            else if (rootElemName == @"dtbook")
            {
                docMarkupType = DocumentMarkupType.DTBOOK;
            }
            else if (rootElemName == @"html")
            {
                dtdID         = @"html5";
                docMarkupType = DocumentMarkupType.XHTML5;
            }

            if (docMarkupType == DocumentMarkupType.NA)
            {
#if DEBUG
                Debugger.Break();
#endif
            }

            if (string.IsNullOrEmpty(dtdID))
            {
                return(docMarkupType);
            }

            if (!string.IsNullOrEmpty(dtdID) && !dtdID.StartsWith(@"http://"))
            {
                dtdID = @"http://www.daisy.org/" + dtdID;
            }

            bool needToLoadDTDManuallyToCheckMixedContentElements = docMarkupType == DocumentMarkupType.XHTML5;
            if (docMarkupType == DocumentMarkupType.DTBOOK)
            {
                XmlNode rootElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc, true, "book", null);
                DebugFix.Assert(rootElement != null);
                if (rootElement != null)
                {
                    XmlAttributeCollection attrs = rootElement.Attributes;
                    if (attrs != null)
                    {
                        XmlNode attr = attrs.GetNamedItem("space", XmlReaderWriterHelper.NS_URL_XML);
                        if (attr == null)
                        {
                            attr = attrs.GetNamedItem("xml:space", XmlReaderWriterHelper.NS_URL_XML);
                        }

                        if (attr != null && attr.Value == "preserve")
                        {
                            //Bookshare hack! :(
                            needToLoadDTDManuallyToCheckMixedContentElements = true;
                        }
                    }
                }
            }

            if (!needToLoadDTDManuallyToCheckMixedContentElements)
            {
                return(docMarkupType);
            }

            bool isHTML = docMarkupType == DocumentMarkupType.XHTML || docMarkupType == DocumentMarkupType.XHTML5;

#if ENABLE_DTDSHARP
            Stream dtdStream = LocalXmlUrlResolver.mapUri(new Uri(dtdID, UriKind.Absolute), out dtdUniqueResourceId);

            if (!string.IsNullOrEmpty(dtdUniqueResourceId))
            {
                DebugFix.Assert(dtdStream != null);

                List <string> list;
                m_listOfMixedContentXmlElementNames.TryGetValue(dtdUniqueResourceId, out list);

                if (list == null)
                {
                    if (dtdStream != null)
                    {
                        list = new List <string>();
                        m_listOfMixedContentXmlElementNames.Add(dtdUniqueResourceId, list);

                        initMixedContentXmlElementNamesFromDTD(dtdUniqueResourceId, dtdStream);
                    }
                    else
                    {
#if DEBUG
                        Debugger.Break();
#endif
                    }
                }
                else
                {
                    if (dtdStream != null)
                    {
                        dtdStream.Close();
                    }
                }
            }
            else
            {
#if DEBUG
                Debugger.Break();
#endif
            }
#else
            dtdUniqueResourceId = dtdID;

            List <string> list;
            m_listOfMixedContentXmlElementNames.TryGetValue(dtdUniqueResourceId, out list);

            if (list != null)
            {
                return(docMarkupType);
            }

            list = new List <string>();
            m_listOfMixedContentXmlElementNames.Add(dtdUniqueResourceId, list);

            IXmlReader reader = null;


            //string dll = @"SaxNET.dll";
            ////#if NET40
            ////                            dll = @"\SaxNET_NET4.dll";
            ////#endif
            //string appFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            //string dtdPath = Path.Combine(appFolder, dll);
            //Assembly assembly = Assembly.LoadFrom(dtdPath);
            //                            try
            //                            {
            //                                reader = SaxReaderFactory.CreateReader(assembly, null);
            //                            }
            //                            catch (Exception e)
            //                            {
            //#if DEBUG
            //                                Debugger.Break();
            //#endif
            //                            }

            bool useCSharpSaxImpl = IsRunning64(); // docMarkupType == DocumentMarkupType.XHTML5;
            if (useCSharpSaxImpl)
            {
                reader = new SaxDriver();
            }
            else
            {
                reader = new ExpatReader();
            }

            DebugFix.Assert(reader != null);
            if (reader == null)
            {
                return(docMarkupType);
            }
            //Type readerType = reader.GetType();

            reader.EntityResolver = new SaxEntityResolver();

            SaxErrorHandler errorHandler = new SaxErrorHandler();
            reader.ErrorHandler = errorHandler;


            if (reader is SaxDriver)
            {
                //"namespaces"
                try
                {
                    reader.SetFeature(Constants.NamespacesFeature, true);
                }
                catch (Exception e)
                {
#if DEBUG
                    Debugger.Break();
#endif
                }

                //"namespace-prefixes"
                try
                {
                    reader.SetFeature(Constants.NamespacePrefixesFeature, true);
                }
                catch (Exception e)
                {
#if DEBUG
                    Debugger.Break();
#endif
                }

                //"external-general-entities"
                try
                {
                    reader.SetFeature(Constants.ExternalGeneralFeature, true);
                }
                catch (Exception e)
                {
#if DEBUG
                    Debugger.Break();
#endif
                }

                //"external-parameter-entities"
                try
                {
                    reader.SetFeature(Constants.ExternalParameterFeature, true);
                }
                catch (Exception e)
                {
#if DEBUG
                    Debugger.Break();
#endif
                }

                //"xmlns-uris"
                try
                {
                    reader.SetFeature(Constants.XmlNsUrisFeature, true);
                }
                catch (Exception e)
                {
#if DEBUG
                    Debugger.Break();
#endif
                }

                //"resolve-dtd-uris"
                try
                {
                    reader.SetFeature(Constants.ResolveDtdUrisFeature, true);
                }
                catch (Exception e)
                {
#if DEBUG
                    Debugger.Break();
#endif
                }
            }


            if (reader is ExpatReader)
            {
                // http://xml.org/sax/features/namespaces
                try
                {
                    reader.SetFeature(Constants.NamespacesFeature, true);
                }
                catch (Exception e)
                {
#if DEBUG
                    Debugger.Break();
#endif
                }

                // http://xml.org/sax/features/external-general-entities
                try
                {
                    reader.SetFeature(Constants.ExternalGeneralFeature, true);
                }
                catch (Exception e)
                {
#if DEBUG
                    Debugger.Break();
#endif
                }

                // http://xml.org/sax/features/external-parameter-entities
                try
                {
                    reader.SetFeature(Constants.ExternalParameterFeature, true);
                }
                catch (Exception e)
                {
#if DEBUG
                    Debugger.Break();
#endif
                }

                // http://xml.org/sax/features/resolve-dtd-uris
                try
                {
                    reader.SetFeature(Constants.ResolveDtdUrisFeature, true);
                }
                catch (Exception e)
                {
#if DEBUG
                    Debugger.Break();
#endif
                }

                // http://xml.org/sax/features/lexical-handler/parameter-entities
                try
                {
                    reader.SetFeature(Constants.LexicalParameterFeature, true);
                }
                catch (Exception e)
                {
#if DEBUG
                    Debugger.Break();
#endif
                }

                if (false)
                {
                    try
                    {
                        reader.SetFeature("http://kd-soft.net/sax/features/skip-internal-entities",
                                          false);
                    }
                    catch (Exception e)
                    {
#if DEBUG
                        Debugger.Break();
#endif
                    }

                    try
                    {
                        reader.SetFeature(
                            "http://kd-soft.net/sax/features/parse-unless-standalone", true);
                    }
                    catch (Exception e)
                    {
#if DEBUG
                        Debugger.Break();
#endif
                    }

                    try
                    {
                        reader.SetFeature("http://kd-soft.net/sax/features/parameter-entities", true);
                    }
                    catch (Exception e)
                    {
#if DEBUG
                        Debugger.Break();
#endif
                    }

                    try
                    {
                        reader.SetFeature("http://kd-soft.net/sax/features/standalone-error", true);
                    }
                    catch (Exception e)
                    {
#if DEBUG
                        Debugger.Break();
#endif
                    }
                }

                // SUPPORTED, but then NOT SUPPORTED (deeper inside Expat C# wrapper code)

                //                                    // http://xml.org/sax/features/namespace-prefixes
                //                                    try
                //                                    {
                //                                        reader.SetFeature(Constants.NamespacePrefixesFeature, true);
                //                                    }
                //                                    catch (Exception e)
                //                                    {
                //#if DEBUG
                //                                        Debugger.Break();
                //#endif
                //                                    }

                //                                    // http://xml.org/sax/features/xmlns-uris
                //                                    try
                //                                    {
                //                                        reader.SetFeature(Constants.XmlNsUrisFeature, true);
                //                                    }
                //                                    catch (Exception e)
                //                                    {
                //#if DEBUG
                //                                        Debugger.Break();
                //#endif
                //                                    }
                //                                    // http://xml.org/sax/features/validation
                //                                    try
                //                                    {
                //                                        reader.SetFeature(Constants.ValidationFeature, true);
                //                                    }
                //                                    catch (Exception e)
                //                                    {
                //#if DEBUG
                //                                        Debugger.Break();
                //#endif
                //                                    }

                //                                    // http://xml.org/sax/features/unicode-normalization-checking
                //                                    try
                //                                    {
                //                                        reader.SetFeature(Constants.UnicodeNormCheckFeature, true);
                //                                    }
                //                                    catch (Exception e)
                //                                    {
                //#if DEBUG
                //                                        Debugger.Break();
                //#endif
                //                                    }


                // NOT SUPPORTED:


                // http://xml.org/sax/features/xml-1.1
                //                                    try
                //                                    {
                //                                        reader.SetFeature(Constants.Xml11Feature, true);
                //                                    }
                //                                    catch (Exception e)
                //                                    {
                //#if DEBUG
                //                                        Debugger.Break();
                //#endif
                //                                    }

                // http://xml.org/sax/features/xml-declaration
                //                                    try
                //                                    {
                //                                        reader.SetFeature(Constants.XmlDeclFeature, true);
                //                                    }
                //                                    catch (Exception e)
                //                                    {
                //#if DEBUG
                //                                        Debugger.Break();
                //#endif
                //                                    }

                // http://xml.org/sax/features/use-external-subset
                //                                    try
                //                                    {
                //                                        reader.SetFeature(Constants.UseExternalSubsetFeature, true);
                //                                    }
                //                                    catch (Exception e)
                //                                    {
                //#if DEBUG
                //                                        Debugger.Break();
                //#endif
                //                                    }

                // http://xml.org/sax/features/reader-control
                //                                    try
                //                                    {
                //                                        reader.SetFeature(Constants.ReaderControlFeature, true);
                //                                    }
                //                                    catch (Exception e)
                //                                    {
                //#if DEBUG
                //                                        Debugger.Break();
                //#endif
                //                                    }
            }

            SaxContentHandler handler = new SaxContentHandler(list);

            try
            {
                reader.DtdHandler = handler;
            }
            catch (Exception e)
            {
#if DEBUG
                Debugger.Break();
#endif
                errorHandler.AddMessage("Cannot set dtd handler: " + e.Message);
            }

            try
            {
                reader.ContentHandler = handler;
            }
            catch (Exception e)
            {
#if DEBUG
                Debugger.Break();
#endif
                errorHandler.AddMessage("Cannot set content handler: " + e.Message);
            }

            try
            {
                reader.LexicalHandler = handler;
            }
            catch (Exception e)
            {
#if DEBUG
                Debugger.Break();
#endif
                errorHandler.AddMessage("Cannot set lexical handler: " + e.Message);
            }

            try
            {
                reader.DeclHandler = handler;
            }
            catch (Exception e)
            {
#if DEBUG
                Debugger.Break();
#endif
                errorHandler.AddMessage("Cannot set declaration handler: " + e.Message);
            }

            string rootElementName = isHTML ? @"html" : @"dtbook";
            string dtdWrapper      = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE " + rootElementName + " SYSTEM \"" + dtdID + "\"><" + rootElementName + "></" + rootElementName + ">";
            //StringReader strReader = new StringReader(dtdWrapper);
            Stream      stream    = new MemoryStream(Encoding.UTF8.GetBytes(dtdWrapper));
            TextReader  txtReader = new StreamReader(stream, Encoding.UTF8);
            InputSource input     = new InputSource <TextReader>(txtReader, dtdID + "/////SYSID");
            input.Encoding = "UTF-8";
            input.PublicId = "??";

            reader.Parse(input);
#endif //ENABLE_DTDSHARP


            return(docMarkupType);
        }
Пример #16
0
        protected override 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;
            }
            // assign obi project file path to xuk path to prevent creation of xukspine file.
            XukPath = m_session.Path;
            //Console.WriteLine(XukPath);

            Presentation spinePresentation = m_Project.Presentations.Get(0);

            m_IsTOCFromNavDoc = false;
            if (navDocPath != null)
            {
                string fullNavPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), navDocPath);

                XmlDocument navDoc = urakawa.xuk.XmlReaderWriterHelper.ParseXmlDocument(fullNavPath, true, true);
                ParseNCXDocument(navDoc);
                m_IsTOCFromNavDoc = true;
            }
            //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();
            TreenodesWithoutManagedAudioMediaData = new List <TreeNode>();
            Presentation spineItemPresentation = null;

            int index = -1;

            foreach (string docPath in spineOfContentDocuments)
            {
                index++;

                reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ReadXMLDoc, docPath));
                //System.Windows.Forms.MessageBox.Show(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 (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)
                    {
                        ExternalFileData externalData = null;
                        if (docPath == coverImagePath)
                        {
                            externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create
                                           <CoverImageExternalFileData>();
                        }
                        else
                        {
                            externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create
                                           <GenericExternalFileData>();
                        }
                        if (externalData != null)
                        {
                            externalData.InitializeWithData(fullDocPath, docPath, true, null);

                            addOPF_GlobalAssetPath(fullDocPath);
                        }
                    }

                    continue;
                }

                //spineChild.GetOrCreateXmlProperty().SetAttribute("xuk", "", "true");

                XmlDocument xmlDoc = urakawa.xuk.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),

                //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;

                //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());


                if (m_AudioConversionSession != null)
                {
                    RemoveSubCancellable(m_AudioConversionSession);
                    m_AudioConversionSession = null;
                }

                m_AudioConversionSession = new AudioFormatConvertorSession(
                    m_Presentation.DataProviderManager.DataFileDirectoryFullPath,
                    m_Presentation.MediaDataManager.DefaultPCMFormat,
                    m_autoDetectPcmFormat,
                    true);

                //AddSubCancellable(m_AudioConversionSession);



                if (RequestCancellation)
                {
                    return;
                }

                if (parseContentDocParts(fullDocPath, m_Project, xmlDoc, docPath, DocumentMarkupType.NA))
                {
                    return; // user cancel
                }



                /*
                 * 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);
                 *  }
                 * }
                 */

                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);

                        SectionNode           section      = m_Presentation.FirstSection;
                        IEnumerable <XmlNode> textElements = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(overlayXmlDoc, true, "text", null, false);
                        if (textElements == null)
                        {
                            continue;
                        }
                        // audio list replaced by text list
                        //IEnumerable<XmlNode> audioElements = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(overlayXmlDoc, true, "audio", null, false);
                        //if (audioElements == null)
                        //{
                        //continue;
                        //}

                        //foreach (XmlNode audioNode in audioElements)
                        foreach (XmlNode textNode in textElements)
                        {
                            XmlAttributeCollection attrs = textNode.Attributes;
                            if (attrs == null)
                            {
                                continue;
                            }
                            //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;
                            XmlNode    audioNode    = null;
                            PageNumber pgNumber     = null;
                            //XmlNodeList children = audioNode.ParentNode.ChildNodes;
                            XmlNodeList children = textNode.ParentNode.ChildNodes;
                            foreach (XmlNode child in children)
                            {
                                //if (child == audioNode)
                                //{
                                //continue;
                                //}
                                //if (child.LocalName != "text")
                                //{
                                //continue;
                                //}
                                if (child.LocalName == "audio")
                                {
                                    audioNode = child;
                                }

                                //XmlAttributeCollection textAttrs = child.Attributes;
                                XmlAttributeCollection textAttrs = textNode.Attributes;
                                if (textAttrs == null)
                                {
                                    continue;
                                }

                                XmlNode textSrc = textAttrs.GetNamedItem("src");
                                if (textSrc == null)
                                {
                                    continue;
                                }

                                string urlDecoded = FileDataProvider.UriDecode(textSrc.Value);
                                string contentFilesDirectoryPath = Path.GetDirectoryName(fullOverlayPath);
                                if (urlDecoded.StartsWith("./"))
                                {
                                    urlDecoded = urlDecoded.Remove(0, 2);
                                }
                                if (urlDecoded.StartsWith("../"))
                                {
                                    urlDecoded = urlDecoded.Remove(0, 3);
                                    contentFilesDirectoryPath = Path.GetDirectoryName(contentFilesDirectoryPath);
                                }
                                if (urlDecoded.IndexOf('#') > 0)
                                {
                                    string[] srcParts = urlDecoded.Split('#');
                                    if (srcParts.Length != 2)
                                    {
                                        continue;
                                    }

                                    string fullTextRefPath = Path.Combine(contentFilesDirectoryPath,
                                                                          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);
                                    // replacing it
                                    //System.Windows.Forms.MessageBox.Show("retrieving: " + urlDecoded);
                                    if (m_XmlIdToSectionNodeMap.ContainsKey(urlDecoded))
                                    {
                                        textTreeNode = m_XmlIdToSectionNodeMap[urlDecoded];
                                    }
                                    else if (m_XmlIdToSectionNodeMap.ContainsKey(srcParts[0]))
                                    {
                                        textTreeNode = m_XmlIdToSectionNodeMap[srcParts[0]];
                                    }
                                    if (textTreeNode != null)
                                    {
                                        section = (SectionNode)textTreeNode;
                                        //System.Windows.Forms.MessageBox.Show(((SectionNode)textTreeNode).Label);
                                    }
                                }
                                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 (m_XmlIdToPageNodeMap.ContainsKey(urlDecoded) &&
                                    m_XmlIdToPageNodeMap[urlDecoded] != null)
                                {
                                    EmptyNode pgNode = m_XmlIdToPageNodeMap[urlDecoded];
                                    pgNumber = pgNode.PageNumber;

                                    // if the section does not match then the parent of the page node should become the section.
                                    if (pgNode.IsRooted &&
                                        textTreeNode == null &&
                                        pgNode.Parent != section)
                                    {
                                        section = pgNode.ParentAs <SectionNode>();
                                        //Console.WriteLine("text node is null");
                                    }
                                    if (pgNode.IsRooted)
                                    {
                                        pgNode.Detach();
                                    }
                                    // the phrases following the page phrase in smil will refer to same content doc ID. so to avoid reassigning page, the page node in dictionary is assigned to null.
                                    m_XmlIdToPageNodeMap[urlDecoded] = null;
                                }
                            }

                            if (section != null && audioNode != null)
                            {
                                PhraseNode audioWrapperNode = m_Presentation.CreatePhraseNode();

                                section.AppendChild(audioWrapperNode);
                                addAudio(audioWrapperNode, audioNode, false, fullOverlayPath);
                                if (audioWrapperNode.Duration == 0 && !TreenodesWithoutManagedAudioMediaData.Contains(audioWrapperNode))
                                {
                                    TreenodesWithoutManagedAudioMediaData.Add(audioWrapperNode);
                                }
                                if (pgNumber != null)
                                {
                                    audioWrapperNode.PageNumber = pgNumber;
                                    pgNumber = null;
                                }
                            }

                            audioNode = null;
                        }
                    }
                }


                //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);
                     * }
                     */
                }
            }
        }
Пример #17
0
        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);
                //}
            }
        }
Пример #18
0
        private void parseHeadLinks(string rootFilePath, Project project, XmlDocument contentDoc)
        {
            XmlNode headXmlNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(contentDoc.DocumentElement, true, "head", null);

            if (headXmlNode == null)
            {
                return;
            }

            Presentation presentation = project.Presentations.Get(0);

            List <string> externalFileRelativePaths = new List <string>();

            foreach (ExternalFiles.ExternalFileData extData in presentation.ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable)
            {
                if (!string.IsNullOrEmpty(extData.OriginalRelativePath))
                {
                    string fullPath = Path.Combine(Path.GetDirectoryName(rootFilePath), extData.OriginalRelativePath);
                    string relPath  = FileDataProvider.NormaliseFullFilePath(fullPath).Replace('/', '\\');

                    if (!externalFileRelativePaths.Contains(relPath))
                    {
                        externalFileRelativePaths.Add(relPath);
                    }
                }
            }

            List <XmlNode> externalFilesLinks = new List <XmlNode>();

            externalFilesLinks.AddRange(XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headXmlNode, true, "link", headXmlNode.NamespaceURI, false));
            externalFilesLinks.AddRange(XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headXmlNode, true, "script", headXmlNode.NamespaceURI, false));
            externalFilesLinks.AddRange(XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headXmlNode, true, "style", headXmlNode.NamespaceURI, false));
            externalFilesLinks.AddRange(XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headXmlNode, true, "title", headXmlNode.NamespaceURI, false));

            foreach (XmlNode linkNode in externalFilesLinks)
            {
                TreeNode treeNode = presentation.TreeNodeFactory.Create();
                presentation.HeadNode.AppendChild(treeNode);
                XmlProperty xmlProp = presentation.PropertyFactory.CreateXmlProperty();
                treeNode.AddProperty(xmlProp);
                xmlProp.SetQName(linkNode.LocalName,
                                 headXmlNode.NamespaceURI == linkNode.NamespaceURI ? "" : linkNode.NamespaceURI);
                //Console.WriteLine("XmlProperty: " + xmlProp.LocalName);

                foreach (System.Xml.XmlAttribute xAttr in linkNode.Attributes)
                {
                    if (
                        //xAttr.LocalName.Equals(XmlReaderWriterHelper.NS_PREFIX_XMLNS, StringComparison.OrdinalIgnoreCase)
                        //|| xAttr.LocalName.Equals("xsi", StringComparison.OrdinalIgnoreCase)
                        xAttr.NamespaceURI.Equals(XmlReaderWriterHelper.NS_URL_XMLNS, StringComparison.OrdinalIgnoreCase) ||
                        xAttr.LocalName.Equals("space", StringComparison.OrdinalIgnoreCase) &&
                        xAttr.NamespaceURI.Equals(XmlReaderWriterHelper.NS_URL_XML, StringComparison.OrdinalIgnoreCase)
                        )
                    {
                        continue;
                    }

                    xmlProp.SetAttribute(xAttr.Name,
                                         linkNode.NamespaceURI == xAttr.NamespaceURI ? "" : xAttr.NamespaceURI,
                                         xAttr.Value);

                    if ((xAttr.Name.Equals("href", StringComparison.OrdinalIgnoreCase) ||
                         xAttr.Name.Equals("src", StringComparison.OrdinalIgnoreCase)) &&
                        !string.IsNullOrEmpty(xAttr.Value) &&
                        !FileDataProvider.isHTTPFile(xAttr.Value))
                    {
                        string urlDecoded = FileDataProvider.UriDecode(xAttr.Value);

                        string fullPath     = Path.Combine(Path.GetDirectoryName(rootFilePath), urlDecoded);
                        string pathFromAttr = FileDataProvider.NormaliseFullFilePath(fullPath).Replace('/', '\\');

                        if (!externalFileRelativePaths.Contains(pathFromAttr))
                        {
                            if (File.Exists(pathFromAttr))
                            {
                                ExternalFiles.ExternalFileData efd = presentation.ExternalFilesDataFactory.Create <ExternalFiles.GenericExternalFileData>();
                                try
                                {
                                    efd.InitializeWithData(pathFromAttr, urlDecoded, true, null);

                                    externalFileRelativePaths.Add(pathFromAttr);

                                    addOPF_GlobalAssetPath(pathFromAttr);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.Message);
                                    Console.WriteLine(ex.StackTrace);

#if DEBUG
                                    Debugger.Break();
#endif
                                }
                            }
#if DEBUG
                            else
                            {
                                Debugger.Break();
                            }
#endif
                        }
                    }
                }

                string innerText = linkNode.InnerText; // includes CDATA sections! (merges "//" javascript comment markers too)

                if (!string.IsNullOrEmpty(innerText))
                {
                    urakawa.media.TextMedia textMedia = presentation.MediaFactory.CreateTextMedia();
                    textMedia.Text = innerText;
                    ChannelsProperty cProp = presentation.PropertyFactory.CreateChannelsProperty();
                    cProp.SetMedia(presentation.ChannelsManager.GetOrCreateTextChannel(), textMedia);
                    treeNode.AddProperty(cProp);
                    //Console.WriteLine("Link inner text: " + textMedia.Text);
                }
            }
        }
Пример #19
0
        private void handleAdditionalManifestItems(string opfPath, XmlDocument opfXmlDoc)
        {
            XmlNode manifNodeRoot = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(opfXmlDoc, true, "manifest", null);

            if (manifNodeRoot == null)
            {
                return;
            }

            XmlNodeList listOfManifestItemNodes = manifNodeRoot.ChildNodes;

            foreach (XmlNode manifItemNode in listOfManifestItemNodes)
            {
                if (RequestCancellation)
                {
                    return;
                }

                if (manifItemNode.NodeType != XmlNodeType.Element ||
                    manifItemNode.LocalName != "item")
                {
                    continue;
                }

                XmlAttributeCollection manifItemAttributes = manifItemNode.Attributes;
                if (manifItemAttributes == null)
                {
                    continue;
                }

                XmlNode attrHref      = manifItemAttributes.GetNamedItem("href");
                XmlNode attrMediaType = manifItemAttributes.GetNamedItem("media-type");
                if (attrHref == null || String.IsNullOrEmpty(attrHref.Value) ||
                    attrMediaType == null || String.IsNullOrEmpty(attrMediaType.Value))
                {
                    continue;
                }

                if (FileDataProvider.isHTTPFile(attrHref.Value))
                {
                    continue;
                }

                if (attrHref.Value.EndsWith(@".opf"))
                {
                    continue;
                }

                if (attrMediaType.Value == DataProviderFactory.SMIL_MIME_TYPE ||
                    attrMediaType.Value == DataProviderFactory.SMIL_MIME_TYPE_ ||
                    attrMediaType.Value == DataProviderFactory.DTBOOK_MIME_TYPE ||
                    attrMediaType.Value == DataProviderFactory.DTB_RES_MIME_TYPE ||
                    attrMediaType.Value == DataProviderFactory.NCX_MIME_TYPE
                    )
                {
                    continue;
                }


                string href = FileDataProvider.UriDecode(attrHref.Value);

                string fullPath = Path.Combine(Path.GetDirectoryName(opfPath), href);
                fullPath = FileDataProvider.NormaliseFullFilePath(fullPath).Replace('/', '\\');

                bool alreadyPreserved = false;
                foreach (
                    //ExternalFiles.ExternalFileData exfiledata in m_Project.Presentations.Get(0).ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable
                    string path in m_OPF_GlobalAssetPaths
                    )
                {
                    if (path == fullPath)
                    {
                        alreadyPreserved = true;
                        break;
                    }

                    //if (!string.IsNullOrEmpty(exfiledata_OriginalRelativePath))
                    //{
                    //    string fp = Path.Combine(opfPath, exfiledata_OriginalRelativePath);
                    //    fp = FileDataProvider.NormaliseFullFilePath(fp).Replace('/', '\\');
                    //}
                }

                if (alreadyPreserved)
                {
                    continue;
                }

                if (!File.Exists(fullPath))
                {
#if DEBUG
                    Debugger.Break();
#endif
                    continue;
                }

                string  optionalInfo   = null;
                XmlNode attrProperties = manifItemAttributes.GetNamedItem("properties");
                if (attrProperties != null)
                {
                    optionalInfo = attrProperties.Value;
                }

                ExternalFiles.ExternalFileData efd = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.GenericExternalFileData>();
                try
                {
                    efd.InitializeWithData(fullPath, href, true, optionalInfo);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);

#if DEBUG
                    Debugger.Break();
#endif
                }
            }
        }
Пример #20
0
        private void parseContainerXML(string 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"));

            m_OPF_ContainerRelativePath = FileDataProvider.UriDecode(fullPathAttr.Value);

            if (m_OPF_ContainerRelativePath.StartsWith(@"./"))
            {
                m_OPF_ContainerRelativePath = m_OPF_ContainerRelativePath.Substring(2);
            }

            m_Book_FilePath = Path.Combine(rootDirectory, m_OPF_ContainerRelativePath.Replace('/', '\\'));


            openAndParseOPF(m_Book_FilePath);



            //if (!string.IsNullOrEmpty(m_OPF_ContainerRelativePath))

            string metaInfDir = Path.GetDirectoryName(containerPath);

            DirectoryInfo dirInfo = new DirectoryInfo(metaInfDir);

#if NET40
            IEnumerable <FileInfo> fileInfos = dirInfo.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly);
#else
            FileInfo[] fileInfos = dirInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);
#endif
            foreach (FileInfo fileInfo in fileInfos)
            {
                ExternalFiles.ExternalFileData efd = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.GenericExternalFileData>();
                try
                {
                    string relativePath = META_INF_prefix + fileInfo.Name;

                    efd.InitializeWithData(fileInfo.FullName, relativePath, true, null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);

#if DEBUG
                    Debugger.Break();
#endif
                }
            }
        }
        private void parseOpf(XmlDocument opfXmlDoc)
        {
            List <string> spine;
            Dictionary <string, string>         spineAttributes;
            List <Dictionary <string, string> > spineItemsAttributes;
            string spineMimeType;
            string dtbookPath;
            string ncxPath;
            string navDocPath;
            string coverImagePath;

            if (RequestCancellation)
            {
                return;
            }

            XmlNode packageNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(opfXmlDoc, true, "package", null);

            if (packageNode != null)
            {
                XmlAttributeCollection packageNodeAttrs = packageNode.Attributes;
                if (packageNodeAttrs != null && packageNodeAttrs.Count > 0)
                {
                    m_PackageUniqueIdAttr = packageNodeAttrs.GetNamedItem("unique-identifier");
                    m_PackagePrefixAttr   = packageNodeAttrs.GetNamedItem("prefix");
                }
            }

            string idCoverImageFromMetadata    = null;
            IEnumerable <XmlNode> metaElements = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(opfXmlDoc, true, "meta", null, false);

            foreach (XmlNode metaElement in metaElements)
            {
                XmlAttributeCollection metaElementAttributes = metaElement.Attributes;

                if (metaElementAttributes == null || metaElementAttributes.Count <= 0)
                {
                    continue;
                }

                XmlNode attrName = metaElementAttributes.GetNamedItem("name");
                if (attrName == null || string.IsNullOrEmpty(attrName.Value) ||
                    attrName.Value != @"cover")
                {
                    continue;
                }

                XmlNode attrContent = metaElementAttributes.GetNamedItem("content");
                if (attrContent == null && string.IsNullOrEmpty(attrContent.Value))
                {
                    continue;
                }

                idCoverImageFromMetadata = attrContent.Value;
                break;
            }

            parseOpfManifest(opfXmlDoc, out spine, out spineAttributes, out spineItemsAttributes, out spineMimeType, out dtbookPath, out ncxPath, out navDocPath, out coverImagePath, idCoverImageFromMetadata);

            if (RequestCancellation)
            {
                return;
            }

            m_IsSpine = spineMimeType == DataProviderFactory.XHTML_MIME_TYPE ||
                        spineMimeType == DataProviderFactory.IMAGE_SVG_MIME_TYPE;
            DebugFix.Assert(m_IsSpine == !(spineMimeType == DataProviderFactory.SMIL_MIME_TYPE_));

            if (m_IsSpine)
            {
                reInitialiseProjectSpine();
            }
            XmlNode metadataXmlNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(opfXmlDoc.DocumentElement, true, "metadata", null);

            parseMetadata(m_Book_FilePath, m_Project, opfXmlDoc, metadataXmlNode);

            m_PublicationUniqueIdentifier_OPF     = m_PublicationUniqueIdentifier;
            m_PublicationUniqueIdentifierNode_OPF = m_PublicationUniqueIdentifierNode;

            if (dtbookPath != null && !m_IsSpine &&
                !AudioNCXImport)
            {
                if (RequestCancellation)
                {
                    return;
                }
                string      fullDtbookPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), dtbookPath);
                XmlDocument dtbookXmlDoc   = XmlReaderWriterHelper.ParseXmlDocument(fullDtbookPath, true, true);

                if (parseContentDocParts(fullDtbookPath, m_Project, dtbookXmlDoc, dtbookPath, DocumentMarkupType.DTBOOK))
                {
                    return; // user cancel
                }

                //if (RequestCancellation) return;
                //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMetadata, dtbookPath));
                //parseMetadata(m_Book_FilePath, m_Project, dtbookXmlDoc);

                //if (RequestCancellation) return;
                //ParseHeadLinks(m_Book_FilePath, m_Project, dtbookXmlDoc);

                //if (RequestCancellation) return;
                //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingContent, dtbookPath));
                //parseContentDocument(m_Book_FilePath, m_Project, dtbookXmlDoc, null, fullDtbookPath, null, DocumentMarkupType.DTBOOK);
            }

            //if (false && ncxPath != null) //we skip NCX metadata parsing (we get publication metadata only from OPF and DTBOOK/XHTMLs)
            if (
                //(string.IsNullOrEmpty(dtbookPath) && !string.IsNullOrEmpty(ncxPath))  ||
                AudioNCXImport)
            {
                //m_IsAudioNCX = true;
                if (RequestCancellation)
                {
                    return;
                }
                string      fullNcxPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), ncxPath);
                XmlDocument ncxXmlDoc   = XmlReaderWriterHelper.ParseXmlDocument(fullNcxPath, false, false);

                if (RequestCancellation)
                {
                    return;
                }
                reportProgress(-1, "Parsing metadata: [" + ncxPath + "]");

                XmlNode headXmlNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(ncxXmlDoc.DocumentElement, true, "head", null);
                parseMetadata(fullNcxPath, m_Project, ncxXmlDoc, headXmlNode);

                if (AudioNCXImport)
                {
                    ParseNCXDocument(ncxXmlDoc);
                }
            }

            if (RequestCancellation)
            {
                return;
            }
            switch (spineMimeType)
            {
            case DataProviderFactory.SMIL_MIME_TYPE_:
            {
                parseSmiles(spine);
                break;
            }

            case DataProviderFactory.XHTML_MIME_TYPE:
            case DataProviderFactory.IMAGE_SVG_MIME_TYPE:
            {
                if (!string.IsNullOrEmpty(coverImagePath) && !spine.Contains(coverImagePath))
                {
                    string fullCoverImagePath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), coverImagePath);
                    fullCoverImagePath = FileDataProvider.NormaliseFullFilePath(fullCoverImagePath).Replace('/', '\\');

                    if (File.Exists(fullCoverImagePath))
                    {
                        ExternalFiles.ExternalFileData externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.CoverImageExternalFileData>();
                        try
                        {
                            externalData.InitializeWithData(fullCoverImagePath, coverImagePath, true, null);

                            addOPF_GlobalAssetPath(fullCoverImagePath);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                            Console.WriteLine(ex.StackTrace);

#if DEBUG
                            Debugger.Break();
#endif
                        }
                    }
#if DEBUG
                    else
                    {
                        Debugger.Break();
                    }
#endif
                }

                if (!string.IsNullOrEmpty(navDocPath) && !spine.Contains(navDocPath))
                {
                    string fullNavDocPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), navDocPath);
                    fullNavDocPath = FileDataProvider.NormaliseFullFilePath(fullNavDocPath).Replace('/', '\\');

                    if (File.Exists(fullNavDocPath))
                    {
                        ExternalFiles.ExternalFileData externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.NavDocExternalFileData>();
                        try
                        {
                            externalData.InitializeWithData(fullNavDocPath, navDocPath, true, null);

                            addOPF_GlobalAssetPath(fullNavDocPath);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                            Console.WriteLine(ex.StackTrace);

#if DEBUG
                            Debugger.Break();
#endif
                        }
                    }
#if DEBUG
                    else
                    {
                        Debugger.Break();
                    }
#endif
                }

                if (!string.IsNullOrEmpty(ncxPath))
                {
                    string fullNcxPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), ncxPath);
                    fullNcxPath = FileDataProvider.NormaliseFullFilePath(fullNcxPath).Replace('/', '\\');

                    if (File.Exists(fullNcxPath))
                    {
                        ExternalFiles.ExternalFileData externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.NCXExternalFileData>();
                        try
                        {
                            externalData.InitializeWithData(fullNcxPath, ncxPath, true, null);

                            addOPF_GlobalAssetPath(fullNcxPath);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                            Console.WriteLine(ex.StackTrace);

#if DEBUG
                            Debugger.Break();
#endif
                        }
                    }
#if DEBUG
                    else
                    {
                        Debugger.Break();
                    }
#endif
                }

                parseContentDocuments(spine, spineAttributes, spineItemsAttributes, coverImagePath, navDocPath);

                break;
            }
            }
        }
Пример #22
0
        private void parseSmilForNCX(string fullSmilPath)
        {
            //foreach (string s in m_SmilRefToNavPointTreeNodeMap.Keys) System.Windows.Forms.MessageBox.Show(s + " : " + m_SmilRefToNavPointTreeNodeMap[s].GetXmlElementLocalName() );
            if (RequestCancellation)
            {
                return;
            }
            XmlDocument smilXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullSmilPath, false, false);

            if (RequestCancellation)
            {
                return;
            }
            m_SmilXmlNodeToTreeNodeMap = new Dictionary <XmlNode, TreeNode>();
            //we skip SMIL metadata parsing (we get publication metadata only from OPF and DTBOOK/XHTMLs)
            //parseMetadata(smilXmlDoc);

            //XmlNodeList allTextNodes = smilXmlDoc.GetElementsByTagName("text");
            //if (allTextNodes.Count == 0)
            //{
            //    return;
            //}

            //reportProgress(-1, "Parsing SMIL: [" + Path.GetFileName(fullSmilPath) + "]");
            TreeNode navPointTreeNode = null;

            XmlNamespaceManager firstDocNSManager = new XmlNamespaceManager(smilXmlDoc.NameTable);

            firstDocNSManager.AddNamespace("firstNS",
                                           smilXmlDoc.DocumentElement.NamespaceURI);
            bool     isHeading        = false;
            bool     isPageInProcess  = false;
            TreeNode audioWrapperNode = null;


            XmlNodeList smilNodeList = smilXmlDoc.DocumentElement.SelectNodes(".//firstNS:seq | .//firstNS:par",
                                                                              firstDocNSManager);

            //foreach (XmlNode parNode in XmlDocumentHelper.GetChildrenElementsWithName(smilXmlDoc, true, "par", null, false))
            foreach (XmlNode parNode in smilNodeList)
            {
                XmlAttributeCollection parNodeAttrs = parNode.Attributes;
                if (parNodeAttrs == null || parNodeAttrs.Count == 0)
                {
                    continue;
                }
                //XmlNode textNodeAttrSrc = parNodeAttrs.GetNamedItem("src");
                XmlNode parNodeID = parNodeAttrs.GetNamedItem("id");
                if (parNodeID == null || String.IsNullOrEmpty(parNodeID.Value))
                {
                    continue;
                }


                string ncxContentSRC = Path.GetFileName(fullSmilPath) + "#" + parNodeID.Value;

                TreeNode obj;
                m_SmilRefToNavPointTreeNodeMap.TryGetValue(ncxContentSRC, out obj);

                // for now we are assuming the first phrase as heading phrase. this need refinement such that phrase anywhere in section can be imported as heading)
                if (obj != null) //m_SmilRefToNavPointTreeNodeMap.ContainsKey(ncxContentSRC))
                {
                    m_IsDocTitleCreated = true;
                    navPointTreeNode    = obj; // m_SmilRefToNavPointTreeNodeMap[ncxContentSRC];
                    //System.Windows.Forms.MessageBox.Show(ncxContentSRC + " section:" + navPointTreeNode.GetXmlElementLocalName() + " : " + Path.GetFileName( fullSmilPath ) );
                    //: audioWrapperNode =  CreateTreeNodeForAudioNode(navPointTreeNode, true);
                    //isHeading = true;
                }

                // handle doctitle if audio exists before first heading by adding doctitle node as first treenode
                if (navPointTreeNode == null && !m_IsDocTitleCreated &&
                    (XmlDocumentHelper.GetFirstChildElementOrSelfWithName(parNode, false, "audio", null) != null || XmlDocumentHelper.GetFirstChildElementOrSelfWithName(parNode, false, "text", null) != null))
                {
                    m_IsDocTitleCreated = true;
                    navPointTreeNode    = CreateTreeNodeForNavPoint(m_Project.Presentations.Get(0).RootNode, m_DocTitleXmlNode);
                    m_NavPointNode_NavLabelMap.Add(navPointTreeNode, m_DocTitleXmlNode);
                }
                //else if (m_PageReferencesMapDictionaryForNCX.ContainsKey(ncxContentSRC)

                if (m_PageReferencesMapDictionaryForNCX.ContainsKey(ncxContentSRC) ||
                    (parNode.Attributes.GetNamedItem("customTest") != null &&
                     parNode.Attributes.GetNamedItem("customTest").Value == "pagenum"))
                {
                    isPageInProcess = true;
                    if (navPointTreeNode == null)
                    {
                        continue;
                    }
                    //:audioWrapperNode = CreateTreeNodeForAudioNode(navPointTreeNode, false);
                }



                if (navPointTreeNode == null)
                {
                    continue;
                }

                //System.Windows.Forms.MessageBox.Show(parNode.LocalName);

                ManagedAudioMedia textTreeNodeAudio = navPointTreeNode.GetManagedAudioMedia();
                if (textTreeNodeAudio != null)
                {
                    //Ignore.
                    continue;
                }


                XmlNodeList textPeers = parNode.ChildNodes;
                foreach (XmlNode textPeerNode in textPeers)
                //foreach (XmlNode textPeerNode in XmlDocumentHelper.GetChildrenElementsWithName(parNode, true, "audio", null, false))
                {
                    if (RequestCancellation)
                    {
                        return;
                    }

                    //if (XmlDocumentHelper.GetFirstChildElementWithName(parNode, false, "audio", null) == null) continue;
                    if (textPeerNode.NodeType != XmlNodeType.Element)
                    {
                        continue;
                    }
                    if (textPeerNode.LocalName == "audio")
                    {
                        audioWrapperNode = CreateTreeNodeForAudioNode(navPointTreeNode, isHeading, textPeerNode, fullSmilPath);
                        CheckAndAssignForHeadingAudio(navPointTreeNode, audioWrapperNode, textPeerNode);
                        XmlProperty xmlProp = navPointTreeNode.Presentation.PropertyFactory.CreateXmlProperty();
                        audioWrapperNode.AddProperty(xmlProp);

                        // +":" + navPointTreeNode.GetTextFlattened(false);
                        xmlProp.SetQName("phrase", "");

                        string pageRefInSmil = Path.GetFileName(fullSmilPath) + "#" + parNode.Attributes.GetNamedItem("id").Value;

                        XmlNode xNode;
                        m_PageReferencesMapDictionaryForNCX.TryGetValue(pageRefInSmil, out xNode);

                        if (xNode != null && //m_PageReferencesMapDictionaryForNCX.ContainsKey(pageRefInSmil)
                            isPageInProcess)
                        {
                            isPageInProcess = false;
                            XmlNode pageTargetNode = xNode; //m_PageReferencesMapDictionaryForNCX[pageRefInSmil];

                            AddPagePropertiesToAudioNode(audioWrapperNode, pageTargetNode);
                        }
                        isHeading = false;


                        addAudio(audioWrapperNode, textPeerNode, false, fullSmilPath);
                        break;
                    }
                    else if (textPeerNode.LocalName == "a")
                    {
                        XmlNodeList aChildren = textPeerNode.ChildNodes;
                        foreach (XmlNode aChild in aChildren)
                        {
                            if (aChild.LocalName == "audio")
                            {
                                //addAudio(audioWrapperNode, aChild, false, fullSmilPath);
                                audioWrapperNode = CreateTreeNodeForAudioNode(navPointTreeNode, false, aChild, fullSmilPath);
                                addAudio(audioWrapperNode, aChild, false, fullSmilPath);
                                break;
                            }
                            else
                            {
                                AddAnchorNode(navPointTreeNode, textPeerNode, fullSmilPath);
                                break;
                            }
                        }
                    }
                    else if (textPeerNode.LocalName == "seq" || textPeerNode.LocalName == "par")
                    {
                        if (audioWrapperNode != null)
                        {
                            m_SmilXmlNodeToTreeNodeMap.Add(textPeerNode, audioWrapperNode);
                        }

                        /*
                         *    XmlNodeList seqChildren = textPeerNode.ChildNodes;
                         *    foreach (XmlNode seqChild in seqChildren)
                         *    //1{
                         *        if (seqChild.LocalName == "audio")
                         *        {//2
                         *            addAudio(audioWrapperNode, seqChild, true, fullSmilPath);
                         *        }//-2
                         *    }//-1
                         *
                         *    SequenceMedia seqManAudioMedia = audioWrapperNode.GetManagedAudioSequenceMedia();
                         *    if (seqManAudioMedia == null)
                         *    {//1
                         *        //Debug.Fail("This should never happen !");
                         *        break;
                         *    }//-1
                         *
                         *    ManagedAudioMedia managedAudioMedia = audioWrapperNode.Presentation.MediaFactory.CreateManagedAudioMedia();
                         *    AudioMediaData mediaData = audioWrapperNode.Presentation.MediaDataFactory.CreateAudioMediaData();
                         *    managedAudioMedia.AudioMediaData = mediaData;
                         *
                         *    foreach (Media seqChild in seqManAudioMedia.ChildMedias.ContentsAs_YieldEnumerable)
                         *    {//1
                         *        ManagedAudioMedia seqManMedia = (ManagedAudioMedia)seqChild;
                         *        mediaData.MergeWith(seqManMedia.AudioMediaData);
                         *    }//-1
                         *
                         *    ChannelsProperty chProp = audioWrapperNode.GetChannelsProperty();
                         *    chProp.SetMedia(m_audioChannel, null);
                         *    chProp.SetMedia(m_audioChannel, managedAudioMedia);
                         */
                        break;
                    }
                }
            }
        }
Пример #23
0
        public void TestOCLAdaptation(object directory)
        {
            DirectoryInfo testDir = new DirectoryInfo(directory.ToString());

            try
            {
                FileInfo[] inputFiles  = testDir.GetFiles("*in.xml");
                FileInfo   projectFile = testDir.GetFiles("*.eXo").FirstOrDefault();

                if (projectFile == null)
                {
                    Assert.Fail("No project file found for test {0}", testDir.Name);
                }

                FileInfo[] stylesheetFiles = testDir.GetFiles("*.xslt");

                FileInfo referenceStylesheetFileInfo = null;

                foreach (FileInfo stylesheetFile in stylesheetFiles)
                {
                    if (stylesheetFile.Name.Contains("DesiredStylesheet") ||
                        stylesheetFile.Name.Contains("LastStylesheet") ||
                        stylesheetFile.Name.Contains("generated") ||
                        stylesheetFile.Name.Contains("last-working"))
                    {
                        continue;
                    }

                    referenceStylesheetFileInfo = stylesheetFile;
                }

                Project project = serializationManager.LoadProject(projectFile);

                XsltAdaptationScriptGenerator generator               = new XsltAdaptationScriptGenerator();
                ChangeDetector             detector                   = new ChangeDetector();
                PSMSchema                  psmSchemaOldVersion        = project.ProjectVersions[0].PSMSchemas.First();
                PSMSchema                  psmSchemaNewVersion        = project.ProjectVersions[1].PSMSchemas.First();
                DetectedChangeInstancesSet detectedChangeInstancesSet = detector.DetectChanges(psmSchemaOldVersion, psmSchemaNewVersion);
                generator.Initialize(psmSchemaOldVersion, psmSchemaNewVersion, detectedChangeInstancesSet);
                generator.SchemaAware = true;
                generator.GenerateTransformationStructure();
                XDocument testGeneratedStylesheet         = generator.GetAdaptationTransformation();
                string    testGeneratedStylesheetFileName = testDir.FullName + "/" + testDir.Name + "-generated.xslt";
                testGeneratedStylesheet.SaveInUtf8(testGeneratedStylesheetFileName);
                Console.WriteLine("Revalidation stylesheet generated.");
                Console.WriteLine();

                string generatedStylesheetText = File.ReadAllText(testGeneratedStylesheetFileName);

                StringBuilder failMessage         = new StringBuilder();
                int           failCounts          = 0;
                StringBuilder inconclusiveMessage = new StringBuilder();


                if (referenceStylesheetFileInfo != null)
                {
                    //XDocument xdRefStylesheet = XDocument.Load(referenceStylesheet.FullName);
                    //xdRefStylesheet.RemoveComments();
                    //string  referenceStylesheetText = xdRefStylesheet.ToString();
                    //XDocument xdGenStylesheet = XDocument.Load(testGeneratedStylesheetFile);
                    //xdGenStylesheet.RemoveComments();
                    //generatedStylesheetText = xdGenStylesheet.ToString();
                    string diff;
                    if (XmlDocumentHelper.DocumentCompare(testGeneratedStylesheetFileName, referenceStylesheetFileInfo.FullName, out diff,
                                                          XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreWhitespace))
                    {
                        string message = string.Format("Generated stylesheet for {1} is identical to reference stylesheet {0}.", referenceStylesheetFileInfo.Name, testDir.Name);
                        Console.WriteLine(message);
                    }
                    else
                    {
                        string message = string.Format("Generated stylesheet for {1} differs from reference stylesheet {0}.", referenceStylesheetFileInfo.Name, testDir.Name);
                        Console.WriteLine(message);
                        inconclusiveMessage.AppendLine(message);
                    }
                }
                else
                {
                    string message = string.Format("No reference stylesheet available. ");
                    Console.WriteLine(message);
                }
                Console.WriteLine();

                string tmpDir = Path.GetTempPath();

                foreach (FileInfo inputFile in inputFiles)
                {
                    Console.WriteLine("Testing revalidation of file {0}.", inputFile.Name);

                    string input  = File.ReadAllText(inputFile.FullName);
                    string output = XsltProcessing.TransformSAXON(inputFile.FullName, testGeneratedStylesheetFileName, true);

                    string genOutputFile = inputFile.FullName.Replace("in.xml", "out-generated.xml");
                    File.WriteAllText(genOutputFile, output);
                    Console.WriteLine("XSLT transformation succeeded, results written to {0}. ", genOutputFile);

                    string refOutputFile = inputFile.FullName.Replace("in.xml", "out.xml");
                    if (File.Exists(refOutputFile))
                    {
                        bool bIdentical = XmlDocumentHelper.DocumentCompare(refOutputFile, genOutputFile, XmlDiffOptions.IgnoreXmlDecl | XmlDiffOptions.IgnoreComments);
                        if (bIdentical)
                        {
                            string message = string.Format("Output for file {0} is identical to the reference output. ", inputFile.Name);
                            Console.WriteLine(message);
                        }
                        else
                        {
                            string message = string.Format("Result differs from reference output for file {0}", inputFile.Name);
                            Console.WriteLine(message);
                            failMessage.AppendLine(message);
                            failCounts++;
                        }
                    }
                    else
                    {
                        string message = string.Format("Reference output not found for file {0}", inputFile.Name);
                        Console.WriteLine(message);
                        inconclusiveMessage.AppendLine(message);
                    }
                }

                if (inputFiles.Length == 0)
                {
                    string message = string.Format("No input files for test {0}", testDir.Name);
                    Console.WriteLine(message);
                    inconclusiveMessage.AppendLine(message);
                }

                if (failCounts > 0)
                {
                    string finalMessage = string.Format("Failed for {0}/{1} test inputs. \r\n", failCounts, inputFiles.Length);
                    Console.WriteLine(finalMessage);
                    failMessage.Insert(0, finalMessage);
                    Assert.Fail(failMessage.ToString());
                }

                if (inconclusiveMessage.Length > 0)
                {
                    Assert.Inconclusive(inconclusiveMessage.ToString());
                }

                if (failCounts == 0)
                {
                    string lastWorkingStylesheetFile = testDir.FullName + "/" + testDir.Name + "-last-working.xslt";
                    testGeneratedStylesheet.SaveInUtf8(lastWorkingStylesheetFile);
                }

                Console.WriteLine("Test succeeded. ");
            }
            catch (Exception exception)
            {
            }
        }
Пример #24
0
        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);
        }
Пример #25
0
        protected void SendRequest(string serviceName, string methodName, IEnumerable <Tuple <string, string> > xpath2Values)
        {
            var service = _serviceConfig.Services[serviceName];

            if (service == null)
            {
                throw new ConfigurationErrorsException($"Конфигурация для сервиса {serviceName} не задана");
            }

            var method = service.Methods[methodName];

            if (method == null)
            {
                throw new ConfigurationErrorsException($"Конфигурация для метода {methodName} не задана");
            }

            if (method.RequiredBody && !xpath2Values.Any())
            {
                throw new ConfigurationErrorsException($"Метод {methodName} имеет обязательные параметры для запроса (-с файл)");
            }

            Info("Создание запроса...");
            var soapFormatter = new GisSoapFormatter
            {
                Template = PathHelper.ToAppAbsolutePath(method.Template),
                //SchemaVersion = _serviceConfig.SchemaVersion, TODO  Удалить если всё норм
                AddOrgPPAGuid    = service.AddSenderId,
                ValuesDictionary = xpath2Values,
                // TODO обратить внимание на эту строчку, нужно ли из конфига брать? или из базы guid организации.
                OrgPPAGuid  = _serviceConfig.RIRCorgPPAGUID,
                Config      = _serviceConfig.SoapConfiguration,
                MessageGuid = ""
            };

            var soapString = soapFormatter.GetSoapRequest(soapFormatter.MessageGuid);

            System.IO.File.WriteAllText(@"soapString.txt", soapString);
            if (IsSignatureRequired && service.AddSignature)
            {
                Info("Добавление подписи в запрос...");
                var soapXml = XmlDocumentHelper.Create(soapString);
                soapString = SignNode(soapXml, Constants.SoapContentXpath);
                System.IO.File.WriteAllText(@"soapStringSign.txt", soapString);
            }



            IEnumerable <Tuple <string, string> > resultValues;

            try
            {
                Info($"Отправка запроса по адресу: {_serviceConfig.BaseUrl}{service.Path}/{method.Action}");

                Console.WriteLine($"Отправка запроса по адресу: {_serviceConfig.BaseUrl}{service.Path}/{method.Action}");

                var response = CallGisService($"{_serviceConfig.BaseUrl}{service.Path}", method.Action, soapString, _serviceConfig.Login, _serviceConfig.Password);

                Console.WriteLine(response);

                Info("Обработка ответа на запрос...");
                resultValues = ProcessSoapResponse(response);
                Console.WriteLine(resultValues);
            }
            catch (XadesBesValidationException ex)
            {
                Error($"Подпись ответа от ГИС ЖКХ не прошла проверку: {ex.Message}", ex);
                return;
            }
            catch (WebException ex)
            {
                Warning($"Сервер ответил с ошибкой: {ex.Message}");
                using (var streamWriter = new StreamReader(ex.Response.GetResponseStream()))
                {
                    var response = streamWriter.ReadToEnd();
                    resultValues = ProcessSoapResponse(response);
                }
            }

            Info($"Сохранение ответа ...");
            Console.WriteLine(resultValues);
            Success("Запрос успешно выполнен");
        }
Пример #26
0
        protected void SendRequest(string serviceName, string methodName, IEnumerable <Tuple <string, string> > xpath2Values, string outputFile)
        {
            var service = _serviceConfig.Services[serviceName];

            if (service == null)
            {
                throw new ConfigurationErrorsException(string.Format("Конфигурация для сервиса {0} не задана", serviceName));
            }

            var method = service.Methods[methodName];

            if (method == null)
            {
                throw new ConfigurationErrorsException(string.Format("Конфигурация для метода {0} не задана", methodName));
            }

            if (method.RequiredBody && !xpath2Values.Any())
            {
                throw new ConfigurationErrorsException(string.Format("Метод {0} имеет обязательные параметры для запроса (-с файл)", methodName));
            }

            Info("Создание запроса...");
            var soapFormatter = new GisSoapFormatter
            {
                Template         = PathHelper.ToAppAbsolutePath(method.Template),
                AddSenderId      = service.AddOrgPpaGuid,
                ValuesDictionary = xpath2Values,
                OrgPpaGuid       = _serviceConfig.OrgPpaGuid,
                Config           = _serviceConfig.SoapConfiguration
            };

            var soapString = soapFormatter.GetSoapRequest();

            if (IsSignatureRequired && service.AddSignature)
            {
                Info("Добавление подписи в запрос...");
                var soapXml = XmlDocumentHelper.Create(soapString);
                soapString = SignNode(soapXml, Constants.SoapContentXpath);
            }

            IEnumerable <Tuple <string, string> > resultValues;

            try
            {
                Info(string.Format("Отправка запроса по адресу: {0}{1}/{2}", _serviceConfig.BaseUrl, service.Path, method.Action));
                var response = CallGisService(_serviceConfig.BaseUrl + service.Path, method.Action, soapString, Option.BasicAuthorization);
                Info("Обработка ответа на запрос...");
                resultValues = ProcessSoapResponse(response);
            }
            catch (XadesBesValidationException ex)
            {
                Error(string.Format("Подпись ответа от ГИС ЖКХ не прошла проверку: {0}", ex.Message), ex);
                return;
            }
            catch (WebException ex)
            {
                Warning(string.Format("Сервер ответил с ошибкой: {0}", ex.Message));
                using (var streamWriter = new StreamReader(ex.Response.GetResponseStream()))
                {
                    var response = streamWriter.ReadToEnd();
                    resultValues = ProcessSoapResponse(response);
                }
            }

            Info(string.Format("Сохранение ответа в файл {0}...", outputFile));
            Helpers.CsvHelper.WriteCsv(outputFile, resultValues);
            Success("Запрос успешно выполнен");
        }
Пример #27
0
        private void diagramXmlParseBody_(XmlNode diagramElementNode, string xmlFilePath, TreeNode treeNode, int objectIndex)
        {
            string diagramElementName = diagramElementNode.Name;

            AlternateContent           altContent     = treeNode.Presentation.AlternateContentFactory.CreateAlternateContent();
            AlternateContentAddCommand cmd_AltContent =
                treeNode.Presentation.CommandFactory.CreateAlternateContentAddCommand(treeNode, altContent);

            treeNode.Presentation.UndoRedoManager.Execute(cmd_AltContent);



            Metadata diagramElementName_Metadata = treeNode.Presentation.MetadataFactory.CreateMetadata();

            diagramElementName_Metadata.NameContentAttribute              = new MetadataAttribute();
            diagramElementName_Metadata.NameContentAttribute.Name         = DiagramContentModelHelper.DiagramElementName;
            diagramElementName_Metadata.NameContentAttribute.NamespaceUri = null;
            diagramElementName_Metadata.NameContentAttribute.Value        = diagramElementName;
            AlternateContentMetadataAddCommand cmd_AltContent_diagramElementName_Metadata =
                treeNode.Presentation.CommandFactory.CreateAlternateContentMetadataAddCommand(
                    treeNode,
                    null,
                    altContent,
                    diagramElementName_Metadata,
                    null
                    );

            treeNode.Presentation.UndoRedoManager.Execute(cmd_AltContent_diagramElementName_Metadata);


            if (diagramElementNode.Attributes != null)
            {
                for (int i = 0; i < diagramElementNode.Attributes.Count; i++)
                {
                    XmlAttribute attribute = diagramElementNode.Attributes[i];


                    if (attribute.Name.StartsWith(XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":"))
                    {
                        //
                    }
                    else if (attribute.Name == XmlReaderWriterHelper.NS_PREFIX_XMLNS)
                    {
                        //
                    }
                    else if (attribute.Name == DiagramContentModelHelper.TOBI_Audio)
                    {
                        string fullPath = null;
                        if (FileDataProvider.isHTTPFile(attribute.Value))
                        {
                            fullPath = FileDataProvider.EnsureLocalFilePathDownloadTempDirectory(attribute.Value);
                        }
                        else
                        {
                            fullPath = Path.Combine(Path.GetDirectoryName(xmlFilePath), attribute.Value);
                        }
                        if (fullPath != null && File.Exists(fullPath))
                        {
                            string extension = Path.GetExtension(fullPath);

                            bool isWav = extension.Equals(DataProviderFactory.AUDIO_WAV_EXTENSION, StringComparison.OrdinalIgnoreCase);

                            AudioLibPCMFormat wavFormat = null;
                            if (isWav)
                            {
                                Stream fileStream = File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                                try
                                {
                                    uint dataLength;
                                    wavFormat = AudioLibPCMFormat.RiffHeaderParse(fileStream, out dataLength);
                                }
                                finally
                                {
                                    fileStream.Close();
                                }
                            }
                            string originalFilePath = null;

                            DebugFix.Assert(treeNode.Presentation.MediaDataManager.EnforceSinglePCMFormat);

                            bool wavNeedsConversion = false;
                            if (wavFormat != null)
                            {
                                wavNeedsConversion = !wavFormat.IsCompatibleWith(treeNode.Presentation.MediaDataManager.DefaultPCMFormat.Data);
                            }
                            if (!isWav || wavNeedsConversion)
                            {
                                originalFilePath = fullPath;

                                var audioFormatConvertorSession =
                                    new AudioFormatConvertorSession(
                                        //AudioFormatConvertorSession.TEMP_AUDIO_DIRECTORY,
                                        treeNode.Presentation.DataProviderManager.DataFileDirectoryFullPath,
                                        treeNode.Presentation.MediaDataManager.DefaultPCMFormat,
                                        false,
                                        m_UrakawaSession.IsAcmCodecsDisabled);

                                //filePath = m_AudioFormatConvertorSession.ConvertAudioFileFormat(filePath);

                                bool cancelled = false;

                                var converter = new AudioClipConverter(audioFormatConvertorSession, fullPath);

                                bool error = ShellView.RunModalCancellableProgressTask(true,
                                                                                       "Converting audio...",
                                                                                       converter,
                                                                                       () =>
                                {
                                    m_Logger.Log(@"Audio conversion CANCELLED", Category.Debug, Priority.Medium);
                                    cancelled = true;
                                },
                                                                                       () =>
                                {
                                    m_Logger.Log(@"Audio conversion DONE", Category.Debug, Priority.Medium);
                                    cancelled = false;
                                });

                                if (cancelled)
                                {
                                    //DebugFix.Assert(!result);
                                    break;
                                }

                                fullPath = converter.ConvertedFilePath;
                                if (string.IsNullOrEmpty(fullPath))
                                {
                                    break;
                                }

                                m_Logger.Log(string.Format("Converted audio {0} to {1}", originalFilePath, fullPath),
                                             Category.Debug, Priority.Medium);

                                //Stream fileStream = File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                                //try
                                //{
                                //    uint dataLength;
                                //    wavFormat = AudioLibPCMFormat.RiffHeaderParse(fileStream, out dataLength);
                                //}
                                //finally
                                //{
                                //    fileStream.Close();
                                //}
                            }


                            ManagedAudioMedia manAudioMedia  = treeNode.Presentation.MediaFactory.CreateManagedAudioMedia();
                            AudioMediaData    audioMediaData = treeNode.Presentation.MediaDataFactory.CreateAudioMediaData(DataProviderFactory.AUDIO_WAV_EXTENSION);
                            manAudioMedia.AudioMediaData = audioMediaData;

                            FileDataProvider dataProv = (FileDataProvider)treeNode.Presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE);
                            dataProv.InitByCopyingExistingFile(fullPath);
                            audioMediaData.AppendPcmData(dataProv);

                            //                            Stream wavStream = null;
                            //                            try
                            //                            {
                            //                                wavStream = File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);

                            //                                uint dataLength;
                            //                                AudioLibPCMFormat pcmInfo = AudioLibPCMFormat.RiffHeaderParse(wavStream, out dataLength);

                            //                                if (!treeNode.Presentation.MediaDataManager.DefaultPCMFormat.Data.IsCompatibleWith(pcmInfo))
                            //                                {
                            //#if DEBUG
                            //                                    Debugger.Break();
                            //#endif //DEBUG
                            //                                    wavStream.Close();
                            //                                    wavStream = null;

                            //                                    var audioFormatConvertorSession =
                            //                                        new AudioFormatConvertorSession(
                            //                                        //AudioFormatConvertorSession.TEMP_AUDIO_DIRECTORY,
                            //                                        treeNode.Presentation.DataProviderManager.DataFileDirectoryFullPath,
                            //                                    treeNode.Presentation.MediaDataManager.DefaultPCMFormat, m_UrakawaSession.IsAcmCodecsDisabled);

                            //                                    string newfullWavPath = audioFormatConvertorSession.ConvertAudioFileFormat(fullPath);

                            //                                    FileDataProvider dataProv = (FileDataProvider)treeNode.Presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE);
                            //                                    dataProv.InitByMovingExistingFile(newfullWavPath);
                            //                                    audioMediaData.AppendPcmData(dataProv);
                            //                                }
                            //                                else // use original wav file by copying it to data directory
                            //                                {
                            //                                    FileDataProvider dataProv = (FileDataProvider)treeNode.Presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE);
                            //                                    dataProv.InitByCopyingExistingFile(fullPath);
                            //                                    audioMediaData.AppendPcmData(dataProv);
                            //                                }
                            //                            }
                            //                            finally
                            //                            {
                            //                                if (wavStream != null) wavStream.Close();
                            //                            }



                            AlternateContentSetManagedMediaCommand cmd_AltContent_diagramElement_Audio =
                                treeNode.Presentation.CommandFactory.CreateAlternateContentSetManagedMediaCommand(treeNode, altContent, manAudioMedia);
                            treeNode.Presentation.UndoRedoManager.Execute(cmd_AltContent_diagramElement_Audio);

                            //SetDescriptionAudio(altContent, audio, treeNode);
                        }
                    }
                    else
                    {
                        Metadata diagramElementAttribute_Metadata = treeNode.Presentation.MetadataFactory.CreateMetadata();
                        diagramElementAttribute_Metadata.NameContentAttribute              = new MetadataAttribute();
                        diagramElementAttribute_Metadata.NameContentAttribute.Name         = attribute.Name;
                        diagramElementAttribute_Metadata.NameContentAttribute.NamespaceUri = attribute.NamespaceURI;
                        diagramElementAttribute_Metadata.NameContentAttribute.Value        = attribute.Value;
                        AlternateContentMetadataAddCommand cmd_AltContent_diagramElementAttribute_Metadata =
                            treeNode.Presentation.CommandFactory.CreateAlternateContentMetadataAddCommand(
                                treeNode,
                                null,
                                altContent,
                                diagramElementAttribute_Metadata,
                                null
                                );
                        treeNode.Presentation.UndoRedoManager.Execute(
                            cmd_AltContent_diagramElementAttribute_Metadata);
                    }
                }
            }

            int nObjects = -1;

            XmlNode textNode = diagramElementNode;

            if (diagramElementName == DiagramContentModelHelper.D_SimplifiedImage ||
                diagramElementName == DiagramContentModelHelper.D_Tactile)
            {
                string  localTourName = DiagramContentModelHelper.StripNSPrefix(DiagramContentModelHelper.D_Tour);
                XmlNode tour          =
                    XmlDocumentHelper.GetFirstChildElementOrSelfWithName(diagramElementNode, false,
                                                                         localTourName,
                                                                         DiagramContentModelHelper.NS_URL_DIAGRAM);
                textNode = tour;

                IEnumerable <XmlNode> objects = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(diagramElementNode, false,
                                                                                                    DiagramContentModelHelper.
                                                                                                    Object,
                                                                                                    DiagramContentModelHelper.
                                                                                                    NS_URL_ZAI, false);
                nObjects = 0;
                foreach (XmlNode obj in objects)
                {
                    nObjects++;
                }

                int i = -1;
                foreach (XmlNode obj in objects)
                {
                    i++;
                    if (i != objectIndex)
                    {
                        continue;
                    }

                    if (obj.Attributes == null || obj.Attributes.Count <= 0)
                    {
                        break;
                    }

                    for (int j = 0; j < obj.Attributes.Count; j++)
                    {
                        XmlAttribute attribute = obj.Attributes[j];


                        if (attribute.Name.StartsWith(XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":"))
                        {
                            //
                        }
                        else if (attribute.Name == XmlReaderWriterHelper.NS_PREFIX_XMLNS)
                        {
                            //
                        }
                        else if (attribute.Name == DiagramContentModelHelper.Src)
                        {
                            //
                        }
                        else if (attribute.Name == DiagramContentModelHelper.SrcType)
                        {
                            //
                        }
                        else
                        {
                            Metadata diagramElementAttribute_Metadata = treeNode.Presentation.MetadataFactory.CreateMetadata();
                            diagramElementAttribute_Metadata.NameContentAttribute              = new MetadataAttribute();
                            diagramElementAttribute_Metadata.NameContentAttribute.Name         = attribute.Name;
                            diagramElementAttribute_Metadata.NameContentAttribute.NamespaceUri = attribute.NamespaceURI;
                            diagramElementAttribute_Metadata.NameContentAttribute.Value        = attribute.Value;
                            AlternateContentMetadataAddCommand cmd_AltContent_diagramElementAttribute_Metadata =
                                treeNode.Presentation.CommandFactory.CreateAlternateContentMetadataAddCommand(
                                    treeNode,
                                    null,
                                    altContent,
                                    diagramElementAttribute_Metadata,
                                    null
                                    );
                            treeNode.Presentation.UndoRedoManager.Execute(
                                cmd_AltContent_diagramElementAttribute_Metadata);
                        }
                    }

                    XmlAttribute srcAttr = (XmlAttribute)obj.Attributes.GetNamedItem(DiagramContentModelHelper.Src);
                    if (srcAttr != null)
                    {
                        XmlAttribute srcType =
                            (XmlAttribute)obj.Attributes.GetNamedItem(DiagramContentModelHelper.SrcType);

                        ManagedImageMedia img = treeNode.Presentation.MediaFactory.CreateManagedImageMedia();

                        string imgFullPath = null;
                        if (FileDataProvider.isHTTPFile(srcAttr.Value))
                        {
                            imgFullPath = FileDataProvider.EnsureLocalFilePathDownloadTempDirectory(srcAttr.Value);
                        }
                        else
                        {
                            imgFullPath = Path.Combine(Path.GetDirectoryName(xmlFilePath), srcAttr.Value);
                        }
                        if (imgFullPath != null && File.Exists(imgFullPath))
                        {
                            string extension = Path.GetExtension(imgFullPath);

                            ImageMediaData imgData = treeNode.Presentation.MediaDataFactory.CreateImageMediaData(extension);
                            if (imgData != null)
                            {
                                imgData.InitializeImage(imgFullPath, Path.GetFileName(imgFullPath));
                                img.ImageMediaData = imgData;

                                AlternateContentSetManagedMediaCommand cmd_AltContent_Image =
                                    treeNode.Presentation.CommandFactory.CreateAlternateContentSetManagedMediaCommand(
                                        treeNode, altContent, img);
                                treeNode.Presentation.UndoRedoManager.Execute(cmd_AltContent_Image);
                            }
                        }
                    }
                }
            }

            if (textNode != null)
            {
                string strText = textNode.InnerXml;

                if (!string.IsNullOrEmpty(strText))
                {
                    strText = strText.Trim();
                    strText = Regex.Replace(strText, @"\s+", " ");
                    strText = strText.Replace("\r\n", "\n");
                }

                if (!string.IsNullOrEmpty(strText))
                {
                    TextMedia txtMedia = treeNode.Presentation.MediaFactory.CreateTextMedia();
                    txtMedia.Text = strText;
                    AlternateContentSetManagedMediaCommand cmd_AltContent_Text =
                        treeNode.Presentation.CommandFactory.CreateAlternateContentSetManagedMediaCommand(treeNode,
                                                                                                          altContent,
                                                                                                          txtMedia);
                    treeNode.Presentation.UndoRedoManager.Execute(cmd_AltContent_Text);
                }
            }

            if (nObjects > 0 && ++objectIndex <= nObjects - 1)
            {
                diagramXmlParseBody_(diagramElementNode, xmlFilePath, treeNode, objectIndex);
            }
        }
Пример #28
0
        private void ParseSmilDocument(SectionNode section, XmlNode xNode, string smilFileName, string strId)
        {
            if (xNode.ChildNodes.Count == 0)
            {
                return;
            }
            foreach (XmlNode n in xNode.ChildNodes)
            {
                if (n.LocalName == "par")
                {
                    // check for skippable items
                    string  skippableName      = null;
                    XmlNode systemRequiredNode = n.Attributes.GetNamedItem("system-required");
                    if (systemRequiredNode != null)
                    {
                        string strSkippableName = systemRequiredNode.Value;
                        if (!string.IsNullOrEmpty(strSkippableName))
                        {
                            strSkippableName = strSkippableName.Replace("-on", "");
                            //Console.WriteLine(strSkippableName) ;
                            if (EmptyNode.SkippableNamesList.Contains(strSkippableName))
                            {
                                skippableName = strSkippableName;
                            }
                        }
                    }
                    EmptyNode page             = null;
                    EmptyNode originalPageNode = null;
                    XmlNode   txtNode          = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(n, true, "text", n.NamespaceURI);
                    if (txtNode != null)
                    {
                        string src   = txtNode.Attributes.GetNamedItem("src").Value;
                        string nccID = src.Split('#')[1];

                        if (m_NccReferenceToPageMap.ContainsKey(nccID))
                        {
                            originalPageNode = m_NccReferenceToPageMap[nccID];
                            // if text ID has no audio or seq sibling it means that its page with no audio
                            if (txtNode.ParentNode.ChildNodes.Count == 1)
                            {
                                Console.WriteLine("Page text node in smil has no sibling: no audio, no seq");
                                EmptyNode newNode = m_Presentation.TreeNodeFactory.Create <EmptyNode>();
                                section.AppendChild(newNode);
                                if (page == null)
                                {
                                    page = newNode;
                                }
                                UpdatePageNumber(originalPageNode, page);
                            }
                        }
                    }
                    XmlNode seqNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(n, true, "seq", n.NamespaceURI);
                    if (seqNode != null)
                    {
                        foreach (XmlNode audioNode in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(seqNode, true, "audio", seqNode.NamespaceURI, false))
                        {
                            EmptyNode newNode = CreatePhraseNodeFromAudioElement(section, audioNode);
                            if (page == null)
                            {
                                page = newNode;
                            }
                            if (!string.IsNullOrEmpty(skippableName))
                            {
                                newNode.SetRole(EmptyNode.Role.Custom, skippableName);
                            }
                        }
                        UpdatePageNumber(originalPageNode, page);
                    }
                    else
                    {     //1
                        foreach (XmlNode audioNode in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(n, true, "audio", n.NamespaceURI, false))
                        { //2
                            EmptyNode newNode = CreatePhraseNodeFromAudioElement(section, audioNode);
                            if (page == null)
                            {
                                page = newNode;
                            }
                        } //-2
                        UpdatePageNumber(originalPageNode, page);
                    }     //-1
                    if (page == null)
                    {
                        ParseSmilDocument(section, n, smilFileName, strId);
                    }
                }
                else if (n.LocalName == "audio")
                {
                    CreatePhraseNodeFromAudioElement(section, n);
                    ParseSmilDocument(section, n, smilFileName, strId);
                }
            }
        }
Пример #29
0
        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 generateImageDescriptionInDTBook(TreeNode n, XmlNode currentXmlNode, string exportImageName, XmlDocument DTBookDocument)
        {
            AlternateContentProperty altProp = n.GetAlternateContentProperty();

            if (currentXmlNode.LocalName == null ||
                !currentXmlNode.LocalName.Equals("img", StringComparison.OrdinalIgnoreCase) ||
                altProp == null || altProp.IsEmpty)
            {
                return;
            }

            m_Map_AltProperty_TO_Description.Add(altProp, new Description());

            PCMFormatInfo     audioFormat = m_Presentation.MediaDataManager.DefaultPCMFormat;
            AudioLibPCMFormat pcmFormat   = audioFormat.Data;

            pcmFormat.SampleRate       = (ushort)m_sampleRate;
            pcmFormat.NumberOfChannels = (ushort)(m_audioStereo ? 2 : 1);

            Dictionary <string, List <string> > map_DiagramElementName_TO_TextualDescriptions = new Dictionary <string, List <string> >();

            string imageDescriptionDirectoryPath = GetAndCreateImageDescriptionDirectoryPath(true, exportImageName, m_OutputDirectory);
            string descriptionFile = CreateImageDescription(m_SkipACM, pcmFormat, m_encodeAudioFiles, m_BitRate_Encoding,
                                                            imageDescriptionDirectoryPath, exportImageName,
                                                            altProp,
                                                            map_DiagramElementName_TO_TextualDescriptions,
                                                            m_Map_AltProperty_TO_Description,
                                                            m_Map_AltContentAudio_TO_RelativeExportedFilePath);

            if (m_includeImageDescriptions && !String.IsNullOrEmpty(descriptionFile))
            {
                //short term way for executing image description code: will be updated in later phase of implementation
                XmlNode prodNoteNode = DTBookDocument.CreateElement("prodnote", currentXmlNode.NamespaceURI);
                XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteNode, "render", "optional");
                string id_Prodnote = GetNextID(ID_DTBPrefix);
                XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteNode, "id", id_Prodnote);
                XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteNode, "imgref", currentXmlNode.Attributes.GetNamedItem("id").Value);
                XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteNode, "class", DiagramContentModelHelper.EPUB_DescribedAt);

                currentXmlNode.ParentNode.AppendChild(prodNoteNode);
                if (!m_Image_ProdNoteMap.ContainsKey(n))
                {
                    m_Image_ProdNoteMap.Add(n, new List <XmlNode>());
                }
                m_Image_ProdNoteMap[n].Add(prodNoteNode);
                XmlNode anchorNode = DTBookDocument.CreateElement("a", currentXmlNode.NamespaceURI);

                XmlNode pAnchor = DTBookDocument.CreateElement(
                    DiagramContentModelHelper.P, currentXmlNode.NamespaceURI
                    );
                pAnchor.AppendChild(anchorNode);
                prodNoteNode.AppendChild(pAnchor);
                string descriptionFileUrl = descriptionFile.Replace('\\', '/');

                XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, anchorNode, "href", FileDataProvider.UriEncode(descriptionFileUrl));
                XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, anchorNode, "external", "true");
                anchorNode.AppendChild(DTBookDocument.CreateTextNode("Image description (DIAGRAM XML)"));

                if (map_DiagramElementName_TO_TextualDescriptions.Count > 0)
                {
                    foreach (string diagramDescriptionElementName in map_DiagramElementName_TO_TextualDescriptions.Keys)
                    {
                        //System.Windows.Forms.MessageBox.Show(s + " : " + imageDescriptions[s]);

                        XmlNode prodNoteDesc = DTBookDocument.CreateElement("prodnote", currentXmlNode.NamespaceURI);
                        XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteDesc, "render", "optional");
                        string id_ProdnoteDesc = GetNextID(ID_DTBPrefix);
                        XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteDesc, "id", id_ProdnoteDesc);
                        XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteDesc, "imgref", currentXmlNode.Attributes.GetNamedItem("id").Value);
                        XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, prodNoteDesc, "class", diagramDescriptionElementName);
                        currentXmlNode.ParentNode.AppendChild(prodNoteDesc);
                        m_Image_ProdNoteMap[n].Add(prodNoteDesc);

                        foreach (string txt in map_DiagramElementName_TO_TextualDescriptions[diagramDescriptionElementName])
                        {
                            string descText = txt;

                            bool xmlParseFail = descText.StartsWith(DIAGRAM_XML_PARSE_FAIL);

                            bool descriptionTextContainsMarkup = !xmlParseFail && descText.IndexOf('<') >= 0; // descText.Contains("<");
                            if (descriptionTextContainsMarkup)
                            {
                                try
                                {
                                    prodNoteDesc.InnerXml = descText;
                                }
                                catch (Exception ex)
                                {
#if DEBUG
                                    Debugger.Break();
#endif
                                    Console.WriteLine(@"Cannot set DIAGRAM XML: " + descText);

                                    XmlNode wrapperNode = DTBookDocument.CreateElement(DiagramContentModelHelper.CODE,
                                                                                       currentXmlNode.NamespaceURI);
                                    prodNoteDesc.AppendChild(wrapperNode);
                                    wrapperNode.AppendChild(DTBookDocument.CreateTextNode(descText));
                                }
                            }
                            else if (xmlParseFail)
                            {
                                //descText = descText.Replace(DIAGRAM_XML_PARSE_FAIL, "");
                                descText = descText.Substring(DIAGRAM_XML_PARSE_FAIL.Length);

                                XmlNode wrapperNode = DTBookDocument.CreateElement(DiagramContentModelHelper.CODE, currentXmlNode.NamespaceURI);
                                prodNoteDesc.AppendChild(wrapperNode);
                                wrapperNode.AppendChild(DTBookDocument.CreateTextNode(descText));
                            }
                            else
                            {
                                string normalizedText = descText.Replace("\r\n", "\n");

                                string[] parasText = normalizedText.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                                //string[] parasText = System.Text.RegularExpressions.Regex.Split(normalizedText, "\n");

                                for (int i = 0; i < parasText.Length; i++)
                                {
                                    string paraText = parasText[i].Trim();
                                    if (string.IsNullOrEmpty(paraText))
                                    {
                                        continue;
                                    }

                                    XmlNode paragraph = DTBookDocument.CreateElement(
                                        //DiagramContentModelHelper.NS_PREFIX_ZAI,
                                        DiagramContentModelHelper.P
                                        , currentXmlNode.NamespaceURI
                                        //, DiagramContentModelHelper.NS_URL_ZAI
                                        );

                                    paragraph.InnerText = paraText;

                                    prodNoteDesc.AppendChild(paragraph);
                                }
                            }
                        }
                    }
                }

                /*
                 * if ( EXPORT_IMAGE_DESCRIPTION_IN_DTBOOK )
                 * {//1
                 * // to do copy the diagram nodes that descend directly from body
                 *  if (m_AltProperrty_DiagramDocument.ContainsKey(n.GetAlternateContentProperty()))
                 *  {//2
                 *
                 *      XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, DTBookDocument.GetElementsByTagName("dtbook")[0],
                 * XmlReaderWriterHelper.NS_PREFIX_XMLNS+":" + DiagramContentModelHelper.NS_PREFIX_DIAGRAM,
                 * DiagramContentModelHelper.NS_URL_DIAGRAM);
                 *      XmlDocument descriptionDocument = m_AltProperrty_DiagramDocument[n.GetAlternateContentProperty()];
                 *      XmlNodeList diagramNodesList = descriptionDocument.GetElementsByTagName("d:body")[0].ChildNodes;
                 *      foreach (XmlNode xn in diagramNodesList)
                 *      {//3
                 *          XmlNode newNode = DTBookDocument.ImportNode(xn, true);
                 *          prodNoteNode.AppendChild(newNode);
                 *          for (int i = 0; i < newNode.Attributes.Count; i++)
                 *          {//4
                 *              XmlAttribute attr = newNode.Attributes[i];
                 *              if (attr.Name == DiagramContentModelHelper.NS_PREFIX_XML + ":id")
                 *              {//-4
                 *                  XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, newNode, "id", attr.Value);
                 *                  newNode.Attributes.Remove(attr);
                 *              }//-3
                 *          }//-2
                 *
                 *      }//-1
                 *
                 *  }
                 *
                 * //XmlNode newNode = DTBookDocument.ImportNode(M_DescriptionDocument.GetElementsByTagName("d:description")[0], true);
                 *  //prodNoteNode.AppendChild(newNode);
                 * }
                 */
            }
            //}
            //catch (System.Exception ex)
            //{
            //System.Windows.Forms.MessageBox.Show(ex.ToString());
            //}
            //}

            //}
        }