DocumentController.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. using System.Diagnostics;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.EntityFrameworkCore;
  5. using bitforum.Models;
  6. using bitforum.Models.Page;
  7. using bitforum.Constants;
  8. using bitforum.Helpers;
  9. using bitforum.Services;
  10. using bitforum.Repository;
  11. namespace bitforum.Controllers.Page
  12. {
  13. [Authorize]
  14. [Route("Page")]
  15. public class DocumentController : Controller
  16. {
  17. private readonly ILogger<DocumentController> _logger;
  18. private readonly IFileUploadService _fileUploadService;
  19. private readonly IRedisRepository _redisRepository;
  20. private readonly DefaultDbContext _db;
  21. private readonly string _IndexViewPath = "~/Views/Page/Document/Index.cshtml";
  22. private readonly string _WriteViewPath = "~/Views/Page/Document/Write.cshtml";
  23. private readonly string _EditViewPath = "~/Views/Page/Document/Edit.cshtml";
  24. public DocumentController(ILogger<DocumentController> logger, IFileUploadService fileUploadService, IRedisRepository redisRepository, DefaultDbContext db)
  25. {
  26. _logger = logger;
  27. _fileUploadService = fileUploadService;
  28. _redisRepository = redisRepository;
  29. _db = db;
  30. }
  31. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  32. public IActionResult Error()
  33. {
  34. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  35. }
  36. [HttpGet("Document")]
  37. public IActionResult Index()
  38. {
  39. var domain = Setting.AppConfig.AppName;
  40. var documents = _db.Document.OrderByDescending(c => c.ID).ToList();
  41. var data = new List<object>();
  42. if (documents.Count > 0)
  43. {
  44. foreach (var row in documents)
  45. {
  46. var entry = new
  47. {
  48. row.ID,
  49. Link = $"{domain }/docs/{row.Code}",
  50. row.Code,
  51. row.Subject,
  52. row.Content,
  53. Views = row.Views.ToString("N0"),
  54. IsActive = (row.IsActive ? 'Y' : 'N'),
  55. UpdatedAt = row.UpdatedAt.GetDateAt(),
  56. CreatedAt = row.CreatedAt.GetDateAt(),
  57. EditURL = $"/Page/Document/{row.ID}/Edit",
  58. DeleteURL = $"/Page/Document/{row.ID}/Delete"
  59. };
  60. data.Add(entry);
  61. }
  62. }
  63. ViewBag.Data = data;
  64. ViewBag.Total = (data?.Count ?? 0);
  65. return View(_IndexViewPath);
  66. }
  67. [HttpGet("Document/Write")]
  68. public IActionResult Write()
  69. {
  70. ViewBag.siteURL = Setting.AppConfig.AppName;
  71. return View(_WriteViewPath);
  72. }
  73. [HttpPost("Document/Create")]
  74. public async Task<IActionResult> Create(Document request)
  75. {
  76. try
  77. {
  78. if (!ModelState.IsValid)
  79. {
  80. throw new Exception("유효성 검사에 실패하였습니다.");
  81. }
  82. // 중복확인
  83. if (await _db.Document.AnyAsync(c => c.Code == request.Code))
  84. {
  85. throw new Exception("이미 존재하는 주소입니다.");
  86. }
  87. request.Content = _fileUploadService.UploadEditorAsync(request.Content, null, UploadFolder.Document).Result;
  88. request.UpdatedAt = null;
  89. request.CreatedAt = DateTime.UtcNow;
  90. _db.Document.Add(request);
  91. int affectedRows = await _db.SaveChangesAsync();
  92. if (affectedRows <= 0)
  93. {
  94. throw new Exception("문서 등록 중 오류가 발생했습니다.");
  95. }
  96. await _redisRepository.SetObjectAsync($"{RedisConst.DocumentKey}-{request.Code}", request, RedisConst.CacheExpiration);
  97. string message = "문서가 등록되었습니다.";
  98. TempData["SuccessMessage"] = message;
  99. _logger.LogInformation(message);
  100. return RedirectToAction("Index");
  101. }
  102. catch (Exception e)
  103. {
  104. TempData["ErrorMessages"] = e.Message;
  105. _logger.LogError(e, e.Message);
  106. return View(_WriteViewPath, request);
  107. }
  108. }
  109. [HttpGet("Document/{id}/Edit")]
  110. public async Task<IActionResult> Edit(int id)
  111. {
  112. try
  113. {
  114. if (id <= 0)
  115. {
  116. throw new Exception("유효하지 않은 문서 ID입니다.");
  117. }
  118. var document = await _db.Document.FirstAsync(c => c.ID == id);
  119. if (document is null)
  120. {
  121. throw new Exception("사용자 정보를 찾을 수 없습니다.");
  122. }
  123. ViewBag.siteURL = Setting.AppConfig.AppName;
  124. return View(_EditViewPath, document);
  125. }
  126. catch (Exception e)
  127. {
  128. TempData["ErrorMessages"] = e.Message;
  129. _logger.LogError(e, e.Message);
  130. return Index();
  131. }
  132. }
  133. [HttpPost("Document/Update")]
  134. public async Task<IActionResult> Update(Document request)
  135. {
  136. try
  137. {
  138. if (!ModelState.IsValid)
  139. {
  140. throw new Exception("유효성 검사에 실패하였습니다.");
  141. }
  142. // 중복확인
  143. if (await _db.Document.AnyAsync(c => c.Code == request.Code && c.ID != request.ID))
  144. {
  145. throw new Exception("이미 존재하는 Code 주소입니다.");
  146. }
  147. // 기존 문서 조회
  148. var document = await _db.Document.FindAsync(request.ID);
  149. if (document is null)
  150. {
  151. throw new Exception("사용자 정보를 찾을 수 없습니다.");
  152. }
  153. document.IsActive = request.IsActive;
  154. document.Code = request.Code;
  155. document.Subject = request.Subject;
  156. document.Content = _fileUploadService.UploadEditorAsync(request.Content, document.Content, UploadFolder.Document).Result;
  157. document.UpdatedAt = DateTime.UtcNow;
  158. int affectedRows = await _db.SaveChangesAsync();
  159. if (affectedRows <= 0)
  160. {
  161. throw new Exception("문서 수정 중 오류가 발생했습니다.");
  162. }
  163. await _redisRepository.SetObjectAsync($"{RedisConst.DocumentKey}-{request.Code}", document, RedisConst.CacheExpiration);
  164. string message = $"{document.ID}번 문서가 수정되었습니다.";
  165. TempData["SuccessMessage"] = message;
  166. _logger.LogInformation(message);
  167. return await Edit(request.ID);
  168. }
  169. catch (Exception e)
  170. {
  171. TempData["ErrorMessages"] = e.Message;
  172. _logger.LogError(e, e.Message);
  173. return View(_EditViewPath, request);
  174. }
  175. }
  176. [HttpGet("Document/{id}/Delete")]
  177. public async Task<IActionResult> Delete(int id)
  178. {
  179. try
  180. {
  181. if (id <= 0)
  182. {
  183. throw new Exception("유효하지 않은 문서 ID입니다.");
  184. }
  185. var document = await _db.Document.FindAsync(id);
  186. if (document == null)
  187. {
  188. throw new Exception("문서 정보를 찾을 수 없습니다.");
  189. }
  190. _db.Document.Remove(document);
  191. int affectedRows = await _db.SaveChangesAsync();
  192. if (affectedRows <= 0)
  193. {
  194. throw new Exception("문서 삭제 중 오류가 발생했습니다.");
  195. }
  196. await _fileUploadService.CleanUpEditorImagesAsync(document.Content);
  197. await _redisRepository.DeleteAsync($"{RedisConst.DocumentKey}-{document.Code}");
  198. string message = "문서가 삭제되었습니다.";
  199. TempData["SuccessMessage"] = message;
  200. _logger.LogInformation(message);
  201. }
  202. catch (Exception e)
  203. {
  204. TempData["ErrorMessages"] = e.Message;
  205. _logger.LogError(e, e.Message);
  206. }
  207. return Index();
  208. }
  209. }
  210. }