OmdbProvider.cs 19 KB

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