using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; namespace PlotLine.Controllers; [Authorize] public sealed class MapsController(MapRepository maps, IProjectRepository projects, ILocationRepository locations, IFloorPlanRepository floorPlans, IProjectAccessService access, ICurrentUserService currentUser) : Controller { private int UserID => currentUser.UserId!.Value; public async Task Index(int projectId, int? id, bool detached = false) { if (projectId == 0) return View("ChooseProject", await projects.ListActiveForUserAsync(UserID)); if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); var project = await projects.GetForUserAsync(projectId, UserID); if (project is null) return NotFound(); var document = id.HasValue ? await maps.GetAsync(projectId, id.Value, UserID) : null; if (id.HasValue && document is null) return NotFound(); if (detached) ViewData["DetachedWorkspace"] = true; return View(new MapsViewModel { Project = project, Maps = await maps.ListAsync(projectId, UserID), Document = document, ReferenceImages = await maps.ListImagesAsync(projectId, UserID), Locations = await locations.ListByProjectAsync(projectId), FloorPlans = await floorPlans.ListByProjectAsync(projectId) }); } [HttpGet] public async Task State(int projectId, int id) { if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); var document = await maps.GetAsync(projectId, id, UserID); return document is null ? NotFound() : Json(document); } [HttpPost, ValidateAntiForgeryToken] public async Task Create(StoryMap model) { if (!await access.CanAccessProjectAsync(model.ProjectID)) return NotFound(); if (!ModelState.IsValid || !MapValidation.Kinds.Contains(model.Kind)) return BadRequest("Choose a map name and kind."); try { return Json(new { id = await maps.CreateAsync(model, UserID) }); } catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); } } [HttpPost, ValidateAntiForgeryToken, RequestSizeLimit(8_000_000)] public async Task Save([FromBody] MapDocument document) { if (document is null || document.Map is null) return BadRequest(new { message = "Choose a map." }); if (!await access.CanAccessProjectAsync(document.Map.ProjectID)) return NotFound(); if (!ModelState.IsValid) return BadRequest(new { message = "Check map fields." }); var error = MapValidation.Validate(document); if (error is not null) return BadRequest(new { message = error }); try { await maps.SaveAsync(document, UserID); return Json(await maps.GetAsync(document.Map.ProjectID, document.Map.MapID, UserID)); } catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); } } [HttpPost, ValidateAntiForgeryToken] public async Task Delete(int projectId, int id, int revision) { if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); try { await maps.DeleteAsync(projectId, id, revision, UserID); return Json(new { ok = true }); } catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); } } [HttpGet] public async Task Story(int projectId, int id, int? scenarioId, [FromServices] IMapStoryService story) { if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); var projection = await story.GetAsync(projectId, id, UserID, scenarioId); return projection is null ? NotFound() : Json(projection); } [HttpPost, ValidateAntiForgeryToken] public async Task Journey(int projectId, int? scenarioId, [FromBody] MapJourneyNote note, [FromServices] IMapStoryService story, [FromServices] IMapStoryRepository repository) { if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); if (!ModelState.IsValid || note is null || note.TravelMethod?.Length > 80 || note.TypicalMinutes is < 1 or > 525600) return BadRequest(new { message = "Check journey annotations." }); var projection = await story.GetAsync(projectId, note.MapID, UserID, scenarioId); if (projection is null || !projection.Legs.Any(l => l.CharacterID == note.CharacterID && l.FromSceneID == note.FromSceneID && l.ToSceneID == note.ToSceneID)) return NotFound(); try { await repository.SaveJourneyAsync(projectId, UserID, note); return Json(new { ok = true }); } catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); } } [HttpGet] public async Task ReferenceImage(int projectId,Guid imageId) { if(!await access.CanAccessProjectAsync(projectId))return NotFound(); var image=await maps.GetImageAsync(projectId,UserID,imageId);if(image?.ImageData is null)return NotFound(); Response.Headers.CacheControl="private, no-cache";Response.Headers.XContentTypeOptions="nosniff";Response.Headers["Cross-Origin-Resource-Policy"]="same-origin"; return File(image.ImageData,image.ContentType,lastModified:null,entityTag:new Microsoft.Net.Http.Headers.EntityTagHeaderValue("\""+Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(image.ImageData))+"\"")); } [HttpPost,ValidateAntiForgeryToken,RequestSizeLimit(11_000_000)] public async Task UploadReference(int projectId,IFormFile? referenceImage,[FromServices]MapReferenceImageService images) { if(!await access.CanAccessProjectAsync(projectId))return NotFound();if(referenceImage is null)return BadRequest(new{message="Choose a reference image."}); try{return Json(await images.UploadAsync(projectId,UserID,referenceImage));} catch(InvalidDataException ex){return BadRequest(new{message=ex.Message});} catch(SqlException ex) when(ex.Number==51000){return Conflict(new{message=ex.Message});} } [HttpPost,ValidateAntiForgeryToken] public async Task DeleteUnusedReference(int projectId,Guid imageId) { if(!await access.CanAccessProjectAsync(projectId))return NotFound(); try{await maps.DeleteImageAsync(projectId,UserID,imageId);return Json(new{ok=true});} catch(SqlException ex) when(ex.Number==51000){return Conflict(new{message=ex.Message});} } }