mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-05 15:51:36 +00:00
Improved reading and writing large Office files without copying them into memory (#1243)
This commit is contained in:
1 parent
918572c158
commit
dbe609a9a7
37 files changed
+1161
-471
No files matched your search
@@ -1,80 +0,0 @@
|
||||
using System.IO.Compression;
|
||||
|
||||
using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
|
||||
namespace AIStudio.Tools.OpenXml;
|
||||
|
||||
/// <summary>
|
||||
/// Writes a copy of an Office document in which some parts have a changed DOM, without holding the rest of the
|
||||
/// document in memory.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The Open XML SDK saves a package 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, often hundreds of megabytes. So the source
|
||||
/// stays open for reading only, and a new archive comes about entry by entry: each entry of the source is streamed
|
||||
/// through in its order, and each changed part is written from its DOM instead.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// This serves only changes within the XML of existing parts. Whoever adds or removes parts or relationships, as the
|
||||
/// Slide Assistant does, needs the SDK to save the package.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class PackageRewrite
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes a copy of the source with the DOM of the changed parts.
|
||||
/// </summary>
|
||||
/// <param name="sourcePath">The source, which stays as it is.</param>
|
||||
/// <param name="changedParts">The parts of the source, opened by the SDK, whose DOM changed.</param>
|
||||
/// <param name="documentPath">The new document, which must not exist yet.</param>
|
||||
/// <param name="token">The cancellation token, checked between entries.</param>
|
||||
/// <exception cref="InvalidOperationException">A changed part has no entry in the source, e.g., because the source changed.</exception>
|
||||
public static void Write(string sourcePath, IReadOnlyCollection<OpenXmlPart> changedParts, string documentPath, CancellationToken token)
|
||||
{
|
||||
var partsByEntry = changedParts.ToDictionary(EntryNameOf, StringComparer.OrdinalIgnoreCase);
|
||||
using var sourceFile = TemplateFile.OpenRead(sourcePath);
|
||||
using var source = new ZipArchive(sourceFile, 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 source.Entries)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (partsByEntry.TryGetValue(entry.FullName, out var part))
|
||||
{
|
||||
var newEntry = CreateEntryLike(document, entry, CompressionLevel.Optimal);
|
||||
using var stream = newEntry.Open();
|
||||
RootElementOf(part).Save(stream);
|
||||
written++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// A stored entry, such as a video, stays stored; deflating it once more would take time and gain nothing:
|
||||
var copy = CreateEntryLike(document, entry, entry.CompressedLength >= entry.Length ? CompressionLevel.NoCompression : CompressionLevel.Optimal);
|
||||
using var from = entry.Open();
|
||||
using var to = copy.Open();
|
||||
from.CopyTo(to);
|
||||
}
|
||||
|
||||
if (written != partsByEntry.Count)
|
||||
throw new InvalidOperationException($"{partsByEntry.Count - written} changed part(s) have no entry in the document '{sourcePath}'.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The name of the entry which holds a part, e.g., "ppt/slides/slide1.xml" for the part "/ppt/slides/slide1.xml".
|
||||
/// </summary>
|
||||
private static string EntryNameOf(OpenXmlPart part) => Uri.UnescapeDataString(part.Uri.OriginalString).TrimStart('/');
|
||||
|
||||
private static OpenXmlPartRootElement RootElementOf(OpenXmlPart part) => part.RootElement ?? throw new InvalidOperationException($"The changed part '{part.Uri}' has no XML.");
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
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);
|
||||
}
|
||||
@@ -3,8 +3,8 @@ using AIStudio.Settings;
|
||||
namespace AIStudio.Tools.OpenXml;
|
||||
|
||||
/// <summary>
|
||||
/// A file below the data directory, in which a new Office document comes about before it goes into the file the
|
||||
/// user chose, see TargetFile.
|
||||
/// A file below the data directory, in which a new Office document or a piece of it comes about, such as the skeleton
|
||||
/// of a document or a picture for it, before the document goes into the file the user chose, see TargetFile.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
namespace AIStudio.Tools.OpenXml;
|
||||
|
||||
/// <summary>
|
||||
/// A copy of a template in the temporary folder, in which an Office document comes about before it
|
||||
/// goes into the file the user chose.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Only the complete document is streamed into the file the user chose, see TargetFile, so a failure
|
||||
/// before the document is complete leaves the target untouched. Disposing the copy removes it.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The writer edits the copy with the Open XML SDK, which saves it in the update mode of ZipArchive.
|
||||
/// That mode loads every entry behind the first changed one into memory, e.g., the pictures and videos
|
||||
/// behind the first slide. The Slide Assistant needs it all the same, since it adds and removes parts.
|
||||
/// A writer which only changes the XML of existing parts uses PackageRewrite instead, as the document
|
||||
/// segments do.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal sealed class TemplateCopy : IDisposable
|
||||
{
|
||||
private readonly ILogger logger;
|
||||
|
||||
private TemplateCopy(string filePath, ILogger logger)
|
||||
{
|
||||
this.FilePath = filePath;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The path of the copy.
|
||||
/// </summary>
|
||||
public string FilePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Copies the template into a folder below the temporary folder of the system.
|
||||
/// </summary>
|
||||
/// <param name="templatePath">The path of the template.</param>
|
||||
/// <param name="temporaryDirectory">The name of the folder below the temporary folder, one per
|
||||
/// kind of document.</param>
|
||||
/// <param name="fileExtension">The extension of the document which comes about, including the
|
||||
/// leading dot.</param>
|
||||
/// <param name="logger">Where to report a temporary file which cannot be removed.</param>
|
||||
/// <param name="token">The cancellation token.</param>
|
||||
/// <returns>The copy.</returns>
|
||||
public static async Task<TemplateCopy> CreateAsync(string templatePath, string temporaryDirectory, string fileExtension, ILogger logger, CancellationToken token)
|
||||
{
|
||||
var directory = Path.Join(Path.GetTempPath(), temporaryDirectory);
|
||||
Directory.CreateDirectory(directory);
|
||||
|
||||
var copy = new TemplateCopy(Path.Join(directory, $"{Guid.NewGuid():N}{fileExtension}"), logger);
|
||||
try
|
||||
{
|
||||
await using var templateFile = TemplateFile.OpenRead(templatePath);
|
||||
await using var copyFile = new FileStream(copy.FilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
|
||||
await templateFile.CopyToAsync(copyFile, token);
|
||||
}
|
||||
catch
|
||||
{
|
||||
copy.Dispose();
|
||||
throw;
|
||||
}
|
||||
|
||||
return copy;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the copy for the writer to edit it.
|
||||
/// </summary>
|
||||
/// <returns>The copy, opened for reading and writing.</returns>
|
||||
public FileStream OpenForEditing() => new(this.FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
|
||||
|
||||
/// <summary>
|
||||
/// Streams the complete document into the file the user chose, see TargetFile.WriteOverAsync.
|
||||
/// </summary>
|
||||
/// <param name="targetPath">The path of the file the user chose. It may exist; the save dialog
|
||||
/// asked about overwriting it.</param>
|
||||
/// <param name="token">The cancellation token.</param>
|
||||
public Task WriteIntoAsync(string targetPath, CancellationToken token) => TargetFile.WriteOverAsync(this.FilePath, targetPath, this.logger, token);
|
||||
|
||||
/// <summary>
|
||||
/// Removes the copy.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A copy of the template left behind would pile up in the temporary folder with every attempt.
|
||||
/// </remarks>
|
||||
public void Dispose() => TargetFile.DeleteQuietly(this.FilePath, this.logger);
|
||||
}
|
||||
Reference in new issue
Block a user