OmdbProvider.cs 19 KB

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