-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathGotifySocketService.cs
More file actions
328 lines (281 loc) · 11.8 KB
/
Copy pathGotifySocketService.cs
File metadata and controls
328 lines (281 loc) · 11.8 KB
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
using System.Net.Sockets;
using System.Net.WebSockets;
using iGotify_Notification_Assist.Models;
using SecNtfyNuGet;
namespace iGotify_Notification_Assist.Services;
public class GotifySocketService
{
public bool isInit { get; private set; }
private static GotifySocketService? _instance;
// Data structure for tracking threads and WebSocket connections
private static List<ThreadSocket>? _threadSockets;
public static GotifySocketService getInstance()
{
return _instance ??= new GotifySocketService();
}
public void Init()
{
var path = $"{GetLocationsOf.App}/data";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
// Create Database File
var isDbFileExists = DatabaseService.CreateDatebase(path);
if (isDbFileExists)
{
DatabaseService.UpdateDatebase(path, "Users", "Headers", "text not null default ''");
}
Console.WriteLine($"Database is created: {isDbFileExists}");
isInit = isDbFileExists;
}
public static void KillWsThread(string clientToken)
{
if (_threadSockets != null)
{
var threadSocket = _threadSockets.Find(x => x.clientToken == clientToken);
if (threadSocket == null) return;
try
{
// 1) Signal termination
threadSocket.cts?.Cancel();
// 2) If you have a WebSocket, close it actively so that blocking reads wake up
threadSocket.ws!.Stop();
// 3) Wait for thread end (short timeout so nothing hangs)
if (threadSocket.thread!.IsAlive)
threadSocket.thread.Join(millisecondsTimeout: 500);
}
finally
{
threadSocket.cts?.Dispose();
_threadSockets.Remove(threadSocket);
}
}
}
public static void KillAllWsThread()
{
if (_threadSockets != null)
{
foreach (var threadSocket in _threadSockets)
{
try
{
// 1) Signal termination
threadSocket.cts?.Cancel();
// 2) If you have a WebSocket, close it actively so that blocking reads wake up
threadSocket.ws!.Stop();
// 3) Wait for thread end (short timeout so nothing hangs)
if (threadSocket.thread!.IsAlive)
threadSocket.thread.Join(millisecondsTimeout: 500);
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
threadSocket.cts?.Dispose();
}
}
_threadSockets.Clear();
}
}
public static void StartWsThread(string gotifyServerUrl, string clientToken)
{
// Add the thread and the associated WebSocket connection to the data structure
if (_threadSockets == null)
_threadSockets = new List<ThreadSocket>();
var threadSocket = _threadSockets.Find(x => x.clientToken == clientToken);
if (threadSocket == null)
{
threadSocket = new ThreadSocket();
_threadSockets.Add(threadSocket);
threadSocket.thread = new Thread(() => StartWsConn(threadSocket, gotifyServerUrl, clientToken));
threadSocket.thread.Start();
}
else
Console.WriteLine($"Client: {clientToken} already connected! Skipping...");
}
public static void StartWsThread(Users user)
{
// Add the thread and the associated WebSocket connection to the data structure
if (_threadSockets == null)
_threadSockets = new List<ThreadSocket>();
var threadSocket = _threadSockets.Find(x => x.clientToken == user.ClientToken);
if (threadSocket == null)
{
threadSocket = new ThreadSocket();
_threadSockets.Add(threadSocket);
threadSocket.thread = new Thread(() => StartWsConn(threadSocket, user));
threadSocket.thread.Start();
}
else
Console.WriteLine($"Client: {user.ClientToken} already connected! Skipping...");
}
private static void StartWsConn(ThreadSocket threadSocket, Users user)
{
while (!threadSocket.cts!.IsCancellationRequested)
{
try
{
string wsUrl;
string socket;
socket = user.GotifyUrl.Contains("http://") ? "ws" : "wss";
var gotifyServerUrl = user.GotifyUrl.Replace("http://", "").Replace("https://", "").Replace("\"", "");
wsUrl = $"{socket}://{gotifyServerUrl}/stream?token={user.ClientToken}";
// Starting WebSocket instance
Console.WriteLine("Client connecting...");
var wsc = new WebSockClient { URL = wsUrl, user = user };
wsc.Start(user.ClientToken);
// Connect the client
threadSocket.clientToken = user.ClientToken;
threadSocket.ws = wsc;
Thread.Sleep(Timeout.Infinite);
}
catch (WebSocketException wse)
{
Console.WriteLine(
$"Unable to Connect to WS or WSS connection aborted with clientToken: {user.ClientToken}");
Console.WriteLine(wse.StackTrace);
//currentProcess.Kill(true);
}
}
Console.WriteLine($"Client disconnected: {user.ClientToken}");
}
private static void StartWsConn(ThreadSocket threadSocket, string gotifyServerUrl, string clientToken)
{
while (!threadSocket.cts!.IsCancellationRequested)
{
try
{
string wsUrl;
string socket;
socket = gotifyServerUrl.Contains("http://") ? "ws" : "wss";
gotifyServerUrl = gotifyServerUrl.Replace("http://", "").Replace("https://", "").Replace("\"", "");
wsUrl = $"{socket}://{gotifyServerUrl}/stream?token={clientToken}";
// Starting WebSocket instance
Console.WriteLine("Client connecting...");
var wsc = new WebSockClient { URL = wsUrl };
wsc.Start(clientToken);
// Connect the client
wsc.Start(clientToken);
// Connect the client
threadSocket.clientToken = clientToken;
threadSocket.ws = wsc;
Thread.Sleep(Timeout.Infinite);
}
catch (WebSocketException wse)
{
Console.WriteLine($"Unable to Connect to WS or WSS connection aborted with clientToken: {clientToken}");
Console.WriteLine(wse.StackTrace);
//currentProcess.Kill(true);
}
}
Console.WriteLine($"Client disconnected: {clientToken}");
}
/// <summary>
/// Initialise WebSocket with all passed variables from container
/// </summary>
public async void Start()
{
var secntfyUrl = Environments.secNtfyUrl;
var gotifyUrls = Environments.gotifyUrls;
var gotifyClientTokens = Environments.gotifyClientTokens;
var secntfyTokens = Environments.secNtfyTokens;
var gotifyUrlList = new List<string>();
var gotifyClientList = new List<string>();
var secntfyTokenList = new List<string>();
if (gotifyUrls.Length > 0 && gotifyClientTokens.Length > 0 && secntfyTokens.Length > 0)
{
try
{
gotifyUrlList = gotifyUrls.Split(";").ToList();
gotifyClientList = gotifyClientTokens.Split(";").ToList();
secntfyTokenList = secntfyTokens.Split(";").ToList();
var clientCounter = 0;
foreach (string client in gotifyClientList)
{
var dm = new DeviceModel();
dm.ClientToken = client;
if (!await DatabaseService.CheckIfUserExists(dm))
{
dm.GotifyUrl = gotifyUrlList.ElementAt(clientCounter);
dm.DeviceToken = secntfyTokenList.ElementAt(clientCounter);
if (!await DatabaseService.InsertUser(dm))
{
throw new ApplicationException("Insert Database Exception!");
}
}
clientCounter++;
}
}
catch (Exception e)
{
Console.WriteLine($"Error: {e.Message}");
Console.WriteLine("Something went wrong when inserting you're connection!");
Console.WriteLine("Please check you're environment lists!");
}
}
else
{
var statusServerList = gotifyUrlList.Count == 0 ? "empty" : "filled";
Console.WriteLine($"Gotify Url list is: {statusServerList}");
var statusClientList = gotifyClientList.Count == 0 ? "empty" : "filled";
Console.WriteLine($"Gotify Client list is: {statusClientList}");
var statusNtfyList = secntfyTokenList.Count == 0 ? "empty" : "filled";
Console.WriteLine($"SecNtfy Token list is: {statusNtfyList}");
Console.WriteLine(
$"If one or more lists are empty please check the environment variable! GOTIFY_SERVERS or GOTIFY_CLIENTS or NTFY_TOKENS");
Console.WriteLine(
$"If all lists are empty do nothing, you will configure the gotify server over the iGotify app.");
}
var userList = await DatabaseService.GetUsers();
StartConnection(userList, secntfyUrl);
}
private void StartConnection(List<Users> userList, string secntfyUrl)
{
foreach (var user in userList)
{
string isGotifyAvailable;
string isSecNtfyAvailable;
try
{
isGotifyAvailable = SecNtfy.CheckIfUrlReachable(user.GotifyUrl) ? "yes" : "no";
if (isGotifyAvailable == "no")
{
StartConnection(userList, secntfyUrl);
return;
}
}
catch
{
Console.WriteLine($"Gotify Server: '{user.GotifyUrl}' is not available try to reconnect in 10s.");
StartDelayedConnection(userList, secntfyUrl);
return;
}
try
{
bool isSecNtfyAvailableBool = SecNtfy.CheckIfUrlReachable(secntfyUrl);
isSecNtfyAvailable = isSecNtfyAvailableBool ? "yes" : "no";
if (!isSecNtfyAvailableBool)
Console.WriteLine($"SecNtfy Server: '{secntfyUrl}' is not available, please check your internet connection!");
}
catch
{
Console.WriteLine($"SecNtfy Server: '{secntfyUrl}' is not available try to reconnect in 10s.");
StartDelayedConnection(userList, secntfyUrl);
return;
}
Console.WriteLine($"Gotify - Url: {user.GotifyUrl}");
Console.WriteLine($"Is Gotify - Url available: {isGotifyAvailable}");
Console.WriteLine($"SecNtfy Server - Url: {secntfyUrl}");
Console.WriteLine($"Is SecNtfy Server - Url available: {isSecNtfyAvailable}");
Console.WriteLine($"Client - Token: {user.ClientToken}");
StartWsThread(user);
}
}
private async void StartDelayedConnection(List<Users> userList, string secntfyUrl)
{
await Task.Delay(10000);
Console.WriteLine("Reconnecting...");
StartConnection(userList, secntfyUrl);
}
}