-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
409 lines (367 loc) · 15.4 KB
/
Program.cs
File metadata and controls
409 lines (367 loc) · 15.4 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
using Optimarr.Services;
using Optimarr.Controllers;
using Optimarr.Data;
using Optimarr.Middleware;
using Optimarr.Models;
using System.Text.Json.Serialization;
using Serilog;
using Serilog.Events;
using Microsoft.EntityFrameworkCore;
using System.Linq;
// Configure Serilog
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithEnvironmentName()
.Enrich.WithMachineName()
.Enrich.WithThreadId()
.WriteTo.Console(
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}")
.WriteTo.File(
path: "logs/optimarr-.log",
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 30,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
try
{
Log.Information("Starting optimarr application");
var builder = WebApplication.CreateBuilder(args);
// Ensure required directories exist and are writable
var contentRoot = builder.Environment.ContentRootPath;
var configDir = Path.Combine(contentRoot, "config");
var dataDir = Path.Combine(contentRoot, "data");
var logsDir = Path.Combine(contentRoot, "logs");
// Create directories if they don't exist and verify write permissions
var directoriesToCheck = new[]
{
new { Path = configDir, Name = "config", ReadOnly = true },
new { Path = dataDir, Name = "data", ReadOnly = false },
new { Path = logsDir, Name = "logs", ReadOnly = false }
};
var errors = new List<string>();
foreach (var dir in directoriesToCheck)
{
try
{
// Create directory if it doesn't exist
if (!Directory.Exists(dir.Path))
{
Directory.CreateDirectory(dir.Path);
Log.Information("Created {Name} directory: {Path}", dir.Name, dir.Path);
}
else
{
Log.Information("{Name} directory exists: {Path}", dir.Name, dir.Path);
}
// Check write permissions (skip for read-only config)
if (!dir.ReadOnly)
{
var testFile = Path.Combine(dir.Path, ".write-test");
try
{
// Try to write a test file
File.WriteAllText(testFile, DateTime.UtcNow.ToString("O"));
File.Delete(testFile);
Log.Information("{Name} directory is writable: {Path}", dir.Name, dir.Path);
}
catch (UnauthorizedAccessException ex)
{
var error = $"{dir.Name} directory is not writable: {dir.Path}. Error: {ex.Message}";
errors.Add(error);
Log.Error(ex, "Permission denied for {Name} directory: {Path}", dir.Name, dir.Path);
}
catch (Exception ex)
{
var error = $"{dir.Name} directory write test failed: {dir.Path}. Error: {ex.Message}";
errors.Add(error);
Log.Error(ex, "Failed to write test file in {Name} directory: {Path}", dir.Name, dir.Path);
}
}
else
{
// For read-only directories, just check if it exists and is readable
if (!Directory.Exists(dir.Path))
{
var error = $"{dir.Name} directory does not exist and could not be created: {dir.Path}";
errors.Add(error);
Log.Error("{Name} directory does not exist: {Path}", dir.Name, dir.Path);
}
else
{
Log.Information("{Name} directory is readable: {Path}", dir.Name, dir.Path);
}
}
}
catch (Exception ex)
{
var error = $"Failed to create or access {dir.Name} directory: {dir.Path}. Error: {ex.Message}";
errors.Add(error);
Log.Error(ex, "Failed to create or access {Name} directory: {Path}", dir.Name, dir.Path);
}
}
// If there are errors, throw an exception with all error messages
if (errors.Any())
{
var errorMessage = "Directory permission errors detected:\n" + string.Join("\n", errors);
Log.Fatal(errorMessage);
throw new InvalidOperationException(errorMessage);
}
// Configure appsettings.json location - check config folder first, then root
var configPath = Path.Combine(builder.Environment.ContentRootPath, "config", "appsettings.json");
var rootConfigPath = Path.Combine(builder.Environment.ContentRootPath, "appsettings.json");
try
{
// If config folder doesn't have appsettings.json but root does, copy it (if config is writable)
if (!File.Exists(configPath) && File.Exists(rootConfigPath))
{
try
{
// Try to copy from root to config (only works if config folder is writable)
File.Copy(rootConfigPath, configPath, overwrite: false);
Log.Information("Copied appsettings.json from root to config folder");
}
catch (UnauthorizedAccessException)
{
// Config folder is read-only, that's okay - we'll use root config
Log.Information("Config folder is read-only, using appsettings.json from root");
}
catch (Exception ex)
{
Log.Warning(ex, "Could not copy appsettings.json to config folder, will use root config");
}
}
// Load config from config folder if it exists
if (File.Exists(configPath))
{
builder.Configuration.AddJsonFile(configPath, optional: false, reloadOnChange: true);
Log.Information("Loaded appsettings.json from config folder: {ConfigPath}", configPath);
}
// Also load from root if it exists (for development or if config folder doesn't have it)
else if (File.Exists(rootConfigPath))
{
builder.Configuration.AddJsonFile(rootConfigPath, optional: true, reloadOnChange: true);
Log.Information("Loaded appsettings.json from root: {RootConfigPath}", rootConfigPath);
}
else
{
// If neither exists, log a warning (but don't fail - ASP.NET Core has defaults)
Log.Warning("No appsettings.json found in config folder ({ConfigPath}) or root ({RootConfigPath}). Using default configuration.", configPath, rootConfigPath);
}
}
catch (Exception ex)
{
Log.Error(ex, "Error loading appsettings.json. The application will continue with default configuration.");
// Don't throw - ASP.NET Core can work without appsettings.json
}
// Use Serilog for logging
builder.Host.UseSerilog();
// Add services to the container
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
// Configure Kestrel server options for long-running requests (10 minutes)
builder.Services.Configure<Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions>(options =>
{
options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(10);
options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(10);
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{
Title = "Optimarr API",
Version = "v1",
Description = "Media Optimization API with Servarr Integration"
});
});
// Configure database (data directory already created above)
var dbPath = Path.Combine(builder.Environment.ContentRootPath, "data", "optimarr.db");
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlite($"Data Source={dbPath}"));
builder.Services.Configure<ServarrOptions>(builder.Configuration.GetSection("Servarr"));
// Register application services
builder.Services.AddScoped<VideoAnalyzerService>(sp =>
new VideoAnalyzerService(
sp.GetRequiredService<IConfiguration>(),
sp.GetService<ILogger<VideoAnalyzerService>>(),
sp.GetRequiredService<AppDbContext>()));
builder.Services.AddScoped<LibraryScannerService>();
builder.Services.AddSingleton<SonarrService>();
builder.Services.AddSingleton<ISonarrService>(sp => sp.GetRequiredService<SonarrService>());
builder.Services.AddSingleton<IServarrService>(sp => sp.GetRequiredService<SonarrService>());
builder.Services.AddSingleton<RadarrService>();
builder.Services.AddSingleton<IRadarrService>(sp => sp.GetRequiredService<RadarrService>());
builder.Services.AddSingleton<IServarrService>(sp => sp.GetRequiredService<RadarrService>());
builder.Services.AddScoped<ServarrSyncService>();
builder.Services.AddScoped<VideoServarrMatcherService>();
builder.Services.AddSingleton<VideoMatchingProgressService>();
builder.Services.AddSingleton<JellyfinService>(sp =>
new JellyfinService(sp.GetRequiredService<IConfiguration>(),
sp.GetService<ILogger<JellyfinService>>()));
// Register background services
builder.Services.AddHostedService<DatabaseMigrationService>();
builder.Services.AddHostedService<PlaybackSyncService>();
builder.Services.AddHostedService<ProcessingRescanService>();
// CORS — allow only explicitly configured origins (S3)
var allowedOrigins = builder.Configuration
.GetSection("Cors:AllowedOrigins")
.Get<string[]>() ?? Array.Empty<string>();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowConfigured", policy =>
{
if (allowedOrigins.Length == 0)
{
// No origins configured — restrict to localhost only (safe default)
policy.WithOrigins(
"http://localhost:5000", "http://localhost:8080",
"http://127.0.0.1:5000", "http://127.0.0.1:8080")
.AllowAnyMethod()
.AllowAnyHeader();
}
else
{
policy.WithOrigins(allowedOrigins)
.AllowAnyMethod()
.AllowAnyHeader();
}
});
});
var app = builder.Build();
// Verify all required directories exist
var requiredDirs = new[] { configDir, dataDir, logsDir };
var missingDirs = requiredDirs.Where(dir => !Directory.Exists(dir)).ToList();
if (missingDirs.Any())
{
Log.Warning("Some required directories are missing: {MissingDirs}", string.Join(", ", missingDirs));
foreach (var dir in missingDirs)
{
try
{
Directory.CreateDirectory(dir);
Log.Information("Created missing directory: {Dir}", dir);
}
catch (Exception ex)
{
Log.Error(ex, "Failed to create directory: {Dir}", dir);
}
}
}
else
{
Log.Information("All required directories verified: config, data, logs");
}
// Database migration is handled by DatabaseMigrationService
// No need to call EnsureCreated here - migrations will handle it
// Check MediaInfo CLI tool availability
try
{
Log.Information("Checking MediaInfo CLI tool availability...");
var processStartInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = "mediainfo",
Arguments = "--Version",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
try
{
using var process = System.Diagnostics.Process.Start(processStartInfo);
if (process != null)
{
var output = process.StandardOutput.ReadToEnd();
var error = process.StandardError.ReadToEnd();
process.WaitForExit();
if (process.ExitCode == 0 && !string.IsNullOrWhiteSpace(output))
{
Log.Information("✓ MediaInfo CLI tool is available. Version: {Version}", output.Trim());
}
else
{
Log.Error("✗ MediaInfo CLI tool failed. Exit code: {ExitCode}, Error: {Error}",
process.ExitCode, error);
}
}
else
{
Log.Error("✗ Failed to start mediainfo process");
}
}
catch (System.ComponentModel.Win32Exception ex)
{
Log.Error(ex, "✗ MediaInfo CLI tool not found. Make sure 'mediainfo' is installed and in PATH.");
}
catch (Exception ex)
{
Log.Error(ex, "✗ Error checking MediaInfo CLI: {Message}", ex.Message);
}
}
catch (Exception ex)
{
Log.Warning(ex, "Error checking MediaInfo CLI availability");
}
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Optimarr API v1");
});
}
// S8: global API exception handling in JSON format without stack trace leakage.
app.UseExceptionHandler(exceptionApp =>
{
exceptionApp.Run(async context =>
{
var exceptionFeature = context.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerPathFeature>();
if (exceptionFeature?.Error != null)
{
Log.Error(
exceptionFeature.Error,
"Unhandled exception for request path {Path}",
exceptionFeature.Path);
}
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new { error = "An internal error occurred. Check logs for details." });
});
});
app.UseCors("AllowConfigured");
// API key authentication — runs after CORS so preflight OPTIONS pass through (S7)
app.UseMiddleware<ApiKeyMiddleware>();
// Serve static files (web UI)
app.UseDefaultFiles();
app.UseStaticFiles();
// Security hardening headers (Part E)
app.Use(async (context, next) =>
{
context.Response.Headers.Append("X-Content-Type-Options", "nosniff");
context.Response.Headers.Append("X-Frame-Options", "SAMEORIGIN");
await next();
});
app.UseAuthorization();
app.MapControllers();
// Fallback to index.html for SPA routing
app.MapFallbackToFile("index.html");
Log.Information("optimarr application started successfully");
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}