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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
|
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Providers.Music;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Extensions;
namespace MediaBrowser.Providers.TV
{
public class FanartSeriesProvider : IRemoteImageProvider, IHasOrder
{
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private readonly IServerConfigurationManager _config;
private readonly IHttpClient _httpClient;
private readonly IFileSystem _fileSystem;
private readonly IJsonSerializer _json;
private const string FanArtBaseUrl = "https://webservice.fanart.tv/v3/tv/{1}?api_key={0}";
// &client_key=52c813aa7b8c8b3bb87f4797532a2f8c
internal static FanartSeriesProvider Current { get; private set; }
public FanartSeriesProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem, IJsonSerializer json)
{
_config = config;
_httpClient = httpClient;
_fileSystem = fileSystem;
_json = json;
Current = this;
}
public string Name
{
get { return ProviderName; }
}
public static string ProviderName
{
get { return "FanArt"; }
}
public bool Supports(BaseItem item)
{
return item is Series;
}
public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
{
return new List<ImageType>
{
ImageType.Primary,
ImageType.Thumb,
ImageType.Art,
ImageType.Logo,
ImageType.Backdrop,
ImageType.Banner
};
}
public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
{
var list = new List<RemoteImageInfo>();
var series = (Series)item;
var id = series.GetProviderId(MetadataProviders.Tvdb);
if (!string.IsNullOrEmpty(id))
{
// Bad id entered
try
{
await EnsureSeriesJson(id, cancellationToken).ConfigureAwait(false);
}
catch (HttpException ex)
{
if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
{
throw;
}
}
var path = GetFanartJsonPath(id);
try
{
AddImages(list, path, cancellationToken);
}
catch (FileNotFoundException)
{
// No biggie. Don't blow up
}
catch (IOException)
{
// No biggie. Don't blow up
}
}
var language = item.GetPreferredMetadataLanguage();
var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
// Sort first by width to prioritize HD versions
return list.OrderByDescending(i => i.Width ?? 0)
.ThenByDescending(i =>
{
if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
{
return 3;
}
if (!isLanguageEn)
{
if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
{
return 2;
}
}
if (string.IsNullOrEmpty(i.Language))
{
return isLanguageEn ? 3 : 2;
}
return 0;
})
.ThenByDescending(i => i.CommunityRating ?? 0)
.ThenByDescending(i => i.VoteCount ?? 0);
}
private void AddImages(List<RemoteImageInfo> list, string path, CancellationToken cancellationToken)
{
var root = _json.DeserializeFromFile<RootObject>(path);
AddImages(list, root, cancellationToken);
}
private void AddImages(List<RemoteImageInfo> list, RootObject obj, CancellationToken cancellationToken)
{
PopulateImages(list, obj.hdtvlogo, ImageType.Logo, 800, 310);
PopulateImages(list, obj.hdclearart, ImageType.Art, 1000, 562);
PopulateImages(list, obj.clearlogo, ImageType.Logo, 400, 155);
PopulateImages(list, obj.clearart, ImageType.Art, 500, 281);
PopulateImages(list, obj.showbackground, ImageType.Backdrop, 1920, 1080, true);
PopulateImages(list, obj.seasonthumb, ImageType.Thumb, 500, 281);
PopulateImages(list, obj.tvthumb, ImageType.Thumb, 500, 281);
PopulateImages(list, obj.tvbanner, ImageType.Banner, 1000, 185);
PopulateImages(list, obj.tvposter, ImageType.Primary, 1000, 1426);
}
private void PopulateImages(List<RemoteImageInfo> list,
List<Image> images,
ImageType type,
int width,
int height,
bool allowSeasonAll = false)
{
if (images == null)
{
return;
}
list.AddRange(images.Select(i =>
{
var url = i.url;
var season = i.season;
var isSeasonValid = string.IsNullOrEmpty(season) ||
(allowSeasonAll && string.Equals(season, "all", StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(url) && isSeasonValid)
{
var likesString = i.likes;
int likes;
var info = new RemoteImageInfo
{
RatingType = RatingType.Likes,
Type = type,
Width = width,
Height = height,
ProviderName = Name,
Url = url.Replace("http://", "https://", StringComparison.OrdinalIgnoreCase),
Language = i.lang
};
if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Integer, _usCulture, out likes))
{
info.CommunityRating = likes;
}
return info;
}
return null;
}).Where(i => i != null));
}
public int Order
{
get { return 1; }
}
public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClient.GetResponse(new HttpRequestOptions
{
CancellationToken = cancellationToken,
Url = url
});
}
/// <summary>
/// Gets the series data path.
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <param name="seriesId">The series id.</param>
/// <returns>System.String.</returns>
internal static string GetSeriesDataPath(IApplicationPaths appPaths, string seriesId)
{
var seriesDataPath = Path.Combine(GetSeriesDataPath(appPaths), seriesId);
return seriesDataPath;
}
/// <summary>
/// Gets the series data path.
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <returns>System.String.</returns>
internal static string GetSeriesDataPath(IApplicationPaths appPaths)
{
var dataPath = Path.Combine(appPaths.CachePath, "fanart-tv");
return dataPath;
}
public string GetFanartJsonPath(string tvdbId)
{
var dataPath = GetSeriesDataPath(_config.ApplicationPaths, tvdbId);
return Path.Combine(dataPath, "fanart.json");
}
private readonly SemaphoreSlim _ensureSemaphore = new SemaphoreSlim(1, 1);
internal async Task EnsureSeriesJson(string tvdbId, CancellationToken cancellationToken)
{
var path = GetFanartJsonPath(tvdbId);
// Only allow one thread in here at a time since every season will be calling this method, possibly concurrently
await _ensureSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var fileInfo = _fileSystem.GetFileSystemInfo(path);
if (fileInfo.Exists)
{
if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
{
return;
}
}
await DownloadSeriesJson(tvdbId, cancellationToken).ConfigureAwait(false);
}
finally
{
_ensureSemaphore.Release();
}
}
public FanartOptions GetFanartOptions()
{
return _config.GetConfiguration<FanartOptions>("fanart");
}
/// <summary>
/// Downloads the series json.
/// </summary>
/// <param name="tvdbId">The TVDB identifier.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
internal async Task DownloadSeriesJson(string tvdbId, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var url = string.Format(FanArtBaseUrl, FanartArtistProvider.ApiKey, tvdbId);
var clientKey = GetFanartOptions().UserApiKey;
if (!string.IsNullOrWhiteSpace(clientKey))
{
url += "&client_key=" + clientKey;
}
var path = GetFanartJsonPath(tvdbId);
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
try
{
using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions
{
Url = url,
CancellationToken = cancellationToken,
BufferContent = true
}, "GET").ConfigureAwait(false))
{
using (var response = httpResponse.Content)
{
using (var fileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
{
await response.CopyToAsync(fileStream).ConfigureAwait(false);
}
}
}
}
catch (HttpException exception)
{
if (exception.StatusCode.HasValue && exception.StatusCode.Value == HttpStatusCode.NotFound)
{
// If the user has automatic updates enabled, save a dummy object to prevent repeated download attempts
_json.SerializeToFile(new RootObject(), path);
return;
}
throw;
}
}
public class Image
{
public string id { get; set; }
public string url { get; set; }
public string lang { get; set; }
public string likes { get; set; }
public string season { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string thetvdb_id { get; set; }
public List<Image> clearlogo { get; set; }
public List<Image> hdtvlogo { get; set; }
public List<Image> clearart { get; set; }
public List<Image> showbackground { get; set; }
public List<Image> tvthumb { get; set; }
public List<Image> seasonposter { get; set; }
public List<Image> seasonthumb { get; set; }
public List<Image> hdclearart { get; set; }
public List<Image> tvbanner { get; set; }
public List<Image> characterart { get; set; }
public List<Image> tvposter { get; set; }
public List<Image> seasonbanner { get; set; }
}
}
public class FanartConfigStore : IConfigurationFactory
{
public IEnumerable<ConfigurationStore> GetConfigurations()
{
return new ConfigurationStore[]
{
new ConfigurationStore
{
Key = "fanart",
ConfigurationType = typeof(FanartOptions)
}
};
}
}
}
|