jellyfin/MediaBrowser.Providers/Movies/MovieDbProvider.cs

511 lines
17 KiB
C#
Raw Normal View History

using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Net;
2013-03-03 22:43:06 -07:00
using MediaBrowser.Controller.Configuration;
2013-02-20 18:33:05 -07:00
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
2013-06-09 09:47:28 -07:00
using MediaBrowser.Controller.Providers;
2013-02-20 18:33:05 -07:00
using MediaBrowser.Model.Logging;
2013-03-03 22:43:06 -07:00
using MediaBrowser.Model.Serialization;
2013-02-20 18:33:05 -07:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
2013-06-09 09:47:28 -07:00
namespace MediaBrowser.Providers.Movies
2013-02-20 18:33:05 -07:00
{
/// <summary>
/// Class MovieDbProvider
/// </summary>
public class MovieDbProvider : IRemoteMetadataProvider<Movie>, IDisposable
2013-02-20 18:33:05 -07:00
{
internal readonly SemaphoreSlim MovieDbResourcePool = new SemaphoreSlim(1, 1);
2013-03-03 22:43:06 -07:00
internal static MovieDbProvider Current { get; private set; }
private readonly IJsonSerializer _jsonSerializer;
private readonly IHttpClient _httpClient;
private readonly IFileSystem _fileSystem;
private readonly IServerConfigurationManager _configurationManager;
private readonly ILogger _logger;
2013-02-24 17:13:45 -07:00
public MovieDbProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILogger logger)
{
_jsonSerializer = jsonSerializer;
_httpClient = httpClient;
_fileSystem = fileSystem;
_configurationManager = configurationManager;
_logger = logger;
2013-03-03 22:43:06 -07:00
Current = this;
}
public Task<MetadataResult<Movie>> GetMetadata(ItemId id, CancellationToken cancellationToken)
2013-03-03 22:43:06 -07:00
{
return GetItemMetadata<Movie>(id, cancellationToken);
2013-02-24 14:53:54 -07:00
}
public Task<MetadataResult<T>> GetItemMetadata<T>(ItemId id, CancellationToken cancellationToken)
where T : Video, new ()
2013-02-20 18:33:05 -07:00
{
var movieDb = new GenericMovieDbInfo<T>(_logger, _jsonSerializer);
return movieDb.GetMetadata(id, cancellationToken);
2013-02-20 18:33:05 -07:00
}
public string Name
2013-02-20 18:33:05 -07:00
{
get { return "TheMovieDb"; }
2013-02-20 18:33:05 -07:00
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
2013-02-20 18:33:05 -07:00
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
MovieDbResourcePool.Dispose();
}
}
2013-02-20 18:33:05 -07:00
/// <summary>
/// The _TMDB settings task
/// </summary>
private TmdbSettingsResult _tmdbSettings;
private readonly SemaphoreSlim _tmdbSettingsSemaphore = new SemaphoreSlim(1, 1);
2013-02-20 18:33:05 -07:00
/// <summary>
/// Gets the TMDB settings.
/// </summary>
/// <returns>Task{TmdbSettingsResult}.</returns>
internal async Task<TmdbSettingsResult> GetTmdbSettings(CancellationToken cancellationToken)
2013-02-20 18:33:05 -07:00
{
if (_tmdbSettings != null)
2013-02-20 18:33:05 -07:00
{
return _tmdbSettings;
2013-02-20 18:33:05 -07:00
}
await _tmdbSettingsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
2013-02-20 18:33:05 -07:00
try
{
// Check again in case it got populated while we were waiting.
if (_tmdbSettings != null)
{
return _tmdbSettings;
}
using (var json = await GetMovieDbResponse(new HttpRequestOptions
2013-05-03 21:15:39 -07:00
{
Url = string.Format(TmdbConfigUrl, ApiKey),
CancellationToken = cancellationToken,
AcceptHeader = AcceptHeader
2013-05-03 21:15:39 -07:00
}).ConfigureAwait(false))
2013-02-20 18:33:05 -07:00
{
_tmdbSettings = _jsonSerializer.DeserializeFromStream<TmdbSettingsResult>(json);
return _tmdbSettings;
2013-02-20 18:33:05 -07:00
}
}
finally
2013-02-20 18:33:05 -07:00
{
_tmdbSettingsSemaphore.Release();
2013-02-20 18:33:05 -07:00
}
}
private const string TmdbConfigUrl = "http://api.themoviedb.org/3/configuration?api_key={0}";
2013-10-22 12:52:33 -07:00
private const string GetMovieInfo3 = @"http://api.themoviedb.org/3/movie/{0}?api_key={1}&append_to_response=casts,releases,images,keywords,trailers";
2013-05-03 21:15:39 -07:00
internal static string ApiKey = "f6bd687ffa63cd282b6ff2c6877f2669";
internal static string AcceptHeader = "application/json,image/*";
2013-02-20 18:33:05 -07:00
/// <summary>
/// Gets the movie data path.
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <param name="tmdbId">The TMDB id.</param>
/// <returns>System.String.</returns>
2014-01-30 14:23:54 -07:00
internal static string GetMovieDataPath(IApplicationPaths appPaths, string tmdbId)
{
2014-01-30 14:23:54 -07:00
var dataPath = GetMoviesDataPath(appPaths);
return Path.Combine(dataPath, tmdbId);
}
internal static string GetMoviesDataPath(IApplicationPaths appPaths)
{
var dataPath = Path.Combine(appPaths.DataPath, "tmdb-movies");
return dataPath;
}
/// <summary>
/// Downloads the movie info.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="preferredMetadataLanguage">The preferred metadata language.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
2014-01-30 14:23:54 -07:00
internal async Task DownloadMovieInfo(string id, string preferredMetadataLanguage, CancellationToken cancellationToken)
{
2014-01-30 14:23:54 -07:00
var mainResult = await FetchMainResult(id, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
2013-02-20 18:33:05 -07:00
if (mainResult == null) return;
2014-01-30 14:23:54 -07:00
var dataFilePath = GetDataFilePath(id, preferredMetadataLanguage);
2013-12-28 09:58:13 -07:00
Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
_jsonSerializer.SerializeToFile(mainResult, dataFilePath);
2013-02-20 18:33:05 -07:00
}
2014-02-03 10:44:13 -07:00
private readonly Task _cachedTask = Task.FromResult(true);
internal Task EnsureMovieInfo(string tmdbId, string language, CancellationToken cancellationToken)
2014-01-10 06:52:01 -07:00
{
if (string.IsNullOrEmpty(tmdbId))
{
throw new ArgumentNullException("tmdbId");
}
if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException("language");
}
var path = GetDataFilePath(tmdbId, language);
2014-01-10 06:52:01 -07:00
var fileInfo = _fileSystem.GetFileSystemInfo(path);
if (fileInfo.Exists)
{
// If it's recent or automatic updates are enabled, don't re-download
if ((_configurationManager.Configuration.EnableTmdbUpdates) || (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 7)
2014-01-10 06:52:01 -07:00
{
2014-02-03 10:44:13 -07:00
return _cachedTask;
2014-01-10 06:52:01 -07:00
}
}
return DownloadMovieInfo(tmdbId, language, cancellationToken);
2014-01-10 06:52:01 -07:00
}
internal string GetDataFilePath(string tmdbId, string preferredLanguage)
{
if (string.IsNullOrEmpty(tmdbId))
{
throw new ArgumentNullException("tmdbId");
}
if (string.IsNullOrEmpty(preferredLanguage))
{
throw new ArgumentNullException("preferredLanguage");
}
var path = GetMovieDataPath(_configurationManager.ApplicationPaths, tmdbId);
2013-12-28 09:58:13 -07:00
var filename = string.Format("all-{0}.json",
preferredLanguage ?? string.Empty);
return Path.Combine(path, filename);
}
/// <summary>
/// Fetches the main result.
/// </summary>
2013-02-20 18:33:05 -07:00
/// <param name="id">The id.</param>
/// <param name="language">The language.</param>
/// <param name="cancellationToken">The cancellation token</param>
2013-02-20 18:33:05 -07:00
/// <returns>Task{CompleteMovieData}.</returns>
internal async Task<CompleteMovieData> FetchMainResult(string id, string language, CancellationToken cancellationToken)
2013-02-20 18:33:05 -07:00
{
2014-01-30 14:23:54 -07:00
var url = string.Format(GetMovieInfo3, id, ApiKey);
2013-10-22 12:52:33 -07:00
// Get images in english and with no language
url += "&include_image_language=en,null";
2013-10-22 12:52:33 -07:00
if (!string.IsNullOrEmpty(language))
{
// If preferred language isn't english, get those images too
if (!string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
{
url += string.Format(",{0}", language);
}
url += string.Format("&language={0}", language);
2013-10-22 12:52:33 -07:00
}
CompleteMovieData mainResult;
2013-02-20 18:33:05 -07:00
cancellationToken.ThrowIfCancellationRequested();
using (var json = await GetMovieDbResponse(new HttpRequestOptions
2013-02-20 18:33:05 -07:00
{
Url = url,
CancellationToken = cancellationToken,
AcceptHeader = AcceptHeader
2013-05-03 21:15:39 -07:00
}).ConfigureAwait(false))
2013-02-20 18:33:05 -07:00
{
mainResult = _jsonSerializer.DeserializeFromStream<CompleteMovieData>(json);
2013-02-20 18:33:05 -07:00
}
cancellationToken.ThrowIfCancellationRequested();
if (mainResult != null && string.IsNullOrEmpty(mainResult.overview))
{
2013-10-22 12:52:33 -07:00
if (!string.IsNullOrEmpty(language) && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
2013-02-20 18:33:05 -07:00
{
_logger.Info("MovieDbProvider couldn't find meta for language " + language + ". Trying English...");
2014-01-30 14:23:54 -07:00
url = string.Format(GetMovieInfo3, id, ApiKey) + "&include_image_language=en,null&language=en";
2013-02-20 18:33:05 -07:00
using (var json = await GetMovieDbResponse(new HttpRequestOptions
2013-02-20 18:33:05 -07:00
{
Url = url,
CancellationToken = cancellationToken,
AcceptHeader = AcceptHeader
2013-05-03 21:15:39 -07:00
}).ConfigureAwait(false))
2013-02-20 18:33:05 -07:00
{
mainResult = _jsonSerializer.DeserializeFromStream<CompleteMovieData>(json);
2013-02-20 18:33:05 -07:00
}
if (String.IsNullOrEmpty(mainResult.overview))
{
_logger.Error("MovieDbProvider - Unable to find information for (id:" + id + ")");
2013-02-20 18:33:05 -07:00
return null;
}
}
}
return mainResult;
}
private DateTime _lastRequestDate = DateTime.MinValue;
/// <summary>
/// Gets the movie db response.
/// </summary>
internal async Task<Stream> GetMovieDbResponse(HttpRequestOptions options)
{
var cancellationToken = options.CancellationToken;
await MovieDbResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Limit to three requests per second
var diff = 340 - (DateTime.Now - _lastRequestDate).TotalMilliseconds;
if (diff > 0)
{
await Task.Delay(Convert.ToInt32(diff), cancellationToken).ConfigureAwait(false);
}
_lastRequestDate = DateTime.Now;
return await _httpClient.Get(options).ConfigureAwait(false);
}
finally
{
_lastRequestDate = DateTime.Now;
MovieDbResourcePool.Release();
}
}
2013-02-20 18:33:05 -07:00
2013-10-22 12:52:33 -07:00
public void Dispose()
{
Dispose(true);
}
2013-02-20 18:33:05 -07:00
/// <summary>
/// Class TmdbTitle
/// </summary>
2013-10-22 12:52:33 -07:00
internal class TmdbTitle
{
/// <summary>
/// Gets or sets the iso_3166_1.
/// </summary>
/// <value>The iso_3166_1.</value>
public string iso_3166_1 { get; set; }
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>The title.</value>
public string title { get; set; }
}
/// <summary>
/// Class TmdbAltTitleResults
/// </summary>
2013-10-22 12:52:33 -07:00
internal class TmdbAltTitleResults
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
public int id { get; set; }
/// <summary>
/// Gets or sets the titles.
/// </summary>
/// <value>The titles.</value>
public List<TmdbTitle> titles { get; set; }
}
2013-10-22 12:52:33 -07:00
internal class BelongsToCollection
2013-02-20 18:33:05 -07:00
{
public int id { get; set; }
public string name { get; set; }
public string poster_path { get; set; }
public string backdrop_path { get; set; }
}
2013-10-22 12:52:33 -07:00
internal class GenreItem
2013-02-20 18:33:05 -07:00
{
public int id { get; set; }
public string name { get; set; }
}
2013-10-22 12:52:33 -07:00
internal class ProductionCompany
2013-02-20 18:33:05 -07:00
{
public string name { get; set; }
public int id { get; set; }
}
2013-10-22 12:52:33 -07:00
internal class ProductionCountry
2013-02-20 18:33:05 -07:00
{
public string iso_3166_1 { get; set; }
public string name { get; set; }
}
2013-10-22 12:52:33 -07:00
internal class SpokenLanguage
2013-02-20 18:33:05 -07:00
{
public string iso_639_1 { get; set; }
public string name { get; set; }
}
2013-10-22 12:52:33 -07:00
internal class Cast
2013-02-20 18:33:05 -07:00
{
public int id { get; set; }
public string name { get; set; }
public string character { get; set; }
public int order { get; set; }
public int cast_id { get; set; }
2013-02-20 18:33:05 -07:00
public string profile_path { get; set; }
}
2013-10-22 12:52:33 -07:00
internal class Crew
2013-02-20 18:33:05 -07:00
{
public int id { get; set; }
public string name { get; set; }
public string department { get; set; }
public string job { get; set; }
public string profile_path { get; set; }
2013-02-20 18:33:05 -07:00
}
2013-10-22 12:52:33 -07:00
internal class Casts
2013-02-20 18:33:05 -07:00
{
public List<Cast> cast { get; set; }
public List<Crew> crew { get; set; }
2013-02-20 18:33:05 -07:00
}
2013-10-22 12:52:33 -07:00
internal class Country
2013-02-20 18:33:05 -07:00
{
public string iso_3166_1 { get; set; }
public string certification { get; set; }
public DateTime release_date { get; set; }
2013-02-20 18:33:05 -07:00
}
2013-10-22 12:52:33 -07:00
internal class Releases
2013-02-20 18:33:05 -07:00
{
public List<Country> countries { get; set; }
2013-02-20 18:33:05 -07:00
}
2013-10-22 12:52:33 -07:00
internal class Backdrop
{
public string file_path { get; set; }
public int width { get; set; }
public int height { get; set; }
public object iso_639_1 { get; set; }
public double aspect_ratio { get; set; }
public double vote_average { get; set; }
public int vote_count { get; set; }
}
internal class Poster
{
public string file_path { get; set; }
public int width { get; set; }
public int height { get; set; }
public string iso_639_1 { get; set; }
public double aspect_ratio { get; set; }
public double vote_average { get; set; }
public int vote_count { get; set; }
}
internal class Images
{
public List<Backdrop> backdrops { get; set; }
public List<Poster> posters { get; set; }
}
internal class Keyword
2013-02-20 18:33:05 -07:00
{
public int id { get; set; }
public string name { get; set; }
}
2013-10-22 12:52:33 -07:00
internal class Keywords
{
public List<Keyword> keywords { get; set; }
2013-02-20 18:33:05 -07:00
}
2013-10-22 12:52:33 -07:00
internal class Youtube
{
public string name { get; set; }
public string size { get; set; }
public string source { get; set; }
}
internal class Trailers
{
public List<object> quicktime { get; set; }
public List<Youtube> youtube { get; set; }
}
internal class CompleteMovieData
2013-02-20 18:33:05 -07:00
{
public bool adult { get; set; }
public string backdrop_path { get; set; }
public BelongsToCollection belongs_to_collection { get; set; }
public int budget { get; set; }
public List<GenreItem> genres { get; set; }
2013-02-20 18:33:05 -07:00
public string homepage { get; set; }
public int id { get; set; }
public string imdb_id { get; set; }
public string original_title { get; set; }
public string overview { get; set; }
public double popularity { get; set; }
public string poster_path { get; set; }
public List<ProductionCompany> production_companies { get; set; }
public List<ProductionCountry> production_countries { get; set; }
public DateTime release_date { get; set; }
public int revenue { get; set; }
public int runtime { get; set; }
public List<SpokenLanguage> spoken_languages { get; set; }
public string status { get; set; }
2013-02-20 18:33:05 -07:00
public string tagline { get; set; }
public string title { get; set; }
2013-10-22 12:52:33 -07:00
public string name { get; set; }
2013-02-20 18:33:05 -07:00
public double vote_average { get; set; }
public int vote_count { get; set; }
public Casts casts { get; set; }
public Releases releases { get; set; }
2013-10-22 12:52:33 -07:00
public Images images { get; set; }
public Keywords keywords { get; set; }
public Trailers trailers { get; set; }
}
2013-02-20 18:33:05 -07:00
}
}