OmdbProvider.cs 22 KB

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