aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Net/Handlers/BaseSerializationHandler.cs
blob: 53b3ee817f2ebeb19e4eff4df9b27024c16f5ab9 (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
using MediaBrowser.Common.Serialization;
using System;
using System.IO;
using System.Threading.Tasks;

namespace MediaBrowser.Common.Net.Handlers
{
    public abstract class BaseSerializationHandler<T> : BaseHandler
        where T : class
    {
        public SerializationFormat SerializationFormat
        {
            get
            {
                string format = QueryString["dataformat"];

                if (string.IsNullOrEmpty(format))
                {
                    return SerializationFormat.Json;
                }

                return (SerializationFormat)Enum.Parse(typeof(SerializationFormat), format, true);
            }
        }

        protected string ContentType
        {
            get
            {
                switch (SerializationFormat)
                {
                    case SerializationFormat.Jsv:
                        return "text/plain";
                    case SerializationFormat.Protobuf:
                        return "application/x-protobuf";
                    default:
                        return MimeTypes.JsonMimeType;
                }
            }
        }

        protected override async Task<ResponseInfo> GetResponseInfo()
        {
            ResponseInfo info = new ResponseInfo
            {
                ContentType = ContentType
            };

            _objectToSerialize = await GetObjectToSerialize().ConfigureAwait(false);

            if (_objectToSerialize == null)
            {
                info.StatusCode = 404;
            }

            return info;
        }

        private T _objectToSerialize;

        protected abstract Task<T> GetObjectToSerialize();

        protected override Task WriteResponseToOutputStream(Stream stream)
        {
            return Task.Run(() =>
            {
                switch (SerializationFormat)
                {
                    case SerializationFormat.Jsv:
                        JsvSerializer.SerializeToStream(_objectToSerialize, stream);
                        break;
                    case SerializationFormat.Protobuf:
                        ProtobufSerializer.SerializeToStream(_objectToSerialize, stream);
                        break;
                    default:
                        JsonSerializer.SerializeToStream(_objectToSerialize, stream);
                        break;
                }
            });
        }
    }

    public enum SerializationFormat
    {
        Json,
        Jsv,
        Protobuf
    }

}