Handler.cs 7.0 KB

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