forked from ShokoAnime/ShokoServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTmdbMetadataService.cs
2330 lines (1991 loc) · 97.6 KB
/
TmdbMetadataService.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
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 System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Polly;
using Polly.Bulkhead;
using Polly.RateLimit;
using Polly.Retry;
using Quartz;
using Shoko.Commons.Extensions;
using Shoko.Plugin.Abstractions.Enums;
using Shoko.Plugin.Abstractions.Extensions;
using Shoko.Server.Models.Interfaces;
using Shoko.Server.Models.TMDB;
using Shoko.Server.Repositories.Cached;
using Shoko.Server.Repositories.Direct;
using Shoko.Server.Scheduling;
using Shoko.Server.Scheduling.Jobs.TMDB;
using Shoko.Server.Server;
using Shoko.Server.Settings;
using Shoko.Server.Utilities;
using TMDbLib.Client;
using TMDbLib.Objects.Collections;
using TMDbLib.Objects.Exceptions;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Movies;
using TMDbLib.Objects.People;
using TMDbLib.Objects.TvShows;
using TitleLanguage = Shoko.Plugin.Abstractions.DataModels.TitleLanguage;
using MovieCredits = TMDbLib.Objects.Movies.Credits;
// Suggestions we don't need in this file.
#pragma warning disable CA1822
#pragma warning disable CA1826
#nullable enable
namespace Shoko.Server.Providers.TMDB;
public class TmdbMetadataService
{
private static readonly int _maxConcurrency = Math.Min(6, Environment.ProcessorCount);
private static TmdbMetadataService? _instance = null;
private static readonly object _instanceLockObj = new();
internal static TmdbMetadataService? Instance
{
get
{
if (_instance is not null)
return _instance;
lock (_instanceLockObj)
{
if (_instance is not null)
return _instance;
return _instance = Utils.ServiceContainer?.GetService<TmdbMetadataService>();
}
}
}
private static string? _imageServerUrl = null;
public static string? ImageServerUrl
{
get
{
// Return cached version if possible.
if (_imageServerUrl is not null)
return _imageServerUrl;
// In case the server url is attempted to be accessed before the lazily initialized instance has been created, create it now if the service container is available.
var instance = Instance;
if (instance is null)
return null;
try
{
var config = instance.UseClient(c => c.GetAPIConfiguration(), "Get API configuration").Result;
return _imageServerUrl = config.Images.SecureBaseUrl;
}
catch (Exception ex)
{
instance._logger.LogError(ex, "Encountered an exception while trying to find the image server url to use; {ErrorMessage}", ex.Message);
throw;
}
}
}
private readonly ILogger<TmdbMetadataService> _logger;
private readonly ISchedulerFactory _schedulerFactory;
private readonly ISettingsProvider _settingsProvider;
private readonly TmdbImageService _imageService;
private readonly TmdbLinkingService _linkingService;
private readonly AnimeSeriesRepository _animeSeries;
private readonly TMDB_AlternateOrderingRepository _tmdbAlternateOrdering;
private readonly TMDB_AlternateOrdering_EpisodeRepository _tmdbAlternateOrderingEpisodes;
private readonly TMDB_AlternateOrdering_SeasonRepository _tmdbAlternateOrderingSeasons;
private readonly TMDB_CollectionRepository _tmdbCollections;
private readonly TMDB_CompanyRepository _tmdbCompany;
private readonly TMDB_EpisodeRepository _tmdbEpisodes;
private readonly TMDB_Episode_CastRepository _tmdbEpisodeCast;
private readonly TMDB_Episode_CrewRepository _tmdbEpisodeCrew;
private readonly TMDB_ImageRepository _tmdbImages;
private readonly TMDB_MovieRepository _tmdbMovies;
private readonly TMDB_Movie_CastRepository _tmdbMovieCast;
private readonly TMDB_Movie_CrewRepository _tmdbMovieCrew;
private readonly TMDB_NetworkRepository _tmdbNetwork;
private readonly TMDB_OverviewRepository _tmdbOverview;
private readonly TMDB_PersonRepository _tmdbPeople;
private readonly TMDB_SeasonRepository _tmdbSeasons;
private readonly TMDB_ShowRepository _tmdbShows;
private readonly TMDB_TitleRepository _tmdbTitle;
private readonly CrossRef_AniDB_TMDB_MovieRepository _xrefAnidbTmdbMovies;
private readonly CrossRef_AniDB_TMDB_ShowRepository _xrefAnidbTmdbShows;
private readonly TMDB_Collection_MovieRepository _xrefTmdbCollectionMovies;
private readonly TMDB_Company_EntityRepository _xrefTmdbCompanyEntity;
private readonly TMDB_Show_NetworkRepository _xrefTmdbShowNetwork;
private TMDbClient? _rawClient = null;
// We lazy-init it on first use, this will give us time to set up the server before we attempt to init the tmdb client.
private TMDbClient CachedClient => _rawClient ??= new(_settingsProvider.GetSettings().TMDB.UserApiKey ?? (
Constants.TMDB.ApiKey != "TMDB_API_KEY_GOES_HERE"
? Constants.TMDB.ApiKey
: throw new Exception("You need to provide an api key before using the TMDB provider!")
));
// This policy will ensure only 10 requests can be in-flight at the same time.
private readonly AsyncBulkheadPolicy _bulkheadPolicy;
// This policy will ensure we can only make 40 requests per 10 seconds.
private readonly AsyncRateLimitPolicy _rateLimitPolicy;
// This policy, together with the above policy, will ensure the rate limits are enforced, while also ensuring we
// throw if an exception that's not rate-limit related is thrown.
private readonly AsyncRetryPolicy _retryPolicy;
private readonly ConcurrentDictionary<string, SemaphoreSlim> _concurrencyGuards = new();
/// <summary>
/// Execute the given function with the TMDb client, applying rate limiting and retry policies.
/// </summary>
/// <typeparam name="T">The type of the result of the function.</typeparam>
/// <param name="func">The function to execute with the TMDb client.</param>
/// <param name="displayName">The name of the function to display in the logs.</param>
/// <returns>A task that will complete with the result of the function, after applying the rate limiting and retry policies.</returns>
public async Task<T> UseClient<T>(Func<TMDbClient, Task<T>> func, string? displayName)
{
displayName ??= func.Method.Name;
var now = DateTime.Now;
var attempts = 0;
var waitTime = TimeSpan.Zero;
try
{
_logger.LogTrace("Scheduled call: {DisplayName}", displayName);
var val = await _bulkheadPolicy.ExecuteAsync(() =>
{
var now1 = DateTime.Now;
waitTime = now1 - now;
now = now1;
_logger.LogTrace("Executing call: {DisplayName} (Waited {Waited}ms)", displayName, waitTime.TotalMilliseconds);
return _retryPolicy.ExecuteAsync(() =>
{
++attempts;
return _rateLimitPolicy.ExecuteAsync(() => func(CachedClient));
});
}).ConfigureAwait(false);
var delta = DateTime.Now - now;
_logger.LogTrace("Completed call: {DisplayName} (Waited {Waited}ms, Executed: {Delta}ms, {Attempts} attempts)", displayName, waitTime.TotalMilliseconds, delta.TotalMilliseconds, attempts);
return val;
}
catch (Exception ex)
{
var delta = DateTime.Now - now;
_logger.LogError(ex, "Failed call: {DisplayName} (Waited {Waited}ms, Executed: {Delta}ms, {Attempts} attempts)", displayName, waitTime.TotalMilliseconds, delta.TotalMilliseconds, attempts);
throw;
}
}
public TmdbMetadataService(
ILogger<TmdbMetadataService> logger,
ISchedulerFactory commandFactory,
ISettingsProvider settingsProvider,
TmdbImageService imageService,
TmdbLinkingService linkingService,
AnimeSeriesRepository animeSeries,
TMDB_AlternateOrderingRepository tmdbAlternateOrdering,
TMDB_AlternateOrdering_EpisodeRepository tmdbAlternateOrderingEpisodes,
TMDB_AlternateOrdering_SeasonRepository tmdbAlternateOrderingSeasons,
TMDB_CollectionRepository tmdbCollections,
TMDB_CompanyRepository tmdbCompany,
TMDB_EpisodeRepository tmdbEpisodes,
TMDB_Episode_CastRepository tmdbEpisodeCast,
TMDB_Episode_CrewRepository tmdbEpisodeCrew,
TMDB_ImageRepository tmdbImages,
TMDB_MovieRepository tmdbMovies,
TMDB_Movie_CastRepository tmdbMovieCast,
TMDB_Movie_CrewRepository tmdbMovieCrew,
TMDB_NetworkRepository tmdbNetwork,
TMDB_OverviewRepository tmdbOverview,
TMDB_PersonRepository tmdbPeople,
TMDB_SeasonRepository tmdbSeasons,
TMDB_ShowRepository tmdbShows,
TMDB_TitleRepository tmdbTitle,
CrossRef_AniDB_TMDB_MovieRepository xrefAnidbTmdbMovies,
CrossRef_AniDB_TMDB_ShowRepository xrefAnidbTmdbShows,
TMDB_Collection_MovieRepository xrefTmdbCollectionMovies,
TMDB_Company_EntityRepository xrefTmdbCompanyEntity,
TMDB_Show_NetworkRepository xrefTmdbShowNetwork
)
{
_logger = logger;
_schedulerFactory = commandFactory;
_settingsProvider = settingsProvider;
_imageService = imageService;
_linkingService = linkingService;
_animeSeries = animeSeries;
_tmdbAlternateOrdering = tmdbAlternateOrdering;
_tmdbAlternateOrderingEpisodes = tmdbAlternateOrderingEpisodes;
_tmdbAlternateOrderingSeasons = tmdbAlternateOrderingSeasons;
_tmdbCollections = tmdbCollections;
_tmdbCompany = tmdbCompany;
_tmdbEpisodes = tmdbEpisodes;
_tmdbEpisodeCast = tmdbEpisodeCast;
_tmdbEpisodeCrew = tmdbEpisodeCrew;
_tmdbImages = tmdbImages;
_tmdbMovies = tmdbMovies;
_tmdbMovieCast = tmdbMovieCast;
_tmdbMovieCrew = tmdbMovieCrew;
_tmdbNetwork = tmdbNetwork;
_tmdbOverview = tmdbOverview;
_tmdbPeople = tmdbPeople;
_tmdbSeasons = tmdbSeasons;
_tmdbShows = tmdbShows;
_tmdbTitle = tmdbTitle;
_xrefAnidbTmdbMovies = xrefAnidbTmdbMovies;
_xrefAnidbTmdbShows = xrefAnidbTmdbShows;
_xrefTmdbCollectionMovies = xrefTmdbCollectionMovies;
_xrefTmdbCompanyEntity = xrefTmdbCompanyEntity;
_xrefTmdbShowNetwork = xrefTmdbShowNetwork;
_instance ??= this;
_bulkheadPolicy = Policy.BulkheadAsync(_maxConcurrency, int.MaxValue);
_rateLimitPolicy = Policy.RateLimitAsync(45, TimeSpan.FromSeconds(10), 45);
_retryPolicy = Policy
.Handle<RateLimitRejectedException>()
.Or<HttpRequestException>()
.Or<RequestLimitExceededException>()
.WaitAndRetryAsync(int.MaxValue, (_, _) => TimeSpan.Zero, async (ex, ts, retryCount, ctx) =>
{
// Retry on rate limit exceptions, throw on everything else.
switch (ex)
{
// If we got a _local_ rate limit exception, wait and try again.
case RateLimitRejectedException rlrEx:
{
var retryAfter = rlrEx.RetryAfter;
await Task.Delay(retryAfter).ConfigureAwait(false);
break;
}
// If we got a _remote_ rate limit exception, wait and try again.
case RequestLimitExceededException rleEx:
{
// Note: We don't actually wait here since the library has already waited for us.
var retryAfter = rleEx.RetryAfter ?? TimeSpan.FromSeconds(1);
_logger.LogTrace("Hit remote rate limit. Waiting and retrying. Retry count: {RetryCount}, Retry after: {RetryAfter}", retryCount, retryAfter);
break;
}
// If we timed out or got a too many requests exception, just wait and try again.
case HttpRequestException hrEx when hrEx.InnerException is TaskCanceledException:
{
// If we timed out more than 3 times, just throw the exception, since the exceptions were likely caused by other network issues.
var timeoutRetryCount = ctx.TryGetValue("timeoutRetryCount", out var timeoutRetryCountValue) ? (int)timeoutRetryCountValue : 0;
if (timeoutRetryCount >= 3)
goto default;
ctx["timeoutRetryCount"] = timeoutRetryCount + 1;
break;
}
default:
throw ex;
}
});
}
public async Task ScheduleSearchForMatch(int anidbId, bool force)
{
await (await _schedulerFactory.GetScheduler()).StartJob<SearchTmdbJob>(c =>
{
c.AnimeID = anidbId;
c.ForceRefresh = force;
});
}
public async Task ScanForMatches()
{
var settings = _settingsProvider.GetSettings();
if (!settings.TMDB.AutoLink)
return;
var allSeries = _animeSeries.GetAll();
var scheduler = await _schedulerFactory.GetScheduler();
foreach (var ser in allSeries)
{
if (ser.IsTMDBAutoMatchingDisabled)
continue;
var anime = ser.AniDB_Anime;
if (anime == null)
continue;
if (anime.IsRestricted && !settings.TMDB.AutoLinkRestricted)
continue;
if (anime.TmdbMovieCrossReferences is { Count: > 0 })
continue;
if (anime.TmdbShowCrossReferences is { Count: > 0 })
continue;
_logger.LogTrace("Found anime without TMDB association: {MainTitle}", anime.MainTitle);
await scheduler.StartJob<SearchTmdbJob>(c => c.AnimeID = ser.AniDB_ID);
}
}
#region Movies
#region Genres (Movies)
private IReadOnlyDictionary<int, string>? _movieGenres = null;
public async Task<IReadOnlyDictionary<int, string>> GetMovieGenres()
{
if (_movieGenres is not null)
return _movieGenres;
using (await GetLockForEntity(ForeignEntityType.Movie, 0, "genre", "Load").ConfigureAwait(false))
{
if (_movieGenres is not null)
return _movieGenres;
var genres = await UseClient(c => c.GetMovieGenresAsync(), "Get Movie Genres").ConfigureAwait(false);
_movieGenres = genres.ToDictionary(x => x.Id, x => x.Name);
return _movieGenres;
}
}
#endregion
#region Update (Movies)
public bool IsMovieUpdating(int movieId)
=> IsEntityLocked(ForeignEntityType.Movie, movieId, "metadata");
public async Task UpdateAllMovies(bool force, bool saveImages)
{
var allXRefs = _xrefAnidbTmdbMovies.GetAll();
_logger.LogInformation("Scheduling {Count} movies to be updated.", allXRefs.Count);
var scheduler = await _schedulerFactory.GetScheduler();
foreach (var xref in allXRefs)
await scheduler.StartJob<UpdateTmdbMovieJob>(
c =>
{
c.TmdbMovieID = xref.TmdbMovieID;
c.ForceRefresh = force;
c.DownloadImages = saveImages;
}
).ConfigureAwait(false);
}
public async Task ScheduleUpdateOfMovie(int movieId, bool forceRefresh = false, bool downloadImages = false, bool? downloadCrewAndCast = null, bool? downloadCollections = null)
{
// Schedule the movie info to be downloaded or updated.
await (await _schedulerFactory.GetScheduler().ConfigureAwait(false)).StartJob<UpdateTmdbMovieJob>(c =>
{
c.TmdbMovieID = movieId;
c.ForceRefresh = forceRefresh;
c.DownloadImages = downloadImages;
c.DownloadCrewAndCast = downloadCrewAndCast;
c.DownloadCollections = downloadCollections;
}).ConfigureAwait(false);
}
public async Task<bool> UpdateMovie(int movieId, bool forceRefresh = false, bool downloadImages = false, bool downloadCrewAndCast = false, bool downloadCollections = false)
{
using (await GetLockForEntity(ForeignEntityType.Movie, movieId, "metadata", "Update").ConfigureAwait(false))
{
// Abort if we're within a certain time frame as to not try and get us rate-limited.
var tmdbMovie = _tmdbMovies.GetByTmdbMovieID(movieId) ?? new(movieId);
var newlyAdded = tmdbMovie.TMDB_MovieID == 0;
if (!forceRefresh && tmdbMovie.CreatedAt != tmdbMovie.LastUpdatedAt && tmdbMovie.LastUpdatedAt > DateTime.Now.AddHours(-1))
{
_logger.LogInformation("Skipping update of movie {MovieID} as it was last updated {LastUpdatedAt}", movieId, tmdbMovie.LastUpdatedAt);
return false;
}
// Abort if we couldn't find the movie by id.
var methods = MovieMethods.Translations | MovieMethods.ReleaseDates | MovieMethods.ExternalIds;
if (downloadCrewAndCast)
methods |= MovieMethods.Credits;
var movie = await UseClient(c => c.GetMovieAsync(movieId, "en-US", null, methods), $"Get movie {movieId}").ConfigureAwait(false);
if (movie == null)
return false;
var settings = _settingsProvider.GetSettings();
var preferredTitleLanguages = settings.TMDB.DownloadAllTitles ? null : Languages.PreferredNamingLanguages.Select(a => a.Language).ToHashSet();
var preferredOverviewLanguages = settings.TMDB.DownloadAllOverviews ? null : Languages.PreferredDescriptionNamingLanguages.Select(a => a.Language).ToHashSet();
var contentRantingLanguages = settings.TMDB.DownloadAllContentRatings
? null
: Languages.PreferredNamingLanguages.Select(a => a.Language)
.Concat(Languages.PreferredEpisodeNamingLanguages.Select(a => a.Language))
.Except([TitleLanguage.Main, TitleLanguage.Unknown, TitleLanguage.None])
.ToHashSet();
var updated = tmdbMovie.Populate(movie, contentRantingLanguages);
var (titlesUpdated, overviewsUpdated) = UpdateTitlesAndOverviewsWithTuple(tmdbMovie, movie.Translations, preferredTitleLanguages, preferredOverviewLanguages);
updated = titlesUpdated || overviewsUpdated || updated;
updated = UpdateMovieExternalIDs(tmdbMovie, movie.ExternalIds) || updated;
updated = await UpdateCompanies(tmdbMovie, movie.ProductionCompanies) || updated;
if (downloadCrewAndCast)
updated = await UpdateMovieCastAndCrew(tmdbMovie, movie.Credits, forceRefresh, downloadImages) || updated;
if (updated)
{
tmdbMovie.LastUpdatedAt = DateTime.Now;
_tmdbMovies.Save(tmdbMovie);
}
if (downloadCollections)
await UpdateMovieCollections(movie);
foreach (var xref in _xrefAnidbTmdbMovies.GetByTmdbMovieID(movieId))
{
if ((titlesUpdated || overviewsUpdated) && xref.AnimeSeries is { } series)
{
if (titlesUpdated)
{
series.ResetPreferredTitle();
series.ResetAnimeTitles();
}
if (overviewsUpdated)
series.ResetPreferredOverview();
}
}
if (downloadImages)
await DownloadMovieImages(movieId, tmdbMovie.OriginalLanguage);
if (newlyAdded || updated)
ShokoEventHandler.Instance.OnMovieUpdated(tmdbMovie, newlyAdded ? UpdateReason.Added : UpdateReason.Updated);
return updated;
}
}
private async Task<bool> UpdateMovieCastAndCrew(TMDB_Movie tmdbMovie, MovieCredits credits, bool forceRefresh, bool downloadImages)
{
var peopleToKeep = new HashSet<int>();
var counter = 0;
var castToAdd = 0;
var castToKeep = new HashSet<string>();
var castToSave = new List<TMDB_Movie_Cast>();
var existingCastDict = _tmdbMovieCast.GetByTmdbMovieID(tmdbMovie.Id)
.ToDictionary(cast => cast.TmdbCreditID);
foreach (var cast in credits.Cast)
{
var ordering = counter++;
peopleToKeep.Add(cast.Id);
castToKeep.Add(cast.CreditId);
var roleUpdated = false;
if (!existingCastDict.TryGetValue(cast.CreditId, out var role))
{
role = new()
{
TmdbMovieID = tmdbMovie.Id,
TmdbPersonID = cast.Id,
TmdbCreditID = cast.CreditId,
};
castToAdd++;
roleUpdated = true;
}
if (role.CharacterName != cast.Character)
{
role.CharacterName = cast.Character;
roleUpdated = true;
}
if (role.Ordering != ordering)
{
role.Ordering = ordering;
roleUpdated = true;
}
if (roleUpdated)
{
castToSave.Add(role);
}
}
var crewToAdd = 0;
var crewToKeep = new HashSet<string>();
var crewToSave = new List<TMDB_Movie_Crew>();
var existingCrewDict = _tmdbMovieCrew.GetByTmdbMovieID(tmdbMovie.Id)
.ToDictionary(crew => crew.TmdbCreditID);
foreach (var crew in credits.Crew)
{
peopleToKeep.Add(crew.Id);
crewToKeep.Add(crew.CreditId);
var roleUpdated = false;
if (!existingCrewDict.TryGetValue(crew.CreditId, out var role))
{
role = new()
{
TmdbMovieID = tmdbMovie.Id,
TmdbPersonID = crew.Id,
TmdbCreditID = crew.CreditId,
};
crewToAdd++;
roleUpdated = true;
}
if (role.Department != crew.Department)
{
role.Department = crew.Department;
roleUpdated = true;
}
if (role.Job != crew.Job)
{
role.Job = crew.Job;
roleUpdated = true;
}
if (roleUpdated)
{
crewToSave.Add(role);
}
}
var castToRemove = existingCastDict.Values
.ExceptBy(castToKeep, cast => cast.TmdbCreditID)
.ToList();
var crewToRemove = existingCrewDict.Values
.ExceptBy(crewToKeep, crew => crew.TmdbCreditID)
.ToList();
_tmdbMovieCast.Save(castToSave);
_tmdbMovieCrew.Save(crewToSave);
_tmdbMovieCast.Delete(castToRemove);
_tmdbMovieCrew.Delete(crewToRemove);
_logger.LogDebug(
"Added/updated/removed/skipped {aa}/{au}/{ar}/{as} cast and {ra}/{ru}/{rr}/{rs} crew for movie {MovieTitle} (Movie={MovieId})",
castToAdd,
castToSave.Count - castToAdd,
castToRemove.Count,
existingCastDict.Count - (castToSave.Count - castToAdd),
crewToAdd,
crewToSave.Count - crewToAdd,
crewToRemove.Count,
existingCrewDict.Count - (crewToSave.Count - crewToAdd),
tmdbMovie.EnglishTitle,
tmdbMovie.Id
);
// Only add/remove staff if we're not doing a quick refresh.
var peopleAdded = 0;
var peopleUpdated = 0;
var peoplePurged = 0;
var peopleToPurge = existingCastDict.Values.Select(cast => cast.TmdbPersonID)
.Concat(existingCrewDict.Values.Select(crew => crew.TmdbPersonID))
.Except(peopleToKeep)
.ToHashSet();
foreach (var personId in peopleToKeep)
{
var (added, updated) = await UpdatePerson(personId, forceRefresh, downloadImages);
if (added)
peopleAdded++;
if (updated)
peopleUpdated++;
}
foreach (var personId in peopleToPurge)
{
if (await PurgePerson(personId))
peoplePurged++;
}
_logger.LogDebug("Added/removed {a}/{u}/{r}/{s} staff for movie {MovieTitle} (Movie={MovieId})",
peopleAdded,
peopleUpdated,
peoplePurged,
peopleToPurge.Count + peopleToPurge.Count - peopleAdded - peopleUpdated - peoplePurged,
tmdbMovie.EnglishTitle,
tmdbMovie.Id
);
return castToSave.Count > 0 ||
castToRemove.Count > 0 ||
crewToSave.Count > 0 ||
crewToRemove.Count > 0 ||
peopleAdded > 0 ||
peopleUpdated > 0 ||
peoplePurged > 0;
}
private async Task UpdateMovieCollections(Movie movie)
{
if (movie.BelongsToCollection?.Id is not { } collectionId)
{
CleanupMovieCollection(movie.Id);
return;
}
var movieXRefs = _xrefTmdbCollectionMovies.GetByTmdbCollectionID(collectionId);
var tmdbCollection = _tmdbCollections.GetByTmdbCollectionID(collectionId) ?? new(collectionId);
var collection = await UseClient(c => c.GetCollectionAsync(collectionId, CollectionMethods.Images | CollectionMethods.Translations), $"Get movie collection {collectionId} for movie {movie.Id} \"{movie.Title}\"").ConfigureAwait(false);
if (collection == null)
{
PurgeMovieCollection(collectionId);
return;
}
var settings = _settingsProvider.GetSettings();
var preferredTitleLanguages = settings.TMDB.DownloadAllTitles ? null : Languages.PreferredNamingLanguages.Select(a => a.Language).ToHashSet();
var preferredOverviewLanguages = settings.TMDB.DownloadAllOverviews ? null : Languages.PreferredDescriptionNamingLanguages.Select(a => a.Language).ToHashSet();
var updated = tmdbCollection.Populate(collection);
updated = UpdateTitlesAndOverviews(tmdbCollection, collection.Translations, preferredTitleLanguages, preferredOverviewLanguages) || updated;
var xrefsToAdd = 0;
var xrefsToSave = new List<TMDB_Collection_Movie>();
var xrefsToRemove = movieXRefs.Where(xref => !collection.Parts.Any(part => xref.TmdbMovieID == part.Id)).ToList();
var movieXref = movieXRefs.FirstOrDefault(xref => xref.TmdbMovieID == movie.Id);
var index = collection.Parts.FindIndex(part => part.Id == movie.Id);
if (index == -1)
index = collection.Parts.Count;
if (movieXref == null)
{
xrefsToAdd++;
xrefsToSave.Add(new(collectionId, movie.Id, index + 1));
}
else if (movieXref.Ordering != index + 1)
{
movieXref.Ordering = index + 1;
xrefsToSave.Add(movieXref);
}
_logger.LogDebug(
"Added/updated/removed/skipped {ta}/{tu}/{tr}/{ts} movie cross-references for movie collection {CollectionTitle} (Id={CollectionId})",
xrefsToAdd,
xrefsToSave.Count - xrefsToAdd,
xrefsToRemove.Count,
movieXRefs.Count + xrefsToAdd - xrefsToRemove.Count - xrefsToSave.Count,
tmdbCollection.EnglishTitle,
tmdbCollection.Id);
_xrefTmdbCollectionMovies.Save(xrefsToSave);
_xrefTmdbCollectionMovies.Delete(xrefsToRemove);
if (updated || xrefsToSave.Count > 0 || xrefsToRemove.Count > 0)
{
tmdbCollection.LastUpdatedAt = DateTime.Now;
_tmdbCollections.Save(tmdbCollection);
}
}
public async Task ScheduleDownloadAllMovieImages(int movieId, bool forceDownload = false)
{
// Schedule the movie info to be downloaded or updated.
await (await _schedulerFactory.GetScheduler().ConfigureAwait(false)).StartJob<DownloadTmdbMovieImagesJob>(c =>
{
c.TmdbMovieID = movieId;
c.ForceDownload = forceDownload;
}).ConfigureAwait(false);
}
public async Task DownloadAllMovieImages(int movieId, bool forceDownload = false)
{
using (await GetLockForEntity(ForeignEntityType.Movie, movieId, "images", "Update").ConfigureAwait(false))
{
var tmdbMovie = _tmdbMovies.GetByTmdbMovieID(movieId);
if (tmdbMovie is null)
return;
await DownloadMovieImages(movieId, tmdbMovie.OriginalLanguage, forceDownload);
}
}
private async Task DownloadMovieImages(int movieId, TitleLanguage? mainLanguage = null, bool forceDownload = false)
{
var settings = _settingsProvider.GetSettings();
if (!settings.TMDB.AutoDownloadPosters && !settings.TMDB.AutoDownloadLogos && !settings.TMDB.AutoDownloadBackdrops)
return;
var images = await UseClient(c => c.GetMovieImagesAsync(movieId), $"Get images for movie {movieId}").ConfigureAwait(false);
var languages = GetLanguages(mainLanguage);
if (settings.TMDB.AutoDownloadPosters)
await _imageService.DownloadImagesByType(images.Posters, ImageEntityType.Poster, ForeignEntityType.Movie, movieId, settings.TMDB.MaxAutoPosters, languages, forceDownload);
if (settings.TMDB.AutoDownloadLogos)
await _imageService.DownloadImagesByType(images.Logos, ImageEntityType.Logo, ForeignEntityType.Movie, movieId, settings.TMDB.MaxAutoLogos, languages, forceDownload);
if (settings.TMDB.AutoDownloadBackdrops)
await _imageService.DownloadImagesByType(images.Backdrops, ImageEntityType.Backdrop, ForeignEntityType.Movie, movieId, settings.TMDB.MaxAutoBackdrops, languages, forceDownload);
}
#endregion
#region Purge (Movies)
public async Task PurgeAllUnusedMovies()
{
var allMovies = _tmdbMovies.GetAll().Select(movie => movie.TmdbMovieID)
.Concat(_tmdbImages.GetAll().Where(image => image.TmdbMovieID.HasValue).Select(image => image.TmdbMovieID!.Value))
.Concat(_xrefAnidbTmdbMovies.GetAll().Select(xref => xref.TmdbMovieID))
.Concat(_xrefTmdbCompanyEntity.GetAll().Where(x => x.TmdbEntityType == ForeignEntityType.Movie).Select(x => x.TmdbEntityID))
.Concat(_tmdbMovieCast.GetAll().Select(x => x.TmdbMovieID))
.Concat(_tmdbMovieCrew.GetAll().Select(x => x.TmdbMovieID))
.Concat(_tmdbCollections.GetAll().Select(collection => collection.TmdbCollectionID))
.Concat(_xrefTmdbCollectionMovies.GetAll().Select(collectionMovie => collectionMovie.TmdbMovieID))
.ToHashSet();
var toKeep = _xrefAnidbTmdbMovies.GetAll()
.Select(xref => xref.TmdbMovieID)
.ToHashSet();
var toBePurged = allMovies
.Except(toKeep)
.ToHashSet();
_logger.LogInformation("Scheduling {Count} out of {AllCount} movies to be purged.", toBePurged.Count, allMovies.Count);
var scheduler = await _schedulerFactory.GetScheduler();
foreach (var movieID in toBePurged)
await scheduler.StartJob<PurgeTmdbMovieJob>(c => c.TmdbMovieID = movieID);
}
public async Task SchedulePurgeOfMovie(int movieId, bool removeImageFiles = true)
{
await (await _schedulerFactory.GetScheduler().ConfigureAwait(false)).StartJob<PurgeTmdbMovieJob>(c =>
{
c.TmdbMovieID = movieId;
c.RemoveImageFiles = removeImageFiles;
});
}
/// <summary>
/// Purge a TMDB movie from the local database.
/// </summary>
/// <param name="movieId">TMDB Movie ID.</param>
/// <param name="removeImageFiles">Remove image files.</param>
public async Task PurgeMovie(int movieId, bool removeImageFiles = true)
{
using (await GetLockForEntity(ForeignEntityType.Movie, movieId, "metadata", "Purge").ConfigureAwait(false))
{
await _linkingService.RemoveAllMovieLinksForMovie(movieId);
_imageService.PurgeImages(ForeignEntityType.Movie, movieId, removeImageFiles);
var movie = _tmdbMovies.GetByTmdbMovieID(movieId);
if (movie != null)
{
_logger.LogTrace("Removing movie {MovieName} (Movie={MovieID})", movie.OriginalTitle, movie.Id);
_tmdbMovies.Delete(movie);
}
PurgeMovieCompanies(movieId, removeImageFiles);
PurgeMovieCastAndCrew(movieId, removeImageFiles);
CleanupMovieCollection(movieId);
PurgeTitlesAndOverviews(ForeignEntityType.Movie, movieId);
}
}
private void PurgeMovieCompanies(int movieId, bool removeImageFiles = true)
{
var xrefsToRemove = _xrefTmdbCompanyEntity.GetByTmdbEntityTypeAndID(ForeignEntityType.Movie, movieId);
foreach (var xref in xrefsToRemove)
{
// Delete xref or purge company.
var xrefs = _xrefTmdbCompanyEntity.GetByTmdbCompanyID(xref.TmdbCompanyID);
if (xrefs.Count > 1)
_xrefTmdbCompanyEntity.Delete(xref);
else
PurgeCompany(xref.TmdbCompanyID, removeImageFiles);
}
}
private async void PurgeMovieCastAndCrew(int movieId, bool removeImageFiles = true)
{
var castMembers = _tmdbMovieCast.GetByTmdbMovieID(movieId);
var crewMembers = _tmdbMovieCrew.GetByTmdbMovieID(movieId);
_tmdbMovieCast.Delete(castMembers);
_tmdbMovieCrew.Delete(crewMembers);
var allPeopleSet = castMembers.Select(c => c.TmdbPersonID)
.Concat(crewMembers.Select(c => c.TmdbPersonID))
.Distinct()
.ToHashSet();
foreach (var personId in allPeopleSet)
await PurgePerson(personId, removeImageFiles);
}
private void CleanupMovieCollection(int movieId, bool removeImageFiles = true)
{
var xref = _xrefTmdbCollectionMovies.GetByTmdbMovieID(movieId);
if (xref == null)
return;
var allXRefs = _xrefTmdbCollectionMovies.GetByTmdbCollectionID(xref.TmdbCollectionID);
if (allXRefs.Count > 1)
_xrefTmdbCollectionMovies.Delete(xref);
else
PurgeMovieCollection(xref.TmdbCollectionID, removeImageFiles);
}
private void PurgeMovieCollection(int collectionId, bool removeImageFiles = true)
{
var collection = _tmdbCollections.GetByTmdbCollectionID(collectionId);
var collectionXRefs = _xrefTmdbCollectionMovies.GetByTmdbCollectionID(collectionId);
if (collectionXRefs.Count > 0)
{
_logger.LogTrace(
"Removing {Count} cross-references for movie collection {CollectionName} (Collection={CollectionID})",
collectionXRefs.Count, collection?.EnglishTitle ?? string.Empty,
collectionId
);
_xrefTmdbCollectionMovies.Delete(collectionXRefs);
}
_imageService.PurgeImages(ForeignEntityType.Collection, collectionId, removeImageFiles);
PurgeTitlesAndOverviews(ForeignEntityType.Collection, collectionId);
if (collection != null)
{
_logger.LogTrace(
"Removing movie collection {CollectionName} (Collection={CollectionID})",
collection.EnglishTitle,
collectionId
);
_tmdbCollections.Delete(collection);
}
}
#endregion
#endregion
#region Shows
#region Genres (Shows)
private IReadOnlyDictionary<int, string>? _tvShowGenres = null;
public async Task<IReadOnlyDictionary<int, string>> GetShowGenres()
{
if (_tvShowGenres is not null)
return _tvShowGenres;
using (await GetLockForEntity(ForeignEntityType.Show, 0, "genre", "Load").ConfigureAwait(false))
{
if (_tvShowGenres is not null)
return _tvShowGenres;
var genres = await UseClient(c => c.GetTvGenresAsync(), "Get TV Show Genres").ConfigureAwait(false);
_tvShowGenres = genres.ToDictionary(x => x.Id, x => x.Name);
return _tvShowGenres;
}
}
#endregion
#region Update (Shows)
public async Task UpdateAllShows(bool force = false, bool downloadImages = false)
{
var allXRefs = _xrefAnidbTmdbShows.GetAll();
_logger.LogInformation("Scheduling {Count} shows to be updated.", allXRefs.Count);
var scheduler = await _schedulerFactory.GetScheduler();
foreach (var xref in allXRefs)
{
await scheduler.StartJob<UpdateTmdbShowJob>(
c =>
{
c.TmdbShowID = xref.TmdbShowID;
c.ForceRefresh = force;
c.DownloadImages = downloadImages;
}
).ConfigureAwait(false);
}
}
public bool IsShowUpdating(int showId)
=> IsEntityLocked(ForeignEntityType.Show, showId, "metadata");
public async Task ScheduleUpdateOfShow(int showId, bool forceRefresh = false, bool downloadImages = false, bool? downloadCrewAndCast = null, bool? downloadAlternateOrdering = null)
{
// Schedule the show info to be downloaded or updated.
await (await _schedulerFactory.GetScheduler().ConfigureAwait(false)).StartJob<UpdateTmdbShowJob>(c =>
{
c.TmdbShowID = showId;
c.ForceRefresh = forceRefresh;
c.DownloadImages = downloadImages;
c.DownloadCrewAndCast = downloadCrewAndCast;
c.DownloadAlternateOrdering = downloadAlternateOrdering;
}).ConfigureAwait(false);
}
public async Task<bool> UpdateShow(int showId, bool forceRefresh = false, bool downloadImages = false, bool downloadCrewAndCast = false, bool downloadAlternateOrdering = false, bool quickRefresh = false)
{
using (await GetLockForEntity(ForeignEntityType.Show, showId, "metadata", "Update").ConfigureAwait(false))
{
// Abort if we're within a certain time frame as to not try and get us rate-limited.
var tmdbShow = _tmdbShows.GetByTmdbShowID(showId) ?? new(showId);
var newlyAdded = tmdbShow.CreatedAt == tmdbShow.LastUpdatedAt;
var xrefs = _xrefAnidbTmdbShows.GetByTmdbShowID(showId);
if (!forceRefresh && tmdbShow.CreatedAt != tmdbShow.LastUpdatedAt && tmdbShow.LastUpdatedAt > DateTime.Now.AddHours(-1))
{
_logger.LogInformation("Skipping update of show {ShowID} as it was last updated {LastUpdatedAt}", showId, tmdbShow.LastUpdatedAt);
// Do the auto-matching if we're not doing a quick refresh.
if (!quickRefresh)
foreach (var xref in xrefs)
_linkingService.MatchAnidbToTmdbEpisodes(xref.AnidbAnimeID, xref.TmdbShowID, null, true, true);
return false;
}
var methods = TvShowMethods.ContentRatings | TvShowMethods.Translations | TvShowMethods.ExternalIds;
if (downloadAlternateOrdering && !quickRefresh)
methods |= TvShowMethods.EpisodeGroups;
var show = await UseClient(c => c.GetTvShowAsync(showId, methods, "en-US"), $"Get Show {showId}").ConfigureAwait(false);
if (show == null)
return false;
var settings = _settingsProvider.GetSettings();
var preferredTitleLanguages = settings.TMDB.DownloadAllTitles ? null : Languages.PreferredNamingLanguages.Select(a => a.Language).ToHashSet();
var preferredOverviewLanguages = settings.TMDB.DownloadAllOverviews ? null : Languages.PreferredDescriptionNamingLanguages.Select(a => a.Language).ToHashSet();
var contentRantingLanguages = settings.TMDB.DownloadAllContentRatings
? null
: Languages.PreferredNamingLanguages.Select(a => a.Language)
.Concat(Languages.PreferredEpisodeNamingLanguages.Select(a => a.Language))
.Except([TitleLanguage.Main, TitleLanguage.Unknown, TitleLanguage.None])
.ToHashSet();
var shouldFireEvents = !quickRefresh || xrefs.Count > 0;
var updated = tmdbShow.Populate(show, contentRantingLanguages);
var (titlesUpdated, overviewsUpdated) = UpdateTitlesAndOverviewsWithTuple(tmdbShow, show.Translations, preferredTitleLanguages, preferredOverviewLanguages);
updated = titlesUpdated || overviewsUpdated || updated;
updated = UpdateShowExternalIDs(tmdbShow, show.ExternalIds) || updated;
updated = await UpdateCompanies(tmdbShow, show.ProductionCompanies) || updated;
var (episodesOrSeasonsUpdated, updatedEpisodes) = await UpdateShowSeasonsAndEpisodes(show, downloadCrewAndCast, forceRefresh, downloadImages, quickRefresh, shouldFireEvents);
updated = episodesOrSeasonsUpdated || updated;
if (downloadAlternateOrdering && !quickRefresh)
updated = await UpdateShowAlternateOrdering(show) || updated;
if (newlyAdded || updated)
{
if (shouldFireEvents)
tmdbShow.LastUpdatedAt = DateTime.Now;
_tmdbShows.Save(tmdbShow);
}