Subversion Repositories vs2008

Rev

Rev 10 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

using System;
using System.Collections.Generic;
using System.IO;
using System.Management;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using com.jamiehill;

namespace OneNoteHTMLImporter {
    class OneNoteHTMLImporter {
        private JPHOneNoteUtilities onp = null;
        private OneNoteXMLObject unfiledNotes;
        private XY initialPosition = new XY(40, 80);
        private XY defaultIconSize = new XY(65, 75);
        private static String browserPostfix = "_files";
        private static String HTMLFileDir = "HTML File Storage";
        public static String myName = "OneNote HTML Importer";

        public OneNoteHTMLImporter() {
            onp = new JPHOneNoteUtilities();
            unfiledNotes = onp.GetUnfiledNotesSection();
        }

        private string GetOpeningXml(string id, string pageName) {
            string xml = "<?xml version=\"1.0\"?>" +
               "   <one:Page xmlns:one=\"" + onp.GetOneNoteNamespace() + "\" ID=\"" + id + "\">" +
               "      <one:PageSettings RTL=\"false\" color=\"automatic\">" +
               "         <one:PageSize>" +
               "            <one:Automatic/>" +
               "         </one:PageSize>" +
               "         <one:RuleLines visible=\"false\"/>" +
               "      </one:PageSettings>" +
               "      <one:Title style=\"font-family:Calibri;font-size:17.0pt\" lang=\"en-US\">" +
               "         <one:OE alignment=\"left\">" +
               "            <one:T>" +
               "               <![CDATA[" + pageName + "]]>" +
               "            </one:T>" +
               "         </one:OE>" +
               "      </one:Title>";
            return (xml);
        }

        private string GetClosingXml() {
            string xml = "   </one:Page>";
            return (xml);
        }

        private string GetHtmlXml(FileInfo file, XY position) {
            string xml = "<one:Outline>" +
                         "  <one:Position x=\""+position.x+"\" y=\""+position.y+"\"/>"+
                         "  <one:OEChildren>"+
                         "    <one:OE>"+
                         "      <one:InsertedFile pathSource=\"" + file.FullName + "\"/>"+
                         "    </one:OE>"+
                         "  </one:OEChildren>"+
                         "</one:Outline>\n"+
                         "     <one:Outline>"+
                         "       <one:Position x=\"" + position.x + "\" y=\"" + (position.y + defaultIconSize.y + 15) + "\"/>" +
                         "       <one:OEChildren>" +
                         "         <one:HTMLBlock>" +
                         "           <one:File path=\"" + file.FullName + "\"/>" +
                         "         </one:HTMLBlock>" +
                         "       </one:OEChildren>" +
                         "     </one:Outline>";

            return (xml);
        }

        private string MakeFirstLetterUpper(string str) {
            int len = str.Length;

            if (len <= 0) return (str);
            if (len == 1) return (str.ToUpper());

            char[] letters = str.ToCharArray();
            letters[0] = Char.ToUpper(letters[0]);

            return (new string(letters));
        }

        public string GetHTMLTitle(FileInfo fi) {
            StreamReader stream = null;
            string title = "Untitled page";
            try {
                stream = fi.OpenText();
            } catch {
                return (title);
            }

            while (stream.Peek() > 0) {
                string text = stream.ReadLine();
                if (Regex.Match(text, "<title>", RegexOptions.IgnoreCase).Success) {
                    Match m = Regex.Match(text, @"<title>\s*(?<title>.+?)\s*</title>", RegexOptions.IgnoreCase);
                    if (!m.Success) {
                        string build = text;
                        while (stream.Peek() > 0) {
                            text = stream.ReadLine();
                            if (Regex.Match(text, "</title>",RegexOptions.IgnoreCase).Success) {
                                build += text;
                                break;
                            } else {
                                build += text;
                            }
                        }
                        m = Regex.Match(build, @"<title>\s*(?<title>.+?)\s*</title>",RegexOptions.IgnoreCase);
                    }
                    if (m.Success) {
                        title = MakeFirstLetterUpper(m.Groups["title"].ToString());
                    } else {
                        title = "Untitled page";
                    }
                    break;
                }
            }
            stream.Close();
            return (title);
        }

        public void MakeStorageDirectory(ref FileInfo fi) {
            string ondnp = onp.GetDefaultNotebookPath();
            string guid = System.Guid.NewGuid().ToString();
            DirectoryInfo notebookd = new DirectoryInfo(ondnp);
            DirectoryInfo htmld = new DirectoryInfo(ondnp+"\\"+HTMLFileDir+"\\"+guid);
            try {
                if (!htmld.Exists) htmld.Create();
            } catch (Exception e) {
                throw new SystemException("Failed to create storage directory: "+htmld.FullName+" -- "+e);
            }

            try {
                File.Move(fi.FullName, htmld.FullName + "\\" + fi.Name);
            } catch (Exception e) {
                DialogResult dr = MessageBox.Show("File move failed: " + fi.FullName + " -> " + htmld.FullName + "\\" + fi.Name + " (" + e.ToString() + ")", "Error", MessageBoxButtons.OK);
            }

            DirectoryInfo di = GetAdditionalFilesDir(fi);
            try {
                DirectoryInfo ndi = new DirectoryInfo(htmld.FullName + "\\" + di.Name);
                ndi.Create();
                DirectoryCopy(di.FullName, htmld.FullName + "\\" + di.Name, true);
                Directory.Delete(di.FullName, true);
            } catch (Exception e) {
                DialogResult dr = MessageBox.Show("Directory move failed: " + di.FullName + " -> " + htmld.FullName + "\\" + di.Name + " (" + e.ToString() + ")", "Error", MessageBoxButtons.OK);
            }

            fi = new FileInfo(htmld.FullName + "\\" + fi.Name);
        }

        static uint DirectoryCopy(string SourcePath, string DestinationPath, bool Recursive) {
            if (Directory.Exists(DestinationPath)) Directory.Delete(DestinationPath, true);
            string objPath = @"\\.\root\cimv2:Win32_Directory.Name=" + "\"" + SourcePath.Replace("\\", "\\\\") + "\"";
            using (ManagementObject dir = new ManagementObject(objPath)) {
                ManagementBaseObject inputArgs = dir.GetMethodParameters("CopyEx");
                inputArgs["FileName"] = DestinationPath.Replace("\\", "\\\\");
                inputArgs["Recursive"] = Recursive;
                ManagementBaseObject outParams = dir.InvokeMethod("CopyEx", inputArgs, null);
                return ((uint)(outParams.Properties["ReturnValue"].Value));
            }
        }

        public DirectoryInfo GetAdditionalFilesDir(FileInfo fi) {
            String name = fi.Name;
            name = Regex.Replace(name, fi.Extension, "");
            String extdir = name + browserPostfix;
            return (new DirectoryInfo(extdir));
        }

        public void FixUpHTML(FileInfo fi) {
            StreamReader stream = null;
            try {
                stream = fi.OpenText();
            } catch (Exception e) {
                throw e;
            }
                
            String extdir = GetAdditionalFilesDir(fi).Name;
            String sp_extdir = Regex.Replace(extdir, " ","%20");

            Stream os = File.OpenWrite(fi.FullName + ".new");
            string text = stream.ReadToEnd();
            stream.Close();

           
            string dir = fi.DirectoryName;
            dir = Regex.Replace(dir, Regex.Escape(@"\"), "/");
            //text = Regex.Replace(text, "\"(" + extdir + "/)", "\"file:///" + dir + "/$1", RegexOptions.Singleline);
            text = Regex.Replace(text, "(" + extdir + "|" + sp_extdir + "/)", "file:///" + dir + "/$1", RegexOptions.Singleline);
            
            os.Write((new ASCIIEncoding()).GetBytes(text), 0, text.Length);
            os.Close();

            fi.Delete();
            (new FileInfo(fi.FullName + ".new")).MoveTo(fi.FullName);
        }

        public FileInfo PickFile(string[] args) {
            OpenFileDialog fileOpen = new OpenFileDialog();
            string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            bool flag = false;

            //fileOpen.ShowReadOnly = true;
            
            if (args.Length > 0) {
                if (File.Exists(args[0])) {
                    fileOpen.FileName = args[0];
                    flag = true;
                } else if (Directory.Exists(args[0])) path = args[0];
            }
            if (!flag) {
                fileOpen.Title = myName + ": Open";
                fileOpen.InitialDirectory = path;
                fileOpen.Filter = "HTM Files (*.htm, *.html, *.xhtml)|*.htm;*.html;*.xhtml|All files (*.*)|*.*";
                fileOpen.FilterIndex = 0;
                fileOpen.RestoreDirectory = false;
                if (fileOpen.ShowDialog() != DialogResult.OK) return (null);
            }

            FileInfo fi = new FileInfo(fileOpen.FileName);
            if (!fi.Exists) {
                DialogResult dr = MessageBox.Show("File not found: " + fileOpen.FileName, "Error", MessageBoxButtons.OK);
                return (null);
            } else return (fi);
        }

        [STAThread]
        static int Main(string[] args) {
            OneNoteHTMLImporter onchi = new OneNoteHTMLImporter();
            OneNoteXMLObject newPage = new OneNoteXMLObject(null, null, null, null, null, null, null, false);

            FileInfo fi = onchi.PickFile(args);
            if (fi == null) return (1);

            try {
                onchi.MakeStorageDirectory(ref fi);
                onchi.FixUpHTML(fi);
                newPage = onchi.onp.CreatePage(ref onchi.unfiledNotes);
            } catch (Exception e) {
                DialogResult dr = MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK);
            }

            string title = onchi.GetHTMLTitle(fi);
            string xml = onchi.GetOpeningXml(newPage.id, title);
            xml += onchi.GetHtmlXml(fi, onchi.initialPosition);
            xml += onchi.GetClosingXml();

            try {
                onchi.onp.UpdatePage(xml);
            } catch (Exception e) {
                DialogResult dr = MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK);
                onchi.onp.DeletePage(ref newPage);
            }
            
            return (0);
        }
    }
}