forked from ShokoAnime/ShokoServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTmdbController.cs
2778 lines (2400 loc) · 115 KB
/
TmdbController.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.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Shoko.Commons.Extensions;
using Shoko.Plugin.Abstractions.DataModels;
using Shoko.Plugin.Abstractions.Extensions;
using Shoko.Server.API.Annotations;
using Shoko.Server.API.ModelBinders;
using Shoko.Server.API.v3.Helpers;
using Shoko.Server.API.v3.Models.Common;
using Shoko.Server.API.v3.Models.Shoko;
using Shoko.Server.API.v3.Models.TMDB.Input;
using Shoko.Server.Extensions;
using Shoko.Server.Models.CrossReference;
using Shoko.Server.Models.TMDB;
using Shoko.Server.Providers.TMDB;
using Shoko.Server.Repositories;
using Shoko.Server.Settings;
using Shoko.Server.Utilities;
using CrossRefSource = Shoko.Models.Enums.CrossRefSource;
using DataSource = Shoko.Server.API.v3.Models.Common.DataSource;
using File = Shoko.Server.API.v3.Models.Shoko.File;
using InternalEpisodeType = Shoko.Models.Enums.EpisodeType;
using MatchRating = Shoko.Models.Enums.MatchRating;
using TmdbEpisode = Shoko.Server.API.v3.Models.TMDB.Episode;
using TmdbMovie = Shoko.Server.API.v3.Models.TMDB.Movie;
using TmdbSearch = Shoko.Server.API.v3.Models.TMDB.Search;
using TmdbSeason = Shoko.Server.API.v3.Models.TMDB.Season;
using TmdbShow = Shoko.Server.API.v3.Models.TMDB.Show;
#pragma warning disable CA1822
#nullable enable
namespace Shoko.Server.API.v3.Controllers;
[ApiController]
[Route("/api/v{version:apiVersion}/[controller]")]
[ApiV3]
[Authorize]
public partial class TmdbController : BaseController
{
private readonly ILogger<TmdbController> _logger;
private readonly TmdbSearchService _tmdbSearchService;
private readonly TmdbMetadataService _tmdbMetadataService;
public TmdbController(ISettingsProvider settingsProvider, ILogger<TmdbController> logger, TmdbSearchService tmdbSearchService, TmdbMetadataService tmdbService) : base(settingsProvider)
{
_logger = logger;
_tmdbSearchService = tmdbSearchService;
_tmdbMetadataService = tmdbService;
}
#region Movies
#region Constants
internal const string MovieNotFound = "A TMDB.Movie by the given `movieID` was not found.";
#endregion
#region Basics
/// <summary>
/// List all locally available tmdb movies.
/// </summary>
/// <param name="search"></param>
/// <param name="fuzzy"></param>
/// <param name="include"></param>
/// <param name="restricted"></param>
/// <param name="video"></param>
/// <param name="pageSize"></param>
/// <param name="page"></param>
/// <returns></returns>
[HttpGet("Movie")]
public ActionResult<ListResult<TmdbMovie>> GetTmdbMovies(
[FromQuery] string? search = null,
[FromQuery] bool fuzzy = true,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TmdbMovie.IncludeDetails>? include = null,
[FromQuery] IncludeOnlyFilter restricted = IncludeOnlyFilter.True,
[FromQuery] IncludeOnlyFilter video = IncludeOnlyFilter.True,
[FromQuery, Range(0, 1000)] int pageSize = 50,
[FromQuery, Range(1, int.MaxValue)] int page = 1
)
{
var hasSearch = !string.IsNullOrWhiteSpace(search);
var movies = RepoFactory.TMDB_Movie.GetAll()
.AsParallel()
.Where(movie =>
{
if (restricted != IncludeOnlyFilter.True)
{
var includeRestricted = restricted == IncludeOnlyFilter.Only;
var isRestricted = movie.IsRestricted;
if (isRestricted != includeRestricted)
return false;
}
if (video != IncludeOnlyFilter.True)
{
var includeVideo = video == IncludeOnlyFilter.Only;
var isVideo = movie.IsVideo;
if (isVideo != includeVideo)
return false;
}
return true;
});
if (hasSearch)
{
var languages = SettingsProvider.GetSettings()
.Language.DescriptionLanguageOrder
.Select(lang => lang.GetTitleLanguage())
.Concat(new TitleLanguage[] { TitleLanguage.English })
.ToHashSet();
return movies
.Search(
search,
movie => movie.GetAllTitles()
.WhereInLanguages(languages)
.Select(title => title.Value)
.Append(movie.EnglishTitle)
.Append(movie.OriginalTitle)
.Distinct()
.ToList(),
fuzzy
)
.ToListResult(a => new TmdbMovie(a.Result, include?.CombineFlags()), page, pageSize);
}
return movies
.OrderBy(movie => movie.EnglishTitle)
.ThenBy(movie => movie.TmdbMovieID)
.ToListResult(m => new TmdbMovie(m, include?.CombineFlags()), page, pageSize);
}
[HttpPost("Movie/Bulk")]
public ActionResult<List<TmdbMovie>> BulkGetTmdbMoviesByMovieIDs([FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Disallow)] TmdbBulkFetchBody<TmdbMovie.IncludeDetails> body) =>
body.IDs
.Select(episodeID => episodeID <= 0 ? null : RepoFactory.TMDB_Movie.GetByTmdbMovieID(episodeID))
.WhereNotNull()
.Select(episode => new TmdbMovie(episode, body.Include?.CombineFlags(), body.Language))
.ToList();
/// <summary>
/// Get the local metadata for a TMDB movie.
/// </summary>
/// <param name="movieID">TMDB Movie ID.</param>
/// <param name="include"></param>
/// <param name="language"></param>
/// <returns></returns>
[HttpGet("Movie/{movieID}")]
public ActionResult<TmdbMovie> GetTmdbMovieByMovieID(
[FromRoute] int movieID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TmdbMovie.IncludeDetails>? include = null,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
return new TmdbMovie(movie, include?.CombineFlags(), language);
}
/// <summary>
/// Remove the local copy of the metadata for a TMDB movie.
/// </summary>
/// <param name="movieID">TMDB Movie ID.</param>
/// <param name="removeImageFiles">Also remove images related to the show.</param>
/// <returns></returns>
[Authorize("admin")]
[HttpDelete("Movie/{movieID}")]
public async Task<ActionResult> RemoveTmdbMovieByMovieID(
[FromRoute] int movieID,
[FromQuery] bool removeImageFiles = true
)
{
await _tmdbMetadataService.SchedulePurgeOfMovie(movieID, removeImageFiles);
return NoContent();
}
[HttpGet("Movie/{movieID}/Titles")]
public ActionResult<IReadOnlyList<Title>> GetTitlesForTmdbMovieByMovieID(
[FromRoute] int movieID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
var preferredTitle = movie.GetPreferredTitle();
return new(movie.GetAllTitles().ToDto(movie.EnglishTitle, preferredTitle, language));
}
[HttpGet("Movie/{movieID}/Overviews")]
public ActionResult<IReadOnlyList<Overview>> GetOverviewsForTmdbMovieByMovieID(
[FromRoute] int movieID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
var preferredOverview = movie.GetPreferredOverview();
return new(movie.GetAllOverviews().ToDto(movie.EnglishTitle, preferredOverview, language));
}
[HttpGet("Movie/{movieID}/Images")]
public ActionResult<Images> GetImagesForTmdbMovieByMovieID(
[FromRoute] int movieID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
return movie.GetImages()
.ToDto(language);
}
[HttpGet("Movie/{movieID}/Cast")]
public ActionResult<IReadOnlyList<Role>> GetCastForTmdbMovieByMovieID(
[FromRoute] int movieID
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
return movie.Cast
.Select(cast => new Role(cast))
.ToList();
}
[HttpGet("Movie/{movieID}/Crew")]
public ActionResult<IReadOnlyList<Role>> GetCrewForTmdbMovieByMovieID(
[FromRoute] int movieID
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
return movie.Crew
.Select(cast => new Role(cast))
.ToList();
}
[HttpGet("Movie/{movieID}/CrossReferences")]
public ActionResult<IReadOnlyList<TmdbMovie.CrossReference>> GetCrossReferencesForTmdbMovieByMovieID(
[FromRoute] int movieID
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
return movie.CrossReferences
.Select(xref => new TmdbMovie.CrossReference(xref))
.ToList();
}
[HttpGet("Movie/{movieID}/FileCrossReferences")]
public ActionResult<IReadOnlyList<FileCrossReference>> GetFileCrossReferencesForTmdbMovieByMovieID(
[FromRoute] int movieID
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
return FileCrossReference.From(movie.FileCrossReferences);
}
[HttpGet("Movie/{movieID}/Studios")]
public ActionResult<IReadOnlyList<Studio>> GetStudiosForTmdbMovieByMovieID(
[FromRoute] int movieID
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
return movie.GetTmdbCompanies()
.Select(company => new Studio(company))
.ToList();
}
[HttpGet("Movie/{movieID}/ContentRatings")]
public ActionResult<IReadOnlyList<ContentRating>> GetContentRatingsForTmdbMovieByMovieID(
[FromRoute] int movieID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
return new(movie.ContentRatings.ToDto(language));
}
#endregion
#region Same-Source Linked Entries
[HttpGet("Movie/{movieID}/Collection")]
public ActionResult<TmdbMovie.Collection> GetTmdbMovieCollectionByMovieID(
[FromRoute] int movieID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TmdbMovie.Collection.IncludeDetails>? include = null
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
var movieCollection = movie.TmdbCollection;
if (movieCollection is null)
return NotFound(MovieCollectionByMovieIDNotFound);
return new TmdbMovie.Collection(movieCollection, include?.CombineFlags());
}
#endregion
#region Cross-Source Linked Entries
/// <summary>
/// Get all AniDB series linked to a TMDB movie.
/// </summary>
/// <param name="movieID">TMDB Movie ID.</param>
/// <returns></returns>
[HttpGet("Movie/{movieID}/AniDB/Anime")]
public ActionResult<List<Series.AniDB>> GetAniDBAnimeByTmdbMovieID(
[FromRoute] int movieID
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
return movie.CrossReferences
.Select(xref => xref.AnidbAnime)
.WhereNotNull()
.Select(anime => new Series.AniDB(anime))
.ToList();
}
/// <summary>
/// Get all AniDB episodes linked to a TMDB movie.
/// </summary>
/// <param name="movieID">TMDB Movie ID.</param>
/// <returns></returns>
[HttpGet("Movie/{movieID}/AniDB/Episodes")]
public ActionResult<List<Episode.AniDB>> GetAniDBEpisodesByTmdbMovieID(
[FromRoute] int movieID
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
return movie.CrossReferences
.Select(xref => xref.AnidbEpisode)
.WhereNotNull()
.Select(episode => new Episode.AniDB(episode))
.ToList();
}
/// <summary>
/// Get all Shoko series linked to a TMDB movie.
/// </summary>
/// <param name="movieID">TMDB Movie ID.</param>
/// <param name="randomImages">Randomize images shown for the <see cref="Series"/>.</param>
/// <param name="includeDataFrom">Include data from selected <see cref="DataSource"/>s.</param>
/// <returns></returns>
[HttpGet("Movie/{movieID}/Shoko/Series")]
public ActionResult<List<Series>> GetShokoSeriesByTmdbMovieID(
[FromRoute] int movieID,
[FromQuery] bool randomImages = false,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<DataSource>? includeDataFrom = null
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
return movie.CrossReferences
.Select(xref => xref.AnimeSeries)
.WhereNotNull()
.Select(series => new Series(series, User.JMMUserID, randomImages, includeDataFrom))
.ToList();
}
/// <summary>
/// Get all Shoko episodes linked to a TMDB movie.
/// </summary>
/// <param name="movieID">TMDB Movie ID.</param>
/// <param name="includeDataFrom">Include data from selected <see cref="DataSource"/>s.</param>
/// <returns></returns>
[HttpGet("Movie/{movieID}/Shoko/Episodes")]
public ActionResult<List<Episode>> GetShokoEpisodesByTmdbMovieID(
[FromRoute] int movieID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<DataSource>? includeDataFrom = null
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
return movie.CrossReferences
.Select(xref => xref.AnimeEpisode)
.WhereNotNull()
.Select(episode => new Episode(HttpContext, episode, includeDataFrom))
.ToList();
}
/// <summary>
/// Get all files linked to a TMDB Movie.
/// </summary>
/// <param name="movieID">TMDB Movie ID.</param>
/// <param name="pageSize">Limits the number of results per page. Set to 0 to disable the limit.</param>
/// <param name="page">Page number.</param>
/// <param name="include">Include items that are not included by default</param>
/// <param name="exclude">Exclude items of certain types</param>
/// <param name="include_only">Filter to only include items of certain types</param>
/// <param name="sortOrder">Sort ordering. Attach '-' at the start to reverse the order of the criteria.</param>
/// <param name="includeDataFrom">Include data from selected <see cref="DataSource"/>s.</param>
/// <returns></returns>
[HttpGet("Movie/{movieID}/Shoko/Files")]
public ActionResult<ListResult<File>> GetShokoFilesByMovieID(
[FromRoute] int movieID,
[FromQuery, Range(0, 1000)] int pageSize = 100,
[FromQuery, Range(1, int.MaxValue)] int page = 1,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] FileNonDefaultIncludeType[]? include = null,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] FileExcludeTypes[]? exclude = null,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] FileIncludeOnlyType[]? include_only = null,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] List<string>? sortOrder = null,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<DataSource>? includeDataFrom = null
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
var videoLocals = movie.CrossReferences
.Select(xref => xref.AnimeEpisode)
.WhereNotNull()
.SelectMany(xref => xref.VideoLocals)
.DistinctBy(video => video.VideoLocalID);
return ModelHelper.FilterFiles(videoLocals, User, pageSize, page, include, exclude, include_only, sortOrder, includeDataFrom);
}
#endregion
#region Actions
/// <summary>
/// Refresh or download the metadata for a TMDB movie.
/// </summary>
/// <param name="movieID">TMDB Movie ID.</param>
/// <param name="body">Body containing options for refreshing or downloading metadata.</param>
/// <returns>
/// If <paramref name="body.Immediate"/> is <see langword="true"/>, returns an <see cref="OkResult"/>,
/// otherwise returns a <see cref="NoContentResult"/>.
/// </returns>
[Authorize("admin")]
[HttpPost("Movie/{movieID}/Action/Refresh")]
public async Task<ActionResult> RefreshTmdbMovieByMovieID(
[FromRoute] int movieID,
[FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Disallow)] TmdbRefreshMovieBody body
)
{
if (body.SkipIfExists)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is not null)
return Ok();
}
if (body.Immediate)
{
await _tmdbMetadataService.UpdateMovie(movieID, body.Force, body.DownloadImages, body.DownloadCrewAndCast ?? SettingsProvider.GetSettings().TMDB.AutoDownloadCrewAndCast, body.DownloadCollections ?? SettingsProvider.GetSettings().TMDB.AutoDownloadCollections);
return Ok();
}
await _tmdbMetadataService.ScheduleUpdateOfMovie(movieID, body.Force, body.DownloadImages, body.DownloadCrewAndCast, body.DownloadCollections);
return NoContent();
}
/// <summary>
/// Download images for a TMDB movie.
/// </summary>
/// <param name="movieID">TMDB Movie ID.</param>
/// <param name="body">Body containing options for downloading images.</param>
/// <returns>
/// If <paramref name="body.Immediate"/> is <see langword="true"/>, returns an <see cref="OkResult"/>,
/// otherwise returns a <see cref="NoContentResult"/>.
/// </returns>
[Authorize("admin")]
[HttpPost("Movie/{movieID}/Action/DownloadImages")]
public async Task<ActionResult> DownloadImagesForTmdbMovieByMovieID(
[FromRoute] int movieID,
[FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Disallow)] TmdbDownloadImagesBody body
)
{
var movie = RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID);
if (movie is null)
return NotFound(MovieNotFound);
if (body.Immediate)
{
await _tmdbMetadataService.DownloadAllMovieImages(movieID, body.Force);
return Ok();
}
await _tmdbMetadataService.ScheduleDownloadAllMovieImages(movieID, body.Force);
return NoContent();
}
#endregion
#region Online (Search / Bulk / Single)
/// <summary>
/// Search TMDB for movies using the offline or online search.
/// </summary>
/// <param name="query">Query to search for.</param>
/// <param name="includeRestricted">Include restricted movies.</param>
/// <param name="year">First aired year.</param>
/// <param name="pageSize">The page size. Set to 0 to only grab the total.</param>
/// <param name="page">The page index.</param>
/// <returns></returns>
[Authorize("admin")]
[HttpGet("Movie/Online/Search")]
public ListResult<TmdbSearch.RemoteSearchMovie> SearchOnlineForTmdbMovies(
[FromQuery] string query,
[FromQuery] bool includeRestricted = false,
[FromQuery, Range(0, int.MaxValue)] int year = 0,
[FromQuery, Range(0, 100)] int pageSize = 6,
[FromQuery, Range(1, int.MaxValue)] int page = 1
)
{
var (pageView, totalMovies) = _tmdbSearchService.SearchMovies(query, includeRestricted, year, page, pageSize)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
return new ListResult<TmdbSearch.RemoteSearchMovie>(totalMovies, pageView.Select(a => new TmdbSearch.RemoteSearchMovie(a)));
}
/// <summary>
/// Search for multiple TMDB movies by their IDs.
/// </summary>
/// <remarks>
/// If any of the IDs are not found, a <see cref="ValidationProblemDetails"/> is returned.
/// </remarks>
/// <param name="body">Body containing the IDs of the movies to search for.</param>
/// <returns>
/// A list of <see cref="TmdbSearch.RemoteSearchMovie"/> containing the search results.
/// The order of the returned movies is determined by the order of the IDs in <paramref name="body"/>.
/// </returns>
[HttpPost("Movie/Online/Bulk")]
public async Task<ActionResult<List<TmdbSearch.RemoteSearchMovie>>> SearchBulkForTmdbMovies(
[FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Disallow)] TmdbBulkSearchBody body
)
{
// We don't care if the inputs are non-unique, but we don't want to double fetch,
// so we do a distinct here, then at the end we map back to the original order.
var uniqueIds = body.IDs.Distinct().ToList();
var movieDict = uniqueIds
.Select(id => id <= 0 ? null : RepoFactory.TMDB_Movie.GetByTmdbMovieID(id))
.WhereNotNull()
.Select(movie => new TmdbSearch.RemoteSearchMovie(movie))
.ToDictionary(movie => movie.ID);
foreach (var id in uniqueIds.Except(movieDict.Keys))
{
var movie = id <= 0 ? null : await _tmdbMetadataService.UseClient(c => c.GetMovieAsync(id), $"Get movie {id}");
if (movie is null)
continue;
movieDict[movie.Id] = new TmdbSearch.RemoteSearchMovie(movie);
}
var unknownMovies = uniqueIds.Except(movieDict.Keys).ToList();
if (unknownMovies.Count > 0)
{
foreach (var id in unknownMovies)
ModelState.AddModelError(nameof(body.IDs), $"Movie with id '{id}' not found.");
return ValidationProblem(ModelState);
}
return body.IDs
.Select(id => movieDict[id])
.ToList();
}
/// <summary>
/// Search TMDB for a movie.
/// </summary>
/// <param name="movieID">TMDB Movie ID.</param>
/// <returns>
/// If the movie is already in the database, returns the local copy.
/// Otherwise, returns the remote copy from TMDB.
/// If the movie is not found on TMDB, returns 404.
/// </returns>
[HttpGet("Movie/Online/{movieID}")]
public async Task<ActionResult<TmdbSearch.RemoteSearchMovie>> SearchOnlineForTmdbMovieByMovieID(
[FromRoute] int movieID
)
{
if (RepoFactory.TMDB_Movie.GetByTmdbMovieID(movieID) is { } localMovie)
return new TmdbSearch.RemoteSearchMovie(localMovie);
if (await _tmdbMetadataService.UseClient(c => c.GetMovieAsync(movieID), $"Get movie {movieID}") is not { } remoteMovie)
return NotFound("Movie not found on TMDB.");
return new TmdbSearch.RemoteSearchMovie(remoteMovie);
}
#endregion
#endregion
#region Movie Collection
#region Constants
internal const string MovieCollectionNotFound = "A TMDB.MovieCollection by the given `collectionID` was not found.";
internal const string MovieCollectionByMovieIDNotFound = "A TMDB.MovieCollection by the given `movieID` was not found.";
#endregion
#region Basics
[HttpGet("Movie/Collection")]
public ActionResult<ListResult<TmdbMovie.Collection>> GetMovieCollections(
[FromRoute] string search,
[FromQuery] bool fuzzy = true,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TmdbMovie.Collection.IncludeDetails>? include = null,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null,
[FromQuery, Range(0, 1000)] int pageSize = 50,
[FromQuery, Range(1, int.MaxValue)] int page = 1
)
{
if (!string.IsNullOrWhiteSpace(search))
{
var languages = SettingsProvider.GetSettings()
.Language.DescriptionLanguageOrder
.Select(lang => lang.GetTitleLanguage())
.Concat(new TitleLanguage[] { TitleLanguage.English })
.ToHashSet();
return RepoFactory.TMDB_Collection.GetAll()
.Search(
search,
collection => collection.GetAllTitles()
.WhereInLanguages(languages)
.Select(title => title.Value)
.Append(collection.EnglishTitle)
.Distinct()
.ToList(),
fuzzy
)
.ToListResult(a => new TmdbMovie.Collection(a.Result, include?.CombineFlags(), language), page, pageSize);
}
return RepoFactory.TMDB_Collection.GetAll()
.ToListResult(a => new TmdbMovie.Collection(a, include?.CombineFlags(), language), page, pageSize);
}
[HttpGet("Movie/Collection/{collectionID}")]
public ActionResult<TmdbMovie.Collection> GetMovieCollectionByCollectionID(
[FromRoute] int collectionID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TmdbMovie.Collection.IncludeDetails>? include = null,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var collection = RepoFactory.TMDB_Collection.GetByTmdbCollectionID(collectionID);
if (collection is null)
return NotFound(MovieCollectionNotFound);
return new TmdbMovie.Collection(collection, include?.CombineFlags(), language);
}
[HttpGet("Movie/Collection/{collectionID}/Titles")]
public ActionResult<IReadOnlyList<Title>> GetTitlesForMovieCollectionByCollectionID(
[FromRoute] int collectionID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var collection = RepoFactory.TMDB_Collection.GetByTmdbCollectionID(collectionID);
if (collection is null)
return NotFound(MovieCollectionNotFound);
var preferredTitle = collection.GetPreferredTitle();
return new(collection.GetAllTitles().ToDto(collection.EnglishTitle, preferredTitle, language));
}
[HttpGet("Movie/Collection/{collectionID}/Overviews")]
public ActionResult<IReadOnlyList<Overview>> GetOverviewsForMovieCollectionByCollectionID(
[FromRoute] int collectionID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var collection = RepoFactory.TMDB_Collection.GetByTmdbCollectionID(collectionID);
if (collection is null)
return NotFound(MovieCollectionNotFound);
var preferredOverview = collection.GetPreferredOverview();
return new(collection.GetAllOverviews().ToDto(collection.EnglishTitle, preferredOverview, language));
}
[HttpGet("Movie/Collection/{collectionID}/Images")]
public ActionResult<Images> GetImagesForMovieCollectionByCollectionID(
[FromRoute] int collectionID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var collection = RepoFactory.TMDB_Collection.GetByTmdbCollectionID(collectionID);
if (collection is null)
return NotFound(MovieCollectionNotFound);
return collection.GetImages()
.ToDto(language);
}
#endregion
#region Same-Source Linked Entries
[HttpGet("Movie/Collection/{collectionID}/Movie")]
public ActionResult<List<TmdbMovie>> GetMoviesForMovieCollectionByCollectionID(
[FromRoute] int collectionID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TmdbMovie.IncludeDetails>? include = null,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var collection = RepoFactory.TMDB_Collection.GetByTmdbCollectionID(collectionID);
if (collection is null)
return NotFound(MovieCollectionNotFound);
return collection.GetTmdbMovies()
.Select(movie => new TmdbMovie(movie, include?.CombineFlags(), language))
.ToList();
}
#endregion
#endregion
#region Shows
#region Constants
internal const string AlternateOrderingIdRegex = @"^(?:[0-9]{1,23}|[a-f0-9]{24})$";
internal const string ShowNotFound = "A TMDB.Show by the given `showID` was not found.";
internal const string ShowNotFoundBySeasonID = "A TMDB.Show by the given `seasonID` was not found";
internal const string ShowNotFoundByOrderingID = "A TMDB.Show by the given `orderingID` was not found";
internal const string ShowNotFoundByEpisodeID = "A TMDB.Show by the given `episodeID` was not found";
#endregion
#region Basics
/// <summary>
/// List all locally available tmdb shows.
/// </summary>
/// <param name="search"></param>
/// <param name="fuzzy"></param>
/// <param name="include"></param>
/// <param name="language"></param>
/// <param name="restricted"></param>
/// <param name="pageSize"></param>
/// <param name="page"></param>
/// <returns></returns>
[HttpGet("Show")]
public ActionResult<ListResult<TmdbShow>> GetTmdbShows(
[FromQuery] string? search = null,
[FromQuery] bool fuzzy = true,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TmdbShow.IncludeDetails>? include = null,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null,
[FromQuery] IncludeOnlyFilter restricted = IncludeOnlyFilter.True,
[FromQuery, Range(0, 1000)] int pageSize = 50,
[FromQuery, Range(1, int.MaxValue)] int page = 1
)
{
var hasSearch = !string.IsNullOrWhiteSpace(search);
var shows = RepoFactory.TMDB_Show.GetAll()
.AsParallel()
.Where(show =>
{
if (restricted != IncludeOnlyFilter.True)
{
var includeRestricted = restricted == IncludeOnlyFilter.Only;
var isRestricted = show.IsRestricted;
if (isRestricted != includeRestricted)
return false;
}
return true;
});
if (hasSearch)
{
var languages = SettingsProvider.GetSettings()
.Language.DescriptionLanguageOrder
.Select(lang => lang.GetTitleLanguage())
.Concat(new TitleLanguage[] { TitleLanguage.English })
.ToHashSet();
return shows
.Search(
search,
show => show.GetAllTitles()
.WhereInLanguages(languages)
.Select(title => title.Value)
.Append(show.EnglishTitle)
.Append(show.OriginalTitle)
.Distinct()
.ToList(),
fuzzy
)
.ToListResult(a => new TmdbShow(a.Result, include?.CombineFlags(), language), page, pageSize);
}
return shows
.OrderBy(show => show.EnglishTitle)
.ThenBy(show => show.TmdbShowID)
.ToListResult(m => new TmdbShow(m, include?.CombineFlags()), page, pageSize);
}
[HttpPost("Show/Bulk")]
public ActionResult<List<TmdbShow>> BulkGetTmdbShowsByShowIDs([FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Disallow)] TmdbBulkFetchBody<TmdbShow.IncludeDetails> body) =>
body.IDs
.Select(episodeID => episodeID <= 0 ? null : RepoFactory.TMDB_Show.GetByTmdbShowID(episodeID))
.WhereNotNull()
.Select(episode => new TmdbShow(episode, body.Include?.CombineFlags(), body.Language))
.ToList();
/// <summary>
/// Get the local metadata for a TMDB show.
/// </summary>
/// <returns></returns>
[HttpGet("Show/{showID}")]
public ActionResult<TmdbShow> GetTmdbShowByShowID(
[FromRoute] int showID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TmdbShow.IncludeDetails>? include = null,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null,
[FromQuery, RegularExpression(AlternateOrderingIdRegex)] string? alternateOrderingID = null
)
{
var show = RepoFactory.TMDB_Show.GetByTmdbShowID(showID);
if (show is null)
return NotFound(ShowNotFound);
if (string.IsNullOrEmpty(alternateOrderingID) && !string.IsNullOrWhiteSpace(show.PreferredAlternateOrderingID))
alternateOrderingID = show.PreferredAlternateOrderingID;
if (!string.IsNullOrWhiteSpace(alternateOrderingID))
{
if (alternateOrderingID.Length == SeasonIdHexLength)
{
var alternateOrdering = RepoFactory.TMDB_AlternateOrdering.GetByTmdbEpisodeGroupCollectionID(alternateOrderingID);
if (alternateOrdering is null || alternateOrdering.TmdbShowID != show.TmdbShowID)
return ValidationProblem("Invalid alternateOrderingID for show.", "alternateOrderingID");
return new TmdbShow(show, alternateOrdering, include?.CombineFlags(), language);
}
if (alternateOrderingID != show.Id.ToString())
return ValidationProblem("Invalid alternateOrderingID for show.", "alternateOrderingID");
}
return new TmdbShow(show, include?.CombineFlags());
}
/// <summary>
/// Remove the local copy of the metadata for a TMDB show.
/// </summary>
/// <param name="showID">TMDB Movie ID.</param>
/// <param name="removeImageFiles">Also remove images related to the show.</param>
/// <returns></returns>
[Authorize("admin")]
[HttpDelete("Show/{showID}")]
public async Task<ActionResult> RemoveTmdbShowByShowID(
[FromRoute] int showID,
[FromQuery] bool removeImageFiles = true
)
{
await _tmdbMetadataService.SchedulePurgeOfShow(showID, removeImageFiles);
return NoContent();
}
[HttpGet("Show/{showID}/Titles")]
public ActionResult<IReadOnlyList<Title>> GetTitlesForTmdbShowByShowID(
[FromRoute] int showID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var show = RepoFactory.TMDB_Show.GetByTmdbShowID(showID);
if (show is null)
return NotFound(ShowNotFound);
var preferredTitle = show.GetPreferredTitle();
return new(show.GetAllTitles().ToDto(show.EnglishTitle, preferredTitle, language));
}
[HttpGet("Show/{showID}/Overviews")]
public ActionResult<IReadOnlyList<Overview>> GetOverviewsForTmdbShowByShowID(
[FromRoute] int showID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var show = RepoFactory.TMDB_Show.GetByTmdbShowID(showID);
if (show is null)
return NotFound(ShowNotFound);
var preferredOverview = show.GetPreferredOverview();
return new(show.GetAllOverviews().ToDto(show.EnglishOverview, preferredOverview, language));
}
[HttpGet("Show/{showID}/Images")]
public ActionResult<Images> GetImagesForTmdbShowByShowID(
[FromRoute] int showID,
[FromQuery, ModelBinder(typeof(CommaDelimitedModelBinder))] HashSet<TitleLanguage>? language = null
)
{
var show = RepoFactory.TMDB_Show.GetByTmdbShowID(showID);
if (show is null)
return NotFound(ShowNotFound);
return show.GetImages()
.ToDto(language);
}
[HttpGet("Show/{showID}/Ordering")]
public ActionResult<IReadOnlyList<TmdbShow.OrderingInformation>> GetOrderingForTmdbShowByShowID(
[FromRoute] int showID,
[FromQuery, RegularExpression(AlternateOrderingIdRegex)] string? alternateOrderingID = null
)
{
var show = RepoFactory.TMDB_Show.GetByTmdbShowID(showID);
if (show is null)
return NotFound(ShowNotFound);
if (string.IsNullOrEmpty(alternateOrderingID) && !string.IsNullOrWhiteSpace(show.PreferredAlternateOrderingID))
alternateOrderingID = show.PreferredAlternateOrderingID;
if (!string.IsNullOrWhiteSpace(alternateOrderingID) && alternateOrderingID.Length != SeasonIdHexLength && alternateOrderingID != show.Id.ToString())
return ValidationProblem("Invalid alternateOrderingID for show.", "alternateOrderingID");
var alternateOrdering = !string.IsNullOrWhiteSpace(alternateOrderingID) ? RepoFactory.TMDB_AlternateOrdering.GetByTmdbEpisodeGroupCollectionID(alternateOrderingID) : null;
if (alternateOrdering is null || alternateOrdering.TmdbShowID != show.TmdbShowID)
return ValidationProblem("Invalid alternateOrderingID for show.", "alternateOrderingID");
var ordering = new List<TmdbShow.OrderingInformation>
{
new(show, alternateOrdering),
};
foreach (var altOrder in show.TmdbAlternateOrdering)
ordering.Add(new(show, altOrder, alternateOrdering));
return ordering
.OrderByDescending(o => o.InUse)
.ThenByDescending(o => string.IsNullOrEmpty(o.OrderingID))
.ThenBy(o => o.OrderingName)
.ToList();
}
[HttpPost("Show/{showID}/Ordering/SetPreferred")]
public ActionResult SetPreferredTmdbShowOrdering(
[FromRoute] int showID,
[FromBody] TmdbSetPreferredOrderingBody body
)
{
var show = RepoFactory.TMDB_Show.GetByTmdbShowID(showID);
if (show is null)
return NotFound(ShowNotFound);