MovieDbBoxSetProvider.cs 12 KB

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