FileWriter.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 Emby.Server.Implementations.IO;
  9. using MediaBrowser.Model.IO;
  10. using MediaBrowser.Model.Services;
  11. using Microsoft.Extensions.Logging;
  12. namespace Emby.Server.Implementations.HttpServer
  13. {
  14. public class FileWriter : IHttpResult
  15. {
  16. private ILogger Logger { get; set; }
  17. public IFileSystem FileSystem { get; }
  18. private string RangeHeader { get; set; }
  19. private bool IsHeadRequest { get; set; }
  20. private long RangeStart { get; set; }
  21. private long RangeEnd { get; set; }
  22. private long RangeLength { get; set; }
  23. public long TotalContentLength { get; set; }
  24. public Action OnComplete { get; set; }
  25. public Action OnError { get; set; }
  26. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  27. public List<Cookie> Cookies { get; private set; }
  28. public FileShareMode FileShare { get; set; }
  29. /// <summary>
  30. /// The _options
  31. /// </summary>
  32. private readonly IDictionary<string, string> _options = new Dictionary<string, string>();
  33. /// <summary>
  34. /// Gets the options.
  35. /// </summary>
  36. /// <value>The options.</value>
  37. public IDictionary<string, string> Headers => _options;
  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(nameof(contentType));
  44. }
  45. Path = path;
  46. Logger = logger;
  47. FileSystem = fileSystem;
  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. 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. var rangeString = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
  84. Headers["Content-Range"] = rangeString;
  85. Logger.LogInformation("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString);
  86. }
  87. /// <summary>
  88. /// The _requested ranges
  89. /// </summary>
  90. private List<KeyValuePair<long, long?>> _requestedRanges;
  91. /// <summary>
  92. /// Gets the requested ranges.
  93. /// </summary>
  94. /// <value>The requested ranges.</value>
  95. protected List<KeyValuePair<long, long?>> RequestedRanges
  96. {
  97. get
  98. {
  99. if (_requestedRanges == null)
  100. {
  101. _requestedRanges = new List<KeyValuePair<long, long?>>();
  102. // Example: bytes=0-,32-63
  103. var ranges = RangeHeader.Split('=')[1].Split(',');
  104. foreach (var range in ranges)
  105. {
  106. var vals = range.Split('-');
  107. long start = 0;
  108. long? end = null;
  109. if (!string.IsNullOrEmpty(vals[0]))
  110. {
  111. start = long.Parse(vals[0], UsCulture);
  112. }
  113. if (!string.IsNullOrEmpty(vals[1]))
  114. {
  115. end = long.Parse(vals[1], UsCulture);
  116. }
  117. _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
  118. }
  119. }
  120. return _requestedRanges;
  121. }
  122. }
  123. private string[] SkipLogExtensions = new string[]
  124. {
  125. ".js",
  126. ".html",
  127. ".css"
  128. };
  129. public async Task WriteToAsync(IResponse response, CancellationToken cancellationToken)
  130. {
  131. try
  132. {
  133. // Headers only
  134. if (IsHeadRequest)
  135. {
  136. return;
  137. }
  138. var path = Path;
  139. if (string.IsNullOrWhiteSpace(RangeHeader) || (RangeStart <= 0 && RangeEnd >= TotalContentLength - 1))
  140. {
  141. var extension = System.IO.Path.GetExtension(path);
  142. if (extension == null || !SkipLogExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
  143. {
  144. Logger.LogDebug("Transmit file {0}", path);
  145. }
  146. //var count = FileShare == FileShareMode.ReadWrite ? TotalContentLength : 0;
  147. // TODO not DI friendly lol
  148. await response.TransmitFile(path, 0, 0, FileShare, FileSystem, new StreamHelper(), cancellationToken).ConfigureAwait(false);
  149. return;
  150. }
  151. // TODO not DI friendly lol
  152. await response.TransmitFile(path, RangeStart, RangeLength, FileShare, FileSystem, new StreamHelper(), 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 => (HttpStatusCode)Status;
  169. set => Status = (int)value;
  170. }
  171. public string StatusDescription { get; set; }
  172. }
  173. }