OmdbProvider.cs 19 KB

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