| | | 1 | | using Chronicis.Api.Data; |
| | | 2 | | using Chronicis.Api.Infrastructure; |
| | | 3 | | using Chronicis.Api.Services; |
| | | 4 | | using Chronicis.Shared.DTOs; |
| | | 5 | | using Chronicis.Shared.Extensions; |
| | | 6 | | using Microsoft.AspNetCore.Authorization; |
| | | 7 | | using Microsoft.AspNetCore.Mvc; |
| | | 8 | | using Microsoft.EntityFrameworkCore; |
| | | 9 | | |
| | | 10 | | namespace Chronicis.Api.Controllers; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// API endpoints for World management. |
| | | 14 | | /// </summary> |
| | | 15 | | [ApiController] |
| | | 16 | | [Route("worlds")] |
| | | 17 | | [Authorize] |
| | | 18 | | public class WorldsController : ControllerBase |
| | | 19 | | { |
| | | 20 | | private readonly IWorldService _worldService; |
| | | 21 | | private readonly IWorldMembershipService _membershipService; |
| | | 22 | | private readonly IWorldInvitationService _invitationService; |
| | | 23 | | private readonly IWorldPublicSharingService _publicSharingService; |
| | | 24 | | private readonly IExportService _exportService; |
| | | 25 | | private readonly IArticleHierarchyService _hierarchyService; |
| | | 26 | | private readonly ChronicisDbContext _context; |
| | | 27 | | private readonly ICurrentUserService _currentUserService; |
| | | 28 | | private readonly ILogger<WorldsController> _logger; |
| | | 29 | | |
| | 0 | 30 | | public WorldsController( |
| | 0 | 31 | | IWorldService worldService, |
| | 0 | 32 | | IWorldMembershipService membershipService, |
| | 0 | 33 | | IWorldInvitationService invitationService, |
| | 0 | 34 | | IWorldPublicSharingService publicSharingService, |
| | 0 | 35 | | IExportService exportService, |
| | 0 | 36 | | IArticleHierarchyService hierarchyService, |
| | 0 | 37 | | ChronicisDbContext context, |
| | 0 | 38 | | ICurrentUserService currentUserService, |
| | 0 | 39 | | ILogger<WorldsController> logger) |
| | | 40 | | { |
| | 0 | 41 | | _worldService = worldService; |
| | 0 | 42 | | _membershipService = membershipService; |
| | 0 | 43 | | _invitationService = invitationService; |
| | 0 | 44 | | _publicSharingService = publicSharingService; |
| | 0 | 45 | | _exportService = exportService; |
| | 0 | 46 | | _hierarchyService = hierarchyService; |
| | 0 | 47 | | _context = context; |
| | 0 | 48 | | _currentUserService = currentUserService; |
| | 0 | 49 | | _logger = logger; |
| | 0 | 50 | | } |
| | | 51 | | |
| | | 52 | | /// <summary> |
| | | 53 | | /// GET /api/worlds - Get all worlds the user has access to. |
| | | 54 | | /// </summary> |
| | | 55 | | [HttpGet] |
| | | 56 | | public async Task<ActionResult<IEnumerable<WorldDto>>> GetWorlds() |
| | | 57 | | { |
| | 0 | 58 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | 0 | 59 | | _logger.LogDebug("Getting worlds for user {UserId}", user.Id); |
| | | 60 | | |
| | 0 | 61 | | var worlds = await _worldService.GetUserWorldsAsync(user.Id); |
| | 0 | 62 | | return Ok(worlds); |
| | 0 | 63 | | } |
| | | 64 | | |
| | | 65 | | /// <summary> |
| | | 66 | | /// GET /api/worlds/{id} - Get a specific world with its campaigns. |
| | | 67 | | /// </summary> |
| | | 68 | | [HttpGet("{id:guid}")] |
| | | 69 | | public async Task<ActionResult<WorldDto>> GetWorld(Guid id) |
| | | 70 | | { |
| | 0 | 71 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | 0 | 72 | | _logger.LogDebug("Getting world {WorldId} for user {UserId}", id, user.Id); |
| | | 73 | | |
| | 0 | 74 | | var world = await _worldService.GetWorldAsync(id, user.Id); |
| | | 75 | | |
| | 0 | 76 | | if (world == null) |
| | | 77 | | { |
| | 0 | 78 | | return NotFound(new { error = "World not found or access denied" }); |
| | | 79 | | } |
| | | 80 | | |
| | 0 | 81 | | return Ok(world); |
| | 0 | 82 | | } |
| | | 83 | | |
| | | 84 | | /// <summary> |
| | | 85 | | /// POST /api/worlds - Create a new world. |
| | | 86 | | /// </summary> |
| | | 87 | | [HttpPost] |
| | | 88 | | public async Task<ActionResult<WorldDto>> CreateWorld([FromBody] WorldCreateDto dto) |
| | | 89 | | { |
| | 0 | 90 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 91 | | |
| | 0 | 92 | | if (dto == null || string.IsNullOrWhiteSpace(dto.Name)) |
| | | 93 | | { |
| | 0 | 94 | | return BadRequest(new { error = "Name is required" }); |
| | | 95 | | } |
| | | 96 | | |
| | 0 | 97 | | _logger.LogDebugSanitized("Creating world '{Name}' for user {UserId}", dto.Name, user.Id); |
| | | 98 | | |
| | 0 | 99 | | var world = await _worldService.CreateWorldAsync(dto, user.Id); |
| | | 100 | | |
| | 0 | 101 | | return CreatedAtAction(nameof(GetWorld), new { id = world.Id }, world); |
| | 0 | 102 | | } |
| | | 103 | | |
| | | 104 | | /// <summary> |
| | | 105 | | /// PUT /api/worlds/{id} - Update a world. |
| | | 106 | | /// </summary> |
| | | 107 | | [HttpPut("{id:guid}")] |
| | | 108 | | public async Task<ActionResult<WorldDto>> UpdateWorld(Guid id, [FromBody] WorldUpdateDto dto) |
| | | 109 | | { |
| | 0 | 110 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 111 | | |
| | 0 | 112 | | if (dto == null || string.IsNullOrWhiteSpace(dto.Name)) |
| | | 113 | | { |
| | 0 | 114 | | return BadRequest(new { error = "Name is required" }); |
| | | 115 | | } |
| | | 116 | | |
| | 0 | 117 | | _logger.LogDebug("Updating world {WorldId} for user {UserId}", id, user.Id); |
| | | 118 | | |
| | 0 | 119 | | var world = await _worldService.UpdateWorldAsync(id, dto, user.Id); |
| | | 120 | | |
| | 0 | 121 | | if (world == null) |
| | | 122 | | { |
| | 0 | 123 | | return NotFound(new { error = "World not found or access denied" }); |
| | | 124 | | } |
| | | 125 | | |
| | 0 | 126 | | return Ok(world); |
| | 0 | 127 | | } |
| | | 128 | | |
| | | 129 | | /// <summary> |
| | | 130 | | /// POST /api/worlds/{id}/check-public-slug - Check if a public slug is available. |
| | | 131 | | /// </summary> |
| | | 132 | | [HttpPost("{id:guid}/check-public-slug")] |
| | | 133 | | public async Task<ActionResult<PublicSlugCheckResultDto>> CheckPublicSlug(Guid id, [FromBody] PublicSlugCheckDto dto |
| | | 134 | | { |
| | 0 | 135 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 136 | | |
| | | 137 | | // Verify user owns this world |
| | 0 | 138 | | var world = await _worldService.GetWorldAsync(id, user.Id); |
| | 0 | 139 | | if (world == null || world.OwnerId != user.Id) |
| | | 140 | | { |
| | 0 | 141 | | return StatusCode(403, new { error = "Only the world owner can check public slugs" }); |
| | | 142 | | } |
| | | 143 | | |
| | 0 | 144 | | if (dto == null || string.IsNullOrWhiteSpace(dto.Slug)) |
| | | 145 | | { |
| | 0 | 146 | | return BadRequest(new { error = "Slug is required" }); |
| | | 147 | | } |
| | | 148 | | |
| | 0 | 149 | | _logger.LogDebugSanitized("Checking public slug '{Slug}' for world {WorldId}", dto.Slug, id); |
| | | 150 | | |
| | 0 | 151 | | var result = await _publicSharingService.CheckPublicSlugAsync(dto.Slug, id); |
| | 0 | 152 | | return Ok(result); |
| | 0 | 153 | | } |
| | | 154 | | |
| | | 155 | | // ===== Member Management ===== |
| | | 156 | | |
| | | 157 | | /// <summary> |
| | | 158 | | /// GET /api/worlds/{id}/members - Get all members of a world. |
| | | 159 | | /// </summary> |
| | | 160 | | [HttpGet("{id:guid}/members")] |
| | | 161 | | public async Task<ActionResult<IEnumerable<WorldMemberDto>>> GetWorldMembers(Guid id) |
| | | 162 | | { |
| | 0 | 163 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | 0 | 164 | | _logger.LogDebug("Getting members for world {WorldId}", id); |
| | | 165 | | |
| | 0 | 166 | | var members = await _membershipService.GetMembersAsync(id, user.Id); |
| | 0 | 167 | | return Ok(members); |
| | 0 | 168 | | } |
| | | 169 | | |
| | | 170 | | /// <summary> |
| | | 171 | | /// PUT /api/worlds/{worldId}/members/{memberId} - Update a member's role. |
| | | 172 | | /// </summary> |
| | | 173 | | [HttpPut("{worldId:guid}/members/{memberId:guid}")] |
| | | 174 | | public async Task<ActionResult<WorldMemberDto>> UpdateWorldMember( |
| | | 175 | | Guid worldId, |
| | | 176 | | Guid memberId, |
| | | 177 | | [FromBody] WorldMemberUpdateDto dto) |
| | | 178 | | { |
| | 0 | 179 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 180 | | |
| | 0 | 181 | | if (dto == null) |
| | | 182 | | { |
| | 0 | 183 | | return BadRequest(new { error = "Invalid request body" }); |
| | | 184 | | } |
| | | 185 | | |
| | 0 | 186 | | _logger.LogDebug("Updating member {MemberId} in world {WorldId}", memberId, worldId); |
| | | 187 | | |
| | 0 | 188 | | var member = await _membershipService.UpdateMemberRoleAsync(worldId, memberId, dto, user.Id); |
| | | 189 | | |
| | 0 | 190 | | if (member == null) |
| | | 191 | | { |
| | 0 | 192 | | return NotFound(new { error = "Member not found, access denied, or cannot demote last GM" }); |
| | | 193 | | } |
| | | 194 | | |
| | 0 | 195 | | return Ok(member); |
| | 0 | 196 | | } |
| | | 197 | | |
| | | 198 | | /// <summary> |
| | | 199 | | /// DELETE /api/worlds/{worldId}/members/{memberId} - Remove a member from a world. |
| | | 200 | | /// </summary> |
| | | 201 | | [HttpDelete("{worldId:guid}/members/{memberId:guid}")] |
| | | 202 | | public async Task<IActionResult> RemoveWorldMember(Guid worldId, Guid memberId) |
| | | 203 | | { |
| | 0 | 204 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | 0 | 205 | | _logger.LogDebug("Removing member {MemberId} from world {WorldId}", memberId, worldId); |
| | | 206 | | |
| | 0 | 207 | | var success = await _membershipService.RemoveMemberAsync(worldId, memberId, user.Id); |
| | | 208 | | |
| | 0 | 209 | | if (!success) |
| | | 210 | | { |
| | 0 | 211 | | return NotFound(new { error = "Member not found, access denied, or cannot remove last GM" }); |
| | | 212 | | } |
| | | 213 | | |
| | 0 | 214 | | return NoContent(); |
| | 0 | 215 | | } |
| | | 216 | | |
| | | 217 | | // ===== Invitation Management ===== |
| | | 218 | | |
| | | 219 | | /// <summary> |
| | | 220 | | /// GET /api/worlds/{id}/invitations - Get all invitations for a world. |
| | | 221 | | /// </summary> |
| | | 222 | | [HttpGet("{id:guid}/invitations")] |
| | | 223 | | public async Task<ActionResult<IEnumerable<WorldInvitationDto>>> GetWorldInvitations(Guid id) |
| | | 224 | | { |
| | 0 | 225 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | 0 | 226 | | _logger.LogDebug("Getting invitations for world {WorldId}", id); |
| | | 227 | | |
| | 0 | 228 | | var invitations = await _invitationService.GetInvitationsAsync(id, user.Id); |
| | 0 | 229 | | return Ok(invitations); |
| | 0 | 230 | | } |
| | | 231 | | |
| | | 232 | | /// <summary> |
| | | 233 | | /// POST /api/worlds/{id}/invitations - Create a new invitation. |
| | | 234 | | /// </summary> |
| | | 235 | | [HttpPost("{id:guid}/invitations")] |
| | | 236 | | public async Task<ActionResult<WorldInvitationDto>> CreateWorldInvitation( |
| | | 237 | | Guid id, |
| | | 238 | | [FromBody] WorldInvitationCreateDto? dto) |
| | | 239 | | { |
| | 0 | 240 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 241 | | |
| | 0 | 242 | | dto ??= new WorldInvitationCreateDto(); // Use defaults if body is empty |
| | | 243 | | |
| | 0 | 244 | | _logger.LogDebug("Creating invitation for world {WorldId}", id); |
| | | 245 | | |
| | 0 | 246 | | var invitation = await _invitationService.CreateInvitationAsync(id, dto, user.Id); |
| | | 247 | | |
| | 0 | 248 | | if (invitation == null) |
| | | 249 | | { |
| | 0 | 250 | | return StatusCode(403, new { error = "Access denied or failed to create invitation" }); |
| | | 251 | | } |
| | | 252 | | |
| | 0 | 253 | | return CreatedAtAction(nameof(GetWorldInvitations), new { id = id }, invitation); |
| | 0 | 254 | | } |
| | | 255 | | |
| | | 256 | | /// <summary> |
| | | 257 | | /// DELETE /api/worlds/{worldId}/invitations/{invitationId} - Revoke an invitation. |
| | | 258 | | /// </summary> |
| | | 259 | | [HttpDelete("{worldId:guid}/invitations/{invitationId:guid}")] |
| | | 260 | | public async Task<IActionResult> RevokeWorldInvitation(Guid worldId, Guid invitationId) |
| | | 261 | | { |
| | 0 | 262 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | 0 | 263 | | _logger.LogDebug("Revoking invitation {InvitationId} for world {WorldId}", invitationId, worldId); |
| | | 264 | | |
| | 0 | 265 | | var success = await _invitationService.RevokeInvitationAsync(worldId, invitationId, user.Id); |
| | | 266 | | |
| | 0 | 267 | | if (!success) |
| | | 268 | | { |
| | 0 | 269 | | return NotFound(new { error = "Invitation not found or access denied" }); |
| | | 270 | | } |
| | | 271 | | |
| | 0 | 272 | | return NoContent(); |
| | 0 | 273 | | } |
| | | 274 | | |
| | | 275 | | /// <summary> |
| | | 276 | | /// POST /api/worlds/join - Join a world using an invitation code. |
| | | 277 | | /// </summary> |
| | | 278 | | [HttpPost("join")] |
| | | 279 | | public async Task<ActionResult<WorldJoinResultDto>> JoinWorld([FromBody] WorldJoinDto dto) |
| | | 280 | | { |
| | 0 | 281 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 282 | | |
| | 0 | 283 | | if (dto == null || string.IsNullOrWhiteSpace(dto.Code)) |
| | | 284 | | { |
| | 0 | 285 | | return BadRequest(new { error = "Invitation code is required" }); |
| | | 286 | | } |
| | | 287 | | |
| | 0 | 288 | | _logger.LogDebugSanitized("User {UserId} attempting to join world with code {Code}", user.Id, dto.Code); |
| | | 289 | | |
| | 0 | 290 | | var result = await _invitationService.JoinWorldAsync(dto.Code, user.Id); |
| | | 291 | | |
| | 0 | 292 | | if (result.Success) |
| | | 293 | | { |
| | 0 | 294 | | return Ok(result); |
| | | 295 | | } |
| | | 296 | | |
| | 0 | 297 | | return BadRequest(result); |
| | 0 | 298 | | } |
| | | 299 | | |
| | | 300 | | // ===== Export ===== |
| | | 301 | | |
| | | 302 | | /// <summary> |
| | | 303 | | /// GET /api/worlds/{id}/export - Export world to a markdown zip archive. |
| | | 304 | | /// </summary> |
| | | 305 | | [HttpGet("{id:guid}/export")] |
| | | 306 | | public async Task<IActionResult> ExportWorld(Guid id) |
| | | 307 | | { |
| | 0 | 308 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | 0 | 309 | | _logger.LogDebug("Exporting world {WorldId} for user {UserId}", id, user.Id); |
| | | 310 | | |
| | 0 | 311 | | var zipData = await _exportService.ExportWorldToMarkdownAsync(id, user.Id); |
| | | 312 | | |
| | 0 | 313 | | if (zipData == null) |
| | | 314 | | { |
| | 0 | 315 | | return NotFound(new { error = "World not found or access denied" }); |
| | | 316 | | } |
| | | 317 | | |
| | | 318 | | // Get world name for filename |
| | 0 | 319 | | var world = await _worldService.GetWorldAsync(id, user.Id); |
| | 0 | 320 | | var worldName = world?.Name ?? "world"; |
| | 0 | 321 | | var safeWorldName = string.Join("_", worldName.Split(Path.GetInvalidFileNameChars())); |
| | 0 | 322 | | if (safeWorldName.Length > 50) |
| | 0 | 323 | | safeWorldName = safeWorldName[..50]; |
| | 0 | 324 | | var fileName = $"{safeWorldName}_export_{DateTime.UtcNow:yyyyMMdd_HHmmss}.zip"; |
| | | 325 | | |
| | 0 | 326 | | return File(zipData, "application/zip", fileName); |
| | 0 | 327 | | } |
| | | 328 | | |
| | | 329 | | // ===== Link Suggestions ===== |
| | | 330 | | |
| | | 331 | | /// <summary> |
| | | 332 | | /// GET /worlds/{id}/link-suggestions - Get link suggestions for autocomplete based on a search query. |
| | | 333 | | /// </summary> |
| | | 334 | | [HttpGet("{id:guid}/link-suggestions")] |
| | | 335 | | public async Task<ActionResult<LinkSuggestionsResponseDto>> GetLinkSuggestions( |
| | | 336 | | Guid id, |
| | | 337 | | [FromQuery] string query) |
| | | 338 | | { |
| | 0 | 339 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 340 | | |
| | 0 | 341 | | if (string.IsNullOrWhiteSpace(query) || query.Length < 2) |
| | | 342 | | { |
| | 0 | 343 | | return Ok(new LinkSuggestionsResponseDto()); |
| | | 344 | | } |
| | | 345 | | |
| | 0 | 346 | | _logger.LogDebugSanitized("Getting link suggestions for query '{Query}' in world {WorldId}", query, id); |
| | | 347 | | |
| | | 348 | | // Verify user has access to the world |
| | 0 | 349 | | var hasAccess = await _context.WorldMembers |
| | 0 | 350 | | .AnyAsync(wm => wm.WorldId == id && wm.UserId == user.Id); |
| | | 351 | | |
| | 0 | 352 | | if (!hasAccess) |
| | | 353 | | { |
| | 0 | 354 | | return Forbid(); |
| | | 355 | | } |
| | | 356 | | |
| | 0 | 357 | | var normalizedQuery = query.ToLowerInvariant(); |
| | | 358 | | |
| | | 359 | | // Search articles by title match |
| | 0 | 360 | | var titleMatches = await _context.Articles |
| | 0 | 361 | | .Where(a => a.WorldId == id) |
| | 0 | 362 | | .Where(a => a.Title != null && a.Title.ToLower().Contains(normalizedQuery)) |
| | 0 | 363 | | .OrderBy(a => a.Title) |
| | 0 | 364 | | .Take(20) |
| | 0 | 365 | | .Select(a => new LinkSuggestionDto |
| | 0 | 366 | | { |
| | 0 | 367 | | ArticleId = a.Id, |
| | 0 | 368 | | Title = a.Title ?? "Untitled", |
| | 0 | 369 | | Slug = a.Slug, |
| | 0 | 370 | | ArticleType = a.Type, |
| | 0 | 371 | | DisplayPath = "", |
| | 0 | 372 | | MatchedAlias = null // Title match, no alias |
| | 0 | 373 | | }) |
| | 0 | 374 | | .ToListAsync(); |
| | | 375 | | |
| | | 376 | | // Search articles by alias match (excluding those already found by title) |
| | 0 | 377 | | var titleMatchIds = titleMatches.Select(t => t.ArticleId).ToHashSet(); |
| | | 378 | | |
| | 0 | 379 | | var aliasMatches = await _context.ArticleAliases |
| | 0 | 380 | | .Include(aa => aa.Article) |
| | 0 | 381 | | .Where(aa => aa.Article.WorldId == id) |
| | 0 | 382 | | .Where(aa => aa.AliasText.ToLower().Contains(normalizedQuery)) |
| | 0 | 383 | | .Where(aa => !titleMatchIds.Contains(aa.ArticleId)) |
| | 0 | 384 | | .OrderBy(aa => aa.AliasText) |
| | 0 | 385 | | .Take(20) |
| | 0 | 386 | | .Select(aa => new LinkSuggestionDto |
| | 0 | 387 | | { |
| | 0 | 388 | | ArticleId = aa.ArticleId, |
| | 0 | 389 | | Title = aa.Article.Title ?? "Untitled", |
| | 0 | 390 | | Slug = aa.Article.Slug, |
| | 0 | 391 | | ArticleType = aa.Article.Type, |
| | 0 | 392 | | DisplayPath = "", |
| | 0 | 393 | | MatchedAlias = aa.AliasText // This matched via alias |
| | 0 | 394 | | }) |
| | 0 | 395 | | .ToListAsync(); |
| | | 396 | | |
| | | 397 | | // Combine results: title matches first, then alias matches |
| | 0 | 398 | | var suggestions = titleMatches |
| | 0 | 399 | | .Concat(aliasMatches) |
| | 0 | 400 | | .Take(20) |
| | 0 | 401 | | .ToList(); |
| | | 402 | | |
| | | 403 | | // Build display paths using centralised hierarchy service |
| | 0 | 404 | | foreach (var suggestion in suggestions) |
| | | 405 | | { |
| | 0 | 406 | | suggestion.DisplayPath = await _hierarchyService.BuildDisplayPathAsync(suggestion.ArticleId); |
| | | 407 | | } |
| | | 408 | | |
| | 0 | 409 | | return Ok(new LinkSuggestionsResponseDto { Suggestions = suggestions }); |
| | 0 | 410 | | } |
| | | 411 | | |
| | | 412 | | } |