1
+ namespace Bloxstrap . Integrations
2
+ {
3
+ public class IntegrationWatcher : IDisposable
4
+ {
5
+ private readonly ActivityWatcher _activityWatcher ;
6
+ private readonly Dictionary < int , CustomIntegration > _activeIntegrations = new ( ) ;
7
+
8
+ public IntegrationWatcher ( ActivityWatcher activityWatcher )
9
+ {
10
+ _activityWatcher = activityWatcher ;
11
+
12
+ _activityWatcher . OnGameJoin += OnGameJoin ;
13
+ _activityWatcher . OnGameLeave += OnGameLeave ;
14
+ }
15
+
16
+ private void OnGameJoin ( object ? sender , EventArgs e )
17
+ {
18
+ if ( ! _activityWatcher . InGame )
19
+ return ;
20
+
21
+ long currentGameId = _activityWatcher . Data . PlaceId ;
22
+
23
+ foreach ( var integration in App . Settings . Prop . CustomIntegrations )
24
+ {
25
+ if ( ! integration . SpecifyGame || integration . GameID != currentGameId . ToString ( ) )
26
+ continue ;
27
+
28
+ LaunchIntegration ( integration ) ;
29
+ }
30
+ }
31
+
32
+ private void OnGameLeave ( object ? sender , EventArgs e )
33
+ {
34
+ foreach ( var pid in _activeIntegrations . Keys . ToList ( ) )
35
+ {
36
+ var integration = _activeIntegrations [ pid ] ;
37
+ if ( integration . AutoCloseOnGame )
38
+ {
39
+ TerminateProcess ( pid ) ;
40
+ _activeIntegrations . Remove ( pid ) ;
41
+ }
42
+ }
43
+ }
44
+
45
+ private void LaunchIntegration ( CustomIntegration integration )
46
+ {
47
+ const string LOG_IDENT = "IntegrationWatcher::LaunchIntegration" ;
48
+
49
+ try
50
+ {
51
+ var process = Process . Start ( new ProcessStartInfo
52
+ {
53
+ FileName = integration . Location ,
54
+ Arguments = integration . LaunchArgs . Replace ( "\r \n " , " " ) ,
55
+ WorkingDirectory = Path . GetDirectoryName ( integration . Location ) ,
56
+ UseShellExecute = true
57
+ } ) ;
58
+
59
+ if ( process != null )
60
+ {
61
+ App . Logger . WriteLine ( LOG_IDENT , $ "Integration '{ integration . Name } ' launched for game ID '{ integration . GameID } ' (PID { process . Id } ).") ;
62
+ _activeIntegrations [ process . Id ] = integration ;
63
+ }
64
+ }
65
+ catch ( Exception ex )
66
+ {
67
+ App . Logger . WriteLine ( LOG_IDENT , $ "Failed to launch integration '{ integration . Name } ': { ex . Message } ") ;
68
+ }
69
+ }
70
+
71
+ private void TerminateProcess ( int pid )
72
+ {
73
+ const string LOG_IDENT = "IntegrationWatcher::TerminateProcess" ;
74
+
75
+ try
76
+ {
77
+ var process = Process . GetProcessById ( pid ) ;
78
+ process . Kill ( ) ;
79
+
80
+ App . Logger . WriteLine ( LOG_IDENT , $ "Terminated integration process (PID { pid } ).") ;
81
+ }
82
+ catch ( Exception )
83
+ {
84
+ App . Logger . WriteLine ( LOG_IDENT , $ "Failed to terminate process (PID { pid } ), likely already exited.") ;
85
+ }
86
+ }
87
+
88
+ public void Dispose ( )
89
+ {
90
+ foreach ( var pid in _activeIntegrations . Keys )
91
+ {
92
+ TerminateProcess ( pid ) ;
93
+ }
94
+
95
+ _activeIntegrations . Clear ( ) ;
96
+
97
+ GC . SuppressFinalize ( this ) ;
98
+ }
99
+ }
100
+ }
0 commit comments