diff options
| author | Luke <luke.pulverenti@gmail.com> | 2017-02-24 15:21:11 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2017-02-24 15:21:11 -0500 |
| commit | cd6b7f3bdc5bcbc6c68131cc40b71b68ac1b73a6 (patch) | |
| tree | 48b8f6d94e3f762a486aa1c4fa6937cf23c18dee /Emby.Server.Implementations/Services | |
| parent | c07e774ca9c0f234ec6899e17fc70301d1990290 (diff) | |
| parent | 66a844e6399f1d79be8e10ea098ba6768e0d123b (diff) | |
Merge pull request #2489 from MediaBrowser/beta
Beta
Diffstat (limited to 'Emby.Server.Implementations/Services')
10 files changed, 1711 insertions, 0 deletions
diff --git a/Emby.Server.Implementations/Services/HttpResult.cs b/Emby.Server.Implementations/Services/HttpResult.cs new file mode 100644 index 000000000..dfad09f7b --- /dev/null +++ b/Emby.Server.Implementations/Services/HttpResult.cs @@ -0,0 +1,58 @@ +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 object Response { get; set; } + + public HttpResult(object response, string contentType, HttpStatusCode statusCode) + { + this.Headers = new Dictionary<string, string>(); + this.Cookies = new List<Cookie>(); + + this.Response = response; + this.ContentType = contentType; + this.StatusCode = statusCode; + } + + public string ContentType { get; set; } + + public IDictionary<string, string> Headers { get; private set; } + + public List<Cookie> Cookies { get; private set; } + + public int Status { get; set; } + + public HttpStatusCode StatusCode + { + get { return (HttpStatusCode)Status; } + set { Status = (int)value; } + } + + public IRequest RequestContext { get; set; } + + public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken) + { + var response = RequestContext != null ? RequestContext.Response : null; + + var bytesResponse = this.Response as byte[]; + if (bytesResponse != null) + { + if (response != null) + response.SetContentLength(bytesResponse.Length); + + await responseStream.WriteAsync(bytesResponse, 0, bytesResponse.Length).ConfigureAwait(false); + return; + } + + await ResponseHelper.WriteObject(this.RequestContext, this.Response, response).ConfigureAwait(false); + } + } +} diff --git a/Emby.Server.Implementations/Services/RequestHelper.cs b/Emby.Server.Implementations/Services/RequestHelper.cs new file mode 100644 index 000000000..7538d3102 --- /dev/null +++ b/Emby.Server.Implementations/Services/RequestHelper.cs @@ -0,0 +1,51 @@ +using System; +using System.IO; +using Emby.Server.Implementations.HttpServer; + +namespace Emby.Server.Implementations.Services +{ + public class RequestHelper + { + public static Func<Type, Stream, object> GetRequestReader(HttpListenerHost host, string contentType) + { + switch (GetContentTypeWithoutEncoding(contentType)) + { + case "application/xml": + case "text/xml": + case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml + return host.DeserializeXml; + + case "application/json": + case "text/json": + return host.DeserializeJson; + } + + return null; + } + + public static Action<object, Stream> GetResponseWriter(HttpListenerHost host, string contentType) + { + switch (GetContentTypeWithoutEncoding(contentType)) + { + case "application/xml": + case "text/xml": + case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml + return host.SerializeToXml; + + case "application/json": + case "text/json": + return host.SerializeToJson; + } + + return null; + } + + private static string GetContentTypeWithoutEncoding(string contentType) + { + return contentType == null + ? null + : contentType.Split(';')[0].ToLower().Trim(); + } + + } +}
\ No newline at end of file diff --git a/Emby.Server.Implementations/Services/ResponseHelper.cs b/Emby.Server.Implementations/Services/ResponseHelper.cs new file mode 100644 index 000000000..d4ce1cabf --- /dev/null +++ b/Emby.Server.Implementations/Services/ResponseHelper.cs @@ -0,0 +1,179 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Emby.Server.Implementations.HttpServer; +using MediaBrowser.Model.Services; + +namespace Emby.Server.Implementations.Services +{ + public static class ResponseHelper + { + private static async Task<bool> WriteToOutputStream(IResponse response, object result) + { + var asyncStreamWriter = result as IAsyncStreamWriter; + if (asyncStreamWriter != null) + { + await asyncStreamWriter.WriteToAsync(response.OutputStream, CancellationToken.None).ConfigureAwait(false); + return true; + } + + var streamWriter = result as IStreamWriter; + if (streamWriter != null) + { + streamWriter.WriteTo(response.OutputStream); + return true; + } + + var stream = result as Stream; + if (stream != null) + { + using (stream) + { + await stream.CopyToAsync(response.OutputStream).ConfigureAwait(false); + return true; + } + } + + var bytes = result as byte[]; + if (bytes != null) + { + response.ContentType = "application/octet-stream"; + response.SetContentLength(bytes.Length); + + await response.OutputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); + return true; + } + + return false; + } + + public static Task WriteToResponse(IResponse httpRes, IRequest httpReq, object result) + { + if (result == null) + { + if (httpRes.StatusCode == (int)HttpStatusCode.OK) + { + httpRes.StatusCode = (int)HttpStatusCode.NoContent; + } + + httpRes.SetContentLength(0); + return Task.FromResult(true); + } + + var httpResult = result as IHttpResult; + if (httpResult != null) + { + httpResult.RequestContext = httpReq; + httpReq.ResponseContentType = httpResult.ContentType ?? httpReq.ResponseContentType; + return WriteToResponseInternal(httpRes, httpResult, httpReq); + } + + return WriteToResponseInternal(httpRes, result, httpReq); + } + + /// <summary> + /// Writes to response. + /// Response headers are customizable by implementing IHasHeaders an returning Dictionary of Http headers. + /// </summary> + /// <param name="response">The response.</param> + /// <param name="result">Whether or not it was implicity handled by ServiceStack's built-in handlers.</param> + /// <param name="request">The serialization context.</param> + /// <returns></returns> + private static async Task WriteToResponseInternal(IResponse response, object result, IRequest request) + { + var defaultContentType = request.ResponseContentType; + + var httpResult = result as IHttpResult; + if (httpResult != null) + { + if (httpResult.RequestContext == null) + httpResult.RequestContext = request; + + response.StatusCode = httpResult.Status; + response.StatusDescription = httpResult.StatusCode.ToString(); + if (string.IsNullOrEmpty(httpResult.ContentType)) + { + httpResult.ContentType = defaultContentType; + } + response.ContentType = httpResult.ContentType; + + if (httpResult.Cookies != null) + { + var httpRes = response as IHttpResponse; + if (httpRes != null) + { + foreach (var cookie in httpResult.Cookies) + { + httpRes.SetCookie(cookie); + } + } + } + } + + var responseOptions = result as IHasHeaders; + if (responseOptions != null) + { + foreach (var responseHeaders in responseOptions.Headers) + { + if (string.Equals(responseHeaders.Key, "Content-Length", StringComparison.OrdinalIgnoreCase)) + { + response.SetContentLength(long.Parse(responseHeaders.Value)); + continue; + } + + response.AddHeader(responseHeaders.Key, responseHeaders.Value); + } + } + + //ContentType='text/html' is the default for a HttpResponse + //Do not override if another has been set + if (response.ContentType == null || response.ContentType == "text/html") + { + response.ContentType = defaultContentType; + } + + if (new HashSet<string> { "application/json", }.Contains(response.ContentType)) + { + response.ContentType += "; charset=utf-8"; + } + + var writeToOutputStreamResult = await WriteToOutputStream(response, result).ConfigureAwait(false); + if (writeToOutputStreamResult) + { + return; + } + + var responseText = result as string; + if (responseText != null) + { + var bytes = Encoding.UTF8.GetBytes(responseText); + response.SetContentLength(bytes.Length); + await response.OutputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); + return; + } + + await WriteObject(request, result, response).ConfigureAwait(false); + } + + public static async Task WriteObject(IRequest request, object result, IResponse response) + { + var contentType = request.ResponseContentType; + var serializer = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType); + + using (var ms = new MemoryStream()) + { + serializer(result, ms); + + ms.Position = 0; + response.SetContentLength(ms.Length); + await ms.CopyToAsync(response.OutputStream).ConfigureAwait(false); + } + + //serializer(result, outputStream); + } + } +} diff --git a/Emby.Server.Implementations/Services/ServiceController.cs b/Emby.Server.Implementations/Services/ServiceController.cs new file mode 100644 index 000000000..d283bf81f --- /dev/null +++ b/Emby.Server.Implementations/Services/ServiceController.cs @@ -0,0 +1,218 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading.Tasks; +using Emby.Server.Implementations.HttpServer; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Services; + +namespace Emby.Server.Implementations.Services +{ + public delegate Task<object> InstanceExecFn(IRequest requestContext, object intance, object request); + public delegate object ActionInvokerFn(object intance, object request); + public delegate void VoidActionInvokerFn(object intance, object request); + + public class ServiceController + { + public static ServiceController Instance; + private readonly Func<IEnumerable<Type>> _resolveServicesFn; + + public ServiceController(Func<IEnumerable<Type>> resolveServicesFn) + { + Instance = this; + _resolveServicesFn = resolveServicesFn; + } + + public void Init(HttpListenerHost appHost) + { + foreach (var serviceType in _resolveServicesFn()) + { + RegisterService(appHost, serviceType); + } + } + + private Type[] GetGenericArguments(Type type) + { + return type.GetTypeInfo().IsGenericTypeDefinition + ? type.GetTypeInfo().GenericTypeParameters + : type.GetTypeInfo().GenericTypeArguments; + } + + public void RegisterService(HttpListenerHost appHost, Type serviceType) + { + var processedReqs = new HashSet<Type>(); + + var actions = ServiceExecGeneral.Reset(serviceType); + + foreach (var mi in serviceType.GetActions()) + { + var requestType = mi.GetParameters()[0].ParameterType; + if (processedReqs.Contains(requestType)) continue; + processedReqs.Add(requestType); + + ServiceExecGeneral.CreateServiceRunnersFor(requestType, actions); + + var returnMarker = GetTypeWithGenericTypeDefinitionOf(requestType, typeof(IReturn<>)); + var responseType = returnMarker != null ? + GetGenericArguments(returnMarker)[0] + : mi.ReturnType != typeof(object) && mi.ReturnType != typeof(void) ? + mi.ReturnType + : Type.GetType(requestType.FullName + "Response"); + + RegisterRestPaths(appHost, requestType); + + appHost.AddServiceInfo(serviceType, requestType, responseType); + } + } + + private static Type GetTypeWithGenericTypeDefinitionOf(Type type, Type genericTypeDefinition) + { + foreach (var t in type.GetTypeInfo().ImplementedInterfaces) + { + if (t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == genericTypeDefinition) + { + return t; + } + } + + var genericType = FirstGenericType(type); + if (genericType != null && genericType.GetGenericTypeDefinition() == genericTypeDefinition) + { + return genericType; + } + + return null; + } + + public static Type FirstGenericType(Type type) + { + while (type != null) + { + if (type.GetTypeInfo().IsGenericType) + return type; + + type = type.GetTypeInfo().BaseType; + } + return null; + } + + public readonly Dictionary<string, List<RestPath>> RestPathMap = new Dictionary<string, List<RestPath>>(StringComparer.OrdinalIgnoreCase); + + public void RegisterRestPaths(HttpListenerHost appHost, Type requestType) + { + var attrs = appHost.GetRouteAttributes(requestType); + foreach (RouteAttribute attr in attrs) + { + var restPath = new RestPath(appHost.CreateInstance, appHost.GetParseFn, requestType, attr.Path, attr.Verbs, attr.Summary, attr.Notes); + + if (!restPath.IsValid) + throw new NotSupportedException(string.Format( + "RestPath '{0}' on Type '{1}' is not Valid", attr.Path, requestType.GetMethodName())); + + RegisterRestPath(restPath); + } + } + + private static readonly char[] InvalidRouteChars = new[] { '?', '&' }; + + public void RegisterRestPath(RestPath restPath) + { + if (!restPath.Path.StartsWith("/")) + throw new ArgumentException(string.Format("Route '{0}' on '{1}' must start with a '/'", restPath.Path, restPath.RequestType.GetMethodName())); + if (restPath.Path.IndexOfAny(InvalidRouteChars) != -1) + throw new ArgumentException(string.Format("Route '{0}' on '{1}' contains invalid chars. " + + "See https://github.com/ServiceStack/ServiceStack/wiki/Routing for info on valid routes.", restPath.Path, restPath.RequestType.GetMethodName())); + + List<RestPath> pathsAtFirstMatch; + if (!RestPathMap.TryGetValue(restPath.FirstMatchHashKey, out pathsAtFirstMatch)) + { + pathsAtFirstMatch = new List<RestPath>(); + RestPathMap[restPath.FirstMatchHashKey] = pathsAtFirstMatch; + } + pathsAtFirstMatch.Add(restPath); + } + + public RestPath GetRestPathForRequest(string httpMethod, string pathInfo, ILogger logger) + { + var matchUsingPathParts = RestPath.GetPathPartsForMatching(pathInfo); + + List<RestPath> firstMatches; + + var yieldedHashMatches = RestPath.GetFirstMatchHashKeys(matchUsingPathParts); + foreach (var potentialHashMatch in yieldedHashMatches) + { + if (!this.RestPathMap.TryGetValue(potentialHashMatch, out firstMatches)) + { + continue; + } + + var bestScore = -1; + foreach (var restPath in firstMatches) + { + var score = restPath.MatchScore(httpMethod, matchUsingPathParts, logger); + if (score > bestScore) bestScore = score; + } + + if (bestScore > 0) + { + foreach (var restPath in firstMatches) + { + if (bestScore == restPath.MatchScore(httpMethod, matchUsingPathParts, logger)) + return restPath; + } + } + } + + var yieldedWildcardMatches = RestPath.GetFirstMatchWildCardHashKeys(matchUsingPathParts); + foreach (var potentialHashMatch in yieldedWildcardMatches) + { + if (!this.RestPathMap.TryGetValue(potentialHashMatch, out firstMatches)) continue; + + var bestScore = -1; + foreach (var restPath in firstMatches) + { + var score = restPath.MatchScore(httpMethod, matchUsingPathParts, logger); + if (score > bestScore) bestScore = score; + } + if (bestScore > 0) + { + foreach (var restPath in firstMatches) + { + if (bestScore == restPath.MatchScore(httpMethod, matchUsingPathParts, logger)) + return restPath; + } + } + } + + return null; + } + + public async Task<object> Execute(HttpListenerHost appHost, object requestDto, IRequest req) + { + req.Dto = requestDto; + var requestType = requestDto.GetType(); + req.OperationName = requestType.Name; + + var serviceType = appHost.GetServiceTypeByRequest(requestType); + + var service = appHost.CreateInstance(serviceType); + + //var service = typeFactory.CreateInstance(serviceType); + + var serviceRequiresContext = service as IRequiresRequest; + if (serviceRequiresContext != null) + { + serviceRequiresContext.Request = req; + } + + if (req.Dto == null) // Don't override existing batched DTO[] + req.Dto = requestDto; + + //Executes the service and returns the result + var response = await ServiceExecGeneral.Execute(serviceType, req, service, requestDto, requestType.GetMethodName()).ConfigureAwait(false); + + return response; + } + } + +}
\ No newline at end of file diff --git a/Emby.Server.Implementations/Services/ServiceExec.cs b/Emby.Server.Implementations/Services/ServiceExec.cs new file mode 100644 index 000000000..e0b5e69c0 --- /dev/null +++ b/Emby.Server.Implementations/Services/ServiceExec.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Threading.Tasks; +using MediaBrowser.Model.Services; + +namespace Emby.Server.Implementations.Services +{ + public static class ServiceExecExtensions + { + public static HashSet<string> AllVerbs = new HashSet<string>(new[] { + "OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", // RFC 2616 + "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "MOVE", "LOCK", "UNLOCK", // RFC 2518 + "VERSION-CONTROL", "REPORT", "CHECKOUT", "CHECKIN", "UNCHECKOUT", + "MKWORKSPACE", "UPDATE", "LABEL", "MERGE", "BASELINE-CONTROL", "MKACTIVITY", // RFC 3253 + "ORDERPATCH", // RFC 3648 + "ACL", // RFC 3744 + "PATCH", // https://datatracker.ietf.org/doc/draft-dusseault-http-patch/ + "SEARCH", // https://datatracker.ietf.org/doc/draft-reschke-webdav-search/ + "BCOPY", "BDELETE", "BMOVE", "BPROPFIND", "BPROPPATCH", "NOTIFY", + "POLL", "SUBSCRIBE", "UNSUBSCRIBE" + }); + + public static IEnumerable<MethodInfo> GetActions(this Type serviceType) + { + foreach (var mi in serviceType.GetRuntimeMethods().Where(i => i.IsPublic && !i.IsStatic)) + { + if (mi.GetParameters().Length != 1) + continue; + + var actionName = mi.Name; + if (!AllVerbs.Contains(actionName, StringComparer.OrdinalIgnoreCase) && !string.Equals(actionName, ServiceMethod.AnyAction, StringComparison.OrdinalIgnoreCase)) + continue; + + yield return mi; + } + } + } + + internal static class ServiceExecGeneral + { + public static Dictionary<string, ServiceMethod> execMap = new Dictionary<string, ServiceMethod>(); + + public static void CreateServiceRunnersFor(Type requestType, List<ServiceMethod> actions) + { + foreach (var actionCtx in actions) + { + if (execMap.ContainsKey(actionCtx.Id)) continue; + + execMap[actionCtx.Id] = actionCtx; + } + } + + public static async Task<object> Execute(Type serviceType, IRequest request, object instance, object requestDto, string requestName) + { + var actionName = request.Verb ?? "POST"; + + ServiceMethod actionContext; + if (ServiceExecGeneral.execMap.TryGetValue(ServiceMethod.Key(serviceType, actionName, requestName), out actionContext) + || ServiceExecGeneral.execMap.TryGetValue(ServiceMethod.AnyKey(serviceType, requestName), out actionContext)) + { + if (actionContext.RequestFilters != null) + { + foreach (var requestFilter in actionContext.RequestFilters) + { + requestFilter.RequestFilter(request, request.Response, requestDto); + if (request.Response.IsClosed) return null; + } + } + + var response = actionContext.ServiceAction(instance, requestDto); + + var taskResponse = response as Task; + if (taskResponse != null) + { + await taskResponse.ConfigureAwait(false); + response = ServiceHandler.GetTaskResult(taskResponse); + } + + return response; + } + + var expectedMethodName = actionName.Substring(0, 1) + actionName.Substring(1).ToLower(); + throw new NotImplementedException(string.Format("Could not find method named {1}({0}) or Any({0}) on Service {2}", requestDto.GetType().GetMethodName(), expectedMethodName, serviceType.GetMethodName())); + } + + public static List<ServiceMethod> Reset(Type serviceType) + { + var actions = new List<ServiceMethod>(); + + foreach (var mi in serviceType.GetActions()) + { + var actionName = mi.Name; + var args = mi.GetParameters(); + + var requestType = args[0].ParameterType; + var actionCtx = new ServiceMethod + { + Id = ServiceMethod.Key(serviceType, actionName, requestType.GetMethodName()) + }; + + try + { + actionCtx.ServiceAction = CreateExecFn(serviceType, requestType, mi); + } + catch + { + //Potential problems with MONO, using reflection for fallback + actionCtx.ServiceAction = (service, request) => + mi.Invoke(service, new[] { request }); + } + + var reqFilters = new List<IHasRequestFilter>(); + + foreach (var attr in mi.GetCustomAttributes(true)) + { + var hasReqFilter = attr as IHasRequestFilter; + + if (hasReqFilter != null) + reqFilters.Add(hasReqFilter); + } + + if (reqFilters.Count > 0) + actionCtx.RequestFilters = reqFilters.OrderBy(i => i.Priority).ToArray(); + + actions.Add(actionCtx); + } + + return actions; + } + + private static ActionInvokerFn CreateExecFn(Type serviceType, Type requestType, MethodInfo mi) + { + var serviceParam = Expression.Parameter(typeof(object), "serviceObj"); + var serviceStrong = Expression.Convert(serviceParam, serviceType); + + var requestDtoParam = Expression.Parameter(typeof(object), "requestDto"); + var requestDtoStrong = Expression.Convert(requestDtoParam, requestType); + + Expression callExecute = Expression.Call( + serviceStrong, mi, requestDtoStrong); + + if (mi.ReturnType != typeof(void)) + { + var executeFunc = Expression.Lambda<ActionInvokerFn> + (callExecute, serviceParam, requestDtoParam).Compile(); + + return executeFunc; + } + else + { + var executeFunc = Expression.Lambda<VoidActionInvokerFn> + (callExecute, serviceParam, requestDtoParam).Compile(); + + return (service, request) => + { + executeFunc(service, request); + return null; + }; + } + } + } +}
\ No newline at end of file diff --git a/Emby.Server.Implementations/Services/ServiceHandler.cs b/Emby.Server.Implementations/Services/ServiceHandler.cs new file mode 100644 index 000000000..8b59b4843 --- /dev/null +++ b/Emby.Server.Implementations/Services/ServiceHandler.cs @@ -0,0 +1,296 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading.Tasks; +using Emby.Server.Implementations.HttpServer; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Services; + +namespace Emby.Server.Implementations.Services +{ + public class ServiceHandler + { + public async Task<object> HandleResponseAsync(object response) + { + var taskResponse = response as Task; + + if (taskResponse == null) + { + return response; + } + + await taskResponse.ConfigureAwait(false); + + var taskResult = GetTaskResult(taskResponse); + + var subTask = taskResult as Task; + if (subTask != null) + { + taskResult = GetTaskResult(subTask); + } + + return taskResult; + } + + internal static object GetTaskResult(Task task) + { + try + { + var taskObject = task as Task<object>; + if (taskObject != null) + { + return taskObject.Result; + } + + task.Wait(); + + var type = task.GetType().GetTypeInfo(); + if (!type.IsGenericType) + { + return null; + } + + return type.GetDeclaredProperty("Result").GetValue(task); + } + catch (TypeAccessException) + { + return null; //return null for void Task's + } + } + + protected static object CreateContentTypeRequest(HttpListenerHost host, IRequest httpReq, Type requestType, string contentType) + { + if (!string.IsNullOrEmpty(contentType) && httpReq.ContentLength > 0) + { + var deserializer = RequestHelper.GetRequestReader(host, contentType); + if (deserializer != null) + { + return deserializer(requestType, httpReq.InputStream); + } + } + return host.CreateInstance(requestType); + } + + public static RestPath FindMatchingRestPath(string httpMethod, string pathInfo, ILogger logger, out string contentType) + { + pathInfo = GetSanitizedPathInfo(pathInfo, out contentType); + + return ServiceController.Instance.GetRestPathForRequest(httpMethod, pathInfo, logger); + } + + public static string GetSanitizedPathInfo(string pathInfo, out string contentType) + { + contentType = null; + var pos = pathInfo.LastIndexOf('.'); + if (pos >= 0) + { + var format = pathInfo.Substring(pos + 1); + contentType = GetFormatContentType(format); + if (contentType != null) + { + pathInfo = pathInfo.Substring(0, pos); + } + } + return pathInfo; + } + + private static string GetFormatContentType(string format) + { + //built-in formats + if (format == "json") + return "application/json"; + if (format == "xml") + return "application/xml"; + + return null; + } + + public RestPath GetRestPath(string httpMethod, string pathInfo) + { + if (this.RestPath == null) + { + string contentType; + this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, new NullLogger(), out contentType); + + if (contentType != null) + ResponseContentType = contentType; + } + return this.RestPath; + } + + public RestPath RestPath { get; set; } + + // Set from SSHHF.GetHandlerForPathInfo() + public string ResponseContentType { get; set; } + + public async Task ProcessRequestAsync(HttpListenerHost appHost, IRequest httpReq, IResponse httpRes, ILogger logger, string operationName) + { + var restPath = GetRestPath(httpReq.Verb, httpReq.PathInfo); + if (restPath == null) + { + throw new NotSupportedException("No RestPath found for: " + httpReq.Verb + " " + httpReq.PathInfo); + } + + SetRoute(httpReq, restPath); + + if (ResponseContentType != null) + httpReq.ResponseContentType = ResponseContentType; + + var request = httpReq.Dto = CreateRequest(appHost, httpReq, restPath, logger); + + appHost.ApplyRequestFilters(httpReq, httpRes, request); + + var rawResponse = await appHost.ServiceController.Execute(appHost, request, httpReq).ConfigureAwait(false); + + var response = await HandleResponseAsync(rawResponse).ConfigureAwait(false); + + // Apply response filters + foreach (var responseFilter in appHost.ResponseFilters) + { + responseFilter(httpReq, httpRes, response); + } + + await ResponseHelper.WriteToResponse(httpRes, httpReq, response).ConfigureAwait(false); + } + + public static object CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, ILogger logger) + { + var requestType = restPath.RequestType; + + if (RequireqRequestStream(requestType)) + { + // Used by IRequiresRequestStream + return CreateRequiresRequestStreamRequest(host, httpReq, requestType); + } + + var requestParams = GetFlattenedRequestParams(httpReq); + return CreateRequest(host, httpReq, restPath, requestParams); + } + + private static bool RequireqRequestStream(Type requestType) + { + var requiresRequestStreamTypeInfo = typeof(IRequiresRequestStream).GetTypeInfo(); + + return requiresRequestStreamTypeInfo.IsAssignableFrom(requestType.GetTypeInfo()); + } + + private static IRequiresRequestStream CreateRequiresRequestStreamRequest(HttpListenerHost host, IRequest req, Type requestType) + { + var restPath = GetRoute(req); + var request = ServiceHandler.CreateRequest(req, restPath, GetRequestParams(req), host.CreateInstance(requestType)); + + var rawReq = (IRequiresRequestStream)request; + rawReq.RequestStream = req.InputStream; + return rawReq; + } + + public static object CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams) + { + var requestDto = CreateContentTypeRequest(host, httpReq, restPath.RequestType, httpReq.ContentType); + + return CreateRequest(httpReq, restPath, requestParams, requestDto); + } + + public static object CreateRequest(IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams, object requestDto) + { + string contentType; + var pathInfo = !restPath.IsWildCardPath + ? GetSanitizedPathInfo(httpReq.PathInfo, out contentType) + : httpReq.PathInfo; + + return restPath.CreateRequest(pathInfo, requestParams, requestDto); + } + + /// <summary> + /// Duplicate Params are given a unique key by appending a #1 suffix + /// </summary> + private static Dictionary<string, string> GetRequestParams(IRequest request) + { + var map = new Dictionary<string, string>(); + + foreach (var name in request.QueryString.Keys) + { + if (name == null) continue; //thank you ASP.NET + + var values = request.QueryString.GetValues(name); + if (values.Length == 1) + { + map[name] = values[0]; + } + else + { + for (var i = 0; i < values.Length; i++) + { + map[name + (i == 0 ? "" : "#" + i)] = values[i]; + } + } + } + + if ((IsMethod(request.Verb, "POST") || IsMethod(request.Verb, "PUT")) && request.FormData != null) + { + foreach (var name in request.FormData.Keys) + { + if (name == null) continue; //thank you ASP.NET + + var values = request.FormData.GetValues(name); + if (values.Length == 1) + { + map[name] = values[0]; + } + else + { + for (var i = 0; i < values.Length; i++) + { + map[name + (i == 0 ? "" : "#" + i)] = values[i]; + } + } + } + } + + return map; + } + + private static bool IsMethod(string method, string expected) + { + return string.Equals(method, expected, StringComparison.OrdinalIgnoreCase); + } + + /// <summary> + /// Duplicate params have their values joined together in a comma-delimited string + /// </summary> + private static Dictionary<string, string> GetFlattenedRequestParams(IRequest request) + { + var map = new Dictionary<string, string>(); + + foreach (var name in request.QueryString.Keys) + { + if (name == null) continue; //thank you ASP.NET + map[name] = request.QueryString[name]; + } + + if ((IsMethod(request.Verb, "POST") || IsMethod(request.Verb, "PUT")) && request.FormData != null) + { + foreach (var name in request.FormData.Keys) + { + if (name == null) continue; //thank you ASP.NET + map[name] = request.FormData[name]; + } + } + + return map; + } + + private static void SetRoute(IRequest req, RestPath route) + { + req.Items["__route"] = route; + } + + private static RestPath GetRoute(IRequest req) + { + object route; + req.Items.TryGetValue("__route", out route); + return route as RestPath; + } + } + +} diff --git a/Emby.Server.Implementations/Services/ServiceMethod.cs b/Emby.Server.Implementations/Services/ServiceMethod.cs new file mode 100644 index 000000000..bcbc6fb57 --- /dev/null +++ b/Emby.Server.Implementations/Services/ServiceMethod.cs @@ -0,0 +1,24 @@ +using System; + +namespace Emby.Server.Implementations.Services +{ + public class ServiceMethod + { + public const string AnyAction = "ANY"; + + public string Id { get; set; } + + public ActionInvokerFn ServiceAction { get; set; } + public MediaBrowser.Model.Services.IHasRequestFilter[] RequestFilters { get; set; } + + public static string Key(Type serviceType, string method, string requestDtoName) + { + return serviceType.FullName + " " + method.ToUpper() + " " + requestDtoName; + } + + public static string AnyKey(Type serviceType, string requestDtoName) + { + return Key(serviceType, AnyAction, requestDtoName); + } + } +}
\ No newline at end of file diff --git a/Emby.Server.Implementations/Services/ServicePath.cs b/Emby.Server.Implementations/Services/ServicePath.cs new file mode 100644 index 000000000..255b20919 --- /dev/null +++ b/Emby.Server.Implementations/Services/ServicePath.cs @@ -0,0 +1,563 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using MediaBrowser.Model.Logging; + +namespace Emby.Server.Implementations.Services +{ + public class RestPath + { + private const string WildCard = "*"; + private const char WildCardChar = '*'; + private const string PathSeperator = "/"; + private const char PathSeperatorChar = '/'; + private const char ComponentSeperator = '.'; + private const string VariablePrefix = "{"; + + readonly bool[] componentsWithSeparators; + + private readonly string restPath; + private readonly string allowedVerbs; + private readonly bool allowsAllVerbs; + public bool IsWildCardPath { get; private set; } + + private readonly string[] literalsToMatch; + + private readonly string[] variablesNames; + + private readonly bool[] isWildcard; + private readonly int wildcardCount = 0; + + public int VariableArgsCount { get; set; } + + /// <summary> + /// The number of segments separated by '/' determinable by path.Split('/').Length + /// e.g. /path/to/here.ext == 3 + /// </summary> + public int PathComponentsCount { get; set; } + + /// <summary> + /// The total number of segments after subparts have been exploded ('.') + /// e.g. /path/to/here.ext == 4 + /// </summary> + public int TotalComponentsCount { get; set; } + + public string[] Verbs + { + get + { + return allowsAllVerbs + ? new[] { "ANY" } + : AllowedVerbs.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); + } + } + + public Type RequestType { get; private set; } + + public string Path { get { return this.restPath; } } + + public string Summary { get; private set; } + + public string Notes { get; private set; } + + public bool AllowsAllVerbs { get { return this.allowsAllVerbs; } } + + public string AllowedVerbs { get { return this.allowedVerbs; } } + + public int Priority { get; set; } //passed back to RouteAttribute + + public static string[] GetPathPartsForMatching(string pathInfo) + { + var parts = pathInfo.ToLower().Split(PathSeperatorChar) + .Where(x => !String.IsNullOrEmpty(x)).ToArray(); + return parts; + } + + public static List<string> GetFirstMatchHashKeys(string[] pathPartsForMatching) + { + var hashPrefix = pathPartsForMatching.Length + PathSeperator; + return GetPotentialMatchesWithPrefix(hashPrefix, pathPartsForMatching); + } + + public static List<string> GetFirstMatchWildCardHashKeys(string[] pathPartsForMatching) + { + const string hashPrefix = WildCard + PathSeperator; + return GetPotentialMatchesWithPrefix(hashPrefix, pathPartsForMatching); + } + + private static List<string> GetPotentialMatchesWithPrefix(string hashPrefix, string[] pathPartsForMatching) + { + var list = new List<string>(); + + foreach (var part in pathPartsForMatching) + { + list.Add(hashPrefix + part); + + var subParts = part.Split(ComponentSeperator); + if (subParts.Length == 1) continue; + + foreach (var subPart in subParts) + { + list.Add(hashPrefix + subPart); + } + } + + return list; + } + + public RestPath(Func<Type, object> createInstanceFn, Func<Type, Func<string, object>> getParseFn, Type requestType, string path, string verbs, string summary = null, string notes = null) + { + this.RequestType = requestType; + this.Summary = summary; + this.Notes = notes; + this.restPath = path; + + this.allowsAllVerbs = verbs == null || String.Equals(verbs, WildCard, StringComparison.OrdinalIgnoreCase); + if (!this.allowsAllVerbs) + { + this.allowedVerbs = verbs.ToUpper(); + } + + var componentsList = new List<string>(); + + //We only split on '.' if the restPath has them. Allows for /{action}.{type} + var hasSeparators = new List<bool>(); + foreach (var component in this.restPath.Split(PathSeperatorChar)) + { + if (String.IsNullOrEmpty(component)) continue; + + if (StringContains(component, VariablePrefix) + && component.IndexOf(ComponentSeperator) != -1) + { + hasSeparators.Add(true); + componentsList.AddRange(component.Split(ComponentSeperator)); + } + else + { + hasSeparators.Add(false); + componentsList.Add(component); + } + } + + var components = componentsList.ToArray(); + this.TotalComponentsCount = components.Length; + + this.literalsToMatch = new string[this.TotalComponentsCount]; + this.variablesNames = new string[this.TotalComponentsCount]; + this.isWildcard = new bool[this.TotalComponentsCount]; + this.componentsWithSeparators = hasSeparators.ToArray(); + this.PathComponentsCount = this.componentsWithSeparators.Length; + string firstLiteralMatch = null; + + var sbHashKey = new StringBuilder(); + for (var i = 0; i < components.Length; i++) + { + var component = components[i]; + + if (component.StartsWith(VariablePrefix)) + { + var variableName = component.Substring(1, component.Length - 2); + if (variableName[variableName.Length - 1] == WildCardChar) + { + this.isWildcard[i] = true; + variableName = variableName.Substring(0, variableName.Length - 1); + } + this.variablesNames[i] = variableName; + this.VariableArgsCount++; + } + else + { + this.literalsToMatch[i] = component.ToLower(); + sbHashKey.Append(i + PathSeperatorChar.ToString() + this.literalsToMatch); + + if (firstLiteralMatch == null) + { + firstLiteralMatch = this.literalsToMatch[i]; + } + } + } + + for (var i = 0; i < components.Length - 1; i++) + { + if (!this.isWildcard[i]) continue; + if (this.literalsToMatch[i + 1] == null) + { + throw new ArgumentException( + "A wildcard path component must be at the end of the path or followed by a literal path component."); + } + } + + this.wildcardCount = this.isWildcard.Count(x => x); + this.IsWildCardPath = this.wildcardCount > 0; + + this.FirstMatchHashKey = !this.IsWildCardPath + ? this.PathComponentsCount + PathSeperator + firstLiteralMatch + : WildCardChar + PathSeperator + firstLiteralMatch; + + this.IsValid = sbHashKey.Length > 0; + this.UniqueMatchHashKey = sbHashKey.ToString(); + + this.typeDeserializer = new StringMapTypeDeserializer(createInstanceFn, getParseFn, this.RequestType); + RegisterCaseInsenstivePropertyNameMappings(); + } + + private void RegisterCaseInsenstivePropertyNameMappings() + { + foreach (var propertyInfo in GetSerializableProperties(RequestType)) + { + var propertyName = propertyInfo.Name; + propertyNamesMap.Add(propertyName.ToLower(), propertyName); + } + } + + internal static string[] IgnoreAttributesNamed = new[] { + "IgnoreDataMemberAttribute", + "JsonIgnoreAttribute" + }; + + + private static List<Type> _excludeTypes = new List<Type> { typeof(Stream) }; + + internal static PropertyInfo[] GetSerializableProperties(Type type) + { + var properties = GetPublicProperties(type); + var readableProperties = properties.Where(x => x.GetMethod != null); + + // else return those properties that are not decorated with IgnoreDataMember + return readableProperties + .Where(prop => prop.GetCustomAttributes(true) + .All(attr => + { + var name = attr.GetType().Name; + return !IgnoreAttributesNamed.Contains(name); + })) + .Where(prop => !_excludeTypes.Contains(prop.PropertyType)) + .ToArray(); + } + + private static PropertyInfo[] GetPublicProperties(Type type) + { + if (type.GetTypeInfo().IsInterface) + { + var propertyInfos = new List<PropertyInfo>(); + + var considered = new List<Type>(); + var queue = new Queue<Type>(); + considered.Add(type); + queue.Enqueue(type); + + while (queue.Count > 0) + { + var subType = queue.Dequeue(); + foreach (var subInterface in subType.GetTypeInfo().ImplementedInterfaces) + { + if (considered.Contains(subInterface)) continue; + + considered.Add(subInterface); + queue.Enqueue(subInterface); + } + + var typeProperties = GetTypesPublicProperties(subType); + + var newPropertyInfos = typeProperties + .Where(x => !propertyInfos.Contains(x)); + + propertyInfos.InsertRange(0, newPropertyInfos); + } + + return propertyInfos.ToArray(); + } + + return GetTypesPublicProperties(type) + .Where(t => t.GetIndexParameters().Length == 0) // ignore indexed properties + .ToArray(); + } + + private static PropertyInfo[] GetTypesPublicProperties(Type subType) + { + var pis = new List<PropertyInfo>(); + foreach (var pi in subType.GetRuntimeProperties()) + { + var mi = pi.GetMethod ?? pi.SetMethod; + if (mi != null && mi.IsStatic) continue; + pis.Add(pi); + } + return pis.ToArray(); + } + + + public bool IsValid { get; set; } + + /// <summary> + /// Provide for quick lookups based on hashes that can be determined from a request url + /// </summary> + public string FirstMatchHashKey { get; private set; } + + public string UniqueMatchHashKey { get; private set; } + + private readonly StringMapTypeDeserializer typeDeserializer; + + private readonly Dictionary<string, string> propertyNamesMap = new Dictionary<string, string>(); + + public int MatchScore(string httpMethod, string[] withPathInfoParts, ILogger logger) + { + int wildcardMatchCount; + var isMatch = IsMatch(httpMethod, withPathInfoParts, logger, out wildcardMatchCount); + if (!isMatch) + { + return -1; + } + + var score = 0; + + //Routes with least wildcard matches get the highest score + score += Math.Max((100 - wildcardMatchCount), 1) * 1000; + + //Routes with less variable (and more literal) matches + score += Math.Max((10 - VariableArgsCount), 1) * 100; + + //Exact verb match is better than ANY + var exactVerb = String.Equals(httpMethod, AllowedVerbs, StringComparison.OrdinalIgnoreCase); + score += exactVerb ? 10 : 1; + + return score; + } + + private bool StringContains(string str1, string str2) + { + return str1.IndexOf(str2, StringComparison.OrdinalIgnoreCase) != -1; + } + + /// <summary> + /// For performance withPathInfoParts should already be a lower case string + /// to minimize redundant matching operations. + /// </summary> + public bool IsMatch(string httpMethod, string[] withPathInfoParts, ILogger logger, out int wildcardMatchCount) + { + wildcardMatchCount = 0; + + if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath) + { + //logger.Info("withPathInfoParts mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); + return false; + } + + if (!this.allowsAllVerbs && !StringContains(this.allowedVerbs, httpMethod)) + { + //logger.Info("allowsAllVerbs mismatch for {0} for {1} allowedverbs {2}", httpMethod, string.Join("/", withPathInfoParts), this.allowedVerbs); + return false; + } + + if (!ExplodeComponents(ref withPathInfoParts)) + { + //logger.Info("ExplodeComponents mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); + return false; + } + + if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath) + { + //logger.Info("TotalComponentsCount mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); + return false; + } + + int pathIx = 0; + for (var i = 0; i < this.TotalComponentsCount; i++) + { + if (this.isWildcard[i]) + { + if (i < this.TotalComponentsCount - 1) + { + // Continue to consume up until a match with the next literal + while (pathIx < withPathInfoParts.Length && !LiteralsEqual(withPathInfoParts[pathIx], this.literalsToMatch[i + 1])) + { + pathIx++; + wildcardMatchCount++; + } + + // Ensure there are still enough parts left to match the remainder + if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1)) + { + //logger.Info("withPathInfoParts length mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); + return false; + } + } + else + { + // A wildcard at the end matches the remainder of path + wildcardMatchCount += withPathInfoParts.Length - pathIx; + pathIx = withPathInfoParts.Length; + } + } + else + { + var literalToMatch = this.literalsToMatch[i]; + if (literalToMatch == null) + { + // Matching an ordinary (non-wildcard) variable consumes a single part + pathIx++; + continue; + } + + if (withPathInfoParts.Length <= pathIx || !LiteralsEqual(withPathInfoParts[pathIx], literalToMatch)) + { + //logger.Info("withPathInfoParts2 length mismatch for {0} for {1}. not equals: {2} != {3}.", httpMethod, string.Join("/", withPathInfoParts), withPathInfoParts[pathIx], literalToMatch); + return false; + } + pathIx++; + } + } + + return pathIx == withPathInfoParts.Length; + } + + private bool LiteralsEqual(string str1, string str2) + { + // Most cases + if (String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + // Handle turkish i + str1 = str1.ToUpperInvariant(); + str2 = str2.ToUpperInvariant(); + + // Invariant IgnoreCase would probably be better but it's not available in PCL + return String.Equals(str1, str2, StringComparison.CurrentCultureIgnoreCase); + } + + private bool ExplodeComponents(ref string[] withPathInfoParts) + { + var totalComponents = new List<string>(); + for (var i = 0; i < withPathInfoParts.Length; i++) + { + var component = withPathInfoParts[i]; + if (String.IsNullOrEmpty(component)) continue; + + if (this.PathComponentsCount != this.TotalComponentsCount + && this.componentsWithSeparators[i]) + { + var subComponents = component.Split(ComponentSeperator); + if (subComponents.Length < 2) return false; + totalComponents.AddRange(subComponents); + } + else + { + totalComponents.Add(component); + } + } + + withPathInfoParts = totalComponents.ToArray(); + return true; + } + + public object CreateRequest(string pathInfo, Dictionary<string, string> queryStringAndFormData, object fromInstance) + { + var requestComponents = pathInfo.Split(PathSeperatorChar) + .Where(x => !String.IsNullOrEmpty(x)).ToArray(); + + ExplodeComponents(ref requestComponents); + + if (requestComponents.Length != this.TotalComponentsCount) + { + var isValidWildCardPath = this.IsWildCardPath + && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount; + + if (!isValidWildCardPath) + throw new ArgumentException(String.Format( + "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'", + pathInfo, this.restPath)); + } + + var requestKeyValuesMap = new Dictionary<string, string>(); + var pathIx = 0; + for (var i = 0; i < this.TotalComponentsCount; i++) + { + var variableName = this.variablesNames[i]; + if (variableName == null) + { + pathIx++; + continue; + } + + string propertyNameOnRequest; + if (!this.propertyNamesMap.TryGetValue(variableName.ToLower(), out propertyNameOnRequest)) + { + if (String.Equals("ignore", variableName, StringComparison.OrdinalIgnoreCase)) + { + pathIx++; + continue; + } + + throw new ArgumentException("Could not find property " + + variableName + " on " + RequestType.GetMethodName()); + } + + var value = requestComponents.Length > pathIx ? requestComponents[pathIx] : null; //wildcard has arg mismatch + if (value != null && this.isWildcard[i]) + { + if (i == this.TotalComponentsCount - 1) + { + // Wildcard at end of path definition consumes all the rest + var sb = new StringBuilder(); + sb.Append(value); + for (var j = pathIx + 1; j < requestComponents.Length; j++) + { + sb.Append(PathSeperatorChar + requestComponents[j]); + } + value = sb.ToString(); + } + else + { + // Wildcard in middle of path definition consumes up until it + // hits a match for the next element in the definition (which must be a literal) + // It may consume 0 or more path parts + var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1]; + if (!String.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase)) + { + var sb = new StringBuilder(); + sb.Append(value); + pathIx++; + while (!String.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase)) + { + sb.Append(PathSeperatorChar + requestComponents[pathIx++]); + } + value = sb.ToString(); + } + else + { + value = null; + } + } + } + else + { + // Variable consumes single path item + pathIx++; + } + + requestKeyValuesMap[propertyNameOnRequest] = value; + } + + if (queryStringAndFormData != null) + { + //Query String and form data can override variable path matches + //path variables < query string < form data + foreach (var name in queryStringAndFormData) + { + requestKeyValuesMap[name.Key] = name.Value; + } + } + + return this.typeDeserializer.PopulateFromMap(fromInstance, requestKeyValuesMap); + } + + public override int GetHashCode() + { + return UniqueMatchHashKey.GetHashCode(); + } + } +}
\ No newline at end of file diff --git a/Emby.Server.Implementations/Services/StringMapTypeDeserializer.cs b/Emby.Server.Implementations/Services/StringMapTypeDeserializer.cs new file mode 100644 index 000000000..fc1cf4ed9 --- /dev/null +++ b/Emby.Server.Implementations/Services/StringMapTypeDeserializer.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace Emby.Server.Implementations.Services +{ + /// <summary> + /// Serializer cache of delegates required to create a type from a string map (e.g. for REST urls) + /// </summary> + public class StringMapTypeDeserializer + { + internal class PropertySerializerEntry + { + public PropertySerializerEntry(Action<object,object> propertySetFn, Func<string, object> propertyParseStringFn) + { + PropertySetFn = propertySetFn; + PropertyParseStringFn = propertyParseStringFn; + } + + public Action<object, object> PropertySetFn; + public Func<string,object> PropertyParseStringFn; + public Type PropertyType; + } + + private readonly Type type; + private readonly Dictionary<string, PropertySerializerEntry> propertySetterMap + = new Dictionary<string, PropertySerializerEntry>(StringComparer.OrdinalIgnoreCase); + + public Func<string, object> GetParseFn(Type propertyType) + { + if (propertyType == typeof(string)) + return s => s; + + return _GetParseFn(propertyType); + } + + private readonly Func<Type, object> _CreateInstanceFn; + private readonly Func<Type, Func<string, object>> _GetParseFn; + + public StringMapTypeDeserializer(Func<Type, object> createInstanceFn, Func<Type, Func<string, object>> getParseFn, Type type) + { + _CreateInstanceFn = createInstanceFn; + _GetParseFn = getParseFn; + this.type = type; + + foreach (var propertyInfo in RestPath.GetSerializableProperties(type)) + { + var propertySetFn = TypeAccessor.GetSetPropertyMethod(type, propertyInfo); + var propertyType = propertyInfo.PropertyType; + var propertyParseStringFn = GetParseFn(propertyType); + var propertySerializer = new PropertySerializerEntry(propertySetFn, propertyParseStringFn) { PropertyType = propertyType }; + + propertySetterMap[propertyInfo.Name] = propertySerializer; + } + } + + public object PopulateFromMap(object instance, IDictionary<string, string> keyValuePairs) + { + string propertyName = null; + string propertyTextValue = null; + PropertySerializerEntry propertySerializerEntry = null; + + if (instance == null) + instance = _CreateInstanceFn(type); + + foreach (var pair in keyValuePairs.Where(x => !string.IsNullOrEmpty(x.Value))) + { + propertyName = pair.Key; + propertyTextValue = pair.Value; + + if (!propertySetterMap.TryGetValue(propertyName, out propertySerializerEntry)) + { + if (propertyName == "v") + { + continue; + } + + continue; + } + + if (propertySerializerEntry.PropertySetFn == null) + { + continue; + } + + if (propertySerializerEntry.PropertyType == typeof(bool)) + { + //InputExtensions.cs#530 MVC Checkbox helper emits extra hidden input field, generating 2 values, first is the real value + propertyTextValue = LeftPart(propertyTextValue, ','); + } + + var value = propertySerializerEntry.PropertyParseStringFn(propertyTextValue); + if (value == null) + { + continue; + } + propertySerializerEntry.PropertySetFn(instance, value); + } + + return instance; + } + + public static string LeftPart(string strVal, char needle) + { + if (strVal == null) return null; + var pos = strVal.IndexOf(needle); + return pos == -1 + ? strVal + : strVal.Substring(0, pos); + } + } + + internal class TypeAccessor + { + public static Action<object, object> GetSetPropertyMethod(Type type, PropertyInfo propertyInfo) + { + if (!propertyInfo.CanWrite || propertyInfo.GetIndexParameters().Any()) return null; + + var setMethodInfo = propertyInfo.SetMethod; + return (instance, value) => setMethodInfo.Invoke(instance, new[] { value }); + } + } +} diff --git a/Emby.Server.Implementations/Services/UrlExtensions.cs b/Emby.Server.Implementations/Services/UrlExtensions.cs new file mode 100644 index 000000000..c7346789a --- /dev/null +++ b/Emby.Server.Implementations/Services/UrlExtensions.cs @@ -0,0 +1,33 @@ +using System; + +namespace Emby.Server.Implementations.Services +{ + /// <summary> + /// Donated by Ivan Korneliuk from his post: + /// http://korneliuk.blogspot.com/2012/08/servicestack-reusing-dtos.html + /// + /// Modified to only allow using routes matching the supplied HTTP Verb + /// </summary> + public static class UrlExtensions + { + public static string GetMethodName(this Type type) + { + var typeName = type.FullName != null //can be null, e.g. generic types + ? LeftPart(type.FullName, "[[") //Generic Fullname + .Replace(type.Namespace + ".", "") //Trim Namespaces + .Replace("+", ".") //Convert nested into normal type + : type.Name; + + return type.IsGenericParameter ? "'" + typeName : typeName; + } + + public static string LeftPart(string strVal, string needle) + { + if (strVal == null) return null; + var pos = strVal.IndexOf(needle, StringComparison.OrdinalIgnoreCase); + return pos == -1 + ? strVal + : strVal.Substring(0, pos); + } + } +}
\ No newline at end of file |
