OmdbProvider.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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.IO;
  18. using MediaBrowser.Controller.IO;
  19. namespace MediaBrowser.Providers.Omdb
  20. {
  21. public class OmdbProvider
  22. {
  23. internal static readonly SemaphoreSlim ResourcePool = new SemaphoreSlim(1, 1);
  24. private readonly IJsonSerializer _jsonSerializer;
  25. private readonly IFileSystem _fileSystem;
  26. private readonly IServerConfigurationManager _configurationManager;
  27. private readonly IHttpClient _httpClient;
  28. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  29. public OmdbProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager configurationManager)
  30. {
  31. _jsonSerializer = jsonSerializer;
  32. _httpClient = httpClient;
  33. _fileSystem = fileSystem;
  34. _configurationManager = configurationManager;
  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))
  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. // Seeing some bogus RT data on omdb for series, so filter it out here
  62. // RT doesn't even have tv series
  63. int tomatoMeter;
  64. if (!string.IsNullOrEmpty(result.tomatoMeter)
  65. && int.TryParse(result.tomatoMeter, NumberStyles.Integer, _usCulture, out tomatoMeter)
  66. && tomatoMeter >= 0)
  67. {
  68. item.CriticRating = tomatoMeter;
  69. }
  70. if (!string.IsNullOrEmpty(result.tomatoConsensus)
  71. && !string.Equals(result.tomatoConsensus, "No consensus yet.", StringComparison.OrdinalIgnoreCase))
  72. {
  73. item.CriticRatingSummary = WebUtility.HtmlDecode(result.tomatoConsensus);
  74. }
  75. int voteCount;
  76. if (!string.IsNullOrEmpty(result.imdbVotes)
  77. && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out voteCount)
  78. && voteCount >= 0)
  79. {
  80. item.VoteCount = voteCount;
  81. }
  82. float imdbRating;
  83. if (!string.IsNullOrEmpty(result.imdbRating)
  84. && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out imdbRating)
  85. && imdbRating >= 0)
  86. {
  87. item.CommunityRating = imdbRating;
  88. }
  89. if (!string.IsNullOrEmpty(result.Website))
  90. {
  91. item.HomePageUrl = result.Website;
  92. }
  93. if (!string.IsNullOrWhiteSpace(result.imdbID))
  94. {
  95. item.SetProviderId(MetadataProviders.Imdb, result.imdbID);
  96. }
  97. ParseAdditionalMetadata(itemResult, result);
  98. }
  99. public async Task<bool> FetchEpisodeData<T>(MetadataResult<T> itemResult, int episodeNumber, int seasonNumber, string imdbId, string language, string country, CancellationToken cancellationToken)
  100. where T : BaseItem
  101. {
  102. if (string.IsNullOrWhiteSpace(imdbId))
  103. {
  104. throw new ArgumentNullException("imdbId");
  105. }
  106. T item = itemResult.Item;
  107. var seasonResult = await GetSeasonRootObject(imdbId, seasonNumber, cancellationToken).ConfigureAwait(false);
  108. if (seasonResult == null)
  109. {
  110. return false;
  111. }
  112. RootObject result = null;
  113. foreach (var episode in (seasonResult.Episodes ?? new RootObject[] { }))
  114. {
  115. if (episode.Episode == episodeNumber)
  116. {
  117. result = episode;
  118. break;
  119. }
  120. }
  121. if (result == null)
  122. {
  123. return false;
  124. }
  125. // Only take the name and rating if the user's language is set to english, since Omdb has no localization
  126. if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
  127. {
  128. item.Name = result.Title;
  129. if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase))
  130. {
  131. item.OfficialRating = result.Rated;
  132. }
  133. }
  134. int year;
  135. if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4
  136. && int.TryParse(result.Year.Substring(0, 4), NumberStyles.Number, _usCulture, out year)
  137. && year >= 0)
  138. {
  139. item.ProductionYear = year;
  140. }
  141. // Seeing some bogus RT data on omdb for series, so filter it out here
  142. // RT doesn't even have tv series
  143. int tomatoMeter;
  144. if (!string.IsNullOrEmpty(result.tomatoMeter)
  145. && int.TryParse(result.tomatoMeter, NumberStyles.Integer, _usCulture, out tomatoMeter)
  146. && tomatoMeter >= 0)
  147. {
  148. item.CriticRating = tomatoMeter;
  149. }
  150. if (!string.IsNullOrEmpty(result.tomatoConsensus)
  151. && !string.Equals(result.tomatoConsensus, "No consensus yet.", StringComparison.OrdinalIgnoreCase))
  152. {
  153. item.CriticRatingSummary = WebUtility.HtmlDecode(result.tomatoConsensus);
  154. }
  155. int voteCount;
  156. if (!string.IsNullOrEmpty(result.imdbVotes)
  157. && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out voteCount)
  158. && voteCount >= 0)
  159. {
  160. item.VoteCount = voteCount;
  161. }
  162. float imdbRating;
  163. if (!string.IsNullOrEmpty(result.imdbRating)
  164. && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out imdbRating)
  165. && imdbRating >= 0)
  166. {
  167. item.CommunityRating = imdbRating;
  168. }
  169. if (!string.IsNullOrEmpty(result.Website))
  170. {
  171. item.HomePageUrl = result.Website;
  172. }
  173. if (!string.IsNullOrWhiteSpace(result.imdbID))
  174. {
  175. item.SetProviderId(MetadataProviders.Imdb, result.imdbID);
  176. }
  177. ParseAdditionalMetadata(itemResult, result);
  178. return true;
  179. }
  180. internal async Task<RootObject> GetRootObject(string imdbId, CancellationToken cancellationToken)
  181. {
  182. var path = await EnsureItemInfo(imdbId, cancellationToken).ConfigureAwait(false);
  183. string resultString;
  184. using (Stream stream = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
  185. {
  186. using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
  187. {
  188. resultString = reader.ReadToEnd();
  189. resultString = resultString.Replace("\"N/A\"", "\"\"");
  190. }
  191. }
  192. var result = _jsonSerializer.DeserializeFromString<RootObject>(resultString);
  193. return result;
  194. }
  195. internal async Task<SeasonRootObject> GetSeasonRootObject(string imdbId, int seasonId, CancellationToken cancellationToken)
  196. {
  197. var path = await EnsureSeasonInfo(imdbId, seasonId, cancellationToken).ConfigureAwait(false);
  198. string resultString;
  199. using (Stream stream = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
  200. {
  201. using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
  202. {
  203. resultString = reader.ReadToEnd();
  204. resultString = resultString.Replace("\"N/A\"", "\"\"");
  205. }
  206. }
  207. var result = _jsonSerializer.DeserializeFromString<SeasonRootObject>(resultString);
  208. return result;
  209. }
  210. internal static bool IsValidSeries(Dictionary<string, string> seriesProviderIds)
  211. {
  212. string id;
  213. if (seriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out id) && !string.IsNullOrEmpty(id))
  214. {
  215. // This check should ideally never be necessary but we're seeing some cases of this and haven't tracked them down yet.
  216. if (!string.IsNullOrWhiteSpace(id))
  217. {
  218. return true;
  219. }
  220. }
  221. return false;
  222. }
  223. public static async Task<string> GetOmdbBaseUrl(CancellationToken cancellationToken)
  224. {
  225. return "https://www.omdbapi.com";
  226. }
  227. private async Task<string> EnsureItemInfo(string imdbId, CancellationToken cancellationToken)
  228. {
  229. if (string.IsNullOrWhiteSpace(imdbId))
  230. {
  231. throw new ArgumentNullException("imdbId");
  232. }
  233. var imdbParam = imdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? imdbId : "tt" + imdbId;
  234. var path = GetDataFilePath(imdbParam);
  235. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  236. if (fileInfo.Exists)
  237. {
  238. // If it's recent or automatic updates are enabled, don't re-download
  239. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
  240. {
  241. return path;
  242. }
  243. }
  244. var baseUrl = await GetOmdbBaseUrl(cancellationToken).ConfigureAwait(false);
  245. var url = string.Format(baseUrl + "/?i={0}&plot=full&tomatoes=true&r=json", imdbParam);
  246. using (var stream = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false))
  247. {
  248. var rootObject = _jsonSerializer.DeserializeFromStream<RootObject>(stream);
  249. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  250. _jsonSerializer.SerializeToFile(rootObject, path);
  251. }
  252. return path;
  253. }
  254. private async Task<string> EnsureSeasonInfo(string seriesImdbId, int seasonId, CancellationToken cancellationToken)
  255. {
  256. if (string.IsNullOrWhiteSpace(seriesImdbId))
  257. {
  258. throw new ArgumentNullException("imdbId");
  259. }
  260. var imdbParam = seriesImdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? seriesImdbId : "tt" + seriesImdbId;
  261. var path = GetSeasonFilePath(imdbParam, seasonId);
  262. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  263. if (fileInfo.Exists)
  264. {
  265. // If it's recent or automatic updates are enabled, don't re-download
  266. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
  267. {
  268. return path;
  269. }
  270. }
  271. var baseUrl = await GetOmdbBaseUrl(cancellationToken).ConfigureAwait(false);
  272. var url = string.Format(baseUrl + "/?i={0}&season={1}&detail=full", imdbParam, seasonId);
  273. using (var stream = await GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false))
  274. {
  275. var rootObject = _jsonSerializer.DeserializeFromStream<SeasonRootObject>(stream);
  276. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  277. _jsonSerializer.SerializeToFile(rootObject, path);
  278. }
  279. return path;
  280. }
  281. public static Task<Stream> GetOmdbResponse(IHttpClient httpClient, string url, CancellationToken cancellationToken)
  282. {
  283. return httpClient.Get(new HttpRequestOptions
  284. {
  285. Url = url,
  286. ResourcePool = ResourcePool,
  287. CancellationToken = cancellationToken,
  288. BufferContent = true,
  289. EnableDefaultUserAgent = true
  290. });
  291. }
  292. internal string GetDataFilePath(string imdbId)
  293. {
  294. if (string.IsNullOrEmpty(imdbId))
  295. {
  296. throw new ArgumentNullException("imdbId");
  297. }
  298. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  299. var filename = string.Format("{0}.json", imdbId);
  300. return Path.Combine(dataPath, filename);
  301. }
  302. internal string GetSeasonFilePath(string imdbId, int seasonId)
  303. {
  304. if (string.IsNullOrEmpty(imdbId))
  305. {
  306. throw new ArgumentNullException("imdbId");
  307. }
  308. var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
  309. var filename = string.Format("{0}_season_{1}.json", imdbId, seasonId);
  310. return Path.Combine(dataPath, filename);
  311. }
  312. private void ParseAdditionalMetadata<T>(MetadataResult<T> itemResult, RootObject result)
  313. where T : BaseItem
  314. {
  315. T item = itemResult.Item;
  316. var isConfiguredForEnglish = IsConfiguredForEnglish(item);
  317. // Grab series genres because imdb data is better than tvdb. Leave movies alone
  318. // But only do it if english is the preferred language because this data will not be localized
  319. if (isConfiguredForEnglish && !string.IsNullOrWhiteSpace(result.Genre))
  320. {
  321. item.Genres.Clear();
  322. foreach (var genre in result.Genre
  323. .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
  324. .Select(i => i.Trim())
  325. .Where(i => !string.IsNullOrWhiteSpace(i)))
  326. {
  327. item.AddGenre(genre);
  328. }
  329. }
  330. var hasAwards = item as IHasAwards;
  331. if (hasAwards != null && !string.IsNullOrEmpty(result.Awards))
  332. {
  333. hasAwards.AwardSummary = WebUtility.HtmlDecode(result.Awards);
  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 int Episode { get; set; }
  397. public string Runtime { get; set; }
  398. public string Genre { get; set; }
  399. public string Director { get; set; }
  400. public string Writer { get; set; }
  401. public string Actors { get; set; }
  402. public string Plot { get; set; }
  403. public string Poster { get; set; }
  404. public string imdbRating { get; set; }
  405. public string imdbVotes { get; set; }
  406. public string imdbID { get; set; }
  407. public string Type { get; set; }
  408. public string tomatoMeter { get; set; }
  409. public string tomatoImage { get; set; }
  410. public string tomatoRating { get; set; }
  411. public string tomatoReviews { get; set; }
  412. public string tomatoFresh { get; set; }
  413. public string tomatoRotten { get; set; }
  414. public string tomatoConsensus { get; set; }
  415. public string tomatoUserMeter { get; set; }
  416. public string tomatoUserRating { get; set; }
  417. public string tomatoUserReviews { get; set; }
  418. public string DVD { get; set; }
  419. public string BoxOffice { get; set; }
  420. public string Production { get; set; }
  421. public string Website { get; set; }
  422. public string Response { get; set; }
  423. public string Language { get; set; }
  424. public string Country { get; set; }
  425. public string Awards { get; set; }
  426. public string Metascore { get; set; }
  427. }
  428. }
  429. }