SitesController.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using Masuit.MyBlogs.Core.Common;
  2. using Masuit.MyBlogs.Core.Extensions.DriveHelpers;
  3. using Masuit.MyBlogs.Core.Extensions.Firewall;
  4. using Masuit.MyBlogs.Core.Infrastructure.Drive;
  5. using Masuit.MyBlogs.Core.Models.Drive;
  6. using Masuit.MyBlogs.Core.Models.DTO;
  7. using Masuit.MyBlogs.Core.Models.ViewModel;
  8. using Masuit.Tools.Core.Net;
  9. using Microsoft.AspNetCore.Mvc;
  10. using Microsoft.AspNetCore.Mvc.Filters;
  11. using Newtonsoft.Json;
  12. using Newtonsoft.Json.Serialization;
  13. namespace Masuit.MyBlogs.Core.Controllers.Drive
  14. {
  15. [ApiController]
  16. [ServiceFilter(typeof(FirewallAttribute))]
  17. [Route("api/")]
  18. public class SitesController : Controller
  19. {
  20. private readonly IDriveAccountService _siteService;
  21. private readonly IDriveService _driveService;
  22. private readonly SettingService _setting;
  23. public UserInfoDto CurrentUser => HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo) ?? new UserInfoDto();
  24. public SitesController(IDriveAccountService siteService, IDriveService driveService, SettingService setting)
  25. {
  26. this._siteService = siteService;
  27. this._driveService = driveService;
  28. this._setting = setting;
  29. }
  30. /// <summary>
  31. /// 返回所有sites
  32. /// </summary>
  33. /// <returns></returns>
  34. [HttpGet("sites"), ResponseCache(Duration = 600, Location = ResponseCacheLocation.Client)]
  35. public IActionResult GetSites()
  36. {
  37. return Json(_siteService.GetSites(), new JsonSerializerSettings()
  38. {
  39. ContractResolver = new CamelCasePropertyNamesContractResolver()
  40. });
  41. }
  42. /// <summary>
  43. /// 根据路径获取文件夹内容
  44. /// </summary>
  45. /// <returns></returns>
  46. [HttpGet("sites/{siteName}/{**path}"), ResponseCache(Duration = 600, Location = ResponseCacheLocation.Client)]
  47. public async Task<IActionResult> GetDirectory(string siteName, string path)
  48. {
  49. if (string.IsNullOrEmpty(siteName))
  50. {
  51. return NotFound(new ErrorResponse()
  52. {
  53. message = "找不到请求的 Site Name"
  54. });
  55. }
  56. if (string.IsNullOrEmpty(path))
  57. {
  58. try
  59. {
  60. var result = await _driveService.GetRootItems(siteName, CurrentUser.IsAdmin);
  61. return Json(result, new JsonSerializerSettings()
  62. {
  63. ContractResolver = new CamelCasePropertyNamesContractResolver()
  64. });
  65. }
  66. catch (Exception e)
  67. {
  68. return StatusCode(500, e.Message);
  69. }
  70. }
  71. else
  72. {
  73. try
  74. {
  75. var result = await _driveService.GetDriveItemsByPath(path, siteName, CurrentUser.IsAdmin);
  76. if (result == null)
  77. {
  78. return NotFound(new ErrorResponse()
  79. {
  80. message = $"路径{path}不存在"
  81. });
  82. }
  83. return Json(result, new JsonSerializerSettings()
  84. {
  85. ContractResolver = new CamelCasePropertyNamesContractResolver()
  86. });
  87. }
  88. catch
  89. {
  90. return NotFound(new ErrorResponse()
  91. {
  92. message = $"路径{path}不存在"
  93. });
  94. }
  95. }
  96. }
  97. /// <summary>
  98. /// 下载文件
  99. /// </summary>
  100. /// <param name="path"></param>
  101. /// <returns></returns>
  102. [HttpGet("files/{siteName}/{**path}"), ResponseCache(Duration = 600, Location = ResponseCacheLocation.Client)]
  103. public async Task<IActionResult> Download(string siteName, string path)
  104. {
  105. try
  106. {
  107. var result = await _driveService.GetDriveItemByPath(path, siteName);
  108. if (result != null)
  109. {
  110. return Redirect(result.DownloadUrl);
  111. }
  112. return NotFound(new ErrorResponse()
  113. {
  114. message = $"所求的{path}不存在"
  115. });
  116. }
  117. catch (Exception e)
  118. {
  119. return StatusCode(500, e.Message);
  120. }
  121. }
  122. /// <summary>
  123. /// 获取基本信息
  124. /// </summary>
  125. /// <returns></returns>
  126. [HttpGet("info"), ResponseCache(Duration = 600, Location = ResponseCacheLocation.Client)]
  127. public IActionResult GetInfo()
  128. {
  129. bool isAollowAnonymous = !string.IsNullOrEmpty(_setting.Get("AllowAnonymouslyUpload")) && Convert.ToBoolean(_setting.Get("AllowAnonymouslyUpload"));
  130. return Json(new
  131. {
  132. appName = _setting.Get("AppName"),
  133. webName = _setting.Get("WebName"),
  134. defaultDrive = _setting.Get("DefaultDrive"),
  135. readme = _setting.Get("Readme"),
  136. footer = _setting.Get("Footer"),
  137. allowUpload = isAollowAnonymous
  138. }, new JsonSerializerSettings()
  139. {
  140. ContractResolver = new CamelCasePropertyNamesContractResolver()
  141. });
  142. }
  143. /// <summary>
  144. /// 获得readme
  145. /// </summary>
  146. /// <returns></returns>
  147. [HttpGet("readme"), ResponseCache(Duration = 600, Location = ResponseCacheLocation.Client)]
  148. public IActionResult GetReadme()
  149. {
  150. return Json(new
  151. {
  152. readme = _setting.Get("Readme")
  153. }, new JsonSerializerSettings()
  154. {
  155. ContractResolver = new CamelCasePropertyNamesContractResolver()
  156. });
  157. }
  158. /// <summary>
  159. /// 获取文件分片上传路径
  160. /// </summary>
  161. /// <returns></returns>
  162. [HttpGet("upload/{siteName}/{**fileName}"), ResponseCache(Duration = 600, Location = ResponseCacheLocation.Client)]
  163. public async Task<IActionResult> GetUploadUrl(string siteName, string fileName)
  164. {
  165. bool isAollowAnonymous = !string.IsNullOrEmpty(_setting.Get("AllowAnonymouslyUpload")) && Convert.ToBoolean(_setting.Get("AllowAnonymouslyUpload"));
  166. if (!isAollowAnonymous)
  167. {
  168. if (Request.Headers.ContainsKey("Authorization"))
  169. {
  170. if (!CurrentUser.IsAdmin)
  171. {
  172. return Unauthorized(new ErrorResponse()
  173. {
  174. message = "未经授权的访问"
  175. });
  176. }
  177. }
  178. else
  179. {
  180. return Unauthorized(new ErrorResponse()
  181. {
  182. message = "未经授权的访问"
  183. });
  184. }
  185. }
  186. string path = Path.Combine($"upload/{Guid.NewGuid()}", fileName);
  187. try
  188. {
  189. var result = await _driveService.GetUploadUrl(path, siteName);
  190. return Json(new
  191. {
  192. requestUrl = result,
  193. fileUrl = $"{OneDriveConfiguration.BaseUri}/api/files/{siteName}/{path}"
  194. }, new JsonSerializerSettings()
  195. {
  196. ContractResolver = new CamelCasePropertyNamesContractResolver()
  197. });
  198. }
  199. catch (Exception e)
  200. {
  201. return StatusCode(500, e.Message);
  202. }
  203. }
  204. /// <summary>
  205. /// 获取文件分片上传路径
  206. /// </summary>
  207. /// <returns></returns>
  208. [HttpGet("cli/upload/{siteName}/:/{**path}")]
  209. public async Task<IActionResult> GetUploadUrl(string siteName, string path, string uploadPassword)
  210. {
  211. if (uploadPassword != _setting.Get("UploadPassword"))
  212. {
  213. return Unauthorized(new ErrorResponse()
  214. {
  215. message = "上传密码错误"
  216. });
  217. }
  218. if (string.IsNullOrEmpty(path))
  219. {
  220. return BadRequest(new ErrorResponse()
  221. {
  222. message = "必须存在上传路径"
  223. });
  224. }
  225. try
  226. {
  227. var result = await _driveService.GetUploadUrl(path, siteName);
  228. return Json(new
  229. {
  230. requestUrl = result
  231. }, new JsonSerializerSettings()
  232. {
  233. ContractResolver = new CamelCasePropertyNamesContractResolver()
  234. });
  235. }
  236. catch (Exception e)
  237. {
  238. return StatusCode(500, e.Message);
  239. }
  240. }
  241. public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
  242. {
  243. if (CommonHelper.SystemSettings.GetOrAdd("CloseSite", "false") == "true")
  244. {
  245. context.Result = new BadRequestObjectResult(new { code = 403 });
  246. return Task.CompletedTask;
  247. }
  248. return next();
  249. }
  250. }
  251. }