-
Notifications
You must be signed in to change notification settings - Fork 0
/
Worker.cs
209 lines (183 loc) · 7.25 KB
/
Worker.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
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Celestial.Providers;
using Celestial.Triggers;
namespace Celestial;
public class Worker : BackgroundService
{
private readonly IProvider _provider;
private readonly ILogger<Worker> _logger;
private readonly IHostApplicationLifetime _host;
private Settings settings = null!;
private CancellationTokenSource ctsConfig = null!;
private CancellationTokenSource ctsCombined = null!;
public Worker(IProvider provider, ILogger<Worker> logger, IHostApplicationLifetime host)
{
_provider = provider;
_logger = logger;
_host = host;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await LoadSettingsAsync(stoppingToken);
_logger.LogInformation("Using provider {provider}", _provider.GetName());
using (var watcher = new FileSystemWatcher(Path.GetDirectoryName(GetConfigPath())!))
{
watcher.Filter = ConfigFileName;
watcher.IncludeSubdirectories = false;
watcher.EnableRaisingEvents = true;
watcher.Changed += OnConfigFileChange;
if (!settings.Triggers.Any())
{
_logger.LogCritical("No triggers defined, waiting for config file change");
try
{
// delay of -1ms waits indefinitely
await Task.Delay(-1, ctsCombined.Token);
}
catch (TaskCanceledException e)
{
if (e.CancellationToken == ctsCombined.Token)
{
if (ctsConfig.IsCancellationRequested && !stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Config file change detected, reloading settings");
await LoadSettingsAsync(stoppingToken);
}
}
else
{
throw;
}
}
}
await SetInitialBackgroundAsync();
await RunAsync(stoppingToken);
}
}
private async Task SetInitialBackgroundAsync()
{
var previousTrigger = settings.Triggers
.Select(t => new { Trigger = t, Previous = t.GetPreviousOccurrence(DateTime.Now, settings) })
.Where(t => t.Previous < DateTime.Now)
.OrderByDescending(t => t.Previous)
.FirstOrDefault();
if (previousTrigger != null)
{
_logger.LogInformation("Setting initial state from previous trigger {trigger} ({time})", previousTrigger.Trigger, previousTrigger.Previous?.ToString("s"));
try
{
await _provider.SetBackgroundAsync(previousTrigger.Trigger.Path);
}
catch (Exception e)
{
_logger.LogError(e, "Exception thrown when setting background");
}
}
else
{
_logger.LogWarning("Could not determine initial state from previous trigger");
}
}
private async Task RunAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Trigger? nextTrigger = null;
DateTime? next = null;
foreach (var trigger in settings.Triggers)
{
if (!trigger.IsValid(out string? reason))
{
_logger.LogWarning("Invalid trigger: {reason}", reason);
continue;
}
DateTime? triggerNext;
try
{
triggerNext = trigger.GetNextOccurrence(DateTime.Now, settings);
}
catch (Exception e)
{
_logger.LogError(e, "Exception thrown when getting next occurrence");
continue;
}
if (triggerNext < next || (!next.HasValue && triggerNext.HasValue))
{
nextTrigger = trigger;
next = triggerNext;
}
}
if (next.HasValue && nextTrigger != null && next > DateTime.Now)
{
// calculate time until next trigger fires
TimeSpan delay = next.Value - DateTime.Now;
if (delay > TimeSpan.Zero)
{
_logger.LogInformation("Next trigger is {trigger} in {delay} ({time})", nextTrigger, delay, next?.ToString("s"));
try
{
// wait until trigger time (if in future)
await Task.Delay(delay, ctsCombined.Token);
}
catch (TaskCanceledException e)
{
if (e.CancellationToken == ctsCombined.Token)
{
if (ctsConfig.IsCancellationRequested && !stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Config file change detected, reloading settings");
await LoadSettingsAsync(stoppingToken);
await SetInitialBackgroundAsync();
continue;
}
}
else
{
throw;
}
}
}
if (!stoppingToken.IsCancellationRequested)
{
// set background once trigger time is reached
_logger.LogInformation("Changing background to {background}", nextTrigger.Path);
try
{
await _provider.SetBackgroundAsync(nextTrigger.Path);
}
catch (Exception e)
{
_logger.LogError(e, "Exception thrown when setting background");
}
}
}
else
{
_logger.LogError("No further occurrences found, exiting");
_host.StopApplication();
return;
}
}
}
private void OnConfigFileChange(object sender, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Changed || e.ChangeType == WatcherChangeTypes.Created)
{
// request cancellation to break out of any Task.Delays in progress and reload settings
ctsConfig.Cancel();
}
}
private async Task LoadSettingsAsync(CancellationToken stoppingToken)
{
settings = await Settings.LoadFromFileAsync(GetConfigPath(), _logger);
ctsConfig = new CancellationTokenSource();
ctsCombined = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken, ctsConfig.Token);
}
private string GetConfigPath() => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"celestial",
ConfigFileName
);
private const string ConfigFileName = "config.json";
}