OmdbProvider.cs 19 KB

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