FileWriter.cs 6.2 KB

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