54 lines
4.7 KiB
C#
54 lines
4.7 KiB
C#
using System.Security.Cryptography;
|
|
using PlotLine.Data;
|
|
using PlotLine.Models;
|
|
using SkiaSharp;
|
|
namespace PlotLine.Services;
|
|
|
|
// Shared encoded-format inspection; Floor Plans keeps its existing file/persistence workflow.
|
|
public static class RasterImageValidation
|
|
{
|
|
public static SKImageInfo Inspect(byte[] bytes, long maxPixels = long.MaxValue)
|
|
{
|
|
using var codec=SKCodec.Create(new MemoryStream(bytes));
|
|
if(codec is null||codec.EncodedFormat is not (SKEncodedImageFormat.Png or SKEncodedImageFormat.Jpeg or SKEncodedImageFormat.Webp)||codec.Info.Width<1||codec.Info.Height<1||(long)codec.Info.Width*codec.Info.Height>maxPixels)throw new InvalidDataException("Choose a valid PNG, JPEG or WebP image within the image size limit.");
|
|
return codec.Info;
|
|
}
|
|
}
|
|
public sealed class MapReferenceImageService(MapRepository maps,ISubscriptionService subscriptions)
|
|
{
|
|
public const long MaxUploadBytes=10L*1024*1024;
|
|
public const int MaxStoredBytes=8*1024*1024;
|
|
public const long MaxPixels=16_777_216;
|
|
public static MapReferenceImage Normalize(byte[] bytes,string fileName)
|
|
{
|
|
if(bytes.LongLength is 0 or >MaxUploadBytes||!new[]{".png",".jpg",".jpeg",".webp"}.Contains(Path.GetExtension(fileName).ToLowerInvariant()))throw new InvalidDataException("Choose a PNG, JPEG or WebP image, 10 MB or smaller.");
|
|
var info=RasterImageValidation.Inspect(bytes,MaxPixels);
|
|
using var codec=SKCodec.Create(new MemoryStream(bytes))??throw new InvalidDataException("Invalid image.");
|
|
using var decoded=new SKBitmap(info.Width,info.Height,SKColorType.Bgra8888,SKAlphaType.Premul);
|
|
if(codec.GetPixels(decoded.Info,decoded.GetPixels())!=SKCodecResult.Success)throw new InvalidDataException("The image could not be completely decoded. Choose another image.");
|
|
var ratio=Math.Min(1,4096d/Math.Max(info.Width,info.Height));
|
|
using var scaled=decoded.Resize(new SKImageInfo(Math.Max(1,(int)Math.Round(info.Width*ratio)),Math.Max(1,(int)Math.Round(info.Height*ratio))),new SKSamplingOptions(SKFilterMode.Linear,SKMipmapMode.Linear))??throw new InvalidDataException("Image could not be resized.");
|
|
using var image=SKImage.FromBitmap(scaled);using var encoded=image.Encode(SKEncodedImageFormat.Webp,90);
|
|
if(encoded is null||encoded.Size>MaxStoredBytes)throw new InvalidDataException("The processed image is too large. Try a smaller reference image.");
|
|
var name=Path.GetFileName(fileName.Replace('\\','/'));if(name.Length>200)name=name[..200];
|
|
return new(){ImageID=Guid.NewGuid(),OriginalFileName=name,Width=scaled.Width,Height=scaled.Height,ImageData=encoded.ToArray(),FileSizeBytes=encoded.Size};
|
|
}
|
|
public async Task<MapReferenceImage> UploadAsync(int projectId,int userId,IFormFile upload)
|
|
{
|
|
if(upload.Length is <=0 or >MaxUploadBytes)throw new InvalidDataException("Choose an image, 10 MB or smaller.");
|
|
await using var source=upload.OpenReadStream();using var buffer=new MemoryStream();var chunk=new byte[81920];int read;
|
|
while((read=await source.ReadAsync(chunk))>0){if(buffer.Length+read>MaxUploadBytes)throw new InvalidDataException("Reference images must be 10 MB or smaller.");await buffer.WriteAsync(chunk.AsMemory(0,read));}
|
|
var image=Normalize(buffer.ToArray(),upload.FileName);
|
|
var existing=await maps.FindImageAsync(projectId,userId,SHA256.HashData(image.ImageData!));if(existing is not null)return existing;
|
|
var owner=await maps.ImageStorageOwnerAsync(projectId,userId);var quota=await subscriptions.CanUploadFileAsync(owner,image.FileSizeBytes);
|
|
if(!quota.Allowed)throw new InvalidDataException("This project's storage allowance would be exceeded. Remove unused references or review the project owner's subscription.");
|
|
return await maps.AddImageAsync(projectId,userId,image);
|
|
}
|
|
public static bool ValidBackupImage(MapReferenceImage image)
|
|
{
|
|
if(image.ImageID==Guid.Empty||image.ImageData is not {Length:>0 and <=MaxStoredBytes}||image.ContentType!="image/webp"||string.IsNullOrWhiteSpace(image.OriginalFileName)||image.OriginalFileName.Length>200)return false;
|
|
try{var info=RasterImageValidation.Inspect(image.ImageData,MaxPixels);using var codec=SKCodec.Create(new MemoryStream(image.ImageData));if(codec is null||codec.EncodedFormat!=SKEncodedImageFormat.Webp||info.Width!=image.Width||info.Height!=image.Height||info.Width>4096||info.Height>4096)return false;using var bitmap=new SKBitmap(info.Width,info.Height,SKColorType.Bgra8888,SKAlphaType.Premul);return codec.GetPixels(bitmap.Info,bitmap.GetPixels())==SKCodecResult.Success;}
|
|
catch(Exception e) when(e is InvalidDataException or ArgumentException){return false;}
|
|
}
|
|
}
|