-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPayNow.cs
485 lines (387 loc) · 16.6 KB
/
PayNow.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
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Libraries;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using System.Text;
namespace Oxide.Plugins
{
[Info("PayNow", "PayNow Services Inc", "0.0.13")]
[Description("Official plugin for the PayNow.gg store integration.")]
internal class PayNow : CovalencePlugin
{
const string COMMAND_QUEUE_URL = "https://api.paynow.gg/v1/delivery/command-queue/";
const string GS_LINK_URL = "https://api.paynow.gg/v1/delivery/gameserver/link";
PluginConfig _config;
readonly Dictionary<string, string> _headers = new Dictionary<string, string>();
readonly CommandHistory _executedCommands = new CommandHistory(25);
readonly StringBuilder _cachedStringBuilder = new StringBuilder();
readonly HashSet<string> _commandsToAcknowledge = new HashSet<string>(1000);
Timer _pendingCommandsTimer;
#region Oxide
[HookMethod("Loaded")]
void Loaded()
{
if (string.IsNullOrEmpty(_config.ApiToken))
PrintWarning("No API token set! Use the 'paynow.token <token>' command to set it.");
UpdateHeaders();
}
[HookMethod("OnServerInitialized")]
void OnServerInitialized() => ValidateToken();
[Command("paynow.token")]
void CommandToken(IPlayer player, string command, string[] args)
{
if (!player.IsServer && !player.IsAdmin)
return;
if (args.Length != 1)
{
player.Reply("Usage: paynow.token <token>");
return;
}
StopPendingCommandsLoop();
_config.ApiToken = args[0]?.Trim();
SaveConfig();
UpdateHeaders();
player.Reply("Successfully saved the PayNow API token! Attempting to validate it...");
ValidateToken();
}
void ValidateToken() => LinkGameServer(StartPendingCommandsLoop);
void StartPendingCommandsLoop()
{
if (_pendingCommandsTimer != null) return;
Puts("Started checking for pending commands");
GetPendingCommands();
timer.Every(_config.ApiCheckIntervalSeconds, GetPendingCommands);
}
void StopPendingCommandsLoop() => timer.Destroy(ref _pendingCommandsTimer);
#endregion
#region WebRequests
void LinkGameServer(Action continuationCallback)
{
// Don't make the API call if we don't have a token
if (string.IsNullOrEmpty(_config.ApiToken))
return;
var data = new LinkGameServerRequest
{
Ip = server.Address + ":" + server.Port,
Hostname = server.Name,
Platform = game,
Version = Version.ToString()
};
try
{
// Make the API call
webrequest.Enqueue(GS_LINK_URL, JsonConvert.SerializeObject(data), (code, responseString) => HandleLinkGameServerResponse(code, responseString, continuationCallback), this, RequestMethod.POST, _headers);
}
catch (Exception ex)
{
PrintException("Failure initiate game server link request to PayNow, trying again in 5 seconds...", ex);
timer.In(5, () => LinkGameServer(continuationCallback));
return;
}
}
void HandleLinkGameServerResponse(int code, string responseString, Action continuationCallback)
{
// Check we are authorised to be here...
if (code == 401 || code == 403)
{
PrintError("Failure linking game server to PayNow, invalid token supplied. Please update your token and try again");
return;
}
// Check if we got a valid response code....
if (code >= 500)
{
PrintWarning("Failure linking game server to PayNow, trying again in 5 seconds...");
timer.In(5, () => LinkGameServer(continuationCallback));
return;
}
LinkGameServerResponse response;
try
{
response = JsonConvert.DeserializeObject<LinkGameServerResponse>(responseString);
}
catch (Exception ex)
{
PrintException("Failure whilst deserializing link game server response, trying again in 5 seconds...", ex);
timer.In(5, () => LinkGameServer(continuationCallback));
return;
}
if (response == null)
{
PrintError("PayNow API returned a null link game server response, trying again in 5 seconds...");
timer.In(5, () => LinkGameServer(continuationCallback));
return;
}
if (response.UpdateAvailable)
{
Puts("Update available! latest version: {0}, current version: {1}", response.LatestVersion, Version.ToString());
}
if (response.PreviouslyLinked != null)
{
PrintWarning("This token has been previously used on \"{0}\" ({1}), ensure you have removed this token from the previous server.", response.PreviouslyLinked.HostName, response.PreviouslyLinked.IP);
}
if (response.GameServer == null)
{
PrintError("PayNow API did not return a GameServer object, this may be a transient issue, please try again or contact support.");
return;
}
Puts("Connected to PayNow using the token for \"{0}\" ({1}) successfully!", response.GameServer.Name, response.GameServer.Id);
continuationCallback?.Invoke();
}
void GetPendingCommands()
{
// Don't make the API call if we don't have a token
if (string.IsNullOrEmpty(_config.ApiToken))
return;
try
{
// Make the API call
webrequest.Enqueue(COMMAND_QUEUE_URL, BuildOnlinePlayersJson(), HandlePendingCommands, this, RequestMethod.POST, _headers, _config.ApiCheckIntervalSeconds);
}
catch (Exception ex)
{
PrintException("Failed retrieve get pending commands", ex);
}
}
void HandlePendingCommands(int code, string response)
{
try
{
// Check if we got a valid response
if (code != 200 || response == null)
throw new Exception($"Server sent an invalid response: ({code}) ({response})");
// Deserialize the response
QueuedCommand[] data = JsonConvert.DeserializeObject<QueuedCommand[]>(response);
if (data == null)
throw new Exception($"Response deserialized to null: ({response})");
// Process the data
ProcessPendingCommands(data);
}
catch (Exception ex)
{
PrintException("Failed handle pending commands", ex);
}
}
void AcknowledgeCommands(HashSet<string> commandsIds)
{
// Check if we have any order ids to acknowledge
if (commandsIds.Count == 0) return;
try
{
// Make the API call to acknowledge the commands
webrequest.Enqueue(COMMAND_QUEUE_URL, BuildAcknowledgeJson(commandsIds), HandleAcknowledgeCommands, this, RequestMethod.DELETE, _headers);
}
catch (Exception ex)
{
PrintException("Failed to acknowledge commands", ex);
}
}
void HandleAcknowledgeCommands(int code, string response)
{
// Check if we got a valid response
if (code >= 200 && code < 300) return;
// Log an error if we didn't get a 204 response
PrintError(
$"Command acknowledgement resulted in an unexpected response code: ({code.ToString()}) ({response})");
}
#endregion
#region Command Processing
void ProcessPendingCommands(QueuedCommand[] queuedCommands)
{
// Check if we got any data
if (queuedCommands.Length == 0)
return;
int executedCommands = 0;
_commandsToAcknowledge.Clear();
for (int i = 0; i < queuedCommands.Length; i++)
{
QueuedCommand command = queuedCommands[i];
// Make sure we don't execute the same command twice
if (_executedCommands.Contains(command.AttemptId))
{
_commandsToAcknowledge.Add(command.AttemptId);
continue;
}
try
{
if (command.OnlineOnly && players.Connected.All(x => x.Id != command.SteamId))
continue;
// Try executing the command
if (ExecuteCommand(command.Command))
{
// Add the order id to the list of acknowledged orders
executedCommands += 1;
_commandsToAcknowledge.Add(command.AttemptId);
_executedCommands.Add(command.AttemptId);
}
else
{
// Log an error if the command failed
PrintWarning($"Failed to run command {command.Command} ({command.AttemptId})!");
}
}
catch (Exception ex)
{
// Log an error if an exception occurs
PrintException("Failed to execute command", ex);
}
}
// Log the amount of commands we executed
if (_config.LogCommandExecutions)
Puts(
$"Received {queuedCommands.Length.ToString()} and executed {executedCommands.ToString()} commands!");
// Acknowledge the commands
AcknowledgeCommands(_commandsToAcknowledge);
}
bool ExecuteCommand(string command)
{
// Run the command
server.Command(command);
// TODO: Fetch Command Response, currently not possible when using oxide covalence libraries
return true;
}
#endregion
#region Api DTOs
[Serializable]
public class QueuedCommand
{
[JsonProperty("attempt_id")] public string AttemptId;
[JsonProperty("steam_id")] public string SteamId;
[JsonProperty("command")] public string Command;
[JsonProperty("online_only")] public bool OnlineOnly;
[JsonProperty("queued_at")] public string QueuedAt;
}
[Serializable]
public class LinkGameServerRequest
{
[JsonProperty("ip")] public string Ip;
[JsonProperty("hostname")] public string Hostname;
[JsonProperty("platform")] public string Platform;
[JsonProperty("version")] public string Version;
}
[Serializable]
public class LinkGameServerResponse
{
[JsonProperty("update_available")] public bool UpdateAvailable { get; set; }
[JsonProperty("latest_version")] public string LatestVersion { get; set; }
[JsonProperty("previously_linked")] public PreviouslyLinkedData PreviouslyLinked { get; set; }
[JsonProperty("gameserver")] public GameServerData GameServer { get; set; }
public class PreviouslyLinkedData
{
[JsonProperty("ip")] public string IP { get; set; }
[JsonProperty("host_name")] public string HostName { get; set; }
[JsonProperty("last_linked_at")] public DateTime LastLinkedAt { get; set; }
}
public class GameServerData
{
[JsonProperty("id")] public long Id { get; set; }
[JsonProperty("store_id")] public long StoreId { get; set; }
[JsonProperty("name")] public string Name { get; set; }
[JsonProperty("created_at")] public DateTime? CreatedAt { get; set; }
[JsonProperty("updated_at")] public DateTime? UpdatedAt { get; set; }
}
}
#endregion
#region Configuration
[Serializable]
class PluginConfig
{
[JsonProperty("API token")] public string ApiToken = string.Empty;
[JsonProperty("Time between API checks in seconds")]
public float ApiCheckIntervalSeconds = 10;
[JsonProperty("Log command executions")]
public bool LogCommandExecutions = true;
// Backwards compatibility
[JsonProperty("ApiToken")]
public string OldApiToken
{
set { ApiToken = value; }
}
[JsonProperty("ApiCheckIntervalSeconds")]
public float OldApiCheckIntervalSeconds
{
set { ApiCheckIntervalSeconds = value; }
}
}
protected override void LoadDefaultConfig()
{
_config = new PluginConfig();
}
protected override void LoadConfig()
{
base.LoadConfig();
_config = Config.ReadObject<PluginConfig>();
SaveConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config, true);
}
#endregion
#region Helpers
void UpdateHeaders()
{
_headers["Content-Type"] = "application/json";
_headers["Authorization"] = "Gameserver " + _config.ApiToken;
}
string BuildAcknowledgeJson(HashSet<string> orderIds)
{
_cachedStringBuilder.Clear();
// Json format [{"attempt_id": "123"}]
_cachedStringBuilder.Append("[");
if (orderIds.Count > 0)
{
foreach (var element in orderIds)
{
_cachedStringBuilder.Append("{\"attempt_id\": \"");
_cachedStringBuilder.Append(element);
_cachedStringBuilder.Append("\"}");
_cachedStringBuilder.Append(",");
}
_cachedStringBuilder.Remove(_cachedStringBuilder.Length - 1, 1);
}
_cachedStringBuilder.Append("]");
return _cachedStringBuilder.ToString();
}
string BuildOnlinePlayersJson()
{
_cachedStringBuilder.Clear();
// Json format {"steam_ids": ["123"]}
_cachedStringBuilder.Append("{\"steam_ids\":[");
var addedPlayers = false;
foreach (var player in players.Connected)
{
addedPlayers = true;
_cachedStringBuilder.Append("\"");
_cachedStringBuilder.Append(player.Id);
_cachedStringBuilder.Append("\"");
_cachedStringBuilder.Append(",");
}
if (addedPlayers) _cachedStringBuilder.Remove(_cachedStringBuilder.Length - 1, 1);
_cachedStringBuilder.Append("]}");
return _cachedStringBuilder.ToString();
}
class CommandHistory
{
readonly Queue<string> _queue;
readonly int _capacity;
public CommandHistory(int capacity)
{
_capacity = capacity;
_queue = new Queue<string>(capacity);
}
public void Add(string command)
{
if (_queue.Count >= _capacity)
_queue.Dequeue();
_queue.Enqueue(command);
}
public bool Contains(string command) => _queue.Contains(command);
}
void PrintException(string message, Exception ex) => Interface.Oxide.LogException($"[{Title}] {message}", ex);
#endregion
}
}