-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Unit2.pas
833 lines (730 loc) · 24.6 KB
/
Unit2.pas
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
unit Unit2;
interface
uses
Winapi.Windows,
Winapi.Messages,
Winapi.shellapi,
PsAPI,
TlHelp32,
System.Types,
System.SysUtils,
System.Variants,
System.Math,
System.Classes,
System.JSON,
System.Generics.Collections,
System.NetEncoding,
System.DateUtils,
System.StrUtils,
System.IOUTils,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ExtCtrls,
idURI,
IdGlobalProtocols,
IdStack,
IdGlobal,
IdBaseComponent,
IdComponent,
IdTCPConnection,
IdTCPClient,
IdHTTP,
IdMessageClient,
IdMessage,
IdMessageBuilder,
IdAttachment,
IdMessageParts,
IdEMailAddress,
IdAttachmentFile,
IdSMTPBase,
IdSMTP,
IdAttachmentMemory,
System.Net.URLClient,
System.Net.HttpClientComponent,
System.Net.HttpClient,
Vcl.WinXPickers,
Vcl.ComCtrls,
Vcl.Imaging.pngimage,
Unit1;
type
TMainForm = class(TForm)
mmInfo: TMemo;
btStart: TButton;
btStop: TButton;
btSwagger: TButton;
tmrStart: TTimer;
tmrInit: TTimer;
btRedoc: TButton;
btEMail: TButton;
procedure btStartClick(ASender: TObject);
procedure btStopClick(ASender: TObject);
procedure FormCreate(ASender: TObject);
function GetAppName: String;
function GetAppRelease: TDateTime;
function GetAppReleaseUTC: TDateTime;
function GetAppVersion: String;
procedure GetAppParameters(List: TStringList);
function GetAppFileName: String;
function GetAppFileSize: Int64;
function GetAppTimeZone: String;
function GetAppTimeZoneOffset: Integer;
procedure GetIPAddresses(List: TStringList);
function GetMemoryUsage: NativeUInt;
procedure btSwaggerClick(Sender: TObject);
procedure tmrStartTimer(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure tmrInitTimer(Sender: TObject);
procedure btRedocClick(Sender: TObject);
procedure LogEvent(Details: String);
procedure LogException(Source, EClass, EMessage, Data: String);
procedure SendActivityLog(Subject: String);
procedure btEMailClick(Sender: TObject);
public
AppName: String;
AppVersion: String;
AppRelease: TDateTime;
AppReleaseUTC: TDateTime;
AppParameters: TStringList;
AppFileSize: Int64;
AppFileName: String;
AppTimeZone: String;
AppTimeZoneOffset: Integer;
IPAddresses: TStringList;
AppConfigFile: String;
AppConfiguration: TJSONObject;
ChatModels: TStringList;
AppCacheFolder: String;
AppIconsFolder: String;
AppIcons: TJSONArray;
AppIconSets: String;
AppAudioClipsFolder: String;
AppAudioClips: TJSONArray;
DatabaseName: String;
DatabaseAlias: String;
DatabaseEngine: String;
DatabaseUsername: String;
DatabasePassword: String;
DatabaseConfig: String;
LastException: TDateTime;
AppStartup: TDateTime;
MailServerAvailable: Boolean;
MailServerHost: String;
MailServerPort: Integer;
MailServerUser: String;
MailServerPass: String;
MailServerFrom: String;
MailServerName: String;
strict private
procedure UpdateGUI;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
{ TMainForm }
// Attribution: https://stackoverflow.com/questions/24929026/issues-with-filesize-function
{$WARN SYMBOL_PLATFORM OFF}
function GetSizeOfFile(const Filename: string): Int64;
type
TSizeType = (stDWORD, stInt64);
var
sizerec: packed record
case TSizeType of
stDWORD: (SizeLow: LongWord; SizeHigh: LongWord);
stInt64: (Size: Int64);
end;
sr : TSearchRec;
begin
if FindFirst(fileName, faAnyFile, sr ) <> 0 then
begin
Result := -1;
Exit;
end;
try
sizerec.SizeLow := sr.FindData.nFileSizeLow;
sizerec.SizeHigh := sr.FindData.nFileSizeHigh;
Result := sizerec.Size;
finally
FindClose(sr) ;
end;
end;
{$WARN SYMBOL_PLATFORM ON}
procedure TMainForm.btStartClick(ASender: TObject);
begin
ServerContainer.SparkleHttpSysDispatcher.Start;
UpdateGUI;
end;
procedure TMainForm.btStopClick(ASender: TObject);
begin
ServerContainer.SparkleHttpSysDispatcher.Stop;
UpdateGUI;
end;
procedure TMainForm.btSwaggerClick(Sender: TObject);
var
url: String;
const
cHttp = '://+';
cHttpLocalhost = '://localhost';
begin
url := StringReplace(
ServerContainer.XDataServer.BaseUrl,
cHttp, cHttpLocalhost, [rfIgnoreCase])+'/swaggerui';
ShellExecute(0, 'open', PChar(url), nil, nil, SW_SHOWNORMAL);
end;
procedure TMainForm.btEMailClick(Sender: TObject);
begin
SendActivityLog('Activity Log');
end;
procedure TMainForm.btRedocClick(Sender: TObject);
var
url: String;
const
cHttp = '://+';
cHttpLocalhost = '://localhost';
begin
url := StringReplace(
ServerContainer.XDataServer.BaseUrl,
cHttp, cHttpLocalhost, [rfIgnoreCase])+'/redoc';
ShellExecute(0, 'open', PChar(url), nil, nil, SW_SHOWNORMAL);
end;
procedure TMainForm.FormCreate(ASender: TObject);
begin
LastException := Now - 1;
AppStartup := Now;
tmrInit.Enabled := True;
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
if MainForm.Tag = 0 then
begin
MainForm.Tag := 1;
MainForm.WindowState := wsMaximized;
MainForm.WindowState := wsMinimized;
end;
end;
function TMainForm.GetAppFileName: String;
begin
Result := ParamStr(0);
end;
function TMainForm.GetAppFileSize: Int64;
var
SearchRec: TSearchRec;
begin
Result := -1;
if FindFirst(ParamStr(0), faAnyFile, SearchRec) = 0
then Result := SearchRec.Size;
FindClose(SearchRec);
end;
function TMainForm.GetAppName: String;
begin
Result := MainForm.Caption;
end;
procedure TMainForm.GetAppParameters(List: TStringList);
var
i: Integer;
begin
i := 1;
while i <= ParamCount do
begin
List.Add('"'+ParamStr(i)+'"');
i := i + 1;
end;
end;
function TMainForm.GetAppRelease: TDateTime;
begin
Result := System.IOUtils.TFile.GetLastWriteTime(ParamStr(0));
end;
function TMainForm.GetAppReleaseUTC: TDateTime;
begin
Result := System.IOUtils.TFile.GetLastWriteTimeUTC(ParamStr(0));
end;
function TMainForm.GetAppTimeZone: String;
var
ZoneInfo: TTimeZoneInformation;
begin
GetTimeZoneInformation(ZoneInfo);
Result := ZoneInfo.StandardName;
end;
function TMainForm.GetAppTimeZoneOffset: Integer;
var
ZoneInfo: TTimeZoneInformation;
begin
GetTimeZoneInformation(ZoneInfo);
Result := ZoneInfo.Bias;
end;
// https://stackoverflow.com/questions/1717844/how-to-determine-delphi-application-version
function TMainForm.GetAppVersion: String;
const
c_StringInfo = 'StringFileInfo\040904E4\FileVersion';
var
n, Len : cardinal;
Buf, Value : PChar;
exeName:String;
begin
exeName := ParamStr(0);
Result := '';
n := GetFileVersionInfoSize(PChar(exeName),n);
if n > 0 then begin
Buf := AllocMem(n);
try
GetFileVersionInfo(PChar(exeName),0,n,Buf);
if VerQueryValue(Buf,PChar(c_StringInfo),Pointer(Value),Len) then begin
Result := Trim(Value);
end;
finally
FreeMem(Buf,n);
end;
end;
end;
// https://stackoverflow.com/questions/576538/delphi-how-to-get-all-local-ips
procedure TMainForm.GetIPAddresses(List: TStringList);
var
i: Integer;
IPList: TIdStackLocalAddressList;
IPAddr: TIdStackLocalAddress;
begin
TIdStack.IncUsage;
List.Clear;
IPList := TIdStackLocalAddressList.Create;
try
GStack.GetLocalAddressList(IPList);
for i := 0 to IPList.Count-1 do
begin
IPAddr := IPList[I];
case IPAddr.IPVersion of
Id_IPv4: begin
List.Add('IPV4: '+IPAddr.IPAddress);
end;
Id_IPv6: begin
List.Add('IPV6: '+IPAddr.IPAddress);
end;
end;
end;
finally
IPList.Free;
TIdStack.DecUsage;
end;
List.Sort;
i := 0;
while i < List.Count do
begin
List[i] := '"'+List[i]+'"';
i := i +1;
end;
end;
// https://stackoverflow.com/questions/437683/how-to-get-the-memory-used-by-a-delphi-program
function TMainForm.GetMemoryUsage: NativeUInt;
var
MemCounters: TProcessMemoryCounters;
begin
Result := 0;
MemCounters.cb := SizeOf(MemCounters);
if GetProcessMemoryInfo(GetCurrentProcess, @MemCounters, SizeOf(MemCounters))
then Result := MemCounters.WorkingSetSize
else LogEvent('ERROR: WorkingSetSize not available');
end;
procedure TMainForm.LogEvent(Details: String);
begin
try
mmInfo.Lines.Add(FormatDateTime('yyyy-mm-dd HH:nn:ss.zzz', Now)+' '+Details);
SendMessage(mmInfo.Handle, EM_LINESCROLL, 0, mmInfo.Lines.Count);
except on E: Exception do
begin
end;
end;
end;
procedure TMainForm.LogException(Source, EClass, EMessage, Data: String);
begin
LogEvent('');
LogEvent('[ EXCEPTION ] '+Source);
LogEvent('[ '+EClass+' ] '+EMessage);
LogEvent('[ Data ] '+Data);
if (MinutesBetween(now, LastException) > 15) then
begin
LastException := Now;
SendActivityLog('Exception Detected');
end;
end;
procedure TMainForm.SendActivityLog(Subject: String);
var
SMTP1: TIdSMTP;
Msg1: TIdMessage;
Addr1: TIdEmailAddressItem;
Html1: TIdMessageBuilderHtml;
SMTPResult: WideString;
begin
if not(MailServerAvailable) then
begin
LogEvent('WARNING: '+Subject+' e-mail not sent (Mail services not configured)');
end
else
begin
// Send warning email
Msg1 := nil;
Addr1 := nil;
SMTP1 := TIdSMTP.Create(nil);
SMTP1.Host := MainForm.MailServerHost;
SMTP1.Port := MainForm.MailServerPort;
SMTP1.Username := MainForm.MailServerUser;
SMTP1.Password := MainForm.MailServerPass;
try
Html1 := TIdMessageBuilderHtml.Create;
try
Html1.Html.Add('<html>');
Html1.Html.Add('<head>');
Html1.Html.Add('</head>');
Html1.Html.Add('<body><pre>');
Html1.Html.Add(mmInfo.Lines.Text);
Html1.Html.Add('</pre></body>');
Html1.Html.Add('</html>');
Html1.HtmlCharSet := 'utf-8';
Msg1 := Html1.NewMessage(nil);
// Startup should be < 10s but otherwise send the running time
if MillisecondsBetween(Now, AppStartup) < 30000
then Msg1.Subject := '['+GetEnvironmentVariable('COMPUTERNAME')+'] '+Subject+': '+MainForm.Caption+' ('+IntToStr(MillisecondsBetween(Now, AppStartup))+'ms)'
else Msg1.Subject := '['+GetEnvironmentVariable('COMPUTERNAME')+'] '+Subject+': '+MainForm.Caption+' ('+FormatDateTime('hh:nn:ss', Now - AppStartup)+'}';
Msg1.From.Text := MainForm.MailServerFrom;
Msg1.From.Name := MainForm.MailServerName;
Addr1 := Msg1.Recipients.Add;
Addr1.Address := MainForm.MailserverFrom;
SMTP1.Connect;
try
try
SMTP1.Send(Msg1);
except on E: Exception do
begin
SMTPResult := SMTPResult+'[ '+E.ClassName+' ] '+E.Message+Chr(10);
end;
end;
finally
SMTP1.Disconnect();
end;
finally
Addr1.Free;
Msg1.Free;
Html1.Free;
end;
except on E: Exception do
begin
SMTPResult := SMTPResult+'[ '+E.ClassName+' ] '+E.Message+Chr(10);
end;
end;
SMTP1.Free;
if SMTPResult = ''
then LogEvent('NOTICE: '+Subject+' e-mail sent to '+MailServerName+' <'+MailServerFrom+'>')
else
begin
LogEvent('WARNING: '+Subject+' e-mail to '+MailServerName+' <'+MailServerFrom+'> FAILED.');
LogEvent('WARNING: SMTP Error: '+SMTPResult);
end;
end;
end;
procedure TMainForm.tmrInitTimer(Sender: TObject);
var
i: Integer;
ConfigFile: TStringList;
begin
tmrInit.Enabled := False;
// Let's use these internally for consistency
FormatSettings.DateSeparator := '-';
FormatSettings.ShortDateFormat := 'yyyy-mm-dd';
FormatSettings.TimeSeparator := ':';
FormatSettings.ShortTimeFormat := 'hh:nn:ss';
// Get System Values
AppName := GetAppName;
AppVersion := GetAppVersion;
AppRelease := GetAppRelease;
AppReleaseUTC := GetAppReleaseUTC;
AppFileName := GetAppFileName;
AppFileSize := GetAppFileSize;
AppTimeZone := GetAppTimeZone;
AppTimeZoneOffset := GetAppTimeZoneOffset;
Caption := AppName+' Ver '+AppVersion+' Rel '+FormatDateTime('yyyy-mmm-dd',AppRelease);
// List of App Parameters
AppParameters := TStringList.Create;
AppParameters.QuoteChar := ' ';
GetAppParameters(AppParameters);
// List of IP Addresses
IPAddresses := TStringList.Create;
IPAddresses.QuoteChar := ' ';
GetIPAddresses(IPAddresses);
// Load JSON Configuration
LogEvent('Loading Configuration.');
AppConfigFile := StringReplace(ExtractFileName(ParamStr(0)),'exe','json',[]);
i := 0;
while i < AppParameters.Count do
begin
if Pos('"CONFIG=',UpperCase(AppParameters[i])) = 1
then AppConfigFile := Copy(AppParameters[i],9,length(AppParameters[i])-9);
i := i + 1;
end;
ConfigFile := TStringList.Create;
if FileExists(AppConfigFile) then
begin
try
ConfigFile.LoadFromFile(AppConfigFile);
LogEvent('- Configuration File Loaded: '+AppConfigFile);
AppConfiguration := TJSONObject.ParseJSONValue(ConfigFile.Text) as TJSONObject;
except on E: Exception do
begin
LogException('Configuration File Error', E.ClassName, E.Message, AppConfigFile);
end;
end;
end
else // File doesn't exist
begin
LogEvent('- Configuration File Not Found: '+AppConfigFile);
end;
ConfigFile.Free;
Application.ProcessMessages;
if Appconfiguration = nil then
begin
// Create an empty AppConfiguration
LogEvent('- Using Default Configuration');
AppConfiguration := TJSONObject.Create;
AppConfiguration.AddPair('BaseURL','http://+:65432/hexagongs');
end;
// Get Mail Configuration
MailServerAvailable := False;
if AppConfiguration.GetValue('Mail Services') <> nil then
begin
btEMail.Enabled := True;
MailServerAvailable := True;
MailServerHost := ((AppConfiguration.GetValue('Mail Services') as TJSONObject).GetValue('SMTP Host') as TJSONString).Value;
MailServerPort := ((AppConfiguration.GetValue('Mail Services') as TJSONObject).GetValue('SMTP Port') as TJSONNumber).AsInt;
MailServerUser := ((AppConfiguration.GetValue('Mail Services') as TJSONObject).GetValue('SMTP User') as TJSONString).Value;
MailServerPass := ((AppConfiguration.GetValue('Mail Services') as TJSONObject).GetValue('SMTP Pass') as TJSONString).Value;
MailServerFrom := ((AppConfiguration.GetValue('Mail Services') as TJSONObject).GetValue('SMTP From') as TJSONString).Value;
MailServerName := ((AppConfiguration.GetValue('Mail Services') as TJSONObject).GetValue('SMTP Name') as TJSONString).Value;
LogEvent('- SMTP Mail Server: '+MailServerHost+' / '+IntToStr(MailServerPort));
end
else
begin
LogEvent('- SMTP Mail Server: Unavailable');
end;
LogEvent('Done.');
LogEvent('');
Application.ProcessMessages;
ServerContainer.XDataServer.BaseURL := (AppConfiguration.getValue('BaseURL') as TJSONString).Value;
tmrStart.Enabled := True;
end;
procedure TMainForm.tmrStartTimer(Sender: TObject);
var
i: Integer;
ImageFile: TStringList;
// TableName: String;
CacheFolderDirs: String;
CacheFolderFiles: String;
CacheFolderSize: Double;
CacheFolderList: TStringDynArray;
IconFiles: TStringDynArray;
IconFile: TStringList;
IconJSON: TJSONObject;
IconSets: TJSONArray;
IconWidth: Integer;
IconHeight: Integer;
IconCount: Integer;
IconTotal: Integer;
AudioClips: TStringDynArray;
ClipName: String;
begin
tmrStart.Enabled := False;
// This is (potentially) used when populating the photo table
ImageFile := TStringList.Create;
// Cache Folder
if (AppConfiguration.GetValue('Cache Folder') <> nil)
then AppCacheFolder := (AppConfiguration.GetValue('Cache Folder') as TJSONString).Value
else AppCacheFolder := GetCurrentDir+'/cache';
if RightStr(AppCacheFolder,1) <> '/'
then AppCacheFolder := AppCacheFolder + '/';
if not(ForceDirectories(AppCacheFolder))
then LogEvent('ERROR Initializing Cache Folder: '+AppCacheFolder);
if not(ForceDirectories(AppCacheFolder+'images'))
then LogEvent('ERROR Initializing Cache Folder: '+AppCacheFolder+'images');
if not(ForceDirectories(AppCacheFolder+'images/ai'))
then LogEvent('ERROR Initializing Cache Folder: '+AppCacheFolder+'images/ai');
if not(ForceDirectories(AppCacheFolder+'images/people'))
then LogEvent('ERROR Initializing Cache Folder: '+AppCacheFolder+'images/people');
CacheFolderDirs := FloatToStrF(Length(TDirectory.GetDirectories(AppCacheFolder,'*',TsearchOption.soAllDirectories)),ffNumber,8,0);
CacheFolderList := TDirectory.GetFiles(AppCacheFolder,'*.*',TsearchOption.soAllDirectories);
CacheFolderFiles := FloatToStrF(Length(CacheFolderList),ffNumber,8,0);
CacheFolderSize := 0;
for i := 0 to Length(CacheFolderList)-1 do
CacheFolderSize := CacheFolderSize + (FileSizeByName(CacheFolderList[i]) / 1024 / 1024);
// Display System Values
LogEvent('App Name: '+AppName);
LogEvent('...Version: '+AppVersion);
LogEvent('...Release: '+FormatDateTime('yyyy-mmm-dd (ddd) hh:nn:ss', AppRelease));
LogEvent('...Release UTC: '+FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', AppReleaseUTC));
LogEvent('...Server Time: '+FormatDateTime('yyyy-mmm-dd (ddd) hh:nn:ss', Now));
LogEvent('...TimeZone: '+AppTimeZone);
LogEvent('...TimeZone Offset: '+IntToStr(AppTimeZoneOffset)+'m');
LogEvent('...Base URL: '+ServerContainer.XDataServer.BaseURL);
LogEvent('...File Name: '+AppFileName);
LogEvent('...File Size: '+Format('%.1n',[AppFileSize / 1024 / 1024])+' MB');
LogEvent('...Cache Folder: '+AppCacheFolder);
LogEvent('...Cache Statistics: '+CacheFolderDirs+' Folders, '+CacheFolderFiles+' Files, '+FloatToStrF(CacheFolderSize,ffNumber,8,1)+' MB');
LogEvent('...Memory Usage: '+Format('%.1n',[GetMemoryUsage / 1024 / 1024])+' MB');
LogEvent('...Parameters:');
i := 0;
while i < AppParameters.Count do
begin
LogEvent(' '+StringReplace(AppParameters[i],'"','',[rfReplaceAll]));
i := i + 1;
end;
LogEvent('...IP Addresses:');
i := 0;
while i < IPAddresses.Count do
begin
LogEvent(' '+StringReplace(IPAddresses[i],'"','',[rfReplaceAll]));
i := i + 1;
end;
// Are chat services avialable?
if (AppConfiguration.GetValue('Chat Interface') as TJSONArray) = nil
then LogEvent('...Chat: UNAVAILABLE')
else
begin
LogEvent('...Chat:');
i := 0;
while i < (AppConfiguration.GetValue('Chat Interface') as TJSONArray).Count do
begin;
LogEvent(' '+(((AppConfiguration.GetValue('Chat Interface') as TJSONArray).items[i] as TJSONObject).getValue('Name') as TJSONString).Value);
i := i + 1;
end;
end;
// Load up Icon Sets
if (AppConfiguration.GetValue('Icons') <> nil)
then AppIconsFolder := (AppConfiguration.GetValue('Icons') as TJSONString).Value
else AppIconsFolder := GetCurrentDir+'/icon-sets';
if RightStr(AppIconsFolder,1) <> '/'
then AppIconsFolder := AppIconsFolder + '/';
ForceDirectories(AppIconsFolder);
IconFiles := TDirectory.GetFiles(AppIconsFolder,'*.json',TsearchOption.soAllDirectories);
AppIcons := TJSONArray.Create;
IconSets := TJSONArray.Create;
IconTotal := 0;
if length(IconFiles) = 0 then
begin
LogEvent('...No Icon Sets Loaded: None Found.');
end
else
begin
LogEvent('...Loading '+IntToStr(Length(IconFiles))+' Icon Sets:');
IconFile := TStringList.Create;
for i := 0 to Length(IconFiles)-1 do
begin
// Load JSON File
IconFile.LoadFromFile(IconFiles[i], TEncoding.UTF8);
IconJSON := TJSONObject.ParseJSONValue(IconFile.Text) as TJSONObject;
AppIcons.Add(IconJSON);
// Get Icon Count information
IconCount := (IconJSON.GetValue('icons') as TJSONObject).Count;
IconTotal := IconTotal + IconCount;
// Log what we're doing
LogEvent(' ['+TPath.GetFileName(IconFiles[i])+'] '+
((IconJSON.GetValue('info') as TJSONObject).GetValue('name') as TJSONString).Value+' - '+
IntToStr(IconCount)+' Icons');
// Sort out the default width and height. This is either from the width and height properties
// found in the root of the JSON object, or in the info element, or perhaps not at all in the
// the case of the width property, in which case we'll assume it is the same as the height.
// We're doing this now as we're not passing back this information to the client, just the
// name, license, and icons, so the client will need this to properly generate the SVG data.
IconHeight := 0;
IconWidth := 0;
if IconJSON.GetValue('height') <> nil
then IconHeight := (IconJSON.GetValue('height') as TJSONNumber).AsInt
else if (IconJSON.GetValue('info') as TJSONObject).GetValue('height') <> nil
then IconHeight := ((IconJSON.GetValue('info') as TJSONObject).GetValue('height') as TJSONNumber).AsInt;
if IconJSON.GetValue('width') <> nil
then IconWidth := (IconJSON.GetValue('width') as TJSONNumber).AsInt
else if (IconJSON.GetValue('info') as TJSONObject).GetValue('width') <> nil
then IconWidth := ((IconJSON.GetValue('info') as TJSONObject).GetValue('width') as TJSONNumber).AsInt;
if IconWidth = 0 then IconWidth := IconHeight;
// Here we're building the JSON that we'll pass to the client telling them what icon sets are
// available, along with the other data they will need that is at the icon-set level
IconSets.add(TJSONObject.ParseJSONValue('{'+
'"name":"'+((IconJSON.GetValue('info') as TJSONObject).GetValue('name') as TJSONString).Value+'",'+
'"license":"'+(((IconJSON.GetValue('info') as TJSONObject).GetValue('license') as TJSONObject).GetValue('title') as TJSONString).Value+'",'+
'"width":'+IntToStr(IconWidth)+','+
'"height":'+IntToStr(IconHeight)+','+
'"count":'+IntToStr(IconCount)+','+
'"library":'+IntToStr(i)+
'}') as TJSONObject);
Application.ProcessMessages;
end;
IconFile.Free;
end;
LogEvent(' Icons Loaded: '+FloatToStrF(IconTotal,ffNumber,10,0));
// We don't need to do anything else with this, so we'll store it as a string and
// then return just that when asked for this ata.
AppIconSets := IconSets.ToString;
// Load up Audio clips
if (AppConfiguration.GetValue('Audio') <> nil)
then AppAudioClipsFolder := (AppConfiguration.GetValue('Audio') as TJSONString).Value
else AppAudioClipsFolder := GetCurrentDir+'/audio-clips';
if RightStr(AppAudioClipsFolder,1) <> '/'
then AppAudioClipsFolder := AppAudioClipsFolder + '/';
ForceDirectories(AppAudioClipsFolder);
AudioClips := TDirectory.GetFiles(AppAudioClipsFolder,'*.*',TsearchOption.soAllDirectories);
AppAudioClips := TJSONArray.Create;
if length(AudioClips) = 0 then
begin
LogEvent('...No Audio Clips Loaded: None Found.');
end
else
begin
LogEvent('...Found '+IntToStr(Length(AudioClips))+' Audio Clips');
for i := 0 to Length(AudioClips)-1 do
begin
ClipName := StringReplace(copy(AudioClips[i],length(AppAudioClipsFolder)+1,length(AudioClips[i])),'\','/',[rfReplaceAll]);
ClipName := StringReplace(ClipName,'_',' ',[rfReplaceAll]);
ClipName := StringReplace(ClipName,'-',' ',[rfReplaceAll]);
ClipName := StringReplace(ClipName,'.mp3','',[rfReplaceAll]);
ClipName := StringReplace(ClipName,'.wav','',[rfReplaceAll]);
ClipName := StringReplace(ClipName,'.ogg','',[rfReplaceAll]);
ClipName := StringReplace(ClipName,'.oga','',[rfReplaceAll]);
ClipName := StringReplace(ClipName,'.acc','',[rfReplaceAll]);
AppAudioClips.Add(TJSONObject.ParseJSONValue('{'+
'"Name":"'+ClipName+'",'+
'"Type":"'+Uppercase(StringReplace(TPath.GetExtension(AudioClips[i]),'.','',[rfReplaceAll]))+'",'+
'"FullName":"'+StringReplace(copy(AudioClips[i],length(AppAudioClipsFolder)+1,length(AudioClips[i])),'\','/',[rfReplaceAll])+'",'+
'"Size":'+IntToStr(GetSizeOfFile(AudioClips[i]))+
'}') as TJSONObject);
end;
end;
LogEvent('...Memory Usage: '+Format('%.1n',[GetMemoryUsage / 1024 / 1024])+' MB');
LogEvent('Done.');
LogEvent('');
// Start Server
ServerContainer.SparkleHttpSysDispatcher.Active := True;
UpdateGUI;
SendActivityLog('Startup Confirmation');
// Cleanup
ImageFile.Free;
end;
procedure TMainForm.UpdateGUI;
const
cHttp = '://+';
cHttpLocalhost = '://localhost';
begin
btStart.Enabled := not ServerContainer.SparkleHttpSysDispatcher.Active;
btStop.Enabled := not btStart.Enabled;
if ServerContainer.SparkleHttpSysDispatcher.Active then
begin
LogEvent('XData Server started at '+StringReplace( ServerContainer.XDataServer.BaseUrl, cHttp, cHttpLocalhost, [rfIgnoreCase]));
LogEvent('SwaggerUI started at '+StringReplace( ServerContainer.XDataServer.BaseUrl, cHttp, cHttpLocalhost, [rfIgnoreCase])+'/swaggerui');
LogEvent('Redoc started at '+StringReplace( ServerContainer.XDataServer.BaseUrl, cHttp, cHttpLocalhost, [rfIgnoreCase])+'/redoc');
btSwagger.Enabled := True;
btRedoc.Enabled := True;
end
else
begin
LogEvent('XData Server stopped');
btSwagger.Enabled := False;
btRedoc.Enabled := False;
end;
end;
end.