FileWriter.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. #pragma warning disable CS1591
  2. #pragma warning disable SA1600
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Runtime.InteropServices;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.Services;
  14. using Microsoft.Extensions.Logging;
  15. using Microsoft.AspNetCore.Http;
  16. using Microsoft.Net.Http.Headers;
  17. namespace Emby.Server.Implementations.HttpServer
  18. {
  19. public class FileWriter : IHttpResult
  20. {
  21. private static readonly CultureInfo UsCulture = CultureInfo.ReadOnly(new CultureInfo("en-US"));
  22. private static readonly string[] _skipLogExtensions = {
  23. ".js",
  24. ".html",
  25. ".css"
  26. };
  27. private readonly IStreamHelper _streamHelper;
  28. private readonly ILogger _logger;
  29. private readonly IFileSystem _fileSystem;
  30. /// <summary>
  31. /// The _options
  32. /// </summary>
  33. private readonly IDictionary<string, string> _options = new Dictionary<string, string>();
  34. /// <summary>
  35. /// The _requested ranges
  36. /// </summary>
  37. private List<KeyValuePair<long, long?>> _requestedRanges;
  38. public FileWriter(string path, string contentType, string rangeHeader, ILogger logger, IFileSystem fileSystem, IStreamHelper streamHelper)
  39. {
  40. if (string.IsNullOrEmpty(contentType))
  41. {
  42. throw new ArgumentNullException(nameof(contentType));
  43. }
  44. _streamHelper = streamHelper;
  45. _fileSystem = fileSystem;
  46. Path = path;
  47. _logger = logger;
  48. RangeHeader = rangeHeader;
  49. Headers[HeaderNames.ContentType] = contentType;
  50. TotalContentLength = fileSystem.GetFileInfo(path).Length;
  51. Headers[HeaderNames.AcceptRanges] = "bytes";
  52. if (string.IsNullOrWhiteSpace(rangeHeader))
  53. {
  54. Headers[HeaderNames.ContentLength] = TotalContentLength.ToString(CultureInfo.InvariantCulture);
  55. StatusCode = HttpStatusCode.OK;
  56. }
  57. else
  58. {
  59. StatusCode = HttpStatusCode.PartialContent;
  60. SetRangeValues();
  61. }
  62. FileShare = FileShare.Read;
  63. Cookies = new List<Cookie>();
  64. }
  65. private string RangeHeader { get; set; }
  66. private bool IsHeadRequest { get; set; }
  67. private long RangeStart { get; set; }
  68. private long RangeEnd { get; set; }
  69. private long RangeLength { get; set; }
  70. public long TotalContentLength { get; set; }
  71. public Action OnComplete { get; set; }
  72. public Action OnError { get; set; }
  73. public List<Cookie> Cookies { get; private set; }
  74. public FileShare FileShare { get; set; }
  75. /// <summary>
  76. /// Gets the options.
  77. /// </summary>
  78. /// <value>The options.</value>
  79. public IDictionary<string, string> Headers => _options;
  80. public string Path { get; set; }
  81. /// <summary>
  82. /// Gets the requested ranges.
  83. /// </summary>
  84. /// <value>The requested ranges.</value>
  85. protected List<KeyValuePair<long, long?>> RequestedRanges
  86. {
  87. get
  88. {
  89. if (_requestedRanges == null)
  90. {
  91. _requestedRanges = new List<KeyValuePair<long, long?>>();
  92. // Example: bytes=0-,32-63
  93. var ranges = RangeHeader.Split('=')[1].Split(',');
  94. foreach (var range in ranges)
  95. {
  96. var vals = range.Split('-');
  97. long start = 0;
  98. long? end = null;
  99. if (!string.IsNullOrEmpty(vals[0]))
  100. {
  101. start = long.Parse(vals[0], UsCulture);
  102. }
  103. if (!string.IsNullOrEmpty(vals[1]))
  104. {
  105. end = long.Parse(vals[1], UsCulture);
  106. }
  107. _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
  108. }
  109. }
  110. return _requestedRanges;
  111. }
  112. }
  113. public string ContentType { get; set; }
  114. public IRequest RequestContext { get; set; }
  115. public object Response { get; set; }
  116. public int Status { get; set; }
  117. public HttpStatusCode StatusCode
  118. {
  119. get => (HttpStatusCode)Status;
  120. set => Status = (int)value;
  121. }
  122. /// <summary>
  123. /// Sets the range values.
  124. /// </summary>
  125. private void SetRangeValues()
  126. {
  127. var requestedRange = RequestedRanges[0];
  128. // If the requested range is "0-", we can optimize by just doing a stream copy
  129. if (!requestedRange.Value.HasValue)
  130. {
  131. RangeEnd = TotalContentLength - 1;
  132. }
  133. else
  134. {
  135. RangeEnd = requestedRange.Value.Value;
  136. }
  137. RangeStart = requestedRange.Key;
  138. RangeLength = 1 + RangeEnd - RangeStart;
  139. // Content-Length is the length of what we're serving, not the original content
  140. var lengthString = RangeLength.ToString(CultureInfo.InvariantCulture);
  141. Headers[HeaderNames.ContentLength] = lengthString;
  142. var rangeString = $"bytes {RangeStart}-{RangeEnd}/{TotalContentLength}";
  143. Headers[HeaderNames.ContentRange] = rangeString;
  144. _logger.LogDebug("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString);
  145. }
  146. public async Task WriteToAsync(HttpResponse response, CancellationToken cancellationToken)
  147. {
  148. try
  149. {
  150. // Headers only
  151. if (IsHeadRequest)
  152. {
  153. return;
  154. }
  155. var path = Path;
  156. var offset = RangeStart;
  157. var count = RangeLength;
  158. if (string.IsNullOrWhiteSpace(RangeHeader) || RangeStart <= 0 && RangeEnd >= TotalContentLength - 1)
  159. {
  160. var extension = System.IO.Path.GetExtension(path);
  161. if (extension == null || !_skipLogExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
  162. {
  163. _logger.LogDebug("Transmit file {0}", path);
  164. }
  165. offset = 0;
  166. count = 0;
  167. }
  168. await TransmitFile(response.Body, path, offset, count, FileShare, cancellationToken).ConfigureAwait(false);
  169. }
  170. finally
  171. {
  172. OnComplete?.Invoke();
  173. }
  174. }
  175. public async Task TransmitFile(Stream stream, string path, long offset, long count, FileShare fileShare, CancellationToken cancellationToken)
  176. {
  177. var fileOptions = FileOptions.SequentialScan;
  178. // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
  179. if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  180. {
  181. fileOptions |= FileOptions.Asynchronous;
  182. }
  183. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, fileShare, IODefaults.FileStreamBufferSize, fileOptions))
  184. {
  185. if (offset > 0)
  186. {
  187. fs.Position = offset;
  188. }
  189. if (count > 0)
  190. {
  191. await _streamHelper.CopyToAsync(fs, stream, count, cancellationToken).ConfigureAwait(false);
  192. }
  193. else
  194. {
  195. await fs.CopyToAsync(stream, IODefaults.CopyToBufferSize, cancellationToken).ConfigureAwait(false);
  196. }
  197. }
  198. }
  199. }
  200. }