90 lines
9.1 KiB
C#
90 lines
9.1 KiB
C#
using System.Data;
|
|
using System.Text.Json;
|
|
using Dapper;
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
using PlotLine.Data;
|
|
using PlotLine.Models;
|
|
using PlotLine.ViewModels;
|
|
namespace PlotLine.Services.Context;
|
|
|
|
public sealed class SpatialScope
|
|
{
|
|
public int ProjectID{get;set;}public int BookID{get;set;}public int ChapterID{get;set;}public int SceneID{get;set;}
|
|
public string SceneTitle{get;set;}="";public string ChapterTitle{get;set;}="";public decimal ChapterNumber{get;set;}public decimal SceneNumber{get;set;}
|
|
public int? PrimaryLocationID{get;set;}public DateTime Version{get;set;}public bool CanEdit{get;set;}
|
|
public string Label=>$"Ch {ChapterNumber:0.##}: {ChapterTitle} · Scene {SceneNumber:0.##}: {SceneTitle}";
|
|
}
|
|
public sealed class SpatialScene
|
|
{
|
|
public int Position{get;set;}public int SceneID{get;set;}public int ChapterID{get;set;}public decimal ChapterNumber{get;set;}public string ChapterTitle{get;set;}="";public decimal SceneNumber{get;set;}public string SceneTitle{get;set;}="";public int? LocationID{get;set;}public DateTime Version{get;set;}
|
|
public string Label=>$"Ch {ChapterNumber:0.##}: {ChapterTitle} · Scene {SceneNumber:0.##}: {SceneTitle}";
|
|
}
|
|
public sealed class SpatialLocation:LocationWorkspaceRecord {public int ChildCount{get;set;}}
|
|
public sealed record SpatialAssignment(int SceneID,int LocationID,string Kind,int Position);
|
|
public sealed record SpatialMapLink(int LocationID,int ResourceID,string Name,Guid FeatureID,bool IsPlaced,string GeometryClass,bool IsLocked);
|
|
public sealed record SpatialPlanLink(int ResourceID,string Name,int LocationID,int? FloorID,int? BlockID);
|
|
public sealed class SpatialCatalog {public int ID{get;set;}public string Name{get;set;}="";public string? Kind{get;set;}public int Revision{get;set;}public DateTime ModifiedDate{get;set;}public int? LocationID{get;set;}public string? Version{get;set;}}
|
|
public sealed record SpatialRelation(int ID,int FromLocationID,int ToLocationID,string FromName,string ToName,string TypeName,string? Notes);
|
|
public sealed record SpatialVersion(int ID,string Version);
|
|
public sealed record SpatialFragment(string Kind,SpatialScope Scope);
|
|
public sealed record SpatialDocument(SpatialScope Scope,SpatialScene[] Scenes,SpatialAssignment[] Assignments,SpatialLocation[] Locations,SpatialMapLink[] Maps,SpatialPlanLink[] Plans,SpatialCatalog[] MapCatalog,SpatialCatalog[] PlanCatalog,SpatialRelation[] Relationships,object[] Types);
|
|
public sealed record SpatialMutation(int BookID,int SceneID,string Kind,int? LocationID,int? ResourceID,string? GeometryID,string Expected,double? X=null,double? Y=null,bool Replace=false);
|
|
public sealed record SpatialMutationResult(int ProjectID,string Kind,int? ResourceID,string? GeometryID,string Version,string? Previous,bool Changed);
|
|
public sealed record SpatialReceipt(int User,SpatialMutation Target,string Previous,DateTime Expires);
|
|
public sealed record SpatialCreation(int BookID,int SceneID,string Name,int? ParentID,string? Expected=null,int? PlanID=null,string? BlockID=null,bool Replace=false);
|
|
public sealed record SpatialFloorCanvas(FloorPlanEditorViewModel Model,SpatialVersion[] Versions);
|
|
|
|
public sealed class ContextSpatial(ISqlConnectionFactory connections,ICurrentUserService user,IDataProtectionProvider protection,ContextWorkspaceNotifications notifications)
|
|
{
|
|
private int Author=>user.UserId??throw new UnauthorizedAccessException();
|
|
private IDataProtector Protector=>protection.CreateProtector("Context.Spatial.Undo.v1");
|
|
public async Task<SpatialScope> Scope(int book,int scene)
|
|
{
|
|
using var db=connections.CreateConnection();return await db.QuerySingleAsync<SpatialScope>("dbo.SpatialContext_Scope",new{UserID=Author,BookID=book,SceneID=scene},commandType:CommandType.StoredProcedure);
|
|
}
|
|
public async Task<SpatialDocument> Read(int book,int scene,int? inspect)
|
|
{
|
|
using var db=connections.CreateConnection();using var data=await db.QueryMultipleAsync("dbo.SpatialContext_Read",new{UserID=Author,BookID=book,SceneID=scene,InspectID=inspect},commandType:CommandType.StoredProcedure);
|
|
var scope=await data.ReadSingleAsync<SpatialScope>();var scenes=(await data.ReadAsync<SpatialScene>()).ToArray();var assignments=(await data.ReadAsync<SpatialAssignment>()).ToArray();var locations=(await data.ReadAsync<SpatialLocation>()).ToArray();var maps=(await data.ReadAsync<SpatialMapLink>()).ToArray();var plans=(await data.ReadAsync<SpatialPlanLink>()).ToArray();var mapCatalog=(await data.ReadAsync<SpatialCatalog>()).ToArray();var planCatalog=(await data.ReadAsync<SpatialCatalog>()).ToArray();var relationships=(await data.ReadAsync<SpatialRelation>()).ToArray();var types=(await data.ReadAsync<LocationTypeTaxonomyEntry>()).Select(LocationWorkspaceIcons.Presentation).ToArray();
|
|
return new(scope,scenes,assignments,locations,maps,plans,mapCatalog,planCatalog,relationships,types);
|
|
}
|
|
private async Task<SpatialMutationResult> Apply(IDbConnection db,SpatialMutation input,IDbTransaction? transaction=null,string? previous=null)
|
|
{
|
|
if(input.Kind is not("scene" or "map" or "room" or "plan")||input.Expected?.Length is not(>0 and <=80)||input.GeometryID?.Length>50||input.X.HasValue&&!double.IsFinite(input.X.Value)||input.Y.HasValue&&!double.IsFinite(input.Y.Value))throw new ArgumentException("Choose a valid spatial operation.");
|
|
return await db.QuerySingleAsync<SpatialMutationResult>("dbo.SpatialContext_Mutate",new{UserID=Author,input.BookID,input.SceneID,input.Kind,input.LocationID,input.ResourceID,input.GeometryID,input.Expected,input.X,input.Y,input.Replace,Restore=previous!=null,Previous=previous},transaction,commandType:CommandType.StoredProcedure);
|
|
}
|
|
public async Task<object> Mutate(SpatialMutation input)
|
|
{
|
|
using var db=connections.CreateConnection();var result=await Apply(db,input);return await Accepted(input,result);
|
|
}
|
|
private async Task<object> Accepted(SpatialMutation input,SpatialMutationResult result)
|
|
{
|
|
string? undo=null;if(result.Changed&&result.Previous!=null)undo=Protector.Protect(JsonSerializer.Serialize(new SpatialReceipt(Author,input with{Expected=result.Version,GeometryID=result.GeometryID},result.Previous,DateTime.UtcNow.AddMinutes(10))));
|
|
if(result.Changed){await notifications.Invalidate(Author,projectId:result.ProjectID,bookId:input.Kind=="scene"?input.BookID:(int?)null,kind:input.Kind is "map"?"maps":input.Kind is "room" or "plan"?"floorplans":"locations");}
|
|
return new{saved=true,result,undoToken=undo};
|
|
}
|
|
public async Task<object> Undo(string token)
|
|
{
|
|
SpatialReceipt receipt;try{receipt=JsonSerializer.Deserialize<SpatialReceipt>(Protector.Unprotect(token))??throw new Exception();}catch{throw new ArgumentException("Undo is unavailable.");}
|
|
if(receipt.User!=Author||receipt.Expires<DateTime.UtcNow)throw new ArgumentException("Undo expired. Existing work is unchanged.");
|
|
using var db=connections.CreateConnection();var result=await Apply(db,receipt.Target,previous:receipt.Previous);if(result.Changed){await notifications.Invalidate(Author,projectId:result.ProjectID,bookId:receipt.Target.Kind=="scene"?receipt.Target.BookID:(int?)null,kind:receipt.Target.Kind=="map"?"maps":receipt.Target.Kind=="scene"?"locations":"floorplans");}return new{saved=true,result};
|
|
}
|
|
public async Task<object> Create(SpatialCreation input)
|
|
{
|
|
var scope=await Scope(input.BookID,input.SceneID);if(!scope.CanEdit)throw new UnauthorizedAccessException();if(string.IsNullOrWhiteSpace(input.Name)||input.Name.Length>200)throw new ArgumentException("Enter a location name of up to 200 characters.");
|
|
using var db=connections.CreateConnection();db.Open();using var tx=db.BeginTransaction();
|
|
var id=await db.QuerySingleAsync<int>("dbo.Location_WorkspaceCreate",new{scope.ProjectID,UserID=Author,input.Name,ParentID=input.ParentID},tx,commandType:CommandType.StoredProcedure);
|
|
SpatialMutationResult? changed=null;SpatialMutation? target=null;
|
|
if(input.Expected!=null){target=new(input.BookID,input.SceneID,input.BlockID!=null?"room":"scene",id,input.PlanID,input.BlockID,input.Expected,Replace:input.Replace);changed=await Apply(db,target,tx);}
|
|
tx.Commit();await notifications.Invalidate(Author,projectId:scope.ProjectID,kind:"locations");
|
|
return new{id,assignment=changed==null?null:await Accepted(target!,changed)};
|
|
}
|
|
public async Task<SpatialFloorCanvas> Floor(int book,int scene,int plan)
|
|
{
|
|
var scope=await Scope(book,scene);using var db=connections.CreateConnection();db.Open();using var tx=db.BeginTransaction(IsolationLevel.RepeatableRead);using var rows=await db.QueryMultipleAsync("dbo.FloorPlan_GetEditor",new{FloorPlanID=plan},tx,commandType:CommandType.StoredProcedure);
|
|
var header=await rows.ReadSingleOrDefaultAsync<FloorPlanEditViewModel>();if(header==null||header.ProjectID!=scope.ProjectID)throw new UnauthorizedAccessException();
|
|
var model=new FloorPlanEditorViewModel{Project=new(){ProjectID=scope.ProjectID},FloorPlan=header,Floors=(await rows.ReadAsync<FloorPlanFloorEditViewModel>()).ToList(),Blocks=(await rows.ReadAsync<FloorPlanBlockEditViewModel>()).ToList(),Transitions=(await rows.ReadAsync<FloorPlanTransitionEditViewModel>()).ToList()};rows.Dispose();
|
|
var versions=(await db.QueryAsync<SpatialVersion>("dbo.SpatialContext_RoomVersions",new{UserID=Author,BookID=book,SceneID=scene,PlanID=plan},tx,commandType:CommandType.StoredProcedure)).ToArray();tx.Commit();return new(model,versions);
|
|
}
|
|
}
|