forked from aspnet/AspNetWebStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathByteRangeStreamContent.cs
More file actions
222 lines (205 loc) · 10.9 KB
/
ByteRangeStreamContent.cs
File metadata and controls
222 lines (205 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http.Internal;
using System.Threading.Tasks;
using System.Web.Http;
namespace System.Net.Http
{
/// <summary>
/// <see cref="HttpContent"/> implementation which provides a byte range view over a stream used to generate HTTP
/// 206 (Partial Content) byte range responses. The <see cref="ByteRangeStreamContent"/> supports one or more
/// byte ranges regardless of whether the ranges are consecutive or not. If there is only one range then a
/// single partial response body containing a Content-Range header is generated. If there are more than one
/// ranges then a multipart/byteranges response is generated where each body part contains a range indicated
/// by the associated Content-Range header field.
/// </summary>
public class ByteRangeStreamContent : HttpContent
{
private const string SupportedRangeUnit = "bytes";
private const string ByteRangesContentSubtype = "byteranges";
private const int DefaultBufferSize = 4096;
private const int MinBufferSize = 1;
private readonly Stream _content;
private readonly long _start;
private readonly HttpContent _byteRangeContent;
private bool _disposed;
/// <summary>
/// <see cref="HttpContent"/> implementation which provides a byte range view over a stream used to generate HTTP
/// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend
/// of the selected resource represented by the <paramref name="content"/> parameter then an
/// <see cref="InvalidByteRangeException"/> is thrown indicating the valid Content-Range of the content.
/// </summary>
/// <param name="content">The stream over which to generate a byte range view.</param>
/// <param name="range">The range or ranges, typically obtained from the Range HTTP request header field.</param>
/// <param name="mediaType">The media type of the content stream.</param>
public ByteRangeStreamContent(Stream content, RangeHeaderValue range, string mediaType)
: this(content, range, new MediaTypeHeaderValue(mediaType), DefaultBufferSize)
{
}
/// <summary>
/// <see cref="HttpContent"/> implementation which provides a byte range view over a stream used to generate HTTP
/// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend
/// of the selected resource represented by the <paramref name="content"/> parameter then an
/// <see cref="InvalidByteRangeException"/> is thrown indicating the valid Content-Range of the content.
/// </summary>
/// <param name="content">The stream over which to generate a byte range view.</param>
/// <param name="range">The range or ranges, typically obtained from the Range HTTP request header field.</param>
/// <param name="mediaType">The media type of the content stream.</param>
/// <param name="bufferSize">The buffer size used when copying the content stream.</param>
public ByteRangeStreamContent(Stream content, RangeHeaderValue range, string mediaType, int bufferSize)
: this(content, range, new MediaTypeHeaderValue(mediaType), bufferSize)
{
}
/// <summary>
/// <see cref="HttpContent"/> implementation which provides a byte range view over a stream used to generate HTTP
/// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend
/// of the selected resource represented by the <paramref name="content"/> parameter then an
/// <see cref="InvalidByteRangeException"/> is thrown indicating the valid Content-Range of the content.
/// </summary>
/// <param name="content">The stream over which to generate a byte range view.</param>
/// <param name="range">The range or ranges, typically obtained from the Range HTTP request header field.</param>
/// <param name="mediaType">The media type of the content stream.</param>
public ByteRangeStreamContent(Stream content, RangeHeaderValue range, MediaTypeHeaderValue mediaType)
: this(content, range, mediaType, DefaultBufferSize)
{
}
/// <summary>
/// <see cref="HttpContent"/> implementation which provides a byte range view over a stream used to generate HTTP
/// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend
/// of the selected resource represented by the <paramref name="content"/> parameter then an
/// <see cref="InvalidByteRangeException"/> is thrown indicating the valid Content-Range of the content.
/// </summary>
/// <param name="content">The stream over which to generate a byte range view.</param>
/// <param name="range">The range or ranges, typically obtained from the Range HTTP request header field.</param>
/// <param name="mediaType">The media type of the content stream.</param>
/// <param name="bufferSize">The buffer size used when copying the content stream.</param>
public ByteRangeStreamContent(Stream content, RangeHeaderValue range, MediaTypeHeaderValue mediaType, int bufferSize)
{
if (content == null)
{
throw Error.ArgumentNull("content");
}
if (!content.CanSeek)
{
throw Error.Argument("content", Properties.Resources.ByteRangeStreamNotSeekable, typeof(ByteRangeStreamContent).Name);
}
if (range == null)
{
throw Error.ArgumentNull("range");
}
if (mediaType == null)
{
throw Error.ArgumentNull("mediaType");
}
if (bufferSize < MinBufferSize)
{
throw Error.ArgumentMustBeGreaterThanOrEqualTo("bufferSize", bufferSize, MinBufferSize);
}
if (!range.Unit.Equals(SupportedRangeUnit, StringComparison.OrdinalIgnoreCase))
{
throw Error.Argument("range", Properties.Resources.ByteRangeStreamContentNotBytesRange, range.Unit, SupportedRangeUnit);
}
try
{
// If we have more than one range then we use a multipart/byteranges content type as wrapper.
// Otherwise we use a non-multipart response.
if (range.Ranges.Count > 1)
{
// Create Multipart content and copy headers to this content
MultipartContent rangeContent = new MultipartContent(ByteRangesContentSubtype);
_byteRangeContent = rangeContent;
foreach (RangeItemHeaderValue rangeValue in range.Ranges)
{
try
{
ByteRangeStream rangeStream = new ByteRangeStream(content, rangeValue);
HttpContent rangeBodyPart = new StreamContent(rangeStream, bufferSize);
rangeBodyPart.Headers.ContentType = mediaType;
rangeBodyPart.Headers.ContentRange = rangeStream.ContentRange;
rangeContent.Add(rangeBodyPart);
}
catch (ArgumentOutOfRangeException)
{
// We ignore range errors until we check that we have at least one valid range
}
}
// If no overlapping ranges were found then stop
if (!rangeContent.Any())
{
ContentRangeHeaderValue actualContentRange = new ContentRangeHeaderValue(content.Length);
string msg = Error.Format(Properties.Resources.ByteRangeStreamNoneOverlap, range.ToString());
throw new InvalidByteRangeException(actualContentRange, msg);
}
}
else if (range.Ranges.Count == 1)
{
try
{
ByteRangeStream rangeStream = new ByteRangeStream(content, range.Ranges.First());
_byteRangeContent = new StreamContent(rangeStream, bufferSize);
_byteRangeContent.Headers.ContentType = mediaType;
_byteRangeContent.Headers.ContentRange = rangeStream.ContentRange;
}
catch (ArgumentOutOfRangeException)
{
ContentRangeHeaderValue actualContentRange = new ContentRangeHeaderValue(content.Length);
string msg = Error.Format(Properties.Resources.ByteRangeStreamNoOverlap, range.ToString());
throw new InvalidByteRangeException(actualContentRange, msg);
}
}
else
{
throw Error.Argument("range", Properties.Resources.ByteRangeStreamContentNoRanges);
}
// Copy headers from byte range content so that we get the right content type etc.
_byteRangeContent.Headers.CopyTo(Headers);
_content = content;
_start = content.Position;
}
catch
{
if (_byteRangeContent != null)
{
_byteRangeContent.Dispose();
}
throw;
}
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
// Reset stream to start position
_content.Position = _start;
// Copy result to output
return _byteRangeContent.CopyToAsync(stream);
}
protected override bool TryComputeLength(out long length)
{
long? contentLength = _byteRangeContent.Headers.ContentLength;
if (contentLength.HasValue)
{
length = contentLength.Value;
return true;
}
length = -1;
return false;
}
protected override void Dispose(bool disposing)
{
Contract.Assert(_byteRangeContent != null);
if (disposing)
{
if (!_disposed)
{
_byteRangeContent.Dispose();
_content.Dispose();
_disposed = true;
}
}
base.Dispose(disposing);
}
}
}