forked from randomouscrap98/SmileBASICSourceChat
/
chatManager.cs
1348 lines (1184 loc) · 51 KB
/
chatManager.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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Net;
using System.Timers;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using MyExtensions;
using ChatEssentials;
using ModuleSystem;
using MyWebSocket;
using MyExtensions.Logging;
using System.Diagnostics;
namespace ChatServer
{
//This is what other functions should look like when subscribing to our event
//public delegate void ChatEvent(SystemRequest request);
public class ChatServerSettings : WebSocketSettings
{
public TimeSpan MaxModuleWait = TimeSpan.FromSeconds(5);
public TimeSpan MaxFileWait = TimeSpan.FromSeconds(10);
public TimeSpan SaveInterval = TimeSpan.FromSeconds(30);
public int MaxMessageKeep = 100;
public int MaxMessageSend = 5;
public string GlobalTag = "";
public bool MonitorThreads = false;
private List<string> acceptedTags = new List<string>();
private string saveFolder = "";
/// <summary>
/// A list of all accepted tags for chat messages. Will always include global tag, even
/// if you don't add it.
/// </summary>
/// <value>The accepted tags.</value>
public List<string> AcceptedTags
{
get
{
List<string> acceptedTagsCopy = new List<string>(acceptedTags);
if (!acceptedTags.Contains(GlobalTag))
acceptedTagsCopy.Add(GlobalTag);
return acceptedTagsCopy;
}
set
{
acceptedTags = value;
}
}
/// <summary>
/// The folder where the chat server will save all its data.
/// </summary>
/// <value>The save folder.</value>
public string SaveFolder
{
get { return StringExtensions.PathFixer(saveFolder); }
set { saveFolder = value; }
}
public ChatServerSettings(int port, string service, Func<WebSocketUser> generator, Logger logger = null)
: base(port, service, generator, logger)
{
}
public void DumpSettings()
{
Dictionary<string, string> settingValues = new Dictionary<string, string>();
settingValues.Add("fileWait", this.MaxFileWait.ToString());
settingValues.Add("moduleWait", this.MaxModuleWait.ToString());
settingValues.Add("maxReceiveSize", this.MaxReceiveSize.ToString());
settingValues.Add("pingInterval", this.PingInterval.ToString());
settingValues.Add("readWriteTimeout", this.ReadWriteTimeout.ToString());
settingValues.Add("receiveBuffer", this.ReceiveBufferSize.ToString());
settingValues.Add("sendBuffer", this.SendBufferSize.ToString());
settingValues.Add("shutdownTimeout", this.ShutdownTimeout.ToString());
settingValues.Add("monitorThreads", this.MonitorThreads.ToString());
LogProvider.LogGeneral("Settings dump: " +
string.Join(" ", settingValues.Select(x => "[" + x.Key + "] " + x.Value)), LogLevel.Debug, "ChatSettings");
}
}
//This is the manager for the chat. It includes information which all individual chat sessions
//will probably need, and manages the saving/loading of resources.
public class ChatServer : WebSocketServer
{
//Other things can dump their crap into this event, and when I call it in here,
//it'll call all of them. Nifty.
//public event ChatEvent Request;
//public const int FileWaitSeconds = 10;
public const int HeaderSize = 64;
public const string LogTag = "ChatServer";
public const string BandwidthFile = "bandwidth.json";
public const string UserFile = "users.json";
public const string MessageFile = "messages.json";
public const string HistoryFile = "history.json";
public const string RoomFile = "rooms.json";
//public readonly List<string> AllAcceptedTags = new List<string>();
//public readonly string GlobalTag = "";
public readonly BandwidthMonitor Bandwidth = new BandwidthMonitor();
//public readonly string SaveFolder = "";
/*public readonly string IrcServer = "";
public readonly string IrcChannel = "";
public readonly string IrcTag = "";*/
//private ChatServerSettings settings;
private List<Module> modules = new List<Module>();
private List<UserMessageJSONObject> messages = new List<UserMessageJSONObject>();
private Dictionary<string, List<UserMessageJSONObject>> history = new Dictionary<string, List<UserMessageJSONObject>>();
private readonly ModuleLoader loader;
private readonly AuthServer authServer;
private readonly LanguageTags languageTags;
//private readonly HashSet<Chat> activeChatters = new HashSet<Chat>();
private readonly Dictionary<int, User> users = new Dictionary<int, User>();
private Dictionary<string, PMRoom> rooms = new Dictionary<string, PMRoom>();
private readonly System.Timers.Timer saveTimer;
private readonly System.Timers.Timer threadMonitorTimer;
private int lastThreadCount = 0;
//private readonly System.Timers.Timer cleanupTimer;
//private readonly System.Timers.Timer pingTimer;
//private readonly SimpleIRCRelay relay;
//public readonly MyExtensions.Logging.Logger Logger = MyExtensions.Logging.Logger.DefaultLogger;
//public readonly Object userLock = new Object();
public readonly Object managerLock = new Object();
public readonly Object fileLock = new Object();
public List<UserMessageJSONObject> GetMessages()
{
lock (managerLock)
{
return messages.Select(x => new UserMessageJSONObject(x)).ToList();
}
}
public Dictionary<string, List<UserMessageJSONObject>> GetHistory()
{
lock (managerLock)
{
Dictionary<string, List<UserMessageJSONObject>> historyCopy = new Dictionary<string, List<UserMessageJSONObject>>();
foreach (string key in history.Keys)
{
historyCopy.Add(key, history[key].Select(x => new UserMessageJSONObject(x)).ToList());
}
return historyCopy;
}
}
public static string Policy
{
get
{
return @"
The SmileBASIC Source chat is mostly self-moderated. This means we expect you to conduct yourselves in a civil
manner and deal with conflicts on your own. However, should extreme behavior arise, the admins can take action
and enact punishment at their discretion. If a user is bothersome, there is an ""ignore"" option available.
If there are no moderators available and you wish to report a situation that isn't getting resolved, you can
send an email to smilebasicsource@gmail.com, and a moderator should show up shortly if they're available.
You use the chat at your own risk; neither SmileBASIC Source nor any member of its staff are responsible for
the actions of any user within the chat.".Replace("\n", " ");
}
}
public ChatServerSettings ChatSettings
{
get { return (ChatServerSettings)Settings; }
}
public ChatServer(ChatServerSettings settings, ModuleLoader loader, AuthServer authServer,
LanguageTags languageTags) : base(settings)
{
this.modules = loader.ActiveModules;
this.authServer = authServer;
this.loader = loader;
this.languageTags = languageTags;
#region BandwidthLoad
//Attempt to load the bandwidth monitor in the constructor. It's not a big deal if it doesn't load
//though, so just fall back to the nice default empty monitor if we fail.
BandwidthMonitor tempMonitor;
if (MySerialize.LoadObject<BandwidthMonitor>(SavePath(BandwidthFile), out tempMonitor))
{
Bandwidth = tempMonitor;
Log("Loaded bandwidth data from file", MyExtensions.Logging.LogLevel.Debug);
}
else
{
Log("Couldn't load bandwidth data! Defaulting to empty bandwidth", MyExtensions.Logging.LogLevel.Error);
}
#endregion
#region UserLoad
//Attempt to load the users in the constructor. Again, not a big deal if it doesn't load.
Dictionary<int, User> tempUsers;
if (MySerialize.LoadObject<Dictionary<int, User>>(SavePath(UserFile), out tempUsers))
{
users = tempUsers;
if(users.Count > 0)
{
UserSession.SetNextID(users.Max(x => x.Value.MaxSessionID) + 1);
};
Log("Loaded user data from file", MyExtensions.Logging.LogLevel.Debug);
}
else
{
Log("Couldn't load user data! Defaulting to empty user dictionary", MyExtensions.Logging.LogLevel.Error);
}
#endregion
#region MessageLoad
//Attempt to load the messages in the constructor. Again, not a big deal if it doesn't load.
List<UserMessageJSONObject> tempMessages;
if (MySerialize.LoadObject<List<UserMessageJSONObject>>(SavePath(MessageFile), out tempMessages))
{
messages = tempMessages;
UserMessageJSONObject.FindNextID(messages);
PMRoom.FindNextID(messages.Select(x => x.tag).ToList());
Log("Loaded messages from file", MyExtensions.Logging.LogLevel.Debug);
}
else
{
Log("Couldn't load messages! Defaulting to empty message list", MyExtensions.Logging.LogLevel.Error);
}
#endregion
#region HistoryLoad
Dictionary<string, List<UserMessageJSONObject>> tempHistory;
if (MySerialize.LoadObject<Dictionary<string, List<UserMessageJSONObject>>>(SavePath(HistoryFile), out tempHistory))
{
history = tempHistory;
PMRoom.FindNextID(history.SelectMany(x => x.Value.Select(y => y.tag)).ToList());
Log("Loaded history from file", MyExtensions.Logging.LogLevel.Debug);
}
else
{
Log("Couldn't load history! Defaulting to empty history", MyExtensions.Logging.LogLevel.Error);
}
#endregion
#region RoomLoad
Dictionary<string, PMRoom> tempRooms;
if (MySerialize.LoadObject<Dictionary<string, PMRoom>>(SavePath(RoomFile), out tempRooms))
{
rooms = tempRooms;
PMRoom.FindNextID(rooms.Select(x => x.Key).ToList());
Log("Loaded rooms from file", MyExtensions.Logging.LogLevel.Debug);
}
else
{
Log("Couldn't load rooms! Defaulting to no rooms", MyExtensions.Logging.LogLevel.Error);
}
#endregion
//now set up the save file timer
saveTimer = new System.Timers.Timer(settings.SaveInterval.TotalMilliseconds);//1000 * managerOptions.GetAsType<int>("saveInterval"));
saveTimer.Elapsed += SaveTimerElapsed;
saveTimer.Start();
if (settings.MonitorThreads)
{
threadMonitorTimer = new System.Timers.Timer(1000);
threadMonitorTimer.Elapsed += MonitorThreadsElapsed;
threadMonitorTimer.Start();
}
}
//Set up the logger when building the chat provider. Logging will go out to a file and the console
//if possible. Otherwise, log to the default logger (which is like throwing them away)
// public ChatManager(ModuleLoader loader, AuthServer authServer, LanguageTags languageTags,
// Options managerOptions, MyExtensions.Logging.Logger logger = null)
// /*int maxMessageKeep, int maxMessageSend, int saveInterval, int maxModuleWait,
// string acceptedTags, string globalTag, string saveFolder,
// string ircServer, string ircChannel, string ircTag,
// MyExtensions.Logging.Logger logger = null)*/
// {
// /*GetOption<int>("messageBacklog"), GetOption<int>("messageSend"),
// GetOption<int>("saveInterval"), GetOption<int>("moduleWaitSeconds"),
// GetOption<string>("acceptedTags"), GetOption<string>("globalTag"),
// GetOption<string>("saveFolder"), GetOption<string>("ircServer"),
// GetOption<string>("ircChannel"), GetOption<string>("ircTag"), logger);*/
//
//
//
// MaxMessageKeep = managerOptions.GetAsType<int>("messageBacklog");
// MaxMessageSend = managerOptions.GetAsType<int>("messageSend");
// MaxModuleWaitSeconds = managerOptions.GetAsType<int>("moduleWaitSeconds");
// /*IrcServer = managerOptions.GetAsType<string>("ircServer");
// IrcChannel = managerOptions.GetAsType<string>("ircChannel");
// IrcTag = managerOptions.GetAsType<string>("ircTag");*/
//
// GlobalTag = managerOptions.GetAsType<string>("globalTag");
// AllAcceptedTags = managerOptions.GetAsType<string>("acceptedTags").Split(",".ToCharArray(),
// StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToList();
// AllAcceptedTags.Add(GlobalTag);
//
// SaveFolder = MyExtensions.StringExtensions.PathFixer(managerOptions.GetAsType<string>("saveFolder"));
//
// if (logger != null)
// Logger = logger;
//
// //Attempt to load the bandwidth monitor in the constructor. It's not a big deal if it doesn't load
// //though, so just fall back to the nice default empty monitor if we fail.
// BandwidthMonitor tempMonitor;
//
// if (MySerialize.LoadObject<BandwidthMonitor>(SavePath(BandwidthFile), out tempMonitor))
// {
// Bandwidth = tempMonitor;
// Log("Loaded bandwidth data from file", MyExtensions.Logging.LogLevel.Debug);
// }
// else
// {
// Log("Couldn't load bandwidth data! Defaulting to empty bandwidth", MyExtensions.Logging.LogLevel.Error);
// }
//
// //Attempt to load the users in the constructor. Again, not a big deal if it doesn't load.
// Dictionary<int, User> tempUsers;
//
// if (MySerialize.LoadObject<Dictionary<int, User>>(SavePath(UserFile), out tempUsers))
// {
// users = tempUsers;
// Log("Loaded user data from file", MyExtensions.Logging.LogLevel.Debug);
// }
// else
// {
// Log("Couldn't load user data! Defaulting to empty user dictionary", MyExtensions.Logging.LogLevel.Error);
// }
//
// //Attempt to load the messages in the constructor. Again, not a big deal if it doesn't load.
// List<UserMessageJSONObject> tempMessages;
//
// if (MySerialize.LoadObject<List<UserMessageJSONObject>>(SavePath(MessageFile), out tempMessages))
// {
// messages = tempMessages;
// UserMessageJSONObject.FindNextID(messages);
// PMRoom.FindNextID(messages.Select(x => x.tag).ToList());
// Log("Loaded messages from file", MyExtensions.Logging.LogLevel.Debug);
// }
// else
// {
// Log("Couldn't load messages! Defaulting to empty message list", MyExtensions.Logging.LogLevel.Error);
// }
//
// Dictionary<string, List<UserMessageJSONObject>> tempHistory;
//
// if (MySerialize.LoadObject<Dictionary<string, List<UserMessageJSONObject>>>(SavePath(HistoryFile), out tempHistory))
// {
// history = tempHistory;
// PMRoom.FindNextID(history.SelectMany(x => x.Value.Select(y => y.tag)).ToList());
// Log("Loaded history from file", MyExtensions.Logging.LogLevel.Debug);
// }
// else
// {
// Log("Couldn't load history! Defaulting to empty history", MyExtensions.Logging.LogLevel.Error);
// }
//
// Dictionary<string, PMRoom> tempRooms;
//
// if (MySerialize.LoadObject<Dictionary<string, PMRoom>>(SavePath(RoomFile), out tempRooms))
// {
// rooms = tempRooms;
// PMRoom.FindNextID(rooms.Select(x => x.Key).ToList());
// Log("Loaded rooms from file", MyExtensions.Logging.LogLevel.Debug);
// }
// else
// {
// Log("Couldn't load rooms! Defaulting to no rooms", MyExtensions.Logging.LogLevel.Error);
// }
//
// //Connect to the IRC as the relay bot
// /*relay = new SimpleIRCRelay(IrcServer, IrcChannel, "sbs_relay_bot", this.Logger);
// relay.IRCRelayMessageEvent += IrcRelayMessage;
// relay.IRCRelayJoinEvent += IrcRelayJoin;
// relay.IRCRelayLeaveEvent += IrcRelayLeave;
// relay.ConnectAsync();*/
//
// //now set up the save file timer
// saveTimer = new System.Timers.Timer(1000 * managerOptions.GetAsType<int>("saveInterval"));
// saveTimer.Elapsed += SaveTimerElapsed;
// saveTimer.Start();
//
//// cleanupTimer = new System.Timers.Timer(1000 * managerOptions.GetAsType<int>("cleanInterval"));
//// cleanupTimer.Elapsed += CleanupTimerElapsed;
//// cleanupTimer.Start();
//
// /*pingTimer = new System.Timers.Timer(30000);
// pingTimer.Elapsed += PingTimer_Elapsed;
// pingTimer.Start();*/
// }
/*void PingTimer_Elapsed (object sender, ElapsedEventArgs e)
{
relay.Ping();
}*/
//When the server shuts down, do this.
// public void Stop()
// public override
// {
// SaveData();
// }\
public void SafeStop()
{
Stop();
SaveData();
}
//Force the manager to lock itself up. Warning: this really does lock the server up!
public void Lockup()
{
lock (managerLock)
{
//Now sit here for a while and think about what you've done!
Thread.Sleep(100000); //Just 100 seconds; not too bad.
}
}
// private void Log(string message, LogLevel level = LogLevel.Normal, string tag = "General")
// {
// Settings.LogProvider.LogGeneral(message, level, tag);
// }
// private void Log(string message, MyExtensions.Logging.LogLevel level = MyExtensions.Logging.LogLevel.Normal)
// {
// Settings.LogProvider.LogGeneral(message, level, LogTag);
// }
// void CleanupTimerElapsed (object sender, ElapsedEventArgs e)
// {
// List<Chat> leaveChatters = new List<Chat>();
//
// if(Monitor.TryEnter(managerLock, TimeSpan.FromSeconds(1)))
// {
// try
// {
// foreach(Chat chatter in new HashSet<Chat>(activeChatters))
// {
// List<string> reasons = new List<string>();
//
// if(chatter.State == WebSocketState.Closing)
// reasons.Add("closing state");
// if(chatter.State == WebSocketState.Closed)
// reasons.Add("closed state");
//// if(!chatter.Context.WebSocket.IsAlive)
//// reasons.Add("not alive?");
// if(chatter.TimeSincePing.TotalSeconds > 90)
// reasons.Add("not pinging enough");
//
// if(reasons.Count > 0)
// {
// Log("Found a dangling chatter (" + chatter.ThisUser.Username + ")? Trying to remove now",
// MyExtensions.Logging.LogLevel.Warning);
// Log("Dangle Reasons: " + string.Join(",", reasons), MyExtensions.Logging.LogLevel.Debug);
// leaveChatters.Add(chatter);
// }
// }
// }
// finally
// {
// Monitor.Exit(managerLock);
// }
// }
// else
// {
// Logger.LogGeneral("Couldn't run the cleanup... probably just saving module data",
// MyExtensions.Logging.LogLevel.SuperDebug, LogTag);
// }
//
// foreach (Chat chatter in leaveChatters)
// {
// LeaveChat(chatter);
// chatter.Context.WebSocket.CloseAsync();
// Log("Successfully (?) removed dangling chatter", MyExtensions.Logging.LogLevel.Warning);
// }
// }
//Start the save process
private void SaveTimerElapsed(object source, System.Timers.ElapsedEventArgs e)
{
SaveData();
Log("Automatically saved chat data to files", MyExtensions.Logging.LogLevel.Debug);
}
//Check on the thread count to see when it increases.
private void MonitorThreadsElapsed(object source, System.Timers.ElapsedEventArgs e)
{
int thisThreadCount;
using(Process process = Process.GetCurrentProcess())
{
thisThreadCount = process.Threads.Count;
}
//If we've never run before, chill. Set the value so we'll have it for NEXT time.
if (lastThreadCount == 0)
lastThreadCount = thisThreadCount;
if (lastThreadCount < thisThreadCount)
Log("Threads +increased from " + lastThreadCount + " to " + thisThreadCount, LogLevel.Debug);
else if (lastThreadCount > thisThreadCount)
Log("Threads -decreased from " + lastThreadCount + " to " + thisThreadCount, LogLevel.Debug);
lastThreadCount = thisThreadCount;
}
//Forces file save for all pertinent manager data
public void SaveData()
{
if (Monitor.TryEnter(fileLock, ChatSettings.MaxFileWait))
{
try
{
lock (Bandwidth.byteLock)
{
Log("Enter bandwidth lock", MyExtensions.Logging.LogLevel.Locks);
if (MySerialize.SaveObject<BandwidthMonitor>(SavePath(BandwidthFile), Bandwidth))
Log("Saved bandwidth data to file", MyExtensions.Logging.LogLevel.Debug);
else
Log("Couldn't save bandwidth data to file!", MyExtensions.Logging.LogLevel.Error);
Log("Exit bandwidth lock", MyExtensions.Logging.LogLevel.Locks);
}
if(Monitor.TryEnter(managerLock, ChatSettings.MaxModuleWait))
{
try
{
Log("Enter manager save lock", MyExtensions.Logging.LogLevel.Locks);
//Save users
if (MySerialize.SaveObject<Dictionary<int, User>>(SavePath(UserFile), users))
Log("Saved user data to file", MyExtensions.Logging.LogLevel.Debug);
else
Log("Couldn't save user data to file!", MyExtensions.Logging.LogLevel.Error);
//Save messages
if (MySerialize.SaveObject<List<UserMessageJSONObject>>(SavePath(MessageFile), messages))
Log("Saved messages to file", MyExtensions.Logging.LogLevel.Debug);
else
Log("Couldn't save messages to file!", MyExtensions.Logging.LogLevel.Error);
//Save history
if(MySerialize.SaveObject<Dictionary<string, List<UserMessageJSONObject>>>(SavePath(HistoryFile), history))
Log("Saved history to file", MyExtensions.Logging.LogLevel.Debug);
else
Log("Couldn't save history to file!", MyExtensions.Logging.LogLevel.Error);
//Save rooms
if (MySerialize.SaveObject<Dictionary<string, PMRoom>>(SavePath(RoomFile), rooms))
Log("Saved rooms to file", MyExtensions.Logging.LogLevel.Debug);
else
Log("Couldn't save rooms to file!", MyExtensions.Logging.LogLevel.Error);
Log("Exit manager save lock", MyExtensions.Logging.LogLevel.Locks);
}
finally
{
Monitor.Exit(managerLock);
}
}
else
{
Log("Couldn't save general manager data because the manager is locked up! (wait: " + ChatSettings.MaxModuleWait.TotalSeconds + ")", MyExtensions.Logging.LogLevel.Error);
}
//Save all module data
foreach (Module module in modules)
{
if(Monitor.TryEnter(module.Lock, ChatSettings.MaxFileWait))
{
try
{
if(loader.SaveWrapper(module))
Log("Saved " + module.ModuleName + " data", MyExtensions.Logging.LogLevel.Debug);
else
Log("Couldn't save " + module.ModuleName + " data!", LogLevel.Error);
}
finally
{
Monitor.Exit(module.Lock);
}
}
else
{
Log("Couldn't save " + module.ModuleName + " data; it appears to be busy", LogLevel.Warning);
}
}
}
finally
{
Monitor.Exit(fileLock);
}
}
else
{
Log("Couldn't save files... another process may still be writing", LogLevel.Warning);
}
}
public string SavePath(string filename)
{
return ChatSettings.SaveFolder + filename;
}
/*public int RegisterIrcUser(string username)
{
//Do NOT register relay users!
if (IrcSkipUsers().Contains(username))
return -1;
lock (userLock)
{
int lookupID = UserLookup(username);
if (lookupID < 0)
{
int ID = users.Max(x => x.Key);
if (ID < 1000000000)
ID = 1000000000;
User newUser = new User(++ID);
newUser.SetIRC(username, true);
users.Add(newUser.UID, newUser);
Log("Registered new IRC user #" + newUser.UID + ": " + newUser.Username);
return newUser.UID;
}
else if (lookupID < 1000000000)
{
Log("Tried to register a real user as an IRC user!", MyExtensions.Logging.LogLevel.Error);
}
else
return lookupID;
}
return -1;
}*/
public User GetUser(int uid)
{
User user = new User(0);
lock (managerLock)
{
Log("Enter getuser lock", MyExtensions.Logging.LogLevel.Locks);
if (users.ContainsKey(uid))
user = users[uid];
Log("Exit getuser lock", MyExtensions.Logging.LogLevel.Locks);
}
return user;
}
public bool UserExists(int uid)
{
bool userExists = false;
lock (managerLock)
{
Log("Enter userexists lock", MyExtensions.Logging.LogLevel.Locks);
userExists = users.ContainsKey(uid);
Log("Exit userexists lock", MyExtensions.Logging.LogLevel.Locks);
}
return userExists;
}
public int UserLookup(string username)
{
int userID = -1;
lock (managerLock)
{
Log("Enter userlookup lock", MyExtensions.Logging.LogLevel.Locks);
try
{
userID = users.First(x => x.Value.Username == username).Key;
}
catch
{
userID = -1;
}
Log("Exit userlookup lock", MyExtensions.Logging.LogLevel.Locks);
}
return userID;
}
public List<string> AllAcceptedTagsForUser(int user)
{
List<string> allTags = new List<string>();
lock (managerLock)
{
Log("Enter allacceptedtagsforuser lock", MyExtensions.Logging.LogLevel.Locks);
allTags = ChatSettings.AcceptedTags.Union(rooms.Where(x => x.Value.Users.Contains(user)).Select(x => x.Key)).ToList();
Log("Exit allacceptedtagsforuser lock", MyExtensions.Logging.LogLevel.Locks);
}
return allTags;
}
public bool ValidTagForUser(int user, string tag)
{
return AllAcceptedTagsForUser(user).Contains(tag);
}
/*public List<Module> VisibleModulesForUser(int user)
{
lock (userLock)
{
List<Module> returnModules = new List<Module>();
if (users.ContainsKey(user))
{
UserInfo realUser = new UserInfo(users[user]);
returnModules = modules.Where(x => !x.Hidden(realUser)).ToList();
}
return returnModules;
}
}*/
public bool LeavePMRoom(int user, string room, out string error)
{
error = "";
bool result = false;
lock (managerLock)
{
Log("Enter leavepmroom lock", MyExtensions.Logging.LogLevel.Locks);
if (!users.ContainsKey(user))
{
error = "You don't seem to exist... I'm not sure how to leave the room";
}
else if (ChatSettings.AcceptedTags.Contains(room))//!rooms.ContainsKey(room))
{
error = "You can't leave this room!";
}
else if (!rooms.ContainsKey(room))
{
error = "This room doesn't exist?";
}
else if (!rooms[room].Users.Contains(user))
{
error = "You're not in that room.";
}
else
{
rooms[room].Users.Remove(user);
if (rooms[room].Users.Count < 2)
rooms.Remove(room);
result = true;
}
Log("Exit leavepmroom lock", MyExtensions.Logging.LogLevel.Locks);
}
if (result)
BroadcastUserList();
return result;
}
public bool CreatePMRoom(HashSet<int> newUsers, int creator, out string error)
{
error = "";
bool result = false;
lock(managerLock)
{
Log("Enter createpmroom lock", MyExtensions.Logging.LogLevel.Locks);
if (newUsers.Count < 2)
{
error = "There's not enough people to make the room";
}
else if (rooms.Any(x => x.Value.Users.SetEquals(newUsers)))
{
error = "There's already a room with this exact set of people!";
}
else if (!newUsers.All(x => users.ContainsKey(x)))
{
error = "One or more of the given users doesn't exist!";
}
/*else if (newUsers.Any(x => users[x].IrcUser))
{
error = "You can't include IRC users in a PM room!";
}*/
else if (!users.ContainsKey(creator))
{
error = "You don't seem to exist... I'm not sure how to create the room";
}
else if (users[creator].Banned || users[creator].Blocked)
{
error = "You are banned or blocked and cannot create a room";
}
else
{
PMRoom newRoom = new PMRoom(newUsers, creator, TimeSpan.FromDays(1));
rooms.Add(newRoom.Name, newRoom);
result = true;
}
Log("Exit createpmroom lock", MyExtensions.Logging.LogLevel.Locks);
}
if (result)
BroadcastUserList();
return result;
}
//ONLY the registration of a new user. It has nothing to do with authentication
private bool TryRegister(int uid, string key)
{
bool good = false;
lock (managerLock)
{
Log("Enter register lock", MyExtensions.Logging.LogLevel.Locks);
if (users.ContainsKey(uid))
{
good = true;
}
else if (authServer.CheckAuth(uid, key))
{
users.Add(uid, new User(uid));
good = true;
}
Log("Exit register lock", MyExtensions.Logging.LogLevel.Locks);
}
return good;
}
/// <summary>
/// Attempt to authenticate the given user with the given key. LOCKS MANAGER!
/// </summary>
/// <param name="chatSession">Chat session.</param>
/// <param name="uid">Uid.</param>
/// <param name="key">Key.</param>
public bool CheckAuthentication(/*Chat chatSession,*/ int uid, string key, /*out List<Chat> duplicates,*/ out string error)
{
//duplicates = new List<Chat>();
error = "";
if (authServer.CheckAuth(uid, key))
{
if (TryRegister(uid, key))
{
if (!GetUser(uid).PullInfoFromQueryPage())
{
error = "Couldn't authenticate because your user information couldn't be found";
Log("Authentication failed: Couldn't get user information from website", LogLevel.Warning);
return false;
}
// lock (managerLock)
// {
// Log("Enter authenticate lock", MyExtensions.Logging.LogLevel.Locks);
// duplicates = activeChatters.Where(x => x.UID == uid).ToList();
// foreach (Chat chatter in activeChatters.Where(x => x.UID == uid))
// chatter.Context.WebSocket.CloseAsync();
// activeChatters.RemoveWhere(x => x.UID == uid);
// activeChatters.Add(chatSession);
// Log("Exit authenticate lock", MyExtensions.Logging.LogLevel.Locks);
// }
return true;
}
}
else
{
Log("User " + uid + " tried to bind with bad auth code: " + key);
error = "Key was invalid";
}
return false;
}
/// <summary>
/// When a (hopefully) authenticated user leaves chat, this crap happens. LOCKS MANAGER!
/// </summary>
/// <param name="chatSession">Current Chat Session</param>
public void UpdateAuthUserlist()//Chat chatSession)
{
//bool didLeave = false;
if (Monitor.TryEnter(managerLock, ChatSettings.MaxModuleWait))
{
try
{
Log("Enter leavechat lock", MyExtensions.Logging.LogLevel.Locks);
//didLeave = activeChatters.Remove(chatSession);
authServer.UpdateUserList(ConnectedUsers().Select(x => ((Chat)x).UID).Where(x => x > 0).ToList());//activeChatters.Select(x => x.UID).ToList());
Log("Exit leavechat lock", MyExtensions.Logging.LogLevel.Locks);
}
finally
{
Monitor.Exit(managerLock);
}
}
// else
// {
// Log("Session " + chatSession.UID + " could not leave properly! Data may be inconsistent!", MyExtensions.Logging.LogLevel.Error);
// }
// BroadcastUserList();
//
// //Only perform special leaving messages and processing if the user was real
// if (users.ContainsKey(chatSession.UID) && didLeave)
// {
// if (!users[chatSession.UID].PerformOnChatLeave())
// Logger.Warning("User session timer was in an invalid state!");
//
// if (users[chatSession.UID].ShowMessages)
// Broadcast(new LanguageTagParameters(ChatTags.Leave, users[chatSession.UID]), new SystemMessageJSONObject());
// }
//SimpleLeave(chatSession.UID);
// BroadcastUserList();
//
// //Only perform special leaving messages and processing if the user was real
// if (users.ContainsKey(chatSession.UID))
// {
// if (!users[chatSession.UID].PerformOnChatLeave())
// Logger.Warning("User session timer was in an invalid state!");
//
// if (users[chatSession.UID].ShowMessages)
// Broadcast(new LanguageTagParameters(ChatTags.Leave, users[chatSession.UID]), new SystemMessageJSONObject());
// }
}
// public void SimpleEnter(int uid)
// {
// BroadcastUserList();
//
// //Only perform special leaving messages and processing if the user was real
// if (users.ContainsKey(uid))
// {
// if (!users[uid].PerformOnChatEnter())
// Logger.Warning("User session timer was in an invalid state!");
//
// if (users[uid].ShowMessages)
// Broadcast(new LanguageTagParameters(ChatTags.Join, users[uid]), new SystemMessageJSONObject());
// }
// }
// public void SimpleLeave(int uid)
// {
// BroadcastUserList();
//
// //Only perform special leaving messages and processing if the user was real
// if (users.ContainsKey(uid))
// {
// if (!users[uid].PerformOnChatLeave())
// Logger.Warning("User session timer was in an invalid state!");
//
// if (users[uid].ShowMessages)
// Broadcast(new LanguageTagParameters(ChatTags.Leave, users[uid]), new SystemMessageJSONObject());
// }
// }
/*public void IrcRelayJoin(string username)
{
Log("IRC Join: " + username);
SimpleEnter(UserLookup(username));
}
public void IrcRelayLeave(string username)
{
Log("IRC Leave: " + username);
SimpleLeave(UserLookup(username));
}
public void IrcRelayMessage(string sender, string message)
{
//Skip this buttneck
if (IrcSkipUsers().Contains(sender))
return;
User ircUser = GetUser(UserLookup(sender));