Subversion Repositories vs2008

Rev

Rev 10 | Blame | Compare with Previous | Last modification | View Log | RSS feed

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

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 BuildXml(string id, FileInfo file, XY position) {
      try {
        string title = this.GetHTMLTitle(file);

        XNamespace ns = onp.GetOneNoteNamespace();
        XElement x = new XElement(
          ns + "Page",
          new XAttribute(XNamespace.Xmlns + "one", ns.NamespaceName),
          new XAttribute("ID", id),
          new XElement(
            ns + "PageSettings",
            new XAttribute("RTL", "false"),
            new XAttribute("color", "automatic"),
            new XElement(
              ns + "PageSize",
              new XElement(ns + "Automatic")
            ),
            new XElement(
              ns + "RuleLines",
              new XAttribute("visible", "false")
            )
          ),
          new XElement(
            ns + "Title",
            new XAttribute("style", "font-famly:Calibri;font-size:17.0pt"),
            new XAttribute("lang", "en-US"),
            new XElement(
              ns + "OE",
              new XAttribute("alignment", "left"),
              new XElement(
                ns + "T",
                new XCData(title)
              )
            )
          ),
          new XElement(
            ns + "Outline",
            new XElement(
              ns + "Position",
              new XAttribute("x", position.x),
              new XAttribute("y", position.y)
            ),
            new XElement(
              ns + "OEChildren",
              new XElement(
                ns + "OE",
                new XElement(
                  ns + "InsertedFile",
                  new XAttribute("pathSource", file.FullName)
                )
              )
            )
          ),
          new XElement(
            ns + "Outline",
            new XElement(
              ns + "Position",
              new XAttribute("x", position.x),
              new XAttribute("y", (position.y + defaultIconSize.y + 15))
            ),
            new XElement(
              ns + "OEChildren",
              new XElement(
                ns + "HTMLBlock",
                new XElement(
                  ns + "File",
                  new XAttribute("path", file.FullName)
                )
              )
            )
          )
        );

        string xml = (new XDeclaration("1.0", null, null)).ToString() + "\n";
        xml += x.ToString();

        return (xml);
      } catch (Exception e) {
        throw new SystemException("Xml generation failed: " + e);
      }
    }

    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 bool ParseArgs(ref ArrayList args, ref int argc, string opt, out string arg) {
      arg = null;
      int tc = argc;
      if (argc > 0) {
        for (int i = 0; i < argc; i++) {
          string value = args[i].ToString();
          if (value == opt) {
            tc--;
            if (i + 1 < argc && args[i + 1].ToString().Length > 0) {
              tc--;
              arg = args[i + 1].ToString();
              args.RemoveAt(i + 1);
              args.RemoveAt(i);
              break;
            }
            args.RemoveAt(i);
            break;
          } else if (Regex.Match(value, "^" + opt).Success) {
            tc--;
            args.RemoveAt(i);
            Match m = Regex.Match(value, "^" + opt + "(.+)");
            arg = m.Groups[1].ToString();
            break;
          }
        }
      }
      argc = tc;
      if (arg != null) {
        return true;
      } else {
        return false;
      }
    }

    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(fi.DirectoryName + "\\" + 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 + "|" + 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 startDir) {
      OpenFileDialog fileOpen = new OpenFileDialog();
      string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

      if (Directory.Exists(startDir)) {
        path = startDir;
      }

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

      int len = args.Length;
      ArrayList a = new ArrayList(args);

      string param = null;
      if (onchi.ParseArgs(ref a, ref len, "-e", out param)) {
        if (!Regex.Match(param, @"^[_\-]").Success) {
          browserPostfix = "_" + param;
        } else {
          browserPostfix = param;
        }
      }

      param = null;
      onchi.ParseArgs(ref a, ref len, "-s", out param);

      FileInfo fi = onchi.PickFile(param);
      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 xml = onchi.BuildXml(newPage.id, fi, onchi.initialPosition);

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

      return (0);
    }
  }
}