Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
237 lines (191 loc) · 8.53 KB
/
Copy pathProgram.cs
File metadata and controls
237 lines (191 loc) · 8.53 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
using BookNotifier.Integrations.Ao3;
using BookNotifier.Integrations.GoodReads;
using BookNotifier.Integrations.Literotica;
using BookNotifier.Integrations.RoyalRoad;
using BookNotifier.Integrations.ScribbleHub;
using BookNotifier.Services;
using BookNotifier.Utilities;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace BookNotifier
{
internal class Program
{
// Declare first or else flareclient will not register the env
private static readonly EnvService Env = new();
public static FlareSolverClient FlareClient = new();
private static bool RunOnce { get; set; }
public static bool IgnorePost { get; set; }
// Must exceed FlareSolver's 30m Cloudflare-ban wait.
private static readonly TimeSpan RunTimeout = TimeSpan.FromHours(1);
public static async Task Main(string[] args)
{
CultureInfo ci = new("en-CA");
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data"));
if (args.Contains("--selftest", StringComparer.OrdinalIgnoreCase))
{
SelfCheck.Run();
return;
}
AppDomain.CurrentDomain.UnhandledException += (_, f) => LogError(f.ExceptionObject.ToString() ?? "Unhandled exception");
TaskScheduler.UnobservedTaskException += (_, ef) => LogError(ef.Exception.Message);
RunOnce = args.Contains("--runonce", StringComparer.OrdinalIgnoreCase);
IgnorePost = args.Contains("--ignore-post", StringComparer.OrdinalIgnoreCase);
Log($"Running Once: {RunOnce}");
Log($"Ignoring Discord Post: {IgnorePost}");
Log($"Env Vars Found: {Env.Variables.Count}");
string[] notifiers = (Environment.GetEnvironmentVariable("NOTIFIER")
?? throw new InvalidOperationException("Missing NOTIFIER environment variable."))
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(x => x.ToLowerInvariant())
.Distinct()
.ToArray();
if (notifiers.Length == 0)
throw new InvalidOperationException("NOTIFIER is empty. Expected one or more of: goodreads, scribblehub, literotica, royalroad, ao3.");
string[] needsFlareSolver = [.. notifiers.Intersect(["scribblehub", "royalroad", "ao3"])];
if (needsFlareSolver.Length > 0 && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("FLARESOLVER_URL")))
throw new InvalidOperationException($"FLARESOLVER_URL is required for: {string.Join(", ", needsFlareSolver)}.");
Log($"Starting notifiers: {string.Join(", ", notifiers)}");
IEnumerable<Task> notifierTasks = notifiers.Select(notifier => notifier switch
{
"goodreads" => RunLoopAsync("goodreads", GetRecheckMs("GOODREADS"), RunGoodReadsAsync),
"scribblehub" => RunLoopAsync("scribblehub", GetRecheckMs("SCRIBBLEHUB"), RunScribbleHubAsync),
"literotica" => RunLoopAsync("literotica", GetRecheckMs("LITEROTICA"), RunLiteroticaAsync),
"royalroad" => RunLoopAsync("royalroad", GetRecheckMs("ROYALROAD"), RunRoyalRoadAsync),
"ao3" => RunLoopAsync("ao3", GetRecheckMs("AO3"), RunAo3Async),
_ => throw new InvalidOperationException(
$"Unknown notifier '{notifier}'. Expected one or more of: goodreads, scribblehub, literotica, royalroad, ao3.")
});
await Task.WhenAll(notifierTasks);
if (RunOnce) Environment.Exit(0);
}
[SuppressMessage("ReSharper", "FunctionNeverReturns")]
private static async Task RunLoopAsync(string name, long recheckMs, Func<Task> action)
{
// Resume the interval across restarts: wait out whatever is left since the last finished run.
if (!RunOnce && await FileStoreService.LoadLastRunAsync(name) is { } lastRun)
{
TimeSpan remaining = lastRun + TimeSpan.FromMilliseconds(recheckMs) - DateTimeOffset.UtcNow;
// Clamp so a future timestamp (clock change) can't delay beyond one full interval.
remaining = TimeSpan.FromMilliseconds(Math.Min(remaining.TotalMilliseconds, recheckMs));
if (remaining > TimeSpan.Zero)
{
Log($"[{name}] Last ran {lastRun:u}, next run in {remaining:hh\\:mm\\:ss}.");
await Task.Delay(remaining);
}
}
while (true)
{
try
{
Log($"[{name}] Running...");
// A hung request (SDK call, webhook, etc.) would otherwise stall this loop forever;
// WaitAsync abandons the stuck run so the next cycle still happens.
await action().WaitAsync(RunTimeout);
Log($"[{name}] Check complete.");
}
catch (TimeoutException)
{
LogError($"[{name}] Run exceeded {RunTimeout.TotalMinutes}m and was abandoned, will retry next cycle.");
}
catch (Exception ex)
{
LogError($"[{name}] Error: {ex.Message}");
}
if (RunOnce) break;
await FileStoreService.SaveLastRunAsync(name, DateTimeOffset.UtcNow);
Log($"[{name}] Waiting {recheckMs}ms...");
await Task.Delay(TimeSpan.FromMilliseconds(recheckMs));
}
}
private static long GetRecheckMs(string prefix)
{
if (RunOnce) return long.MaxValue;
string key = $"{prefix}_RECHECK_MS";
string raw = (Environment.GetEnvironmentVariable(key)
?? throw new InvalidOperationException($"Missing {key} environment variable."))
.Replace("_", "")
.Replace(" ", "");
return !long.TryParse(raw, out long ms)
? throw new InvalidOperationException($"Failed to parse {key}.")
: ms;
}
private static async Task RunAo3Async()
{
string username = Environment.GetEnvironmentVariable("AO3_USERNAME") ?? throw new InvalidOperationException("Missing AO3_USERNAME environment variable");
string pseudoname = Environment.GetEnvironmentVariable("AO3_PSEUDO") ?? username;
Ao3Client ao3Client = new(username, pseudoname);
await ao3Client.RunCheck();
}
private static async Task RunGoodReadsAsync()
{
using GoodReadsClient sdk = new();
try
{
IReadOnlyList<GoodReadsBookDetails> readingListData =
await sdk.GetReadingListBooksAsync(
Environment.GetEnvironmentVariable("GOODREADS_USER_ID")
?? throw new InvalidOperationException("Missing GOODREADS_USER_ID environment variable."),
Environment.GetEnvironmentVariable("GOODREADS_SHELF_TAG")
?? throw new InvalidOperationException("Missing GOODREADS_SHELF_TAG environment variable.")
);
Dictionary<string, List<GoodReadsBook>> authorBooks = [];
foreach (GoodReadsAuthor author in readingListData.Select(x => x.Author).DistinctBy(x => x.Name))
{
List<GoodReadsBook> books = await sdk.GetAuthorsBooks(author.Url);
authorBooks[author.Name] = books;
}
await sdk.RunAsync(readingListData, authorBooks);
}
finally
{
await sdk.DestroyFlareSessionIfNeededAsync();
}
}
private static async Task RunScribbleHubAsync()
{
string userId = Environment.GetEnvironmentVariable("SCRIBBLEHUB_USERID") ?? throw new InvalidOperationException("Missing required USERID environment variable");
ScribbleClient api = new(userId);
await api.RunCheck();
}
private static async Task RunLiteroticaAsync()
{
string username = Environment.GetEnvironmentVariable("LITEROTICA_USERNAME") ?? throw new InvalidOperationException("Missing LITEROTICA_USERNAME environment variable.");
string password = Environment.GetEnvironmentVariable("LITEROTICA_PASSWORD") ?? throw new InvalidOperationException("Missing LITEROTICA_PASSWORD environment variable.");
using LiteroticaClient client = new(username, password);
await client.RunAsync();
}
private static async Task RunRoyalRoadAsync()
{
string userId = Environment.GetEnvironmentVariable("ROYALROAD_USERID") ?? throw new InvalidOperationException("Missing ROYALROAD_USERID environment variable.");
if (!int.TryParse(userId, out int userIdOut)) throw new InvalidOperationException($"Failed to parse {userId} as int");
RoyalRoadClient client = new(userIdOut);
await client.RunAsync();
}
}
internal class EnvService
{
public IReadOnlyDictionary<string, string> Variables { get; private set; }
internal EnvService()
{
Dictionary<string, string> vars = [];
string envPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ".env");
if (!File.Exists(envPath)) { Variables = vars; return; }
foreach (string line in File.ReadAllLines(envPath))
{
if (string.IsNullOrWhiteSpace(line) || line.StartsWith('#')) continue;
string[] parts = line.Split('=', 2);
if (parts.Length != 2) continue;
string key = parts[0].Trim();
if (string.IsNullOrEmpty(key)) continue;
string value = parts[1].Trim().Trim('"').Trim('\'');
vars[key] = value;
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(key)))
Environment.SetEnvironmentVariable(key, value);
}
Variables = vars;
}
}
}