aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Net/Handlers/StaticFileHandler.cs
blob: bc367403b83af9713b5340f684ce8351fff199ca (plain)
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
using MediaBrowser.Common.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace MediaBrowser.Common.Net.Handlers
{
    public class StaticFileHandler : BaseHandler
    {
        public override bool HandlesRequest(HttpListenerRequest request)
        {
            return false;
        }

        private string _Path;
        public virtual string Path
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(_Path))
                {
                    return _Path;
                }

                return QueryString["path"];
            }
            set
            {
                _Path = value;
            }
        }

        private bool _SourceStreamEnsured = false;
        private Stream _SourceStream = null;
        private Stream SourceStream
        {
            get
            {
                EnsureSourceStream();
                return _SourceStream;
            }
        }

        private void EnsureSourceStream()
        {
            if (!_SourceStreamEnsured)
            {
                try
                {
                    _SourceStream = File.OpenRead(Path);
                }
                catch (FileNotFoundException ex)
                {
                    StatusCode = 404;
                    Logger.LogException(ex);
                }
                catch (DirectoryNotFoundException ex)
                {
                    StatusCode = 404;
                    Logger.LogException(ex);
                }
                catch (UnauthorizedAccessException ex)
                {
                    StatusCode = 403;
                    Logger.LogException(ex);
                }
                finally
                {
                    _SourceStreamEnsured = true;
                }
            }
        }

        protected override bool SupportsByteRangeRequests
        {
            get
            {
                return true;
            }
        }

        public override bool ShouldCompressResponse(string contentType)
        {
            // Can't compress these
            if (IsRangeRequest)
            {
                return false;
            }

            // Don't compress media
            if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            // It will take some work to support compression within this handler
            return false;
        }

        protected override long? GetTotalContentLength()
        {
            return SourceStream.Length;
        }

        protected override Task<DateTime?> GetLastDateModified()
        {
            DateTime? value = null;

            EnsureSourceStream();

            if (SourceStream != null)
            {
                value = File.GetLastWriteTimeUtc(Path);
            }

            return Task.FromResult<DateTime?>(value);
        }

        public override Task<string> GetContentType()
        {
            return Task.FromResult<string>(MimeTypes.GetMimeType(Path));
        }

        protected override Task PrepareResponse()
        {
            EnsureSourceStream();
            return Task.FromResult<object>(null);
        }

        protected override Task WriteResponseToOutputStream(Stream stream)
        {
            if (IsRangeRequest)
            {
                KeyValuePair<long, long?> requestedRange = RequestedRanges.First();

                // If the requested range is "0-" and we know the total length, we can optimize by avoiding having to buffer the content into memory
                if (requestedRange.Value == null && TotalContentLength != null)
                {
                    return ServeCompleteRangeRequest(requestedRange, stream);
                }
                else if (TotalContentLength.HasValue)
                {
                    // This will have to buffer a portion of the content into memory
                    return ServePartialRangeRequestWithKnownTotalContentLength(requestedRange, stream);
                }
                else
                {
                    // This will have to buffer the entire content into memory
                    return ServePartialRangeRequestWithUnknownTotalContentLength(requestedRange, stream);
                }
            }
            else
            {
                return SourceStream.CopyToAsync(stream);
            }
        }

        protected override void DisposeResponseStream()
        {
            base.DisposeResponseStream();

            if (SourceStream != null)
            {
                SourceStream.Dispose();
            }
        }

        /// <summary>
        /// Handles a range request of "bytes=0-"
        /// This will serve the complete content and add the content-range header
        /// </summary>
        private Task ServeCompleteRangeRequest(KeyValuePair<long, long?> requestedRange, Stream responseStream)
        {
            long totalContentLength = TotalContentLength.Value;

            long rangeStart = requestedRange.Key;
            long rangeEnd = totalContentLength - 1;
            long rangeLength = 1 + rangeEnd - rangeStart;

            // Content-Length is the length of what we're serving, not the original content
            HttpListenerContext.Response.ContentLength64 = rangeLength;
            HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);

            if (rangeStart > 0)
            {
                SourceStream.Position = rangeStart;
            }

            return SourceStream.CopyToAsync(responseStream);
        }

        /// <summary>
        /// Serves a partial range request where the total content length is not known
        /// </summary>
        private async Task ServePartialRangeRequestWithUnknownTotalContentLength(KeyValuePair<long, long?> requestedRange, Stream responseStream)
        {
            // Read the entire stream so that we can determine the length
            byte[] bytes = await ReadBytes(SourceStream, 0, null).ConfigureAwait(false);

            long totalContentLength = bytes.LongLength;

            long rangeStart = requestedRange.Key;
            long rangeEnd = requestedRange.Value ?? (totalContentLength - 1);
            long rangeLength = 1 + rangeEnd - rangeStart;

            // Content-Length is the length of what we're serving, not the original content
            HttpListenerContext.Response.ContentLength64 = rangeLength;
            HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);

            await responseStream.WriteAsync(bytes, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength)).ConfigureAwait(false);
        }

        /// <summary>
        /// Serves a partial range request where the total content length is already known
        /// </summary>
        private async Task ServePartialRangeRequestWithKnownTotalContentLength(KeyValuePair<long, long?> requestedRange, Stream responseStream)
        {
            long totalContentLength = TotalContentLength.Value;
            long rangeStart = requestedRange.Key;
            long rangeEnd = requestedRange.Value ?? (totalContentLength - 1);
            long rangeLength = 1 + rangeEnd - rangeStart;

            // Only read the bytes we need
            byte[] bytes = await ReadBytes(SourceStream, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength)).ConfigureAwait(false);

            // Content-Length is the length of what we're serving, not the original content
            HttpListenerContext.Response.ContentLength64 = rangeLength;

            HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);

            await responseStream.WriteAsync(bytes, 0, Convert.ToInt32(rangeLength)).ConfigureAwait(false);
        }

        /// <summary>
        /// Reads bytes from a stream
        /// </summary>
        /// <param name="input">The input stream</param>
        /// <param name="start">The starting position</param>
        /// <param name="count">The number of bytes to read, or null to read to the end.</param>
        private async Task<byte[]> ReadBytes(Stream input, int start, int? count)
        {
            if (start > 0)
            {
                input.Position = start;
            }

            if (count == null)
            {
                byte[] buffer = new byte[16 * 1024];

                using (MemoryStream ms = new MemoryStream())
                {
                    int read;
                    while ((read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
                    {
                        await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false);
                    }
                    return ms.ToArray();
                }
            }
            else
            {
                byte[] buffer = new byte[count.Value];

                using (MemoryStream ms = new MemoryStream())
                {
                    int read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);

                    await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false);

                    return ms.ToArray();
                }
            }

        }
    }
}