FileWriter.cs 8.0 KB

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