Files
AI-Studio/app/MindWork AI Studio/Tools/OpenXml/PackageSkeleton.cs
T

237 lines
12 KiB
C#

using System.IO.Compression;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
namespace AIStudio.Tools.OpenXml;
/// <summary>
/// A copy of an Office document which holds only its XML. Through it, the Open XML SDK reads the document and a writer
/// edits it, and a new document comes about, without the pictures and videos of the document ever coming into memory or
/// into the temporary folder.
/// </summary>
/// <remarks>
/// <para>
/// The SDK copies a document it opens for reading only into the temporary folder of the system, as a whole, so that it
/// can repair broken links; on many Linux systems, that folder lives in memory. And it saves a document in the update
/// mode of ZipArchive, which loads every entry behind the first changed one into memory, e.g., all pictures and videos
/// behind the first slide. Documents of organizations easily take hundreds of megabytes.
/// </para>
/// <para>
/// So the skeleton keeps every entry of the source in its order, yet only the XML and the relationships with their
/// content; every other entry stays empty. The SDK reads and edits the skeleton instead of the source. The new document
/// then comes about entry by entry along the skeleton: the XML from the skeleton or from a changed DOM, the pictures and
/// videos streamed through from the source, and new parts from files of their own. What a writer removed from the
/// skeleton stays out.
/// </para>
/// <para>
/// The source is opened twice for a moment rather than kept open, so that PowerPoint or Word may save it meanwhile; the
/// checksums of the emptied entries tell whether it changed in between. The skeleton lies in a StagedDocument, which
/// disposing removes.
/// </para>
/// </remarks>
internal sealed class PackageSkeleton : IDisposable
{
/// <summary>
/// The extensions of new parts whose format is compressed already, e.g., photos, which deflating would only slow down.
/// </summary>
private static readonly HashSet<string> COMPRESSED_PART_EXTENSIONS = new(StringComparer.OrdinalIgnoreCase)
{
".jpg",
".jpeg",
".png",
".gif",
};
private readonly string sourcePath;
private readonly StagedDocument file;
private readonly Dictionary<string, EmptiedEntry> emptiedEntries;
private PackageSkeleton(string sourcePath, StagedDocument file, Dictionary<string, EmptiedEntry> emptiedEntries)
{
this.sourcePath = sourcePath;
this.file = file;
this.emptiedEntries = emptiedEntries;
}
/// <summary>
/// Writes the skeleton of an Office document.
/// </summary>
/// <param name="sourcePath">The document, which stays as it is.</param>
/// <param name="fileExtension">The extension of the document, including the leading dot, e.g., ".pptx".</param>
/// <param name="logger">Where to report a skeleton which cannot be removed.</param>
/// <param name="token">The cancellation token, checked between entries.</param>
/// <returns>The skeleton.</returns>
public static PackageSkeleton Create(string sourcePath, string fileExtension, ILogger logger, CancellationToken token)
{
var file = StagedDocument.Create(fileExtension, logger);
try
{
var emptiedEntries = new Dictionary<string, EmptiedEntry>(StringComparer.OrdinalIgnoreCase);
using (var sourceFile = TemplateFile.OpenRead(sourcePath))
using (var source = new ZipArchive(sourceFile, ZipArchiveMode.Read))
using (var skeletonFile = new FileStream(file.FilePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
using (var skeleton = new ZipArchive(skeletonFile, ZipArchiveMode.Create))
{
foreach (var entry in source.Entries)
{
token.ThrowIfCancellationRequested();
if (!HoldsXml(entry))
{
// An entry which is never opened stays empty:
CreateEntryLike(skeleton, entry, CompressionLevel.NoCompression);
emptiedEntries[entry.FullName] = new EmptiedEntry(entry.Crc32, entry.Length);
continue;
}
// The skeleton is only a step on the way, so it is compressed quickly rather than well:
var copy = CreateEntryLike(skeleton, entry, CompressionLevel.Fastest);
using var from = entry.Open();
using var to = copy.Open();
from.CopyTo(to);
}
}
return new PackageSkeleton(sourcePath, file, emptiedEntries);
}
catch
{
file.Dispose();
throw;
}
}
/// <summary>
/// Whether an entry of an Office document holds XML, e.g., a slide or relationships, which the skeleton keeps.
/// </summary>
public static bool HoldsXml(ZipArchiveEntry entry) => entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || entry.FullName.EndsWith(".rels", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// The name of the entry which holds a part, e.g., "ppt/media/image1.png" for the part "/ppt/media/image1.png".
/// </summary>
public static string EntryNameOf(Uri partUri) => Uri.UnescapeDataString(partUri.OriginalString).TrimStart('/');
/// <summary>
/// Opens the skeleton for the SDK to read it.
/// </summary>
/// <remarks>
/// The SDK copies a document it opens for reading only into the temporary folder; of the skeleton, that is only the
/// XML. A writer which only changes the DOM of existing parts reads the skeleton this way as well, and hands the
/// changed parts to TryWriteDocument.
/// </remarks>
/// <returns>The skeleton, opened for reading.</returns>
public FileStream OpenRead() => new(this.file.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
/// <summary>
/// Opens the skeleton for a writer which adds or removes parts, such as the Slide Assistant.
/// </summary>
/// <remarks>
/// The SDK saves the skeleton in the update mode of ZipArchive, which loads only XML here. A new part whose content
/// lies in a file of its own stays empty, and its file goes to TryWriteDocument.
/// </remarks>
/// <returns>The skeleton, opened for reading and writing.</returns>
public FileStream OpenForEditing() => new(this.file.FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
/// <summary>
/// Writes the new document along the entries of the skeleton.
/// </summary>
/// <remarks>
/// A new part comes from its file, even under the name of an entry of the source: the SDK may give a new part the
/// name of one a writer removed. A changed part comes from its DOM, an emptied entry from the source, and everything
/// else from the skeleton. A stored entry, such as a video, stays stored; deflating it once more would take time and
/// gain nothing. When the source changed since the skeleton was written, the document stays incomplete, and the
/// caller removes it.
/// </remarks>
/// <param name="changedParts">The parts of the skeleton, opened by the SDK for reading, whose DOM changed.</param>
/// <param name="newPartFiles">The files which hold the content of new parts, by the names of their entries, see EntryNameOf.
/// Entries the skeleton no longer has are passed over.</param>
/// <param name="documentPath">The new document, which must not exist yet.</param>
/// <param name="token">The cancellation token, checked between entries.</param>
/// <returns>Whether the document was written; false when the source changed in between.</returns>
/// <exception cref="InvalidOperationException">A changed part has no entry in the skeleton.</exception>
public bool TryWriteDocument(IReadOnlyCollection<OpenXmlPart> changedParts, IReadOnlyDictionary<string, string> newPartFiles, string documentPath, CancellationToken token)
{
var partsByEntry = changedParts.ToDictionary(part => EntryNameOf(part.Uri), StringComparer.OrdinalIgnoreCase);
using var sourceFile = TemplateFile.OpenRead(this.sourcePath);
using var source = new ZipArchive(sourceFile, ZipArchiveMode.Read);
var sourceEntries = new Dictionary<string, ZipArchiveEntry>(StringComparer.OrdinalIgnoreCase);
foreach (var entry in source.Entries)
sourceEntries.TryAdd(entry.FullName, entry);
using var skeletonFile = this.OpenRead();
using var skeleton = new ZipArchive(skeletonFile, ZipArchiveMode.Read);
using var documentFile = new FileStream(documentPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);
using var document = new ZipArchive(documentFile, ZipArchiveMode.Create);
var written = 0;
foreach (var entry in skeleton.Entries)
{
token.ThrowIfCancellationRequested();
if (newPartFiles.TryGetValue(entry.FullName, out var partFile))
{
var newEntry = CreateEntryLike(document, entry, COMPRESSED_PART_EXTENSIONS.Contains(Path.GetExtension(entry.FullName)) ? CompressionLevel.NoCompression : CompressionLevel.Optimal);
using var from = new FileStream(partFile, FileMode.Open, FileAccess.Read, FileShare.Read);
using var to = newEntry.Open();
from.CopyTo(to);
continue;
}
if (partsByEntry.TryGetValue(entry.FullName, out var part))
{
using var stream = CreateEntryLike(document, entry, CompressionLevel.Optimal).Open();
RootElementOf(part).Save(stream);
written++;
continue;
}
if (this.emptiedEntries.TryGetValue(entry.FullName, out var emptied))
{
if (!sourceEntries.TryGetValue(entry.FullName, out var sourceEntry) || sourceEntry.Crc32 != emptied.Crc32 || sourceEntry.Length != emptied.Length)
return false;
CopyThrough(sourceEntry, document);
continue;
}
CopyThrough(entry, document);
}
if (written != partsByEntry.Count)
throw new InvalidOperationException($"{partsByEntry.Count - written} changed part(s) have no entry in the skeleton of the document '{this.sourcePath}'.");
return true;
}
/// <summary>
/// Removes the skeleton.
/// </summary>
public void Dispose() => this.file.Dispose();
private static OpenXmlPartRootElement RootElementOf(OpenXmlPart part) => part.RootElement ?? throw new InvalidOperationException($"The changed part '{part.Uri}' has no XML.");
/// <summary>
/// Copies an entry as it is; a stored one stays stored.
/// </summary>
private static void CopyThrough(ZipArchiveEntry entry, ZipArchive archive)
{
var copy = CreateEntryLike(archive, entry, entry.CompressedLength >= entry.Length ? CompressionLevel.NoCompression : CompressionLevel.Optimal);
using var from = entry.Open();
using var to = copy.Open();
from.CopyTo(to);
}
private static ZipArchiveEntry CreateEntryLike(ZipArchive archive, ZipArchiveEntry entry, CompressionLevel compressionLevel)
{
var newEntry = archive.CreateEntry(entry.FullName, compressionLevel);
newEntry.LastWriteTime = entry.LastWriteTime;
newEntry.ExternalAttributes = entry.ExternalAttributes;
return newEntry;
}
/// <summary>
/// What an entry of the source looked like when the skeleton left it empty.
/// </summary>
/// <param name="Crc32">The checksum of its content.</param>
/// <param name="Length">The length of its content, unpacked.</param>
private sealed record EmptiedEntry(uint Crc32, long Length);
}