2
0

FileWriter.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. using Microsoft.Net.Http.Headers;
  13. namespace Emby.Server.Implementations.HttpServer
  14. {
  15. public class FileWriter : IHttpResult
  16. {
  17. private ILogger Logger { get; set; }
  18. public IFileSystem FileSystem { get; }
  19. private string RangeHeader { get; set; }
  20. private bool IsHeadRequest { get; set; }
  21. private long RangeStart { get; set; }
  22. private long RangeEnd { get; set; }
  23. private long RangeLength { get; set; }
  24. public long TotalContentLength { get; set; }
  25. public Action OnComplete { get; set; }
  26. public Action OnError { get; set; }
  27. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  28. public List<Cookie> Cookies { get; private set; }
  29. public FileShareMode FileShare { get; set; }
  30. /// <summary>
  31. /// The _options
  32. /// </summary>
  33. private readonly IDictionary<string, string> _options = new Dictionary<string, string>();
  34. /// <summary>
  35. /// Gets the options.
  36. /// </summary>
  37. /// <value>The options.</value>
  38. public IDictionary<string, string> Headers => _options;
  39. public string Path { get; set; }
  40. public FileWriter(string path, string contentType, string rangeHeader, ILogger logger, IFileSystem fileSystem)
  41. {
  42. if (string.IsNullOrEmpty(contentType))
  43. {
  44. throw new ArgumentNullException(nameof(contentType));
  45. }
  46. Path = path;
  47. Logger = logger;
  48. FileSystem = fileSystem;
  49. RangeHeader = rangeHeader;
  50. Headers[HeaderNames.ContentType] = contentType;
  51. TotalContentLength = fileSystem.GetFileInfo(path).Length;
  52. Headers[HeaderNames.AcceptRanges] = "bytes";
  53. if (string.IsNullOrWhiteSpace(rangeHeader))
  54. {
  55. StatusCode = HttpStatusCode.OK;
  56. }
  57. else
  58. {
  59. StatusCode = HttpStatusCode.PartialContent;
  60. SetRangeValues();
  61. }
  62. FileShare = FileShareMode.Read;
  63. Cookies = new List<Cookie>();
  64. }
  65. /// <summary>
  66. /// Sets the range values.
  67. /// </summary>
  68. private void SetRangeValues()
  69. {
  70. var requestedRange = RequestedRanges[0];
  71. // If the requested range is "0-", we can optimize by just doing a stream copy
  72. if (!requestedRange.Value.HasValue)
  73. {
  74. RangeEnd = TotalContentLength - 1;
  75. }
  76. else
  77. {
  78. RangeEnd = requestedRange.Value.Value;
  79. }
  80. RangeStart = requestedRange.Key;
  81. RangeLength = 1 + RangeEnd - RangeStart;
  82. // Content-Length is the length of what we're serving, not the original content
  83. var lengthString = RangeLength.ToString(UsCulture);
  84. var rangeString = $"bytes {RangeStart}-{RangeEnd}/{TotalContentLength}";
  85. Headers[HeaderNames.ContentRange] = rangeString;
  86. Logger.LogInformation("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. private string[] SkipLogExtensions = new string[]
  125. {
  126. ".js",
  127. ".html",
  128. ".css"
  129. };
  130. public async Task WriteToAsync(IResponse response, CancellationToken cancellationToken)
  131. {
  132. try
  133. {
  134. // Headers only
  135. if (IsHeadRequest)
  136. {
  137. return;
  138. }
  139. var path = Path;
  140. if (string.IsNullOrWhiteSpace(RangeHeader) || (RangeStart <= 0 && RangeEnd >= TotalContentLength - 1))
  141. {
  142. var extension = System.IO.Path.GetExtension(path);
  143. if (extension == null || !SkipLogExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
  144. {
  145. Logger.LogDebug("Transmit file {0}", path);
  146. }
  147. //var count = FileShare == FileShareMode.ReadWrite ? TotalContentLength : 0;
  148. // TODO not DI friendly lol
  149. await response.TransmitFile(path, 0, 0, FileShare, FileSystem, new StreamHelper(), cancellationToken).ConfigureAwait(false);
  150. return;
  151. }
  152. // TODO not DI friendly lol
  153. await response.TransmitFile(path, RangeStart, RangeLength, FileShare, FileSystem, new StreamHelper(), cancellationToken).ConfigureAwait(false);
  154. }
  155. finally
  156. {
  157. if (OnComplete != null)
  158. {
  159. OnComplete();
  160. }
  161. }
  162. }
  163. public string ContentType { get; set; }
  164. public IRequest RequestContext { get; set; }
  165. public object Response { get; set; }
  166. public int Status { get; set; }
  167. public HttpStatusCode StatusCode
  168. {
  169. get => (HttpStatusCode)Status;
  170. set => Status = (int)value;
  171. }
  172. public string StatusDescription { get; set; }
  173. }
  174. }