OmdbProvider.cs 22 KB

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