FileWriter.cs 6.8 KB

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