-
Notifications
You must be signed in to change notification settings - Fork 281
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
realize forward webSocket service & update actions
- Loading branch information
Showing
7 changed files
with
191 additions
and
56 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
using System.Text; | ||
using System.Text.Json; | ||
using Lagrange.OneBot.Core.Entity.Action; | ||
using Lagrange.OneBot.Core.Entity.Meta; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.Logging; | ||
using PHS.Networking.Enums; | ||
using WebsocketsSimple.Server; | ||
using WebsocketsSimple.Server.Events.Args; | ||
using WebsocketsSimple.Server.Models; | ||
using Timer = System.Threading.Timer; | ||
|
||
namespace Lagrange.OneBot.Core.Network; | ||
|
||
public sealed class ForwardWSService : ILagrangeWebService | ||
{ | ||
public event EventHandler<MsgRecvEventArgs> OnMessageReceived = delegate { }; | ||
|
||
private readonly WebsocketServer _server; | ||
|
||
private readonly IConfiguration _config; | ||
|
||
private readonly ILogger _logger; | ||
|
||
private readonly Timer _timer; | ||
|
||
private readonly bool _shouldAuthenticate; | ||
|
||
private static readonly Encoding _utf8 = new UTF8Encoding(false); | ||
|
||
public ForwardWSService(IConfiguration config, ILogger<LagrangeApp> logger) | ||
{ | ||
_config = config; | ||
_logger = logger; | ||
|
||
var ws = _config.GetSection("Implementation").GetSection("ForwardWebSocket"); | ||
|
||
_timer = new Timer(OnHeartbeat, null, int.MaxValue, ws.GetValue<int>("HeartBeatInterval")); | ||
_shouldAuthenticate = !string.IsNullOrEmpty(_config["AccessToken"]); | ||
|
||
_server = new WebsocketServer(new ParamsWSServer(ws.GetValue<int>("Port"))); | ||
_server.MessageEvent += OnMessage; | ||
|
||
if (_shouldAuthenticate) | ||
_server.ConnectionEvent += OnConnection; | ||
} | ||
|
||
public async Task StartAsync(CancellationToken cancellationToken) | ||
{ | ||
await _server.StartAsync(cancellationToken); | ||
var lifecycle = new OneBotLifecycle(_config.GetValue<uint>("Account:Uin"), "connect"); | ||
await SendJsonAsync(lifecycle, cancellationToken); | ||
} | ||
|
||
public Task StopAsync(CancellationToken cancellationToken) | ||
{ | ||
_timer.Dispose(); | ||
_server.Dispose(); | ||
|
||
return Task.CompletedTask; | ||
} | ||
|
||
public async Task SendJsonAsync<T>(T json, CancellationToken cancellationToken = default) | ||
{ | ||
var payload = JsonSerializer.Serialize(json); | ||
|
||
if (json is OneBotResult oneBotResult) | ||
{ | ||
var connection = _server.Connections.FirstOrDefault( | ||
(c) => c.ConnectionId == oneBotResult.Identifier | ||
); | ||
|
||
if (connection is not null) | ||
await _server.SendToConnectionAsync(payload, connection); | ||
} | ||
else | ||
await _server.BroadcastToAllConnectionsAsync(payload, cancellationToken); | ||
} | ||
|
||
private void OnHeartbeat(object? sender) | ||
{ | ||
var status = new OneBotStatus(true, true); | ||
var heartBeat = new OneBotHeartBeat( | ||
_config.GetValue<uint>("Account:Uin"), | ||
_config.GetValue<int>("Implementation:ForwardWebSocket:HeartBeatInterval"), | ||
status | ||
); | ||
|
||
SendJsonAsync(heartBeat).GetAwaiter().GetResult(); | ||
} | ||
|
||
private void OnConnection(object sender, WSConnectionServerEventArgs e) | ||
{ | ||
if ( | ||
_shouldAuthenticate | ||
&& e.ConnectionEventType == ConnectionEventType.Connected | ||
&& ( | ||
e.RequestHeaders is null | ||
|| !e.RequestHeaders.TryGetValue("Authorization", out string? authorization) | ||
|| authorization != $"Bearer {_config["AccessToken"]}" | ||
) | ||
) | ||
{ | ||
e.Connection.Websocket.Abort(); | ||
} | ||
} | ||
|
||
private void OnMessage(object sender, WSMessageServerEventArgs e) | ||
{ | ||
if (e.MessageEventType == MessageEventType.Receive) | ||
{ | ||
string text = _utf8.GetString(e.Bytes); | ||
OnMessageReceived.Invoke(this, new(e.Message ?? "", e.Connection.ConnectionId)); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,88 +1,100 @@ | ||
using System.Net.WebSockets; | ||
using System.Text; | ||
using System.Text.Json; | ||
using Lagrange.OneBot.Core.Entity.Meta; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.Logging; | ||
using Websocket.Client; | ||
using PHS.Networking.Enums; | ||
using WebsocketsSimple.Client; | ||
using WebsocketsSimple.Client.Events.Args; | ||
using WebsocketsSimple.Client.Models; | ||
using Timer = System.Threading.Timer; | ||
|
||
namespace Lagrange.OneBot.Core.Network; | ||
|
||
public sealed class ReverseWSService : ILagrangeWebService | ||
{ | ||
public event EventHandler<MsgRecvEventArgs> OnMessageReceived = delegate { }; | ||
private readonly WebsocketClient _socket; | ||
|
||
private readonly WebsocketClient _websocketClient; | ||
|
||
private readonly IConfiguration _config; | ||
|
||
private readonly ILogger _logger; | ||
|
||
private readonly Timer _timer; | ||
|
||
|
||
private static readonly Encoding _utf8 = new UTF8Encoding(false); | ||
|
||
public ReverseWSService(IConfiguration config, ILogger<LagrangeApp> logger) | ||
{ | ||
_config = config; | ||
_logger = logger; | ||
|
||
var ws = _config.GetSection("Implementation").GetSection("ReverseWebSocket"); | ||
string url = $"ws://{ws["Host"]}:{ws["Port"]}{ws["Suffix"]}"; | ||
|
||
_socket = new WebsocketClient(new Uri(url), () => | ||
var headers = new Dictionary<string, string>() | ||
{ | ||
var socket = new ClientWebSocket(); | ||
|
||
SetRequestHeader(socket, new Dictionary<string, string> | ||
{ | ||
{ "X-Client-Role", "Universal" }, | ||
{ "X-Self-ID", _config.GetValue<uint>("Account:Uin").ToString() }, | ||
{ "User-Agent", Constant.OneBotImpl } | ||
}); | ||
socket.Options.KeepAliveInterval = TimeSpan.FromSeconds(5); | ||
if (_config["AccessToken"] != null) socket.Options.SetRequestHeader("Authorization", $"Bearer {_config["AccessToken"]}"); | ||
|
||
return socket; | ||
}); | ||
|
||
_timer = new Timer(OnHeartbeat, null, int.MaxValue, config.GetValue<int>("Implementation:ReverseWebSocket:HeartBeatInterval")); | ||
_socket.MessageReceived.Subscribe(resp => OnMessageReceived.Invoke(this, new(resp.Text ?? ""))); | ||
{ "X-Client-Role", "Universal" }, | ||
{ "X-Self-ID", _config.GetValue<uint>("Account:Uin").ToString() }, | ||
{ "User-Agent", Constant.OneBotImpl } | ||
}; | ||
|
||
if (_config["AccessToken"] != null) | ||
headers.Add("Authorization", $"Bearer {_config["AccessToken"]}"); | ||
|
||
_websocketClient = new WebsocketClient( | ||
new ParamsWSClient( | ||
host: ws["Host"], | ||
port: ws.GetValue<int>("Port"), | ||
path: ws["Suffix"], | ||
isWebsocketSecured: false, | ||
keepAliveIntervalSec: ws.GetValue<int>("ReconnectInterval") / 1000, | ||
requestHeaders: headers | ||
) | ||
); | ||
_websocketClient.MessageEvent += OnMessage; | ||
|
||
_timer = new Timer(OnHeartbeat, null, int.MaxValue, ws.GetValue<int>("HeartBeatInterval")); | ||
} | ||
|
||
public async Task StartAsync(CancellationToken cancellationToken) | ||
{ | ||
await _socket.Start(); | ||
await _websocketClient.ConnectAsync(); | ||
|
||
var lifecycle = new OneBotLifecycle(_config.GetValue<uint>("Account:Uin"), "connect"); | ||
await SendJsonAsync(lifecycle, cancellationToken); | ||
} | ||
|
||
public Task StopAsync(CancellationToken cancellationToken) | ||
public async Task StopAsync(CancellationToken cancellationToken) | ||
{ | ||
_timer.Dispose(); | ||
_socket.Dispose(); | ||
|
||
return Task.CompletedTask; | ||
await _websocketClient.DisconnectAsync(); | ||
} | ||
|
||
public Task SendJsonAsync<T>(T json, CancellationToken cancellationToken = default) | ||
{ | ||
var payload = JsonSerializer.SerializeToUtf8Bytes(json); | ||
return _socket.SendInstant(payload); | ||
return _websocketClient.SendAsync(payload); | ||
} | ||
|
||
private void OnHeartbeat(object? sender) | ||
{ | ||
var status = new OneBotStatus(true, true); | ||
var heartBeat = new OneBotHeartBeat( | ||
_config.GetValue<uint>("Account:Uin"), | ||
_config.GetValue<int>("Implementation:ReverseWebSocket:HeartBeatInterval"), | ||
status); | ||
|
||
_config.GetValue<uint>("Account:Uin"), | ||
_config.GetValue<int>("Implementation:ReverseWebSocket:HeartBeatInterval"), | ||
status | ||
); | ||
|
||
SendJsonAsync(heartBeat); | ||
} | ||
|
||
private static void SetRequestHeader(ClientWebSocket webSocket, Dictionary<string, string> headers) | ||
private void OnMessage(object sender, WSMessageClientEventArgs e) | ||
{ | ||
foreach (var (key, value) in headers) webSocket.Options.SetRequestHeader(key, value); | ||
if (e.MessageEventType == MessageEventType.Receive) | ||
{ | ||
string text = _utf8.GetString(e.Bytes); | ||
OnMessageReceived.Invoke(this, new(e.Message ?? "")); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters