/
PiletService.cs
191 lines (161 loc) · 5.59 KB
/
PiletService.cs
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
using Microsoft.Extensions.Configuration;
using Microsoft.JSInterop;
using Piral.Blazor.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Linq;
using System.Runtime.Loader;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace Piral.Blazor.Core;
public sealed class PiletService : IPiletService, IDisposable
{
private readonly Uri _baseUrl;
private readonly IConfiguration _config;
private readonly string _name;
private readonly string _version;
private readonly IJSRuntime _js;
private readonly HttpClient _client;
private readonly bool _core;
private readonly AssemblyLoadContext _context;
private readonly List<EventListener> _listeners;
private readonly List<string> _loadedLanguages;
private readonly Dictionary<string, List<string>> _satellites;
public event EventHandler LanguageChanged;
private PiletService(IJSRuntime js, HttpClient client, bool core, AssemblyLoadContext context)
{
_js = js;
_listeners = new List<EventListener>();
_client = client;
_core = core;
_context = context;
_loadedLanguages = new List<string>();
}
public PiletService(IJSRuntime js, HttpClient client, string baseUrl) : this(js, client, false, AssemblyLoadContext.Default)
{
_name = "(unknown)";
_version = "0.0.0";
// Move base URL up in case of a `_framework` containment
_baseUrl = new Uri(baseUrl.Replace("/_framework/", "/"));
// Create config wrapper
_config = new ConfigurationBuilder().AddJsonStream(GetStream("{}")).Build();
}
public PiletService(IJSRuntime js, HttpClient client, AssemblyLoadContext context, PiletDefinition pilet) : this(js, client, context == AssemblyLoadContext.Default, context)
{
_name = pilet.Name;
_version = pilet.Version;
// define satellites
_satellites = pilet.Satellites;
// base URL is already given
_baseUrl = new Uri(pilet.BaseUrl);
// Create config wrapper
_config = new ConfigurationBuilder().AddJsonStream(GetStream(pilet.Config)).Build();
LoadLanguage(Localization.Language).Forget();
}
public string Name => _name;
public string Version => _version;
public bool IsCore => _core;
public IConfiguration Config => _config;
public string GetUrl(string localPath)
{
if (localPath.StartsWith("/") && !localPath.StartsWith("//"))
{
localPath = localPath.Substring(1);
}
return new Uri(_baseUrl, localPath).AbsoluteUri;
}
public async Task LoadLanguage(string language)
{
if (!_loadedLanguages.Contains(language))
{
_loadedLanguages.Add(language);
if (_satellites?.TryGetValue(language, out var satellites) ?? false)
{
foreach (var satellite in satellites)
{
var url = GetUrl(satellite);
var dep = await _client.GetStreamAsync(url);
_context.LoadFromStream(dep);
}
}
// we also support loading region specific languages, e.g., "de-AT"
// in this case we also need to take the "front" to load all satellites
var idx = language.IndexOf('-');
if (idx != -1)
{
var primaryLanguage = language.Substring(0, idx);
await LoadLanguage(primaryLanguage);
}
}
}
public void InformLanguageChange() => LanguageChanged?.Invoke(this, EventArgs.Empty);
public void DispatchEvent<T>(string type, T args)
{
_js.InvokeVoidAsync("Blazor.emitPiralEvent", type, args);
}
public void AddEventListener<T>(string type, Action<T> handler)
{
_listeners.Add(
new EventListener
{
Handler = (json) =>
{
handler.Invoke(json.Deserialize<T>());
},
Reference = handler,
Type = type,
}
);
}
public void RemoveEventListener<T>(string type, Action<T> handler)
{
#pragma warning disable 252
_listeners.RemoveAll(listener => listener.Type == type && listener.Reference == handler);
#pragma warning restore 252
}
public void CallEventListeners(string type, JsonElement args)
{
var originalListeners = _listeners.ToList();
foreach (var listener in originalListeners)
{
if (listener.Type == type)
{
listener.Handler.Invoke(args);
}
}
}
public async Task<T> Call<T>(string fn, params object[] args)
{
var id = Guid.NewGuid();
var responseTo = $"blazor-interop-response-{id}";
var tcs = new TaskCompletionSource<T>();
var handler = tcs.SetResult;
AddEventListener(responseTo, handler);
DispatchEvent($"blazor-interop-{Name}@{Version}", new
{
responseTo,
fn,
args,
});
var result = await tcs.Task;
RemoveEventListener(responseTo, handler);
return result;
}
private static Stream GetStream(string s) => new MemoryStream(Encoding.UTF8.GetBytes(s));
public void Dispose()
{
if (_context != AssemblyLoadContext.Default)
{
_context.Unload();
}
}
struct EventListener
{
public object Reference;
public string Type;
public Action<JsonElement> Handler;
}
}