|
| 1 | +using System.Net.WebSockets; |
| 2 | +using System.Text; |
| 3 | +using iGotify_Notification_Assist.Models; |
| 4 | +using Newtonsoft.Json; |
| 5 | + |
| 6 | +namespace iGotify_Notification_Assist.Services; |
| 7 | + |
| 8 | +public sealed class WebSockClientNative |
| 9 | +{ |
| 10 | + private ClientWebSocket? _socket; |
| 11 | + private volatile bool _isStopped; |
| 12 | + |
| 13 | + public async Task RunAsync(Users user, CancellationToken cancellationToken) |
| 14 | + { |
| 15 | + var wsUrl = BuildWsUrl(user); |
| 16 | + var reconnectDelaySeconds = 1; |
| 17 | + |
| 18 | + while (!cancellationToken.IsCancellationRequested && !_isStopped) |
| 19 | + { |
| 20 | + try |
| 21 | + { |
| 22 | + using var socket = CreateSocket(user); |
| 23 | + _socket = socket; |
| 24 | + |
| 25 | + Console.WriteLine($"Client connecting (native): {user.ClientToken}"); |
| 26 | + await socket.ConnectAsync(new Uri(wsUrl), cancellationToken); |
| 27 | + Console.WriteLine($"Client connected (native): {user.ClientToken}"); |
| 28 | + |
| 29 | + reconnectDelaySeconds = 1; |
| 30 | + await ReceiveLoopAsync(socket, wsUrl, user.ClientToken, cancellationToken); |
| 31 | + } |
| 32 | + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested || _isStopped) |
| 33 | + { |
| 34 | + break; |
| 35 | + } |
| 36 | + catch (WebSocketException wse) |
| 37 | + { |
| 38 | + if (wse.Message.Contains("401")) |
| 39 | + { |
| 40 | + Console.WriteLine( |
| 41 | + $"ClientToken: {user.ClientToken} is not authorized and returned a 401 Unauthorized error! Skipping reconnection..."); |
| 42 | + break; |
| 43 | + } |
| 44 | + |
| 45 | + Console.WriteLine( |
| 46 | + $"Unable to connect or connection aborted for clientToken: {user.ClientToken}. {wse.Message}"); |
| 47 | + } |
| 48 | + catch (Exception ex) |
| 49 | + { |
| 50 | + Console.WriteLine($"Unexpected websocket error for clientToken: {user.ClientToken}. {ex.Message}"); |
| 51 | + } |
| 52 | + finally |
| 53 | + { |
| 54 | + _socket = null; |
| 55 | + } |
| 56 | + |
| 57 | + if (cancellationToken.IsCancellationRequested || _isStopped) |
| 58 | + break; |
| 59 | + |
| 60 | + var jitterMs = Random.Shared.Next(250, 1250); |
| 61 | + var delay = TimeSpan.FromSeconds(reconnectDelaySeconds) + TimeSpan.FromMilliseconds(jitterMs); |
| 62 | + |
| 63 | + Console.WriteLine( |
| 64 | + $"WebSocket reconnect for clientToken: {user.ClientToken} in {Math.Round(delay.TotalSeconds, 1)}s"); |
| 65 | + |
| 66 | + try |
| 67 | + { |
| 68 | + await Task.Delay(delay, cancellationToken); |
| 69 | + } |
| 70 | + catch (OperationCanceledException) |
| 71 | + { |
| 72 | + break; |
| 73 | + } |
| 74 | + |
| 75 | + reconnectDelaySeconds = Math.Min(reconnectDelaySeconds * 2, 30); |
| 76 | + } |
| 77 | + |
| 78 | + Console.WriteLine($"Client disconnected (native): {user.ClientToken}"); |
| 79 | + } |
| 80 | + |
| 81 | + public async Task StopAsync() |
| 82 | + { |
| 83 | + _isStopped = true; |
| 84 | + |
| 85 | + if (_socket == null) |
| 86 | + return; |
| 87 | + |
| 88 | + try |
| 89 | + { |
| 90 | + if (_socket.State == WebSocketState.Open || _socket.State == WebSocketState.CloseReceived) |
| 91 | + { |
| 92 | + await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Connection closing", |
| 93 | + CancellationToken.None); |
| 94 | + } |
| 95 | + else |
| 96 | + { |
| 97 | + _socket.Abort(); |
| 98 | + } |
| 99 | + } |
| 100 | + catch |
| 101 | + { |
| 102 | + _socket.Abort(); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + private static ClientWebSocket CreateSocket(Users user) |
| 107 | + { |
| 108 | + var socket = new ClientWebSocket(); |
| 109 | + |
| 110 | + if (string.IsNullOrWhiteSpace(user.Headers)) |
| 111 | + return socket; |
| 112 | + |
| 113 | + List<CustomHeaders>? customHeaders; |
| 114 | + try |
| 115 | + { |
| 116 | + customHeaders = JsonConvert.DeserializeObject<List<CustomHeaders>>(user.Headers); |
| 117 | + } |
| 118 | + catch |
| 119 | + { |
| 120 | + customHeaders = null; |
| 121 | + } |
| 122 | + |
| 123 | + if (customHeaders == null) |
| 124 | + return socket; |
| 125 | + |
| 126 | + foreach (var header in customHeaders) |
| 127 | + { |
| 128 | + if (string.IsNullOrWhiteSpace(header.Key) || string.IsNullOrWhiteSpace(header.Value)) |
| 129 | + continue; |
| 130 | + |
| 131 | + socket.Options.SetRequestHeader(header.Key, header.Value); |
| 132 | + } |
| 133 | + |
| 134 | + return socket; |
| 135 | + } |
| 136 | + |
| 137 | + private static string BuildWsUrl(Users user) |
| 138 | + { |
| 139 | + var socket = user.GotifyUrl.Contains("http://") ? "ws" : "wss"; |
| 140 | + var gotifyServerUrl = user.GotifyUrl.Replace("http://", "").Replace("https://", "").Replace("\"", ""); |
| 141 | + return $"{socket}://{gotifyServerUrl}/stream?token={user.ClientToken}"; |
| 142 | + } |
| 143 | + |
| 144 | + private static async Task ReceiveLoopAsync(ClientWebSocket socket, string wsUrl, string clientToken, |
| 145 | + CancellationToken cancellationToken) |
| 146 | + { |
| 147 | + var buffer = new byte[8 * 1024]; |
| 148 | + |
| 149 | + while (!cancellationToken.IsCancellationRequested && socket.State == WebSocketState.Open) |
| 150 | + { |
| 151 | + using var ms = new MemoryStream(); |
| 152 | + WebSocketReceiveResult result; |
| 153 | + |
| 154 | + do |
| 155 | + { |
| 156 | + result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken); |
| 157 | + |
| 158 | + if (result.MessageType == WebSocketMessageType.Close) |
| 159 | + { |
| 160 | + if (socket.State == WebSocketState.Open || socket.State == WebSocketState.CloseReceived) |
| 161 | + { |
| 162 | + await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Server closed connection", |
| 163 | + cancellationToken); |
| 164 | + } |
| 165 | + |
| 166 | + return; |
| 167 | + } |
| 168 | + |
| 169 | + ms.Write(buffer, 0, result.Count); |
| 170 | + } while (!result.EndOfMessage); |
| 171 | + |
| 172 | + var rawMessage = Encoding.UTF8.GetString(ms.ToArray()); |
| 173 | + var message = rawMessage.Replace("client::display", "clientdisplay") |
| 174 | + .Replace("client::notification", "clientnotification") |
| 175 | + .Replace("android::action", "androidaction"); |
| 176 | + |
| 177 | + if (Environments.isLogEnabled) |
| 178 | + Console.WriteLine("Message converted: " + message); |
| 179 | + |
| 180 | + GotifyMessage? gm; |
| 181 | + try |
| 182 | + { |
| 183 | + gm = JsonConvert.DeserializeObject<GotifyMessage>(message); |
| 184 | + } |
| 185 | + catch |
| 186 | + { |
| 187 | + gm = null; |
| 188 | + } |
| 189 | + |
| 190 | + if (gm == null) |
| 191 | + { |
| 192 | + Console.WriteLine("GotifyMessage is null"); |
| 193 | + continue; |
| 194 | + } |
| 195 | + |
| 196 | + Console.WriteLine($"WS Instance from (native): {clientToken}"); |
| 197 | + await new DeviceModel().SendNotifications(gm, wsUrl, clientToken); |
| 198 | + } |
| 199 | + } |
| 200 | +} |
0 commit comments