OmdbProvider.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. #pragma warning disable CS159, SA1300
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Text.Json;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Jellyfin.Extensions.Json;
  12. using MediaBrowser.Common;
  13. using MediaBrowser.Common.Net;
  14. using MediaBrowser.Controller.Configuration;
  15. using MediaBrowser.Controller.Entities;
  16. using MediaBrowser.Controller.Providers;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.IO;
  19. namespace MediaBrowser.Providers.Plugins.Omdb
  20. {
  21. /// <summary>Provider for OMDB service.</summary>
  22. public class OmdbProvider
  23. {
  24. private readonly IFileSystem _fileSystem;
  25. private readonly IServerConfigurationManager _configurationManager;
  26. private readonly IHttpClientFactory _httpClientFactory;
  27. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  28. private readonly IApplicationHost _appHost;
  29. private readonly JsonSerializerOptions _jsonOptions;
  30. /// <summary>Initializes a new instance of the <see cref="OmdbProvider"/> class.</summary>
  31. /// <param name="httpClientFactory">HttpClientFactory to use for calls to OMDB service.</param>
  32. /// <param name="fileSystem">IFileSystem to use for store OMDB data.</param>
  33. /// <param name="appHost">IApplicationHost to use.</param>
  34. /// <param name="configurationManager">IServerConfigurationManager to use.</param>
  35. public OmdbProvider(IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IApplicationHost appHost, IServerConfigurationManager configurationManager)
  36. {
  37. _httpClientFactory = httpClientFactory;
  38. _fileSystem = fileSystem;
  39. _configurationManager = configurationManager;
  40. _appHost = appHost;
  41. _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options);
  42. _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStringConverter());
  43. _jsonOptions.Converters.Add(new JsonOmdbNotAvailableInt32Converter());
  44. }
  45. /// <summary>Fetches data from OMDB service.</summary>
  46. /// <param name="itemResult">Metadata about media item.</param>
  47. /// <param name="imdbId">IMDB ID for media.</param>
  48. /// <param name="language">Media language.</param>
  49. /// <param name="country">Country of origin.</param>
  50. /// <param name="cancellationToken">CancellationToken to use for operation.</param>
  51. /// <typeparam name="T">The first generic type parameter.</typeparam>
  52. /// <returns>Returns a Task object that can be awaited.</returns>
  53. public async Task Fetch<T>(MetadataResult<T> itemResult, string imdbId, string language, string country, CancellationToken cancellationToken)
  54. where T : BaseItem
  55. {
  56. if (string.IsNullOrWhiteSpace(imdbId))
  57. {
  58. throw new ArgumentNullException(nameof(imdbId));
  59. }
  60. var item = itemResult.Item;
  61. var result = await GetRootObject(imdbId, cancellationToken).ConfigureAwait(false);
  62. // Only take the name and rating if the user's language is set to English, since Omdb has no localization
  63. if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase) || _configurationManager.Configuration.EnableNewOmdbSupport)
  64. {
  65. item.Name = result.Title;
  66. if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase))
  67. {
  68. item.OfficialRating = result.Rated;
  69. }
  70. }
  71. if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4
  72. && int.TryParse(result.Year.AsSpan().Slice(0, 4), NumberStyles.Number, _usCulture, out var year)
  73. && year >= 0)
  74. {
  75. item.ProductionYear = year;
  76. }
  77. var tomatoScore = result.GetRottenTomatoScore();
  78. if (tomatoScore.HasValue)
  79. {
  80. item.CriticRating = tomatoScore;
  81. }
  82. if (!string.IsNullOrEmpty(result.imdbVotes)
  83. && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out var voteCount)
  84. && voteCount >= 0)
  85. {
  86. // item.VoteCount = voteCount;
  87. }
  88. if (!string.IsNullOrEmpty(result.imdbRating)
  89. && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out var imdbRating)
  90. && imdbRating >= 0)
  91. {
  92. item.CommunityRating = imdbRating;
  93. }
  94. if (!string.IsNullOrEmpty(result.Website))
  95. {
  96. item.HomePageUrl = result.Website;
  97. }
  98. if (!string.IsNullOrWhiteSpace(result.imdbID))
  99. {
  100. item.SetProviderId(MetadataProvider.Imdb, result.imdbID);
  101. }
  102. ParseAdditionalMetadata(itemResult, result);
  103. }
  104. /// <summary>Gets data about an episode.</summary>
  105. /// <param name="itemResult">Metadata about episode.</param>
  106. /// <param name="episodeNumber">Episode number.</param>
  107. /// <param name="seasonNumber">Season number.</param>
  108. /// <param name="episodeImdbId">Episode ID.</param>
  109. /// <param name="seriesImdbId">Season ID.</param>
  110. /// <param name="language">Episode language.</param>
  111. /// <param name="country">Country of origin.</param>
  112. /// <param name="cancellationToken">CancellationToken to use for operation.</param>
  113. /// <typeparam name="T">The first generic type parameter.</typeparam>
  114. /// <returns>Whether operation was successful.</returns>
  115. public async Task<bool> FetchEpisodeData<T>(MetadataResult<T> itemResult, int episodeNumber, int seasonNumber, string episodeImdbId, string seriesImdbId, string language, string country, CancellationToken cancellationToken)
  116. where T : BaseItem
  117. {
  118. if (string.IsNullOrWhiteSpace(seriesImdbId))
  119. {
  120. throw new ArgumentNullException(nameof(seriesImdbId));
  121. }
  122. var item = itemResult.Item;
  123. var seasonResult = await GetSeasonRootObject(seriesImdbId, seasonNumber, cancellationToken).ConfigureAwait(false);
  124. if (seasonResult?.Episodes == null)
  125. {
  126. return false;
  127. }
  128. RootObject result = null;
  129. if (!string.IsNullOrWhiteSpace(episodeImdbId))
  130. {
  131. foreach (var episode in seasonResult.Episodes)
  132. {
  133. if (string.Equals(episodeImdbId, episode.imdbID, StringComparison.OrdinalIgnoreCase))
  134. {
  135. result = episode;
  136. break;
  137. }
  138. }
  139. }
  140. // finally, search by numbers
  141. if (result == null)
  142. {
  143. foreach (var episode in seasonResult.Episodes)
  144. {
  145. if (episode.Episode == episodeNumber)
  146. {
  147. result = episode;
  148. break;
  149. }
  150. }
  151. }
  152. if (result == null)
  153. {
  154. return false;
  155. }
  156. // Only take the name and rating if the user's language is set to English, since Omdb has no localization
  157. if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase) || _configurationManager.Configuration.EnableNewOmdbSupport)
  158. {
  159. item.Name = result.Title;
  160. if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase))
  161. {
  162. item.OfficialRating = result.Rated;
  163. }
  164. }
  165. if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4
  166. && int.TryParse(result.Year.AsSpan().Slice(0, 4), NumberStyles.Number, _usCulture, out var year)
  167. && year >= 0)
  168. {
  169. item.ProductionYear = year;
  170. }
  171. var tomatoScore = result.GetRottenTomatoScore();
  172. if (tomatoScore.HasValue)
  173. {
  174. item.CriticRating = tomatoScore;
  175. }
  176. if (!string.IsNullOrEmpty(result.imdbVotes)
  177. && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out var voteCount)
  178. && voteCount >= 0)
  179. {
  180. // item.VoteCount = voteCount;
  181. }
  182. if (!string.IsNullOrEmpty(result.imdbRating)
  183. && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out var imdbRating)
  184. && imdbRating >= 0)
  185. {
  186. item.CommunityRating = imdbRating;
  187. }
  188. if (!string.IsNullOrEmpty(result.Website))
  189. {
  190. item.HomePageUrl = result.Website;
  191. }
  192. if (!string.IsNullOrWhiteSpace(result.imdbID))
  193. {
  194. item.SetProviderId(MetadataProvider.Imdb, result.imdbID);
  195. }
  196. ParseAdditionalMetadata(itemResult, result);
  197. return true;
  198. }
  199. internal async Task<RootObject> GetRootObject(string imdbId, CancellationToken cancellationToken)
  200. {
  201. var path = await EnsureItemInfo(imdbId, cancellationToken).ConfigureAwait(false);
  202. await using var stream = File.OpenRead(path);
  203. return await JsonSerializer.DeserializeAsync<RootObject>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  204. }
  205. internal async Task<SeasonRootObject> GetSeasonRootObject(string imdbId, int seasonId, CancellationToken cancellationToken)
  206. {
  207. var path = await EnsureSeasonInfo(imdbId, seasonId, cancellationToken).ConfigureAwait(false);
  208. await using var stream = File.OpenRead(path);
  209. return await JsonSerializer.DeserializeAsync<SeasonRootObject>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  210. }
  211. internal static bool IsValidSeries(Dictionary<string, string> seriesProviderIds)
  212. {
  213. if (seriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out string id))
  214. {
  215. // This check should ideally never be necessary but we're seeing some cases of this and haven't tracked them down yet.
  216. if (!string.IsNullOrWhiteSpace(id))
  217. {
  218. return true;
  219. }
  220. }
  221. return false;
  222. }
  223. /// <summary>Gets OMDB URL.</summary>
  224. /// <param name="query">Appends query string to URL.</param>
  225. /// <returns>OMDB URL with optional query string.</returns>
  226. public static string GetOmdbUrl(string query)
  227. {
  228. const string Url = "https://www.omdbapi.com?apikey=2c9d9507";
  229. if (string.IsNullOrWhiteSpace(query))
  230. {
  231. return Url;
  232. }
  233. return Url + "&" + query;
  234. }
  235. private async Task<string> EnsureItemInfo(string imdbId, CancellationToken cancellationToken)
  236. {
  237. if (string.IsNullOrWhiteSpace(imdbId))
  238. {
  239. throw new ArgumentNullException(nameof(imdbId));
  240. }
  241. var imdbParam = imdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? imdbId : "tt" + imdbId;
  242. var path = GetDataFilePath(imdbParam);
  243. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  244. if (fileInfo.Exists)
  245. {
  246. // If it's recent or automatic updates are enabled, don't re-download
  247. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 1)
  248. {
  249. return path;
  250. }
  251. }
  252. else
  253. {
  254. Directory.CreateDirectory(Path.GetDirectoryName(path));
  255. }
  256. var url = GetOmdbUrl(
  257. string.Format(
  258. CultureInfo.InvariantCulture,
  259. "i={0}&plot=short&tomatoes=true&r=json",
  260. imdbParam));
  261. var rootObject = await GetDeserializedOmdbResponse<RootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
  262. await using FileStream jsonFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
  263. await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false);
  264. return path;
  265. }
  266. private async Task<string> EnsureSeasonInfo(string seriesImdbId, int seasonId, CancellationToken cancellationToken)
  267. {
  268. if (string.IsNullOrWhiteSpace(seriesImdbId))
  269. {
  270. throw new ArgumentException("The series IMDb ID was null or whitespace.", nameof(seriesImdbId));
  271. }
  272. var imdbParam = seriesImdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? seriesImdbId : "tt" + seriesImdbId;
  273. var path = GetSeasonFilePath(imdbParam, seasonId);
  274. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  275. if (fileInfo.Exists)
  276. {
  277. // If it's recent or automatic updates are enabled, don't re-download
  278. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 1)
  279. {
  280. return path;
  281. }
  282. }
  283. else
  284. {
  285. Directory.CreateDirectory(Path.GetDirectoryName(path));
  286. }
  287. var url = GetOmdbUrl(
  288. string.Format(
  289. CultureInfo.InvariantCulture,
  290. "i={0}&season={1}&detail=full",
  291. imdbParam,
  292. seasonId));
  293. var rootObject = await GetDeserializedOmdbResponse<SeasonRootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
  294. await using FileStream jsonFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
  295. await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false);
  296. return path;
  297. }
  298. /// <summary>Gets response from OMDB service as type T.</summary>
  299. /// <param name="httpClient">HttpClient instance to use for service call.</param>
  300. /// <param name="url">Http URL to use for service call.</param>
  301. /// <param name="cancellationToken">CancellationToken to use for service call.</param>
  302. /// <typeparam name="T">The first generic type parameter.</typeparam>
  303. /// <returns>OMDB service response as type T.</returns>
  304. public async Task<T> GetDeserializedOmdbResponse<T>(HttpClient httpClient, string url, CancellationToken cancellationToken)
  305. {
  306. using var response = await GetOmdbResponse(httpClient, url, cancellationToken).ConfigureAwait(false);
  307. await using Stream content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  308. return await JsonSerializer.DeserializeAsync<T>(content, _jsonOptions, cancellationToken).ConfigureAwait(false);
  309. }
  310. /// <summary>Gets response from OMDB service.</summary>
  311. /// <param name="httpClient">HttpClient instance to use for service call.</param>
  312. /// <param name="url">Http URL to use for service call.</param>
  313. /// <param name="cancellationToken">CancellationToken to use for service call.</param>
  314. /// <returns>OMDB service response as HttpResponseMessage.</returns>
  315. public static Task<HttpResponseMessage> GetOmdbResponse(HttpClient httpClient, string url, CancellationToken cancellationToken)
  316. {
  317. return httpClient.GetAsync(url, cancellationToken);
  318. }
  319. internal string GetDataFilePath(string imdbId)
  320. {
  321. if (string.IsNullOrEmpty(imdbId))
  322. {
  323. throw new ArgumentNullException(nameof(imdbId));
  324. }
  325. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  326. var filename = string.Format(CultureInfo.InvariantCulture, "{0}.json", imdbId);
  327. return Path.Combine(dataPath, filename);
  328. }
  329. internal string GetSeasonFilePath(string imdbId, int seasonId)
  330. {
  331. if (string.IsNullOrEmpty(imdbId))
  332. {
  333. throw new ArgumentNullException(nameof(imdbId));
  334. }
  335. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  336. var filename = string.Format(CultureInfo.InvariantCulture, "{0}_season_{1}.json", imdbId, seasonId);
  337. return Path.Combine(dataPath, filename);
  338. }
  339. private void ParseAdditionalMetadata<T>(MetadataResult<T> itemResult, RootObject result)
  340. where T : BaseItem
  341. {
  342. var item = itemResult.Item;
  343. var isConfiguredForEnglish = IsConfiguredForEnglish(item) || _configurationManager.Configuration.EnableNewOmdbSupport;
  344. // Grab series genres because IMDb data is better than TVDB. Leave movies alone
  345. // But only do it if English is the preferred language because this data will not be localized
  346. if (isConfiguredForEnglish && !string.IsNullOrWhiteSpace(result.Genre))
  347. {
  348. item.Genres = Array.Empty<string>();
  349. foreach (var genre in result.Genre
  350. .Split(',', StringSplitOptions.RemoveEmptyEntries)
  351. .Select(i => i.Trim())
  352. .Where(i => !string.IsNullOrWhiteSpace(i)))
  353. {
  354. item.AddGenre(genre);
  355. }
  356. }
  357. if (isConfiguredForEnglish)
  358. {
  359. // Omdb is currently English only, so for other languages skip this and let secondary providers fill it in
  360. item.Overview = result.Plot;
  361. }
  362. if (!Plugin.Instance.Configuration.CastAndCrew)
  363. {
  364. return;
  365. }
  366. if (!string.IsNullOrWhiteSpace(result.Director))
  367. {
  368. var person = new PersonInfo
  369. {
  370. Name = result.Director.Trim(),
  371. Type = PersonType.Director
  372. };
  373. itemResult.AddPerson(person);
  374. }
  375. if (!string.IsNullOrWhiteSpace(result.Writer))
  376. {
  377. var person = new PersonInfo
  378. {
  379. Name = result.Writer.Trim(),
  380. Type = PersonType.Writer
  381. };
  382. itemResult.AddPerson(person);
  383. }
  384. if (!string.IsNullOrWhiteSpace(result.Actors))
  385. {
  386. var actorList = result.Actors.Split(',');
  387. foreach (var actor in actorList)
  388. {
  389. if (!string.IsNullOrWhiteSpace(actor))
  390. {
  391. var person = new PersonInfo
  392. {
  393. Name = actor.Trim(),
  394. Type = PersonType.Actor
  395. };
  396. itemResult.AddPerson(person);
  397. }
  398. }
  399. }
  400. }
  401. private bool IsConfiguredForEnglish(BaseItem item)
  402. {
  403. var lang = item.GetPreferredMetadataLanguage();
  404. // The data isn't localized and so can only be used for English users
  405. return string.Equals(lang, "en", StringComparison.OrdinalIgnoreCase);
  406. }
  407. internal class SeasonRootObject
  408. {
  409. public string Title { get; set; }
  410. public string seriesID { get; set; }
  411. public int? Season { get; set; }
  412. public int? totalSeasons { get; set; }
  413. public RootObject[] Episodes { get; set; }
  414. public string Response { get; set; }
  415. }
  416. internal class RootObject
  417. {
  418. public string Title { get; set; }
  419. public string Year { get; set; }
  420. public string Rated { get; set; }
  421. public string Released { get; set; }
  422. public string Runtime { get; set; }
  423. public string Genre { get; set; }
  424. public string Director { get; set; }
  425. public string Writer { get; set; }
  426. public string Actors { get; set; }
  427. public string Plot { get; set; }
  428. public string Language { get; set; }
  429. public string Country { get; set; }
  430. public string Awards { get; set; }
  431. public string Poster { get; set; }
  432. public List<OmdbRating> Ratings { get; set; }
  433. public string Metascore { get; set; }
  434. public string imdbRating { get; set; }
  435. public string imdbVotes { get; set; }
  436. public string imdbID { get; set; }
  437. public string Type { get; set; }
  438. public string DVD { get; set; }
  439. public string BoxOffice { get; set; }
  440. public string Production { get; set; }
  441. public string Website { get; set; }
  442. public string Response { get; set; }
  443. public int? Episode { get; set; }
  444. public float? GetRottenTomatoScore()
  445. {
  446. if (Ratings != null)
  447. {
  448. var rating = Ratings.FirstOrDefault(i => string.Equals(i.Source, "Rotten Tomatoes", StringComparison.OrdinalIgnoreCase));
  449. if (rating != null && rating.Value != null)
  450. {
  451. var value = rating.Value.TrimEnd('%');
  452. if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var score))
  453. {
  454. return score;
  455. }
  456. }
  457. }
  458. return null;
  459. }
  460. }
  461. #pragma warning disable CA1034
  462. /// <summary>Describes OMDB rating.</summary>
  463. public class OmdbRating
  464. {
  465. /// <summary>Gets or sets rating source.</summary>
  466. public string Source { get; set; }
  467. /// <summary>Gets or sets rating value.</summary>
  468. public string Value { get; set; }
  469. }
  470. }
  471. }