OmdbProvider.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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> GetOmdbUrl(string query, CancellationToken cancellationToken)
  218. {
  219. var url = "https://www.omdbapi.com?apikey=fe53f97e";
  220. if (!string.IsNullOrWhiteSpace(query))
  221. {
  222. url += "&" + query;
  223. }
  224. return url;
  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 = await GetOmdbUrl(string.Format("i={0}&plot=full&tomatoes=true&r=json", imdbParam), cancellationToken).ConfigureAwait(false);
  244. using (var stream = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false))
  245. {
  246. var rootObject = _jsonSerializer.DeserializeFromStream<RootObject>(stream);
  247. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  248. _jsonSerializer.SerializeToFile(rootObject, path);
  249. }
  250. return path;
  251. }
  252. private async Task<string> EnsureSeasonInfo(string seriesImdbId, int seasonId, CancellationToken cancellationToken)
  253. {
  254. if (string.IsNullOrWhiteSpace(seriesImdbId))
  255. {
  256. throw new ArgumentNullException("imdbId");
  257. }
  258. var imdbParam = seriesImdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? seriesImdbId : "tt" + seriesImdbId;
  259. var path = GetSeasonFilePath(imdbParam, seasonId);
  260. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  261. if (fileInfo.Exists)
  262. {
  263. // If it's recent or automatic updates are enabled, don't re-download
  264. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
  265. {
  266. return path;
  267. }
  268. }
  269. var url = await GetOmdbUrl(string.Format("i={0}&season={1}&detail=full", imdbParam, seasonId), cancellationToken).ConfigureAwait(false);
  270. using (var stream = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false))
  271. {
  272. var rootObject = _jsonSerializer.DeserializeFromStream<SeasonRootObject>(stream);
  273. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  274. _jsonSerializer.SerializeToFile(rootObject, path);
  275. }
  276. return path;
  277. }
  278. public static Task<Stream> GetOmdbResponse(IHttpClient httpClient, string url, CancellationToken cancellationToken)
  279. {
  280. return httpClient.Get(new HttpRequestOptions
  281. {
  282. Url = url,
  283. CancellationToken = cancellationToken,
  284. BufferContent = true,
  285. EnableDefaultUserAgent = true
  286. });
  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. var isConfiguredForEnglish = IsConfiguredForEnglish(item);
  313. // Grab series genres because imdb data is better than tvdb. Leave movies alone
  314. // But only do it if english is the preferred language because this data will not be localized
  315. if (isConfiguredForEnglish && !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 hasAwards = item as IHasAwards;
  327. if (hasAwards != null && !string.IsNullOrEmpty(result.Awards))
  328. {
  329. hasAwards.AwardSummary = WebUtility.HtmlDecode(result.Awards);
  330. }
  331. if (isConfiguredForEnglish)
  332. {
  333. // Omdb is currently english only, so for other languages skip this and let secondary providers fill it in
  334. item.Overview = result.Plot;
  335. }
  336. //if (!string.IsNullOrWhiteSpace(result.Director))
  337. //{
  338. // var person = new PersonInfo
  339. // {
  340. // Name = result.Director.Trim(),
  341. // Type = PersonType.Director
  342. // };
  343. // itemResult.AddPerson(person);
  344. //}
  345. //if (!string.IsNullOrWhiteSpace(result.Writer))
  346. //{
  347. // var person = new PersonInfo
  348. // {
  349. // Name = result.Director.Trim(),
  350. // Type = PersonType.Writer
  351. // };
  352. // itemResult.AddPerson(person);
  353. //}
  354. //if (!string.IsNullOrWhiteSpace(result.Actors))
  355. //{
  356. // var actorList = result.Actors.Split(',');
  357. // foreach (var actor in actorList)
  358. // {
  359. // if (!string.IsNullOrWhiteSpace(actor))
  360. // {
  361. // var person = new PersonInfo
  362. // {
  363. // Name = actor.Trim(),
  364. // Type = PersonType.Actor
  365. // };
  366. // itemResult.AddPerson(person);
  367. // }
  368. // }
  369. //}
  370. }
  371. private bool IsConfiguredForEnglish(BaseItem item)
  372. {
  373. var lang = item.GetPreferredMetadataLanguage();
  374. // The data isn't localized and so can only be used for english users
  375. return string.Equals(lang, "en", StringComparison.OrdinalIgnoreCase);
  376. }
  377. internal class SeasonRootObject
  378. {
  379. public string Title { get; set; }
  380. public string seriesID { get; set; }
  381. public int Season { get; set; }
  382. public int? totalSeasons { get; set; }
  383. public RootObject[] Episodes { get; set; }
  384. public string Response { get; set; }
  385. }
  386. internal class RootObject
  387. {
  388. public string Title { get; set; }
  389. public string Year { get; set; }
  390. public string Rated { get; set; }
  391. public string Released { get; set; }
  392. public string Runtime { get; set; }
  393. public string Genre { get; set; }
  394. public string Director { get; set; }
  395. public string Writer { get; set; }
  396. public string Actors { get; set; }
  397. public string Plot { get; set; }
  398. public string Language { get; set; }
  399. public string Country { get; set; }
  400. public string Awards { get; set; }
  401. public string Poster { get; set; }
  402. public List<OmdbRating> Ratings { get; set; }
  403. public string Metascore { get; set; }
  404. public string imdbRating { get; set; }
  405. public string imdbVotes { get; set; }
  406. public string imdbID { get; set; }
  407. public string Type { get; set; }
  408. public string DVD { get; set; }
  409. public string BoxOffice { get; set; }
  410. public string Production { get; set; }
  411. public string Website { get; set; }
  412. public string Response { get; set; }
  413. public int Episode { get; set; }
  414. public float? GetRottenTomatoScore()
  415. {
  416. if (Ratings != null)
  417. {
  418. var rating = Ratings.FirstOrDefault(i => string.Equals(i.Source, "Rotten Tomatoes", StringComparison.OrdinalIgnoreCase));
  419. if (rating != null && rating.Value != null)
  420. {
  421. var value = rating.Value.TrimEnd('%');
  422. float score;
  423. if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out score))
  424. {
  425. return score;
  426. }
  427. }
  428. }
  429. return null;
  430. }
  431. }
  432. public class OmdbRating
  433. {
  434. public string Source { get; set; }
  435. public string Value { get; set; }
  436. }
  437. }
  438. }