PlotDirector/PlotLine/Services/ProjectBackupFiles.cs

158 lines
9.6 KiB
C#

using System.Security.Cryptography;
using PlotLine.Models;
namespace PlotLine.Services;
public sealed class ProjectBackupFileUnavailableException(string message, Exception? innerException=null) : IOException(message,innerException);
public interface IProjectBackupFiles
{
Task CaptureAsync(ProjectBackupExport backup);
Task<ProjectBackupFileStage> StageAsync(ProjectBackupExport backup, bool importingCopy);
}
// Files are written to fresh names before SQL publishes their references. Failure removes only those new files.
public sealed class ProjectBackupFileStage : IDisposable
{
private readonly List<string> paths = [];
private bool committed;
internal void Track(string path) => paths.Add(path);
public void Commit() => committed = true;
public void Dispose()
{
if (committed) return;
foreach (var path in paths) if (File.Exists(path)) File.Delete(path);
}
}
public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProjectBackupFiles
{
public static bool IsActiveWebFile(string path)=>new[]{".html",".htm",".xhtml",".svg",".xml",".js",".mjs",".css"}.Contains(Path.GetExtension(path),StringComparer.OrdinalIgnoreCase);
private sealed record Reference(string? Path, string Folder, string EntityType, int EntityID, Action<string?> Assign);
private static IEnumerable<Reference> References(ProjectBackupExport backup)
{
foreach(var character in backup.Data.Characters)
{
var folder=$"characters/{character.CharacterID}";
yield return new(character.ImagePath,folder,"CharacterImage",character.CharacterID,x=>character.ImagePath=x);
yield return new(character.ThumbnailPath,folder,"CharacterImage",character.CharacterID,x=>character.ThumbnailPath=x);
yield return new(character.AvatarImagePath,folder,"CharacterAvatar",character.CharacterID,x=>character.AvatarImagePath=x);
yield return new(character.AvatarThumbnailPath,folder,"CharacterAvatar",character.CharacterID,x=>character.AvatarThumbnailPath=x);
}
foreach(var image in backup.Data.CharacterImages)
{
if(image.IsDeleted) continue;
var folder=$"characters/{image.CharacterID}";
yield return new(image.ImagePath,folder,"CharacterImage",image.CharacterImageID,x=>image.ImagePath=x??"");
yield return new(image.ThumbnailPath,folder,"CharacterImage",image.CharacterImageID,x=>image.ThumbnailPath=x??"");
}
foreach(var asset in backup.Data.StoryAssets)
{
var folder=$"story-assets/{asset.StoryAssetID}";
yield return new(asset.ImagePath,folder,"StoryAssetImage",asset.StoryAssetID,x=>asset.ImagePath=x);
yield return new(asset.ThumbnailPath,folder,"StoryAssetImage",asset.StoryAssetID,x=>asset.ThumbnailPath=x);
}
foreach(var book in backup.Data.Books)
{
var folder=$"books/{book.BookID}";
yield return new(book.CoverStandardPath,folder,"BookCover",book.BookID,x=>book.CoverStandardPath=x);
yield return new(book.CoverThumbnailPath,folder,"BookCover",book.BookID,x=>book.CoverThumbnailPath=x);
}
foreach(var floor in backup.Data.FloorPlanFloors)
{
var folder=$"floor-plans/{backup.Project!.ProjectID}/{floor.FloorPlanID}/backgrounds";
yield return new(floor.BackgroundImagePath,folder,"FloorPlanBackground",floor.FloorPlanFloorID,x=>floor.BackgroundImagePath=x);
}
foreach(var attachment in backup.Data.SceneAttachments)
yield return new(attachment.FilePath,$"scenes/{attachment.SceneID}","SceneAttachment",attachment.SceneID,x=>attachment.FilePath=x);
}
private static bool IsFile(Reference reference) => !string.IsNullOrWhiteSpace(reference.Path) && reference.Path!=BookCoverService.PlaceholderPath;
private static bool ValidPath(Reference reference)
{
var path=reference.Path!;
return path.StartsWith("/uploads/"+reference.Folder+"/",StringComparison.Ordinal)
&& !path.Contains('\\') && !path.Split('/').Any(segment=>segment is "." or "..");
}
public static void Prune(ProjectBackupExport backup){var paths=References(backup).Where(IsFile).Select(r=>r.Path).ToHashSet();backup.Files=backup.Files.Where(f=>paths.Contains(f.Path)).ToArray();}
public static bool HasUploads(ProjectBackupExport backup) => References(backup).Any(IsFile);
public static string? Validate(ProjectBackupExport backup)
{
if(backup.Files is null || backup.Files.Any(file=>file is null))return "Project backup contains invalid file records.";
if(backup.FormatVersion is not ("1.3" or "1.4" or "1.5") && backup.Files.Count>0)return "Embedded files require project backup format 1.3.";
var references=References(backup).Where(IsFile).ToArray();
if(references.Any(reference=>!ValidPath(reference)))return "Project backup contains a file path outside its owning entity's upload folder.";
if(backup.Files.Select(file=>file.Path).Distinct(StringComparer.Ordinal).Count()!=backup.Files.Count)return "Project backup contains duplicate file paths.";
var referenced=references.Select(reference=>reference.Path!).ToHashSet(StringComparer.Ordinal);
foreach(var file in backup.Files)
if(file.Path is null || !referenced.Contains(file.Path) || file.Data is null || !string.Equals(file.Sha256,Convert.ToHexString(SHA256.HashData(file.Data)),StringComparison.OrdinalIgnoreCase))
return "Project backup contains an unreferenced file or file bytes do not match their checksum.";
if(backup.FormatVersion is ("1.3" or "1.4" or "1.5") && references.Any(reference=>!backup.Files.Any(file=>file.Path==reference.Path)))
return "Project backup is missing bytes for a referenced uploaded file.";
return null;
}
public async Task CaptureAsync(ProjectBackupExport backup)
{
var files=new List<ProjectBackupFile>();
foreach(var reference in References(backup).Where(IsFile))
{
if(!ValidPath(reference))throw new InvalidDataException("A project file path does not belong to its owning entity.");
if(files.Any(file=>file.Path==reference.Path))continue;
var physical=storage.TryResolvePublicPath(reference.Path,"uploads/"+reference.Folder);
if(physical is null || !File.Exists(physical))throw new ProjectBackupFileUnavailableException("A referenced project file is missing. The backup was not created.");
byte[] bytes;
try{bytes=await File.ReadAllBytesAsync(physical);}
catch(Exception ex) when(ex is FileNotFoundException or DirectoryNotFoundException)
{throw new ProjectBackupFileUnavailableException("A referenced project file changed during capture. The backup was not created.",ex);}
files.Add(new(){Path=reference.Path!,Data=bytes,Sha256=Convert.ToHexString(SHA256.HashData(bytes))});
}
backup.Files=files;
}
public async Task<ProjectBackupFileStage> StageAsync(ProjectBackupExport backup, bool importingCopy)
{
var stage=new ProjectBackupFileStage();
try
{
foreach(var file in backup.Files){file.RestoredPath=null;file.EntityType=null;file.EntityID=0;}
var references=References(backup).Where(IsFile).ToArray();
if(backup.FormatVersion is not ("1.3" or "1.4" or "1.5"))
{
foreach(var reference in references)
{
if(importingCopy)reference.Assign(null);
else if(!ValidPath(reference) || storage.TryResolvePublicPath(reference.Path,"uploads/"+reference.Folder) is not string path || !File.Exists(path))
throw new InvalidDataException("This older backup has no embedded file bytes and a referenced original file is unavailable.");
}
if(importingCopy)foreach(var character in backup.Data.Characters)character.AvatarSourceCharacterImageID=null;
return stage;
}
foreach(var file in backup.Files)
{
var owners=references.Where(reference=>reference.Path==file.Path).ToArray();
if(owners.Length==0)throw new InvalidDataException("Unreferenced backup file.");
var owner=owners[0];
var extension=Path.GetExtension(file.Path);
if(extension.Length is <2 or >12 || extension[1..].Any(character=>!char.IsAsciiLetterOrDigit(character)))extension=".bin";
// Imported bytes must not become executable same-origin web content. Preserve bytes as a binary download.
if(IsActiveWebFile(file.Path))extension=".bin";
var filename=$"backup-{Guid.NewGuid():N}{extension.ToLowerInvariant()}";
var physical=storage.GetFilePath(owner.Folder,filename);
storage.GetDirectory(owner.Folder);
// CreateNew forbids replacing existing author files, even on a name collision.
await using(var stream=new FileStream(physical,FileMode.CreateNew,FileAccess.Write,FileShare.None))
{
stage.Track(physical);
await stream.WriteAsync(file.Data);
}
var publicPath=storage.GetPublicPath(owner.Folder,filename);
foreach(var reference in owners)reference.Assign(publicPath);
file.RestoredPath=publicPath;
file.EntityType=owner.EntityType;
file.EntityID=owner.EntityID;
}
return stage;
}
catch { stage.Dispose(); throw; }
}
}