OmdbProvider.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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.Collections.Generic;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Providers.Omdb
  18. {
  19. public class OmdbProvider
  20. {
  21. internal static readonly SemaphoreSlim ResourcePool = new SemaphoreSlim(1, 1);
  22. private readonly IJsonSerializer _jsonSerializer;
  23. private readonly IFileSystem _fileSystem;
  24. private readonly IServerConfigurationManager _configurationManager;
  25. private readonly IHttpClient _httpClient;
  26. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  27. public OmdbProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager configurationManager)
  28. {
  29. _jsonSerializer = jsonSerializer;
  30. _httpClient = httpClient;
  31. _fileSystem = fileSystem;
  32. _configurationManager = configurationManager;
  33. }
  34. public async Task Fetch(BaseItem item, string imdbId, string language, string country, CancellationToken cancellationToken)
  35. {
  36. if (string.IsNullOrWhiteSpace(imdbId))
  37. {
  38. throw new ArgumentNullException("imdbId");
  39. }
  40. var result = await GetRootObject(imdbId, cancellationToken);
  41. // Only take the name and rating if the user's language is set to english, since Omdb has no localization
  42. if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
  43. {
  44. item.Name = result.Title;
  45. if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase))
  46. {
  47. item.OfficialRating = result.Rated;
  48. }
  49. }
  50. int year;
  51. if (!string.IsNullOrEmpty(result.Year)
  52. && int.TryParse(result.Year, NumberStyles.Number, _usCulture, out year)
  53. && year >= 0)
  54. {
  55. item.ProductionYear = year;
  56. }
  57. var hasCriticRating = item as IHasCriticRating;
  58. if (hasCriticRating != null)
  59. {
  60. // Seeing some bogus RT data on omdb for series, so filter it out here
  61. // RT doesn't even have tv series
  62. int tomatoMeter;
  63. if (!string.IsNullOrEmpty(result.tomatoMeter)
  64. && int.TryParse(result.tomatoMeter, NumberStyles.Integer, _usCulture, out tomatoMeter)
  65. && tomatoMeter >= 0)
  66. {
  67. hasCriticRating.CriticRating = tomatoMeter;
  68. }
  69. if (!string.IsNullOrEmpty(result.tomatoConsensus)
  70. && !string.Equals(result.tomatoConsensus, "No consensus yet.", StringComparison.OrdinalIgnoreCase))
  71. {
  72. hasCriticRating.CriticRatingSummary = WebUtility.HtmlDecode(result.tomatoConsensus);
  73. }
  74. }
  75. int voteCount;
  76. if (!string.IsNullOrEmpty(result.imdbVotes)
  77. && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out voteCount)
  78. && voteCount >= 0)
  79. {
  80. item.VoteCount = voteCount;
  81. }
  82. float imdbRating;
  83. if (!string.IsNullOrEmpty(result.imdbRating)
  84. && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out imdbRating)
  85. && imdbRating >= 0)
  86. {
  87. item.CommunityRating = imdbRating;
  88. }
  89. if (!string.IsNullOrEmpty(result.Website))
  90. {
  91. item.HomePageUrl = result.Website;
  92. }
  93. if (!string.IsNullOrWhiteSpace(result.imdbID))
  94. {
  95. item.SetProviderId(MetadataProviders.Imdb, result.imdbID);
  96. }
  97. ParseAdditionalMetadata(item, result);
  98. }
  99. public async Task<bool> FetchEpisodeData(BaseItem item, int episodeNumber, int seasonNumber, string imdbId, string language, string country, CancellationToken cancellationToken)
  100. {
  101. if (string.IsNullOrWhiteSpace(imdbId))
  102. {
  103. throw new ArgumentNullException("imdbId");
  104. }
  105. var seasonResult = await GetSeasonRootObject(imdbId, seasonNumber, cancellationToken);
  106. RootObject result = null;
  107. foreach (var episode in seasonResult.Episodes)
  108. {
  109. if (episode.Episode == episodeNumber)
  110. {
  111. result = episode;
  112. break;
  113. }
  114. }
  115. if (result == null)
  116. {
  117. return false;
  118. }
  119. // Only take the name and rating if the user's language is set to english, since Omdb has no localization
  120. if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
  121. {
  122. item.Name = result.Title;
  123. if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase))
  124. {
  125. item.OfficialRating = result.Rated;
  126. }
  127. }
  128. int year;
  129. if (!string.IsNullOrEmpty(result.Year)
  130. && int.TryParse(result.Year, NumberStyles.Number, _usCulture, out year)
  131. && year >= 0)
  132. {
  133. item.ProductionYear = year;
  134. }
  135. var hasCriticRating = item as IHasCriticRating;
  136. if (hasCriticRating != null)
  137. {
  138. // Seeing some bogus RT data on omdb for series, so filter it out here
  139. // RT doesn't even have tv series
  140. int tomatoMeter;
  141. if (!string.IsNullOrEmpty(result.tomatoMeter)
  142. && int.TryParse(result.tomatoMeter, NumberStyles.Integer, _usCulture, out tomatoMeter)
  143. && tomatoMeter >= 0)
  144. {
  145. hasCriticRating.CriticRating = tomatoMeter;
  146. }
  147. if (!string.IsNullOrEmpty(result.tomatoConsensus)
  148. && !string.Equals(result.tomatoConsensus, "No consensus yet.", StringComparison.OrdinalIgnoreCase))
  149. {
  150. hasCriticRating.CriticRatingSummary = WebUtility.HtmlDecode(result.tomatoConsensus);
  151. }
  152. }
  153. int voteCount;
  154. if (!string.IsNullOrEmpty(result.imdbVotes)
  155. && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out voteCount)
  156. && voteCount >= 0)
  157. {
  158. item.VoteCount = voteCount;
  159. }
  160. float imdbRating;
  161. if (!string.IsNullOrEmpty(result.imdbRating)
  162. && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out imdbRating)
  163. && imdbRating >= 0)
  164. {
  165. item.CommunityRating = imdbRating;
  166. }
  167. if (!string.IsNullOrEmpty(result.Website))
  168. {
  169. item.HomePageUrl = result.Website;
  170. }
  171. if (!string.IsNullOrWhiteSpace(result.imdbID))
  172. {
  173. item.SetProviderId(MetadataProviders.Imdb, result.imdbID);
  174. }
  175. ParseAdditionalMetadata(item, result);
  176. return true;
  177. }
  178. internal async Task<RootObject> GetRootObject(string imdbId, CancellationToken cancellationToken)
  179. {
  180. var path = await EnsureItemInfo(imdbId, cancellationToken);
  181. string resultString;
  182. using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 131072))
  183. {
  184. using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
  185. {
  186. resultString = reader.ReadToEnd();
  187. resultString = resultString.Replace("\"N/A\"", "\"\"");
  188. }
  189. }
  190. var result = _jsonSerializer.DeserializeFromString<RootObject>(resultString);
  191. return result;
  192. }
  193. internal async Task<SeasonRootObject> GetSeasonRootObject(string imdbId, int seasonId, CancellationToken cancellationToken)
  194. {
  195. var path = await EnsureSeasonInfo(imdbId, seasonId, cancellationToken);
  196. string resultString;
  197. using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 131072))
  198. {
  199. using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
  200. {
  201. resultString = reader.ReadToEnd();
  202. resultString = resultString.Replace("\"N/A\"", "\"\"");
  203. }
  204. }
  205. var result = _jsonSerializer.DeserializeFromString<SeasonRootObject>(resultString);
  206. return result;
  207. }
  208. internal static bool IsValidSeries(Dictionary<string, string> seriesProviderIds)
  209. {
  210. string id;
  211. if (seriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out id) && !string.IsNullOrEmpty(id))
  212. {
  213. // This check should ideally never be necessary but we're seeing some cases of this and haven't tracked them down yet.
  214. if (!string.IsNullOrWhiteSpace(id))
  215. {
  216. return true;
  217. }
  218. }
  219. return false;
  220. }
  221. private async Task<string> EnsureItemInfo(string imdbId, CancellationToken cancellationToken)
  222. {
  223. if (string.IsNullOrWhiteSpace(imdbId))
  224. {
  225. throw new ArgumentNullException("imdbId");
  226. }
  227. var imdbParam = imdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? imdbId : "tt" + imdbId;
  228. var path = GetDataFilePath(imdbParam);
  229. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  230. if (fileInfo.Exists)
  231. {
  232. // If it's recent or automatic updates are enabled, don't re-download
  233. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
  234. {
  235. return path;
  236. }
  237. }
  238. var url = string.Format("https://www.omdbapi.com/?i={0}&tomatoes=true", imdbParam);
  239. using (var stream = await _httpClient.Get(new HttpRequestOptions
  240. {
  241. Url = url,
  242. ResourcePool = ResourcePool,
  243. CancellationToken = cancellationToken
  244. }).ConfigureAwait(false))
  245. {
  246. var rootObject = _jsonSerializer.DeserializeFromStream<RootObject>(stream);
  247. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  248. _jsonSerializer.SerializeToFile(rootObject, path);
  249. }
  250. return path;
  251. }
  252. private async Task<string> EnsureSeasonInfo(string seriesImdbId, int seasonId, CancellationToken cancellationToken)
  253. {
  254. if (string.IsNullOrWhiteSpace(seriesImdbId))
  255. {
  256. throw new ArgumentNullException("imdbId");
  257. }
  258. var imdbParam = seriesImdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? seriesImdbId : "tt" + seriesImdbId;
  259. var path = GetSeasonFilePath(imdbParam, seasonId);
  260. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  261. if (fileInfo.Exists)
  262. {
  263. // If it's recent or automatic updates are enabled, don't re-download
  264. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
  265. {
  266. return path;
  267. }
  268. }
  269. var url = string.Format("https://www.omdbapi.com/?i={0}&season={1}&detail=full", imdbParam, seasonId);
  270. using (var stream = await _httpClient.Get(new HttpRequestOptions
  271. {
  272. Url = url,
  273. ResourcePool = ResourcePool,
  274. CancellationToken = cancellationToken
  275. }).ConfigureAwait(false))
  276. {
  277. var rootObject = _jsonSerializer.DeserializeFromStream<SeasonRootObject>(stream);
  278. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  279. _jsonSerializer.SerializeToFile(rootObject, path);
  280. }
  281. return path;
  282. }
  283. internal string GetDataFilePath(string imdbId)
  284. {
  285. if (string.IsNullOrEmpty(imdbId))
  286. {
  287. throw new ArgumentNullException("imdbId");
  288. }
  289. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  290. var filename = string.Format("{0}.json", imdbId);
  291. return Path.Combine(dataPath, filename);
  292. }
  293. internal string GetSeasonFilePath(string imdbId, int seasonId)
  294. {
  295. if (string.IsNullOrEmpty(imdbId))
  296. {
  297. throw new ArgumentNullException("imdbId");
  298. }
  299. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  300. var filename = string.Format("{0}_season_{1}.json", imdbId, seasonId);
  301. return Path.Combine(dataPath, filename);
  302. }
  303. private void ParseAdditionalMetadata(BaseItem item, RootObject result)
  304. {
  305. // Grab series genres because imdb data is better than tvdb. Leave movies alone
  306. // But only do it if english is the preferred language because this data will not be localized
  307. if (ShouldFetchGenres(item) &&
  308. !string.IsNullOrWhiteSpace(result.Genre))
  309. {
  310. item.Genres.Clear();
  311. foreach (var genre in result.Genre
  312. .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
  313. .Select(i => i.Trim())
  314. .Where(i => !string.IsNullOrWhiteSpace(i)))
  315. {
  316. item.AddGenre(genre);
  317. }
  318. }
  319. var hasMetascore = item as IHasMetascore;
  320. if (hasMetascore != null)
  321. {
  322. float metascore;
  323. if (!string.IsNullOrEmpty(result.Metascore) && float.TryParse(result.Metascore, NumberStyles.Any, _usCulture, out metascore) && metascore >= 0)
  324. {
  325. hasMetascore.Metascore = metascore;
  326. }
  327. }
  328. var hasAwards = item as IHasAwards;
  329. if (hasAwards != null && !string.IsNullOrEmpty(result.Awards))
  330. {
  331. hasAwards.AwardSummary = WebUtility.HtmlDecode(result.Awards);
  332. }
  333. var hasShortOverview = item as IHasShortOverview;
  334. if (hasShortOverview != null)
  335. {
  336. // Imdb plots are usually pretty short
  337. hasShortOverview.ShortOverview = result.Plot;
  338. }
  339. }
  340. private bool ShouldFetchGenres(BaseItem item)
  341. {
  342. var lang = item.GetPreferredMetadataLanguage();
  343. // The data isn't localized and so can only be used for english users
  344. return string.Equals(lang, "en", StringComparison.OrdinalIgnoreCase);
  345. }
  346. internal class SeasonRootObject
  347. {
  348. public string Title { get; set; }
  349. public string seriesID { get; set; }
  350. public int Season { get; set; }
  351. public int? totalSeasons { get; set; }
  352. public RootObject[] Episodes { get; set; }
  353. public string Response { get; set; }
  354. }
  355. internal class RootObject
  356. {
  357. public string Title { get; set; }
  358. public string Year { get; set; }
  359. public string Rated { get; set; }
  360. public string Released { get; set; }
  361. public int Episode { get; set; }
  362. public string Runtime { get; set; }
  363. public string Genre { get; set; }
  364. public string Director { get; set; }
  365. public string Writer { get; set; }
  366. public string Actors { get; set; }
  367. public string Plot { get; set; }
  368. public string Poster { get; set; }
  369. public string imdbRating { get; set; }
  370. public string imdbVotes { get; set; }
  371. public string imdbID { get; set; }
  372. public string Type { get; set; }
  373. public string tomatoMeter { get; set; }
  374. public string tomatoImage { get; set; }
  375. public string tomatoRating { get; set; }
  376. public string tomatoReviews { get; set; }
  377. public string tomatoFresh { get; set; }
  378. public string tomatoRotten { get; set; }
  379. public string tomatoConsensus { get; set; }
  380. public string tomatoUserMeter { get; set; }
  381. public string tomatoUserRating { get; set; }
  382. public string tomatoUserReviews { get; set; }
  383. public string DVD { get; set; }
  384. public string BoxOffice { get; set; }
  385. public string Production { get; set; }
  386. public string Website { get; set; }
  387. public string Response { get; set; }
  388. public string Language { get; set; }
  389. public string Country { get; set; }
  390. public string Awards { get; set; }
  391. public string Metascore { get; set; }
  392. }
  393. }
  394. }