OmdbProvider.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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;
  14. using MediaBrowser.Common.Net;
  15. using MediaBrowser.Controller.Configuration;
  16. using MediaBrowser.Controller.Entities;
  17. using MediaBrowser.Controller.Providers;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.IO;
  20. namespace MediaBrowser.Providers.Plugins.Omdb
  21. {
  22. /// <summary>Provider for OMDB service.</summary>
  23. public class OmdbProvider
  24. {
  25. private readonly IFileSystem _fileSystem;
  26. private readonly IServerConfigurationManager _configurationManager;
  27. private readonly IHttpClientFactory _httpClientFactory;
  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, CultureInfo.InvariantCulture, 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, CultureInfo.InvariantCulture, 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, CultureInfo.InvariantCulture, 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, CultureInfo.InvariantCulture, 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, CultureInfo.InvariantCulture, 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, CultureInfo.InvariantCulture, 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 = AsyncFile.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 = AsyncFile.OpenRead(path);
  209. return await JsonSerializer.DeserializeAsync<SeasonRootObject>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  210. }
  211. /// <summary>Gets OMDB URL.</summary>
  212. /// <param name="query">Appends query string to URL.</param>
  213. /// <returns>OMDB URL with optional query string.</returns>
  214. public static string GetOmdbUrl(string query)
  215. {
  216. const string Url = "https://www.omdbapi.com?apikey=2c9d9507";
  217. if (string.IsNullOrWhiteSpace(query))
  218. {
  219. return Url;
  220. }
  221. return Url + "&" + query;
  222. }
  223. private async Task<string> EnsureItemInfo(string imdbId, CancellationToken cancellationToken)
  224. {
  225. if (string.IsNullOrWhiteSpace(imdbId))
  226. {
  227. throw new ArgumentNullException(nameof(imdbId));
  228. }
  229. var imdbParam = imdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? imdbId : "tt" + imdbId;
  230. var path = GetDataFilePath(imdbParam);
  231. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  232. if (fileInfo.Exists)
  233. {
  234. // If it's recent or automatic updates are enabled, don't re-download
  235. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 1)
  236. {
  237. return path;
  238. }
  239. }
  240. else
  241. {
  242. Directory.CreateDirectory(Path.GetDirectoryName(path));
  243. }
  244. var url = GetOmdbUrl(
  245. string.Format(
  246. CultureInfo.InvariantCulture,
  247. "i={0}&plot=short&tomatoes=true&r=json",
  248. imdbParam));
  249. var rootObject = await GetDeserializedOmdbResponse<RootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
  250. await using FileStream jsonFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
  251. await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false);
  252. return path;
  253. }
  254. private async Task<string> EnsureSeasonInfo(string seriesImdbId, int seasonId, CancellationToken cancellationToken)
  255. {
  256. if (string.IsNullOrWhiteSpace(seriesImdbId))
  257. {
  258. throw new ArgumentException("The series IMDb ID was null or whitespace.", nameof(seriesImdbId));
  259. }
  260. var imdbParam = seriesImdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? seriesImdbId : "tt" + seriesImdbId;
  261. var path = GetSeasonFilePath(imdbParam, seasonId);
  262. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  263. if (fileInfo.Exists)
  264. {
  265. // If it's recent or automatic updates are enabled, don't re-download
  266. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 1)
  267. {
  268. return path;
  269. }
  270. }
  271. else
  272. {
  273. Directory.CreateDirectory(Path.GetDirectoryName(path));
  274. }
  275. var url = GetOmdbUrl(
  276. string.Format(
  277. CultureInfo.InvariantCulture,
  278. "i={0}&season={1}&detail=full",
  279. imdbParam,
  280. seasonId));
  281. var rootObject = await GetDeserializedOmdbResponse<SeasonRootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
  282. await using FileStream jsonFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
  283. await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false);
  284. return path;
  285. }
  286. /// <summary>Gets response from OMDB service as type T.</summary>
  287. /// <param name="httpClient">HttpClient instance to use for service call.</param>
  288. /// <param name="url">Http URL to use for service call.</param>
  289. /// <param name="cancellationToken">CancellationToken to use for service call.</param>
  290. /// <typeparam name="T">The first generic type parameter.</typeparam>
  291. /// <returns>OMDB service response as type T.</returns>
  292. public async Task<T> GetDeserializedOmdbResponse<T>(HttpClient httpClient, string url, CancellationToken cancellationToken)
  293. {
  294. using var response = await GetOmdbResponse(httpClient, url, cancellationToken).ConfigureAwait(false);
  295. await using Stream content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  296. return await JsonSerializer.DeserializeAsync<T>(content, _jsonOptions, cancellationToken).ConfigureAwait(false);
  297. }
  298. /// <summary>Gets response from OMDB service.</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. /// <returns>OMDB service response as HttpResponseMessage.</returns>
  303. public static Task<HttpResponseMessage> GetOmdbResponse(HttpClient httpClient, string url, CancellationToken cancellationToken)
  304. {
  305. return httpClient.GetAsync(url, cancellationToken);
  306. }
  307. internal string GetDataFilePath(string imdbId)
  308. {
  309. if (string.IsNullOrEmpty(imdbId))
  310. {
  311. throw new ArgumentNullException(nameof(imdbId));
  312. }
  313. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  314. var filename = string.Format(CultureInfo.InvariantCulture, "{0}.json", imdbId);
  315. return Path.Combine(dataPath, filename);
  316. }
  317. internal string GetSeasonFilePath(string imdbId, int seasonId)
  318. {
  319. if (string.IsNullOrEmpty(imdbId))
  320. {
  321. throw new ArgumentNullException(nameof(imdbId));
  322. }
  323. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  324. var filename = string.Format(CultureInfo.InvariantCulture, "{0}_season_{1}.json", imdbId, seasonId);
  325. return Path.Combine(dataPath, filename);
  326. }
  327. private void ParseAdditionalMetadata<T>(MetadataResult<T> itemResult, RootObject result)
  328. where T : BaseItem
  329. {
  330. var item = itemResult.Item;
  331. var isConfiguredForEnglish = IsConfiguredForEnglish(item) || _configurationManager.Configuration.EnableNewOmdbSupport;
  332. // Grab series genres because IMDb data is better than TVDB. Leave movies alone
  333. // But only do it if English is the preferred language because this data will not be localized
  334. if (isConfiguredForEnglish && !string.IsNullOrWhiteSpace(result.Genre))
  335. {
  336. item.Genres = Array.Empty<string>();
  337. foreach (var genre in result.Genre
  338. .Split(',', StringSplitOptions.RemoveEmptyEntries)
  339. .Select(i => i.Trim())
  340. .Where(i => !string.IsNullOrWhiteSpace(i)))
  341. {
  342. item.AddGenre(genre);
  343. }
  344. }
  345. if (isConfiguredForEnglish)
  346. {
  347. // Omdb is currently English only, so for other languages skip this and let secondary providers fill it in
  348. item.Overview = result.Plot;
  349. }
  350. if (!Plugin.Instance.Configuration.CastAndCrew)
  351. {
  352. return;
  353. }
  354. if (!string.IsNullOrWhiteSpace(result.Director))
  355. {
  356. var person = new PersonInfo
  357. {
  358. Name = result.Director.Trim(),
  359. Type = PersonType.Director
  360. };
  361. itemResult.AddPerson(person);
  362. }
  363. if (!string.IsNullOrWhiteSpace(result.Writer))
  364. {
  365. var person = new PersonInfo
  366. {
  367. Name = result.Writer.Trim(),
  368. Type = PersonType.Writer
  369. };
  370. itemResult.AddPerson(person);
  371. }
  372. if (!string.IsNullOrWhiteSpace(result.Actors))
  373. {
  374. var actorList = result.Actors.Split(',');
  375. foreach (var actor in actorList)
  376. {
  377. if (!string.IsNullOrWhiteSpace(actor))
  378. {
  379. var person = new PersonInfo
  380. {
  381. Name = actor.Trim(),
  382. Type = PersonType.Actor
  383. };
  384. itemResult.AddPerson(person);
  385. }
  386. }
  387. }
  388. }
  389. private bool IsConfiguredForEnglish(BaseItem item)
  390. {
  391. var lang = item.GetPreferredMetadataLanguage();
  392. // The data isn't localized and so can only be used for English users
  393. return string.Equals(lang, "en", StringComparison.OrdinalIgnoreCase);
  394. }
  395. internal class SeasonRootObject
  396. {
  397. public string Title { get; set; }
  398. public string seriesID { get; set; }
  399. public int? Season { get; set; }
  400. public int? totalSeasons { get; set; }
  401. public RootObject[] Episodes { get; set; }
  402. public string Response { get; set; }
  403. }
  404. internal class RootObject
  405. {
  406. public string Title { get; set; }
  407. public string Year { get; set; }
  408. public string Rated { get; set; }
  409. public string Released { get; set; }
  410. public string Runtime { get; set; }
  411. public string Genre { get; set; }
  412. public string Director { get; set; }
  413. public string Writer { get; set; }
  414. public string Actors { get; set; }
  415. public string Plot { get; set; }
  416. public string Language { get; set; }
  417. public string Country { get; set; }
  418. public string Awards { get; set; }
  419. public string Poster { get; set; }
  420. public List<OmdbRating> Ratings { get; set; }
  421. public string Metascore { get; set; }
  422. public string imdbRating { get; set; }
  423. public string imdbVotes { get; set; }
  424. public string imdbID { get; set; }
  425. public string Type { get; set; }
  426. public string DVD { get; set; }
  427. public string BoxOffice { get; set; }
  428. public string Production { get; set; }
  429. public string Website { get; set; }
  430. public string Response { get; set; }
  431. public int? Episode { get; set; }
  432. public float? GetRottenTomatoScore()
  433. {
  434. if (Ratings != null)
  435. {
  436. var rating = Ratings.FirstOrDefault(i => string.Equals(i.Source, "Rotten Tomatoes", StringComparison.OrdinalIgnoreCase));
  437. if (rating != null && rating.Value != null)
  438. {
  439. var value = rating.Value.TrimEnd('%');
  440. if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var score))
  441. {
  442. return score;
  443. }
  444. }
  445. }
  446. return null;
  447. }
  448. }
  449. #pragma warning disable CA1034
  450. /// <summary>Describes OMDB rating.</summary>
  451. public class OmdbRating
  452. {
  453. /// <summary>Gets or sets rating source.</summary>
  454. public string Source { get; set; }
  455. /// <summary>Gets or sets rating value.</summary>
  456. public string Value { get; set; }
  457. }
  458. }
  459. }