OmdbProvider.cs 19 KB

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