| | | 1 | | using Chronicis.Api.Data; |
| | | 2 | | using Chronicis.Api.Infrastructure; |
| | | 3 | | using Chronicis.Api.Services; |
| | | 4 | | using Chronicis.Api.Services.Articles; |
| | | 5 | | using Chronicis.Shared.DTOs; |
| | | 6 | | using Chronicis.Shared.Extensions; |
| | | 7 | | using Chronicis.Shared.Models; |
| | | 8 | | using Chronicis.Shared.Utilities; |
| | | 9 | | using Microsoft.AspNetCore.Authorization; |
| | | 10 | | using Microsoft.AspNetCore.Mvc; |
| | | 11 | | using Microsoft.EntityFrameworkCore; |
| | | 12 | | |
| | | 13 | | namespace Chronicis.Api.Controllers; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// API endpoints for Article operations. |
| | | 17 | | /// </summary> |
| | | 18 | | [ApiController] |
| | | 19 | | [Route("articles")] |
| | | 20 | | [Authorize] |
| | | 21 | | public class ArticlesController : ControllerBase |
| | | 22 | | { |
| | | 23 | | private readonly IArticleService _articleService; |
| | | 24 | | private readonly IArticleValidationService _validationService; |
| | | 25 | | private readonly ILinkSyncService _linkSyncService; |
| | | 26 | | private readonly IAutoLinkService _autoLinkService; |
| | | 27 | | private readonly IArticleExternalLinkService _externalLinkService; |
| | | 28 | | private readonly IArticleHierarchyService _hierarchyService; |
| | | 29 | | private readonly ChronicisDbContext _context; |
| | | 30 | | private readonly ICurrentUserService _currentUserService; |
| | | 31 | | private readonly IWorldDocumentService _worldDocumentService; |
| | | 32 | | private readonly ILogger<ArticlesController> _logger; |
| | | 33 | | |
| | 0 | 34 | | public ArticlesController( |
| | 0 | 35 | | IArticleService articleService, |
| | 0 | 36 | | IArticleValidationService validationService, |
| | 0 | 37 | | ILinkSyncService linkSyncService, |
| | 0 | 38 | | IAutoLinkService autoLinkService, |
| | 0 | 39 | | IArticleExternalLinkService externalLinkService, |
| | 0 | 40 | | IArticleHierarchyService hierarchyService, |
| | 0 | 41 | | ChronicisDbContext context, |
| | 0 | 42 | | ICurrentUserService currentUserService, |
| | 0 | 43 | | IWorldDocumentService worldDocumentService, |
| | 0 | 44 | | ILogger<ArticlesController> logger) |
| | | 45 | | { |
| | 0 | 46 | | _articleService = articleService; |
| | 0 | 47 | | _validationService = validationService; |
| | 0 | 48 | | _linkSyncService = linkSyncService; |
| | 0 | 49 | | _autoLinkService = autoLinkService; |
| | 0 | 50 | | _externalLinkService = externalLinkService; |
| | 0 | 51 | | _hierarchyService = hierarchyService; |
| | 0 | 52 | | _context = context; |
| | 0 | 53 | | _currentUserService = currentUserService; |
| | 0 | 54 | | _worldDocumentService = worldDocumentService; |
| | 0 | 55 | | _logger = logger; |
| | 0 | 56 | | } |
| | | 57 | | |
| | | 58 | | /// <summary> |
| | | 59 | | /// GET /api/articles - Returns all root-level articles (those without a parent). |
| | | 60 | | /// </summary> |
| | | 61 | | [HttpGet] |
| | | 62 | | public async Task<ActionResult<IEnumerable<ArticleTreeDto>>> GetRootArticles([FromQuery] Guid? worldId) |
| | | 63 | | { |
| | 0 | 64 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 65 | | |
| | | 66 | | try |
| | | 67 | | { |
| | 0 | 68 | | var articles = await _articleService.GetRootArticlesAsync(user.Id, worldId); |
| | 0 | 69 | | return Ok(articles); |
| | | 70 | | } |
| | 0 | 71 | | catch (Exception ex) |
| | | 72 | | { |
| | 0 | 73 | | _logger.LogError(ex, "Error fetching root articles"); |
| | 0 | 74 | | return StatusCode(500, "Internal server error"); |
| | | 75 | | } |
| | 0 | 76 | | } |
| | | 77 | | |
| | | 78 | | /// <summary> |
| | | 79 | | /// GET /api/articles/all - Returns all articles for the current user in a flat list. |
| | | 80 | | /// </summary> |
| | | 81 | | [HttpGet("all")] |
| | | 82 | | public async Task<ActionResult<IEnumerable<ArticleTreeDto>>> GetAllArticles([FromQuery] Guid? worldId) |
| | | 83 | | { |
| | 0 | 84 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 85 | | |
| | | 86 | | try |
| | | 87 | | { |
| | 0 | 88 | | var articles = await _articleService.GetAllArticlesAsync(user.Id, worldId); |
| | 0 | 89 | | return Ok(articles); |
| | | 90 | | } |
| | 0 | 91 | | catch (Exception ex) |
| | | 92 | | { |
| | 0 | 93 | | _logger.LogError(ex, "Error fetching all articles"); |
| | 0 | 94 | | return StatusCode(500, "Internal server error"); |
| | | 95 | | } |
| | 0 | 96 | | } |
| | | 97 | | |
| | | 98 | | /// <summary> |
| | | 99 | | /// GET /api/articles/{id} - Returns detailed information for a specific article. |
| | | 100 | | /// </summary> |
| | | 101 | | [HttpGet("{id:guid}")] |
| | | 102 | | public async Task<ActionResult<ArticleDto>> GetArticleDetail(Guid id) |
| | | 103 | | { |
| | 0 | 104 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 105 | | |
| | | 106 | | try |
| | | 107 | | { |
| | 0 | 108 | | var article = await _articleService.GetArticleDetailAsync(id, user.Id); |
| | | 109 | | |
| | 0 | 110 | | if (article == null) |
| | | 111 | | { |
| | 0 | 112 | | return NotFound(new { message = $"Article {id} not found" }); |
| | | 113 | | } |
| | | 114 | | |
| | 0 | 115 | | return Ok(article); |
| | | 116 | | } |
| | 0 | 117 | | catch (Exception ex) |
| | | 118 | | { |
| | 0 | 119 | | _logger.LogError(ex, "Error fetching article {ArticleId}", id); |
| | 0 | 120 | | return StatusCode(500, "Internal server error"); |
| | | 121 | | } |
| | 0 | 122 | | } |
| | | 123 | | |
| | | 124 | | /// <summary> |
| | | 125 | | /// GET /api/articles/{id}/children - Returns all child articles of the specified parent. |
| | | 126 | | /// </summary> |
| | | 127 | | [HttpGet("{id:guid}/children")] |
| | | 128 | | public async Task<ActionResult<IEnumerable<ArticleTreeDto>>> GetArticleChildren(Guid id) |
| | | 129 | | { |
| | 0 | 130 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 131 | | |
| | | 132 | | try |
| | | 133 | | { |
| | 0 | 134 | | var children = await _articleService.GetChildrenAsync(id, user.Id); |
| | 0 | 135 | | return Ok(children); |
| | | 136 | | } |
| | 0 | 137 | | catch (Exception ex) |
| | | 138 | | { |
| | 0 | 139 | | _logger.LogError(ex, "Error fetching children for article {ParentId}", id); |
| | 0 | 140 | | return StatusCode(500, "Internal server error"); |
| | | 141 | | } |
| | 0 | 142 | | } |
| | | 143 | | |
| | | 144 | | /// <summary> |
| | | 145 | | /// GET /api/articles/by-path/{*path} - Gets an article by its URL path. |
| | | 146 | | /// </summary> |
| | | 147 | | [HttpGet("by-path/{*path}")] |
| | | 148 | | public async Task<ActionResult<ArticleDto>> GetArticleByPath(string path) |
| | | 149 | | { |
| | 0 | 150 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 151 | | |
| | | 152 | | try |
| | | 153 | | { |
| | 0 | 154 | | var article = await _articleService.GetArticleByPathAsync(path, user.Id); |
| | | 155 | | |
| | 0 | 156 | | if (article == null) |
| | | 157 | | { |
| | 0 | 158 | | return NotFound(new { message = "Article not found" }); |
| | | 159 | | } |
| | | 160 | | |
| | 0 | 161 | | return Ok(article); |
| | | 162 | | } |
| | 0 | 163 | | catch (Exception ex) |
| | | 164 | | { |
| | 0 | 165 | | _logger.LogErrorSanitized(ex, "Error fetching article by path: {Path}", path); |
| | 0 | 166 | | return StatusCode(500, "Internal server error"); |
| | | 167 | | } |
| | 0 | 168 | | } |
| | | 169 | | |
| | | 170 | | /// <summary> |
| | | 171 | | /// POST /api/articles - Creates a new article. |
| | | 172 | | /// </summary> |
| | | 173 | | [HttpPost] |
| | | 174 | | public async Task<ActionResult<ArticleDto>> CreateArticle([FromBody] ArticleCreateDto dto) |
| | | 175 | | { |
| | 0 | 176 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 177 | | |
| | | 178 | | try |
| | | 179 | | { |
| | 0 | 180 | | if (dto == null) |
| | | 181 | | { |
| | 0 | 182 | | return BadRequest("Invalid request body"); |
| | | 183 | | } |
| | | 184 | | |
| | 0 | 185 | | var validationResult = await _validationService.ValidateCreateAsync(dto); |
| | 0 | 186 | | if (!validationResult.IsValid) |
| | | 187 | | { |
| | 0 | 188 | | return BadRequest(new { errors = validationResult.Errors }); |
| | | 189 | | } |
| | | 190 | | |
| | | 191 | | // Generate slug |
| | | 192 | | string slug; |
| | 0 | 193 | | if (!string.IsNullOrWhiteSpace(dto.Slug)) |
| | | 194 | | { |
| | 0 | 195 | | if (!SlugGenerator.IsValidSlug(dto.Slug)) |
| | | 196 | | { |
| | 0 | 197 | | return BadRequest("Slug must contain only lowercase letters, numbers, and hyphens"); |
| | | 198 | | } |
| | | 199 | | |
| | 0 | 200 | | if (!await _articleService.IsSlugUniqueAsync(dto.Slug, dto.ParentId, dto.WorldId, user.Id)) |
| | | 201 | | { |
| | 0 | 202 | | return Conflict($"An article with slug '{dto.Slug}' already exists in this location"); |
| | | 203 | | } |
| | | 204 | | |
| | 0 | 205 | | slug = dto.Slug; |
| | | 206 | | } |
| | | 207 | | else |
| | | 208 | | { |
| | 0 | 209 | | slug = await _articleService.GenerateUniqueSlugAsync(dto.Title, dto.ParentId, dto.WorldId, user.Id); |
| | | 210 | | } |
| | | 211 | | |
| | 0 | 212 | | var article = new Article |
| | 0 | 213 | | { |
| | 0 | 214 | | Id = Guid.NewGuid(), |
| | 0 | 215 | | Title = dto.Title, |
| | 0 | 216 | | Slug = slug, |
| | 0 | 217 | | ParentId = dto.ParentId, |
| | 0 | 218 | | WorldId = dto.WorldId, |
| | 0 | 219 | | CampaignId = dto.CampaignId, |
| | 0 | 220 | | ArcId = dto.ArcId, |
| | 0 | 221 | | Body = dto.Body, |
| | 0 | 222 | | Type = dto.Type, |
| | 0 | 223 | | Visibility = dto.Visibility, |
| | 0 | 224 | | CreatedAt = DateTime.UtcNow, |
| | 0 | 225 | | CreatedBy = user.Id, |
| | 0 | 226 | | EffectiveDate = dto.EffectiveDate ?? DateTime.UtcNow, |
| | 0 | 227 | | IconEmoji = dto.IconEmoji, |
| | 0 | 228 | | SessionDate = dto.SessionDate, |
| | 0 | 229 | | InGameDate = dto.InGameDate, |
| | 0 | 230 | | PlayerId = dto.PlayerId |
| | 0 | 231 | | }; |
| | | 232 | | |
| | 0 | 233 | | _context.Articles.Add(article); |
| | 0 | 234 | | await _context.SaveChangesAsync(); |
| | | 235 | | |
| | | 236 | | // Sync wiki links if body contains content |
| | 0 | 237 | | if (!string.IsNullOrEmpty(dto.Body)) |
| | | 238 | | { |
| | 0 | 239 | | await _linkSyncService.SyncLinksAsync(article.Id, dto.Body); |
| | | 240 | | } |
| | | 241 | | |
| | 0 | 242 | | var responseDto = new ArticleDto |
| | 0 | 243 | | { |
| | 0 | 244 | | Id = article.Id, |
| | 0 | 245 | | Title = article.Title, |
| | 0 | 246 | | Slug = article.Slug, |
| | 0 | 247 | | ParentId = article.ParentId, |
| | 0 | 248 | | WorldId = article.WorldId, |
| | 0 | 249 | | CampaignId = article.CampaignId, |
| | 0 | 250 | | ArcId = article.ArcId, |
| | 0 | 251 | | Body = article.Body ?? string.Empty, |
| | 0 | 252 | | Type = article.Type, |
| | 0 | 253 | | Visibility = article.Visibility, |
| | 0 | 254 | | CreatedAt = article.CreatedAt, |
| | 0 | 255 | | ModifiedAt = article.ModifiedAt, |
| | 0 | 256 | | EffectiveDate = article.EffectiveDate, |
| | 0 | 257 | | CreatedBy = article.CreatedBy, |
| | 0 | 258 | | IconEmoji = article.IconEmoji, |
| | 0 | 259 | | HasChildren = false |
| | 0 | 260 | | }; |
| | | 261 | | |
| | 0 | 262 | | return CreatedAtAction(nameof(GetArticleDetail), new { id = article.Id }, responseDto); |
| | | 263 | | } |
| | 0 | 264 | | catch (Exception ex) |
| | | 265 | | { |
| | 0 | 266 | | _logger.LogError(ex, "Error creating article"); |
| | 0 | 267 | | return StatusCode(500, $"Error creating article: {ex.Message}"); |
| | | 268 | | } |
| | 0 | 269 | | } |
| | | 270 | | |
| | | 271 | | /// <summary> |
| | | 272 | | /// PUT /api/articles/{id} - Updates an existing article. |
| | | 273 | | /// </summary> |
| | | 274 | | [HttpPut("{id:guid}")] |
| | | 275 | | public async Task<ActionResult<ArticleDto>> UpdateArticle(Guid id, [FromBody] ArticleUpdateDto dto) |
| | | 276 | | { |
| | 0 | 277 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 278 | | |
| | | 279 | | try |
| | | 280 | | { |
| | 0 | 281 | | if (dto == null) |
| | | 282 | | { |
| | 0 | 283 | | return BadRequest("Invalid request body"); |
| | | 284 | | } |
| | | 285 | | |
| | 0 | 286 | | var validationResult = await _validationService.ValidateUpdateAsync(id, dto); |
| | 0 | 287 | | if (!validationResult.IsValid) |
| | | 288 | | { |
| | 0 | 289 | | return BadRequest(new { errors = validationResult.Errors }); |
| | | 290 | | } |
| | | 291 | | |
| | | 292 | | // Get article - check user has access via world membership |
| | 0 | 293 | | var article = await _context.Articles |
| | 0 | 294 | | .Where(a => a.Id == id) |
| | 0 | 295 | | .Where(a => a.World != null && a.World.Members.Any(m => m.UserId == user.Id)) |
| | 0 | 296 | | .FirstOrDefaultAsync(); |
| | | 297 | | |
| | 0 | 298 | | if (article == null) |
| | | 299 | | { |
| | 0 | 300 | | return NotFound($"Article {id} not found"); |
| | | 301 | | } |
| | | 302 | | |
| | | 303 | | // Handle slug update if provided |
| | 0 | 304 | | if (!string.IsNullOrWhiteSpace(dto.Slug) && dto.Slug != article.Slug) |
| | | 305 | | { |
| | 0 | 306 | | if (!SlugGenerator.IsValidSlug(dto.Slug)) |
| | | 307 | | { |
| | 0 | 308 | | return BadRequest("Slug must contain only lowercase letters, numbers, and hyphens"); |
| | | 309 | | } |
| | | 310 | | |
| | 0 | 311 | | if (!await _articleService.IsSlugUniqueAsync(dto.Slug, article.ParentId, article.WorldId, user.Id, id)) |
| | | 312 | | { |
| | 0 | 313 | | return Conflict($"An article with slug '{dto.Slug}' already exists in this location"); |
| | | 314 | | } |
| | | 315 | | |
| | 0 | 316 | | article.Slug = dto.Slug; |
| | | 317 | | } |
| | | 318 | | |
| | | 319 | | // Update fields |
| | 0 | 320 | | if (dto.Title != null) |
| | 0 | 321 | | article.Title = dto.Title; |
| | 0 | 322 | | if (dto.Body != null) |
| | 0 | 323 | | article.Body = dto.Body; |
| | 0 | 324 | | if (dto.EffectiveDate.HasValue) |
| | 0 | 325 | | article.EffectiveDate = dto.EffectiveDate.Value; |
| | 0 | 326 | | if (dto.IconEmoji != null) |
| | 0 | 327 | | article.IconEmoji = dto.IconEmoji; |
| | 0 | 328 | | if (dto.SessionDate.HasValue) |
| | 0 | 329 | | article.SessionDate = dto.SessionDate; |
| | 0 | 330 | | if (dto.InGameDate != null) |
| | 0 | 331 | | article.InGameDate = dto.InGameDate; |
| | 0 | 332 | | if (dto.Visibility.HasValue) |
| | 0 | 333 | | article.Visibility = dto.Visibility.Value; |
| | 0 | 334 | | if (dto.Type.HasValue) |
| | 0 | 335 | | article.Type = dto.Type.Value; |
| | | 336 | | |
| | 0 | 337 | | article.ModifiedAt = DateTime.UtcNow; |
| | 0 | 338 | | article.LastModifiedBy = user.Id; |
| | | 339 | | |
| | 0 | 340 | | await _context.SaveChangesAsync(); |
| | | 341 | | |
| | | 342 | | // Sync wiki links after update |
| | 0 | 343 | | if (!string.IsNullOrEmpty(dto.Body)) |
| | | 344 | | { |
| | 0 | 345 | | await _linkSyncService.SyncLinksAsync(id, dto.Body); |
| | | 346 | | } |
| | | 347 | | |
| | | 348 | | // Sync external links after update |
| | 0 | 349 | | await _externalLinkService.SyncExternalLinksAsync(id, dto.Body); |
| | | 350 | | |
| | | 351 | | // Return updated article |
| | 0 | 352 | | var updatedArticle = await _articleService.GetArticleDetailAsync(id, user.Id); |
| | 0 | 353 | | return Ok(updatedArticle); |
| | | 354 | | } |
| | 0 | 355 | | catch (Exception ex) |
| | | 356 | | { |
| | 0 | 357 | | _logger.LogError(ex, "Error updating article {ArticleId}", id); |
| | 0 | 358 | | return StatusCode(500, $"Error updating article: {ex.Message}"); |
| | | 359 | | } |
| | 0 | 360 | | } |
| | | 361 | | |
| | | 362 | | /// <summary> |
| | | 363 | | /// DELETE /api/articles/{id} - Deletes an article and all its children. |
| | | 364 | | /// </summary> |
| | | 365 | | [HttpDelete("{id:guid}")] |
| | | 366 | | public async Task<IActionResult> DeleteArticle(Guid id) |
| | | 367 | | { |
| | 0 | 368 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 369 | | |
| | | 370 | | try |
| | | 371 | | { |
| | | 372 | | // Get article - check user has access via world membership |
| | 0 | 373 | | var article = await _context.Articles |
| | 0 | 374 | | .Where(a => a.Id == id) |
| | 0 | 375 | | .Where(a => a.World != null && a.World.Members.Any(m => m.UserId == user.Id)) |
| | 0 | 376 | | .FirstOrDefaultAsync(); |
| | | 377 | | |
| | 0 | 378 | | if (article == null) |
| | | 379 | | { |
| | 0 | 380 | | return NotFound($"Article {id} not found"); |
| | | 381 | | } |
| | | 382 | | |
| | | 383 | | // Delete all descendants recursively |
| | 0 | 384 | | await DeleteArticleAndDescendantsAsync(id); |
| | | 385 | | |
| | 0 | 386 | | return NoContent(); |
| | | 387 | | } |
| | 0 | 388 | | catch (Exception ex) |
| | | 389 | | { |
| | 0 | 390 | | _logger.LogError(ex, "Error deleting article {ArticleId}", id); |
| | 0 | 391 | | return StatusCode(500, $"Error deleting article: {ex.Message}"); |
| | | 392 | | } |
| | 0 | 393 | | } |
| | | 394 | | |
| | | 395 | | /// <summary> |
| | | 396 | | /// PUT /api/articles/{id}/move - Moves an article to a new parent. |
| | | 397 | | /// </summary> |
| | | 398 | | [HttpPut("{id:guid}/move")] |
| | | 399 | | public async Task<IActionResult> MoveArticle(Guid id, [FromBody] ArticleMoveDto dto) |
| | | 400 | | { |
| | 0 | 401 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 402 | | |
| | | 403 | | try |
| | | 404 | | { |
| | 0 | 405 | | if (dto == null) |
| | | 406 | | { |
| | 0 | 407 | | return BadRequest("Invalid request body"); |
| | | 408 | | } |
| | | 409 | | |
| | 0 | 410 | | var (success, errorMessage) = await _articleService.MoveArticleAsync(id, dto.NewParentId, user.Id); |
| | | 411 | | |
| | 0 | 412 | | if (!success) |
| | | 413 | | { |
| | 0 | 414 | | return BadRequest(errorMessage); |
| | | 415 | | } |
| | | 416 | | |
| | | 417 | | // Return the updated article |
| | 0 | 418 | | var article = await _articleService.GetArticleDetailAsync(id, user.Id); |
| | 0 | 419 | | return Ok(article); |
| | | 420 | | } |
| | 0 | 421 | | catch (Exception ex) |
| | | 422 | | { |
| | 0 | 423 | | _logger.LogError(ex, "Error moving article {ArticleId}", id); |
| | 0 | 424 | | return StatusCode(500, $"Error moving article: {ex.Message}"); |
| | | 425 | | } |
| | 0 | 426 | | } |
| | | 427 | | |
| | | 428 | | #region Aliases |
| | | 429 | | |
| | | 430 | | /// <summary> |
| | | 431 | | /// PUT /api/articles/{id}/aliases - Updates all aliases for an article. |
| | | 432 | | /// Accepts a comma-delimited string that replaces all existing aliases. |
| | | 433 | | /// </summary> |
| | | 434 | | [HttpPut("{id:guid}/aliases")] |
| | | 435 | | public async Task<ActionResult<ArticleDto>> UpdateAliases(Guid id, [FromBody] ArticleAliasesUpdateDto dto) |
| | | 436 | | { |
| | 0 | 437 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 438 | | |
| | | 439 | | try |
| | | 440 | | { |
| | 0 | 441 | | if (dto == null) |
| | | 442 | | { |
| | 0 | 443 | | return BadRequest("Invalid request body"); |
| | | 444 | | } |
| | | 445 | | |
| | | 446 | | // Get article with existing aliases - check user has access via world membership |
| | 0 | 447 | | var article = await _context.Articles |
| | 0 | 448 | | .Include(a => a.Aliases) |
| | 0 | 449 | | .Where(a => a.Id == id) |
| | 0 | 450 | | .Where(a => a.World != null && a.World.Members.Any(m => m.UserId == user.Id)) |
| | 0 | 451 | | .FirstOrDefaultAsync(); |
| | | 452 | | |
| | 0 | 453 | | if (article == null) |
| | | 454 | | { |
| | 0 | 455 | | return NotFound($"Article {id} not found"); |
| | | 456 | | } |
| | | 457 | | |
| | | 458 | | // Parse the comma-delimited aliases |
| | 0 | 459 | | var newAliases = ParseAliases(dto.Aliases); |
| | | 460 | | |
| | | 461 | | // Validate: aliases cannot match the article's own title |
| | 0 | 462 | | var titleLower = article.Title?.ToLowerInvariant() ?? string.Empty; |
| | 0 | 463 | | var invalidAliases = newAliases.Where(a => a.ToLowerInvariant() == titleLower).ToList(); |
| | 0 | 464 | | if (invalidAliases.Any()) |
| | | 465 | | { |
| | 0 | 466 | | return BadRequest($"Alias cannot match the article's title: {string.Join(", ", invalidAliases)}"); |
| | | 467 | | } |
| | | 468 | | |
| | | 469 | | // Remove aliases that are no longer in the list |
| | 0 | 470 | | var aliasesToRemove = article.Aliases |
| | 0 | 471 | | .Where(existing => !newAliases.Contains(existing.AliasText, StringComparer.OrdinalIgnoreCase)) |
| | 0 | 472 | | .ToList(); |
| | 0 | 473 | | foreach (var alias in aliasesToRemove) |
| | | 474 | | { |
| | 0 | 475 | | _context.ArticleAliases.Remove(alias); |
| | | 476 | | } |
| | | 477 | | |
| | | 478 | | // Add new aliases that don't already exist |
| | 0 | 479 | | var existingAliasTexts = article.Aliases |
| | | 480 | | .Select(a => a.AliasText.ToLowerInvariant()) |
| | 0 | 481 | | .ToHashSet(); |
| | | 482 | | |
| | 0 | 483 | | foreach (var aliasText in newAliases) |
| | | 484 | | { |
| | 0 | 485 | | if (!existingAliasTexts.Contains(aliasText.ToLowerInvariant())) |
| | | 486 | | { |
| | 0 | 487 | | var newAlias = new ArticleAlias |
| | 0 | 488 | | { |
| | 0 | 489 | | Id = Guid.NewGuid(), |
| | 0 | 490 | | ArticleId = id, |
| | 0 | 491 | | AliasText = aliasText, |
| | 0 | 492 | | CreatedAt = DateTime.UtcNow |
| | 0 | 493 | | }; |
| | 0 | 494 | | _context.ArticleAliases.Add(newAlias); |
| | | 495 | | } |
| | | 496 | | } |
| | | 497 | | |
| | 0 | 498 | | article.ModifiedAt = DateTime.UtcNow; |
| | 0 | 499 | | article.LastModifiedBy = user.Id; |
| | | 500 | | |
| | 0 | 501 | | await _context.SaveChangesAsync(); |
| | | 502 | | |
| | | 503 | | // Return updated article with aliases |
| | 0 | 504 | | var updatedArticle = await _articleService.GetArticleDetailAsync(id, user.Id); |
| | 0 | 505 | | return Ok(updatedArticle); |
| | | 506 | | } |
| | 0 | 507 | | catch (Exception ex) |
| | | 508 | | { |
| | 0 | 509 | | _logger.LogError(ex, "Error updating aliases for article {ArticleId}", id); |
| | 0 | 510 | | return StatusCode(500, $"Error updating aliases: {ex.Message}"); |
| | | 511 | | } |
| | 0 | 512 | | } |
| | | 513 | | |
| | | 514 | | /// <summary> |
| | | 515 | | /// Parses a comma-delimited string into a list of trimmed, non-empty, unique aliases. |
| | | 516 | | /// </summary> |
| | | 517 | | private static List<string> ParseAliases(string? aliasesString) |
| | | 518 | | { |
| | 0 | 519 | | if (string.IsNullOrWhiteSpace(aliasesString)) |
| | | 520 | | { |
| | 0 | 521 | | return new List<string>(); |
| | | 522 | | } |
| | | 523 | | |
| | 0 | 524 | | return aliasesString |
| | 0 | 525 | | .Split(',', StringSplitOptions.RemoveEmptyEntries) |
| | 0 | 526 | | .Select(a => a.Trim()) |
| | 0 | 527 | | .Where(a => !string.IsNullOrWhiteSpace(a) && a.Length <= 200) |
| | 0 | 528 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 529 | | .ToList(); |
| | | 530 | | } |
| | | 531 | | |
| | | 532 | | #endregion |
| | | 533 | | |
| | | 534 | | #region Wiki Links |
| | | 535 | | |
| | | 536 | | /// <summary> |
| | | 537 | | /// GET /articles/{id}/backlinks - Gets all articles that link to this article. |
| | | 538 | | /// </summary> |
| | | 539 | | [HttpGet("{id:guid}/backlinks")] |
| | | 540 | | public async Task<ActionResult<BacklinksResponseDto>> GetBacklinks(Guid id) |
| | | 541 | | { |
| | 0 | 542 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | 0 | 543 | | _logger.LogDebug("Getting backlinks for article {ArticleId}", id); |
| | | 544 | | |
| | | 545 | | // Verify article exists and user has access |
| | 0 | 546 | | var article = await _context.Articles |
| | 0 | 547 | | .Where(a => a.Id == id) |
| | 0 | 548 | | .Where(a => a.World != null && a.World.Members.Any(m => m.UserId == user.Id)) |
| | 0 | 549 | | .FirstOrDefaultAsync(); |
| | | 550 | | |
| | 0 | 551 | | if (article == null) |
| | | 552 | | { |
| | 0 | 553 | | return NotFound(new { error = "Article not found or access denied" }); |
| | | 554 | | } |
| | | 555 | | |
| | | 556 | | // Get all articles that link TO this article |
| | 0 | 557 | | var backlinks = await _context.ArticleLinks |
| | 0 | 558 | | .Where(l => l.TargetArticleId == id) |
| | 0 | 559 | | .Select(l => new BacklinkDto |
| | 0 | 560 | | { |
| | 0 | 561 | | ArticleId = l.SourceArticleId, |
| | 0 | 562 | | Title = l.SourceArticle.Title ?? "Untitled", |
| | 0 | 563 | | Slug = l.SourceArticle.Slug, |
| | 0 | 564 | | Snippet = l.DisplayText, |
| | 0 | 565 | | DisplayPath = "" |
| | 0 | 566 | | }) |
| | 0 | 567 | | .Distinct() |
| | 0 | 568 | | .ToListAsync(); |
| | | 569 | | |
| | | 570 | | // Build display paths using centralised hierarchy service |
| | 0 | 571 | | foreach (var backlink in backlinks) |
| | | 572 | | { |
| | 0 | 573 | | backlink.DisplayPath = await _hierarchyService.BuildDisplayPathAsync(backlink.ArticleId); |
| | | 574 | | } |
| | | 575 | | |
| | 0 | 576 | | return Ok(new BacklinksResponseDto { Backlinks = backlinks }); |
| | 0 | 577 | | } |
| | | 578 | | |
| | | 579 | | /// <summary> |
| | | 580 | | /// GET /articles/{id}/outgoing-links - Gets all articles that this article links to. |
| | | 581 | | /// </summary> |
| | | 582 | | [HttpGet("{id:guid}/outgoing-links")] |
| | | 583 | | public async Task<ActionResult<BacklinksResponseDto>> GetOutgoingLinks(Guid id) |
| | | 584 | | { |
| | 0 | 585 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | 0 | 586 | | _logger.LogDebug("Getting outgoing links for article {ArticleId}", id); |
| | | 587 | | |
| | | 588 | | // Verify article exists and user has access |
| | 0 | 589 | | var article = await _context.Articles |
| | 0 | 590 | | .Where(a => a.Id == id) |
| | 0 | 591 | | .Where(a => a.World != null && a.World.Members.Any(m => m.UserId == user.Id)) |
| | 0 | 592 | | .FirstOrDefaultAsync(); |
| | | 593 | | |
| | 0 | 594 | | if (article == null) |
| | | 595 | | { |
| | 0 | 596 | | return NotFound(new { error = "Article not found or access denied" }); |
| | | 597 | | } |
| | | 598 | | |
| | | 599 | | // Get all articles that this article links TO |
| | 0 | 600 | | var outgoingLinks = await _context.ArticleLinks |
| | 0 | 601 | | .Where(l => l.SourceArticleId == id) |
| | 0 | 602 | | .Select(l => new BacklinkDto |
| | 0 | 603 | | { |
| | 0 | 604 | | ArticleId = l.TargetArticleId, |
| | 0 | 605 | | Title = l.TargetArticle.Title ?? "Untitled", |
| | 0 | 606 | | Slug = l.TargetArticle.Slug, |
| | 0 | 607 | | Snippet = l.DisplayText, |
| | 0 | 608 | | DisplayPath = "" |
| | 0 | 609 | | }) |
| | 0 | 610 | | .Distinct() |
| | 0 | 611 | | .ToListAsync(); |
| | | 612 | | |
| | | 613 | | // Build display paths using centralised hierarchy service |
| | 0 | 614 | | foreach (var link in outgoingLinks) |
| | | 615 | | { |
| | 0 | 616 | | link.DisplayPath = await _hierarchyService.BuildDisplayPathAsync(link.ArticleId); |
| | | 617 | | } |
| | | 618 | | |
| | 0 | 619 | | return Ok(new BacklinksResponseDto { Backlinks = outgoingLinks }); |
| | 0 | 620 | | } |
| | | 621 | | |
| | | 622 | | /// <summary> |
| | | 623 | | /// POST /articles/resolve-links - Resolves multiple article IDs to check if they exist. |
| | | 624 | | /// </summary> |
| | | 625 | | [HttpPost("resolve-links")] |
| | | 626 | | public async Task<ActionResult<LinkResolutionResponseDto>> ResolveLinks([FromBody] LinkResolutionRequestDto request) |
| | | 627 | | { |
| | 0 | 628 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 629 | | |
| | 0 | 630 | | if (request?.ArticleIds == null || !request.ArticleIds.Any()) |
| | | 631 | | { |
| | 0 | 632 | | return Ok(new LinkResolutionResponseDto { Articles = new Dictionary<Guid, ResolvedLinkDto>() }); |
| | | 633 | | } |
| | | 634 | | |
| | 0 | 635 | | _logger.LogDebug("Resolving {Count} article links", request.ArticleIds.Count); |
| | | 636 | | |
| | | 637 | | // Get all requested articles that the user has access to |
| | 0 | 638 | | var articles = await _context.Articles |
| | 0 | 639 | | .Where(a => request.ArticleIds.Contains(a.Id)) |
| | 0 | 640 | | .Where(a => a.World != null && a.World.Members.Any(m => m.UserId == user.Id)) |
| | 0 | 641 | | .Select(a => new ResolvedLinkDto |
| | 0 | 642 | | { |
| | 0 | 643 | | ArticleId = a.Id, |
| | 0 | 644 | | Exists = true, |
| | 0 | 645 | | Title = a.Title, |
| | 0 | 646 | | Slug = a.Slug |
| | 0 | 647 | | }) |
| | 0 | 648 | | .ToListAsync(); |
| | | 649 | | |
| | | 650 | | // Build response dictionary |
| | 0 | 651 | | var result = new LinkResolutionResponseDto |
| | 0 | 652 | | { |
| | 0 | 653 | | Articles = new Dictionary<Guid, ResolvedLinkDto>() |
| | 0 | 654 | | }; |
| | | 655 | | |
| | | 656 | | // Add found articles |
| | 0 | 657 | | foreach (var article in articles) |
| | | 658 | | { |
| | 0 | 659 | | result.Articles[article.ArticleId] = article; |
| | | 660 | | } |
| | | 661 | | |
| | | 662 | | // Add missing articles as non-existent |
| | 0 | 663 | | foreach (var requestedId in request.ArticleIds) |
| | | 664 | | { |
| | 0 | 665 | | if (!result.Articles.ContainsKey(requestedId)) |
| | | 666 | | { |
| | 0 | 667 | | result.Articles[requestedId] = new ResolvedLinkDto |
| | 0 | 668 | | { |
| | 0 | 669 | | ArticleId = requestedId, |
| | 0 | 670 | | Exists = false, |
| | 0 | 671 | | Title = null, |
| | 0 | 672 | | Slug = null |
| | 0 | 673 | | }; |
| | | 674 | | } |
| | | 675 | | } |
| | | 676 | | |
| | 0 | 677 | | return Ok(result); |
| | 0 | 678 | | } |
| | | 679 | | |
| | | 680 | | /// <summary> |
| | | 681 | | /// POST /articles/{id}/auto-link - Scans article content and returns match positions for wiki links. |
| | | 682 | | /// </summary> |
| | | 683 | | [HttpPost("{id:guid}/auto-link")] |
| | | 684 | | public async Task<ActionResult<AutoLinkResponseDto>> AutoLink(Guid id, [FromBody] AutoLinkRequestDto request) |
| | | 685 | | { |
| | 0 | 686 | | var user = await _currentUserService.GetRequiredUserAsync(); |
| | | 687 | | |
| | 0 | 688 | | if (request == null || string.IsNullOrEmpty(request.Body)) |
| | | 689 | | { |
| | 0 | 690 | | return BadRequest(new { error = "Body content is required" }); |
| | | 691 | | } |
| | | 692 | | |
| | 0 | 693 | | _logger.LogDebug("Auto-linking article {ArticleId}", id); |
| | | 694 | | |
| | | 695 | | // Get article and verify access |
| | 0 | 696 | | var article = await _context.Articles |
| | 0 | 697 | | .Where(a => a.Id == id) |
| | 0 | 698 | | .Where(a => a.World != null && a.World.Members.Any(m => m.UserId == user.Id)) |
| | 0 | 699 | | .Select(a => new { a.Id, a.WorldId }) |
| | 0 | 700 | | .FirstOrDefaultAsync(); |
| | | 701 | | |
| | 0 | 702 | | if (article == null) |
| | | 703 | | { |
| | 0 | 704 | | return NotFound(new { error = "Article not found or access denied" }); |
| | | 705 | | } |
| | | 706 | | |
| | 0 | 707 | | if (!article.WorldId.HasValue) |
| | | 708 | | { |
| | 0 | 709 | | return BadRequest(new { error = "Article must belong to a world" }); |
| | | 710 | | } |
| | | 711 | | |
| | 0 | 712 | | var result = await _autoLinkService.FindLinksAsync( |
| | 0 | 713 | | id, |
| | 0 | 714 | | article.WorldId.Value, |
| | 0 | 715 | | request.Body, |
| | 0 | 716 | | user.Id); |
| | | 717 | | |
| | 0 | 718 | | return Ok(result); |
| | 0 | 719 | | } |
| | | 720 | | |
| | | 721 | | #endregion |
| | | 722 | | |
| | | 723 | | #region Private Helpers |
| | | 724 | | |
| | | 725 | | /// <summary> |
| | | 726 | | /// Recursively deletes an article and all its descendants. |
| | | 727 | | /// </summary> |
| | | 728 | | private async Task DeleteArticleAndDescendantsAsync(Guid articleId) |
| | | 729 | | { |
| | | 730 | | // Get all children |
| | 0 | 731 | | var children = await _context.Articles |
| | 0 | 732 | | .Where(a => a.ParentId == articleId) |
| | 0 | 733 | | .Select(a => a.Id) |
| | 0 | 734 | | .ToListAsync(); |
| | | 735 | | |
| | | 736 | | // Recursively delete children first |
| | 0 | 737 | | foreach (var childId in children) |
| | | 738 | | { |
| | 0 | 739 | | await DeleteArticleAndDescendantsAsync(childId); |
| | | 740 | | } |
| | | 741 | | |
| | | 742 | | // Delete article links pointing to/from this article |
| | 0 | 743 | | var linksToDelete = await _context.ArticleLinks |
| | 0 | 744 | | .Where(l => l.SourceArticleId == articleId || l.TargetArticleId == articleId) |
| | 0 | 745 | | .ToListAsync(); |
| | 0 | 746 | | _context.ArticleLinks.RemoveRange(linksToDelete); |
| | | 747 | | |
| | | 748 | | // Delete inline images associated with this article |
| | 0 | 749 | | await _worldDocumentService.DeleteArticleImagesAsync(articleId); |
| | | 750 | | |
| | | 751 | | // Delete the article itself |
| | 0 | 752 | | var article = await _context.Articles.FindAsync(articleId); |
| | 0 | 753 | | if (article != null) |
| | | 754 | | { |
| | 0 | 755 | | _context.Articles.Remove(article); |
| | | 756 | | } |
| | | 757 | | |
| | 0 | 758 | | await _context.SaveChangesAsync(); |
| | 0 | 759 | | } |
| | | 760 | | |
| | | 761 | | #endregion |
| | | 762 | | } |