FileWriter.cs 6.7 KB

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