jellyfin/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs

570 lines
20 KiB
C#
Raw Normal View History

#pragma warning disable CS1591
2014-02-03 13:51:28 -07:00
using System;
using System.Collections.Generic;
2014-02-03 13:51:28 -07:00
using System.Globalization;
using System.IO;
2014-02-03 13:51:28 -07:00
using System.Linq;
2019-06-14 09:38:14 -07:00
using System.Net.Http;
using System.Text;
using System.Text.Json;
2020-12-24 08:10:30 -07:00
using System.Text.Json.Serialization;
2014-02-03 13:51:28 -07:00
using System.Threading;
using System.Threading.Tasks;
2018-09-12 10:26:21 -07:00
using MediaBrowser.Common;
using MediaBrowser.Common.Json;
2020-12-24 08:10:30 -07:00
using MediaBrowser.Common.Json.Converters;
2020-08-31 10:05:21 -07:00
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
2014-02-03 13:51:28 -07:00
2020-03-09 07:36:02 -07:00
namespace MediaBrowser.Providers.Plugins.Omdb
2014-02-03 13:51:28 -07:00
{
public class OmdbProvider
{
private readonly IFileSystem _fileSystem;
private readonly IServerConfigurationManager _configurationManager;
2020-08-17 12:10:02 -07:00
private readonly IHttpClientFactory _httpClientFactory;
2014-02-03 13:51:28 -07:00
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
2018-09-12 10:26:21 -07:00
private readonly IApplicationHost _appHost;
2020-12-25 11:37:38 -07:00
private readonly JsonSerializerOptions _jsonOptions;
2014-02-03 13:51:28 -07:00
public OmdbProvider(IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IApplicationHost appHost, IServerConfigurationManager configurationManager)
2014-02-03 13:51:28 -07:00
{
2020-08-17 12:10:02 -07:00
_httpClientFactory = httpClientFactory;
_fileSystem = fileSystem;
_configurationManager = configurationManager;
2018-09-12 10:26:21 -07:00
_appHost = appHost;
2020-12-25 11:37:38 -07:00
_jsonOptions = new JsonSerializerOptions(JsonDefaults.GetOptions());
_jsonOptions.Converters.Add(new JsonOmdbNotAvailableStringConverter());
_jsonOptions.Converters.Add(new JsonOmdbNotAvailableStructConverter<int>());
2014-02-03 13:51:28 -07:00
}
public async Task Fetch<T>(MetadataResult<T> itemResult, string imdbId, string language, string country, CancellationToken cancellationToken)
2016-11-15 12:42:43 -07:00
where T : BaseItem
2014-02-03 13:51:28 -07:00
{
2015-05-28 16:37:43 -07:00
if (string.IsNullOrWhiteSpace(imdbId))
{
throw new ArgumentNullException(nameof(imdbId));
2015-05-28 16:37:43 -07:00
}
2019-01-13 13:37:13 -07:00
var item = itemResult.Item;
2016-12-23 12:35:05 -07:00
var result = await GetRootObject(imdbId, cancellationToken).ConfigureAwait(false);
2014-02-03 13:51:28 -07:00
2020-11-18 06:46:14 -07:00
// Only take the name and rating if the user's language is set to English, since Omdb has no localization
2017-10-05 11:10:07 -07:00
if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase) || _configurationManager.Configuration.EnableNewOmdbSupport)
2016-11-15 12:42:43 -07:00
{
item.Name = result.Title;
2015-08-19 09:43:23 -07:00
2016-11-15 12:42:43 -07:00
if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase))
{
item.OfficialRating = result.Rated;
2015-07-06 07:20:23 -07:00
}
2016-11-15 12:42:43 -07:00
}
2015-05-30 07:32:18 -07:00
2016-11-15 12:42:43 -07:00
if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4
&& int.TryParse(result.Year.AsSpan().Slice(0, 4), NumberStyles.Number, _usCulture, out var year)
2016-11-15 12:42:43 -07:00
&& year >= 0)
{
item.ProductionYear = year;
}
2015-05-30 07:32:18 -07:00
2017-04-12 10:09:12 -07:00
var tomatoScore = result.GetRottenTomatoScore();
2014-02-03 13:51:28 -07:00
2017-04-12 10:09:12 -07:00
if (tomatoScore.HasValue)
2016-10-17 09:35:29 -07:00
{
2017-04-12 10:09:12 -07:00
item.CriticRating = tomatoScore;
2016-10-17 09:35:29 -07:00
}
2014-02-03 13:51:28 -07:00
2016-11-15 12:42:43 -07:00
if (!string.IsNullOrEmpty(result.imdbVotes)
&& int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out var voteCount)
2016-11-15 12:42:43 -07:00
&& voteCount >= 0)
{
2020-06-14 02:11:11 -07:00
// item.VoteCount = voteCount;
2016-11-15 12:42:43 -07:00
}
2014-02-03 13:51:28 -07:00
2016-11-15 12:42:43 -07:00
if (!string.IsNullOrEmpty(result.imdbRating)
&& float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out var imdbRating)
2016-11-15 12:42:43 -07:00
&& imdbRating >= 0)
{
item.CommunityRating = imdbRating;
}
2014-02-03 13:51:28 -07:00
if (!string.IsNullOrEmpty(result.Website))
{
item.HomePageUrl = result.Website;
}
2014-02-03 13:51:28 -07:00
2016-11-15 12:42:43 -07:00
if (!string.IsNullOrWhiteSpace(result.imdbID))
{
2020-06-06 12:17:49 -07:00
item.SetProviderId(MetadataProvider.Imdb, result.imdbID);
2016-11-15 12:42:43 -07:00
}
2015-05-30 07:32:18 -07:00
2016-11-15 12:42:43 -07:00
ParseAdditionalMetadata(itemResult, result);
}
public async Task<bool> FetchEpisodeData<T>(MetadataResult<T> itemResult, int episodeNumber, int seasonNumber, string episodeImdbId, string seriesImdbId, string language, string country, CancellationToken cancellationToken)
where T : BaseItem
{
if (string.IsNullOrWhiteSpace(seriesImdbId))
{
throw new ArgumentNullException(nameof(seriesImdbId));
}
2019-01-13 13:37:13 -07:00
var item = itemResult.Item;
var seasonResult = await GetSeasonRootObject(seriesImdbId, seasonNumber, cancellationToken).ConfigureAwait(false);
2016-10-22 07:51:19 -07:00
if (seasonResult?.Episodes == null)
2016-10-22 07:51:19 -07:00
{
return false;
}
RootObject result = null;
if (!string.IsNullOrWhiteSpace(episodeImdbId))
{
foreach (var episode in seasonResult.Episodes)
{
if (string.Equals(episodeImdbId, episode.imdbID, StringComparison.OrdinalIgnoreCase))
{
result = episode;
break;
}
}
}
// finally, search by numbers
if (result == null)
{
foreach (var episode in seasonResult.Episodes)
{
if (episode.Episode == episodeNumber)
{
result = episode;
break;
}
}
}
if (result == null)
{
return false;
}
2020-11-18 06:46:14 -07:00
// Only take the name and rating if the user's language is set to English, since Omdb has no localization
2017-10-05 11:10:07 -07:00
if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase) || _configurationManager.Configuration.EnableNewOmdbSupport)
{
item.Name = result.Title;
if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase))
{
item.OfficialRating = result.Rated;
}
}
if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4
&& int.TryParse(result.Year.AsSpan().Slice(0, 4), NumberStyles.Number, _usCulture, out var year)
&& year >= 0)
{
item.ProductionYear = year;
}
2017-04-12 10:09:12 -07:00
var tomatoScore = result.GetRottenTomatoScore();
2017-04-12 10:09:12 -07:00
if (tomatoScore.HasValue)
2016-10-17 09:35:29 -07:00
{
2017-04-12 10:09:12 -07:00
item.CriticRating = tomatoScore;
}
if (!string.IsNullOrEmpty(result.imdbVotes)
&& int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out var voteCount)
&& voteCount >= 0)
{
2020-06-14 02:11:11 -07:00
// item.VoteCount = voteCount;
}
if (!string.IsNullOrEmpty(result.imdbRating)
&& float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out var imdbRating)
&& imdbRating >= 0)
{
item.CommunityRating = imdbRating;
}
if (!string.IsNullOrEmpty(result.Website))
{
item.HomePageUrl = result.Website;
}
if (!string.IsNullOrWhiteSpace(result.imdbID))
{
2020-06-06 12:17:49 -07:00
item.SetProviderId(MetadataProvider.Imdb, result.imdbID);
}
ParseAdditionalMetadata(itemResult, result);
return true;
}
internal async Task<RootObject> GetRootObject(string imdbId, CancellationToken cancellationToken)
{
2016-12-23 12:35:05 -07:00
var path = await EnsureItemInfo(imdbId, cancellationToken).ConfigureAwait(false);
string resultString;
2020-01-08 09:52:50 -07:00
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
{
resultString = reader.ReadToEnd();
resultString = resultString.Replace("\"N/A\"", "\"\"");
}
}
var result = JsonSerializer.Deserialize<RootObject>(resultString, _jsonOptions);
return result;
}
internal async Task<SeasonRootObject> GetSeasonRootObject(string imdbId, int seasonId, CancellationToken cancellationToken)
{
2016-12-23 12:35:05 -07:00
var path = await EnsureSeasonInfo(imdbId, seasonId, cancellationToken).ConfigureAwait(false);
string resultString;
2020-01-08 09:52:50 -07:00
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
{
resultString = reader.ReadToEnd();
resultString = resultString.Replace("\"N/A\"", "\"\"");
}
}
var result = JsonSerializer.Deserialize<SeasonRootObject>(resultString, _jsonOptions);
return result;
}
internal static bool IsValidSeries(Dictionary<string, string> seriesProviderIds)
{
2020-06-06 12:17:49 -07:00
if (seriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out string id) && !string.IsNullOrEmpty(id))
{
// This check should ideally never be necessary but we're seeing some cases of this and haven't tracked them down yet.
if (!string.IsNullOrWhiteSpace(id))
{
return true;
}
}
return false;
}
2020-08-07 10:26:28 -07:00
public static string GetOmdbUrl(string query)
2017-02-13 14:03:41 -07:00
{
2020-08-07 10:26:28 -07:00
const string Url = "https://www.omdbapi.com?apikey=2c9d9507";
2018-09-12 10:26:21 -07:00
if (string.IsNullOrWhiteSpace(query))
2018-09-12 10:26:21 -07:00
{
2020-08-07 10:26:28 -07:00
return Url;
2018-09-12 10:26:21 -07:00
}
2020-08-07 10:26:28 -07:00
return Url + "&" + query;
2017-02-13 14:03:41 -07:00
}
private async Task<string> EnsureItemInfo(string imdbId, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(imdbId))
{
throw new ArgumentNullException(nameof(imdbId));
}
var imdbParam = imdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? imdbId : "tt" + imdbId;
var path = GetDataFilePath(imdbParam);
var fileInfo = _fileSystem.GetFileSystemInfo(path);
if (fileInfo.Exists)
{
// If it's recent or automatic updates are enabled, don't re-download
2018-09-12 10:26:21 -07:00
if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 1)
{
return path;
}
}
2020-08-07 10:26:28 -07:00
var url = GetOmdbUrl(
string.Format(
CultureInfo.InvariantCulture,
"i={0}&plot=short&tomatoes=true&r=json",
imdbParam));
var rootObject = await GetDeserializedOmdbResponse<RootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
2020-08-17 12:10:02 -07:00
Directory.CreateDirectory(Path.GetDirectoryName(path));
2020-12-23 11:24:58 -07:00
await using FileStream jsonFileStream = File.OpenWrite(path);
await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false);
return path;
}
private async Task<string> EnsureSeasonInfo(string seriesImdbId, int seasonId, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(seriesImdbId))
{
2019-01-12 13:41:08 -07:00
throw new ArgumentException("The series IMDb ID was null or whitespace.", nameof(seriesImdbId));
}
var imdbParam = seriesImdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? seriesImdbId : "tt" + seriesImdbId;
var path = GetSeasonFilePath(imdbParam, seasonId);
var fileInfo = _fileSystem.GetFileSystemInfo(path);
if (fileInfo.Exists)
{
// If it's recent or automatic updates are enabled, don't re-download
2018-09-12 10:26:21 -07:00
if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 1)
{
return path;
}
}
2020-08-07 10:26:28 -07:00
var url = GetOmdbUrl(
string.Format(
CultureInfo.InvariantCulture,
"i={0}&season={1}&detail=full",
imdbParam,
seasonId));
var rootObject = await GetDeserializedOmdbResponse<SeasonRootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
2020-08-17 12:10:02 -07:00
Directory.CreateDirectory(Path.GetDirectoryName(path));
2020-12-23 11:24:58 -07:00
await using FileStream jsonFileStream = File.OpenWrite(path);
await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false);
return path;
}
2020-12-25 11:37:38 -07:00
public async Task<T> GetDeserializedOmdbResponse<T>(HttpClient httpClient, string url, CancellationToken cancellationToken)
2020-12-23 06:45:05 -07:00
{
using var response = await GetOmdbResponse(httpClient, url, cancellationToken).ConfigureAwait(false);
2020-12-27 03:15:46 -07:00
await using Stream content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
2020-12-23 06:45:05 -07:00
2020-12-27 03:15:46 -07:00
return await JsonSerializer.DeserializeAsync<T>(content, _jsonOptions, cancellationToken).ConfigureAwait(false);
2020-12-23 06:45:05 -07:00
}
2020-08-17 12:10:02 -07:00
public static Task<HttpResponseMessage> GetOmdbResponse(HttpClient httpClient, string url, CancellationToken cancellationToken)
2017-02-04 14:22:55 -07:00
{
2020-08-17 12:10:02 -07:00
return httpClient.GetAsync(url, cancellationToken);
2017-02-04 14:22:55 -07:00
}
internal string GetDataFilePath(string imdbId)
{
if (string.IsNullOrEmpty(imdbId))
{
throw new ArgumentNullException(nameof(imdbId));
2014-02-03 13:51:28 -07:00
}
var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
2020-08-07 10:26:28 -07:00
var filename = string.Format(CultureInfo.InvariantCulture, "{0}.json", imdbId);
return Path.Combine(dataPath, filename);
2014-02-03 13:51:28 -07:00
}
internal string GetSeasonFilePath(string imdbId, int seasonId)
{
if (string.IsNullOrEmpty(imdbId))
{
throw new ArgumentNullException(nameof(imdbId));
}
var dataPath = Path.Combine(_configurationManager.ApplicationPaths.CachePath, "omdb");
2020-08-07 10:26:28 -07:00
var filename = string.Format(CultureInfo.InvariantCulture, "{0}_season_{1}.json", imdbId, seasonId);
return Path.Combine(dataPath, filename);
}
private void ParseAdditionalMetadata<T>(MetadataResult<T> itemResult, RootObject result)
where T : BaseItem
2014-02-03 13:51:28 -07:00
{
2019-01-13 13:37:13 -07:00
var item = itemResult.Item;
2017-10-05 11:10:07 -07:00
var isConfiguredForEnglish = IsConfiguredForEnglish(item) || _configurationManager.Configuration.EnableNewOmdbSupport;
2017-02-09 16:25:10 -07:00
// Grab series genres because IMDb data is better than TVDB. Leave movies alone
2020-11-18 06:46:14 -07:00
// But only do it if English is the preferred language because this data will not be localized
2017-02-09 16:25:10 -07:00
if (isConfiguredForEnglish && !string.IsNullOrWhiteSpace(result.Genre))
2014-02-03 13:51:28 -07:00
{
2018-09-12 10:26:21 -07:00
item.Genres = Array.Empty<string>();
2014-02-03 13:51:28 -07:00
foreach (var genre in result.Genre
2020-11-14 08:28:49 -07:00
.Split(',', StringSplitOptions.RemoveEmptyEntries)
2014-02-03 13:51:28 -07:00
.Select(i => i.Trim())
.Where(i => !string.IsNullOrWhiteSpace(i)))
{
item.AddGenre(genre);
}
}
2017-02-09 16:25:10 -07:00
if (isConfiguredForEnglish)
{
2020-11-18 06:46:14 -07:00
// Omdb is currently English only, so for other languages skip this and let secondary providers fill it in
2017-02-09 16:25:10 -07:00
item.Overview = result.Plot;
}
if (!Plugin.Instance.Configuration.CastAndCrew)
{
return;
}
if (!string.IsNullOrWhiteSpace(result.Director))
{
var person = new PersonInfo
{
Name = result.Director.Trim(),
Type = PersonType.Director
};
itemResult.AddPerson(person);
}
if (!string.IsNullOrWhiteSpace(result.Writer))
{
var person = new PersonInfo
{
2020-12-07 19:10:35 -07:00
Name = result.Writer.Trim(),
Type = PersonType.Writer
};
itemResult.AddPerson(person);
}
if (!string.IsNullOrWhiteSpace(result.Actors))
{
var actorList = result.Actors.Split(',');
foreach (var actor in actorList)
{
if (!string.IsNullOrWhiteSpace(actor))
{
var person = new PersonInfo
{
Name = actor.Trim(),
Type = PersonType.Actor
};
itemResult.AddPerson(person);
}
}
}
2014-02-03 13:51:28 -07:00
}
2017-02-09 16:25:10 -07:00
private bool IsConfiguredForEnglish(BaseItem item)
2014-02-03 13:51:28 -07:00
{
var lang = item.GetPreferredMetadataLanguage();
2020-11-18 06:46:14 -07:00
// The data isn't localized and so can only be used for English users
2014-02-15 09:36:09 -07:00
return string.Equals(lang, "en", StringComparison.OrdinalIgnoreCase);
2014-02-03 13:51:28 -07:00
}
internal class SeasonRootObject
{
public string Title { get; set; }
public string seriesID { get; set; }
2020-12-24 08:10:30 -07:00
public int? Season { get; set; }
public int? totalSeasons { get; set; }
public RootObject[] Episodes { get; set; }
public string Response { get; set; }
}
internal class RootObject
2014-02-03 13:51:28 -07:00
{
public string Title { get; set; }
2014-02-03 13:51:28 -07:00
public string Year { get; set; }
2014-02-03 13:51:28 -07:00
public string Rated { get; set; }
2014-02-03 13:51:28 -07:00
public string Released { get; set; }
2014-02-03 13:51:28 -07:00
public string Runtime { get; set; }
2014-02-03 13:51:28 -07:00
public string Genre { get; set; }
2014-02-03 13:51:28 -07:00
public string Director { get; set; }
2014-02-03 13:51:28 -07:00
public string Writer { get; set; }
2014-02-03 13:51:28 -07:00
public string Actors { get; set; }
2014-02-03 13:51:28 -07:00
public string Plot { get; set; }
2017-04-12 10:09:12 -07:00
public string Language { get; set; }
2017-04-12 10:09:12 -07:00
public string Country { get; set; }
2017-04-12 10:09:12 -07:00
public string Awards { get; set; }
2014-02-03 13:51:28 -07:00
public string Poster { get; set; }
2017-04-12 10:09:12 -07:00
public List<OmdbRating> Ratings { get; set; }
2017-04-12 10:09:12 -07:00
public string Metascore { get; set; }
2014-02-03 13:51:28 -07:00
public string imdbRating { get; set; }
2014-02-03 13:51:28 -07:00
public string imdbVotes { get; set; }
2014-02-03 13:51:28 -07:00
public string imdbID { get; set; }
2014-02-03 13:51:28 -07:00
public string Type { get; set; }
2014-02-03 13:51:28 -07:00
public string DVD { get; set; }
2014-02-03 13:51:28 -07:00
public string BoxOffice { get; set; }
2014-02-03 13:51:28 -07:00
public string Production { get; set; }
2014-02-03 13:51:28 -07:00
public string Website { get; set; }
2014-02-03 13:51:28 -07:00
public string Response { get; set; }
2020-12-24 08:10:30 -07:00
public int? Episode { get; set; }
2014-02-03 13:51:28 -07:00
2017-04-12 10:09:12 -07:00
public float? GetRottenTomatoScore()
{
if (Ratings != null)
{
var rating = Ratings.FirstOrDefault(i => string.Equals(i.Source, "Rotten Tomatoes", StringComparison.OrdinalIgnoreCase));
if (rating != null && rating.Value != null)
{
var value = rating.Value.TrimEnd('%');
if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var score))
2017-04-12 10:09:12 -07:00
{
return score;
}
}
}
2017-04-12 10:09:12 -07:00
return null;
}
}
2017-04-12 10:09:12 -07:00
public class OmdbRating
{
public string Source { get; set; }
2017-04-12 10:09:12 -07:00
public string Value { get; set; }
2014-02-03 13:51:28 -07:00
}
}
}