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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
|
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Resolvers.TV;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Net;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
namespace MediaBrowser.Controller.Providers.TV
{
/// <summary>
/// Class RemoteSeriesProvider
/// </summary>
[Export(typeof(BaseMetadataProvider))]
class RemoteSeriesProvider : BaseMetadataProvider
{
/// <summary>
/// The root URL
/// </summary>
private const string rootUrl = "http://www.thetvdb.com/api/";
/// <summary>
/// The series query
/// </summary>
private const string seriesQuery = "GetSeries.php?seriesname={0}";
/// <summary>
/// The series get
/// </summary>
private const string seriesGet = "http://www.thetvdb.com/api/{0}/series/{1}/{2}.xml";
/// <summary>
/// The get actors
/// </summary>
private const string getActors = "http://www.thetvdb.com/api/{0}/series/{1}/actors.xml";
/// <summary>
/// The LOCA l_ MET a_ FIL e_ NAME
/// </summary>
protected const string LOCAL_META_FILE_NAME = "Series.xml";
/// <summary>
/// Supportses the specified item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
public override bool Supports(BaseItem item)
{
return item is Series;
}
/// <summary>
/// Gets the priority.
/// </summary>
/// <value>The priority.</value>
public override MetadataProviderPriority Priority
{
get { return MetadataProviderPriority.Second; }
}
/// <summary>
/// Gets a value indicating whether [requires internet].
/// </summary>
/// <value><c>true</c> if [requires internet]; otherwise, <c>false</c>.</value>
public override bool RequiresInternet
{
get
{
return true;
}
}
/// <summary>
/// Needses the refresh internal.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="providerInfo">The provider info.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
{
var downloadDate = providerInfo.LastRefreshed;
if (Kernel.Instance.Configuration.MetadataRefreshDays == -1 && downloadDate != DateTime.MinValue)
{
return false;
}
if (item.DontFetchMeta) return false;
return !HasLocalMeta(item) && (Kernel.Instance.Configuration.MetadataRefreshDays != -1 &&
DateTime.UtcNow.Subtract(downloadDate).TotalDays > Kernel.Instance.Configuration.MetadataRefreshDays);
}
/// <summary>
/// Fetches metadata and returns true or false indicating if any work that requires persistence was done
/// </summary>
/// <param name="item">The item.</param>
/// <param name="force">if set to <c>true</c> [force].</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{System.Boolean}.</returns>
protected override async Task<bool> FetchAsyncInternal(BaseItem item, bool force, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var series = (Series)item;
if (!item.DontFetchMeta && !HasLocalMeta(series))
{
var path = item.Path ?? "";
var seriesId = Path.GetFileName(path).GetAttributeValue("tvdbid") ?? await GetSeriesId(series, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
if (!string.IsNullOrEmpty(seriesId))
{
series.SetProviderId(MetadataProviders.Tvdb, seriesId);
if (!HasCompleteMetadata(series))
{
await FetchSeriesData(series, seriesId, cancellationToken).ConfigureAwait(false);
}
}
SetLastRefreshed(item, DateTime.UtcNow);
return true;
}
Logger.Info("Series provider not fetching because local meta exists or requested to ignore: " + item.Name);
return false;
}
/// <summary>
/// Fetches the series data.
/// </summary>
/// <param name="series">The series.</param>
/// <param name="seriesId">The series id.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{System.Boolean}.</returns>
private async Task<bool> FetchSeriesData(Series series, string seriesId, CancellationToken cancellationToken)
{
var success = false;
var name = series.Name;
Logger.Debug("TvDbProvider: Fetching series data: " + name);
if (!string.IsNullOrEmpty(seriesId))
{
string url = string.Format(seriesGet, TVUtils.TVDBApiKey, seriesId, Kernel.Instance.Configuration.PreferredMetadataLanguage);
var doc = new XmlDocument();
try
{
using (var xml = await Kernel.Instance.HttpManager.Get(url, Kernel.Instance.ResourcePools.TvDb, cancellationToken).ConfigureAwait(false))
{
doc.Load(xml);
}
}
catch (HttpException)
{
}
if (doc.HasChildNodes)
{
//kick off the actor and image fetch simultaneously
var actorTask = FetchActors(series, seriesId, doc, cancellationToken);
var imageTask = FetchImages(series, seriesId, cancellationToken);
success = true;
series.Name = doc.SafeGetString("//SeriesName");
series.Overview = doc.SafeGetString("//Overview");
series.CommunityRating = doc.SafeGetSingle("//Rating", 0, 10);
series.AirDays = TVUtils.GetAirDays(doc.SafeGetString("//Airs_DayOfWeek"));
series.AirTime = doc.SafeGetString("//Airs_Time");
string n = doc.SafeGetString("//banner");
if (!string.IsNullOrWhiteSpace(n))
{
series.SetImage(ImageType.Banner, TVUtils.BannerUrl + n);
}
string s = doc.SafeGetString("//Network");
if (!string.IsNullOrWhiteSpace(s))
series.AddStudios(new List<string>(s.Trim().Split('|')));
series.OfficialRating = doc.SafeGetString("//ContentRating");
string g = doc.SafeGetString("//Genre");
if (g != null)
{
string[] genres = g.Trim('|').Split('|');
if (g.Length > 0)
{
series.AddGenres(genres);
}
}
//wait for other tasks
await Task.WhenAll(actorTask, imageTask).ConfigureAwait(false);
if (Kernel.Instance.Configuration.SaveLocalMeta)
{
var ms = new MemoryStream();
doc.Save(ms);
await Kernel.Instance.FileSystemManager.SaveToLibraryFilesystem(series, Path.Combine(series.MetaLocation, LOCAL_META_FILE_NAME), ms, cancellationToken).ConfigureAwait(false);
}
}
}
return success;
}
/// <summary>
/// Fetches the actors.
/// </summary>
/// <param name="series">The series.</param>
/// <param name="seriesId">The series id.</param>
/// <param name="doc">The doc.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
private async Task FetchActors(Series series, string seriesId, XmlDocument doc, CancellationToken cancellationToken)
{
string urlActors = string.Format(getActors, TVUtils.TVDBApiKey, seriesId);
var docActors = new XmlDocument();
try
{
using (var actors = await Kernel.Instance.HttpManager.Get(urlActors, Kernel.Instance.ResourcePools.TvDb, cancellationToken).ConfigureAwait(false))
{
docActors.Load(actors);
}
}
catch (HttpException)
{
}
if (docActors.HasChildNodes)
{
XmlNode actorsNode = null;
if (Kernel.Instance.Configuration.SaveLocalMeta)
{
//add to the main doc for saving
var seriesNode = doc.SelectSingleNode("//Series");
if (seriesNode != null)
{
actorsNode = doc.CreateNode(XmlNodeType.Element, "Persons", null);
seriesNode.AppendChild(actorsNode);
}
}
var xmlNodeList = docActors.SelectNodes("Actors/Actor");
if (xmlNodeList != null)
foreach (XmlNode p in xmlNodeList)
{
string actorName = p.SafeGetString("Name");
string actorRole = p.SafeGetString("Role");
if (!string.IsNullOrWhiteSpace(actorName))
{
series.AddPerson(new PersonInfo { Type = PersonType.Actor, Name = actorName, Role = actorRole });
if (Kernel.Instance.Configuration.SaveLocalMeta && actorsNode != null)
{
//create in main doc
var personNode = doc.CreateNode(XmlNodeType.Element, "Person", null);
foreach (XmlNode subNode in p.ChildNodes)
personNode.AppendChild(doc.ImportNode(subNode, true));
//need to add the type
var typeNode = doc.CreateNode(XmlNodeType.Element, "Type", null);
typeNode.InnerText = "Actor";
personNode.AppendChild(typeNode);
actorsNode.AppendChild(personNode);
}
}
}
}
}
/// <summary>
/// Fetches the images.
/// </summary>
/// <param name="series">The series.</param>
/// <param name="seriesId">The series id.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
private async Task FetchImages(Series series, string seriesId, CancellationToken cancellationToken)
{
if ((!string.IsNullOrEmpty(seriesId)) && ((series.PrimaryImagePath == null) || (series.BackdropImagePaths == null)))
{
string url = string.Format("http://www.thetvdb.com/api/" + TVUtils.TVDBApiKey + "/series/{0}/banners.xml", seriesId);
var images = new XmlDocument();
try
{
using (var imgs = await Kernel.Instance.HttpManager.Get(url, Kernel.Instance.ResourcePools.TvDb, cancellationToken).ConfigureAwait(false))
{
images.Load(imgs);
}
}
catch (HttpException)
{
}
if (images.HasChildNodes)
{
if (Kernel.Instance.Configuration.RefreshItemImages || !series.HasLocalImage("folder"))
{
var n = images.SelectSingleNode("//Banner[BannerType='poster']");
if (n != null)
{
n = n.SelectSingleNode("./BannerPath");
if (n != null)
{
try
{
series.PrimaryImagePath = await Kernel.Instance.ProviderManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + n.InnerText, "folder" + Path.GetExtension(n.InnerText), Kernel.Instance.ResourcePools.TvDb, cancellationToken).ConfigureAwait(false);
}
catch (HttpException)
{
}
catch (IOException)
{
}
}
}
}
if (Kernel.Instance.Configuration.DownloadTVBanner && (Kernel.Instance.Configuration.RefreshItemImages || !series.HasLocalImage("banner")))
{
var n = images.SelectSingleNode("//Banner[BannerType='series']");
if (n != null)
{
n = n.SelectSingleNode("./BannerPath");
if (n != null)
{
try
{
var bannerImagePath = await Kernel.Instance.ProviderManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + n.InnerText, "banner" + Path.GetExtension(n.InnerText), Kernel.Instance.ResourcePools.TvDb, cancellationToken);
series.SetImage(ImageType.Banner, bannerImagePath);
}
catch (HttpException)
{
}
catch (IOException)
{
}
}
}
}
var bdNo = 0;
var xmlNodeList = images.SelectNodes("//Banner[BannerType='fanart']");
if (xmlNodeList != null)
foreach (XmlNode b in xmlNodeList)
{
series.BackdropImagePaths = new List<string>();
var p = b.SelectSingleNode("./BannerPath");
if (p != null)
{
var bdName = "backdrop" + (bdNo > 0 ? bdNo.ToString() : "");
if (Kernel.Instance.Configuration.RefreshItemImages || !series.HasLocalImage(bdName))
{
try
{
series.BackdropImagePaths.Add(await Kernel.Instance.ProviderManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + p.InnerText, bdName + Path.GetExtension(p.InnerText), Kernel.Instance.ResourcePools.TvDb, cancellationToken).ConfigureAwait(false));
}
catch (HttpException)
{
}
catch (IOException)
{
}
}
bdNo++;
if (bdNo >= Kernel.Instance.Configuration.MaxBackdrops) break;
}
}
}
}
}
/// <summary>
/// Determines whether [has complete metadata] [the specified series].
/// </summary>
/// <param name="series">The series.</param>
/// <returns><c>true</c> if [has complete metadata] [the specified series]; otherwise, <c>false</c>.</returns>
private bool HasCompleteMetadata(Series series)
{
return (series.HasImage(ImageType.Banner)) && (series.CommunityRating != null)
&& (series.Overview != null) && (series.Name != null) && (series.People != null)
&& (series.Genres != null) && (series.OfficialRating != null);
}
/// <summary>
/// Determines whether [has local meta] [the specified item].
/// </summary>
/// <param name="item">The item.</param>
/// <returns><c>true</c> if [has local meta] [the specified item]; otherwise, <c>false</c>.</returns>
private bool HasLocalMeta(BaseItem item)
{
//need at least the xml and folder.jpg/png
return item.ResolveArgs.ContainsMetaFileByName(LOCAL_META_FILE_NAME) && (item.ResolveArgs.ContainsMetaFileByName("folder.jpg") ||
item.ResolveArgs.ContainsMetaFileByName("folder.png"));
}
/// <summary>
/// Gets the series id.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{System.String}.</returns>
private async Task<string> GetSeriesId(BaseItem item, CancellationToken cancellationToken)
{
var seriesId = item.GetProviderId(MetadataProviders.Tvdb);
if (string.IsNullOrEmpty(seriesId))
{
seriesId = await FindSeries(item.Name, cancellationToken).ConfigureAwait(false);
}
return seriesId;
}
/// <summary>
/// Finds the series.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{System.String}.</returns>
public async Task<string> FindSeries(string name, CancellationToken cancellationToken)
{
//nope - search for it
string url = string.Format(rootUrl + seriesQuery, WebUtility.UrlEncode(name));
var doc = new XmlDocument();
try
{
using (var results = await Kernel.Instance.HttpManager.Get(url, Kernel.Instance.ResourcePools.TvDb, cancellationToken).ConfigureAwait(false))
{
doc.Load(results);
}
}
catch (HttpException)
{
}
if (doc.HasChildNodes)
{
XmlNodeList nodes = doc.SelectNodes("//Series");
string comparableName = GetComparableName(name);
if (nodes != null)
foreach (XmlNode node in nodes)
{
var n = node.SelectSingleNode("./SeriesName");
if (n != null && GetComparableName(n.InnerText) == comparableName)
{
n = node.SelectSingleNode("./seriesid");
if (n != null)
return n.InnerText;
}
else
{
if (n != null)
Logger.Info("TVDb Provider - " + n.InnerText + " did not match " + comparableName);
}
}
}
Logger.Info("TVDb Provider - Could not find " + name + ". Check name on Thetvdb.org.");
return null;
}
/// <summary>
/// The remove
/// </summary>
const string remove = "\"'!`?";
/// <summary>
/// The spacers
/// </summary>
const string spacers = "/,.:;\\(){}[]+-_=–*"; // (there are not actually two - in the they are different char codes)
/// <summary>
/// Gets the name of the comparable.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>System.String.</returns>
internal static string GetComparableName(string name)
{
name = name.ToLower();
name = name.Normalize(NormalizationForm.FormKD);
var sb = new StringBuilder();
foreach (var c in name)
{
if ((int)c >= 0x2B0 && (int)c <= 0x0333)
{
// skip char modifier and diacritics
}
else if (remove.IndexOf(c) > -1)
{
// skip chars we are removing
}
else if (spacers.IndexOf(c) > -1)
{
sb.Append(" ");
}
else if (c == '&')
{
sb.Append(" and ");
}
else
{
sb.Append(c);
}
}
name = sb.ToString();
name = name.Replace(", the", "");
name = name.Replace("the ", " ");
name = name.Replace(" the ", " ");
string prevName;
do
{
prevName = name;
name = name.Replace(" ", " ");
} while (name.Length != prevName.Length);
return name.Trim();
}
}
}
|