-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1702 lines (1573 loc) · 90.2 KB
/
Copy pathProgram.cs
File metadata and controls
1702 lines (1573 loc) · 90.2 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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using PlexRequestsHosted.Components;
using MudBlazor;
using MudBlazor.Services;
using Blazored.LocalStorage;
using Blazored.SessionStorage;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Authentication;
using PlexRequestsHosted.Services.Auth;
using PlexRequestsHosted.Services.Abstractions;
using PlexRequestsHosted.Services.Implementations;
using PlexRequestsHosted.Services.MetadataProviders;
using Microsoft.EntityFrameworkCore;
using PlexRequestsHosted.Infrastructure.Data;
using System.Text;
using System.Text.Json;
using System.IO;
using System.Net.Http;
using System.Net.Security;
using PlexRequestsHosted.Shared.Enums;
using PlexRequestsHosted.Shared.DTOs;
using PlexRequestsHosted.Shared.Media;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.RateLimiting;
using PlexRequestsHosted.Utils;
using System.Threading.RateLimiting;
// Load .env if present and map PLEX_* variables to ASP.NET config keys
static void LoadDotEnvFrom(string rootPath)
{
var candidates = new[]
{
Path.Combine(rootPath, ".env"),
Path.Combine(AppContext.BaseDirectory, ".env"),
Path.Combine(Directory.GetCurrentDirectory(), ".env")
};
var path = candidates.FirstOrDefault(File.Exists);
if (path is null) return;
foreach (var raw in File.ReadAllLines(path, Encoding.UTF8))
{
var line = raw.Trim();
if (string.IsNullOrWhiteSpace(line) || line.StartsWith('#')) continue;
var idx = line.IndexOf('=');
if (idx <= 0) continue;
var key = line[..idx].Trim();
var val = line[(idx + 1)..].Trim().Trim('"');
if (string.IsNullOrWhiteSpace(key)) continue;
Environment.SetEnvironmentVariable(key, val);
// Map friendly keys to ASP.NET configuration keys
if (key.Equals("PLEX_URL", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("Plex__PrimaryServerUrl", val);
else if (key.Equals("PLEX_TOKEN", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("Plex__ServerToken", val);
else if (key.Equals("PLEX_CLIENT_IDENTIFIER", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("Plex__ClientIdentifier", val);
else if (key.Equals("PLEX_ALLOW_INVALID_CERTS", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("Plex__AllowInvalidCerts", val);
else if (key.Equals("TMDB_API_KEY", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("ApiKeys__TMDb__ApiKey", val);
else if (key.Equals("TMDB_READ_ACCESS_TOKEN", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("ApiKeys__TMDb__ReadAccessToken", val);
else if (key.Equals("ADMIN_USERNAMES", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("Admin__Usernames", val);
else if (key.Equals("DB_PATH", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("ConnectionStrings__AppDb", val);
else if (key.Equals("FULFILLMENT_ENABLED", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("Fulfillment__Enabled", val);
else if (key.Equals("FULFILLMENT_API_KEY", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("Fulfillment__ApiKey", val);
else if (key.Equals("BRIDGE_ENABLED", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("Bridge__Enabled", val);
else if (key.Equals("BRIDGE_API_KEY", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("Bridge__ApiKey", val);
else if (key.Equals("BRIDGE_EVENT_RETENTION_DAYS", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("Bridge__EventRetentionDays", val);
else if (key.Equals("DEV_AUTH_ENABLED", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("DevelopmentAuth__Enabled", val);
else if (key.Equals("DEV_AUTH_USERNAME", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("DevelopmentAuth__Username", val);
else if (key.Equals("DEV_AUTH_DISPLAY_NAME", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("DevelopmentAuth__DisplayName", val);
else if (key.Equals("DEV_AUTH_EMAIL", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("DevelopmentAuth__Email", val);
else if (key.Equals("DEV_AUTH_AVATAR_URL", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("DevelopmentAuth__AvatarUrl", val);
else if (key.Equals("DEV_AUTH_ROLES", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("DevelopmentAuth__Roles", val);
else if (key.Equals("DEV_AUTH_TOKEN", StringComparison.OrdinalIgnoreCase))
Environment.SetEnvironmentVariable("DevelopmentAuth__Token", val);
}
}
// Preload .env before configuration is built so env vars flow into builder.Configuration
LoadDotEnvFrom(Directory.GetCurrentDirectory());
var builder = WebApplication.CreateBuilder(args);
// Also attempt loading after, using content root
LoadDotEnvFrom(builder.Environment.ContentRootPath);
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
// UI and storage services for client interactivity
builder.Services.AddMudServices(config =>
{
// Feedback belongs away from the primary header controls. Bottom-left keeps short-lived actions from
// covering the notification bell/avatar and the compact styling prevents a toast stack becoming a wall.
config.SnackbarConfiguration.PositionClass = Defaults.Classes.Position.BottomLeft;
config.SnackbarConfiguration.PreventDuplicates = true;
config.SnackbarConfiguration.NewestOnTop = false;
config.SnackbarConfiguration.ShowCloseIcon = true;
config.SnackbarConfiguration.VisibleStateDuration = 4500;
config.SnackbarConfiguration.ShowTransitionDuration = 180;
config.SnackbarConfiguration.HideTransitionDuration = 180;
config.SnackbarConfiguration.SnackbarVariant = Variant.Filled;
config.SnackbarConfiguration.MaxDisplayedSnackbars = 3;
});
builder.Services.AddBlazoredLocalStorage();
builder.Services.AddBlazoredSessionStorage();
// HTTP client for services that depend on HttpClient
builder.Services.AddHttpClient();
// HttpContext accessor for cookie sign-in from AuthStateProvider
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton(TimeProvider.System);
// Public extension endpoints authenticate with single-purpose device tokens rather than the browser's
// application cookie. Bound abusive guessing and upload loops before either reaches SQLite.
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy("firefox-capture-pair", context => RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 10,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 0,
AutoReplenishment = true
}));
options.AddPolicy("firefox-capture-ingest", context => RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 120,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 0,
AutoReplenishment = true
}));
});
// Behind a reverse proxy / Cloudflare Tunnel (TLS at the edge, plain HTTP to the origin): trust the
// forwarded scheme so HttpsRedirection doesn't loop, the auth cookie gets its Secure flag, and Plex
// OAuth redirect URLs come out as https. cloudflared/the proxy is the only origin client, so trust
// all proxies. If you expose the origin directly to untrusted networks, restrict KnownProxies instead.
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownIPNetworks.Clear();
options.KnownProxies.Clear();
});
// Session support for OAuth PIN storage
// Persist Data Protection keys so session/cookie protection can be unprotected across app restarts
var keysDir = Path.Combine(builder.Environment.ContentRootPath, "keys");
Directory.CreateDirectory(keysDir);
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(keysDir))
.SetApplicationName("PlexRequestsHosted");
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
// Options/config
builder.Services.Configure<PlexRequestsHosted.Services.Implementations.PlexConfiguration>(
builder.Configuration.GetSection("Plex"));
builder.Services.AddMemoryCache();
// Core domain services
// Configure typed HttpClient for PlexApiService with optional invalid cert allowance (for self-signed or IP-based SSL)
var plexSection = builder.Configuration.GetSection("Plex");
var allowInvalidCerts = plexSection.GetValue<bool>("AllowInvalidCerts");
// Cap the per-request timeout so a slow/stalled Plex call can never freeze a Blazor render for the
// default 100s. Plex service methods catch the resulting cancellation and degrade to "unavailable".
builder.Services.AddHttpClient<IPlexApiService, PlexApiService>(c => c.Timeout = TimeSpan.FromSeconds(15))
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) =>
allowInvalidCerts ? true : errors == SslPolicyErrors.None
});
builder.Services.AddHttpClient<IPlexArtworkService, PlexArtworkService>(c => c.Timeout = TimeSpan.FromSeconds(15))
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) =>
allowInvalidCerts ? true : errors == SslPolicyErrors.None
});
// Plex music library access (artist/album/track) — foundation for music requests.
builder.Services.AddHttpClient<PlexRequestsHosted.Services.Implementations.IPlexMusicService, PlexRequestsHosted.Services.Implementations.PlexMusicService>(c => c.Timeout = TimeSpan.FromSeconds(15))
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) =>
allowInvalidCerts ? true : errors == SslPolicyErrors.None
});
builder.Services.AddScoped<IMediaRequestService, MediaRequestService>();
builder.Services.AddScoped<IMediaIdentityService, MediaIdentityService>();
builder.Services.AddScoped<IMusicSettingsService, MusicSettingsService>();
builder.Services.AddScoped<IMusicDirectAcquisitionResolver, YouTubeMusicDirectAcquisitionResolver>();
builder.Services.AddSingleton<IMediaModule, MovieMediaModule>();
builder.Services.AddSingleton<IMediaModule, TelevisionMediaModule>();
builder.Services.AddSingleton<IMediaModule, AnimeMediaModule>();
builder.Services.AddSingleton<IMediaModule, MusicMediaModule>();
builder.Services.AddSingleton<IMediaModuleRegistry, MediaModuleRegistry>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Abstractions.ISeasonAvailabilityEvaluator, PlexRequestsHosted.Services.Implementations.SeasonAvailabilityEvaluator>();
builder.Services.AddScoped<IFulfillmentQueue, FulfillmentQueue>();
// Live download telemetry: the store is a singleton (shared by worker progress reports and the admin
// circuit); the read model service is scoped (needs the DbContext).
builder.Services.AddSingleton<PlexRequestsHosted.Services.Abstractions.IDownloadTelemetryStore, PlexRequestsHosted.Services.Implementations.DownloadTelemetryStore>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Abstractions.IDownloadMonitorService, PlexRequestsHosted.Services.Implementations.DownloadMonitorService>();
builder.Services.AddScoped<IDiscordLinkService, DiscordLinkService>();
builder.Services.AddScoped<IBridgeOutboxService, BridgeOutboxService>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.IMediaIssueService, PlexRequestsHosted.Services.Implementations.MediaIssueService>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.IQualityRuleService, PlexRequestsHosted.Services.Implementations.QualityRuleService>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.IDownloadPreferencesService, PlexRequestsHosted.Services.Implementations.DownloadPreferencesService>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.ILibraryOrganizationPreferencesService, PlexRequestsHosted.Services.Implementations.LibraryOrganizationPreferencesService>();
builder.Services.AddSingleton<PlexRequestsHosted.Services.Implementations.IFolderBrowserService, PlexRequestsHosted.Services.Implementations.FolderBrowserService>();
// Network shares (NAS/network drives): CRUD service + live mount-status store + the background service
// that mounts them read-only so the folder browser can list them. The same instance is exposed as
// INetworkMountController so an admin save/test can trigger an immediate reconcile.
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.INetworkShareService, PlexRequestsHosted.Services.Implementations.NetworkShareService>();
builder.Services.AddSingleton<PlexRequestsHosted.Services.Background.INetworkMountStatusStore, PlexRequestsHosted.Services.Background.NetworkMountStatusStore>();
builder.Services.AddSingleton<PlexRequestsHosted.Services.Background.WebNetworkMountService>();
builder.Services.AddSingleton<PlexRequestsHosted.Services.Background.INetworkMountController>(sp => sp.GetRequiredService<PlexRequestsHosted.Services.Background.WebNetworkMountService>());
builder.Services.AddHostedService(sp => sp.GetRequiredService<PlexRequestsHosted.Services.Background.WebNetworkMountService>());
// Generic background-job engine + its handlers. The scheduler ticks, dispatches due jobs to the matching
// IJobHandler, and records run history. Every recurring job lives here — the four below used to be
// self-timing BackgroundServices with hardcoded Task.Delay loops, which meant no run history, no
// enable/disable, no "Run now" and no visibility in the admin Jobs panel. Their cadence now lives in
// their ScheduledJobEntity row.
builder.Services.AddScoped<PlexRequestsHosted.Services.Jobs.IJobHandler, PlexRequestsHosted.Services.Jobs.MissingSearchJob>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Jobs.IJobHandler, PlexRequestsHosted.Services.Jobs.SearchTaskCleanupJob>();
// The durable job<->torrent link the reconciler joins on. Without it the link lived only in the worker's
// local file and an in-memory store, so a worker restart orphaned every in-flight download.
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.IFulfillmentTransferService, PlexRequestsHosted.Services.Implementations.FulfillmentTransferService>();
// Re-derives tier + format score for already-imported files from their stored release names, so editing a
// custom format reaches the library you already have and not only the next download.
builder.Services.AddScoped<PlexRequestsHosted.Services.Jobs.IJobHandler, PlexRequestsHosted.Services.Jobs.RecomputeFormatScoresJob>();
// Air-date calendar: one job keeps it current from live metadata, the other queues searches when an
// episode's window opens and tells the scheduler when the next one is due.
builder.Services.AddScoped<PlexRequestsHosted.Services.Jobs.IJobHandler, PlexRequestsHosted.Services.Jobs.CalendarRefreshJob>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Jobs.IJobHandler, PlexRequestsHosted.Services.Jobs.AirDateMonitorJob>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.IMonitoringPreferencesService, PlexRequestsHosted.Services.Implementations.MonitoringPreferencesService>();
// Per-series monitoring controls — the first way anything can change Monitored after a request is created.
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.ISeriesMonitoringService, PlexRequestsHosted.Services.Implementations.SeriesMonitoringService>();
// User-defined release scoring rules, scored per quality profile.
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.ICustomFormatService, PlexRequestsHosted.Services.Implementations.CustomFormatService>();
// Registered concretely as well as via IJobHandler: the admin "Upgrade now" action calls straight into it
// rather than keeping a second copy of the same logic.
builder.Services.AddScoped<PlexRequestsHosted.Services.Jobs.UpgradeScanJob>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Jobs.IJobHandler>(sp => sp.GetRequiredService<PlexRequestsHosted.Services.Jobs.UpgradeScanJob>());
// Backstop that requeues/parks jobs stranded by a dead downloader.
builder.Services.AddScoped<PlexRequestsHosted.Services.Jobs.IJobHandler, PlexRequestsHosted.Services.Background.FulfillmentReaperService>();
// Repairs the narrow crash/enqueue gap where a request is durably Approved but has no job history at all.
builder.Services.AddScoped<PlexRequestsHosted.Services.Jobs.IJobHandler, PlexRequestsHosted.Services.Jobs.ApprovedRequestRepairJob>();
// Keeps the DB-backed Plex availability index fresh (per-season episode presence + aged-out removals).
builder.Services.AddScoped<PlexRequestsHosted.Services.Jobs.IJobHandler, PlexRequestsHosted.Services.Background.AvailabilityRefreshService>();
// Safety net: auto-mark requests Available when their content appears on Plex by ANY means.
builder.Services.AddScoped<PlexRequestsHosted.Services.Jobs.IJobHandler, PlexRequestsHosted.Services.Background.AvailabilityReconciliationService>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Abstractions.IJobAdminService, PlexRequestsHosted.Services.Jobs.JobAdminService>();
// Quality tiers/profiles: seeds the catalog + stock profiles and converts the legacy quality rules.
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.QualityProfileSeeder>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.IQualityProfileService, PlexRequestsHosted.Services.Implementations.QualityProfileService>();
// Interactive search + the failure blocklist that stops a retry re-grabbing the same broken torrent.
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.IInteractiveSearchService, PlexRequestsHosted.Services.Implementations.InteractiveSearchService>();
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.IReleaseBlocklistService, PlexRequestsHosted.Services.Implementations.ReleaseBlocklistService>();
// Resolves the downloader's trending-title feed to real metadata for the home page's Recommended row.
builder.Services.AddScoped<PlexRequestsHosted.Services.Implementations.IRecommendedFeedService, PlexRequestsHosted.Services.Implementations.RecommendedFeedService>();
// Per-indexer admin control (enable/priority) + rolling health from downloader search telemetry.
builder.Services.AddScoped<PlexRequestsHosted.Services.Abstractions.IIndexerAdminService, PlexRequestsHosted.Services.Implementations.IndexerAdminService>();
builder.Services.Configure<PlexRequestsHosted.Infrastructure.Capture.FirefoxCaptureOptions>(
builder.Configuration.GetSection(PlexRequestsHosted.Infrastructure.Capture.FirefoxCaptureOptions.Section));
builder.Services.AddSingleton(
PlexRequestsHosted.Services.Implementations.FirefoxExtensionArchive.Inspect(builder.Environment.ContentRootPath));
builder.Services.AddScoped<PlexRequestsHosted.Services.Abstractions.IFirefoxCaptureService,
PlexRequestsHosted.Services.Implementations.FirefoxCaptureService>();
// Optional, rebuildable release catalog. It is a singleton writer over short-lived contexts so concurrent
// worker batches cannot race unique infohash/source constraints. Disabled by default during shadow rollout.
builder.Services.Configure<PlexRequestsHosted.Infrastructure.Catalog.CatalogOptions>(
builder.Configuration.GetSection(PlexRequestsHosted.Infrastructure.Catalog.CatalogOptions.Section));
builder.Services.AddSingleton<PlexRequestsHosted.Shared.Releases.IReleaseParser,
PlexRequestsHosted.Shared.Releases.ReleaseParser>();
builder.Services.AddSingleton<PlexRequestsHosted.Services.Abstractions.IReleaseCatalogService,
PlexRequestsHosted.Services.Implementations.ReleaseCatalogService>();
// Database maintenance: overview/backup/targeted cleanup/factory reset (the System → Database panel).
builder.Services.AddScoped<PlexRequestsHosted.Services.Abstractions.IDatabaseAdminService, PlexRequestsHosted.Services.Implementations.DatabaseAdminService>();
builder.Services.AddHostedService<PlexRequestsHosted.Services.Background.JobSchedulerService>();
builder.Services.AddHostedService<PlexRequestsHosted.Services.Background.CatalogMaintenanceWorker>();
// AuthN/AuthZ
builder.Services
.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultAuthenticateScheme = "Cookies";
options.DefaultChallengeScheme = "Cookies";
})
.AddCookie("Cookies", o =>
{
o.LoginPath = "/login";
o.AccessDeniedPath = "/login";
o.LogoutPath = "/logout";
o.SlidingExpiration = true;
o.ExpireTimeSpan = TimeSpan.FromHours(8);
o.Cookie.HttpOnly = true;
o.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
o.Cookie.SameSite = SameSiteMode.Lax;
o.Cookie.Name = "PlexRequestsAuth";
o.ReturnUrlParameter = "returnUrl";
o.Events.OnRedirectToLogin = context =>
{
// Prevent redirect loops by checking if already on login page
if (context.Request.Path.StartsWithSegments("/login"))
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
}
context.Response.Redirect(context.RedirectUri);
return Task.CompletedTask;
};
o.Events.OnRedirectToAccessDenied = context =>
{
context.Response.StatusCode = 403;
return Task.CompletedTask;
};
});
builder.Services.AddAuthorization(options =>
{
// Pages are secured by default via `@attribute [Authorize]` in Components/_Imports.razor
// (enforced by AuthorizeRouteView); anonymous pages opt out with [AllowAnonymous].
options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});
builder.Services.AddScoped<CustomAuthStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(sp => sp.GetRequiredService<CustomAuthStateProvider>());
builder.Services.AddScoped<IClaimsTransformation, UserAccessClaimsTransformation>();
// App service registrations (stubs for now)
// (Removed duplicate registrations of IPlexApiService/IMediaRequestService)
builder.Services.AddScoped<IPlexAuthService, PlexAuthService>();
builder.Services.AddScoped<IUserProfileService, UserProfileService>();
builder.Services.AddScoped<IUserAccessService, UserAccessService>();
builder.Services.AddScoped<IUserQuotaService, UserQuotaService>();
builder.Services.AddScoped<IUserAdministrationService, UserAdministrationService>();
builder.Services.AddScoped<UserGroupSeeder>();
builder.Services.AddScoped<IToastService, ToastService>();
builder.Services.AddScoped<INotificationPreferenceService, NotificationPreferenceService>();
builder.Services.AddScoped<IThemeService, ThemeService>();
builder.Services.AddScoped<IAuthService, AuthService>();
// In-process notification pub/sub (replaces the SignalR client round-trip) + persistence-backed service
builder.Services.AddSingleton<PlexRequestsHosted.Services.Abstractions.INotificationBroker, PlexRequestsHosted.Services.Implementations.NotificationBroker>();
builder.Services.AddSingleton<PlexRequestsHosted.Services.Abstractions.INotificationService, PlexRequestsHosted.Services.Implementations.NotificationService>();
// Metadata providers (modular; the router picks one per media type with a keyless fallback).
// Singleton so its TMDbClient (and internal HttpClient) is built once, not per scope.
builder.Services.AddSingleton<TmdbMetadataProvider>();
builder.Services.AddScoped<ITmdbEpisodeGroupImportService, TmdbEpisodeGroupImportService>();
builder.Services.AddScoped<TraktMetadataProvider>();
builder.Services.AddScoped<SeedMetadataProvider>();
builder.Services.AddScoped<TvdbMetadataProvider>();
// MusicBrainz requires a descriptive User-Agent; keyless -> default fallback for Music.
builder.Services.AddSingleton<IMusicBrainzRateGate, MusicBrainzRateGate>();
builder.Services.AddHttpClient<IListenBrainzDiscoveryClient, ListenBrainzDiscoveryClient>(c =>
{
c.BaseAddress = new Uri("https://api.listenbrainz.org/");
c.DefaultRequestHeaders.UserAgent.ParseAdd("PlexRequests/1.0 (https://github.com/kalebbroo/PlexRequests)");
c.Timeout = TimeSpan.FromSeconds(15);
});
builder.Services.AddHttpClient<MusicBrainzMetadataProvider>(c =>
{
c.BaseAddress = new Uri("https://musicbrainz.org/");
c.DefaultRequestHeaders.UserAgent.ParseAdd("PlexRequests/1.0 (https://github.com/kalebbroo/PlexRequests)");
c.Timeout = TimeSpan.FromSeconds(20);
});
// Anonymous, read-only YouTube Music web catalog client. This never requests or consumes media streams;
// acquisition remains the downloader's independent indexer responsibility.
builder.Services.AddHttpClient<YouTubeMusicMetadataProvider>(c =>
{
c.BaseAddress = new Uri("https://music.youtube.com/");
c.DefaultRequestHeaders.UserAgent.ParseAdd(
"Mozilla/5.0 (X11; Linux x86_64; rv:142.0) Gecko/20100101 Firefox/142.0");
c.Timeout = TimeSpan.FromSeconds(20);
});
builder.Services.AddScoped<IMusicDiscoveryService, MusicDiscoveryService>();
builder.Services.AddScoped<IMusicCatalogSearchService, MusicCatalogSearchService>();
builder.Services.AddScoped<MetadataRouter>();
builder.Services.AddScoped<IMetadataProviderFactory, MetadataProviderFactory>();
// Background refresher for stale metadata-cache rows (stale-while-revalidate).
builder.Services.AddSingleton<PlexRequestsHosted.Services.Abstractions.IMetadataRefreshCoordinator,
PlexRequestsHosted.Services.Implementations.MetadataRefreshCoordinator>();
// The active provider wrapped in a DB-backed caching decorator: details/imdb/episodes are served from
// SQLite instantly and survive restarts; stale rows refresh in the background.
builder.Services.AddScoped<IMediaMetadataProvider>(sp =>
{
var innerProvider = sp.GetRequiredService<IMetadataProviderFactory>().GetDefaultProvider();
return new PlexRequestsHosted.Services.Implementations.CachingMetadataProvider(
innerProvider,
sp.GetRequiredService<IDbContextFactory<AppDbContext>>(),
sp.GetRequiredService<PlexRequestsHosted.Services.Abstractions.IMetadataRefreshCoordinator>(),
sp.GetRequiredService<IMediaIdentityService>());
});
// Persistence: SQLite. Resolve an absolute path so the DB doesn't depend on the current
// working directory (DB_PATH / ConnectionStrings:AppDb override; default is under the content root).
var configuredDbPath = builder.Configuration["ConnectionStrings:AppDb"];
var dbPath = string.IsNullOrWhiteSpace(configuredDbPath)
? Path.Combine(builder.Environment.ContentRootPath, "app.db")
: (Path.IsPathRooted(configuredDbPath)
? configuredDbPath
: Path.Combine(builder.Environment.ContentRootPath, configuredDbPath));
// Factory registration + a scoped shim: existing scoped consumers keep injecting AppDbContext, while
// the caching layer + background refreshers create their own short-lived, thread-safe contexts.
builder.Services.AddDbContextFactory<AppDbContext>(options =>
options.UseSqlite($"Data Source={dbPath}")
.AddInterceptors(new PlexRequestsHosted.Infrastructure.Data.SqlitePragmaInterceptor()));
builder.Services.AddScoped<AppDbContext>(sp =>
sp.GetRequiredService<IDbContextFactory<AppDbContext>>().CreateDbContext());
// Catalog persistence is deliberately separate from app.db: it is bounded derived data that can be
// pruned or rebuilt without touching requests, users, jobs, or application backups.
var configuredCatalogDbPath = builder.Configuration["ConnectionStrings:CatalogDb"];
var catalogDbPath = string.IsNullOrWhiteSpace(configuredCatalogDbPath)
? Path.Combine(Path.GetDirectoryName(dbPath) ?? builder.Environment.ContentRootPath, "catalog.db")
: (Path.IsPathRooted(configuredCatalogDbPath)
? configuredCatalogDbPath
: Path.Combine(builder.Environment.ContentRootPath, configuredCatalogDbPath));
builder.Services.AddDbContextFactory<PlexRequestsHosted.Infrastructure.Catalog.CatalogDbContext>(options =>
options.UseSqlite($"Data Source={catalogDbPath}")
.AddInterceptors(new PlexRequestsHosted.Infrastructure.Data.SqlitePragmaInterceptor()));
var app = builder.Build();
// Apply forwarded headers first so every downstream component (HSTS, HttpsRedirection, auth cookie,
// OAuth URL building) sees the real client scheme/IP from the proxy.
app.UseForwardedHeaders();
app.UseRateLimiter();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
// Serve static files before authentication to prevent JS/CSS from being blocked
app.UseStaticFiles();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.MapStaticAssets().AllowAnonymous();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
// Apply EF Core migrations on startup (creates the schema on first run, upgrades it thereafter).
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.Migrate();
var catalogOptions = scope.ServiceProvider
.GetRequiredService<Microsoft.Extensions.Options.IOptions<PlexRequestsHosted.Infrastructure.Catalog.CatalogOptions>>()
.Value;
if (catalogOptions.Enabled)
{
var catalog = scope.ServiceProvider
.GetRequiredService<IDbContextFactory<PlexRequestsHosted.Infrastructure.Catalog.CatalogDbContext>>();
await using var catalogDb = await catalog.CreateDbContextAsync();
await catalogDb.Database.MigrateAsync();
}
// Seed the quality-tier catalog, the stock profiles, and (first run only) convert the legacy quality
// rules into profiles + assignment rules, backfilling everything that needs a profile. Idempotent, so
// it runs on every boot and does nothing once complete. Must follow Migrate() — it writes to the tables
// that migration creates. A failure here is logged and swallowed: a seeding problem shouldn't stop the
// app from starting, and the next boot retries.
try
{
await scope.ServiceProvider.GetRequiredService<UserGroupSeeder>().SeedAsync();
await scope.ServiceProvider.GetRequiredService<PlexRequestsHosted.Services.Implementations.QualityProfileSeeder>()
.SeedAsync();
// Stock custom formats, so the panel is populated and the feature is usable on first boot rather
// than only after something happens to touch the service.
await scope.ServiceProvider.GetRequiredService<PlexRequestsHosted.Services.Implementations.ICustomFormatService>()
.SeedAsync();
// Repair torrents written off as Missing that had in fact been imported — see the note on
// CorrectMisclassifiedMissingAsync. Idempotent, so it costs one query once the data is clean.
await scope.ServiceProvider.GetRequiredService<PlexRequestsHosted.Services.Implementations.IFulfillmentTransferService>()
.CorrectMisclassifiedMissingAsync();
}
catch (Exception ex)
{
app.Services.GetRequiredService<ILoggerFactory>()
.CreateLogger("QualityProfileSeeder")
.LogError(ex, "Startup data seeding failed; it will be retried on the next start");
}
}
// Admin-only: write a consistent point-in-time SQLite backup (VACUUM INTO) and stream it to the browser.
// Cookie-authenticated (the button in Admin → System → Database links here), not part of the worker API.
app.MapGet("/api/admin/db/backup", async (PlexRequestsHosted.Services.Abstractions.IDatabaseAdminService dbAdmin) =>
{
var path = await dbAdmin.CreateBackupAsync();
return Results.File(path, "application/octet-stream", Path.GetFileName(path));
}).RequireAuthorization("AdminOnly");
app.MapGet("/api/admin/catalog/stats", async (
PlexRequestsHosted.Services.Abstractions.IReleaseCatalogService catalog,
CancellationToken cancellationToken) =>
Results.Ok(await catalog.GetStatsAsync(cancellationToken)))
.RequireAuthorization("AdminOnly");
app.MapGet("/api/admin/browser-capture/firefox-extension", (
IWebHostEnvironment environment,
PlexRequestsHosted.Services.Implementations.FirefoxExtensionInfo extension) =>
Results.File(
PlexRequestsHosted.Services.Implementations.FirefoxExtensionArchive.Create(environment.ContentRootPath),
"application/x-xpinstall",
$"plexrequests-firefox-capture-v{extension.CurrentVersion}.xpi"))
.RequireAuthorization("AdminOnly");
// Firefox capture uses a two-stage credential: an admin creates a short-lived one-time pairing code in
// the Blazor circuit, then the extension exchanges it for a revocable device token. Neither route accepts
// or returns the Firefox session cookies that got through the upstream challenge.
static string? CaptureBearerToken(HttpContext context)
{
var value = context.Request.Headers.Authorization.ToString();
return value.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)
? value[7..].Trim()
: null;
}
app.MapPost("/api/browser-capture/pair", async (
FirefoxCapturePairRequestDto body,
PlexRequestsHosted.Services.Abstractions.IFirefoxCaptureService capture,
HttpContext context,
CancellationToken cancellationToken) =>
{
context.Response.Headers.CacheControl = "no-store";
try
{
var result = await capture.RedeemPairingAsync(body, cancellationToken);
return result is null ? Results.Unauthorized() : Results.Ok(result);
}
catch (InvalidOperationException ex)
{
return Results.Conflict(new { error = ex.Message });
}
})
.AllowAnonymous()
.DisableAntiforgery()
.WithMetadata(new RequestSizeLimitAttribute(16 * 1024))
.RequireRateLimiting("firefox-capture-pair");
app.MapGet("/api/browser-capture/status", async (
PlexRequestsHosted.Services.Abstractions.IFirefoxCaptureService capture,
HttpContext context,
CancellationToken cancellationToken) =>
{
context.Response.Headers.CacheControl = "no-store";
var token = CaptureBearerToken(context);
if (token is null) return Results.Unauthorized();
var result = await capture.GetConnectionAsync(token, cancellationToken);
return result is null ? Results.Unauthorized() : Results.Ok(result);
})
.AllowAnonymous()
.DisableAntiforgery()
.RequireRateLimiting("firefox-capture-ingest");
app.MapPost("/api/browser-capture/heartbeat", async (
FirefoxCaptureHeartbeatDto body,
PlexRequestsHosted.Services.Abstractions.IFirefoxCaptureService capture,
HttpContext context,
CancellationToken cancellationToken) =>
{
context.Response.Headers.CacheControl = "no-store";
var token = CaptureBearerToken(context);
if (token is null) return Results.Unauthorized();
try
{
var result = await capture.RecordHeartbeatAsync(token, body, cancellationToken);
return result is null ? Results.Unauthorized() : Results.Ok(result);
}
catch (ArgumentException ex)
{
return Results.BadRequest(new { error = ex.Message });
}
})
.AllowAnonymous()
.DisableAntiforgery()
.WithMetadata(new RequestSizeLimitAttribute(4 * 1024))
.RequireRateLimiting("firefox-capture-ingest");
app.MapGet("/api/browser-capture/pending-details", async (
[FromQuery] long? after,
[FromQuery] int? limit,
PlexRequestsHosted.Services.Abstractions.IFirefoxCaptureService capture,
HttpContext context,
CancellationToken cancellationToken) =>
{
context.Response.Headers.CacheControl = "no-store";
var token = CaptureBearerToken(context);
if (token is null) return Results.Unauthorized();
var result = await capture.GetPendingDetailsAsync(
token,
Math.Max(0, after ?? 0),
Math.Clamp(limit ?? 250, 1, 250),
cancellationToken);
return result is null ? Results.Unauthorized() : Results.Ok(result);
})
.AllowAnonymous()
.DisableAntiforgery()
.RequireRateLimiting("firefox-capture-ingest");
app.MapPost("/api/browser-capture/batches", async (
FirefoxCaptureBatchDto body,
PlexRequestsHosted.Services.Abstractions.IFirefoxCaptureService capture,
HttpContext context,
CancellationToken cancellationToken) =>
{
context.Response.Headers.CacheControl = "no-store";
var token = CaptureBearerToken(context);
if (token is null) return Results.Unauthorized();
try
{
return Results.Ok(await capture.IngestAsync(token, body, cancellationToken));
}
catch (UnauthorizedAccessException)
{
return Results.Unauthorized();
}
catch (InvalidOperationException ex)
{
return Results.Conflict(new { error = ex.Message });
}
catch (ArgumentException ex)
{
return Results.BadRequest(new { error = ex.Message });
}
})
.AllowAnonymous()
.DisableAntiforgery()
.WithMetadata(new RequestSizeLimitAttribute(512 * 1024))
.RequireRateLimiting("firefox-capture-ingest");
app.MapPost("/api/browser-capture/hydration-failures", async (
FirefoxCaptureHydrationFailureDto body,
PlexRequestsHosted.Services.Abstractions.IFirefoxCaptureService capture,
HttpContext context,
CancellationToken cancellationToken) =>
{
context.Response.Headers.CacheControl = "no-store";
var token = CaptureBearerToken(context);
if (token is null) return Results.Unauthorized();
try
{
var changed = await capture.ReportHydrationFailureAsync(token, body, cancellationToken);
return changed is null ? Results.Unauthorized() : Results.Ok(new { accepted = changed.Value });
}
catch (ArgumentException ex)
{
return Results.BadRequest(new { error = ex.Message });
}
})
.AllowAnonymous()
.DisableAntiforgery()
.WithMetadata(new RequestSizeLimitAttribute(8 * 1024))
.RequireRateLimiting("firefox-capture-ingest");
// Simple health endpoint for Plex connectivity
app.MapGet("/api/plex/health", async (IPlexApiService plex) =>
{
var info = await plex.GetServerInfoAsync();
return Results.Ok(new { online = info?.IsOnline == true, name = info?.Name, version = info?.Version });
}).RequireAuthorization();
// Admin-only same-origin artwork proxy: keeps the Plex token/private URL out of rendered image tags.
app.MapGet("/api/plex/artwork", async (
[FromQuery] string source,
[FromQuery] int? width,
[FromQuery] int? height,
HttpContext context,
IPlexArtworkService artwork,
CancellationToken cancellationToken) =>
{
var image = await artwork.GetAsync(source, width ?? 320, height ?? 480, cancellationToken);
if (image is null) return Results.NotFound();
context.Response.Headers.CacheControl = "private,max-age=86400";
return Results.File(image.Bytes, image.ContentType);
}).RequireAuthorization("AdminOnly");
// Diagnostics: index stats
app.MapGet("/api/plex/index/stats", async (IPlexApiService plex) =>
{
var stats = await plex.GetIndexStatsAsync();
return Results.Ok(stats);
}).RequireAuthorization();
// Force rebuild of Plex availability index (dev/diagnostics)
app.MapPost("/api/plex/index/rebuild", async (IPlexApiService plex) =>
{
var res = await plex.RebuildAvailabilityIndexAsync();
return Results.Ok(res);
}).RequireAuthorization("AdminOnly");
// Admin folder browser (Library Organization page): lists one directory level at a time so an admin
// can pick a library/NAS path instead of typing it by hand. Read-only, admin-only, cross-platform
// (drive list on Windows, "/" root on Linux/Mac). The Blazor page itself calls IFolderBrowserService
// directly (same process, no need to round-trip through HTTP) — this endpoint exists for parity/any
// external tooling that might want it.
app.MapGet("/api/admin/browse-folders", (string? path, PlexRequestsHosted.Services.Implementations.IFolderBrowserService browser) =>
Results.Ok(browser.Browse(path)))
.RequireAuthorization("AdminOnly");
// Diagnostics: test a single match
app.MapGet("/api/plex/match", async (string? title, int? year, int? tmdbId, string? imdbId, int? tvdbId, MediaType mediaType, IPlexApiService plex) =>
{
var result = await plex.TestMatchAsync(title, year, tmdbId, imdbId, tvdbId, mediaType);
return Results.Ok(result);
}).RequireAuthorization();
// Low-level helpers for first-success diagnostics
app.MapGet("/api/plex/sections/raw", async (IPlexApiService plex) =>
{
var raw = await plex.GetSectionsRawAsync();
return Results.Text(raw, "text/plain");
}).RequireAuthorization();
app.MapGet("/api/plex/metadata/{ratingKey}", async (string ratingKey, IPlexApiService plex) =>
{
var md = await plex.GetMetadataAsync(ratingKey);
return Results.Ok(md);
}).RequireAuthorization();
app.MapGet("/api/plex/search", async (string query, MediaType? mediaType, IPlexApiService plex) =>
{
var results = await plex.SearchServerAsync(query, mediaType);
return Results.Ok(results);
}).RequireAuthorization();
// ---------------------------------------------------------------------------------------------
// Fulfillment worker API. These endpoints are called by the out-of-process downloader (not a
// browser), so they are NOT cookie-authenticated — they are gated by a shared secret in the
// `X-Fulfillment-Key` header, compared in constant time. Configure Fulfillment:ApiKey (env
// FULFILLMENT_API_KEY) to enable them; with no key configured every call is rejected.
// ---------------------------------------------------------------------------------------------
static bool IsAuthorizedWorker(HttpContext ctx, IConfiguration cfg)
{
var configured = cfg["Fulfillment:ApiKey"];
if (string.IsNullOrWhiteSpace(configured)) return false;
if (!ctx.Request.Headers.TryGetValue("X-Fulfillment-Key", out var provided)) return false;
var a = Encoding.UTF8.GetBytes(provided.ToString());
var b = Encoding.UTF8.GetBytes(configured);
return a.Length == b.Length &&
System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(a, b);
}
static string NormalizeLocalReturnUrl(string? returnUrl)
{
if (string.IsNullOrWhiteSpace(returnUrl)) return "/browse";
if (!returnUrl.StartsWith('/') || returnUrl.StartsWith("//")) return "/browse";
if (returnUrl == "/" || returnUrl.StartsWith("/login", StringComparison.OrdinalIgnoreCase)) return "/browse";
return returnUrl;
}
static PlexRequestsHosted.Shared.DTOs.MediaRequestDto ToRequestDto(PlexRequestsHosted.Infrastructure.Entities.MediaRequestEntity r) => new()
{
Id = r.Id,
MediaId = r.MediaId,
MediaType = r.MediaType,
Title = r.Title,
PosterUrl = r.PosterUrl,
Status = r.Status,
RequestedAt = r.RequestedAt,
ApprovedAt = r.ApprovedAt,
AvailableAt = r.AvailableAt,
RequestedByUserId = r.RequestedByUserId ?? 0,
RequestedByUsername = r.RequestedBy ?? string.Empty,
DenialReason = r.DenialReason,
ExternalId = r.ExternalId,
ExternalSource = r.ExternalSource,
RequestScopeKind = r.RequestScopeKind,
MediaRef = !string.IsNullOrWhiteSpace(r.ExternalId)
? MediaRef.FromExternal(r.ExternalSource ?? "external", r.ExternalId, r.MediaType,
r.RequestScopeKind == RequestScopeKind.ArtistCatalog ? MediaKind.Artist
: r.RequestScopeKind == RequestScopeKind.Track ? MediaKind.Track
: r.MediaType.DefaultKind())
: MediaRef.FromTmdb(r.MediaId, r.MediaType)
};
// Worker claims queued jobs to download.
app.MapPost("/api/fulfillment/claim", async (ClaimRequest body, HttpContext ctx, IConfiguration cfg, IFulfillmentQueue queue) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
var jobs = await queue.ClaimNextAsync(body.WorkerId ?? "worker", Math.Clamp(body.Max ?? 1, 1, 25));
return Results.Ok(jobs);
});
// Worker fetches the global download-selection preferences (season-pack strategy, thresholds, etc.).
app.MapGet("/api/fulfillment/config", async (HttpContext ctx, IConfiguration cfg, PlexRequestsHosted.Services.Implementations.IDownloadPreferencesService prefs) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
return Results.Ok(await prefs.GetAsync());
});
// Worker fetches the per-indexer enable/priority config (the admin Indexers panel) — hot-reloadable,
// same pattern as /config above. Providers the panel doesn't know yet default to enabled downloader-side.
app.MapGet("/api/fulfillment/indexers", async (HttpContext ctx, IConfiguration cfg, PlexRequestsHosted.Services.Abstractions.IIndexerAdminService indexers) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
return Results.Ok(await indexers.GetWorkerConfigAsync());
});
// Worker reports each indexer's outcome for a search pass (result count / error / latency), which the
// admin Indexers panel surfaces as per-provider health. Unknown provider names auto-register.
app.MapPost("/api/fulfillment/indexer-status", async (List<PlexRequestsHosted.Shared.DTOs.IndexerStatusReportDto> body, HttpContext ctx, IConfiguration cfg, PlexRequestsHosted.Services.Abstractions.IIndexerAdminService indexers) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
await indexers.ReportStatusAsync(body);
return Results.Ok();
});
// ---- Interactive search -------------------------------------------------------------------------
// The worker polls for admin-initiated searches. This is a pull, not a push, because the web app has no
// route to the downloader: it has no listening port and, under the VPN compose file, shares gluetun's
// network namespace. A short poll interval is what keeps the admin-perceived latency to a couple of seconds.
// ---- Torrent reconciliation -------------------------------------------------------------------
// The downloader registers what it added, then reconciles it against the download client on every pass.
// This is a pull-and-push loop over durable state rather than in-process monitoring, so it is indifferent
// to either side restarting: the next cycle re-derives everything from the client plus the database.
app.MapPost("/api/fulfillment/{jobId:int}/transfers", async (int jobId, List<PlexRequestsHosted.Shared.DTOs.TrackedTransferDto> body, HttpContext ctx, IConfiguration cfg, PlexRequestsHosted.Services.Implementations.IFulfillmentTransferService svc) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
return Results.Ok(await svc.RegisterAsync(jobId, body));
});
// Release catalog ingestion uses at-least-once batches. The catalog service advances the opaque source
// cursor in the same transaction as its releases and receipt, so a worker crash can safely replay.
app.MapPost("/api/fulfillment/catalog/batches", async (
CatalogBatchDto body,
HttpContext ctx,
IConfiguration cfg,
Microsoft.Extensions.Options.IOptions<PlexRequestsHosted.Infrastructure.Catalog.CatalogOptions> options,
PlexRequestsHosted.Services.Abstractions.IReleaseCatalogService catalog,
CancellationToken cancellationToken) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
if (!options.Value.Enabled) return Results.NotFound();
try { return Results.Ok(await catalog.UpsertBatchAsync(body, cancellationToken)); }
catch (ArgumentException ex) { return Results.BadRequest(new { error = ex.Message }); }
});
app.MapGet("/api/fulfillment/catalog/checkpoints/{indexerId:int}", async (
int indexerId,
HttpContext ctx,
IConfiguration cfg,
Microsoft.Extensions.Options.IOptions<PlexRequestsHosted.Infrastructure.Catalog.CatalogOptions> options,
PlexRequestsHosted.Services.Abstractions.IReleaseCatalogService catalog,
CancellationToken cancellationToken) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
if (!options.Value.Enabled) return Results.NotFound();
return Results.Ok(await catalog.GetCheckpointAsync(indexerId, cancellationToken));
});
app.MapPost("/api/fulfillment/catalog/failures", async (
CatalogFailureDto body,
HttpContext ctx,
IConfiguration cfg,
Microsoft.Extensions.Options.IOptions<PlexRequestsHosted.Infrastructure.Catalog.CatalogOptions> options,
PlexRequestsHosted.Services.Abstractions.IReleaseCatalogService catalog,
CancellationToken cancellationToken) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
if (!options.Value.Enabled) return Results.NotFound();
try { return Results.Ok(await catalog.ReportFailureAsync(body, cancellationToken)); }
catch (ArgumentException ex) { return Results.BadRequest(new { error = ex.Message }); }
});
app.MapPost("/api/fulfillment/catalog/search", async (
CatalogQueryDto body,
HttpContext ctx,
IConfiguration cfg,
Microsoft.Extensions.Options.IOptions<PlexRequestsHosted.Infrastructure.Catalog.CatalogOptions> options,
PlexRequestsHosted.Services.Abstractions.IReleaseCatalogService catalog,
CancellationToken cancellationToken) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
if (!options.Value.Enabled) return Results.NotFound();
return Results.Ok(await catalog.SearchAsync(body, cancellationToken));
});
app.MapGet("/api/fulfillment/jobs/{jobId:int}", async (int jobId, HttpContext ctx, IConfiguration cfg, IFulfillmentQueue queue) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
var job = await queue.GetJobAsync(jobId);
return job is null ? Results.NotFound() : Results.Ok(job);
});
app.MapGet("/api/fulfillment/transfers/active", async (HttpContext ctx, IConfiguration cfg, PlexRequestsHosted.Services.Implementations.IFulfillmentTransferService svc) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
return Results.Ok(await svc.GetActiveAsync());
});
app.MapPost("/api/fulfillment/transfers/state", async (List<PlexRequestsHosted.Shared.DTOs.TransferStateUpdateDto> body, HttpContext ctx, IConfiguration cfg, PlexRequestsHosted.Services.Implementations.IFulfillmentTransferService svc) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
return Results.Ok(await svc.ApplyAsync(body));
});
app.MapPost("/api/fulfillment/search/claim", async (ClaimRequest body, HttpContext ctx, IConfiguration cfg, PlexRequestsHosted.Services.Implementations.IInteractiveSearchService search) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
var task = await search.ClaimAsync(body.WorkerId ?? "worker");
return task is null ? Results.NoContent() : Results.Ok(task);
});
app.MapPost("/api/fulfillment/search/{taskId:int}/results", async (int taskId, PlexRequestsHosted.Shared.DTOs.SearchTaskResultDto body, HttpContext ctx, IConfiguration cfg, PlexRequestsHosted.Services.Implementations.IInteractiveSearchService search) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
return await search.CompleteAsync(taskId, body) ? Results.Ok() : Results.NotFound();
});
// The worker reports a release that failed, so it is never grabbed for this request again. Called from the
// pipeline's single failure funnel, so every failure path (stall, error, unresolvable path, failed import)
// records one.
app.MapPost("/api/fulfillment/{jobId:int}/blocklist", async (int jobId, PlexRequestsHosted.Shared.DTOs.BlocklistRequestDto body, HttpContext ctx, IConfiguration cfg, PlexRequestsHosted.Services.Implementations.IReleaseBlocklistService blocklist) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
return await blocklist.BlockAsync(jobId, body) ? Results.Ok() : Results.NotFound();
});
// Episodes automatic release monitoring should watch for: monitored, aired (or undated), and not yet on Plex.
app.MapGet("/api/fulfillment/wanted", async (HttpContext ctx, IConfiguration cfg, AppDbContext db) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
var now = DateTime.UtcNow;
var wanted = await (from a in db.AirSchedule
join r in db.MediaRequests on a.MediaRequestId equals r.Id
where a.Monitored && !a.HasFile && a.MediaRequestId != null
&& (a.SearchState == PlexRequestsHosted.Shared.Enums.AirSearchState.Due
|| a.SearchState == PlexRequestsHosted.Shared.Enums.AirSearchState.Searching
|| a.SearchState == PlexRequestsHosted.Shared.Enums.AirSearchState.AirDateUnknown)
&& (a.AirsAtUtc == null || a.AirsAtUtc <= now)
select new PlexRequestsHosted.Shared.DTOs.WantedEpisodeDto
{
MediaRequestId = a.MediaRequestId!.Value,
ShowTmdbId = a.ShowTmdbId,
Title = r.Title,
ImdbId = db.FulfillmentJobs
.Where(j => j.MediaRequestId == r.Id && j.ImdbId != null)
.OrderByDescending(j => j.Id)
.Select(j => j.ImdbId)
.FirstOrDefault(),
IsAnime = db.FulfillmentJobs.Any(j => j.MediaRequestId == r.Id && j.IsAnime),
Season = a.SeasonNumber,
Episode = a.EpisodeNumber,
QualityProfileId = r.QualityProfileId
}).Take(500).ToListAsync();
return Results.Ok(wanted);
});
// The sweep found a wanted episode. Route it through the normal monitored-episode path so it gets the same
// ranking, blocklist and import treatment as anything else — the sweep only changes WHEN we notice.
app.MapPost("/api/fulfillment/rss-grab", async (List<PlexRequestsHosted.Shared.DTOs.RssGrabDto> body, HttpContext ctx, IConfiguration cfg, AppDbContext db, IMediaRequestService requests) =>
{
if (!IsAuthorizedWorker(ctx, cfg)) return Results.Unauthorized();
int queued = 0;
var now = DateTime.UtcNow;
foreach (var group in body.GroupBy(g => g.MediaRequestId))
{
var episodes = group.Select(g => (g.Season, g.Episode)).Distinct().ToList();
var result = await requests.CreateMonitoredEpisodesAsync(group.Key, episodes);
foreach (var g in group)
{
var row = await db.AirSchedule.FirstOrDefaultAsync(a =>
a.MediaRequestId == g.MediaRequestId && a.SeasonNumber == g.Season && a.EpisodeNumber == g.Episode);
if (row is null) continue;
if (!result.AlreadyCovered)
{
row.LastSearchedAt = now;