-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
295 lines (246 loc) · 9.48 KB
/
Program.cs
File metadata and controls
295 lines (246 loc) · 9.48 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
using Microsoft.Extensions.Hosting.WindowsServices;
using System.Text.Json;
using System.Xml.Linq;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddWindowsService();
var logDirectory = Path.Combine(AppContext.BaseDirectory, "logs");
Directory.CreateDirectory(logDirectory);
var logFilePath = Path.Combine(logDirectory, $"app-{DateTime.UtcNow:yyyyMMdd}.log");
// Keep only recent log files.
CleanupOldLogs(logDirectory, TimeSpan.FromDays(7));
static string LogLine(string level, string message) => $"{DateTimeOffset.UtcNow:O} [{level}] {message}{Environment.NewLine}";
void LogInfo(string message)
{
File.AppendAllText(logFilePath, LogLine("INFO", message));
if (message.Contains("file_path=", StringComparison.Ordinal)
|| message.Contains("touched folder=", StringComparison.Ordinal))
{
Console.WriteLine(message);
}
}
void LogError(string message, Exception? ex = null)
{
var fullMessage = ex is null ? message : $"{message} | {ex.GetType().Name}: {ex.Message}{Environment.NewLine}{ex.StackTrace}";
File.AppendAllText(logFilePath, LogLine("ERROR", fullMessage));
}
void CleanupOldLogs(string directory, TimeSpan retention)
{
try
{
foreach (var file in Directory.EnumerateFiles(directory, "app-*.log", SearchOption.TopDirectoryOnly))
{
DateTime lastWriteUtc;
try
{
lastWriteUtc = File.GetLastWriteTimeUtc(file);
}
catch
{
continue;
}
if (DateTime.UtcNow - lastWriteUtc <= retention)
continue;
try
{
File.Delete(file);
}
catch
{
// ignore retention cleanup failures
}
}
}
catch
{
// ignore retention cleanup failures
}
}
var app = builder.Build();
var plexBaseUrl = Environment.GetEnvironmentVariable("PLEX_BASEURL")?.Trim();
var plexToken = Environment.GetEnvironmentVariable("PLEX_TOKEN")?.Trim();
var plexHttp = new HttpClient
{
Timeout = TimeSpan.FromSeconds(10)
};
static async Task<string?> TryResolveFilePathFromPlexAsync(
HttpClient http,
string plexBaseUrl,
string plexToken,
string ratingKey,
string requestId,
Action<string> logInfo,
Action<string, Exception?> logError)
{
try
{
var baseUri = new Uri(plexBaseUrl.EndsWith('/') ? plexBaseUrl : plexBaseUrl + "/", UriKind.Absolute);
var requestUri = new Uri(baseUri, $"library/metadata/{Uri.EscapeDataString(ratingKey)}?X-Plex-Token={Uri.EscapeDataString(plexToken)}");
using var response = await http.GetAsync(requestUri);
if (!response.IsSuccessStatusCode)
{
logInfo($"request={requestId} plex_lookup_failed status={(int)response.StatusCode}");
return null;
}
var xml = await response.Content.ReadAsStringAsync();
var doc = XDocument.Parse(xml);
var file = doc
.Descendants("Part")
.Select(x => (string?)x.Attribute("file"))
.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x));
return file;
}
catch (Exception ex)
{
logError($"request={requestId} plex_lookup_error ratingKey=\"{ratingKey}\"", ex);
return null;
}
}
static (string? ratingKey, string? metadataKey) TryGetMetadataPointers(JsonElement root)
{
if (!root.TryGetProperty("Metadata", out var metadata))
return (null, null);
var ratingKey = metadata.TryGetProperty("ratingKey", out var ratingKeyProp) ? ratingKeyProp.GetString() : null;
var metadataKey = metadata.TryGetProperty("key", out var keyProp) ? keyProp.GetString() : null;
return (ratingKey, metadataKey);
}
static string? TryGetFilePathFromPayload(JsonElement root)
{
if (!root.TryGetProperty("Metadata", out var metadata)
|| !metadata.TryGetProperty("Media", out var media)
|| media.ValueKind != JsonValueKind.Array
|| media.GetArrayLength() == 0)
{
return null;
}
var media0 = media[0];
if (!media0.TryGetProperty("Part", out var part)
|| part.ValueKind != JsonValueKind.Array
|| part.GetArrayLength() == 0)
{
return null;
}
var part0 = part[0];
if (!part0.TryGetProperty("file", out var fileProp))
return null;
return fileProp.GetString();
}
static bool TryTouchTargetFolder(string filePath, out string? touchedFolder)
{
touchedFolder = null;
if (!File.Exists(filePath))
return false;
var folder = Path.GetDirectoryName(filePath);
if (string.IsNullOrWhiteSpace(folder) || !Directory.Exists(folder))
return false;
// Plex TV paths commonly include "Season XX" folders. Touch the show folder instead.
var folderName = Path.GetFileName(Path.TrimEndingDirectorySeparator(folder));
if (!string.IsNullOrWhiteSpace(folderName)
&& folderName.StartsWith("Season", StringComparison.OrdinalIgnoreCase))
{
var parent = Directory.GetParent(folder)?.FullName;
if (!string.IsNullOrWhiteSpace(parent) && Directory.Exists(parent))
folder = parent;
}
Directory.SetLastWriteTimeUtc(folder, DateTime.UtcNow);
touchedFolder = folder;
return true;
}
async Task<IResult> HandleWebhook(HttpRequest request)
{
var requestId = Guid.NewGuid().ToString("N");
LogInfo($"request={requestId} webhook_received path={request.Path}");
if (!request.HasFormContentType)
{
LogError($"request={requestId} invalid_content_type contentType={request.ContentType}", null);
return Results.BadRequest("Invalid content type");
}
var form = await request.ReadFormAsync();
LogInfo($"request={requestId} content_type={request.ContentType}");
LogInfo($"request={requestId} form_keys=[{string.Join(',', form.Keys)}]");
var payloadRaw = form["payload"].ToString();
if (string.IsNullOrWhiteSpace(payloadRaw))
{
LogError($"request={requestId} missing_payload", null);
return Results.BadRequest("Missing payload");
}
LogInfo($"request={requestId} payload_length={payloadRaw.Length}");
//Console.WriteLine($"request={requestId} payload_begin");
//Console.WriteLine(payloadRaw.ToString());
//Console.WriteLine($"request={requestId} payload_end");
JsonDocument payload;
try
{
payload = JsonDocument.Parse(payloadRaw);
}
catch (JsonException)
{
LogError($"request={requestId} invalid_payload_json", null);
return Results.BadRequest("Invalid payload JSON");
}
using (payload)
{
var root = payload.RootElement;
if (!root.TryGetProperty("event", out var eventProp))
{
LogError($"request={requestId} missing_event", null);
return Results.BadRequest("Missing event");
}
var eventType = eventProp.GetString();
LogInfo($"request={requestId} event={eventType}");
// Resolve full filesystem path:
// 1) from the webhook payload (if present)
// 2) otherwise via Plex API lookup using the ratingKey (requires env vars)
var filePath = TryGetFilePathFromPayload(root);
if (!string.IsNullOrWhiteSpace(filePath))
{
LogInfo($"request={requestId} file_path=\"{filePath}\"");
}
else
{
var (ratingKey, metadataKey) = TryGetMetadataPointers(root);
LogInfo($"request={requestId} file_path_not_provided metadata_key=\"{metadataKey}\" ratingKey=\"{ratingKey}\"");
if (!string.IsNullOrWhiteSpace(ratingKey)
&& !string.IsNullOrWhiteSpace(plexBaseUrl)
&& !string.IsNullOrWhiteSpace(plexToken))
{
LogInfo($"request={requestId} plex_lookup_started ratingKey=\"{ratingKey}\"");
filePath = await TryResolveFilePathFromPlexAsync(plexHttp, plexBaseUrl, plexToken, ratingKey, requestId, LogInfo, LogError);
if (!string.IsNullOrWhiteSpace(filePath))
LogInfo($"request={requestId} plex_lookup_resolved file_path=\"{filePath}\"");
else
LogInfo($"request={requestId} plex_lookup_no_file_path");
}
else
{
LogInfo($"request={requestId} plex_lookup_skipped missing_env_or_ratingKey");
}
}
// Only trigger on play start or full watch
if (eventType is not ("media.play" or "media.scrobble"))
return Results.Ok();
if (string.IsNullOrWhiteSpace(filePath))
{
LogInfo($"request={requestId} processing_skipped_missing_file_path");
return Results.Ok();
}
LogInfo($"request={requestId} processing_started event={eventType}");
try
{
if (!TryTouchTargetFolder(filePath, out var touchedFolder))
{
LogInfo($"request={requestId} touch_skipped file_not_found_or_folder_missing file_path=\"{filePath}\"");
return Results.Ok();
}
LogInfo($"request={requestId} touched folder=\"{touchedFolder}\" file=\"{filePath}\"");
}
catch (Exception ex)
{
LogError($"request={requestId} processing_error", ex);
}
LogInfo($"request={requestId} processing_completed event={eventType}");
return Results.Ok();
}
}
app.MapPost("/webhook", (HttpRequest request) => HandleWebhook(request));
app.MapPost("/", (HttpRequest request) => HandleWebhook(request));
app.Run("http://0.0.0.0:5000");