using System.IO.Compression;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
namespace AIStudio.Tools.OpenXml;
///
/// 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.
///
///
///
/// 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.
///
///
/// 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.
///
///
/// 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.
///
///
internal sealed class PackageSkeleton : IDisposable
{
///
/// The extensions of new parts whose format is compressed already, e.g., photos, which deflating would only slow down.
///
private static readonly HashSet COMPRESSED_PART_EXTENSIONS = new(StringComparer.OrdinalIgnoreCase)
{
".jpg",
".jpeg",
".png",
".gif",
};
private readonly string sourcePath;
private readonly StagedDocument file;
private readonly Dictionary emptiedEntries;
private PackageSkeleton(string sourcePath, StagedDocument file, Dictionary emptiedEntries)
{
this.sourcePath = sourcePath;
this.file = file;
this.emptiedEntries = emptiedEntries;
}
///
/// Writes the skeleton of an Office document.
///
/// The document, which stays as it is.
/// The extension of the document, including the leading dot, e.g., ".pptx".
/// Where to report a skeleton which cannot be removed.
/// The cancellation token, checked between entries.
/// The skeleton.
public static PackageSkeleton Create(string sourcePath, string fileExtension, ILogger logger, CancellationToken token)
{
var file = StagedDocument.Create(fileExtension, logger);
try
{
var emptiedEntries = new Dictionary(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;
}
}
///
/// Whether an entry of an Office document holds XML, e.g., a slide or relationships, which the skeleton keeps.
///
public static bool HoldsXml(ZipArchiveEntry entry) => entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || entry.FullName.EndsWith(".rels", StringComparison.OrdinalIgnoreCase);
///
/// The name of the entry which holds a part, e.g., "ppt/media/image1.png" for the part "/ppt/media/image1.png".
///
public static string EntryNameOf(Uri partUri) => Uri.UnescapeDataString(partUri.OriginalString).TrimStart('/');
///
/// Opens the skeleton for the SDK to read it.
///
///
/// 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.
///
/// The skeleton, opened for reading.
public FileStream OpenRead() => new(this.file.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
///
/// Opens the skeleton for a writer which adds or removes parts, such as the Slide Assistant.
///
///
/// 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.
///
/// The skeleton, opened for reading and writing.
public FileStream OpenForEditing() => new(this.file.FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
///
/// Writes the new document along the entries of the skeleton.
///
///
/// 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.
///
/// The parts of the skeleton, opened by the SDK for reading, whose DOM changed.
/// 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.
/// The new document, which must not exist yet.
/// The cancellation token, checked between entries.
/// Whether the document was written; false when the source changed in between.
/// A changed part has no entry in the skeleton.
public bool TryWriteDocument(IReadOnlyCollection changedParts, IReadOnlyDictionary 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(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;
}
///
/// Removes the skeleton.
///
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.");
///
/// Copies an entry as it is; a stored one stays stored.
///
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;
}
///
/// What an entry of the source looked like when the skeleton left it empty.
///
/// The checksum of its content.
/// The length of its content, unpacked.
private sealed record EmptiedEntry(uint Crc32, long Length);
}