OmdbProvider.cs 19 KB

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