jellyfin-server/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs

222 lines
7.1 KiB
C#
Raw Normal View History

using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
2016-10-25 19:02:04 +00:00
using System.Threading;
2016-07-15 17:13:55 +00:00
using System.Threading.Tasks;
2016-10-25 19:02:04 +00:00
using MediaBrowser.Model.Services;
2016-11-08 18:44:23 +00:00
namespace Emby.Server.Implementations.HttpServer
{
2016-10-25 19:02:04 +00:00
public class RangeRequestWriter : IAsyncStreamWriter, IHttpResult
{
/// <summary>
/// Gets or sets the source stream.
/// </summary>
/// <value>The source stream.</value>
2013-03-13 03:57:54 +00:00
private Stream SourceStream { get; set; }
private string RangeHeader { get; set; }
2013-03-13 03:57:54 +00:00
private bool IsHeadRequest { get; set; }
private long RangeStart { get; set; }
private long RangeEnd { get; set; }
private long RangeLength { get; set; }
private long TotalContentLength { get; set; }
2014-09-03 02:30:24 +00:00
public Action OnComplete { get; set; }
2015-07-18 18:07:03 +00:00
private readonly ILogger _logger;
2014-08-29 12:14:41 +00:00
2016-07-27 17:11:25 +00:00
private const int BufferSize = 81920;
2015-07-31 20:38:08 +00:00
/// <summary>
/// The _options
/// </summary>
private readonly Dictionary<string, string> _options = new Dictionary<string, string>();
/// <summary>
/// The us culture
/// </summary>
private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
/// <summary>
/// Additional HTTP Headers
/// </summary>
/// <value>The headers.</value>
public IDictionary<string, string> Headers => _options;
/// <summary>
/// Initializes a new instance of the <see cref="StreamWriter" /> class.
/// </summary>
/// <param name="rangeHeader">The range header.</param>
/// <param name="source">The source.</param>
/// <param name="contentType">Type of the content.</param>
2013-03-13 03:57:54 +00:00
/// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
2018-09-12 17:26:21 +00:00
public RangeRequestWriter(string rangeHeader, long contentLength, Stream source, string contentType, bool isHeadRequest, ILogger logger)
{
if (string.IsNullOrEmpty(contentType))
{
throw new ArgumentNullException(nameof(contentType));
}
RangeHeader = rangeHeader;
SourceStream = source;
2013-03-13 03:57:54 +00:00
IsHeadRequest = isHeadRequest;
2015-07-18 18:07:03 +00:00
this._logger = logger;
ContentType = contentType;
2016-10-25 19:02:04 +00:00
Headers["Content-Type"] = contentType;
Headers["Accept-Ranges"] = "bytes";
StatusCode = HttpStatusCode.PartialContent;
2018-09-12 17:26:21 +00:00
SetRangeValues(contentLength);
}
/// <summary>
/// Sets the range values.
/// </summary>
2018-09-12 17:26:21 +00:00
private void SetRangeValues(long contentLength)
{
2013-09-18 02:43:34 +00:00
var requestedRange = RequestedRanges[0];
2018-09-12 17:26:21 +00:00
TotalContentLength = contentLength;
// If the requested range is "0-", we can optimize by just doing a stream copy
if (!requestedRange.Value.HasValue)
{
RangeEnd = TotalContentLength - 1;
}
else
{
RangeEnd = requestedRange.Value.Value;
}
RangeStart = requestedRange.Key;
RangeLength = 1 + RangeEnd - RangeStart;
// Content-Length is the length of what we're serving, not the original content
2016-10-25 19:02:04 +00:00
Headers["Content-Length"] = RangeLength.ToString(UsCulture);
Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
2018-09-12 17:26:21 +00:00
if (RangeStart > 0 && SourceStream.CanSeek)
{
SourceStream.Position = RangeStart;
}
}
/// <summary>
/// The _requested ranges
/// </summary>
private List<KeyValuePair<long, long?>> _requestedRanges;
/// <summary>
/// Gets the requested ranges.
/// </summary>
/// <value>The requested ranges.</value>
protected List<KeyValuePair<long, long?>> RequestedRanges
{
get
{
if (_requestedRanges == null)
{
_requestedRanges = new List<KeyValuePair<long, long?>>();
// Example: bytes=0-,32-63
var ranges = RangeHeader.Split('=')[1].Split(',');
foreach (var range in ranges)
{
var vals = range.Split('-');
long start = 0;
long? end = null;
if (!string.IsNullOrEmpty(vals[0]))
{
start = long.Parse(vals[0], UsCulture);
}
if (!string.IsNullOrEmpty(vals[1]))
{
end = long.Parse(vals[1], UsCulture);
}
_requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
}
}
return _requestedRanges;
}
}
2016-10-25 19:02:04 +00:00
public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
2016-07-15 17:13:55 +00:00
{
try
{
// Headers only
if (IsHeadRequest)
{
return;
}
using (var source = SourceStream)
{
// If the requested range is "0-", we can optimize by just doing a stream copy
if (RangeEnd >= TotalContentLength - 1)
{
await source.CopyToAsync(responseStream, BufferSize).ConfigureAwait(false);
}
else
{
await CopyToInternalAsync(source, responseStream, RangeLength).ConfigureAwait(false);
}
}
}
finally
{
if (OnComplete != null)
{
OnComplete();
}
}
}
private static async Task CopyToInternalAsync(Stream source, Stream destination, long copyLength)
2016-07-15 17:13:55 +00:00
{
var array = new byte[BufferSize];
2017-05-05 17:55:38 +00:00
int bytesRead;
while ((bytesRead = await source.ReadAsync(array, 0, array.Length).ConfigureAwait(false)) != 0)
2016-07-15 17:13:55 +00:00
{
2017-05-05 17:55:38 +00:00
if (bytesRead == 0)
{
break;
}
var bytesToCopy = Math.Min(bytesRead, copyLength);
2016-07-15 17:13:55 +00:00
await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToCopy)).ConfigureAwait(false);
copyLength -= bytesToCopy;
if (copyLength <= 0)
{
break;
}
}
}
public string ContentType { get; set; }
2013-12-07 15:52:38 +00:00
public IRequest RequestContext { get; set; }
public object Response { get; set; }
2013-03-13 03:57:54 +00:00
public int Status { get; set; }
public HttpStatusCode StatusCode
{
get => (HttpStatusCode)Status;
set => Status = (int)value;
}
}
}