|
| 1 | +using System.Text.Json.Serialization; |
| 2 | +using Microsoft.Extensions.DependencyInjection; |
| 3 | +using Shiny.AppDeviceBridge; |
| 4 | +using Shiny.AppDeviceBridge.Maps; |
| 5 | +using Shiny.Extensions.Stores; |
| 6 | +using Shiny.Net.HttpServer; |
| 7 | + |
| 8 | +namespace Sample; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// <c>/_bridge/sample-traffic</c>: lets the Map page pick the traffic providers and enter their API keys while the sample runs, |
| 12 | +/// so each provider can be tried without a key in the repository or a rebuild. |
| 13 | +/// <code> |
| 14 | +/// GET /_bridge/sample-traffic { flow, incidents, keys: ["tomtom", …] } which keys are set, never the keys |
| 15 | +/// PUT /_bridge/sample-traffic/keys/{provider} { "key": "…" } tomtom, here, azure-maps |
| 16 | +/// DELETE /_bridge/sample-traffic/keys/{provider} |
| 17 | +/// PUT /_bridge/sample-traffic/selection { "flow": "here", "incidents": true } flow: none, tomtom, here, azure-maps |
| 18 | +/// </code> |
| 19 | +/// <para> |
| 20 | +/// Keys go into the device's secure store (Keychain, Android KeyStore, DPAPI; a plain file on Linux) and are write-only: the |
| 21 | +/// page can set or clear one, but no route returns it. The selection is applied to <see cref="MapsOptions"/> at once and kept |
| 22 | +/// for the next launch. A bridge like any other, so it is behind the bridge policy — this is a sample's convenience, not a |
| 23 | +/// pattern for shipping third-party keys to users. |
| 24 | +/// </para> |
| 25 | +/// </summary> |
| 26 | +sealed class TrafficProvidersBridge : IWebAppBridge |
| 27 | +{ |
| 28 | + const string TomTom = "tomtom"; |
| 29 | + const string Here = "here"; |
| 30 | + const string AzureMaps = "azure-maps"; |
| 31 | + const string None = "none"; |
| 32 | + static readonly string[] Providers = [TomTom, Here, AzureMaps]; |
| 33 | + |
| 34 | + readonly MapsOptions maps; |
| 35 | + readonly Lazy<IKeyValueStore> secure; |
| 36 | + readonly Lazy<IKeyValueStore> local; |
| 37 | + readonly Lock gate = new(); |
| 38 | + |
| 39 | + public TrafficProvidersBridge(MapsOptions maps, IServiceProvider services) |
| 40 | + { |
| 41 | + this.maps = maps; |
| 42 | + this.secure = new(() => services.GetKeyedService<IKeyValueStore>(StoreKeys.Secure) ?? Stores.Secure); |
| 43 | + this.local = new(() => services.GetKeyedService<IKeyValueStore>(StoreKeys.Default) ?? Stores.Default); |
| 44 | + |
| 45 | + // What the user picked last time, so traffic is back on at the next launch without visiting the page. |
| 46 | + this.Apply(); |
| 47 | + } |
| 48 | + |
| 49 | + public string Name => "sample-traffic"; |
| 50 | + |
| 51 | + public bool IsSupported => true; |
| 52 | + |
| 53 | + public void Map(WebAppBridgeRoutes routes) => routes |
| 54 | + .MapGet("", this.GetAsync) |
| 55 | + .MapPut("/keys/{provider}", this.SetKeyAsync) |
| 56 | + .MapDelete("/keys/{provider}", this.ClearKeyAsync) |
| 57 | + .MapPut("/selection", this.SelectAsync); |
| 58 | + |
| 59 | + ValueTask GetAsync(HttpContext context) |
| 60 | + => WebAppBridgeResults.Json(context, this.Settings(), TrafficProvidersJsonContext.Default.TrafficProviderSettings); |
| 61 | + |
| 62 | + async ValueTask SetKeyAsync(HttpContext context) |
| 63 | + { |
| 64 | + if (Provider(context) is not { } provider) |
| 65 | + { |
| 66 | + await WebAppBridgeResults.NotFound(context, "No such traffic provider."); |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + var body = await WebAppBridgeResults.ReadBodyAsync(context, TrafficProvidersJsonContext.Default.TrafficProviderKey); |
| 71 | + if (String.IsNullOrWhiteSpace(body?.Key)) |
| 72 | + { |
| 73 | + await WebAppBridgeResults.BadRequest(context, "A key is required."); |
| 74 | + return; |
| 75 | + } |
| 76 | + |
| 77 | + lock (this.gate) |
| 78 | + { |
| 79 | + this.secure.Value.Set(KeyName(provider), body.Key.Trim()); |
| 80 | + this.Apply(); |
| 81 | + } |
| 82 | + |
| 83 | + await this.GetAsync(context); |
| 84 | + } |
| 85 | + |
| 86 | + async ValueTask ClearKeyAsync(HttpContext context) |
| 87 | + { |
| 88 | + if (Provider(context) is not { } provider) |
| 89 | + { |
| 90 | + await WebAppBridgeResults.NotFound(context, "No such traffic provider."); |
| 91 | + return; |
| 92 | + } |
| 93 | + |
| 94 | + lock (this.gate) |
| 95 | + { |
| 96 | + this.secure.Value.Remove(KeyName(provider)); |
| 97 | + this.Apply(); |
| 98 | + } |
| 99 | + |
| 100 | + await this.GetAsync(context); |
| 101 | + } |
| 102 | + |
| 103 | + async ValueTask SelectAsync(HttpContext context) |
| 104 | + { |
| 105 | + var body = await WebAppBridgeResults.ReadBodyAsync(context, TrafficProvidersJsonContext.Default.TrafficProviderSelection); |
| 106 | + var flow = body?.Flow ?? None; |
| 107 | + |
| 108 | + if (flow != None && !Providers.Contains(flow)) |
| 109 | + { |
| 110 | + await WebAppBridgeResults.BadRequest(context, $"'{flow}' is not a traffic provider."); |
| 111 | + return; |
| 112 | + } |
| 113 | + |
| 114 | + lock (this.gate) |
| 115 | + { |
| 116 | + this.local.Value.Set("sample.traffic.flow", flow); |
| 117 | + this.local.Value.Set("sample.traffic.incidents", body?.Incidents == true ? "true" : "false"); |
| 118 | + this.Apply(); |
| 119 | + } |
| 120 | + |
| 121 | + await this.GetAsync(context); |
| 122 | + } |
| 123 | + |
| 124 | + /// <summary>Builds the providers from the stored selection and keys. A selection whose key is missing draws nothing.</summary> |
| 125 | + void Apply() |
| 126 | + { |
| 127 | + var flow = this.Flow; |
| 128 | + var key = flow == None ? null : this.Key(flow); |
| 129 | + |
| 130 | + this.maps.Traffic = key is null ? null : flow switch |
| 131 | + { |
| 132 | + TomTom => new TomTomTrafficProvider(key), |
| 133 | + Here => new HereTrafficProvider(key), |
| 134 | + AzureMaps => new AzureMapsTrafficProvider(key), |
| 135 | + _ => null |
| 136 | + }; |
| 137 | + |
| 138 | + this.maps.TrafficIncidents = this.Incidents && this.Key(TomTom) is { } tomTom ? new TomTomIncidentProvider(tomTom) : null; |
| 139 | + } |
| 140 | + |
| 141 | + TrafficProviderSettings Settings() => new( |
| 142 | + this.Flow, |
| 143 | + this.Incidents, |
| 144 | + [.. Providers.Where(x => this.Key(x) is not null)], |
| 145 | + this.maps.Traffic is not null, |
| 146 | + this.maps.TrafficIncidents is not null |
| 147 | + ); |
| 148 | + |
| 149 | + string Flow => this.local.Value.Get<string>("sample.traffic.flow") is { } flow && (flow == None || Providers.Contains(flow)) ? flow : None; |
| 150 | + |
| 151 | + bool Incidents => this.local.Value.Get<string>("sample.traffic.incidents") == "true"; |
| 152 | + |
| 153 | + string? Key(string provider) => this.secure.Value.Get<string>(KeyName(provider)) is { Length: > 0 } key ? key : null; |
| 154 | + |
| 155 | + static string KeyName(string provider) => $"sample.traffic.key.{provider}"; |
| 156 | + |
| 157 | + static string? Provider(HttpContext context) |
| 158 | + => context.Request.RouteValues["provider"] is { } provider && Providers.Contains(provider) ? provider : null; |
| 159 | +} |
| 160 | + |
| 161 | +/// <param name="Flow"><c>none</c>, <c>tomtom</c>, <c>here</c> or <c>azure-maps</c>.</param> |
| 162 | +/// <param name="Keys">The providers whose key is set. The keys themselves never leave the device's secure store.</param> |
| 163 | +/// <param name="FlowActive">Whether a flow provider is running: the selection has its key.</param> |
| 164 | +/// <param name="IncidentsActive">Whether TomTom incidents are running: selected, with the TomTom key set.</param> |
| 165 | +sealed record TrafficProviderSettings(string Flow, bool Incidents, IReadOnlyList<string> Keys, bool FlowActive, bool IncidentsActive); |
| 166 | + |
| 167 | +sealed record TrafficProviderKey(string? Key); |
| 168 | + |
| 169 | +sealed record TrafficProviderSelection(string? Flow, bool Incidents); |
| 170 | + |
| 171 | +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true)] |
| 172 | +[JsonSerializable(typeof(TrafficProviderSettings))] |
| 173 | +[JsonSerializable(typeof(TrafficProviderKey))] |
| 174 | +[JsonSerializable(typeof(TrafficProviderSelection))] |
| 175 | +partial class TrafficProvidersJsonContext : JsonSerializerContext; |
0 commit comments