-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
194 lines (157 loc) · 6.27 KB
/
Program.cs
File metadata and controls
194 lines (157 loc) · 6.27 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
using BookNotifier.Integrations.GoodReads;
using BookNotifier.Integrations.Literotica;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using BookNotifier.Integrations.RoyalRoad;
namespace BookNotifier
{
internal class Program
{
public static async Task Main(string[] args)
{
CultureInfo ci = new("en-CA");
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
AppDomain.CurrentDomain.UnhandledException += (_, f) => LogError(f.ExceptionObject.ToString() ?? "Unhandled exception");
TaskScheduler.UnobservedTaskException += (_, ef) => LogError(ef.Exception.Message);
_ = new EnvService();
Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data"));
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.");
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),
_ => throw new InvalidOperationException(
$"Unknown notifier '{notifier}'. Expected one or more of: goodreads, scribblehub, literotica.")
});
await Task.WhenAll(notifierTasks);
}
[SuppressMessage("ReSharper", "FunctionNeverReturns")]
private static async Task RunLoopAsync(string name, long recheckMs, Func<Task> action)
{
while (true)
{
try
{
Log($"[{name}] Running...");
await action();
Log($"[{name}] Check complete.");
}
catch (Exception ex)
{
LogError($"[{name}] Error: {ex.Message}");
}
Log($"[{name}] Waiting {recheckMs}ms...");
await Task.Delay((int)recheckMs);
}
}
private static long GetRecheckMs(string prefix)
{
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 RunGoodReadsAsync()
{
using GoodReadsClient sdk = new();
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.Id))
{
List<GoodReadsBook> books = await sdk.GetAuthorsBooks(author.Url);
authorBooks[author.Name] = books;
}
await sdk.RunAsync(readingListData, authorBooks);
}
private static async Task RunScribbleHubAsync()
{
using Process process = new();
process.StartInfo = new ProcessStartInfo
{
FileName = "dotnet",
Arguments = "ScribbleHub.Project.dll",
WorkingDirectory = AppContext.BaseDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
process.OutputDataReceived += (_, args) =>
{
if (!string.IsNullOrEmpty(args.Data))
Log($"[ScribbleHub.Project] {args.Data}");
};
process.ErrorDataReceived += (_, args) =>
{
if (!string.IsNullOrEmpty(args.Data))
LogError($"[ScribbleHub.Project] {args.Data}");
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
await process.WaitForExitAsync();
if (process.ExitCode != 0)
LogError($"[ScribbleHub.Project] Exited with code {process.ExitCode}");
}
private static 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.");
return new LiteroticaClient(username, password).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");
using 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;
}
}
}