2012-08-28 14:22:25 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.IO;
|
2012-08-22 13:19:18 +00:00
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using MediaBrowser.Common.Serialization;
|
|
|
|
|
|
|
|
|
|
namespace MediaBrowser.Common.Net.Handlers
|
|
|
|
|
{
|
2012-09-02 05:30:25 +00:00
|
|
|
|
public abstract class BaseSerializationHandler<T> : BaseHandler
|
2012-08-22 13:19:18 +00:00
|
|
|
|
{
|
|
|
|
|
public SerializationFormat SerializationFormat
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
string format = QueryString["dataformat"];
|
|
|
|
|
|
|
|
|
|
if (string.IsNullOrEmpty(format))
|
|
|
|
|
{
|
|
|
|
|
return Handlers.SerializationFormat.Json;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return (SerializationFormat)Enum.Parse(typeof(SerializationFormat), format, true);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override Task<string> GetContentType()
|
|
|
|
|
{
|
|
|
|
|
switch (SerializationFormat)
|
|
|
|
|
{
|
|
|
|
|
case Handlers.SerializationFormat.Jsv:
|
|
|
|
|
return Task.FromResult<string>("text/plain");
|
2012-08-28 14:22:25 +00:00
|
|
|
|
case Handlers.SerializationFormat.Protobuf:
|
|
|
|
|
return Task.FromResult<string>("application/x-protobuf");
|
2012-08-22 13:19:18 +00:00
|
|
|
|
default:
|
|
|
|
|
return Task.FromResult<string>(MimeTypes.JsonMimeType);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private bool _ObjectToSerializeEnsured = false;
|
|
|
|
|
private T _ObjectToSerialize;
|
|
|
|
|
|
|
|
|
|
private async Task EnsureObjectToSerialize()
|
|
|
|
|
{
|
|
|
|
|
if (!_ObjectToSerializeEnsured)
|
|
|
|
|
{
|
|
|
|
|
_ObjectToSerialize = await GetObjectToSerialize().ConfigureAwait(false);
|
|
|
|
|
|
|
|
|
|
if (_ObjectToSerialize == null)
|
|
|
|
|
{
|
|
|
|
|
StatusCode = 404;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_ObjectToSerializeEnsured = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected abstract Task<T> GetObjectToSerialize();
|
|
|
|
|
|
|
|
|
|
protected override Task PrepareResponse()
|
|
|
|
|
{
|
|
|
|
|
return EnsureObjectToSerialize();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected async override Task WriteResponseToOutputStream(Stream stream)
|
|
|
|
|
{
|
|
|
|
|
await EnsureObjectToSerialize();
|
|
|
|
|
|
|
|
|
|
switch (SerializationFormat)
|
|
|
|
|
{
|
|
|
|
|
case Handlers.SerializationFormat.Jsv:
|
|
|
|
|
JsvSerializer.SerializeToStream<T>(_ObjectToSerialize, stream);
|
|
|
|
|
break;
|
2012-08-28 14:22:25 +00:00
|
|
|
|
case Handlers.SerializationFormat.Protobuf:
|
|
|
|
|
ProtobufSerializer.SerializeToStream<T>(_ObjectToSerialize, stream);
|
|
|
|
|
break;
|
2012-08-22 13:19:18 +00:00
|
|
|
|
default:
|
|
|
|
|
JsonSerializer.SerializeToStream<T>(_ObjectToSerialize, stream);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public enum SerializationFormat
|
|
|
|
|
{
|
|
|
|
|
Json,
|
2012-08-28 14:22:25 +00:00
|
|
|
|
Jsv,
|
|
|
|
|
Protobuf
|
2012-08-22 13:19:18 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|