OmdbProvider.cs 19 KB

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