Handler.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. using Application.Abstractions.Messaging;
  2. using Application.Abstractions.Data;
  3. using SharedKernel.Storage;
  4. using Microsoft.EntityFrameworkCore;
  5. using System.Text.RegularExpressions;
  6. namespace Application.Features.Admin.Forum.Post.Create;
  7. public sealed class Handler(IAppDbContext db, IFileStorage fileStorage) : ICommandHandler<Command>
  8. {
  9. private static readonly string[] AllowedImageExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"];
  10. private static readonly string[] AllowedFileExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".txt", ".zip", ".rar", ".7z", ".hwp", ".hwpx", ".csv"];
  11. private static readonly Regex ImgBase64Regex = new(@"<img\b[^>]*?\bsrc\s*=\s*""(?<src>data:image/(?<ext>[a-zA-Z0-9.+-]+);base64,(?<data>[a-zA-Z0-9+/=\s]+))""", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  12. public async Task Handle(Command request, CancellationToken ct)
  13. {
  14. if (!await db.Board.AnyAsync(x => x.ID == request.BoardID, ct))
  15. {
  16. throw new KeyNotFoundException("게시판을 찾을 수 없습니다.");
  17. }
  18. var post = new Domain.Entities.Forum.Posts.Post
  19. {
  20. BoardID = request.BoardID,
  21. BoardPrefixID = request.BoardPrefixID,
  22. MemberID = null,
  23. Subject = request.Subject,
  24. Content = request.Content ?? string.Empty,
  25. IsNotice = request.IsNotice,
  26. IsSecret = request.IsSecret,
  27. IsAnonymous = request.IsAnonymous,
  28. Name = "관리자"
  29. };
  30. await db.Post.AddAsync(post, ct);
  31. await db.SaveChangesAsync(ct);
  32. var uploadPath = new FileStoragePath(UploadTarget.Upload, UploadFolder.Post, post.ID);
  33. // 에디터 이미지 처리 (base64 → 파일 + PostImage 레코드)
  34. var content = post.Content;
  35. var matches = ImgBase64Regex.Matches(content);
  36. if (matches.Count > 0)
  37. {
  38. byte imageCount = 0;
  39. var firstImageUrl = (string?)null;
  40. foreach (Match match in matches)
  41. {
  42. var ext = FileUtils.NormalizeExtension(match.Groups["ext"].Value);
  43. var bytes = Convert.FromBase64String(match.Groups["data"].Value);
  44. var result = await fileStorage.SaveBytesAsync(bytes, ext, uploadPath, ct);
  45. if (result is not null)
  46. {
  47. content = content.Replace(match.Groups["src"].Value, result.Url);
  48. firstImageUrl ??= result.Url;
  49. await db.PostImage.AddAsync(new Domain.Entities.Forum.Posts.PostImage
  50. {
  51. BoardID = request.BoardID,
  52. PostID = post.ID,
  53. FileName = result.FileName,
  54. HashedName = result.FileName,
  55. Path = uploadPath.ToRelativePath(),
  56. Url = result.Url,
  57. Extension = ext,
  58. ContentType = $"image/{match.Groups["ext"].Value}",
  59. Size = result.Size,
  60. Width = result.Width,
  61. Height = result.Height
  62. }, ct);
  63. imageCount++;
  64. }
  65. }
  66. post.Content = content;
  67. post.Images = imageCount;
  68. if (string.IsNullOrEmpty(post.Thumbnail) && firstImageUrl is not null)
  69. {
  70. post.Thumbnail = firstImageUrl;
  71. }
  72. }
  73. // 썸네일 처리
  74. if (request.ThumbnailFile is not null)
  75. {
  76. var result = await fileStorage.SaveFileAsync(request.ThumbnailFile, uploadPath, AllowedImageExtensions, ct);
  77. if (result is not null)
  78. {
  79. post.Thumbnail = result.Url;
  80. }
  81. }
  82. // 파일 처리
  83. if (request.Files is { Count: > 0 })
  84. {
  85. byte fileCount = 0;
  86. foreach (var file in request.Files)
  87. {
  88. var result = await fileStorage.SaveFileAsync(file, uploadPath, AllowedFileExtensions, ct);
  89. if (result is not null)
  90. {
  91. var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
  92. await db.PostFile.AddAsync(new Domain.Entities.Forum.Posts.PostFile
  93. {
  94. BoardID = request.BoardID,
  95. PostID = post.ID,
  96. UUID = Guid.NewGuid(),
  97. FileName = file.FileName,
  98. HashedName = result.FileName,
  99. Path = uploadPath.ToRelativePath(),
  100. Url = result.Url,
  101. Extension = ext,
  102. ContentType = file.ContentType,
  103. Size = result.Size
  104. }, ct);
  105. fileCount++;
  106. }
  107. }
  108. post.Files = fileCount;
  109. }
  110. // 태그 처리
  111. if (request.Tags is { Count: > 0 })
  112. {
  113. byte tagCount = 0;
  114. foreach (var tagName in request.Tags)
  115. {
  116. if (string.IsNullOrWhiteSpace(tagName))
  117. {
  118. continue;
  119. }
  120. var name = tagName.Trim();
  121. var slug = name.ToLowerInvariant().Replace(' ', '-');
  122. var tag = await db.Tag.FirstOrDefaultAsync(x => x.Name == name, ct);
  123. if (tag is null)
  124. {
  125. tag = new Domain.Entities.Forum.Posts.Tag
  126. {
  127. Name = name,
  128. Slug = slug
  129. };
  130. await db.Tag.AddAsync(tag, ct);
  131. await db.SaveChangesAsync(ct);
  132. }
  133. tag.UsageCount++;
  134. tag.UpdatedAt = DateTime.UtcNow;
  135. await db.PostTag.AddAsync(new Domain.Entities.Forum.Posts.PostTag
  136. {
  137. BoardID = request.BoardID,
  138. PostID = post.ID,
  139. TagID = tag.ID
  140. }, ct);
  141. tagCount++;
  142. }
  143. post.Tags = tagCount;
  144. }
  145. await db.SaveChangesAsync(ct);
  146. // Board 게시글 카운트 증가
  147. var board = await db.Board.FirstOrDefaultAsync(x => x.ID == request.BoardID, ct);
  148. if (board is not null)
  149. {
  150. board.Posts++;
  151. board.UpdatedAt = DateTime.UtcNow;
  152. // BoardGroup 게시글 카운트 증가
  153. var boardGroup = await db.BoardGroup.FirstOrDefaultAsync(x => x.ID == board.BoardGroupID, ct);
  154. if (boardGroup is not null)
  155. {
  156. boardGroup.Posts++;
  157. boardGroup.UpdatedAt = DateTime.UtcNow;
  158. }
  159. await db.SaveChangesAsync(ct);
  160. }
  161. }
  162. }