MovieDbBoxSetProvider.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Entities.Movies;
  6. using MediaBrowser.Controller.Localization;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  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. namespace MediaBrowser.Providers.BoxSets
  20. {
  21. public class MovieDbBoxSetProvider : IRemoteMetadataProvider<BoxSet, BoxSetInfo>
  22. {
  23. private readonly CultureInfo _enUs = new CultureInfo("en-US");
  24. private const string GetCollectionInfo3 = @"http://api.themoviedb.org/3/collection/{0}?api_key={1}&append_to_response=images";
  25. internal static MovieDbBoxSetProvider Current;
  26. private readonly ILogger _logger;
  27. private readonly IJsonSerializer _json;
  28. private readonly IServerConfigurationManager _config;
  29. private readonly IFileSystem _fileSystem;
  30. private readonly ILocalizationManager _localization;
  31. public MovieDbBoxSetProvider(ILogger logger, IJsonSerializer json, IServerConfigurationManager config, IFileSystem fileSystem, ILocalizationManager localization)
  32. {
  33. _logger = logger;
  34. _json = json;
  35. _config = config;
  36. _fileSystem = fileSystem;
  37. _localization = localization;
  38. Current = this;
  39. }
  40. public async Task<MetadataResult<BoxSet>> GetMetadata(BoxSetInfo id, CancellationToken cancellationToken)
  41. {
  42. var tmdbId = id.GetProviderId(MetadataProviders.Tmdb);
  43. // We don't already have an Id, need to fetch it
  44. if (string.IsNullOrEmpty(tmdbId))
  45. {
  46. var searchResult = await new MovieDbSearch(_logger, _json).FindCollectionId(id, cancellationToken).ConfigureAwait(false);
  47. if (searchResult != null)
  48. {
  49. tmdbId = searchResult.id.ToString(_enUs);
  50. }
  51. }
  52. var result = new MetadataResult<BoxSet>();
  53. if (!string.IsNullOrEmpty(tmdbId))
  54. {
  55. var mainResult = await GetMovieDbResult(tmdbId, id.MetadataLanguage, cancellationToken).ConfigureAwait(false);
  56. if (mainResult != null)
  57. {
  58. result.HasMetadata = true;
  59. result.Item = GetItem(mainResult);
  60. }
  61. }
  62. return result;
  63. }
  64. internal async Task<RootObject> GetMovieDbResult(string tmdbId, string language, CancellationToken cancellationToken)
  65. {
  66. if (string.IsNullOrEmpty(tmdbId))
  67. {
  68. throw new ArgumentNullException("tmdbId");
  69. }
  70. await EnsureInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
  71. var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, language);
  72. if (!string.IsNullOrEmpty(dataFilePath))
  73. {
  74. return _json.DeserializeFromFile<RootObject>(dataFilePath);
  75. }
  76. return null;
  77. }
  78. private BoxSet GetItem(RootObject obj)
  79. {
  80. var item = new BoxSet
  81. {
  82. Name = obj.name,
  83. Overview = obj.overview
  84. };
  85. item.SetProviderId(MetadataProviders.Tmdb, obj.id.ToString(_enUs));
  86. return item;
  87. }
  88. private async Task DownloadInfo(string tmdbId, string preferredMetadataLanguage, CancellationToken cancellationToken)
  89. {
  90. var mainResult = await FetchMainResult(tmdbId, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
  91. if (mainResult == null) return;
  92. var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage);
  93. Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
  94. _json.SerializeToFile(mainResult, dataFilePath);
  95. }
  96. private async Task<RootObject> FetchMainResult(string id, string language, CancellationToken cancellationToken)
  97. {
  98. var url = string.Format(GetCollectionInfo3, id, MovieDbProvider.ApiKey);
  99. var imageLanguages = _localization.GetCultures()
  100. .Select(i => i.TwoLetterISOLanguageName)
  101. .Distinct(StringComparer.OrdinalIgnoreCase)
  102. .ToList();
  103. imageLanguages.Add("null");
  104. if (!string.IsNullOrEmpty(language))
  105. {
  106. // If preferred language isn't english, get those images too
  107. if (imageLanguages.Contains(language, StringComparer.OrdinalIgnoreCase))
  108. {
  109. imageLanguages.Add(language);
  110. }
  111. url += string.Format("&language={0}", language);
  112. }
  113. // Get images in english and with no language
  114. url += "&include_image_language=" + string.Join(",", imageLanguages.ToArray());
  115. cancellationToken.ThrowIfCancellationRequested();
  116. RootObject mainResult = null;
  117. using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  118. {
  119. Url = url,
  120. CancellationToken = cancellationToken,
  121. AcceptHeader = MovieDbSearch.AcceptHeader
  122. }).ConfigureAwait(false))
  123. {
  124. mainResult = _json.DeserializeFromStream<RootObject>(json);
  125. }
  126. cancellationToken.ThrowIfCancellationRequested();
  127. if (mainResult != null && string.IsNullOrEmpty(mainResult.overview))
  128. {
  129. if (!string.IsNullOrEmpty(language) && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
  130. {
  131. url = string.Format(GetCollectionInfo3, id, MovieDbSearch.ApiKey) + "&include_image_language=en,null&language=en";
  132. using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  133. {
  134. Url = url,
  135. CancellationToken = cancellationToken,
  136. AcceptHeader = MovieDbSearch.AcceptHeader
  137. }).ConfigureAwait(false))
  138. {
  139. mainResult = _json.DeserializeFromStream<RootObject>(json);
  140. }
  141. if (String.IsNullOrEmpty(mainResult.overview))
  142. {
  143. _logger.Error("Unable to find information for (id:" + id + ")");
  144. return null;
  145. }
  146. }
  147. }
  148. return mainResult;
  149. }
  150. private readonly Task _cachedTask = Task.FromResult(true);
  151. internal Task EnsureInfo(string tmdbId, string preferredMetadataLanguage, CancellationToken cancellationToken)
  152. {
  153. var path = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage);
  154. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  155. if (fileInfo.Exists)
  156. {
  157. // If it's recent or automatic updates are enabled, don't re-download
  158. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 7)
  159. {
  160. return _cachedTask;
  161. }
  162. }
  163. return DownloadInfo(tmdbId, preferredMetadataLanguage, cancellationToken);
  164. }
  165. public string Name
  166. {
  167. get { return "TheMovieDb"; }
  168. }
  169. private static string GetDataFilePath(IApplicationPaths appPaths, string tmdbId, string preferredLanguage)
  170. {
  171. var path = GetDataPath(appPaths, tmdbId);
  172. var filename = string.Format("all-{0}.json",
  173. preferredLanguage ?? string.Empty);
  174. return Path.Combine(path, filename);
  175. }
  176. private static string GetDataPath(IApplicationPaths appPaths, string tmdbId)
  177. {
  178. var dataPath = GetCollectionsDataPath(appPaths);
  179. return Path.Combine(dataPath, tmdbId);
  180. }
  181. private static string GetCollectionsDataPath(IApplicationPaths appPaths)
  182. {
  183. var dataPath = Path.Combine(appPaths.DataPath, "tmdb-collections");
  184. return dataPath;
  185. }
  186. internal class Part
  187. {
  188. public string title { get; set; }
  189. public int id { get; set; }
  190. public string release_date { get; set; }
  191. public string poster_path { get; set; }
  192. public string backdrop_path { get; set; }
  193. }
  194. internal class Backdrop
  195. {
  196. public double aspect_ratio { get; set; }
  197. public string file_path { get; set; }
  198. public int height { get; set; }
  199. public string iso_639_1 { get; set; }
  200. public double vote_average { get; set; }
  201. public int vote_count { get; set; }
  202. public int width { get; set; }
  203. }
  204. internal class Poster
  205. {
  206. public double aspect_ratio { get; set; }
  207. public string file_path { get; set; }
  208. public int height { get; set; }
  209. public string iso_639_1 { get; set; }
  210. public double vote_average { get; set; }
  211. public int vote_count { get; set; }
  212. public int width { get; set; }
  213. }
  214. internal class Images
  215. {
  216. public List<Backdrop> backdrops { get; set; }
  217. public List<Poster> posters { get; set; }
  218. }
  219. internal class RootObject
  220. {
  221. public int id { get; set; }
  222. public string name { get; set; }
  223. public string overview { get; set; }
  224. public string poster_path { get; set; }
  225. public string backdrop_path { get; set; }
  226. public List<Part> parts { get; set; }
  227. public Images images { get; set; }
  228. }
  229. }
  230. }