-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
417 lines (371 loc) · 21.8 KB
/
Copy pathProgram.cs
File metadata and controls
417 lines (371 loc) · 21.8 KB
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
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Http.Resilience;
using Microsoft.Extensions.Logging;
using Serilog;
using System.Text.Json;
using System.Text.Json.Nodes;
using NwsAlertBot.Config;
using NwsAlertBot.Services;
// ---------------------------------------------------------------
// NWS Alert Social Media + Push Notification Bot
// Built with .NET 8 Console App / Generic Host
// ---------------------------------------------------------------
// A Windows Service's working directory defaults to C:\Windows\System32, not the executable's
// own folder -- and there's no service-creation parameter that can override that. Every relative
// path in this app (appsettings.json, posted_alerts.txt, logs/, etc.) is resolved against the
// process's current directory, so this must run before anything else touches the filesystem.
// Harmless when run interactively or under systemd (WorkingDirectory= already points here).
Directory.SetCurrentDirectory(AppContext.BaseDirectory);
LocalConfigSync.Run();
// Write a startup separator to both the console and the daily log file so it's
// easy to find where a new run begins when reviewing logs.
{
var startLine = $"Started: {DateTime.Now:yyyy-MM-dd HH:mm:ss}";
Console.WriteLine();
Console.WriteLine("==============================");
Console.WriteLine(startLine);
Console.WriteLine();
Directory.CreateDirectory("logs");
File.AppendAllText($"logs/nwsalertbot-{DateTime.Now:yyyyMMdd}.log",
$"\n==============================\n{startLine}\n\n");
}
var host = Host.CreateDefaultBuilder(args)
// No-op unless actually running under the Windows Service Control Manager (interactive runs,
// and systemd on Linux, are unaffected) -- required for the process to respond to the SCM's
// start/stop handshake at all. Without it, Windows kills a service-wrapped console app almost
// immediately (error 1053). See scripts/setup-service.ps1 for creating the actual service.
.UseWindowsService()
.ConfigureAppConfiguration(config =>
{
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
config.AddJsonFile("appsettings.Local.json", optional: true, reloadOnChange: false);
})
.ConfigureServices((context, services) =>
{
var cfg = context.Configuration;
// Bind all config sections
var locationSettings = cfg.GetSection("Location").Get<LocationSettings>() ?? new LocationSettings();
var pollingSettings = cfg.GetSection("Polling").Get<PollingSettings>() ?? new PollingSettings();
var nwsSettings = cfg.GetSection("Nws").Get<NwsSettings>() ?? new NwsSettings();
var facebookSettings = cfg.GetSection("Facebook").Get<FacebookSettings>() ?? new FacebookSettings();
var instagramSettings = cfg.GetSection("Instagram").Get<InstagramSettings>() ?? new InstagramSettings();
var xSettings = cfg.GetSection("X").Get<XSettings>() ?? new XSettings();
var blueskySettings = cfg.GetSection("Bluesky").Get<BlueskySettings>() ?? new BlueskySettings();
var mastodonSettings = cfg.GetSection("Mastodon").Get<MastodonSettings>() ?? new MastodonSettings();
var pushoverSettings = cfg.GetSection("Pushover").Get<PushoverSettings>() ?? new PushoverSettings();
var twilioSettings = cfg.GetSection("Twilio").Get<TwilioSettings>() ?? new TwilioSettings();
var discordSettings = cfg.GetSection("Discord").Get<DiscordSettings>() ?? new DiscordSettings();
var discordDmSettings = cfg.GetSection("DiscordDm").Get<DiscordDmSettings>() ?? new DiscordDmSettings();
var telegramSettings = cfg.GetSection("Telegram").Get<TelegramSettings>() ?? new TelegramSettings();
var voipMsSettings = cfg.GetSection("VoipMs").Get<VoipMsSettings>() ?? new VoipMsSettings();
var mapSettings = cfg.GetSection("Map").Get<MapSettings>() ?? new MapSettings();
var spcSettings = cfg.GetSection("Spc").Get<SpcSettings>() ?? new SpcSettings();
var spcMcdSettings = cfg.GetSection("SpcMcd").Get<SpcMcdSettings>() ?? new SpcMcdSettings();
var hwoSettings = cfg.GetSection("Hwo").Get<HwoSettings>() ?? new HwoSettings();
var eroSettings = cfg.GetSection("Ero").Get<EroSettings>() ?? new EroSettings();
var updateSettings = cfg.GetSection("Update").Get<UpdateSettings>() ?? new UpdateSettings();
// Register settings as singletons
services.AddSingleton(locationSettings);
services.AddSingleton(pollingSettings);
services.AddSingleton(nwsSettings);
services.AddSingleton(facebookSettings);
services.AddSingleton(instagramSettings);
services.AddSingleton(xSettings);
services.AddSingleton(blueskySettings);
services.AddSingleton(mastodonSettings);
services.AddSingleton(pushoverSettings);
services.AddSingleton(twilioSettings);
services.AddSingleton(discordSettings);
services.AddSingleton(discordDmSettings);
services.AddSingleton(telegramSettings);
services.AddSingleton(voipMsSettings);
services.AddSingleton(mapSettings);
services.AddSingleton(spcSettings);
services.AddSingleton(spcMcdSettings);
services.AddSingleton(hwoSettings);
services.AddSingleton(eroSettings);
services.AddSingleton(updateSettings);
// HttpClients — each service gets its own typed client.
// The read-only weather/mapping feeds (NWS, SPC, HWO, WPC ERO, IEM, Mapbox) get a
// standard resilience handler (retry + circuit breaker + timeouts) since they're all
// idempotent GETs against occasionally-flaky government/free-tier APIs polled every few
// minutes anyway — a transient failure just means waiting for the next poll otherwise.
// Deliberately NOT applied to platform-posting clients: X's OAuth1.0a signature includes
// a per-request timestamp/nonce (retrying an identical signed request looks like a replay),
// and Bluesky already has its own hand-rolled 401-reauth retry (CLAUDE.md says don't touch).
services.AddHttpClient<NwsAlertService>(client =>
{
// NWS API requires a descriptive User-Agent with contact info
client.DefaultRequestHeaders.Add("User-Agent", "NwsAlertBot/1.0 (contact@yourorg.com)");
client.DefaultRequestHeaders.Add("Accept", "application/geo+json");
}).AddStandardResilienceHandler();
services.AddHttpClient<FacebookService>();
services.AddHttpClient<InstagramService>();
services.AddHttpClient<XService>();
services.AddHttpClient<BlueskyService>();
services.AddHttpClient<MastodonService>();
services.AddHttpClient<PushoverService>();
services.AddHttpClient<TwilioService>();
services.AddHttpClient<DiscordService>();
services.AddHttpClient<DiscordDmService>();
services.AddHttpClient<TelegramService>();
services.AddHttpClient<VoipMsService>();
services.AddHttpClient<NwsZoneService>(client =>
{
client.DefaultRequestHeaders.Add("User-Agent", "NwsAlertBot/1.0 (contact@yourorg.com)");
client.DefaultRequestHeaders.Add("Accept", "application/geo+json");
}).AddStandardResilienceHandler();
services.AddHttpClient<SpcOutlookService>(client =>
{
client.DefaultRequestHeaders.Add("User-Agent", "NwsAlertBot/1.0 (contact@yourorg.com)");
client.DefaultRequestHeaders.Add("Accept", "application/geo+json");
}).AddStandardResilienceHandler();
services.AddHttpClient<SpcMcdService>(client =>
{
client.DefaultRequestHeaders.Add("User-Agent", "NwsAlertBot/1.0 (contact@yourorg.com)");
client.DefaultRequestHeaders.Add("Accept", "application/geo+json");
}).AddStandardResilienceHandler();
services.AddHttpClient<HwoService>(client =>
{
client.DefaultRequestHeaders.Add("User-Agent", "NwsAlertBot/1.0 (contact@yourorg.com)");
client.DefaultRequestHeaders.Add("Accept", "application/geo+json");
}).AddStandardResilienceHandler();
services.AddHttpClient<WpcEroService>(client =>
{
client.DefaultRequestHeaders.Add("User-Agent", "NwsAlertBot/1.0 (contact@yourorg.com)");
client.DefaultRequestHeaders.Add("Accept", "application/geo+json");
}).AddStandardResilienceHandler();
// Named client for MapService's read-only IEM pre-flight checks (ResolveIemPhenomenaAsync,
// VerifyIemSpsAsync), which currently go through IHttpClientFactory.CreateClient() with no
// name and no existing retry logic.
services.AddHttpClient("WeatherImagery").AddStandardResilienceHandler();
// SocialMediaOrchestrator's map image download previously hand-rolled its own retry loop
// (TryDownloadAsync). Replaced with named clients so the retry policy lives in one place,
// consistent with every other read-only feed above, instead of a bespoke for-loop. Primary
// (IEM) gets the standard resilience handler like everything else; the Mapbox fallback
// deliberately doesn't (it's already the last resort, so there's nothing further to fall
// back to if a retry also fails).
services.AddHttpClient("WeatherImageryPrimary").AddStandardResilienceHandler();
services.AddHttpClient("WeatherImageryFallback");
// GitHub Releases API check for UpdateCheckService — read-only, occasional, benefits
// from the same retry/circuit-breaker handling as the weather feeds above.
services.AddHttpClient<UpdateCheckService>().AddStandardResilienceHandler();
// Core services
services.AddSingleton<AlertTrackerService>();
services.AddSingleton<MapService>();
services.AddSingleton<StartupConfirmationService>();
services.AddSingleton<SocialMediaOrchestrator>();
services.AddSingleton<ImageSmokeTestService>();
// Background polling loop
services.AddHostedService<AlertPollingService>();
})
.UseSerilog((_, _, config) => config
.MinimumLevel.Information()
// Suppress noisy framework namespaces
.MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning)
.MinimumLevel.Override("System", Serilog.Events.LogEventLevel.Warning)
// Suppress HttpClient request-URL logs that would expose API tokens in log files
.MinimumLevel.Override("System.Net.Http.HttpClient.TelegramService", Serilog.Events.LogEventLevel.Warning)
.MinimumLevel.Override("System.Net.Http.HttpClient.BlueskyService", Serilog.Events.LogEventLevel.Warning)
.MinimumLevel.Override("System.Net.Http.HttpClient.XService", Serilog.Events.LogEventLevel.Warning)
.MinimumLevel.Override("System.Net.Http.HttpClient.MastodonService", Serilog.Events.LogEventLevel.Warning)
.MinimumLevel.Override("System.Net.Http.HttpClient.VoipMsService", Serilog.Events.LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(
path: "logs/nwsalertbot-.log",
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 30,
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}"))
.Build();
// Dev tool: posts a synthetic alert with a test image to every enabled image-capable platform,
// then exits without starting the live polling loop. See ImageSmokeTestService for details.
if (args.Contains("--smoke-test-image"))
{
await host.Services.GetRequiredService<ImageSmokeTestService>().RunAsync();
return;
}
await host.RunAsync();
// ---------------------------------------------------------------
// Local config sync — runs once at startup before the host is built.
// Compares appsettings.Local.json against appsettings.json and adds
// any missing keys (within sections that already exist in local) with
// conservative defaults: booleans → false, strings → "", numbers keep
// the base default. Top-level sections absent from local are skipped
// so unconfigured platforms don't get empty blocks injected.
// ---------------------------------------------------------------
static class LocalConfigSync
{
private static readonly JsonSerializerOptions WriteOptions = new() { WriteIndented = true };
// Must match the leniency of the Microsoft.Extensions.Configuration.Json provider used by
// AddJsonFile() (which tolerates "//" comments) — JsonNode.Parse's default options do NOT
// allow comments and throw JsonReaderException on the very first "//" line, crashing the
// process with SIGABRT before the host even builds.
private static readonly JsonDocumentOptions ParseOptions = new()
{
CommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
};
public static void Run(string basePath = "appsettings.json", string localPath = "appsettings.Local.json")
{
if (!File.Exists(localPath) || !File.Exists(basePath)) return;
var localRoot = JsonNode.Parse(File.ReadAllText(localPath), documentOptions: ParseOptions);
var baseRoot = JsonNode.Parse(File.ReadAllText(basePath), documentOptions: ParseOptions);
if (localRoot is not JsonObject localObj || baseRoot is not JsonObject baseObj) return;
var added = new List<string>();
Merge(localObj, baseObj, path: "", added);
if (added.Count == 0) return;
File.WriteAllText(localPath, localRoot.ToJsonString(WriteOptions));
Console.WriteLine($"[Config] Added {added.Count} missing setting(s) to {localPath}: {string.Join(", ", added)}");
}
// Recursively copies keys present in source but absent from local.
// Missing top-level sections that have an Enabled field are injected as disabled.
// Sections without Enabled (e.g. Nws) are skipped at the top level.
// New nested keys (e.g. IncludeSpcMcd added to an existing platform section) preserve
// their base-config default value so feature flags that default to true stay enabled.
private static void Merge(JsonObject local, JsonObject source, string path, List<string> added)
{
foreach (var (key, sourceValue) in source)
{
string fullKey = path.Length > 0 ? $"{path}.{key}" : key;
if (local.ContainsKey(key))
{
if (sourceValue is JsonObject srcChild && local[key] is JsonObject localChild)
Merge(localChild, srcChild, fullKey, added);
}
else if (path.Length == 0)
{
// Top-level: inject service sections (those with Enabled) as disabled
if (sourceValue is JsonObject srcSection && srcSection.ContainsKey("Enabled"))
{
local[key] = BuildOffSection(srcSection);
added.Add($"{key} (disabled)");
}
}
else
{
// New key inside an existing section — preserve the base-config value so
// feature flags that default to true (e.g. IncludeSpcMcd) stay enabled.
local[key] = sourceValue?.DeepClone() ?? JsonValue.Create(false)!;
added.Add(fullKey);
}
}
}
// Builds a JsonObject from source with all values set to off defaults.
private static JsonObject BuildOffSection(JsonObject source)
{
var obj = new JsonObject();
foreach (var (key, value) in source)
obj[key] = value is JsonObject nested ? BuildOffSection(nested) : OffDefault(value);
return obj;
}
// Returns a conservative "off" default for a missing key.
// Booleans → false, strings → "", numbers keep the base value.
private static JsonNode OffDefault(JsonNode? node) => node switch
{
JsonObject => new JsonObject(),
JsonArray => new JsonArray(),
JsonValue v when v.TryGetValue<bool>(out _) => JsonValue.Create(false)!,
JsonValue v when v.TryGetValue<string>(out _) => JsonValue.Create("")!,
JsonValue => node.DeepClone(), // numbers — keep base default
_ => JsonValue.Create(false)!,
};
}
// ---------------------------------------------------------------
// Background polling service
// ---------------------------------------------------------------
public class AlertPollingService : BackgroundService
{
private readonly StartupConfirmationService _confirmation;
private readonly SocialMediaOrchestrator _orchestrator;
private readonly UpdateCheckService _updateCheck;
private readonly NwsSettings _settings;
private readonly LocationSettings _location;
private readonly PollingSettings _polling;
private readonly ILogger<AlertPollingService> _logger;
// Tracks when the last new alert was posted; null means no alert seen yet this session.
private DateTime? _lastNewAlertUtc;
// Tracks the latest expiry time among active Watches, so fast polling covers a Watch's full
// duration rather than dropping back to idle after ActiveAlertWindowHours — see
// SocialMediaOrchestrator.RunAsync's remarks for why Watches need this and Warnings don't.
private DateTimeOffset? _watchActiveUntilUtc;
public AlertPollingService(
StartupConfirmationService confirmation,
SocialMediaOrchestrator orchestrator,
UpdateCheckService updateCheck,
NwsSettings settings,
LocationSettings location,
PollingSettings polling,
ILogger<AlertPollingService> logger)
{
_confirmation = confirmation;
_orchestrator = orchestrator;
_updateCheck = updateCheck;
_settings = settings;
_location = location;
_polling = polling;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
string geoFilter = _location.Zones.Count > 0
? $"Zones: {string.Join(", ", _location.Zones)}"
: _location.Counties.Count > 0
? $"Counties: {string.Join(", ", _location.Counties)}"
: string.IsNullOrWhiteSpace(_settings.State) ? "Nationwide" : $"State: {_settings.State}";
_logger.LogInformation(
"NWS Alert Bot v{Version} started. Idle poll: {Idle}s | Active poll: {Active}s (window: {Hours}h) | {GeoFilter} | Min severity: {Severity} | Active mode trigger: {ActiveMinSeverity}",
UpdateCheckService.GetCurrentVersion()?.ToString() ?? "unknown",
_polling.PollIntervalSeconds, _polling.ActiveAlertPollIntervalSeconds,
_polling.ActiveAlertWindowHours, geoFilter, _settings.FilterSeverity,
string.IsNullOrWhiteSpace(_polling.ActiveAlertMinSeverity) ? "any" : _polling.ActiveAlertMinSeverity);
// Send one-time confirmation to any platform not yet verified
await _confirmation.RunAsync(stoppingToken);
// Main polling loop
while (!stoppingToken.IsCancellationRequested)
{
// Self-throttles internally (UpdateSettings.CheckIntervalHours); a no-op when disabled.
await _updateCheck.CheckForUpdateAsync(stoppingToken);
var (newAlerts, watchExpiresUtc) = await _orchestrator.RunAsync(stoppingToken);
if (newAlerts > 0)
{
if (_lastNewAlertUtc == null && !_watchActiveUntilUtc.HasValue)
_logger.LogInformation("Active storm mode engaged — polling every {Interval}s for {Hours}h.",
_polling.ActiveAlertPollIntervalSeconds, _polling.ActiveAlertWindowHours);
else
_logger.LogInformation("Active storm window reset — {Count} new alert(s) posted.", newAlerts);
_lastNewAlertUtc = DateTime.UtcNow;
}
if (watchExpiresUtc.HasValue &&
(!_watchActiveUntilUtc.HasValue || watchExpiresUtc.Value > _watchActiveUntilUtc.Value))
{
_logger.LogInformation("Active Watch in effect — polling every {Interval}s until it expires at {ExpiresUtc:u}.",
_polling.ActiveAlertPollIntervalSeconds, watchExpiresUtc.Value);
_watchActiveUntilUtc = watchExpiresUtc.Value;
}
bool inFixedWindow = _lastNewAlertUtc.HasValue &&
(DateTime.UtcNow - _lastNewAlertUtc.Value).TotalHours < _polling.ActiveAlertWindowHours;
bool inWatchWindow = _watchActiveUntilUtc.HasValue && DateTimeOffset.UtcNow < _watchActiveUntilUtc.Value;
int delaySeconds;
if (inFixedWindow || inWatchWindow)
{
delaySeconds = _polling.ActiveAlertPollIntervalSeconds;
}
else
{
if (_lastNewAlertUtc.HasValue || _watchActiveUntilUtc.HasValue)
{
_logger.LogInformation("Active storm window expired — returning to idle poll interval ({Interval}s).",
_polling.PollIntervalSeconds);
_lastNewAlertUtc = null;
_watchActiveUntilUtc = null;
}
delaySeconds = _polling.PollIntervalSeconds;
}
await Task.Delay(TimeSpan.FromSeconds(delaySeconds), stoppingToken);
}
_logger.LogInformation("NWS Alert Bot stopped.");
}
}