This repository has been archived by the owner on Apr 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProgram.cs
300 lines (237 loc) · 11.6 KB
/
Program.cs
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
using Microsoft.AspNetCore.Mvc;
using System.Text;
var builder = WebApplication.CreateBuilder( args );
var configuration = new ConfigurationBuilder()
.SetBasePath( Directory.GetCurrentDirectory() )
.AddJsonFile( "appsettings.json", optional: true, reloadOnChange: true )
.AddEnvironmentVariables()
.AddUserSecrets( typeof( Program ).Assembly )
.Build();
var JELLYSEERR_APIKEY = configuration.GetSection( "JELLYSEERR_APIKEY" ).Value;
var JELLYFIN_APIKEY = configuration.GetSection( "JELLYFIN_APIKEY" ).Value;
var JELLYSEERR_HOST_URL = configuration.GetSection( "JELLYSEERR_HOST_URL" ).Value;
var JELLYFIN_HOST_URL = configuration.GetSection( "JELLYFIN_HOST_URL" ).Value;
var LOG_FILE_PATH = configuration.GetSection( "Logging:File:Path" ).Value;
ArgumentNullException.ThrowIfNullOrEmpty( JELLYSEERR_APIKEY );
ArgumentNullException.ThrowIfNullOrEmpty( JELLYSEERR_HOST_URL );
ArgumentNullException.ThrowIfNullOrEmpty( JELLYFIN_HOST_URL );
ArgumentNullException.ThrowIfNullOrEmpty( JELLYFIN_APIKEY );
var JELLYSEERR_URI = new Uri( JELLYSEERR_HOST_URL );
var JELLYFIN_URI = new Uri( JELLYFIN_HOST_URL );
builder.Services.AddLogging( loggingBuilder =>
{
var loggingSection = configuration.GetSection( "Logging" );
loggingBuilder.AddFile( loggingSection );
} );
builder.Services.AddHttpClient( "Jellyseerr", ( client ) =>
{
client.BaseAddress = new Uri( JELLYSEERR_URI, "api/v1/" );
client.DefaultRequestHeaders.Add( "X-Api-Key", JELLYSEERR_APIKEY );
} );
builder.Services.AddHttpClient( "Jellyfin", ( client ) =>
{
client.BaseAddress = JELLYFIN_URI;
client.DefaultRequestHeaders.Add( "Authorization", $"MediaBrowser Token=\"{JELLYFIN_APIKEY}\"" );
} );
var app = builder.Build();
app.MapGet( "/", async ( context ) => await context.Response.WriteAsync( @"
Notification Endpoints:
/radarr/notification
/sonarr/notification
It is of note that any series episode deletion assumes the entire series is deleted. As there seems to be no way to determine if there are episodes left.
Sync Endpoints:
/syncdeleted/movies
This endpoint will query Jellyseerr for all movies that are marked as Available and then query Jellyfin for all the movies that are marked as Available in Jellyseerr.
If a movie is not found in Jellyfin it will be cleared from Jellyseerr.
Log Endpoints:
/logs
This endpoint will try to return the log file content if it exists.
" ) );
app.MapGet( "/logs", async ( HttpResponse response ) =>
{
var log = "No log file found";
if ( !string.IsNullOrWhiteSpace( LOG_FILE_PATH ) )
{
try
{
StringBuilder sb = new StringBuilder();
using ( var logFile = new FileStream( LOG_FILE_PATH, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ) )
using ( var sr = new StreamReader( logFile ) )
{
while ( !sr.EndOfStream )
{
sb.AppendLine( sr.ReadLine() );
}
}
log = sb.ToString();
}
catch ( Exception ex )
{
log = $"Tried reading the file : {LOG_FILE_PATH}, but the following error occurred: {ex}";
}
}
response.StatusCode = 200;
response.ContentType = "text/plain";
response.ContentLength = null;
response.Headers.Add( "Content-Encoding", "identity" );
response.Headers.Add( "Transfer-Encoding", "identity" );
await response.WriteAsync( log );
await response.CompleteAsync();
} );
app.MapGet( "/syncdeleted/movies", async ( [FromServices] IHttpClientFactory httpClientFactory, [FromServices] ILogger<Program> logger, HttpResponse response ) =>
{
var log = await SyncDeletedMovies( httpClientFactory, logger );
response.StatusCode = 200;
response.ContentType = "text/plain";
response.ContentLength = null;
response.Headers.Add( "Content-Encoding", "identity" );
response.Headers.Add( "Transfer-Encoding", "identity" );
await response.WriteAsync( log );
await response.CompleteAsync();
} );
app.MapPost( "/radarr/notification", ( [FromServices] IHttpClientFactory httpClientFactory, [FromServices] ILogger<Program> logger, [FromBody] RadarrNotificationPayload payload )
=> ProcessRadarrNotification( httpClientFactory, logger, payload ) );
app.MapPost( "/sonarr/notification", ( [FromServices] IHttpClientFactory httpClientFactory, [FromServices] ILogger<Program> logger, [FromBody] SonarrNotificationPayload payload )
=> ProcessSonarrNotification( httpClientFactory, logger, payload ) );
app.Run();
async Task ProcessRadarrNotification( IHttpClientFactory httpClientFactory, ILogger logger, RadarrNotificationPayload payload )
{
logger.LogInformation( "Processing Radarr Notification" );
logger.LogInformation( "Received the following Notification: {Notification}", System.Text.Json.JsonSerializer.Serialize( payload ) );
try
{
if ( payload.EventType.Equals( "MovieFileDelete", StringComparison.InvariantCultureIgnoreCase ) && ( payload.DeleteReason is null || !payload.DeleteReason.Equals( "upgrade", StringComparison.InvariantCultureIgnoreCase ) ) )
{
logger.LogInformation( "Processing MovieFileDelete" );
await RunMovieClear( httpClientFactory, logger, payload );
}
else
{
logger.LogInformation( "Nothing to Process" );
}
}
catch ( Exception ex )
{
logger.LogError( "An error has occurred: {Exception}", ex );
}
}
async Task ProcessSonarrNotification( IHttpClientFactory httpClientFactory, ILogger logger, SonarrNotificationPayload payload )
{
logger.LogInformation( "Processing Sonarr Notification" );
logger.LogInformation( "Received the following Notification: {Notification}", System.Text.Json.JsonSerializer.Serialize( payload ) );
try
{
if ( payload.EventType.Equals( "SeriesDelete", StringComparison.InvariantCultureIgnoreCase ) && ( payload.DeleteReason is null || !payload.DeleteReason.Equals( "upgrade", StringComparison.InvariantCultureIgnoreCase ) ) )
{
logger.LogInformation( "Processing SeriesDelete" );
await RunEpisodeClear( httpClientFactory, logger, payload );
}
else if ( payload.EventType.Equals( "EpisodeFileDelete", StringComparison.InvariantCultureIgnoreCase ) && ( payload.DeleteReason is null || !payload.DeleteReason.Equals( "upgrade", StringComparison.InvariantCultureIgnoreCase ) ) )
{
logger.LogInformation( "Processing EpisodeFileDelete" );
await RunEpisodeClear( httpClientFactory, logger, payload );
}
else
{
logger.LogInformation( "Nothing to Process" );
}
}
catch ( Exception ex )
{
logger.LogError( "An error has occurred: {Exception}", ex );
}
};
async Task<string> SyncDeletedMovies( IHttpClientFactory httpClientFactory, ILogger logger )
{
var batchSize = 100;
logger.LogInformation( "Processing Deleted Movies Sync..." );
var log = new StringBuilder();
try
{
log.AppendLine( "Processing Deleted Movies Sync..." );
var jellyfinClient = httpClientFactory.CreateClient( "Jellyfin" );
var jellyseerrClient = httpClientFactory.CreateClient( "Jellyseerr" );
var searchMessage = "Searching JellySeerr media...";
log.AppendLine( searchMessage );
logger.LogInformation( searchMessage );
var searchResult = await jellyseerrClient.GetFromJsonAsync<JellyseerrMediaSearchResult>( $"media?take=999&skip=0&filter=available&sort=added" );
var availableMovies = searchResult.Results.Where( x => x.MediaType.Equals( "movie", StringComparison.InvariantCultureIgnoreCase ) );
var moviesIds = availableMovies
.Where( x => !string.IsNullOrWhiteSpace( x.JellyfinMediaId ) || !string.IsNullOrWhiteSpace( x.JellyfinMediaId4k ) )
.Select( x => new
{
Id = string.IsNullOrWhiteSpace( x.JellyfinMediaId )
? Guid.Parse( x.JellyfinMediaId4k ).ToString( "d" )
: Guid.Parse( x.JellyfinMediaId ).ToString( "d" ),
MediaId = x.Id,
TmdbId = x.TmdbId
} );
var jellyseerrMoviesCount = moviesIds.Count();
var totalMessage = $"Total Jellyseerr Movies found as Available: {jellyseerrMoviesCount}";
log.AppendLine( totalMessage );
logger.LogInformation( totalMessage );
var existingJellyfinItems = new List<JellyfinItem>();
for ( int i = 0; i < jellyseerrMoviesCount; i += batchSize )
{
var batch = moviesIds.Skip( i ).Take( batchSize );
var jellySearchResult = await jellyfinClient.GetFromJsonAsync<JellyfinSearchResult>( $"Items?ids={string.Join( ",", batch.Select( x => x.Id ) )}&enableTotalRecordCount=false&enableImages=false" );
existingJellyfinItems.AddRange( jellySearchResult.Items );
}
var notFoundMovies = moviesIds.Where( x => !existingJellyfinItems.Any( y => Guid.Parse( y.Id ) == Guid.Parse( x.Id ) ) );
var notFoundMessage = "Jellyfin movies/items that were not found: " + notFoundMovies.Count();
log.AppendLine( notFoundMessage );
logger.LogInformation( notFoundMessage );
if ( notFoundMovies.Any() )
{
foreach ( var notFoundMovie in notFoundMovies )
{
var clearMessage = $"Clearing: {new Uri( JELLYSEERR_URI, $"movie/{notFoundMovie.TmdbId}" )}";
log.AppendLine( clearMessage );
logger.LogInformation( clearMessage );
await jellyseerrClient.DeleteAsync( $"media/{notFoundMovie.MediaId}" );
}
}
}
catch ( Exception ex )
{
log.AppendLine( "An error has occurred: " );
log.AppendLine( ex.ToString() );
}
return log.ToString();
}
static async Task RunMovieClear( IHttpClientFactory httpClientFactory, ILogger logger, RadarrNotificationPayload payload )
{
var client = httpClientFactory.CreateClient( "Jellyseerr" );
var response = await client.GetAsync( $"movie/{payload.Movie.TmdbId}" );
if ( !response.IsSuccessStatusCode )
{
logger.LogWarning( "No entry was cleared. Could not find an entry for this movie." );
return;
}
var movie = await response.Content.ReadFromJsonAsync<JellySeerrMovie>();
logger.LogInformation( "Clearing entry... with TmdbId: {TmdbId} | JellySeerr MediaId: {JellySeerrMediaId}", movie.MediaInfo.TmdbId, movie.MediaInfo.Id );
await client.DeleteAsync( $"media/{movie.MediaInfo.Id}" );
}
static async Task RunEpisodeClear( IHttpClientFactory httpClientFactory, ILogger logger, SonarrNotificationPayload payload )
{
var client = httpClientFactory.CreateClient( "Jellyseerr" );
logger.LogInformation( "Searching Jellyseerr for... {Title}", payload.Series.Title );
var searchResult = await client.GetFromJsonAsync<JellyseerrSearchResult>( $"search?query={Uri.EscapeDataString( payload.Series.Title )}&page=1&language=en" );
if ( searchResult is not null && searchResult.Results?.Count > 0 )
{
var foundMedia = searchResult.Results.FirstOrDefault( x => x.MediaInfo?.TvdbId == payload.Series.TvdbId );
if ( foundMedia is not null )
{
logger.LogInformation( "Clearing entry... with TmdbId: {TmdbId} | JellySeerr MediaId: {JellySeerrMediaId}", foundMedia.MediaInfo.TmdbId, foundMedia.MediaInfo.Id );
await client.DeleteAsync( $"media/{foundMedia.MediaInfo.Id}" );
}
else
{
logger.LogWarning( "No entry was cleared. Could not find an entry for this series." );
}
}
else
{
logger.LogWarning( "Could not find this series: {Title}", payload.Series.Title );
}
}