DOCX.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Xml;
  6. using Newtonsoft.Json;
  7. using System.Linq;
  8. namespace DOCX
  9. {
  10. public class Docx : IDisposable
  11. {
  12. private readonly ZipArchive _zip;
  13. private readonly string _authorsJson;
  14. private readonly XmlNamespaceManager _ns = new XmlNamespaceManager(new NameTable());
  15. private readonly string _wNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
  16. private void LoadNamespace()
  17. {
  18. _ns.AddNamespace("w", _wNamespace);
  19. }
  20. public Docx(string path)
  21. {
  22. _zip = ZipFile.Open(path, ZipArchiveMode.Update);
  23. _authorsJson = Path.ChangeExtension(path, "json");
  24. LoadNamespace();
  25. }
  26. public Docx(ZipArchive zipArchive)
  27. {
  28. _zip = zipArchive;
  29. LoadNamespace();
  30. }
  31. private (XmlDocument doc, string message) GetXML(ZipArchiveEntry entry)
  32. {
  33. XmlDocument doc = new XmlDocument()
  34. {
  35. PreserveWhitespace = true // Disables auto-indent
  36. };
  37. try
  38. {
  39. using (StreamReader sr = new StreamReader(entry.Open()))
  40. {
  41. doc.Load(sr);
  42. }
  43. }
  44. catch (Exception e)
  45. {
  46. return (null, $"Error reading {entry.Name}!\n{e}");
  47. }
  48. return (doc, "OK");
  49. }
  50. private (bool status, string message) SaveXML(XmlDocument doc, ZipArchiveEntry entry)
  51. {
  52. try
  53. {
  54. using (var sr = entry.Open())
  55. {
  56. sr.SetLength(doc.OuterXml.Length);
  57. using (StreamWriter sw = new StreamWriter(sr))
  58. {
  59. doc.Save(sw);
  60. }
  61. }
  62. }
  63. catch (Exception e)
  64. {
  65. return (false, $"Error saving {entry.Name}!\n{e}");
  66. }
  67. return (true, "OK");
  68. }
  69. private (bool status, string message) AddTrackRevisions(ZipArchiveEntry settings)
  70. {
  71. var loadResult = GetXML(settings);
  72. if (loadResult.doc == null)
  73. return (false, loadResult.message);
  74. XmlDocument doc = loadResult.doc;
  75. if (doc.SelectSingleNode("//w:trackRevisions", _ns) != null) return (true, "No change needed.");
  76. XmlElement trackRevisions = doc.CreateElement("w", "trackRevisions", _wNamespace);
  77. if (doc.DocumentElement == null)
  78. return (false, "No root element in settings.xml!");
  79. doc.DocumentElement.AppendChild(trackRevisions);
  80. return SaveXML(doc, settings);
  81. }
  82. public (bool status, string message) EnableTrackedChanges()
  83. {
  84. ZipArchiveEntry settings = _zip.GetEntry(@"word/settings.xml");
  85. if (settings == null)
  86. return (false,
  87. "Can't access settings.xml!");
  88. var result = AddTrackRevisions(settings);
  89. return !result.status ? (false, result.message) : (true, "OK");
  90. }
  91. private Dictionary<string, string> _authors = new Dictionary<string, string>();
  92. private string AnonymizeName(string name)
  93. {
  94. if (_authors.TryGetValue(name, out var anonymousName))
  95. return anonymousName;
  96. anonymousName = $"Author{_authors.Count + 1}";
  97. _authors.Add(name, anonymousName);
  98. return anonymousName;
  99. }
  100. private (bool status, string message) AnonymizeAuthors(ZipArchiveEntry comments)
  101. {
  102. var loadResult = GetXML(comments);
  103. if (loadResult.doc == null)
  104. return (false, loadResult.message);
  105. XmlDocument doc = loadResult.doc;
  106. var commentNodes = doc.SelectNodes("//w:comment", _ns);
  107. if (commentNodes == null)
  108. return (false, "There are no comments!");
  109. foreach (XmlNode node in commentNodes)
  110. {
  111. var author = node.Attributes["w:author"];
  112. author.Value = AnonymizeName(author.Value);
  113. }
  114. return SaveXML(doc, comments);
  115. }
  116. private bool SaveAuthors(string path = null)
  117. {
  118. if (string.IsNullOrEmpty(path)) {
  119. if (!string.IsNullOrEmpty(_authorsJson))
  120. path = _authorsJson;
  121. else
  122. return false;
  123. }
  124. using (StreamWriter sw = new StreamWriter(path))
  125. using (JsonWriter writer = new JsonTextWriter(sw))
  126. {
  127. JsonSerializer serializer = new JsonSerializer
  128. {
  129. NullValueHandling = NullValueHandling.Ignore
  130. };
  131. serializer.Serialize(writer, _authors);
  132. }
  133. return true;
  134. }
  135. public (bool status, string message) AnonymizeComments(string path = null)
  136. {
  137. ZipArchiveEntry comments = _zip.GetEntry(@"word/comments.xml");
  138. if (comments == null)
  139. return (false,
  140. "Can't access comments.xml!");
  141. var result = AnonymizeAuthors(comments);
  142. if (!result.status) return (false, result.message);
  143. return !SaveAuthors(path) ? (false, $"Problem saving authors to {path}!") : (true, "OK");
  144. }
  145. private bool LoadAuthors(string path=null)
  146. {
  147. if (string.IsNullOrEmpty(path))
  148. if (File.Exists(_authorsJson))
  149. path = _authorsJson;
  150. else
  151. return false;
  152. using (StreamReader rd = new StreamReader(path))
  153. {
  154. string json = rd.ReadToEnd();
  155. _authors = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  156. }
  157. return _authors.Count > 0;
  158. }
  159. private (bool status, string message) DeanonymizeAuthors(ZipArchiveEntry comments)
  160. {
  161. var loadResult = GetXML(comments);
  162. if (loadResult.doc == null)
  163. return (false, loadResult.message);
  164. XmlDocument doc = loadResult.doc;
  165. var commentNodes = doc.SelectNodes("//w:comment", _ns);
  166. if (commentNodes == null)
  167. return (false, "There are no comments!");
  168. foreach (XmlNode node in commentNodes)
  169. {
  170. var author = node.Attributes["w:author"];
  171. if (_authors.TryGetValue(author.Value, out var name))
  172. author.Value = name;
  173. }
  174. return SaveXML(doc, comments);
  175. }
  176. public (bool status, string message) DeanonymizeComments(string path=null)
  177. {
  178. if (!LoadAuthors(path))
  179. return (false, $"Can't load authors from {path}!");
  180. _authors = _authors.ToDictionary(x => x.Value, x => x.Key);
  181. ZipArchiveEntry comments = _zip.GetEntry(@"word/comments.xml");
  182. if (comments == null)
  183. return (false,
  184. "Can't access comments.xml!");
  185. var result = DeanonymizeAuthors(comments);
  186. return !result.status ? (false, result.message) : (true, "OK");
  187. }
  188. public void Dispose()
  189. {
  190. Dispose(true);
  191. GC.SuppressFinalize(this);
  192. }
  193. ~Docx()
  194. {
  195. Dispose(false);
  196. }
  197. protected virtual void Dispose(bool disposing)
  198. {
  199. if (disposing)
  200. {
  201. _zip.Dispose();
  202. }
  203. }
  204. }
  205. }