MovieDbBoxSetProvider.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Common.Net;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Entities.Movies;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.Providers;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.Globalization;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.Providers;
  18. using MediaBrowser.Model.Serialization;
  19. using MediaBrowser.Providers.Movies;
  20. using Microsoft.Extensions.Logging;
  21. namespace MediaBrowser.Providers.BoxSets
  22. {
  23. public class MovieDbBoxSetProvider : IRemoteMetadataProvider<BoxSet, BoxSetInfo>
  24. {
  25. private const string GetCollectionInfo3 = MovieDbProvider.BaseMovieDbUrl + @"3/collection/{0}?api_key={1}&append_to_response=images";
  26. internal static MovieDbBoxSetProvider Current;
  27. private readonly ILogger _logger;
  28. private readonly IJsonSerializer _json;
  29. private readonly IServerConfigurationManager _config;
  30. private readonly IFileSystem _fileSystem;
  31. private readonly ILocalizationManager _localization;
  32. private readonly IHttpClient _httpClient;
  33. private readonly ILibraryManager _libraryManager;
  34. public MovieDbBoxSetProvider(ILogger logger, IJsonSerializer json, IServerConfigurationManager config, IFileSystem fileSystem, ILocalizationManager localization, IHttpClient httpClient, ILibraryManager libraryManager)
  35. {
  36. _logger = logger;
  37. _json = json;
  38. _config = config;
  39. _fileSystem = fileSystem;
  40. _localization = localization;
  41. _httpClient = httpClient;
  42. _libraryManager = libraryManager;
  43. Current = this;
  44. }
  45. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  46. public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(BoxSetInfo searchInfo, CancellationToken cancellationToken)
  47. {
  48. var tmdbId = searchInfo.GetProviderId(MetadataProviders.Tmdb);
  49. if (!string.IsNullOrEmpty(tmdbId))
  50. {
  51. await EnsureInfo(tmdbId, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
  52. var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, searchInfo.MetadataLanguage);
  53. var info = _json.DeserializeFromFile<RootObject>(dataFilePath);
  54. var images = (info.images ?? new Images()).posters ?? new List<Poster>();
  55. var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
  56. var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
  57. var result = new RemoteSearchResult
  58. {
  59. Name = info.name,
  60. SearchProviderName = Name,
  61. ImageUrl = images.Count == 0 ? null : (tmdbImageUrl + images[0].file_path)
  62. };
  63. result.SetProviderId(MetadataProviders.Tmdb, info.id.ToString(_usCulture));
  64. return new[] { result };
  65. }
  66. return await new MovieDbSearch(_logger, _json, _libraryManager).GetSearchResults(searchInfo, cancellationToken).ConfigureAwait(false);
  67. }
  68. public async Task<MetadataResult<BoxSet>> GetMetadata(BoxSetInfo id, CancellationToken cancellationToken)
  69. {
  70. var tmdbId = id.GetProviderId(MetadataProviders.Tmdb);
  71. // We don't already have an Id, need to fetch it
  72. if (string.IsNullOrEmpty(tmdbId))
  73. {
  74. var searchResults = await new MovieDbSearch(_logger, _json, _libraryManager).GetSearchResults(id, cancellationToken).ConfigureAwait(false);
  75. var searchResult = searchResults.FirstOrDefault();
  76. if (searchResult != null)
  77. {
  78. tmdbId = searchResult.GetProviderId(MetadataProviders.Tmdb);
  79. }
  80. }
  81. var result = new MetadataResult<BoxSet>();
  82. if (!string.IsNullOrEmpty(tmdbId))
  83. {
  84. var mainResult = await GetMovieDbResult(tmdbId, id.MetadataLanguage, cancellationToken).ConfigureAwait(false);
  85. if (mainResult != null)
  86. {
  87. result.HasMetadata = true;
  88. result.Item = GetItem(mainResult);
  89. }
  90. }
  91. return result;
  92. }
  93. internal async Task<RootObject> GetMovieDbResult(string tmdbId, string language, CancellationToken cancellationToken)
  94. {
  95. if (string.IsNullOrEmpty(tmdbId))
  96. {
  97. throw new ArgumentNullException(nameof(tmdbId));
  98. }
  99. await EnsureInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
  100. var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, language);
  101. if (!string.IsNullOrEmpty(dataFilePath))
  102. {
  103. return _json.DeserializeFromFile<RootObject>(dataFilePath);
  104. }
  105. return null;
  106. }
  107. private BoxSet GetItem(RootObject obj)
  108. {
  109. var item = new BoxSet
  110. {
  111. Name = obj.name,
  112. Overview = obj.overview
  113. };
  114. item.SetProviderId(MetadataProviders.Tmdb, obj.id.ToString(_usCulture));
  115. return item;
  116. }
  117. private async Task DownloadInfo(string tmdbId, string preferredMetadataLanguage, CancellationToken cancellationToken)
  118. {
  119. var mainResult = await FetchMainResult(tmdbId, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
  120. if (mainResult == null) return;
  121. var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage);
  122. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(dataFilePath));
  123. _json.SerializeToFile(mainResult, dataFilePath);
  124. }
  125. private async Task<RootObject> FetchMainResult(string id, string language, CancellationToken cancellationToken)
  126. {
  127. var url = string.Format(GetCollectionInfo3, id, MovieDbProvider.ApiKey);
  128. if (!string.IsNullOrEmpty(language))
  129. {
  130. url += string.Format("&language={0}", MovieDbProvider.NormalizeLanguage(language));
  131. // Get images in english and with no language
  132. url += "&include_image_language=" + MovieDbProvider.GetImageLanguagesParam(language);
  133. }
  134. cancellationToken.ThrowIfCancellationRequested();
  135. RootObject mainResult = null;
  136. using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  137. {
  138. Url = url,
  139. CancellationToken = cancellationToken,
  140. AcceptHeader = MovieDbSearch.AcceptHeader
  141. }).ConfigureAwait(false))
  142. {
  143. using (var json = response.Content)
  144. {
  145. mainResult = await _json.DeserializeFromStreamAsync<RootObject>(json).ConfigureAwait(false);
  146. }
  147. }
  148. cancellationToken.ThrowIfCancellationRequested();
  149. if (mainResult != null && string.IsNullOrEmpty(mainResult.name))
  150. {
  151. if (!string.IsNullOrEmpty(language) && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
  152. {
  153. url = string.Format(GetCollectionInfo3, id, MovieDbSearch.ApiKey) + "&language=en";
  154. if (!string.IsNullOrEmpty(language))
  155. {
  156. // Get images in english and with no language
  157. url += "&include_image_language=" + MovieDbProvider.GetImageLanguagesParam(language);
  158. }
  159. using (var response = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  160. {
  161. Url = url,
  162. CancellationToken = cancellationToken,
  163. AcceptHeader = MovieDbSearch.AcceptHeader
  164. }).ConfigureAwait(false))
  165. {
  166. using (var json = response.Content)
  167. {
  168. mainResult = await _json.DeserializeFromStreamAsync<RootObject>(json).ConfigureAwait(false);
  169. }
  170. }
  171. }
  172. }
  173. return mainResult;
  174. }
  175. internal Task EnsureInfo(string tmdbId, string preferredMetadataLanguage, CancellationToken cancellationToken)
  176. {
  177. var path = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage);
  178. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  179. if (fileInfo.Exists)
  180. {
  181. // If it's recent or automatic updates are enabled, don't re-download
  182. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
  183. {
  184. return Task.CompletedTask;
  185. }
  186. }
  187. return DownloadInfo(tmdbId, preferredMetadataLanguage, cancellationToken);
  188. }
  189. public string Name => "TheMovieDb";
  190. private static string GetDataFilePath(IApplicationPaths appPaths, string tmdbId, string preferredLanguage)
  191. {
  192. var path = GetDataPath(appPaths, tmdbId);
  193. var filename = string.Format("all-{0}.json", preferredLanguage ?? string.Empty);
  194. return Path.Combine(path, filename);
  195. }
  196. private static string GetDataPath(IApplicationPaths appPaths, string tmdbId)
  197. {
  198. var dataPath = GetCollectionsDataPath(appPaths);
  199. return Path.Combine(dataPath, tmdbId);
  200. }
  201. private static string GetCollectionsDataPath(IApplicationPaths appPaths)
  202. {
  203. var dataPath = Path.Combine(appPaths.CachePath, "tmdb-collections");
  204. return dataPath;
  205. }
  206. internal class Part
  207. {
  208. public string title { get; set; }
  209. public int id { get; set; }
  210. public string release_date { get; set; }
  211. public string poster_path { get; set; }
  212. public string backdrop_path { get; set; }
  213. }
  214. internal class Backdrop
  215. {
  216. public double aspect_ratio { get; set; }
  217. public string file_path { get; set; }
  218. public int height { get; set; }
  219. public string iso_639_1 { get; set; }
  220. public double vote_average { get; set; }
  221. public int vote_count { get; set; }
  222. public int width { get; set; }
  223. }
  224. internal class Poster
  225. {
  226. public double aspect_ratio { get; set; }
  227. public string file_path { get; set; }
  228. public int height { get; set; }
  229. public string iso_639_1 { get; set; }
  230. public double vote_average { get; set; }
  231. public int vote_count { get; set; }
  232. public int width { get; set; }
  233. }
  234. internal class Images
  235. {
  236. public List<Backdrop> backdrops { get; set; }
  237. public List<Poster> posters { get; set; }
  238. }
  239. internal class RootObject
  240. {
  241. public int id { get; set; }
  242. public string name { get; set; }
  243. public string overview { get; set; }
  244. public string poster_path { get; set; }
  245. public string backdrop_path { get; set; }
  246. public List<Part> parts { get; set; }
  247. public Images images { get; set; }
  248. }
  249. public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
  250. {
  251. return _httpClient.GetResponse(new HttpRequestOptions
  252. {
  253. CancellationToken = cancellationToken,
  254. Url = url
  255. });
  256. }
  257. }
  258. }