FileWriter.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. // TODO
  55. //Headers["Content-Length"] = TotalContentLength.ToString(UsCulture);
  56. StatusCode = HttpStatusCode.OK;
  57. }
  58. else
  59. {
  60. StatusCode = HttpStatusCode.PartialContent;
  61. SetRangeValues();
  62. }
  63. FileShare = FileShareMode.Read;
  64. Cookies = new List<Cookie>();
  65. }
  66. /// <summary>
  67. /// Sets the range values.
  68. /// </summary>
  69. private void SetRangeValues()
  70. {
  71. var requestedRange = RequestedRanges[0];
  72. // If the requested range is "0-", we can optimize by just doing a stream copy
  73. if (!requestedRange.Value.HasValue)
  74. {
  75. RangeEnd = TotalContentLength - 1;
  76. }
  77. else
  78. {
  79. RangeEnd = requestedRange.Value.Value;
  80. }
  81. RangeStart = requestedRange.Key;
  82. RangeLength = 1 + RangeEnd - RangeStart;
  83. // Content-Length is the length of what we're serving, not the original content
  84. var lengthString = RangeLength.ToString(UsCulture);
  85. // TODO Headers["Content-Length"] = lengthString;
  86. var rangeString = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
  87. Headers["Content-Range"] = rangeString;
  88. Logger.LogInformation("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString);
  89. }
  90. /// <summary>
  91. /// The _requested ranges
  92. /// </summary>
  93. private List<KeyValuePair<long, long?>> _requestedRanges;
  94. /// <summary>
  95. /// Gets the requested ranges.
  96. /// </summary>
  97. /// <value>The requested ranges.</value>
  98. protected List<KeyValuePair<long, long?>> RequestedRanges
  99. {
  100. get
  101. {
  102. if (_requestedRanges == null)
  103. {
  104. _requestedRanges = new List<KeyValuePair<long, long?>>();
  105. // Example: bytes=0-,32-63
  106. var ranges = RangeHeader.Split('=')[1].Split(',');
  107. foreach (var range in ranges)
  108. {
  109. var vals = range.Split('-');
  110. long start = 0;
  111. long? end = null;
  112. if (!string.IsNullOrEmpty(vals[0]))
  113. {
  114. start = long.Parse(vals[0], UsCulture);
  115. }
  116. if (!string.IsNullOrEmpty(vals[1]))
  117. {
  118. end = long.Parse(vals[1], UsCulture);
  119. }
  120. _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
  121. }
  122. }
  123. return _requestedRanges;
  124. }
  125. }
  126. private string[] SkipLogExtensions = new string[]
  127. {
  128. ".js",
  129. ".html",
  130. ".css"
  131. };
  132. public async Task WriteToAsync(IResponse response, CancellationToken cancellationToken)
  133. {
  134. try
  135. {
  136. // Headers only
  137. if (IsHeadRequest)
  138. {
  139. return;
  140. }
  141. var path = Path;
  142. if (string.IsNullOrWhiteSpace(RangeHeader) || (RangeStart <= 0 && RangeEnd >= TotalContentLength - 1))
  143. {
  144. var extension = System.IO.Path.GetExtension(path);
  145. if (extension == null || !SkipLogExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
  146. {
  147. Logger.LogDebug("Transmit file {0}", path);
  148. }
  149. //var count = FileShare == FileShareMode.ReadWrite ? TotalContentLength : 0;
  150. // TODO not DI friendly lol
  151. await response.TransmitFile(path, 0, 0, FileShare, FileSystem, new StreamHelper(), cancellationToken).ConfigureAwait(false);
  152. return;
  153. }
  154. // TODO not DI friendly lol
  155. await response.TransmitFile(path, RangeStart, RangeLength, FileShare, FileSystem, new StreamHelper(), cancellationToken).ConfigureAwait(false);
  156. }
  157. finally
  158. {
  159. if (OnComplete != null)
  160. {
  161. OnComplete();
  162. }
  163. }
  164. }
  165. public string ContentType { get; set; }
  166. public IRequest RequestContext { get; set; }
  167. public object Response { get; set; }
  168. public int Status { get; set; }
  169. public HttpStatusCode StatusCode
  170. {
  171. get => (HttpStatusCode)Status;
  172. set => Status = (int)value;
  173. }
  174. public string StatusDescription { get; set; }
  175. }
  176. }