OmdbProvider.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Common;
  11. using MediaBrowser.Common.Net;
  12. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.Serialization;
  18. namespace MediaBrowser.Providers.Plugins.Omdb
  19. {
  20. public class OmdbProvider
  21. {
  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. private readonly IApplicationHost _appHost;
  28. public OmdbProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, IFileSystem fileSystem, IApplicationHost appHost, IServerConfigurationManager configurationManager)
  29. {
  30. _jsonSerializer = jsonSerializer;
  31. _httpClient = httpClient;
  32. _fileSystem = fileSystem;
  33. _configurationManager = configurationManager;
  34. _appHost = appHost;
  35. }
  36. public async Task Fetch<T>(MetadataResult<T> itemResult, string imdbId, string language, string country, CancellationToken cancellationToken)
  37. where T : BaseItem
  38. {
  39. if (string.IsNullOrWhiteSpace(imdbId))
  40. {
  41. throw new ArgumentNullException(nameof(imdbId));
  42. }
  43. var item = itemResult.Item;
  44. var result = await GetRootObject(imdbId, cancellationToken).ConfigureAwait(false);
  45. // Only take the name and rating if the user's language is set to english, since Omdb has no localization
  46. if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase) || _configurationManager.Configuration.EnableNewOmdbSupport)
  47. {
  48. item.Name = result.Title;
  49. if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase))
  50. {
  51. item.OfficialRating = result.Rated;
  52. }
  53. }
  54. if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4
  55. && int.TryParse(result.Year.Substring(0, 4), NumberStyles.Number, _usCulture, out var year)
  56. && year >= 0)
  57. {
  58. item.ProductionYear = year;
  59. }
  60. var tomatoScore = result.GetRottenTomatoScore();
  61. if (tomatoScore.HasValue)
  62. {
  63. item.CriticRating = tomatoScore;
  64. }
  65. if (!string.IsNullOrEmpty(result.imdbVotes)
  66. && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out var voteCount)
  67. && voteCount >= 0)
  68. {
  69. //item.VoteCount = voteCount;
  70. }
  71. if (!string.IsNullOrEmpty(result.imdbRating)
  72. && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out var 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(MetadataProvider.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(nameof(seriesImdbId));
  93. }
  94. var 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)
  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)
  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) || _configurationManager.Configuration.EnableNewOmdbSupport)
  130. {
  131. item.Name = result.Title;
  132. if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase))
  133. {
  134. item.OfficialRating = result.Rated;
  135. }
  136. }
  137. if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4
  138. && int.TryParse(result.Year.Substring(0, 4), NumberStyles.Number, _usCulture, out var year)
  139. && year >= 0)
  140. {
  141. item.ProductionYear = year;
  142. }
  143. var tomatoScore = result.GetRottenTomatoScore();
  144. if (tomatoScore.HasValue)
  145. {
  146. item.CriticRating = tomatoScore;
  147. }
  148. if (!string.IsNullOrEmpty(result.imdbVotes)
  149. && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out var voteCount)
  150. && voteCount >= 0)
  151. {
  152. //item.VoteCount = voteCount;
  153. }
  154. if (!string.IsNullOrEmpty(result.imdbRating)
  155. && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out var imdbRating)
  156. && imdbRating >= 0)
  157. {
  158. item.CommunityRating = imdbRating;
  159. }
  160. if (!string.IsNullOrEmpty(result.Website))
  161. {
  162. item.HomePageUrl = result.Website;
  163. }
  164. if (!string.IsNullOrWhiteSpace(result.imdbID))
  165. {
  166. item.SetProviderId(MetadataProvider.Imdb, result.imdbID);
  167. }
  168. ParseAdditionalMetadata(itemResult, result);
  169. return true;
  170. }
  171. internal async Task<RootObject> GetRootObject(string imdbId, CancellationToken cancellationToken)
  172. {
  173. var path = await EnsureItemInfo(imdbId, cancellationToken).ConfigureAwait(false);
  174. string resultString;
  175. using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  176. {
  177. using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
  178. {
  179. resultString = reader.ReadToEnd();
  180. resultString = resultString.Replace("\"N/A\"", "\"\"");
  181. }
  182. }
  183. var result = _jsonSerializer.DeserializeFromString<RootObject>(resultString);
  184. return result;
  185. }
  186. internal async Task<SeasonRootObject> GetSeasonRootObject(string imdbId, int seasonId, CancellationToken cancellationToken)
  187. {
  188. var path = await EnsureSeasonInfo(imdbId, seasonId, cancellationToken).ConfigureAwait(false);
  189. string resultString;
  190. using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  191. {
  192. using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
  193. {
  194. resultString = reader.ReadToEnd();
  195. resultString = resultString.Replace("\"N/A\"", "\"\"");
  196. }
  197. }
  198. var result = _jsonSerializer.DeserializeFromString<SeasonRootObject>(resultString);
  199. return result;
  200. }
  201. internal static bool IsValidSeries(Dictionary<string, string> seriesProviderIds)
  202. {
  203. if (seriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out string id) && !string.IsNullOrEmpty(id))
  204. {
  205. // This check should ideally never be necessary but we're seeing some cases of this and haven't tracked them down yet.
  206. if (!string.IsNullOrWhiteSpace(id))
  207. {
  208. return true;
  209. }
  210. }
  211. return false;
  212. }
  213. public static string GetOmdbUrl(string query, IApplicationHost appHost, CancellationToken cancellationToken)
  214. {
  215. const string url = "https://www.omdbapi.com?apikey=2c9d9507";
  216. if (string.IsNullOrWhiteSpace(query))
  217. {
  218. return url;
  219. }
  220. return url + "&" + query;
  221. }
  222. private async Task<string> EnsureItemInfo(string imdbId, CancellationToken cancellationToken)
  223. {
  224. if (string.IsNullOrWhiteSpace(imdbId))
  225. {
  226. throw new ArgumentNullException(nameof(imdbId));
  227. }
  228. var imdbParam = imdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? imdbId : "tt" + imdbId;
  229. var path = GetDataFilePath(imdbParam);
  230. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  231. if (fileInfo.Exists)
  232. {
  233. // If it's recent or automatic updates are enabled, don't re-download
  234. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 1)
  235. {
  236. return path;
  237. }
  238. }
  239. var url = GetOmdbUrl(string.Format("i={0}&plot=short&tomatoes=true&r=json", imdbParam), _appHost, cancellationToken);
  240. using (var response = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false))
  241. {
  242. using (var stream = response.Content)
  243. {
  244. var rootObject = await _jsonSerializer.DeserializeFromStreamAsync<RootObject>(stream).ConfigureAwait(false);
  245. Directory.CreateDirectory(Path.GetDirectoryName(path));
  246. _jsonSerializer.SerializeToFile(rootObject, path);
  247. }
  248. }
  249. return path;
  250. }
  251. private async Task<string> EnsureSeasonInfo(string seriesImdbId, int seasonId, CancellationToken cancellationToken)
  252. {
  253. if (string.IsNullOrWhiteSpace(seriesImdbId))
  254. {
  255. throw new ArgumentException("The series IMDb ID was null or whitespace.", nameof(seriesImdbId));
  256. }
  257. var imdbParam = seriesImdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? seriesImdbId : "tt" + seriesImdbId;
  258. var path = GetSeasonFilePath(imdbParam, seasonId);
  259. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  260. if (fileInfo.Exists)
  261. {
  262. // If it's recent or automatic updates are enabled, don't re-download
  263. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 1)
  264. {
  265. return path;
  266. }
  267. }
  268. var url = GetOmdbUrl(string.Format("i={0}&season={1}&detail=full", imdbParam, seasonId), _appHost, cancellationToken);
  269. using (var response = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false))
  270. {
  271. using (var stream = response.Content)
  272. {
  273. var rootObject = await _jsonSerializer.DeserializeFromStreamAsync<SeasonRootObject>(stream).ConfigureAwait(false);
  274. Directory.CreateDirectory(Path.GetDirectoryName(path));
  275. _jsonSerializer.SerializeToFile(rootObject, path);
  276. }
  277. }
  278. return path;
  279. }
  280. public static Task<HttpResponseInfo> GetOmdbResponse(IHttpClient httpClient, string url, CancellationToken cancellationToken)
  281. {
  282. return httpClient.SendAsync(new HttpRequestOptions
  283. {
  284. Url = url,
  285. CancellationToken = cancellationToken,
  286. BufferContent = true,
  287. EnableDefaultUserAgent = true
  288. }, HttpMethod.Get);
  289. }
  290. internal string GetDataFilePath(string imdbId)
  291. {
  292. if (string.IsNullOrEmpty(imdbId))
  293. {
  294. throw new ArgumentNullException(nameof(imdbId));
  295. }
  296. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  297. var filename = string.Format("{0}.json", imdbId);
  298. return Path.Combine(dataPath, filename);
  299. }
  300. internal string GetSeasonFilePath(string imdbId, int seasonId)
  301. {
  302. if (string.IsNullOrEmpty(imdbId))
  303. {
  304. throw new ArgumentNullException(nameof(imdbId));
  305. }
  306. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  307. var filename = string.Format("{0}_season_{1}.json", imdbId, seasonId);
  308. return Path.Combine(dataPath, filename);
  309. }
  310. private void ParseAdditionalMetadata<T>(MetadataResult<T> itemResult, RootObject result)
  311. where T : BaseItem
  312. {
  313. var item = itemResult.Item;
  314. var isConfiguredForEnglish = IsConfiguredForEnglish(item) || _configurationManager.Configuration.EnableNewOmdbSupport;
  315. // Grab series genres because IMDb data is better than TVDB. Leave movies alone
  316. // But only do it if english is the preferred language because this data will not be localized
  317. if (isConfiguredForEnglish && !string.IsNullOrWhiteSpace(result.Genre))
  318. {
  319. item.Genres = Array.Empty<string>();
  320. foreach (var genre in result.Genre
  321. .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
  322. .Select(i => i.Trim())
  323. .Where(i => !string.IsNullOrWhiteSpace(i)))
  324. {
  325. item.AddGenre(genre);
  326. }
  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 (!Plugin.Instance.Configuration.CastAndCrew)
  334. {
  335. return;
  336. }
  337. if (!string.IsNullOrWhiteSpace(result.Director))
  338. {
  339. var person = new PersonInfo
  340. {
  341. Name = result.Director.Trim(),
  342. Type = PersonType.Director
  343. };
  344. itemResult.AddPerson(person);
  345. }
  346. if (!string.IsNullOrWhiteSpace(result.Writer))
  347. {
  348. var person = new PersonInfo
  349. {
  350. Name = result.Director.Trim(),
  351. Type = PersonType.Writer
  352. };
  353. itemResult.AddPerson(person);
  354. }
  355. if (!string.IsNullOrWhiteSpace(result.Actors))
  356. {
  357. var actorList = result.Actors.Split(',');
  358. foreach (var actor in actorList)
  359. {
  360. if (!string.IsNullOrWhiteSpace(actor))
  361. {
  362. var person = new PersonInfo
  363. {
  364. Name = actor.Trim(),
  365. Type = PersonType.Actor
  366. };
  367. itemResult.AddPerson(person);
  368. }
  369. }
  370. }
  371. }
  372. private bool IsConfiguredForEnglish(BaseItem item)
  373. {
  374. var lang = item.GetPreferredMetadataLanguage();
  375. // The data isn't localized and so can only be used for english users
  376. return string.Equals(lang, "en", StringComparison.OrdinalIgnoreCase);
  377. }
  378. internal class SeasonRootObject
  379. {
  380. public string Title { get; set; }
  381. public string seriesID { get; set; }
  382. public int Season { get; set; }
  383. public int? totalSeasons { get; set; }
  384. public RootObject[] Episodes { get; set; }
  385. public string Response { get; set; }
  386. }
  387. internal class RootObject
  388. {
  389. public string Title { get; set; }
  390. public string Year { get; set; }
  391. public string Rated { get; set; }
  392. public string Released { get; set; }
  393. public string Runtime { get; set; }
  394. public string Genre { get; set; }
  395. public string Director { get; set; }
  396. public string Writer { get; set; }
  397. public string Actors { get; set; }
  398. public string Plot { get; set; }
  399. public string Language { get; set; }
  400. public string Country { get; set; }
  401. public string Awards { get; set; }
  402. public string Poster { get; set; }
  403. public List<OmdbRating> Ratings { get; set; }
  404. public string Metascore { get; set; }
  405. public string imdbRating { get; set; }
  406. public string imdbVotes { get; set; }
  407. public string imdbID { get; set; }
  408. public string Type { get; set; }
  409. public string DVD { get; set; }
  410. public string BoxOffice { get; set; }
  411. public string Production { get; set; }
  412. public string Website { get; set; }
  413. public string Response { get; set; }
  414. public int Episode { get; set; }
  415. public float? GetRottenTomatoScore()
  416. {
  417. if (Ratings != null)
  418. {
  419. var rating = Ratings.FirstOrDefault(i => string.Equals(i.Source, "Rotten Tomatoes", StringComparison.OrdinalIgnoreCase));
  420. if (rating != null && rating.Value != null)
  421. {
  422. var value = rating.Value.TrimEnd('%');
  423. if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var 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. }