2
0

FileWriter.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. /// <summary>
  26. /// The _options
  27. /// </summary>
  28. private readonly IDictionary<string, string> _options = new Dictionary<string, string>();
  29. /// <summary>
  30. /// Gets the options.
  31. /// </summary>
  32. /// <value>The options.</value>
  33. public IDictionary<string, string> Headers
  34. {
  35. get { return _options; }
  36. }
  37. public string Path { get; set; }
  38. public FileWriter(string path, string contentType, string rangeHeader, ILogger logger, IFileSystem fileSystem)
  39. {
  40. if (string.IsNullOrEmpty(contentType))
  41. {
  42. throw new ArgumentNullException("contentType");
  43. }
  44. Path = path;
  45. Logger = logger;
  46. RangeHeader = rangeHeader;
  47. Headers["Content-Type"] = contentType;
  48. TotalContentLength = fileSystem.GetFileInfo(path).Length;
  49. if (string.IsNullOrWhiteSpace(rangeHeader))
  50. {
  51. Headers["Content-Length"] = TotalContentLength.ToString(UsCulture);
  52. StatusCode = HttpStatusCode.OK;
  53. }
  54. else
  55. {
  56. Headers["Accept-Ranges"] = "bytes";
  57. StatusCode = HttpStatusCode.PartialContent;
  58. SetRangeValues();
  59. }
  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. Headers["Content-Length"] = RangeLength.ToString(UsCulture);
  81. Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
  82. }
  83. /// <summary>
  84. /// The _requested ranges
  85. /// </summary>
  86. private List<KeyValuePair<long, long?>> _requestedRanges;
  87. /// <summary>
  88. /// Gets the requested ranges.
  89. /// </summary>
  90. /// <value>The requested ranges.</value>
  91. protected List<KeyValuePair<long, long?>> RequestedRanges
  92. {
  93. get
  94. {
  95. if (_requestedRanges == null)
  96. {
  97. _requestedRanges = new List<KeyValuePair<long, long?>>();
  98. // Example: bytes=0-,32-63
  99. var ranges = RangeHeader.Split('=')[1].Split(',');
  100. foreach (var range in ranges)
  101. {
  102. var vals = range.Split('-');
  103. long start = 0;
  104. long? end = null;
  105. if (!string.IsNullOrEmpty(vals[0]))
  106. {
  107. start = long.Parse(vals[0], UsCulture);
  108. }
  109. if (!string.IsNullOrEmpty(vals[1]))
  110. {
  111. end = long.Parse(vals[1], UsCulture);
  112. }
  113. _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
  114. }
  115. }
  116. return _requestedRanges;
  117. }
  118. }
  119. public async Task WriteToAsync(IResponse response, CancellationToken cancellationToken)
  120. {
  121. try
  122. {
  123. // Headers only
  124. if (IsHeadRequest)
  125. {
  126. return;
  127. }
  128. if (string.IsNullOrWhiteSpace(RangeHeader) || (RangeStart <= 0 && RangeEnd >= TotalContentLength - 1))
  129. {
  130. Logger.Info("Transmit file {0}", Path);
  131. await response.TransmitFile(Path, 0, 0, cancellationToken).ConfigureAwait(false);
  132. return;
  133. }
  134. await response.TransmitFile(Path, RangeStart, RangeEnd, cancellationToken).ConfigureAwait(false);
  135. }
  136. finally
  137. {
  138. if (OnComplete != null)
  139. {
  140. OnComplete();
  141. }
  142. }
  143. }
  144. public string ContentType { get; set; }
  145. public IRequest RequestContext { get; set; }
  146. public object Response { get; set; }
  147. public int Status { get; set; }
  148. public HttpStatusCode StatusCode
  149. {
  150. get { return (HttpStatusCode)Status; }
  151. set { Status = (int)value; }
  152. }
  153. public string StatusDescription { get; set; }
  154. }
  155. }