DOCX.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Xml;
  6. using System.Linq;
  7. using System.Text.Json;
  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. {
  120. if (!string.IsNullOrEmpty(_authorsJson))
  121. path = _authorsJson;
  122. else
  123. return false;
  124. }
  125. using (var fs = File.OpenWrite(path))
  126. {
  127. JsonSerializer.Serialize(fs, _authors, typeof(Dictionary<string, string>));
  128. }
  129. return true;
  130. }
  131. public (bool status, string message) AnonymizeComments(string path = null)
  132. {
  133. ZipArchiveEntry comments = _zip.GetEntry(@"word/comments.xml");
  134. if (comments == null)
  135. return (false,
  136. "Can't access comments.xml!");
  137. var result = AnonymizeAuthors(comments);
  138. if (!result.status) return (false, result.message);
  139. return !SaveAuthors(path) ? (false, $"Problem saving authors to {path}!") : (true, "OK");
  140. }
  141. private bool LoadAuthors(string path = null)
  142. {
  143. if (string.IsNullOrEmpty(path))
  144. if (File.Exists(_authorsJson))
  145. path = _authorsJson;
  146. else
  147. return false;
  148. using (var fs = File.OpenRead(path))
  149. {
  150. _authors = JsonSerializer.Deserialize<Dictionary<string, string>>(fs);
  151. }
  152. return _authors.Count > 0;
  153. }
  154. private (bool status, string message) DeanonymizeAuthors(ZipArchiveEntry comments)
  155. {
  156. var loadResult = GetXML(comments);
  157. if (loadResult.doc == null)
  158. return (false, loadResult.message);
  159. XmlDocument doc = loadResult.doc;
  160. var commentNodes = doc.SelectNodes("//w:comment", _ns);
  161. if (commentNodes == null)
  162. return (false, "There are no comments!");
  163. foreach (XmlNode node in commentNodes)
  164. {
  165. var author = node.Attributes["w:author"];
  166. if (_authors.TryGetValue(author.Value, out var name))
  167. author.Value = name;
  168. }
  169. return SaveXML(doc, comments);
  170. }
  171. public (bool status, string message) DeanonymizeComments(string path = null)
  172. {
  173. if (!LoadAuthors(path))
  174. return (false, $"Can't load authors from {path}!");
  175. _authors = _authors.ToDictionary(x => x.Value, x => x.Key);
  176. ZipArchiveEntry comments = _zip.GetEntry(@"word/comments.xml");
  177. if (comments == null)
  178. return (false,
  179. "Can't access comments.xml!");
  180. var result = DeanonymizeAuthors(comments);
  181. return !result.status ? (false, result.message) : (true, "OK");
  182. }
  183. public void Dispose()
  184. {
  185. Dispose(true);
  186. GC.SuppressFinalize(this);
  187. }
  188. ~Docx()
  189. {
  190. Dispose(false);
  191. }
  192. protected virtual void Dispose(bool disposing)
  193. {
  194. if (disposing)
  195. {
  196. _zip.Dispose();
  197. }
  198. }
  199. }
  200. }