WebMediaController.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using GxPress.Auth;
  5. using GxPress.Common.Exceptions;
  6. using GxPress.Repository.Interface.Media;
  7. using GxPress.Request.Media;
  8. using GxPress.Result.Media;
  9. using GxPress.Service.Interface.Media;
  10. using Microsoft.AspNetCore.Authorization;
  11. using Microsoft.AspNetCore.Http;
  12. using Microsoft.AspNetCore.Mvc;
  13. using Microsoft.AspNetCore.StaticFiles;
  14. using Microsoft.Net.Http.Headers;
  15. namespace GxPress.Api.WebControllers
  16. {
  17. /// <summary>
  18. /// 媒体
  19. /// </summary>
  20. [Route("api/web/media")]
  21. [ApiController]
  22. [Authorize]
  23. public class WebMediaController : Controller
  24. {
  25. private readonly IMediaRepository mediaRepository;
  26. private readonly ILoginContext _loginContext;
  27. private readonly IMediaService mediaService;
  28. private IHttpContextAccessor _contextAccessor;
  29. private readonly IMediaLibraryRepository mediaLibraryRepository;
  30. private HttpContext _context { get { return _contextAccessor.HttpContext; } }
  31. public WebMediaController(IMediaRepository mediaRepository, ILoginContext _loginContext, IMediaService mediaService, IHttpContextAccessor contextAccessor, IMediaLibraryRepository mediaLibraryRepository)
  32. {
  33. this.mediaRepository = mediaRepository;
  34. this._loginContext = _loginContext;
  35. this.mediaService = mediaService;
  36. _contextAccessor = contextAccessor;
  37. this.mediaLibraryRepository = mediaLibraryRepository;
  38. }
  39. /// <summary>
  40. /// 详情
  41. /// </summary>
  42. /// <param name="id"></param>
  43. /// <returns></returns>
  44. [HttpGet("{id}")]
  45. [AllowAnonymous]
  46. public async Task<MediaResult> GetAsync(int id)
  47. {
  48. return await mediaService.GetAsync(id);
  49. }
  50. /// <summary>
  51. /// 书籍详情
  52. /// /// </summary>
  53. /// <param name="id"></param>
  54. /// <returns></returns>
  55. [HttpGet("book/{id}")]
  56. [AllowAnonymous]
  57. public async Task<BookMediaResult> GetBookMediaResult(int id)
  58. {
  59. return await mediaService.GetBookMediaResultAsync(id);
  60. }
  61. /// <summary>
  62. /// 获取视频详情
  63. /// </summary>
  64. /// <param name="id"></param>
  65. /// <returns></returns>
  66. [HttpGet("video/{id}")]
  67. [AllowAnonymous]
  68. public async Task<VideoMediaResult> GetVideoMediaResultAsync(int id)
  69. {
  70. return await mediaService.GetVideoMediaResultAsync(id);
  71. }
  72. /// <summary>
  73. /// 获取章节内容
  74. /// </summary>
  75. /// <param name="request"></param>
  76. /// <returns></returns>
  77. [HttpPost("book/content")]
  78. [AllowAnonymous]
  79. public async Task<string> GetBookMediaContentResultAsync(BookCatalogRequest request)
  80. {
  81. return await mediaService.GetBookMediaContentResultAsync(request);
  82. }
  83. /// <summary>
  84. /// 分页视频流
  85. /// </summary>
  86. /// <returns></returns>
  87. [HttpPost]
  88. [AllowAnonymous]
  89. public async Task<IActionResult> GetVideo(VideoMediaFileStreamRequest request)
  90. {
  91. var range = Request.Headers["Range"].ToString().Replace("bytes=", "");
  92. try
  93. {
  94. if (request.MediaLibraryId == 0)
  95. throw new BusinessException("不存在");
  96. if (string.IsNullOrEmpty(range))
  97. throw new BusinessException("服务器异常");
  98. //获取文件
  99. var mediaLibrary = await mediaLibraryRepository.GetAsync(request.MediaLibraryId);
  100. var filepath = "wwwroot" + mediaLibrary.FileUrl;
  101. //var filepath = "http://localhost:83/cache/20200428/1588144602647614.mp4";
  102. //从第3个到第12个字节,共10个字节。(0是第一个字节)
  103. var begin = int.Parse(range.Split('-')[0]);
  104. var end = int.Parse(range.Split('-')[1]);
  105. var byteLength = (end - begin) + 1;
  106. var bytes = new byte[byteLength];
  107. //var fristBytes = new byte[1024];
  108. FileInfo fileInfo = new FileInfo(filepath);
  109. //获取后缀名
  110. var ext = fileInfo.Extension;
  111. new FileExtensionContentTypeProvider().Mappings.TryGetValue(ext, out var contenttype);
  112. //获取文件流
  113. StreamReader stream = new StreamReader(System.IO.File.OpenRead(filepath));
  114. //stream.BaseStream.Read(fristBytes, 0, 1024);
  115. stream.BaseStream.Seek(begin, SeekOrigin.Begin);
  116. stream.BaseStream.Read(bytes, 0, byteLength);
  117. stream.Close();
  118. //var newBytes = new byte[fristBytes.Length + bytes.Length];
  119. // fristBytes.CopyTo(newBytes, 0);
  120. // bytes.CopyTo(newBytes, fristBytes.Length);
  121. _context.Response.Headers.Add(HeaderNames.AcceptRanges, "bytes");
  122. _context.Response.Headers.Add(HeaderNames.ContentRange, $"bytes {Request.Headers["Range"].ToString()}/{fileInfo.Length}");
  123. _context.Response.StatusCode = 206;
  124. var actionResult = File(bytes, contenttype ?? "application/octet-stream", fileInfo.Name);
  125. return actionResult;
  126. }
  127. catch (Exception ex)
  128. {
  129. throw new BusinessException($"{ex.Message}");
  130. }
  131. }
  132. /// <summary>
  133. /// 分页视频流
  134. /// </summary>
  135. /// <returns></returns>
  136. [HttpHead("header/{id}")]
  137. [AllowAnonymous]
  138. public async Task<IActionResult> GetVideoInfo(int id)
  139. {
  140. try
  141. {
  142. var mediaLibrary = await mediaLibraryRepository.GetAsync(id);
  143. var filepath = "wwwroot" + mediaLibrary.FileUrl;
  144. FileInfo fileInfo = new FileInfo(filepath);
  145. byte[] bytsize = new byte[fileInfo.Length];
  146. var ext = fileInfo.Extension;
  147. new FileExtensionContentTypeProvider().Mappings.TryGetValue(ext, out var contenttype);
  148. var actionResult = File(bytsize, contenttype ?? "application/octet-stream", fileInfo.Name);
  149. return actionResult;
  150. }
  151. catch (FileNotFoundException e)
  152. {
  153. throw new Common.Exceptions.BusinessException(e.Message);
  154. }
  155. catch (IOException e)
  156. {
  157. throw new Common.Exceptions.BusinessException(e.Message);
  158. }
  159. }
  160. }
  161. }