-
Notifications
You must be signed in to change notification settings - Fork 4
/
PluginCore.cs
708 lines (594 loc) · 22.6 KB
/
PluginCore.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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Decal.Adapter;
using MyClasses.MetaViewWrappers;
namespace TownCrier
{
[FriendlyName("TownCrier")]
public partial class PluginCore : PluginBase
{
// HTTP methods
private struct METHOD
{
public const string GET = "GET";
public const string POST = "POST";
}
// Events the plugin handles, superset of GameEvent
private struct EVENTS {
public const string LOGIN = "LOGIN";
public const string LOGOFF = "LOGOFF";
public const string LEVEL = "LEVEL";
public const string DEATH = "DEATH";
public const string DROPONDEATH = "DROPONDEATH";
public const string RARE = "RARE";
public const string RARELEVEL = "RARELEVEL";
public const string ITEMPICKUP = "ITEMPICKUP";
};
private struct EVENTDESC
{
public const string LOGIN = "You log in";
public const string LOGOFF = "You log off";
public const string LEVEL = "You level up";
public const string DEATH = "You die";
public const string DROPONDEATH = "You drop items on death";
public const string RARE = "You find a rare";
public const string RARELEVEL = "One of your rares levels up";
public const string ITEMPICKUP = "You pick up an item";
}
private Dictionary<string, bool> EVENTFILTERABLE = new Dictionary<string, bool>() {
{EVENTS.LOGIN, false},
{EVENTS.LOGOFF, false},
{EVENTS.LEVEL, false},
{EVENTS.DEATH, false},
{EVENTS.DROPONDEATH, false},
{EVENTS.RARE, false},
{EVENTS.RARELEVEL, false},
{EVENTS.ITEMPICKUP, true}
};
// Just GameEvent events the plugin handles
private struct GAMEEVENT
{
public const int LOGIN = 0x0013;
public const int TELL = 0x02BD;
public const int DEATH = 0x01AC;
};
private struct Icons
{
public const int Delete = 0x060011F8;
}
private struct COMMAND
{
public const string TRIGGER = "trigger";
public const string PROFILE = "profile";
public const string HELP = "help";
}
protected override void Startup()
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolTypeExtensions.Tls12;
MVWireupHelper.WireupStart(this, Host);
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
protected override void Shutdown()
{
try
{
Globals.Destroy();
MVWireupHelper.WireupEnd(this);
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
/**
* Load CurrentProfile setting from disk
*/
public static void LoadCurrentProfileSetting()
{
try
{
Utilities.LogMessage("LoadCurrentProfileSetting()");
string path = Utilities.GetPlayerSpecificFile("CurrentProfile.txt");
if (!File.Exists(path))
{
Utilities.LogMessage("LoadCurrentProfileSetting(): CurrentProfile.txt not found, assuming [By char] profile.");
return;
}
using (StreamReader reader = new StreamReader(path))
{
string value = reader.ReadToEnd();
if (value.Length < 0)
{
return;
}
Globals.CurrentProfile = value.Trim();
Utilities.LogMessage("LoadCurrentProfileSetting(): Current profile is now " + Globals.CurrentProfile);
}
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
/**
* Load Profile from disk.
*/
public void LoadProfile()
{
try
{
Utilities.LogMessage("LoadProfile()");
string path = Utilities.GetProfilePath();
if (!File.Exists(path))
{
// Can just stop here. profile JSON will get created eventually when
// something in the profile gets edited
return;
}
// Load Profile from disk
string profileString = null;
using (StreamReader reader = new StreamReader(path))
{
profileString = reader.ReadToEnd();
}
Profile profile = Newtonsoft.Json.JsonConvert.DeserializeObject<Profile>(profileString);
// Clean up state and then reset state from the loaded profile
Globals.DisposeAllTimers();
Globals.ChatTriggers.Clear();
Globals.EventTriggers.Clear();
Globals.TimedTriggers.Clear();
Globals.EventTriggers = profile.EventTriggers;
Globals.TimedTriggers = profile.TimedTriggers;
Globals.ChatTriggers = profile.ChatTriggers;
// Refresh UI after
RefreshUI();
}
catch (Exception ex)
{
Utilities.LogMessage("LoadProfile(): Failed to load profile due to " + ex.Message);
Utilities.LogError(ex);
}
}
/**
* Load Webhooks from disk.
*/
public void LoadWebhooks()
{
try
{
Utilities.LogMessage("LoadWebhooks()");
Globals.Webhooks.Clear();
foreach (string path in Directory.GetFiles(Utilities.GetWebhookDirectory(), "*.json"))
{
Utilities.LogMessage("LoadWebhooks(): Attempting to load " + path);
using (StreamReader reader = new StreamReader(path))
{
string webhookJSONString = reader.ReadToEnd();
try
{
Webhook webhook = Newtonsoft.Json.JsonConvert.DeserializeObject<Webhook>(webhookJSONString);
// Don't add if one with this name already exists
if (Globals.Webhooks.FindAll(w => w.Name == webhook.Name).Count != 0)
{
Utilities.WriteToChat(String.Format("Duplicate webhook found while loading webhooks from disk and was skipped. The webhook named '{0}' has already been used and webhooks must use unique names.", webhook.Name));
} else
{
Globals.Webhooks.Add(webhook);
}
}
catch (Exception ex)
{
Utilities.WriteToChat("Failed to load webhook at path '" + path + "' because it was malformed.");
Utilities.WriteToChat(ex.Message);
Utilities.LogError(ex);
}
}
Utilities.LogMessage("LoadWebhooks(): Done loading webhook " + path + " refreshing UI, etc.");
}
// Refresh UI
RefreshWebhooksList();
RefreshEventTriggerWebhookChoice();
RefreshTimedTriggerWebhookChoice();
RefreshChatTriggerWebhookChoice();
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
/**
* Load legacy settings.txt from disk.
*/
private void LoadLegacySettings()
{
try
{
Utilities.LogMessage("Loading legacy settings.");
Utilities.WriteToChat("TownCrier can now uses character-specific profiles by default and also supports sharing profiles across characters. See the Triggers > Profile tab. Your old settings have been migrated.");
Globals.DisposeAllTimers();
Globals.ChatTriggers.Clear();
Globals.EventTriggers.Clear();
Globals.TimedTriggers.Clear();
Globals.Webhooks.Clear();
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal) +
@"\Decal Plugins\" +
Globals.PluginName +
@"\settings.txt";
if (!File.Exists(path))
{
Utilities.LogMessage("Legacy settings file, settings.txt, not found. Stopping loading.");
return;
}
using (StreamReader reader = new StreamReader(path))
{
string line;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
LoadLegacySetting(line);
}
}
RefreshUI();
SaveProfile();
foreach (Webhook webhook in Globals.Webhooks)
{
SaveWebhook(webhook);
}
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
/**
* Parse a single line from a legacy settings.txt file.
*/
private static void LoadLegacySetting(string line)
{
try
{
string[] tokens = line.Split('\t');
switch (tokens[0])
{
case "setting":
switch (tokens[1])
{
case "verbose":
Utilities.LogMessage("Verbosity setting ignored when importing from legacy settings because it is no longer supported.");
break;
default:
break;
}
break;
case "webhook":
if (tokens.Length == 4)
{
Globals.Webhooks.Add(new Webhook(tokens[1], tokens[2], tokens[3], null));
}
else if (tokens.Length == 5)
{
Globals.Webhooks.Add(new Webhook(tokens[1], tokens[2], tokens[3], tokens[4]));
}
break;
case "eventtrigger":
if (tokens.Length != 5)
{
return;
}
// Look up webhook by name
List<Webhook> foundEvent = Globals.Webhooks.FindAll(w => w.Name == tokens[2]);
if (foundEvent.Count <= 0)
{
break;
}
Globals.EventTriggers.Add(new EventTrigger(tokens[1], "", foundEvent[0].Name, tokens[3], bool.Parse(tokens[4])));
break;
case "timedtrigger":
if (tokens.Length != 5)
{
return;
}
// Look up webhook by name
List<Webhook> foundTimed = Globals.Webhooks.FindAll(w => w.Name == tokens[2]);
if (foundTimed.Count <= 0)
{
break;
}
Globals.TimedTriggers.Add(new TimedTrigger(int.Parse(tokens[1]), foundTimed[0].Name, tokens[3], bool.Parse(tokens[4])));
break;
case "chattrigger":
if (tokens.Length != 5)
{
return;
}
// Look up webhook by name
List<Webhook> foundChat = Globals.Webhooks.FindAll(w => w.Name == tokens[2]);
if (foundChat.Count <= 0)
{
break;
}
Globals.ChatTriggers.Add(new ChatTrigger(tokens[1], foundChat[0].Name, tokens[3], bool.Parse(tokens[4])));
break;
default:
break;
}
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
/**
* Save profile as JSON, on a per-character basis.
*/
public static void SaveProfile()
{
try
{
Utilities.LogMessage("SaveProfile()");
string path = Utilities.GetProfilePath();
Utilities.LogMessage("SaveProfile(): Saving profile at path " + path);
// Construct a temporary Dictionary so serialization is easy
Profile profile = new Profile
{
EventTriggers = Globals.EventTriggers,
TimedTriggers = Globals.TimedTriggers,
ChatTriggers = Globals.ChatTriggers
};
using (StreamWriter writer = new StreamWriter(path, false))
{
writer.Write(Newtonsoft.Json.JsonConvert.SerializeObject(profile, Newtonsoft.Json.Formatting.Indented));
}
Utilities.LogMessage("SaveProfile(): Done saving.");
}
catch (Exception ex) { Utilities.LogError(ex); }
}
public static void SaveCurrentProfileSetting()
{
try
{
Utilities.LogMessage("SaveCurrentProfileSetting()");
Utilities.EnsurePathExists(Utilities.GetPlayerSpecificFolder());
string path = Utilities.GetPlayerSpecificFile("CurrentProfile.txt");
using (StreamWriter writer = new StreamWriter(path, false))
{
Utilities.LogMessage("SaveCurrentProfileSetting(): Writing current profile setting of '" + Globals.CurrentProfile + "'");
writer.Write(Globals.CurrentProfile);
}
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
public void ClearProfile()
{
try
{
Utilities.LogMessage("ClearProfile()");
Globals.ChatTriggers.Clear();
Globals.EventTriggers.Clear();
Globals.DisposeAllTimers();
Globals.TimedTriggers.Clear();
SaveProfile();
RefreshTimedTriggerList();
RefreshEventTriggerList();
RefreshChatTriggerList();
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
/**
* Save a single webhook to disk
*/
public static void SaveWebhook(Webhook webhook)
{
try
{
if (webhook == null)
{
Utilities.LogMessage("A call to SaveWebhook was called with a null webhook. Webhook not saved.");
return;
}
Utilities.EnsurePathExists(String.Format(@"{0}\{1}", Globals.PluginDirectory, "Webhooks"));
string path = String.Format(@"{0}\{1}\{2}.json", Globals.PluginDirectory, "Webhooks", webhook.Name);
using (StreamWriter writer = new StreamWriter(path, false))
{
writer.Write(Newtonsoft.Json.JsonConvert.SerializeObject(webhook, Newtonsoft.Json.Formatting.Indented));
}
}
catch (Exception ex) { Utilities.LogError(ex); }
}
/**
* Delete a single webhook from the plugin's state and disk
*/
public static void DeleteWebhook(string name)
{
try
{
Utilities.LogMessage("DeleteWebhook(" + name + ")");
// Find the webhook first
List<Webhook> matches = Globals.Webhooks.FindAll(x => x.Name == name);
if (matches.Count != 1)
{
Utilities.WriteToChat("Couldn't find webhook to delete. Stopping without deleting anything.");
return;
}
// Delete from plugin state
Globals.Webhooks.Remove(matches[0]);
// Then from disk
string path = string.Format(@"{0}\Webhooks\{1}.json", Globals.PluginDirectory, name);
if (!File.Exists(path))
{
Utilities.WriteToChat(string.Format("Couldn't find {0} on disk. Stopping without deleting anything.", path));
return;
}
File.Delete(path);
Utilities.LogMessage("DeleteWebhook(" + name + ") done.");
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
private static void TriggerWebhook(string name, string message)
{
try
{
Utilities.LogMessage(string.Format("TriggerWebhook({0}, {1})", name, message));
Webhook webhook = Globals.Webhooks.Find(x => x.Name == name);
if (webhook == null) {
return;
}
WebhookRequest req = new WebhookRequest(webhook, message);
req.Send();
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
private void TriggerWebhooksForEvent(string evt, string eventMessage)
{
try
{
Utilities.LogMessage(string.Format("TriggerWebhooksForEvent({0}, {1})", evt, eventMessage));
List<EventTrigger> matched = Globals.EventTriggers.FindAll(trigger => trigger.Enabled && trigger.Event == evt);
foreach (EventTrigger trigger in matched)
{
TriggerWebhooksForEventTrigger(trigger, eventMessage);
}
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
private static void TriggerWebhooksForEventTrigger(EventTrigger trigger, string eventMessage)
{
try
{
Utilities.LogMessage(string.Format("TriggerWebhooksForEventTrigger({0}, {1})", trigger.ToString(), eventMessage));
if (!trigger.Enabled)
{
return;
}
if (trigger.Filter != null)
{
if (trigger.Filter.Length >= 0 && !eventMessage.Contains(trigger.Filter))
{
return;
}
}
Webhook webhook = Globals.Webhooks.Find(x => x.Name == trigger.WebhookName);
if (webhook == null)
{
return;
}
// Handle case where messageformat is empty and default to $EVENT
string message = null;
if (trigger.MessageFormat.Length <= 0)
{
message = "$EVENT";
}
else
{
message = trigger.MessageFormat;
}
WebhookRequest req = new WebhookRequest(webhook, message, eventMessage, null);
req.Send();
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
private void TriggerWebhooksForChatTrigger(ChatTrigger trigger, string eventMessage)
{
try
{
Utilities.LogMessage(string.Format("TriggerWebhooksForChatTrigger({0}, {1})", trigger.ToString(), eventMessage));
if (!trigger.Enabled)
{
return;
}
// Handle case where messageformat is empty and default to $EVENT
string message = null;
if (trigger.MessageFormat.Length <= 0)
{
message = "$EVENT";
}
else
{
message = trigger.MessageFormat;
}
Webhook webhook = Globals.Webhooks.Find(x => x.Name == trigger.WebhookName);
if (webhook == null)
{
Utilities.WriteToChat(string.Format("Couldn't find webhook '{0}'." + trigger.WebhookName));
return;
}
WebhookRequest req = new WebhookRequest(webhook, message, eventMessage, trigger.Pattern);
req.Send();
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
private static void PrintEventTrigger(EventTrigger trigger)
{
try
{
Utilities.WriteToChat(trigger.ToString());
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
private static void PrintTimedTrigger(TimedTrigger trigger)
{
try
{
Utilities.WriteToChat(trigger.ToString());
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
private static void PrintChatTrigger(ChatTrigger trigger)
{
try
{
Utilities.WriteToChat(trigger.ToString());
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
private static void PrintWebhook(Webhook webhook)
{
try
{
Utilities.WriteToChat(webhook.ToString());
}
catch (Exception ex)
{
Utilities.LogError(ex);
}
}
}
}