-
Notifications
You must be signed in to change notification settings - Fork 7
/
ProxyServiceModuleUnit.pas
1123 lines (942 loc) · 28.9 KB
/
ProxyServiceModuleUnit.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
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
unit ProxyServiceModuleUnit;
interface
{$SCOPEDENUMS ON}
uses
System.SysUtils,
System.Classes,
System.IOUtils,
System.JSON,
System.DateUtils,
System.Generics.Collections,
System.Generics.Defaults,
System.SyncObjs,
System.Diagnostics,
System.StrUtils,
FMX.Types,
Winapi.ActiveX,
REST.Client,
REST.Types,
REST.Json,
REST.Json.Types,
REST.JsonReflect,
Xml.XmlDoc,
Xml.XmlIntf,
IdStack,
HDHR,
Ceton,
LogUtils,
FileUtils,
EmailUtils;
const
cServiceConfigVersion = 2;
cLogSizeRollover = 2000000;
cMaxLogFiles = 5;
cErrorEmailFrequencySec = 60;
type
TServiceConfigSection = (Channels, Server, Other);
TServiceConfigSections = set of TServiceConfigSection;
TErrorEmailSettings = class(TPersistent)
private
fFrequencySec: Integer;
fSubject: String;
fRecipients: String;
fSender: String;
public
constructor Create;
procedure AssignTo(Dest: TPersistent); override;
procedure Assign(Source: TPersistent); override;
published
property FrequencySec: Integer read fFrequencySec write fFrequencySec;
property Sender: String read fSender write fSender;
property Recipients: String read fRecipients write fRecipients;
property Subject: String read fSubject write fSubject;
end;
TServiceConfig = class(TPersistent)
private
fDeviceID: UInt32;
fCeton: TCetonConfig;
fListenIP: String;
fHTTPPort: Integer;
fDeviceUUID: String;
fExternalAddress: String;
fExternalHTTPPort: Integer;
fVersion: Integer;
fEmailServer: TEmailServerSettings;
fErrorEmail: TErrorEmailSettings;
procedure CreateDeviceID;
procedure CreateDeviceUUID;
public
constructor Create;
destructor Destroy; override;
procedure AssignTo(Dest: TPersistent); override;
function ToJSON: String;
class function FromJSON(const aJSON: String): TServiceConfig; static;
property EmailServer: TEmailServerSettings read fEmailServer;
property ErrorEmail: TErrorEmailSettings read fErrorEmail;
property Ceton: TCetonConfig read fCeton;
property Version: Integer read fVersion write fVersion;
property DeviceID: UInt32 read fDeviceID write fDeviceID;
property DeviceUUID: String read fDeviceUUID write fDeviceUUID;
property ListenIP: String read fListenIP write fListenIP;
property HTTPPort: Integer read fHTTPPort write fHTTPPort;
property ExternalAddress: String read fExternalAddress write fExternalAddress;
property ExternalHTTPPort: Integer read fExternalHTTPPort write fExternalHTTPPort;
end;
IServiceConfigEvents = interface
['{E51631F5-FC88-4FEC-BCF6-9A0F5616CE79}']
procedure Changed(const aSender: TObject; const aSections: TServiceConfigSections);
procedure DiscoveredCetonDevicesChanged;
procedure Log(const aLogName: String; const aMessage: String);
procedure LogError(const aLogName: String; const aMessage: String);
end;
IServiceConfigManager = interface
['{4393C786-9DE0-42DE-BE36-21EA00CFBE70}']
procedure LockConfig(out aConfig: TServiceConfig);
procedure UnlockConfig(var aConfig: TServiceConfig);
procedure Log(const aLogName: String; const aMessage: String);
procedure LogError(const aLogName: String; const aMessage: String);
procedure Changed(const aSender: TObject; const aSections: TServiceConfigSections);
procedure DiscoveredCetonDevicesChanged;
procedure AddListener(const aListener: IServiceConfigEvents);
procedure RemoveListener(const aListener: IServiceConfigEvents);
end;
TServiceConfigManager = class(TInterfacedObject, IServiceConfigManager)
private
fConfig: TServiceConfig;
fEventListeners: TList<IServiceConfigEvents>;
procedure Lock;
procedure Unlock;
protected
// IServiceConfigManager
procedure LockConfig(out aConfig: TServiceConfig);
procedure UnlockConfig(var aConfig: TServiceConfig);
procedure Log(const aLogName: String; const aMessage: String);
procedure LogError(const aLogName: String; const aMessage: String);
procedure Changed(const aSender: TObject; const aSections: TServiceConfigSections);
procedure DiscoveredCetonDevicesChanged;
procedure AddListener(const aListener: IServiceConfigEvents);
procedure RemoveListener(const aListener: IServiceConfigEvents);
public
constructor Create;
destructor Destroy; override;
end;
TProxyServiceModule = class;
TServiceThread = class(TThread, IInterface, IServiceConfigEvents)
private
fServiceModule: TProxyServiceModule;
fChangeEvent: TEvent;
fConfigChanged: Boolean;
fCetonDeviceDiscovered: Boolean;
fLogCaches: TArray<TStringBuilder>;
fErrorEmailCache: TStringBuilder;
fEmailServerSettings: TEmailServerSettings;
fErrorEmailSettings: TErrorEmailSettings;
fErrorEmailStartDateTime: TDateTime;
procedure GetEmailSettings;
procedure SaveLogs;
procedure SendErrorEmail;
procedure QueryDiscoveredCetonDevices;
protected
// IInterface
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
// IServiceConfigEvents
procedure Changed(const aSender: TObject; const aSections: TServiceConfigSections);
procedure Log(const aLogName: String; const aMessage: String);
procedure LogError(const aLogName: String; const aMessage: String);
procedure DiscoveredCetonDevicesChanged;
public
constructor Create(const aServiceModule: TProxyServiceModule);
destructor Destroy; override;
procedure CetonDeviceDiscovered;
procedure Execute; override;
end;
TProxyServiceModule = class(TDataModule, IServiceConfigEvents, ILogger)
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
fConfigManager: IServiceConfigManager;
fClient: TCetonClient;
fThread: TServiceThread;
fDiscoveredCetonDeviceList: TDiscoveredCetonDeviceList;
protected
procedure LoadConfig;
procedure SaveConfig;
procedure MoveLog(const aFilename: String);
protected
// IServiceConfigEvents
procedure Changed(const aSender: TObject; const aSections: TServiceConfigSections);
procedure Log(const aLogName: String; const aMessage: String);
procedure LogError(const aLogName: String; const aMessage: String);
procedure DiscoveredCetonDevicesChanged;
// ILogger
procedure ILogger.Log = HandleLoggerLog;
procedure ILogger.LogError = HandleLoggerLogError;
procedure HandleLoggerLog(const aLogName: String; const aMessage: String);
procedure HandleLoggerLogError(const aLogName: String; const aMessage: String);
public
{ Public declarations }
property ConfigManager: IServiceConfigManager read fConfigManager;
property Client: TCetonClient read fClient;
property DiscoveredCetonDeviceList: TDiscoveredCetonDeviceList read fDiscoveredCetonDeviceList;
procedure CetonDeviceDiscovered(const aIP, aDescriptionXMLURL: String);
function GetConfigPath: String;
end;
var
ProxyServiceModule: TProxyServiceModule;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
{ TServiceConfig }
procedure TServiceConfig.CreateDeviceID;
begin
fDeviceID := THDHRUtils.CreateDeviceID;
end;
function TServiceConfig.ToJSON: String;
var
m: TJSONMarshal;
lJSONValue: TJSONValue;
begin
m := TJSONMarshal.Create(TJSONConverter.Create);
try
m.RegisterConverter(TTunerConfigList, 'fList',
function(Data: TObject; Field: String): TListOfObjects
var
i: Integer;
begin
SetLength(Result, TTunerConfigList(Data).Count);
for i := 0 to High(Result) do
Result[i] := TTunerConfigList(Data)[i];
end);
m.RegisterConverter(TChannelMap, 'fList',
function(Data: TObject; Field: String): TListOfObjects
var
i: Integer;
begin
SetLength(Result, TChannelMap(Data).Count);
for i := 0 to High(Result) do
Result[i] := TChannelMap(Data)[i];
end);
lJSONValue := m.Marshal(Self);
try
Result := lJSONValue.ToString;
finally
lJSONValue.Free;
end;
finally
m.Free;
end;
end;
class function TServiceConfig.FromJSON(const aJSON: String): TServiceConfig;
var
m: TJSONUnMarshal;
lR: TReverterEvent;
lJSONObject: TJSONObject;
begin
Result := TServiceConfig.Create;
try
Result.Version := 0;
m := TJSONUnMarshal.Create;
try
lR := TReverterEvent.Create(TTunerConfig, 'list');
lR.ObjectsReverter :=
procedure(Data: TObject; Field: string; Args: TListOfObjects)
var
i: Integer;
begin
TTunerConfigList(Data).Count := Length(Args);
for i := 0 to High(Args) do
begin
TTunerConfigList(Data)[i].Assign(TTunerConfig(Args[i]));
Args[i].Free;
end;
end;
m.RegisterReverter(TTunerConfigList, 'list', lR);
lR := TReverterEvent.Create(TChannelMapItem, 'list');
lR.ObjectsReverter :=
procedure(Data: TObject; Field: string; Args: TListOfObjects)
var
i: Integer;
begin
for i := 0 to High(Args) do
TChannelMap(Data).Add(TChannelMapItem(Args[i]));
end;
m.RegisterReverter(TChannelMap, 'list', lR);
lJSONObject := TJSONObject(TJSONObject.ParseJSONValue(aJSON));
try
Result := m.CreateObject(TServiceConfig, lJSONObject, Result) as TServiceConfig;
finally
lJSONObject.Free;
end;
finally
m.Free;
end;
if Result.DeviceID = 0 then
Result.CreateDeviceID;
except
FreeAndNil(Result);
Result := TServiceConfig.Create;
end;
end;
constructor TServiceConfig.Create;
begin
fCeton := TCetonConfig.Create;
fEmailServer := TEmailServerSettings.Create;
fErrorEmail := TErrorEmailSettings.Create;
fHTTPPort := HDHR_HTTP_PORT;
fExternalHTTPPort := fHTTPPort;
fVersion := cServiceConfigVersion;
CreateDeviceID;
CreateDeviceUUID;
end;
destructor TServiceConfig.Destroy;
begin
fErrorEmail.Free;
fEmailServer.Free;
fCeton.Free;
inherited;
end;
procedure TServiceConfig.AssignTo(Dest: TPersistent);
var
lDest: TServiceConfig;
begin
if Dest is TServiceConfig then
begin
lDest := TServiceConfig(Dest);
lDest.fVersion := fVersion;
lDest.fEmailServer.Assign(fEmailServer);
lDest.fErrorEmail.Assign(fErrorEmail);
lDest.fCeton.Assign(fCeton);
lDest.fDeviceID := fDeviceID;
lDest.fDeviceUUID := fDeviceUUID;
lDest.fHTTPPort := fHTTPPort;
lDest.fListenIP := fListenIP;
lDest.fExternalAddress := fExternalAddress;
lDest.fExternalHTTPPort := fExternalHTTPPort;
end
else
inherited;
end;
procedure TServiceConfig.CreateDeviceUUID;
begin
fDeviceUUID := TGUID.NewGuid.ToString.Substring(1, 36);
end;
{ TServiceConfigManager }
constructor TServiceConfigManager.Create;
begin
fConfig := TServiceConfig.Create;
fEventListeners := TList<IServiceConfigEvents>.Create;
end;
procedure TServiceConfigManager.Unlock;
begin
System.TMonitor.Exit(Self);
end;
procedure TServiceConfigManager.LockConfig(out aConfig: TServiceConfig);
begin
Lock;
aConfig := fConfig;
end;
procedure TServiceConfigManager.Lock;
begin
System.TMonitor.Enter(Self);
end;
procedure TServiceConfigManager.Changed(const aSender: TObject;
const aSections: TServiceConfigSections);
var
i: Integer;
begin
Lock;
try
for i := 0 to fEventListeners.Count-1 do
begin
fEventListeners[i].Changed(aSender, aSections);
end;
finally
Unlock;
end;
end;
procedure TServiceConfigManager.AddListener(
const aListener: IServiceConfigEvents);
begin
fEventListeners.Add(aListener as IServiceConfigEvents);
end;
procedure TServiceConfigManager.RemoveListener(
const aListener: IServiceConfigEvents);
begin
fEventListeners.Remove(aListener as IServiceConfigEvents);
end;
destructor TServiceConfigManager.Destroy;
begin
fConfig.Free;
fEventListeners.Free;
inherited;
end;
procedure TServiceConfigManager.UnlockConfig(var aConfig: TServiceConfig);
begin
aConfig := nil;
Unlock;
end;
procedure TServiceConfigManager.Log(const aLogName: String; const aMessage: String);
var
i: Integer;
begin
Lock;
try
for i := 0 to fEventListeners.Count-1 do
begin
fEventListeners[i].Log(aLogName, aMessage);
end;
finally
Unlock;
end;
end;
procedure TServiceConfigManager.DiscoveredCetonDevicesChanged;
var
i: Integer;
begin
Lock;
try
for i := 0 to fEventListeners.Count-1 do
begin
fEventListeners[i].DiscoveredCetonDevicesChanged;
end;
finally
Unlock;
end;
end;
procedure TServiceConfigManager.LogError(const aLogName, aMessage: String);
var
i: Integer;
begin
Lock;
try
for i := 0 to fEventListeners.Count-1 do
begin
fEventListeners[i].LogError(aLogName, aMessage);
end;
finally
Unlock;
end;
end;
{ TProxyServiceModule }
procedure TProxyServiceModule.DataModuleCreate(Sender: TObject);
var
i: Integer;
begin
fDiscoveredCetonDeviceList := TDiscoveredCetonDeviceList.Create;
fConfigManager := TServiceConfigManager.Create;
for i := 0 to High(cLogNames) do
begin
try
MoveLog(GetConfigPath+'cetonproxy'+cLogNames[i]+'.log');
except
//
end;
end;
fThread := TServiceThread.Create(Self);
TLogger.SetLogger(Self);
TLogger.Log(cLogDefault, 'Starting cetonproxy');
fClient := TCetonClient.Create;
LoadConfig;
fConfigManager.AddListener(Self);
fThread.Start;
end;
procedure TProxyServiceModule.DataModuleDestroy(Sender: TObject);
begin
FreeAndNil(fThread);
fConfigManager.RemoveListener(Self);
fClient.Free;
fDiscoveredCetonDeviceList.Free;
SaveConfig;
TLogger.Log(cLogDefault, 'Closing cetonproxy');
TLogger.SetLogger(nil);
end;
function TProxyServiceModule.GetConfigPath: String;
begin
if FindCmdLineSwitch('config', Result) then
Result := IncludeTrailingPathDelimiter(Result)
else
Result := TPath.GetHomePath + TPath.DirectorySeparatorChar + 'cetonproxy' + TPath.DirectorySeparatorChar;
end;
procedure TProxyServiceModule.Changed(const aSender: TObject; const aSections: TServiceConfigSections);
begin
// If anything changes the config (besides the TCetonClient itself), then update the
// client with the latest config
if aSender <> Client then
begin
TThread.ForceQueue(nil,
procedure()
var
lCetonConfig: TCetonConfig;
lConfig: TServiceConfig;
lExcludeCetonSections: TCetonConfigSections;
begin
lCetonConfig := TCetonConfig.Create;
try
// Don't copy channels from config manager if we don't have to
lExcludeCetonSections := [];
if not (TServiceConfigSection.Channels in aSections) then
lExcludeCetonSections := lExcludeCetonSections + [TCetonConfigSection.Channels];
ConfigManager.LockConfig(lConfig);
try
lCetonConfig.Assign(lConfig.Ceton, lExcludeCetonSections);
finally
ConfigManager.UnlockConfig(lConfig);
end;
Client.AssignConfig(lCetonConfig, lExcludeCetonSections);
finally
lCetonConfig.Free;
end;
end);
end;
end;
procedure TProxyServiceModule.LoadConfig;
var
lJSON: String;
lConfig, lTempConfig: TServiceConfig;
begin
try
lJSON := TFile.ReadAllText(GetConfigPath + 'config.js');
except
// Ignore
end;
lTempConfig := TServiceConfig.FromJSON(lJSON);
try
if lTempConfig.Version < 2 then
begin
// In older versions of the app, if ListenIP is blank, then it meant
// use the first enumerated local IP. Newer versions use different strategies
// for listening on ports and for reporting the HDHomeRun URL for clients to connect
// to, which could cause DVR software to see us as a different HDHomeRun device.
// So for backward compatibility, assign a listen IP on older configs.
// NOTE: Purposefully using Indy to match old behavior.
TIdStack.IncUsage;
try
lTempConfig.ListenIP := GStack.LocalAddress;
finally
TIdStack.DecUsage;
end;
lTempConfig.Version := 2;
end;
lTempConfig.Version := cServiceConfigVersion;
fConfigManager.LockConfig(lConfig);
try
lConfig.Assign(lTempConfig);
finally
fConfigManager.UnlockConfig(lConfig);
end;
fClient.AssignConfig(lTempConfig.Ceton, []);
finally
lTempConfig.Free;
end;
end;
procedure TProxyServiceModule.SaveConfig;
var
lConfig: TServiceConfig;
begin
try
ConfigManager.LockConfig(lConfig);
try
ForceDirectories(GetConfigPath);
TFile.WriteAllText(GetConfigPath + 'config.js', lConfig.ToJSON);
finally
ConfigManager.UnlockConfig(lConfig);
end;
except
on e: Exception do
TLogger.LogFmt(cLogDefault, 'Unable to save config: %s', [e.Message]);
end;
end;
procedure TProxyServiceModule.Log(const aLogName: String; const aMessage: String);
begin
// Nothing
end;
procedure TProxyServiceModule.HandleLoggerLog(const aLogName: String; const aMessage: String);
begin
// Pass to config manager to allow broadcasting it to multiple recipients
ConfigManager.Log(aLogName, aMessage);
end;
procedure TProxyServiceModule.MoveLog(const aFilename: String);
var
lPath, lFilename: String;
lBaseFilename, lNewFilename: String;
i, lIndex: Integer;
lFiles: TArray<String>;
begin
lPath := IncludeTrailingPathDelimiter(ExtractFilePath(aFilename));
lFilename := ExtractFileName(aFilename);
if TFile.Exists(aFilename) then
begin
lBaseFilename := lPath + ChangeFileExt(lFilename, FormatDateTime('yyyymmddhhhnnss', Now));
lNewFilename := lBaseFilename + '.log';
lIndex := 1;
while TFile.Exists(lNewFilename) do
begin
lNewFilename := lBaseFilename + '-' + IntToStr(lIndex) + '.log';
Inc(lIndex);
end;
TFile.Move(aFilename, lNewFilename);
end;
// Check for a maximum number of log files
lFiles := TDirectory.GetFiles(lPath, ChangeFileExt(lFilename,'*.log'), TSearchOption.soTopDirectoryOnly);
if Length(lFiles) > cMaxLogFiles then
begin
TArray.Sort<String>(lFiles, TComparer<String>.Default);
for i := 0 to High(lFiles)-cMaxLogFiles do
TFile.Delete(lFiles[i]);
end;
end;
procedure TProxyServiceModule.CetonDeviceDiscovered(const aIP,
aDescriptionXMLURL: String);
var
lDevice: TDiscoveredCetonDevice;
begin
lDevice := DiscoveredCetonDeviceList.FindByIP(aIP);
if aDescriptionXMLURL <> lDevice.DescriptionXMLURL then
begin
lDevice.IP := aIP;
lDevice.DescriptionXMLURL := aDescriptionXMLURL;
lDevice.Queried := False;
lDevice.FriendlyName := '';
lDevice.UpdateTicks := TStopWatch.GetTimestamp;
DiscoveredCetonDeviceList.Update(lDevice);
fThread.CetonDeviceDiscovered;
end
else
begin
lDevice.UpdateTicks := TStopWatch.GetTimestamp;
DiscoveredCetonDeviceList.Update(lDevice);
end;
end;
procedure TProxyServiceModule.DiscoveredCetonDevicesChanged;
begin
// Nothing
end;
procedure TProxyServiceModule.LogError(const aLogName, aMessage: String);
begin
// Nothing
end;
procedure TProxyServiceModule.HandleLoggerLogError(const aLogName,
aMessage: String);
begin
// Pass to config manager to allow broadcasting it to multiple recipients
ConfigManager.LogError(aLogName, aMessage);
end;
{ TServiceThread }
constructor TServiceThread.Create(const aServiceModule: TProxyServiceModule);
var
i: Integer;
begin
fServiceModule := aServiceModule;
fChangeEvent := TEvent.Create(nil, False, False, '');
SetLength(fLogCaches, Length(cLogNames));
for i := 0 to High(cLogNames) do
fLogCaches[i] := TStringBuilder.Create;
fEmailServerSettings := TEmailServerSettings.Create;
fErrorEmailSettings := TErrorEmailSettings.Create;
fErrorEmailCache := TStringBuilder.Create;
GetEmailSettings;
fServiceModule.ConfigManager.AddListener(Self);
inherited Create(True);
end;
procedure TServiceThread.Changed(const aSender: TObject;
const aSections: TServiceConfigSections);
begin
fConfigChanged := True;
fChangeEvent.SetEvent;
end;
destructor TServiceThread.Destroy;
var
i: Integer;
begin
Terminate;
fChangeEvent.SetEvent;
WaitFor;
fServiceModule.ConfigManager.RemoveListener(Self);
fChangeEvent.Free;
for i := 0 to High(cLogNames) do
fLogCaches[i].Free;
fErrorEmailCache.Free;
fErrorEmailSettings.Free;
fEmailServerSettings.Free;
inherited;
end;
procedure TServiceThread.QueryDiscoveredCetonDevices;
var
lClient: TRESTClient;
lDeviceArray: TArray<TDiscoveredCetonDevice>;
lDevice: TDiscoveredCetonDevice;
i: Integer;
lRequest: TRESTRequest;
begin
lDeviceArray := fServiceModule.DiscoveredCetonDeviceList.ToArray;
for i := 0 to High(lDeviceArray) do
begin
if not lDeviceArray[i].Queried then
begin
lDevice := lDeviceArray[i];
try
lClient := TRESTClient.Create(lDevice.DescriptionXMLURL);
try
lRequest := TRESTRequest.Create(nil);
try
lRequest.Timeout := 3000;
lRequest.Client := lClient;
lRequest.Method := TRESTRequestMethod.rmGet;
// lRequest.Resource := 'Services/6/Status.html';
lRequest.Execute;
if lRequest.Response.StatusCode = 200 then
begin
try
TDiscoveredCetonDevice.UpdateFromDescriptionXML(lDevice, lRequest.Response.Content);
finally
lDevice.Queried := True;
fServiceModule.DiscoveredCetonDeviceList.Update(lDevice);
end;
end
else
TLogger.LogFmt(cLogDiscovery, 'Unable to reach %s at discovered Ceton device with IP %s: Received status code %d (%s)', [lDevice.DescriptionXMLURL, lDevice.IP, lRequest.Response.StatusCode, lRequest.Response.StatusText]);
finally
lRequest.Free;
end;
finally
lClient.Free;
end;
except
on e: Exception do
TLogger.LogFmt(cLogDiscovery, 'Unable to reach %s at discovered Ceton device with IP %s: %s', [lDevice.DescriptionXMLURL, lDevice.IP, e.Message]);
end;
end;
end;
end;
procedure TServiceThread.Execute;
var
lConfig: TServiceConfig;
lCetonConfig: TCetonConfig;
begin
Coinitialize(nil);
try
while not Terminated do
begin
fChangeEvent.WaitFor(1000);
if fConfigChanged then
begin
fConfigChanged := False;
GetEmailSettings;
fServiceModule.SaveConfig;
end;
SaveLogs;
try
if fServiceModule.Client.CheckTuner then
begin
// If check tuner did something, it may have changed its config, so update the service module's config
lCetonConfig := TCetonConfig.Create;
try
fServiceModule.Client.GetConfig(lCetonConfig);
fServiceModule.ConfigManager.LockConfig(lConfig);
try
lConfig.Ceton.Assign(lCetonConfig, [TCetonConfigSection.Channels]);
finally
fServiceModule.ConfigManager.UnlockConfig(lConfig);
end;
finally
lCetonConfig.Free;
end;
fServiceModule.ConfigManager.Changed(fServiceModule.Client, [TServiceConfigSection.Other]);
end;
except
on e: Exception do
TLogger.Log(cLogDefault, e.Message);
end;
if fCetonDeviceDiscovered then
begin
fCetonDeviceDiscovered := False;
QueryDiscoveredCetonDevices;
fServiceModule.ConfigManager.DiscoveredCetonDevicesChanged;
end;
if fServiceModule.DiscoveredCetonDeviceList.Clean then
fServiceModule.ConfigManager.DiscoveredCetonDevicesChanged;
SendErrorEmail;
end;
finally
CoUninitialize;
end;
end;
function TServiceThread.QueryInterface(const IID: TGUID; out Obj): HResult;
const
E_NOINTERFACE = HResult($80004002);
begin
if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE;
end;
function TServiceThread._AddRef: Integer;
begin
Result := -1;
end;
function TServiceThread._Release: Integer;
begin
Result := -1;
end;
procedure TServiceThread.Log(const aLogName: String; const aMessage: String);
var
lMsg: String;
lIndex: Integer;
begin
lMsg := Format('[%s] %s', [FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now), aMessage]);
FMX.Types.Log.d('%s', [lMsg]);
lIndex := IndexText(aLogName, cLogNames);
if lIndex > -1 then
begin
TMonitor.Enter(fLogCaches[lIndex]);
try
fLogCaches[lIndex].AppendLine(lMsg);
finally
TMonitor.Exit(fLogCaches[lIndex]);
end;
end;
end;
procedure TServiceThread.SaveLogs;
var
lText: String;
lPath: String;
i: Integer;
begin
for i := 0 to High(cLogNames) do
begin
lText := '';
TMonitor.Enter(fLogCaches[i]);
try
if fLogCaches[i].Length = 0 then
Continue;
lText := fLogCaches[i].ToString;
fLogCaches[i].Length := 0;
finally
TMonitor.Exit(fLogCaches[i]);
end;
lPath := fServiceModule.GetConfigPath+'cetonproxy'+cLogNames[i]+'.log';
try
TFile.AppendAllText(lPath, lText);
except
// Ignore
end;
try
if TFile.GetSize(lPath) >= cLogSizeRollover then
fServiceModule.MoveLog(lPath);
except
// Ignore
end;
end;
end;
procedure TServiceThread.CetonDeviceDiscovered;
begin
fCetonDeviceDiscovered := True;
end;
procedure TServiceThread.DiscoveredCetonDevicesChanged;