DOCX.cs 7.7 KB

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