-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
1926 lines (1836 loc) · 91.8 KB
/
Program.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 ComputerUtils.CommandLine;
using ComputerUtils.Discord;
using ComputerUtils.Encryption;
using ComputerUtils.FileManaging;
using ComputerUtils.Logging;
using ComputerUtils.QR;
using ComputerUtils.RandomExtensions;
using ComputerUtils.StringFormatters;
using ComputerUtils.VarUtils;
using ComputerUtils.Webserver;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace ComputerAnalytics
{
class Program
{
static void Main(string[] args)
{
Logger.displayLogInConsole = true;
CommandLineCommandContainer cla = new CommandLineCommandContainer(args);
cla.AddCommandLineArgument(new List<string> { "--workingdir" }, false, "Sets the working Directory for ComputerAnalytics", "directory", "");
cla.AddCommandLineArgument(new List<string> { "update", "--update", "-U" }, true, "Starts in update mode (use with caution. It's best to let it do on it's own)");
cla.AddCommandLineArgument(new List<string> { "--displayMasterToken", "-dmt" }, true, "Outputs the master token without starting the server");
if (cla.HasArgument("help"))
{
cla.ShowHelp();
return;
}
string workingDir = cla.GetValue("--workingdir");
if (cla.HasArgument("update"))
{
Logger.Log("Replacing everything with zip contents.");
Thread.Sleep(1000);
string destDir = new DirectoryInfo(Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)).Parent.FullName + Path.DirectorySeparatorChar;
using (ZipArchive archive = ZipFile.OpenRead(destDir + "updater" + Path.DirectorySeparatorChar + "update.zip"))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
String name = entry.FullName;
if (name.EndsWith("/")) continue;
if (name.Contains("/")) Directory.CreateDirectory(destDir + Path.GetDirectoryName(name));
entry.ExtractToFile(destDir + entry.FullName, true);
}
}
ProcessStartInfo i = new ProcessStartInfo
{
FileName = "dotnet",
Arguments = "\"" + destDir + "ComputerAnalytics.dll\" --workingdir \"" + workingDir + "\"",
UseShellExecute = true
};
Process.Start(i);
Environment.Exit(0);
}
if (!workingDir.EndsWith(Path.DirectorySeparatorChar)) workingDir += Path.DirectorySeparatorChar;
if (workingDir == Path.DirectorySeparatorChar.ToString()) workingDir = AppDomain.CurrentDomain.BaseDirectory;
if (!File.Exists(workingDir + "analytics" + Path.DirectorySeparatorChar + "config.json")) File.WriteAllText(workingDir + "analytics" + Path.DirectorySeparatorChar + "config.json", JsonSerializer.Serialize(new Config()));
Config c = JsonSerializer.Deserialize<Config>(File.ReadAllText(workingDir + "analytics" + Path.DirectorySeparatorChar + "config.json"));
if (cla.HasArgument("-dmt"))
{
QRCodeGeneratorWrapper.Display(c.masterToken);
return;
}
AnalyticsServer s = new AnalyticsServer();
s.workingDir = workingDir;
HttpServer server = new HttpServer();
s.AddToServer(server);
}
}
class AnalyticsServer
{
public HttpServer server = null;
public AnalyticsDatabaseCollection collection = null;
public Dictionary<string, string> replace = new Dictionary<string,string> { { "<", ""}, { ">", ""}, { "\\u003C", "" }, { "\\u003E", "" } };
public string workingDir = "";
/// <summary>
/// Adds analytics functionality to a existing server
/// </summary>
/// <param name="httpServer">server to which you want to add analytics functionality</param>
public void AddToServer(HttpServer httpServer)
{
AppDomain.CurrentDomain.UnhandledException += HandleExeption;
Logger.displayLogInConsole = true;
if (!workingDir.EndsWith(Path.DirectorySeparatorChar)) workingDir += Path.DirectorySeparatorChar;
if (workingDir == Path.DirectorySeparatorChar.ToString()) workingDir = AppDomain.CurrentDomain.BaseDirectory;
Logger.Log("Working directory is " + workingDir);
Logger.Log("Analytics directory is " + workingDir + "analytics");
collection = new AnalyticsDatabaseCollection(this);
this.server = httpServer;
Logger.Log("Public address: " + collection.GetPublicAddress());
SendMasterWebhookMessage("Server started", "The server has just started", 0x42BBEB);
Thread warningSystemsAndSiteMetrics = new Thread(() =>
{
int iteration = 0;
TimeSpan waiting = new TimeSpan(24, 0, 0);
while (true)
{
if (iteration == 1)
{
try
{
double sleep = (waiting - (DateTime.UtcNow - collection.config.lastWebhookUpdate)).TotalMinutes;
Logger.Log("Warning Systems and Site metrics waiting " + sleep + " minutes until next execution");
Thread.Sleep(sleep <= 0 ? 0 : (int)Math.Round(sleep * 60 * 1000));
}
catch (Exception ex)
{
Logger.Log("Error while waiting: " + ex.ToString(), LoggingType.Warning);
}
SendMasterWebhookMessage("ComputerAnalytics metrics report", "__**Those metrics are for the last " + (DateTime.UtcNow - collection.config.lastWebhookUpdate).TotalHours + " hours**__\n\n**Analytics recieved:** `" + collection.config.recievedAnalytics + "`\n**Rejected Analytics:** `" + collection.config.rejectedAnalytics + "`\n**Current Ram usage:**`" + SizeConverter.ByteSizeToString(Process.GetCurrentProcess().WorkingSet64) + "`\n\n_Next update in approximately " + waiting.TotalHours + " hours_", 0x1CAD15);
collection.config.recievedAnalytics = 0;
collection.config.rejectedAnalytics = 0;
for (int i = 0; i < collection.config.Websites.Count; i++)
{
Website w = collection.config.Websites[i];
if (w.discordWebhookUrl != "")
{
try
{
Logger.Log("Sending webhook for " + w.url);
DiscordWebhook webhook = new DiscordWebhook(w.discordWebhookUrl);
webhook.SendEmbed("Site metrics report", "__**Those metrics are for the last " + (DateTime.UtcNow - w.lastWebhookUpdate).TotalHours + " hours**__\n\n**Site clicks:** `" + w.siteClicks + "`\n_If you want more details check the analytics page_\n\n_Next update in approximately " + waiting.TotalHours + " hours_", w.url + " " + DateTime.UtcNow, "ComputerAnalytics", "https://computerelite.github.io/assets/CE_512px.png", collection.GetPublicAddress(), "https://computerelite.github.io/assets/CE_512px.png", collection.GetPublicAddress(), 0x1CAD15);
} catch (Exception ex)
{
Logger.Log("Exception while sending webhook" + ex.ToString(), LoggingType.Warning);
}
collection.config.Websites[i].lastWebhookUpdate = DateTime.UtcNow;
}
collection.config.Websites[i].siteClicks = 0;
}
collection.config.lastWebhookUpdate = DateTime.UtcNow;
collection.SaveConfig();
iteration = -1;
}
iteration++;
}
});
warningSystemsAndSiteMetrics.Start();
Logger.Log("Analytics will be send to " + collection.GetPublicAddress());
server.AddRoute("GET", "/randomtoken", new Func<ServerRequest, bool>(request =>
{
request.SendString(RandomExtension.CreateToken());
return true;
}));
server.AddRoute("POST", "/analytics", new Func<ServerRequest, bool>(request =>
{
string origin = request.context.Request.Headers.Get("Origin");
AnalyticsData data = new AnalyticsData();
try
{
data = AnalyticsData.Recieve(request);
collection.config.recievedAnalytics++;
} catch(Exception e)
{
collection.config.rejectedAnalytics++;
collection.SaveConfig();
//SendMasterWebhookMessage("ComputerAnalytics rejected analytic", "**Reason:** `" + e.Message + "`\n**UA:** `" + request.context.Request.UserAgent + "`", 0xDA3633);
Logger.Log("Error while recieving analytics json:\n" + e.ToString(), LoggingType.Warning);
request.SendString(new AnalyticsResponse("error", e.Message).ToString(), "application/json", 500, true, new Dictionary<string, string>() { { "Access-Control-Allow-Origin", origin }, { "Access-Control-Allow-Credentials", "true" } });
return true;
}
try
{
collection.AddAnalyticsToWebsite(origin, data);
}
catch (Exception e)
{
Logger.Log("Error while accepting analytics json:\n" + e.ToString(), LoggingType.Warning);
request.SendString(new AnalyticsResponse("error", "Error accepting json: " + e.Message).ToString(), "application/json", 500, true, new Dictionary<string, string>() { { "Access-Control-Allow-Origin", origin }, { "Access-Control-Allow-Credentials", "true" } });
return true;
}
request.SendString(new AnalyticsResponse("success", "Analytic recieved").ToString(), "application/json", 200, true, new Dictionary<string, string>() { { "Access-Control-Allow-Origin", origin }, { "Access-Control-Allow-Credentials", "true" } });
return true;
}));
server.AddRoute("OPTIONS", "/analytics", new Func<ServerRequest, bool>(request =>
{
string origin = request.context.Request.Headers.Get("Origin");
request.SendData(new byte[0], "", 200, true, new Dictionary<string, string>() { { "Access-Control-Allow-Origin", collection.GetAllowedOrigin(origin) }, { "Access-Control-Allow-Methods", "POST, OPTIONS" }, { "Access-Control-Allow-Credentials", "true" }, { "Access-Control-Allow-Headers", "content-type" } });
return true;
}));
server.AddRoute("GET", "/analytics.js", new Func<ServerRequest, bool>(request =>
{
string origin = request.queryString.Get("origin");
if(origin == null)
{
request.SendString("alert(`Add '?origin=YourSite' to analytics.js src. Replace YourSite with your site e. g. https://computerelite.github.io`)", "application/javascript") ;
return true;
}
request.automaticHeaders.Add("Access-Control-Allow-Origin", request.queryString.Get("origin"));
request.SendString(ReadResource("analytics.js").Replace("{0}", "\"" + collection.GetPublicAddress() + "/\"").Replace("{1}", collection.GetPublicToken(origin)), "application/javascript");
return true;
}), false, true, true, true, 0, true, 0);
server.AddRoute("GET", "/analytics", new Func<ServerRequest, bool>(request =>
{
if (IsNotLoggedIn(request)) return true;
request.SendString(ReadResource("analytics.html"), "text/html");
return true;
}));
server.AddRoute("GET", "/", new Func<ServerRequest, bool>(request =>
{
request.SendString(ReadResource("login.html"), "text/html");
return true;
}));
server.AddRoute("GET", "/plotly.min.js", new Func<ServerRequest, bool>(request =>
{
request.SendString(ReadResource("plotly.js"), "application/javascript");
return true;
}));
server.AddRoute("GET", "/analytics/endpoints", new Func<ServerRequest, bool>(request =>
{
try
{
request.SendStringReplace(JsonSerializer.Serialize(collection.GetAllEndpointsWithAssociatedData(request)), "application/json", 200, replace);
} catch(Exception e)
{
Logger.Log("Error while crunching data:\n" + e.ToString(), LoggingType.Warning);
request.SendString("Error: " + e.Message, "text/plain", 500);
}
return true;
}));
server.AddRoute("GET", "/analytics/countries", new Func<ServerRequest, bool>(request =>
{
try
{
request.SendStringReplace(JsonSerializer.Serialize(collection.GetAllCountriesWithAssociatedData(request)), "application/json", 200, replace);
}
catch (Exception e)
{
Logger.Log("Error while crunching data:\n" + e.ToString(), LoggingType.Warning);
request.SendString("Error: " + e.Message, "text/plain", 500);
}
return true;
}));
server.AddRoute("GET", "/analytics/time", new Func<ServerRequest, bool>(request =>
{
if (IsNotLoggedIn(request)) return true;
try
{
request.SendStringReplace(JsonSerializer.Serialize(collection.GetAllEndpointsSortedByTimeWithAssociatedData(request)), "application/json", 200, replace);
}
catch (Exception e)
{
Logger.Log("Error while crunching data:\n" + e.ToString(), LoggingType.Warning);
request.SendString("Error: " + e.Message, "text/plain", 500);
}
return true;
}));
server.AddRoute("GET", "/analytics/screen", new Func<ServerRequest, bool>(request =>
{
if (IsNotLoggedIn(request)) return true;
try
{
request.SendStringReplace(JsonSerializer.Serialize(collection.GetAllScreensWithAssociatedData(request)), "application/json", 200, replace);
}
catch (Exception e)
{
Logger.Log("Error while crunching data:\n" + e.ToString(), LoggingType.Warning);
request.SendString("Error: " + e.Message, "text/plain", 500);
}
return true;
}));
server.AddRoute("GET", "/analytics/referrers", new Func<ServerRequest, bool>(request =>
{
if (IsNotLoggedIn(request)) return true;
try
{
request.SendStringReplace(JsonSerializer.Serialize(collection.GetAllReferrersWithAssociatedData(request)), "application/json", 200, replace);
}
catch (Exception e)
{
Logger.Log("Error while crunching data:\n" + e.ToString(), LoggingType.Warning);
request.SendString("Error: " + e.Message, "text/plain", 500);
}
return true;
}));
server.AddRoute("GET", "/analytics/newusers", new Func<ServerRequest, bool>(request =>
{
if (IsNotLoggedIn(request)) return true;
try
{
request.SendStringReplace(JsonSerializer.Serialize(collection.GetNewUsersPerDay(request)), "application/json", 200, replace);
}
catch (Exception e)
{
Logger.Log("Error while crunching data:\n" + e.ToString(), LoggingType.Warning);
request.SendString("Error: " + e.Message, "text/plain", 500);
}
return true;
}));
server.AddRoute("GET", "/websites", new Func<ServerRequest, bool>(request =>
{
if(GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString(JsonSerializer.Serialize(collection.config.Websites), "application/json");
return true;
}));
server.AddRoute("DELETE", "/website", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString(collection.DeleteWebsite(request.bodyString));
return true;
}));
server.AddRoute("POST", "/website", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString(collection.CreateWebsite(request.bodyString), "application/json");
return true;
}));
server.AddRoute("POST", "/renewtokens", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString(collection.RenewTokens(request.bodyString.Split('|')[0], request.bodyString.Split('|')[1]), "application/json"); // url|token
return true;
}));
server.AddRoute("POST", "/addtoken", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString(collection.AddToken(request.bodyString.Split('|')[0], request.bodyString.Split('|')[1]), "application/json"); // url|expires
return true;
}));
server.AddRoute("POST", "/deletetoken", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString(collection.RemoveToken(request.bodyString.Split('|')[0], request.bodyString.Split('|')[1]), "application/json"); // url|token
return true;
}));
server.AddRoute("POST", "/renewmastertoken", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString(collection.RenewMasterToken(), "application/json");
return true;
}));
server.AddRoute("GET", "/manage", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString(ReadResource("manage.html"), "text/html");
return true;
}));
server.AddRoute("GET", "/login", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString("True");
return true;
}));
server.AddRoute("POST", "/publicaddress", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString(collection.SetPublicAddress(request.bodyString), "application/json");
return true;
}));
server.AddRoute("GET", "/publicaddress", new Func<ServerRequest, bool>(request =>
{
request.SendString(collection.GetPublicAddress(), "application/json");
return true;
}));
server.AddRoute("GET", "/requestexport", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
string filename = workingDir + "export.zip";
request.SendString("the zip is being generated. Check /export to get the file once it's available");
//request.SendString("requested export. Please head to /export");
Logger.Log("Exporting all data as zip. This may take a minute to do");
try
{
if (File.Exists(filename)) File.Delete(filename);
} catch
{
Logger.Log("Could not delete old export.zip");
return true;
}
ZipFile.CreateFromDirectory(collection.analyticsDir, filename);
Logger.Log("zip created");
return true;
}));
server.AddRoute("GET", "/export", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
if(!File.Exists(workingDir + "export.zip"))
{
request.SendString("File does not exist yet. Please refresh this site in a bit or request a new export zip from /requestexport", "text/plain", 425);
return true;
}
Logger.Log("Sending zip");
try
{
request.SendFile(workingDir + "export.zip");
File.Delete(workingDir + "export.zip");
} catch { request.SendString("File exists but isn't ready. Please refresh this site in a bit or request a new export zip from /requestexport", "text/plain", 425); }
return true;
}));
server.AddRoute("GET", "/metrics", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
Metrics m = new Metrics();
Process currentProcess = Process.GetCurrentProcess();
m.ramUsage = currentProcess.WorkingSet64;
m.ramUsageString = SizeConverter.ByteSizeToString(m.ramUsage);
m.workingDirectory = workingDir;
request.SendString(JsonSerializer.Serialize(m), "application/json");
return true;
}));
server.AddRoute("GET", "/test", new Func<ServerRequest, bool>(request =>
{
string s = "";
foreach(string header in request.context.Request.Headers.AllKeys)
{
s += header + ": " + request.context.Request.Headers[header] + " <br>";
}
request.SendString(s, "text/html");
return true;
}));
server.AddRoute("POST", "/update", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
FileManager.RecreateDirectoryIfExisting(AppDomain.CurrentDomain.BaseDirectory + "updater");
SendMasterWebhookMessage("ComputerAnalytics Update Deployed", "**Changelog:** `" + (request.queryString.Get("changelog") == null ? "none" : request.queryString.Get("changelog")) + "`", 0x42BBEB);
string zip = AppDomain.CurrentDomain.BaseDirectory + "updater" + Path.DirectorySeparatorChar + "update.zip";
File.WriteAllBytes(zip, request.bodyBytes);
foreach(string s in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory))
{
if (s.EndsWith("zip")) continue;
Logger.Log("Copying " + s);
File.Copy(s, AppDomain.CurrentDomain.BaseDirectory + "updater" + Path.DirectorySeparatorChar + Path.GetFileName(s), true);
}
//Logger.Log("dotnet \"" + AppDomain.CurrentDomain.BaseDirectory + "updater" + Path.DirectorySeparatorChar + "ComputerAnalytics.dll\" update");
request.SendString("Starting update. Please wait a bit and come back.");
ProcessStartInfo i = new ProcessStartInfo
{
Arguments = "\"" + AppDomain.CurrentDomain.BaseDirectory + "updater" + Path.DirectorySeparatorChar + "ComputerAnalytics.dll\" update --workingdir \"" + workingDir.Substring(0, workingDir.Length - 1) + "\"",
UseShellExecute = true,
FileName = "dotnet"
};
Process.Start(i);
Environment.Exit(0);
return true;
}));
server.AddRoute("POST", "/updateoculusdb", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
FileManager.RecreateDirectoryIfExisting("/mnt/DiscoExt/OculusDB/updater");
SendMasterWebhookMessage("OculusDB vy ComputerAnalytics Update Deployed", "**Changelog:** `" + (request.queryString.Get("changelog") == null ? "none" : request.queryString.Get("changelog")) + "`", 0x42BBEB);
string zip = "/mnt/DiscoExt/OculusDB/updater" + Path.DirectorySeparatorChar + "update.zip";
File.WriteAllBytes(zip, request.bodyBytes);
request.SendString("Starting update. Please wait a bit and come back.");
string destDir = "/mnt/DiscoExt/OculusDB/";
using (ZipArchive archive = ZipFile.OpenRead(zip))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
String name = entry.FullName;
if (name.EndsWith("/")) continue;
if (name.Contains("/")) Directory.CreateDirectory(destDir + Path.GetDirectoryName(name));
entry.ExtractToFile(destDir + entry.FullName, true);
}
}
ProcessStartInfo i = new ProcessStartInfo
{
FileName = "dotnet",
Arguments = "\"" + destDir + "OculusDB.dll\" --workingdir \"/mnt/DiscoExt/OculusDB/\"",
RedirectStandardOutput = true,
RedirectStandardError = true
};
Process p = Process.Start(i);
p.OutputDataReceived += (sender, args) =>
{
Logger.Log("OculusDB: " + args.Data);
};
return true;
}));
server.AddRoute("GET", "/console", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
Logger.saveOutputInVariable = true;
request.SendString(ReadResource("console.html"), "text/html");
return true;
}));
server.AddRoute("GET", "/consoleoutput", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendStringReplace(Logger.log, "text/plain", 200, replace);
return true;
}));
server.AddRoute("POST", "/restart", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString("Restarting");
ProcessStartInfo i = new ProcessStartInfo
{
Arguments = "\"" + AppDomain.CurrentDomain.BaseDirectory + "ComputerAnalytics.dll\"",
UseShellExecute = true,
FileName = "dotnet"
};
Process.Start(i);
Environment.Exit(0);
return true;
}));
server.AddRoute("POST", "/shutdown", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString("Shutting down");
Environment.Exit(0);
return true;
}));
server.AddRoute("GET", "/script.js", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken && IsNotLoggedIn(request))
{
request.Send403();
return true;
}
request.SendString(ReadResource("script.js"), "application/javascript");
return true;
}));
server.AddRoute("GET", "/style.css", new Func<ServerRequest, bool>(request =>
{
request.SendString(ReadResource("style.css"), "text/css");
return true;
}));
server.AddRoute("POST", "/masterwebhook", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
collection.config.masterDiscordWebhookUrl = request.bodyString;
collection.SaveConfig();
request.SendString("Set masterwebhook");
return true;
}));
server.AddRoute("GET", "/masterwebhook", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString(collection.config.masterDiscordWebhookUrl);
return true;
}));
server.AddRoute("POST", "/webhook", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
collection.SaveConfig();
request.SendString(collection.SetWebhook(request.queryString.Get("url"), request.bodyString));
return true;
}));
server.AddRoute("GET", "/privacy", new Func<ServerRequest, bool>(request =>
{
request.SendString(ReadResource("privacy.html"), "text/html");
//request.Redirect("https://github.com/ComputerElite/ComputerAnalytics/wiki");
return true;
}));
server.AddRoute("GET", "/privacy.txt", new Func<ServerRequest, bool>(request =>
{
request.SendString(ReadResource("privacy.txt").Replace("{0}", collection.config.useMongoDB ? "via MongoDB" : "locally").Replace("{1}", collection.config.geoLocationEnabled ? "cand to check from which country the most visitors are" : ""));
return true;
}));
server.AddRoute("GET", "/analytics/docs", new Func<ServerRequest, bool>(request =>
{
request.SendString(ReadResource("api.txt"));
return true;
}));
server.AddRoute("GET", "/config", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
request.SendString(JsonSerializer.Serialize(collection.config), "application/json");
return true;
}));
server.AddRoute("POST", "/config", new Func<ServerRequest, bool>(request =>
{
if (GetToken(request) != collection.config.masterToken)
{
request.Send403();
return true;
}
collection.config = JsonSerializer.Deserialize<Config>(request.bodyString);
collection.SaveConfig();
request.SendString("Updated config. Please restart the server to apply the changes you did.");
return true;
}));
// Do all stuff after server setup
collection.LoadAllDatabases(workingDir + "analytics");
collection.ReorderDataOfAllDataSetsV1();
server.StartServer(collection.config.port);
}
public void HandleExeption(object sender, UnhandledExceptionEventArgs args)
{
SendMasterWebhookMessage("Critical Unhandled Exception", "ComputerAnalytics managed to crash. Well done Developer: " + ((Exception)args.ExceptionObject).ToString().Substring(0, 1900), 0xFF0000);
}
public string GetToken(ServerRequest request)
{
Cookie token = request.cookies["token"];
if (token == null)
{
request.Send403();
return "";
}
return token.Value;
}
public void SendMasterWebhookMessage(string title, string description, int color)
{
if (collection.config.masterDiscordWebhookUrl == "") return;
try
{
Logger.Log("Sending master webhook");
DiscordWebhook webhook = new DiscordWebhook(collection.config.masterDiscordWebhookUrl);
webhook.SendEmbed(title, description, "master " + DateTime.UtcNow, "ComputerAnalytics", "https://computerelite.github.io/assets/CE_512px.png", collection.GetPublicAddress(), "https://computerelite.github.io/assets/CE_512px.png", collection.GetPublicAddress(), color);
}
catch (Exception ex)
{
Logger.Log("Exception while sending webhook" + ex.ToString(), LoggingType.Warning);
}
}
public bool IsNotLoggedIn(ServerRequest request)
{
if (!collection.DoesWebsiteWithPrivateTokenExist(GetToken(request)))
{
request.Send403();
return true;
}
return false;
}
public string ReadResource(string name)
{
// Determine path
var assembly = Assembly.GetExecutingAssembly();
string resourcePath = name;
if (!name.StartsWith(Assembly.GetExecutingAssembly().GetName().Name.ToString()))
{
resourcePath = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith(name));
}
using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
class AnalyticsDatabaseCollection
{
public List<AnalyticsDatabase> databases { get; set; } = new List<AnalyticsDatabase>();
public Config config = new Config();
public string analyticsDir = "";
public AnalyticsServer parentServer = null;
public MongoClient mongoClient = null;
public AnalyticsDatabaseCollection(AnalyticsServer parent)
{
this.parentServer = parent;
}
public void LoadAllDatabases(string analyticsDir = "analytics")
{
if (!analyticsDir.EndsWith(Path.DirectorySeparatorChar)) analyticsDir += Path.DirectorySeparatorChar;
this.analyticsDir = analyticsDir;
Logger.Log("Loading all databases");
FileManager.CreateDirectoryIfNotExisting(analyticsDir);
if(!File.Exists(analyticsDir + "config.json")) SaveConfig();
config = JsonSerializer.Deserialize<Config>(File.ReadAllText(analyticsDir + "config.json"));
config.Fix();
if (config.publicAddress == "") SetPublicAddress("http://localhost");
if (config.useMongoDB)
{
mongoClient = new MongoClient(config.mongoDBUrl);
}
for (int i = 0; i < config.Websites.Count; i++)
{
AnalyticsDatabase database = new AnalyticsDatabase(config.Websites[i].url, this, analyticsDir + config.Websites[i].folder);
databases.Add(database);
}
SaveConfig();
Logger.Log("Loaded all databases");
}
public string SetPublicAddress(string newAddress)
{
config.publicAddress = newAddress;
SaveConfig();
return "Set public address to " + GetPublicAddress() + ".";
}
public string GetPublicAddress()
{
return config.publicAddress;
}
public string GetPublicToken(string origin)
{
foreach(Website w in config.Websites)
{
if (w.url == origin) return w.publicToken;
}
return "";
}
public string GetPublicTokenFromPrivateToken(string privateToken)
{
foreach (Website w in config.Websites)
{
if (w.HasPrivateToken(privateToken)) return w.publicToken;
}
return "";
}
public string CreateRandomToken()
{
string token = RandomExtension.CreateToken();
while(config.usedTokens.Contains(token))
{
token = RandomExtension.CreateToken();
}
config.usedTokens.Add(token);
return token;
}
public string AddToken(string url, string expires)
{
DateTime expiration = DateTime.Parse(expires);
for (int i = 0; i < config.Websites.Count; i++)
{
if (config.Websites[i].url == url)
{
config.Websites[i].privateTokens.Add(new Token(CreateRandomToken(), expiration));
SaveConfig();
return "Added token which expires on " + expiration.ToString() + " for " + url;
}
}
return "Website not registered";
}
public int GetDatabaseIndexWithPublicToken(string publicToken, string origin)
{
for (int i = 0; i < config.Websites.Count; i++)
{
if (config.Websites[i].publicToken == publicToken && config.Websites[i].url == origin)
{
return i;
}
}
return -1;
}
public int GetDatabaseIndexWithPublicToken(string publicToken)
{
for (int i = 0; i < config.Websites.Count; i++)
{
if (config.Websites[i].publicToken == publicToken)
{
return i;
}
}
return -1;
}
public int GetDatabaseIndexWithPrivateToken(string privateToken)
{
for (int i = 0; i < config.Websites.Count; i++)
{
if (config.Websites[i].HasPrivateToken(privateToken))
{
return i;
}
}
return -1;
}
public void AddAnalyticsToWebsite(string origin, AnalyticsData data)
{
int i = GetDatabaseIndexWithPublicToken(data.token, origin);
if (i == -1) throw new Exception("Website not registered");
config.Websites[i].siteClicks++;
databases[i].AddAnalyticData(data);
SaveConfig();
return;
}
public void AddAnalyticsToWebsite(AnalyticsData data)
{
int i = GetDatabaseIndexWithPublicToken(data.token);
if (i == -1) throw new Exception("Website not registered");
databases[i].AddAnalyticData(data);
return;
}
public bool Contains(AnalyticsData d)
{
throw new Exception("This method is deprecated");
/*
return false;
int i = GetDatabaseIndexWithPublicToken(d.token);
if (i == -1) throw new Exception("Website not registered");
foreach(string s in Directory.EnumerateFiles(databases[i].analyticsDirectory))
{
if (d.Equals(AnalyticsData.Load(s))) return true;
}
return false;
*/
}
public string GetAllowedOrigin(string origin)
{
foreach(Website w in config.Websites)
{
if(w.url == origin) return w.url;
}
return "";
}
public string SetWebhook(string url, string webhookUrl)
{
for(int i = 0; i < config.Websites.Count; i++)
{
if(config.Websites[i].url == url)
{
config.Websites[i].discordWebhookUrl = webhookUrl;
SaveConfig();
return "Set webhook for " + url;
}
}
return "url does not exist";
}
public string CreateWebsite(string host) // Host e. g. https://computerelite.github.io
{
Website website = new Website();
website.url = host;
website.publicToken = CreateRandomToken();
website.privateTokens.Add(new Token(CreateRandomToken(), DateTime.MaxValue));
website.folder = StringFormatter.FileNameSafe(host).Replace("https", "").Replace("http", "") + Path.DirectorySeparatorChar;
if(config.useMongoDB)
{
if (mongoClient.ListDatabaseNames().ToList().FirstOrDefault(x => x == website.url) != null) return "Website already exists";
} else
{
if (Directory.Exists(analyticsDir + website.folder)) return "Website already exists";
}
AnalyticsDatabase database = new AnalyticsDatabase(website.url, this, analyticsDir + website.folder);
databases.Add(database);
config.Websites.Add(website);
SaveConfig();
return "Created " + website.url;
}
public string DeleteWebsite(string url)
{
for(int i = 0; i < config.Websites.Count; i++)
{
if(config.Websites[i].url == url)
{
if(Directory.Exists(analyticsDir + config.Websites[i].folder)) Directory.Delete(analyticsDir + config.Websites[i].folder, true);
if (config.useMongoDB)
{
Logger.Log("Dropping MongoDBCollection");
mongoClient.GetDatabase(config.mongoDBName).DropCollection(config.Websites[i].url);
}
config.Websites.RemoveAt(i);
SaveConfig();
return "Deleted " + url + " including all Analytics";
}
}
return "Website not registered";
}
public string RenewTokens(string url, string token)
{
for (int i = 0; i < config.Websites.Count; i++)
{
if (config.Websites[i].url == url)
{
if(token == config.Websites[i].publicToken) config.Websites[i].publicToken = CreateRandomToken();
if (token == "")
{
config.Websites[i].publicToken = CreateRandomToken();
for (int ii = 0; ii < config.Websites[i].privateTokens.Count; ii++)
{
config.Websites[i].privateTokens[ii].value = CreateRandomToken();
}
} else
{
for(int ii = 0; ii < config.Websites[i].privateTokens.Count; ii++)