aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/Services/HttpResult.cs
blob: 8ba86f756dd765e6480b79b0a015bd4444dbdd41 (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
#pragma warning disable CS1591

using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;

namespace Emby.Server.Implementations.Services
{
    public class HttpResult
        : IHttpResult, IAsyncStreamWriter
    {
        public HttpResult(object response, string contentType, HttpStatusCode statusCode)
        {
            this.Headers = new Dictionary<string, string>();

            this.Response = response;
            this.ContentType = contentType;
            this.StatusCode = statusCode;
        }

        public object Response { get; set; }

        public string ContentType { get; set; }

        public IDictionary<string, string> Headers { get; private set; }

        public int Status { get; set; }

        public HttpStatusCode StatusCode
        {
            get => (HttpStatusCode)Status;
            set => Status = (int)value;
        }

        public IRequest RequestContext { get; set; }

        public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
        {
            var response = RequestContext?.Response;

            if (this.Response is byte[] bytesResponse)
            {
                var contentLength = bytesResponse.Length;

                if (response != null)
                {
                    response.ContentLength = contentLength;
                }

                if (contentLength > 0)
                {
                    await responseStream.WriteAsync(bytesResponse, 0, contentLength, cancellationToken).ConfigureAwait(false);
                }

                return;
            }

            await ResponseHelper.WriteObject(this.RequestContext, this.Response, response).ConfigureAwait(false);
        }
    }
}