namespace AIStudio.Tools.OpenXml; /// /// 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. /// /// /// /// 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. /// /// /// 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. /// /// internal sealed class TemplateCopy : IDisposable { private readonly ILogger logger; private TemplateCopy(string filePath, ILogger logger) { this.FilePath = filePath; this.logger = logger; } /// /// The path of the copy. /// public string FilePath { get; } /// /// Copies the template into a folder below the temporary folder of the system. /// /// The path of the template. /// The name of the folder below the temporary folder, one per /// kind of document. /// The extension of the document which comes about, including the /// leading dot. /// Where to report a temporary file which cannot be removed. /// The cancellation token. /// The copy. public static async Task 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; } /// /// Opens the copy for the writer to edit it. /// /// The copy, opened for reading and writing. public FileStream OpenForEditing() => new(this.FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None); /// /// Streams the complete document into the file the user chose, see TargetFile.WriteOverAsync. /// /// The path of the file the user chose. It may exist; the save dialog /// asked about overwriting it. /// The cancellation token. public Task WriteIntoAsync(string targetPath, CancellationToken token) => TargetFile.WriteOverAsync(this.FilePath, targetPath, this.logger, token); /// /// Removes the copy. /// /// /// A copy of the template left behind would pile up in the temporary folder with every attempt. /// public void Dispose() => TargetFile.DeleteQuietly(this.FilePath, this.logger); }