OmdbProvider.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. private readonly IJsonSerializer _jsonSerializer;
  22. private readonly IFileSystem _fileSystem;
  23. private readonly IServerConfigurationManager _configurationManager;
  24. private readonly IHttpClient _httpClient;
  25. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  26. public OmdbProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager configurationManager)
  27. {
  28. _jsonSerializer = jsonSerializer;
  29. _httpClient = httpClient;
  30. _fileSystem = fileSystem;
  31. _configurationManager = configurationManager;
  32. }
  33. public async Task Fetch<T>(MetadataResult<T> itemResult, string imdbId, string language, string country, CancellationToken cancellationToken)
  34. where T : BaseItem
  35. {
  36. if (string.IsNullOrWhiteSpace(imdbId))
  37. {
  38. throw new ArgumentNullException("imdbId");
  39. }
  40. T item = itemResult.Item;
  41. var result = await GetRootObject(imdbId, cancellationToken).ConfigureAwait(false);
  42. // Only take the name and rating if the user's language is set to english, since Omdb has no localization
  43. if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
  44. {
  45. item.Name = result.Title;
  46. if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase))
  47. {
  48. item.OfficialRating = result.Rated;
  49. }
  50. }
  51. int year;
  52. if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4
  53. && int.TryParse(result.Year.Substring(0, 4), NumberStyles.Number, _usCulture, out year)
  54. && year >= 0)
  55. {
  56. item.ProductionYear = year;
  57. }
  58. var tomatoScore = result.GetRottenTomatoScore();
  59. if (tomatoScore.HasValue)
  60. {
  61. item.CriticRating = tomatoScore;
  62. }
  63. int voteCount;
  64. if (!string.IsNullOrEmpty(result.imdbVotes)
  65. && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out voteCount)
  66. && voteCount >= 0)
  67. {
  68. item.VoteCount = voteCount;
  69. }
  70. float imdbRating;
  71. if (!string.IsNullOrEmpty(result.imdbRating)
  72. && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out imdbRating)
  73. && imdbRating >= 0)
  74. {
  75. item.CommunityRating = imdbRating;
  76. }
  77. if (!string.IsNullOrEmpty(result.Website))
  78. {
  79. item.HomePageUrl = result.Website;
  80. }
  81. if (!string.IsNullOrWhiteSpace(result.imdbID))
  82. {
  83. item.SetProviderId(MetadataProviders.Imdb, result.imdbID);
  84. }
  85. ParseAdditionalMetadata(itemResult, result);
  86. }
  87. public async Task<bool> FetchEpisodeData<T>(MetadataResult<T> itemResult, int episodeNumber, int seasonNumber, string episodeImdbId, string seriesImdbId, string language, string country, CancellationToken cancellationToken)
  88. where T : BaseItem
  89. {
  90. if (string.IsNullOrWhiteSpace(seriesImdbId))
  91. {
  92. throw new ArgumentNullException("seriesImdbId");
  93. }
  94. T item = itemResult.Item;
  95. var seasonResult = await GetSeasonRootObject(seriesImdbId, seasonNumber, cancellationToken).ConfigureAwait(false);
  96. if (seasonResult == null)
  97. {
  98. return false;
  99. }
  100. RootObject result = null;
  101. if (!string.IsNullOrWhiteSpace(episodeImdbId))
  102. {
  103. foreach (var episode in (seasonResult.Episodes ?? new RootObject[] { }))
  104. {
  105. if (string.Equals(episodeImdbId, episode.imdbID, StringComparison.OrdinalIgnoreCase))
  106. {
  107. result = episode;
  108. break;
  109. }
  110. }
  111. }
  112. // finally, search by numbers
  113. if (result == null)
  114. {
  115. foreach (var episode in (seasonResult.Episodes ?? new RootObject[] { }))
  116. {
  117. if (episode.Episode == episodeNumber)
  118. {
  119. result = episode;
  120. break;
  121. }
  122. }
  123. }
  124. if (result == null)
  125. {
  126. return false;
  127. }
  128. // Only take the name and rating if the user's language is set to english, since Omdb has no localization
  129. if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
  130. {
  131. item.Name = result.Title;
  132. if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase))
  133. {
  134. item.OfficialRating = result.Rated;
  135. }
  136. }
  137. int year;
  138. if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4
  139. && int.TryParse(result.Year.Substring(0, 4), NumberStyles.Number, _usCulture, out year)
  140. && year >= 0)
  141. {
  142. item.ProductionYear = year;
  143. }
  144. var tomatoScore = result.GetRottenTomatoScore();
  145. if (tomatoScore.HasValue)
  146. {
  147. item.CriticRating = tomatoScore;
  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).ConfigureAwait(false);
  177. string resultString;
  178. using (Stream stream = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
  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).ConfigureAwait(false);
  192. string resultString;
  193. using (Stream stream = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
  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. public static async Task<string> GetOmdbBaseUrl(CancellationToken cancellationToken)
  218. {
  219. return "https://www.omdbapi.com";
  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 baseUrl = await GetOmdbBaseUrl(cancellationToken).ConfigureAwait(false);
  239. var url = string.Format(baseUrl + "/?i={0}&plot=full&tomatoes=true&r=json", imdbParam);
  240. using (var stream = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false))
  241. {
  242. var rootObject = _jsonSerializer.DeserializeFromStream<RootObject>(stream);
  243. _fileSystem.CreateDirectory(_fileSystem.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 baseUrl = await GetOmdbBaseUrl(cancellationToken).ConfigureAwait(false);
  266. var url = string.Format(baseUrl + "/?i={0}&season={1}&detail=full", imdbParam, seasonId);
  267. using (var stream = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false))
  268. {
  269. var rootObject = _jsonSerializer.DeserializeFromStream<SeasonRootObject>(stream);
  270. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  271. _jsonSerializer.SerializeToFile(rootObject, path);
  272. }
  273. return path;
  274. }
  275. public static Task<Stream> GetOmdbResponse(IHttpClient httpClient, string url, CancellationToken cancellationToken)
  276. {
  277. return httpClient.Get(new HttpRequestOptions
  278. {
  279. Url = url,
  280. CancellationToken = cancellationToken,
  281. BufferContent = true,
  282. EnableDefaultUserAgent = true
  283. });
  284. }
  285. internal string GetDataFilePath(string imdbId)
  286. {
  287. if (string.IsNullOrEmpty(imdbId))
  288. {
  289. throw new ArgumentNullException("imdbId");
  290. }
  291. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  292. var filename = string.Format("{0}.json", imdbId);
  293. return Path.Combine(dataPath, filename);
  294. }
  295. internal string GetSeasonFilePath(string imdbId, int seasonId)
  296. {
  297. if (string.IsNullOrEmpty(imdbId))
  298. {
  299. throw new ArgumentNullException("imdbId");
  300. }
  301. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  302. var filename = string.Format("{0}_season_{1}.json", imdbId, seasonId);
  303. return Path.Combine(dataPath, filename);
  304. }
  305. private void ParseAdditionalMetadata<T>(MetadataResult<T> itemResult, RootObject result)
  306. where T : BaseItem
  307. {
  308. T item = itemResult.Item;
  309. var isConfiguredForEnglish = IsConfiguredForEnglish(item);
  310. // Grab series genres because imdb data is better than tvdb. Leave movies alone
  311. // But only do it if english is the preferred language because this data will not be localized
  312. if (isConfiguredForEnglish && !string.IsNullOrWhiteSpace(result.Genre))
  313. {
  314. item.Genres.Clear();
  315. foreach (var genre in result.Genre
  316. .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
  317. .Select(i => i.Trim())
  318. .Where(i => !string.IsNullOrWhiteSpace(i)))
  319. {
  320. item.AddGenre(genre);
  321. }
  322. }
  323. var hasAwards = item as IHasAwards;
  324. if (hasAwards != null && !string.IsNullOrEmpty(result.Awards))
  325. {
  326. hasAwards.AwardSummary = WebUtility.HtmlDecode(result.Awards);
  327. }
  328. if (isConfiguredForEnglish)
  329. {
  330. // Omdb is currently english only, so for other languages skip this and let secondary providers fill it in
  331. item.Overview = result.Plot;
  332. }
  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 IsConfiguredForEnglish(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 string Runtime { get; set; }
  390. public string Genre { get; set; }
  391. public string Director { get; set; }
  392. public string Writer { get; set; }
  393. public string Actors { get; set; }
  394. public string Plot { get; set; }
  395. public string Language { get; set; }
  396. public string Country { get; set; }
  397. public string Awards { get; set; }
  398. public string Poster { get; set; }
  399. public List<OmdbRating> Ratings { get; set; }
  400. public string Metascore { get; set; }
  401. public string imdbRating { get; set; }
  402. public string imdbVotes { get; set; }
  403. public string imdbID { get; set; }
  404. public string Type { get; set; }
  405. public string DVD { get; set; }
  406. public string BoxOffice { get; set; }
  407. public string Production { get; set; }
  408. public string Website { get; set; }
  409. public string Response { get; set; }
  410. public int Episode { get; set; }
  411. public float? GetRottenTomatoScore()
  412. {
  413. if (Ratings != null)
  414. {
  415. var rating = Ratings.FirstOrDefault(i => string.Equals(i.Source, "Rotten Tomatoes", StringComparison.OrdinalIgnoreCase));
  416. if (rating != null && rating.Value != null)
  417. {
  418. var value = rating.Value.TrimEnd('%');
  419. float score;
  420. if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out score))
  421. {
  422. return score;
  423. }
  424. }
  425. }
  426. return null;
  427. }
  428. }
  429. public class OmdbRating
  430. {
  431. public string Source { get; set; }
  432. public string Value { get; set; }
  433. }
  434. }
  435. }