FileWriter.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. if (string.IsNullOrWhiteSpace(rangeHeader))
  51. {
  52. Headers["Content-Length"] = TotalContentLength.ToString(UsCulture);
  53. StatusCode = HttpStatusCode.OK;
  54. }
  55. else
  56. {
  57. Headers["Accept-Ranges"] = "bytes";
  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. Headers["Content-Length"] = RangeLength.ToString(UsCulture);
  83. Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
  84. }
  85. /// <summary>
  86. /// The _requested ranges
  87. /// </summary>
  88. private List<KeyValuePair<long, long?>> _requestedRanges;
  89. /// <summary>
  90. /// Gets the requested ranges.
  91. /// </summary>
  92. /// <value>The requested ranges.</value>
  93. protected List<KeyValuePair<long, long?>> RequestedRanges
  94. {
  95. get
  96. {
  97. if (_requestedRanges == null)
  98. {
  99. _requestedRanges = new List<KeyValuePair<long, long?>>();
  100. // Example: bytes=0-,32-63
  101. var ranges = RangeHeader.Split('=')[1].Split(',');
  102. foreach (var range in ranges)
  103. {
  104. var vals = range.Split('-');
  105. long start = 0;
  106. long? end = null;
  107. if (!string.IsNullOrEmpty(vals[0]))
  108. {
  109. start = long.Parse(vals[0], UsCulture);
  110. }
  111. if (!string.IsNullOrEmpty(vals[1]))
  112. {
  113. end = long.Parse(vals[1], UsCulture);
  114. }
  115. _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
  116. }
  117. }
  118. return _requestedRanges;
  119. }
  120. }
  121. public async Task WriteToAsync(IResponse response, CancellationToken cancellationToken)
  122. {
  123. try
  124. {
  125. // Headers only
  126. if (IsHeadRequest)
  127. {
  128. return;
  129. }
  130. if (string.IsNullOrWhiteSpace(RangeHeader) || (RangeStart <= 0 && RangeEnd >= TotalContentLength - 1))
  131. {
  132. Logger.Info("Transmit file {0}", Path);
  133. await response.TransmitFile(Path, 0, 0, FileShare, cancellationToken).ConfigureAwait(false);
  134. return;
  135. }
  136. await response.TransmitFile(Path, RangeStart, RangeLength, FileShare, cancellationToken).ConfigureAwait(false);
  137. }
  138. finally
  139. {
  140. if (OnComplete != null)
  141. {
  142. OnComplete();
  143. }
  144. }
  145. }
  146. public string ContentType { get; set; }
  147. public IRequest RequestContext { get; set; }
  148. public object Response { get; set; }
  149. public int Status { get; set; }
  150. public HttpStatusCode StatusCode
  151. {
  152. get { return (HttpStatusCode)Status; }
  153. set { Status = (int)value; }
  154. }
  155. public string StatusDescription { get; set; }
  156. }
  157. }