OmdbProvider.cs 18 KB

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