基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-17 9b5711d3124622b1f1b18500d442c76492da877a
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
using System.Collections.Concurrent;
using System.IO;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
 
namespace Moli.Desktop.Api;
 
public sealed class LocalApiService : BackgroundService, ILocalApiStatus
{
    private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
    {
        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
    };
 
    private readonly IDesktopRuntime _runtime;
    private readonly IConfigurationService _configuration;
    private readonly IPluginManager _plugins;
    private readonly IDiagnosticsService _diagnostics;
    private readonly IRuntimeEventBus _events;
    private readonly ConcurrentDictionary<WebSocket, byte> _sockets = new();
    private readonly object _statusGate = new();
    private IDisposable? _eventSubscription;
    private WebApplication? _app;
    private LocalApiStatusSnapshot _status = new();
 
    public LocalApiService(
        IDesktopRuntime runtime,
        IConfigurationService configuration,
        IPluginManager plugins,
        IDiagnosticsService diagnostics,
        IRuntimeEventBus events)
    {
        _runtime = runtime;
        _configuration = configuration;
        _plugins = plugins;
        _diagnostics = diagnostics;
        _events = events;
    }
 
    public LocalApiStatusSnapshot GetStatus()
    {
        lock (_statusGate)
        {
            return _status;
        }
    }
 
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var settings = await _configuration.LoadAppSettingsAsync(stoppingToken).ConfigureAwait(false);
        SetStatus(new LocalApiStatusSnapshot { Port = settings.Runtime.ApiPort });
        _eventSubscription = _events.Subscribe(BroadcastAsync);
 
        try
        {
            var builder = WebApplication.CreateBuilder(new WebApplicationOptions
            {
                ApplicationName = typeof(LocalApiService).Assembly.GetName().Name,
                Args = []
            });
            builder.WebHost.UseUrls($"http://127.0.0.1:{settings.Runtime.ApiPort}");
            builder.Services.Configure<JsonOptions>(options =>
            {
                options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                options.SerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
            });
 
            _app = builder.Build();
            _app.UseWebSockets();
            MapEndpoints(_app);
 
            SetStatus(new LocalApiStatusSnapshot
            {
                IsListening = true,
                Port = settings.Runtime.ApiPort,
                Message = $"Listening on http://127.0.0.1:{settings.Runtime.ApiPort}"
            });
            _diagnostics.Record(
                DiagnosticSeverity.Info,
                "LocalApiStarted",
                "Local API started.",
                new Dictionary<string, string> { ["url"] = $"http://127.0.0.1:{settings.Runtime.ApiPort}" });
 
            await _app.RunAsync(stoppingToken).ConfigureAwait(false);
        }
        catch (Exception ex) when (ex is IOException or InvalidOperationException or HttpListenerException)
        {
            SetStatus(new LocalApiStatusSnapshot
            {
                Port = settings.Runtime.ApiPort,
                ErrorCode = "LocalApiStartFailed",
                Message = ex.Message
            });
            _diagnostics.Record(
                DiagnosticSeverity.Error,
                "LocalApiStartFailed",
                "Local API failed to start; desktop runtime will continue.",
                new Dictionary<string, string>
                {
                    ["host"] = "127.0.0.1",
                    ["port"] = settings.Runtime.ApiPort.ToString(),
                    ["exception"] = ex.GetType().Name,
                    ["message"] = ex.Message
                });
        }
    }
 
    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        _eventSubscription?.Dispose();
        foreach (var socket in _sockets.Keys)
        {
            if (socket.State == WebSocketState.Open)
            {
                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Application stopping.", cancellationToken).ConfigureAwait(false);
            }
 
            socket.Dispose();
        }
 
        _sockets.Clear();
        if (_app is not null)
        {
            await _app.StopAsync(cancellationToken).ConfigureAwait(false);
            await _app.DisposeAsync().ConfigureAwait(false);
        }
 
        SetStatus(GetStatus() with { IsListening = false, Message = "Stopped." });
        await base.StopAsync(cancellationToken).ConfigureAwait(false);
    }
 
    private void MapEndpoints(WebApplication app)
    {
        app.MapGet("/api/status", async () =>
        {
            var state = await _runtime.GetStateAsync().ConfigureAwait(false);
            return Results.Json(ApiStatusResponse.From(state, GetStatus()), JsonOptions);
        });
 
        app.MapGet("/api/plugins", async () =>
        {
            var state = await _runtime.GetStateAsync().ConfigureAwait(false);
            return Results.Json(state.Plugins.Select(PluginResponse.From), JsonOptions);
        });
 
        app.MapPost("/api/plugins/{id}/reload", async (string id) =>
        {
            var reload = await _plugins.ReloadAsync(new PluginId(id)).ConfigureAwait(false);
            if (!reload.Succeeded)
            {
                return Error(reload.ErrorCode ?? "PluginReloadFailed", reload.Message ?? "Plugin reload failed.", StatusCodes.Status404NotFound);
            }
 
            var state = await _runtime.ReloadPluginsAsync().ConfigureAwait(false);
            return ToResult(state);
        });
 
        app.MapPost("/api/wallpaper/enable", async () => ToResult(await _runtime.EnableWallpaperAsync().ConfigureAwait(false)));
        app.MapPost("/api/wallpaper/disable", async () => ToResult(await _runtime.DisableWallpaperAsync().ConfigureAwait(false)));
        app.MapPost("/api/edit-mode", async (HttpContext context) =>
        {
            var enabled = await ReadModeAsync(context).ConfigureAwait(false)
                ?? !(await _runtime.GetStateAsync().ConfigureAwait(false)).IsEditMode;
            return ToResult(await _runtime.SetEditModeAsync(enabled).ConfigureAwait(false));
        });
        app.MapPost("/api/safe-input-mode", async (HttpContext context) =>
        {
            var enabled = await ReadModeAsync(context).ConfigureAwait(false)
                ?? !(await _runtime.GetStateAsync().ConfigureAwait(false)).IsSafeInputMode;
            return ToResult(await _runtime.SetSafeInputModeAsync(enabled).ConfigureAwait(false));
        });
        app.MapPost("/api/widgets/{instanceId}/layout", async (string instanceId, WidgetLayoutPatchRequest request) =>
        {
            var result = await _runtime.UpdateWidgetLayoutAsync(new WidgetInstanceId(instanceId), request.ToPatch()).ConfigureAwait(false);
            if (!result.Succeeded)
            {
                return Error(result.ErrorCode ?? "WidgetLayoutUpdateFailed", result.Message ?? "Widget layout update failed.", StatusCodes.Status400BadRequest);
            }
 
            return Results.Json(WidgetResponse.From(result.Value!), JsonOptions);
        });
        app.MapGet("/ws/events", AcceptWebSocketAsync);
    }
 
    private async Task AcceptWebSocketAsync(HttpContext context)
    {
        if (!context.WebSockets.IsWebSocketRequest)
        {
            context.Response.StatusCode = StatusCodes.Status400BadRequest;
            await context.Response.WriteAsJsonAsync(new ApiErrorResponse("WebSocketRequired", "Use a WebSocket request."), JsonOptions).ConfigureAwait(false);
            return;
        }
 
        using var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
        _sockets.TryAdd(socket, 0);
        await SendAsync(socket, new RuntimeEventResponse("api.connected", DateTimeOffset.UtcNow, GetStatus()), context.RequestAborted).ConfigureAwait(false);
 
        var buffer = new byte[1024];
        try
        {
            while (!context.RequestAborted.IsCancellationRequested && socket.State == WebSocketState.Open)
            {
                var message = await socket.ReceiveAsync(buffer, context.RequestAborted).ConfigureAwait(false);
                if (message.MessageType == WebSocketMessageType.Close)
                {
                    break;
                }
            }
        }
        finally
        {
            _sockets.TryRemove(socket, out _);
        }
    }
 
    private async Task BroadcastAsync(RuntimeEvent runtimeEvent)
    {
        var payload = RuntimeEventResponse.From(runtimeEvent);
        foreach (var socket in _sockets.Keys)
        {
            if (socket.State != WebSocketState.Open)
            {
                _sockets.TryRemove(socket, out _);
                continue;
            }
 
            try
            {
                await SendAsync(socket, payload, CancellationToken.None).ConfigureAwait(false);
            }
            catch (WebSocketException)
            {
                _sockets.TryRemove(socket, out _);
            }
        }
    }
 
    private static async Task<bool?> ReadModeAsync(HttpContext context)
    {
        if (context.Request.Query.TryGetValue("enabled", out var values)
            && bool.TryParse(values.FirstOrDefault(), out var queryValue))
        {
            return queryValue;
        }
 
        if (context.Request.ContentLength is null or 0)
        {
            return null;
        }
 
        var request = await context.Request.ReadFromJsonAsync<ModeRequest>(JsonOptions).ConfigureAwait(false);
        return request?.Enabled;
    }
 
    private IResult ToResult(OperationResult<AppRuntimeState> result)
    {
        if (!result.Succeeded)
        {
            return Error(result.ErrorCode ?? "RuntimeCommandFailed", result.Message ?? "Runtime command failed.", StatusCodes.Status400BadRequest);
        }
 
        return Results.Json(ApiStatusResponse.From(result.Value!, GetStatus()), JsonOptions);
    }
 
    private static IResult Error(string code, string message, int statusCode)
        => Results.Json(new ApiErrorResponse(code, message), JsonOptions, statusCode: statusCode);
 
    private static Task SendAsync(WebSocket socket, object payload, CancellationToken cancellationToken)
    {
        var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(payload, JsonOptions));
        return socket.SendAsync(bytes, WebSocketMessageType.Text, true, cancellationToken);
    }
 
    private void SetStatus(LocalApiStatusSnapshot status)
    {
        lock (_statusGate)
        {
            _status = status;
        }
    }
}