OmdbProvider.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. using CommonIO;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Serialization;
  8. using System;
  9. using System.Globalization;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Providers.Omdb
  17. {
  18. public class OmdbProvider
  19. {
  20. internal static readonly SemaphoreSlim ResourcePool = new SemaphoreSlim(1, 1);
  21. private readonly IJsonSerializer _jsonSerializer;
  22. private readonly IFileSystem _fileSystem;
  23. private readonly IServerConfigurationManager _configurationManager;
  24. private readonly IHttpClient _httpClient;
  25. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  26. public OmdbProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager configurationManager)
  27. {
  28. _jsonSerializer = jsonSerializer;
  29. _httpClient = httpClient;
  30. _fileSystem = fileSystem;
  31. _configurationManager = configurationManager;
  32. }
  33. public async Task Fetch(BaseItem item, string imdbId, string language, string country, CancellationToken cancellationToken)
  34. {
  35. if (string.IsNullOrWhiteSpace(imdbId))
  36. {
  37. throw new ArgumentNullException("imdbId");
  38. }
  39. var result = await GetRootObject(imdbId, cancellationToken);
  40. // Only take the name and rating if the user's language is set to english, since Omdb has no localization
  41. if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
  42. {
  43. item.Name = result.Title;
  44. if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase))
  45. {
  46. item.OfficialRating = result.Rated;
  47. }
  48. }
  49. int year;
  50. if (!string.IsNullOrEmpty(result.Year)
  51. && int.TryParse(result.Year, NumberStyles.Number, _usCulture, out year)
  52. && year >= 0)
  53. {
  54. item.ProductionYear = year;
  55. }
  56. var hasCriticRating = item as IHasCriticRating;
  57. if (hasCriticRating != null)
  58. {
  59. // Seeing some bogus RT data on omdb for series, so filter it out here
  60. // RT doesn't even have tv series
  61. int tomatoMeter;
  62. if (!string.IsNullOrEmpty(result.tomatoMeter)
  63. && int.TryParse(result.tomatoMeter, NumberStyles.Integer, _usCulture, out tomatoMeter)
  64. && tomatoMeter >= 0)
  65. {
  66. hasCriticRating.CriticRating = tomatoMeter;
  67. }
  68. if (!string.IsNullOrEmpty(result.tomatoConsensus)
  69. && !string.Equals(result.tomatoConsensus, "No consensus yet.", StringComparison.OrdinalIgnoreCase))
  70. {
  71. hasCriticRating.CriticRatingSummary = WebUtility.HtmlDecode(result.tomatoConsensus);
  72. }
  73. }
  74. int voteCount;
  75. if (!string.IsNullOrEmpty(result.imdbVotes)
  76. && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out voteCount)
  77. && voteCount >= 0)
  78. {
  79. item.VoteCount = voteCount;
  80. }
  81. float imdbRating;
  82. if (!string.IsNullOrEmpty(result.imdbRating)
  83. && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out imdbRating)
  84. && imdbRating >= 0)
  85. {
  86. item.CommunityRating = imdbRating;
  87. }
  88. if (!string.IsNullOrEmpty(result.Website))
  89. {
  90. item.HomePageUrl = result.Website;
  91. }
  92. if (!string.IsNullOrWhiteSpace(result.imdbID))
  93. {
  94. item.SetProviderId(MetadataProviders.Imdb, result.imdbID);
  95. }
  96. ParseAdditionalMetadata(item, result);
  97. }
  98. internal async Task<RootObject> GetRootObject(string imdbId, CancellationToken cancellationToken)
  99. {
  100. var path = await EnsureItemInfo(imdbId, cancellationToken);
  101. string resultString;
  102. using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 131072))
  103. {
  104. using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
  105. {
  106. resultString = reader.ReadToEnd();
  107. resultString = resultString.Replace("\"N/A\"", "\"\"");
  108. }
  109. }
  110. var result = _jsonSerializer.DeserializeFromString<RootObject>(resultString);
  111. return result;
  112. }
  113. private async Task<string> EnsureItemInfo(string imdbId, CancellationToken cancellationToken)
  114. {
  115. if (string.IsNullOrWhiteSpace(imdbId))
  116. {
  117. throw new ArgumentNullException("imdbId");
  118. }
  119. var imdbParam = imdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? imdbId : "tt" + imdbId;
  120. var path = GetDataFilePath(imdbParam);
  121. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  122. if (fileInfo.Exists)
  123. {
  124. // If it's recent or automatic updates are enabled, don't re-download
  125. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
  126. {
  127. return path;
  128. }
  129. }
  130. var url = string.Format("https://www.omdbapi.com/?i={0}&tomatoes=true", imdbParam);
  131. using (var stream = await _httpClient.Get(new HttpRequestOptions
  132. {
  133. Url = url,
  134. ResourcePool = ResourcePool,
  135. CancellationToken = cancellationToken
  136. }).ConfigureAwait(false))
  137. {
  138. var rootObject = _jsonSerializer.DeserializeFromStream<RootObject>(stream);
  139. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  140. _jsonSerializer.SerializeToFile(rootObject, path);
  141. }
  142. return path;
  143. }
  144. internal string GetDataFilePath(string imdbId)
  145. {
  146. if (string.IsNullOrEmpty(imdbId))
  147. {
  148. throw new ArgumentNullException("imdbId");
  149. }
  150. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  151. var filename = string.Format("{0}.json", imdbId);
  152. return Path.Combine(dataPath, filename);
  153. }
  154. private void ParseAdditionalMetadata(BaseItem item, RootObject result)
  155. {
  156. // Grab series genres because imdb data is better than tvdb. Leave movies alone
  157. // But only do it if english is the preferred language because this data will not be localized
  158. if (ShouldFetchGenres(item) &&
  159. !string.IsNullOrWhiteSpace(result.Genre))
  160. {
  161. item.Genres.Clear();
  162. foreach (var genre in result.Genre
  163. .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
  164. .Select(i => i.Trim())
  165. .Where(i => !string.IsNullOrWhiteSpace(i)))
  166. {
  167. item.AddGenre(genre);
  168. }
  169. }
  170. var hasMetascore = item as IHasMetascore;
  171. if (hasMetascore != null)
  172. {
  173. float metascore;
  174. if (!string.IsNullOrEmpty(result.Metascore) && float.TryParse(result.Metascore, NumberStyles.Any, _usCulture, out metascore) && metascore >= 0)
  175. {
  176. hasMetascore.Metascore = metascore;
  177. }
  178. }
  179. var hasAwards = item as IHasAwards;
  180. if (hasAwards != null && !string.IsNullOrEmpty(result.Awards))
  181. {
  182. hasAwards.AwardSummary = WebUtility.HtmlDecode(result.Awards);
  183. }
  184. var hasShortOverview = item as IHasShortOverview;
  185. if (hasShortOverview != null)
  186. {
  187. // Imdb plots are usually pretty short
  188. hasShortOverview.ShortOverview = result.Plot;
  189. }
  190. }
  191. private bool ShouldFetchGenres(BaseItem item)
  192. {
  193. var lang = item.GetPreferredMetadataLanguage();
  194. // The data isn't localized and so can only be used for english users
  195. return string.Equals(lang, "en", StringComparison.OrdinalIgnoreCase);
  196. }
  197. internal class RootObject
  198. {
  199. public string Title { get; set; }
  200. public string Year { get; set; }
  201. public string Rated { get; set; }
  202. public string Released { get; set; }
  203. public string Runtime { get; set; }
  204. public string Genre { get; set; }
  205. public string Director { get; set; }
  206. public string Writer { get; set; }
  207. public string Actors { get; set; }
  208. public string Plot { get; set; }
  209. public string Poster { get; set; }
  210. public string imdbRating { get; set; }
  211. public string imdbVotes { get; set; }
  212. public string imdbID { get; set; }
  213. public string Type { get; set; }
  214. public string tomatoMeter { get; set; }
  215. public string tomatoImage { get; set; }
  216. public string tomatoRating { get; set; }
  217. public string tomatoReviews { get; set; }
  218. public string tomatoFresh { get; set; }
  219. public string tomatoRotten { get; set; }
  220. public string tomatoConsensus { get; set; }
  221. public string tomatoUserMeter { get; set; }
  222. public string tomatoUserRating { get; set; }
  223. public string tomatoUserReviews { get; set; }
  224. public string DVD { get; set; }
  225. public string BoxOffice { get; set; }
  226. public string Production { get; set; }
  227. public string Website { get; set; }
  228. public string Response { get; set; }
  229. public string Language { get; set; }
  230. public string Country { get; set; }
  231. public string Awards { get; set; }
  232. public string Metascore { get; set; }
  233. }
  234. }
  235. }