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