using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace StardewModdingAPI.Web.Framework.UserAgentParsing { /// Middleware that detects the client's platform. public class ClientPlatformMiddleware { /// The key used to retrieve the client's platform from . public const string ClientPlatformKey = "ClientPlatformKey"; /// The next delegate in the middleware pipeline. private readonly RequestDelegate Next; /// Construct an instance. /// The next delegate in the middleware pipeline. public ClientPlatformMiddleware(RequestDelegate next) { this.Next = next; } /// Invoke the middleware. /// The HTTP request context. public async Task InvokeAsync(HttpContext context) { context.Items[ClientPlatformMiddleware.ClientPlatformKey] = this.DetectClientPlatform(context.Request.Headers["User-Agent"]); await this.Next(context); } /// Detect the platform that the client is on. /// The client's user agent. /// The client's platform, or null if no platforms could be detected. private Platform? DetectClientPlatform(string userAgent) { switch (userAgent) { case string ua when ua.Contains("Windows"): return Platform.Windows; // check for Android before Linux because Android user agents also contain Linux case string ua when ua.Contains("Android"): return Platform.Android; case string ua when ua.Contains("Linux"): return Platform.Linux; case string ua when ua.Contains("Mac"): return Platform.Mac; default: return null; } } } }