1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
|
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Providers.Movies;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Globalization;
namespace MediaBrowser.Providers.BoxSets
{
public class MovieDbBoxSetProvider : IRemoteMetadataProvider<BoxSet, BoxSetInfo>
{
private const string GetCollectionInfo3 = @"https://api.themoviedb.org/3/collection/{0}?api_key={1}&append_to_response=images";
internal static MovieDbBoxSetProvider Current;
private readonly ILogger _logger;
private readonly IJsonSerializer _json;
private readonly IServerConfigurationManager _config;
private readonly IFileSystem _fileSystem;
private readonly ILocalizationManager _localization;
private readonly IHttpClient _httpClient;
private readonly ILibraryManager _libraryManager;
public MovieDbBoxSetProvider(ILogger logger, IJsonSerializer json, IServerConfigurationManager config, IFileSystem fileSystem, ILocalizationManager localization, IHttpClient httpClient, ILibraryManager libraryManager)
{
_logger = logger;
_json = json;
_config = config;
_fileSystem = fileSystem;
_localization = localization;
_httpClient = httpClient;
_libraryManager = libraryManager;
Current = this;
}
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(BoxSetInfo searchInfo, CancellationToken cancellationToken)
{
var tmdbId = searchInfo.GetProviderId(MetadataProviders.Tmdb);
if (!string.IsNullOrEmpty(tmdbId))
{
await EnsureInfo(tmdbId, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, searchInfo.MetadataLanguage);
var info = _json.DeserializeFromFile<RootObject>(dataFilePath);
var images = (info.images ?? new Images()).posters ?? new List<Poster>();
var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
var tmdbImageUrl = tmdbSettings.images.secure_base_url + "original";
var result = new RemoteSearchResult
{
Name = info.name,
SearchProviderName = Name,
ImageUrl = images.Count == 0 ? null : (tmdbImageUrl + images[0].file_path)
};
result.SetProviderId(MetadataProviders.Tmdb, info.id.ToString(_usCulture));
return new[] { result };
}
return await new MovieDbSearch(_logger, _json, _libraryManager).GetSearchResults(searchInfo, cancellationToken).ConfigureAwait(false);
}
public async Task<MetadataResult<BoxSet>> GetMetadata(BoxSetInfo id, CancellationToken cancellationToken)
{
var tmdbId = id.GetProviderId(MetadataProviders.Tmdb);
// We don't already have an Id, need to fetch it
if (string.IsNullOrEmpty(tmdbId))
{
var searchResults = await new MovieDbSearch(_logger, _json, _libraryManager).GetSearchResults(id, cancellationToken).ConfigureAwait(false);
var searchResult = searchResults.FirstOrDefault();
if (searchResult != null)
{
tmdbId = searchResult.GetProviderId(MetadataProviders.Tmdb);
}
}
var result = new MetadataResult<BoxSet>();
if (!string.IsNullOrEmpty(tmdbId))
{
var mainResult = await GetMovieDbResult(tmdbId, id.MetadataLanguage, cancellationToken).ConfigureAwait(false);
if (mainResult != null)
{
result.HasMetadata = true;
result.Item = GetItem(mainResult);
}
}
return result;
}
internal async Task<RootObject> GetMovieDbResult(string tmdbId, string language, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(tmdbId))
{
throw new ArgumentNullException("tmdbId");
}
await EnsureInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, language);
if (!string.IsNullOrEmpty(dataFilePath))
{
return _json.DeserializeFromFile<RootObject>(dataFilePath);
}
return null;
}
private BoxSet GetItem(RootObject obj)
{
var item = new BoxSet
{
Name = obj.name,
Overview = obj.overview
};
item.SetProviderId(MetadataProviders.Tmdb, obj.id.ToString(_usCulture));
return item;
}
private async Task DownloadInfo(string tmdbId, string preferredMetadataLanguage, CancellationToken cancellationToken)
{
var mainResult = await FetchMainResult(tmdbId, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
if (mainResult == null) return;
var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage);
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(dataFilePath));
_json.SerializeToFile(mainResult, dataFilePath);
}
private async Task<RootObject> FetchMainResult(string id, string language, CancellationToken cancellationToken)
{
var url = string.Format(GetCollectionInfo3, id, MovieDbProvider.ApiKey);
if (!string.IsNullOrEmpty(language))
{
url += string.Format("&language={0}", MovieDbProvider.NormalizeLanguage(language));
// Get images in english and with no language
url += "&include_image_language=" + MovieDbProvider.GetImageLanguagesParam(language);
}
cancellationToken.ThrowIfCancellationRequested();
RootObject mainResult = null;
using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
{
Url = url,
CancellationToken = cancellationToken,
AcceptHeader = MovieDbSearch.AcceptHeader
}).ConfigureAwait(false))
{
mainResult = _json.DeserializeFromStream<RootObject>(json);
}
cancellationToken.ThrowIfCancellationRequested();
if (mainResult != null && string.IsNullOrEmpty(mainResult.name))
{
if (!string.IsNullOrEmpty(language) && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
{
url = string.Format(GetCollectionInfo3, id, MovieDbSearch.ApiKey) + "&language=en";
if (!string.IsNullOrEmpty(language))
{
// Get images in english and with no language
url += "&include_image_language=" + MovieDbProvider.GetImageLanguagesParam(language);
}
using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
{
Url = url,
CancellationToken = cancellationToken,
AcceptHeader = MovieDbSearch.AcceptHeader
}).ConfigureAwait(false))
{
mainResult = _json.DeserializeFromStream<RootObject>(json);
}
}
}
return mainResult;
}
private readonly Task _cachedTask = Task.FromResult(true);
internal Task EnsureInfo(string tmdbId, string preferredMetadataLanguage, CancellationToken cancellationToken)
{
var path = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage);
var fileInfo = _fileSystem.GetFileSystemInfo(path);
if (fileInfo.Exists)
{
// If it's recent or automatic updates are enabled, don't re-download
if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
{
return _cachedTask;
}
}
return DownloadInfo(tmdbId, preferredMetadataLanguage, cancellationToken);
}
public string Name
{
get { return "TheMovieDb"; }
}
private static string GetDataFilePath(IApplicationPaths appPaths, string tmdbId, string preferredLanguage)
{
var path = GetDataPath(appPaths, tmdbId);
var filename = string.Format("all-{0}.json", preferredLanguage ?? string.Empty);
return Path.Combine(path, filename);
}
private static string GetDataPath(IApplicationPaths appPaths, string tmdbId)
{
var dataPath = GetCollectionsDataPath(appPaths);
return Path.Combine(dataPath, tmdbId);
}
private static string GetCollectionsDataPath(IApplicationPaths appPaths)
{
var dataPath = Path.Combine(appPaths.CachePath, "tmdb-collections");
return dataPath;
}
internal class Part
{
public string title { get; set; }
public int id { get; set; }
public string release_date { get; set; }
public string poster_path { get; set; }
public string backdrop_path { get; set; }
}
internal class Backdrop
{
public double aspect_ratio { get; set; }
public string file_path { get; set; }
public int height { get; set; }
public string iso_639_1 { get; set; }
public double vote_average { get; set; }
public int vote_count { get; set; }
public int width { get; set; }
}
internal class Poster
{
public double aspect_ratio { get; set; }
public string file_path { get; set; }
public int height { get; set; }
public string iso_639_1 { get; set; }
public double vote_average { get; set; }
public int vote_count { get; set; }
public int width { get; set; }
}
internal class Images
{
public List<Backdrop> backdrops { get; set; }
public List<Poster> posters { get; set; }
}
internal class RootObject
{
public int id { get; set; }
public string name { get; set; }
public string overview { get; set; }
public string poster_path { get; set; }
public string backdrop_path { get; set; }
public List<Part> parts { get; set; }
public Images images { get; set; }
}
public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClient.GetResponse(new HttpRequestOptions
{
CancellationToken = cancellationToken,
Url = url
});
}
}
}
|