jellyfin-server/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs

1225 lines
50 KiB
C#
Raw Normal View History

using System;
2013-09-15 19:33:23 +00:00
using System.Collections.Generic;
using System.Globalization;
2013-02-21 01:33:05 +00:00
using System.IO;
using System.Linq;
2013-02-21 01:33:05 +00:00
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
2016-10-27 07:58:33 +00:00
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
2016-10-27 07:58:33 +00:00
using MediaBrowser.Model.Xml;
using Microsoft.Extensions.Logging;
2019-01-29 22:09:48 +00:00
using TvDbSharper;
using TvDbSharper.Dto;
using Series = MediaBrowser.Controller.Entities.TV.Series;
2013-02-21 01:33:05 +00:00
namespace MediaBrowser.Providers.TV.TheTVDB
2013-02-21 01:33:05 +00:00
{
2016-05-26 17:18:58 +00:00
public class TvdbSeriesProvider : IRemoteMetadataProvider<Series, SeriesInfo>, IHasOrder
2013-02-21 01:33:05 +00:00
{
internal static TvdbSeriesProvider Current { get; private set; }
private readonly IZipClient _zipClient;
2014-02-03 20:51:28 +00:00
private readonly IHttpClient _httpClient;
private readonly IFileSystem _fileSystem;
private readonly IXmlReaderSettingsFactory _xmlSettings;
2014-02-03 20:51:28 +00:00
private readonly IServerConfigurationManager _config;
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private readonly ILogger _logger;
2014-11-16 22:46:01 +00:00
private readonly ILibraryManager _libraryManager;
2016-10-27 07:58:33 +00:00
private readonly ILocalizationManager _localizationManager;
2019-01-29 22:09:48 +00:00
private readonly TvDbClient _tvDbClient;
2018-09-12 17:26:21 +00:00
public TvdbSeriesProvider(IZipClient zipClient, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager config, ILogger logger, ILibraryManager libraryManager, IXmlReaderSettingsFactory xmlSettings, ILocalizationManager localizationManager)
2013-02-25 00:13:45 +00:00
{
_zipClient = zipClient;
2014-02-03 20:51:28 +00:00
_httpClient = httpClient;
_fileSystem = fileSystem;
2014-02-03 20:51:28 +00:00
_config = config;
_logger = logger;
2014-11-16 22:46:01 +00:00
_libraryManager = libraryManager;
2016-10-27 07:58:33 +00:00
_xmlSettings = xmlSettings;
_localizationManager = localizationManager;
2013-03-04 05:43:06 +00:00
Current = this;
2019-01-29 22:09:48 +00:00
_tvDbClient = new TvDbClient();
2013-03-04 05:43:06 +00:00
}
2016-01-25 04:12:47 +00:00
private string NormalizeLanguage(string language)
{
if (string.IsNullOrWhiteSpace(language))
{
return language;
}
// pt-br is just pt to tvdb
2019-01-27 11:03:43 +00:00
return language.Split('-')[0].ToLowerInvariant();
2016-01-25 04:12:47 +00:00
}
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken)
{
2015-10-21 05:09:50 +00:00
if (IsValidSeries(searchInfo.ProviderIds))
2014-03-02 15:42:21 +00:00
{
2015-10-21 05:09:50 +00:00
var metadata = await GetMetadata(searchInfo, cancellationToken).ConfigureAwait(false);
2014-08-19 01:42:53 +00:00
2015-10-21 05:09:50 +00:00
if (metadata.HasMetadata)
2014-08-19 01:42:53 +00:00
{
2015-10-21 05:09:50 +00:00
return new List<RemoteSearchResult>
{
new RemoteSearchResult
{
Name = metadata.Item.Name,
PremiereDate = metadata.Item.PremiereDate,
ProductionYear = metadata.Item.ProductionYear,
ProviderIds = metadata.Item.ProviderIds,
SearchProviderName = Name
}
};
}
2014-08-19 01:42:53 +00:00
}
2015-10-21 05:09:50 +00:00
return await FindSeries(searchInfo.Name, searchInfo.Year, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
}
2014-02-07 03:10:13 +00:00
public async Task<MetadataResult<Series>> GetMetadata(SeriesInfo itemId, CancellationToken cancellationToken)
2013-02-21 01:33:05 +00:00
{
2014-02-03 20:51:28 +00:00
var result = new MetadataResult<Series>();
result.QueriedById = true;
2015-10-21 05:09:50 +00:00
if (!IsValidSeries(itemId.ProviderIds))
2013-02-21 01:33:05 +00:00
{
result.QueriedById = false;
2015-09-19 21:25:19 +00:00
await Identify(itemId).ConfigureAwait(false);
}
2015-10-21 05:09:50 +00:00
cancellationToken.ThrowIfCancellationRequested();
2015-10-21 05:09:50 +00:00
if (IsValidSeries(itemId.ProviderIds))
{
2018-09-12 17:26:21 +00:00
var seriesDataPath = await EnsureSeriesInfo(itemId.ProviderIds, itemId.Name, itemId.Year, itemId.MetadataLanguage, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrEmpty(seriesDataPath))
{
return result;
}
2014-02-03 20:51:28 +00:00
result.Item = new Series();
result.HasMetadata = true;
FetchSeriesData(result, itemId.MetadataLanguage, itemId.ProviderIds, cancellationToken);
2013-02-21 01:33:05 +00:00
}
2014-02-03 20:51:28 +00:00
return result;
2013-02-21 01:33:05 +00:00
}
/// <summary>
/// Fetches the series data.
/// </summary>
2015-06-29 01:10:45 +00:00
/// <param name="result">The result.</param>
/// <param name="metadataLanguage">The metadata language.</param>
2015-11-29 20:01:14 +00:00
/// <param name="seriesProviderIds">The series provider ids.</param>
2013-02-21 01:33:05 +00:00
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{System.Boolean}.</returns>
private void FetchSeriesData(MetadataResult<Series> result, string metadataLanguage, Dictionary<string, string> seriesProviderIds, CancellationToken cancellationToken)
2013-02-21 01:33:05 +00:00
{
2019-01-29 22:09:48 +00:00
_tvDbClient.AcceptedLanguage = NormalizeLanguage(metadataLanguage);
2015-06-29 01:10:45 +00:00
var series = result.Item;
2019-01-29 22:09:48 +00:00
TvDbResponse<SeriesSearchResult[]> searchResult;
2015-06-29 01:10:45 +00:00
2019-01-29 22:09:48 +00:00
if (seriesProviderIds.TryGetValue(MetadataProviders.Tvdb.ToString(), out var tvdbId) && !string.IsNullOrEmpty(id))
2015-11-29 20:01:14 +00:00
{
2019-01-29 22:09:48 +00:00
series.SetProviderId(MetadataProviders.Tvdb, tvdbId);
2015-11-29 20:01:14 +00:00
}
2013-10-04 15:22:03 +00:00
2019-01-29 22:09:48 +00:00
if (seriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out var imdbId) && !string.IsNullOrEmpty(id))
2015-11-29 20:01:14 +00:00
{
2019-01-29 22:09:48 +00:00
series.SetProviderId(MetadataProviders.Imdb, imdbId);
tvdbId = GetSeriesByRemoteId(imdbId, MetadataProviders.Imdb.ToString(), metadataLanguage, cancellationToken).Result.ToString();
2015-11-29 20:01:14 +00:00
}
2019-01-29 22:09:48 +00:00
if (seriesProviderIds.TryGetValue(MetadataProviders.Zap2It.ToString(), out var zap2It) && !string.IsNullOrEmpty(id))
2018-09-12 17:26:21 +00:00
{
2019-01-29 22:09:48 +00:00
series.SetProviderId(MetadataProviders.Zap2It, zap2It);
tvdbId = GetSeriesByRemoteId(zap2It, MetadataProviders.Zap2It.ToString(), metadataLanguage, cancellationToken).Result.ToString();
2018-09-12 17:26:21 +00:00
}
2019-01-29 22:09:48 +00:00
var seriesResult = _tvDbClient.Series.GetAsync(Convert.ToInt32(tvdbId), cancellationToken).Result;
// var seriesDataPath = GetSeriesDataPath(_config.ApplicationPaths, seriesProviderIds);
//
// var seriesXmlPath = GetSeriesXmlPath(seriesProviderIds, metadataLanguage);
// var actorsXmlPath = Path.Combine(seriesDataPath, "actors.xml");
2019-01-29 22:09:48 +00:00
FetchSeriesInfo(result, searchResult, cancellationToken);
2013-09-16 17:52:14 +00:00
2014-02-03 20:51:28 +00:00
cancellationToken.ThrowIfCancellationRequested();
2013-10-16 01:44:23 +00:00
2015-07-24 02:48:10 +00:00
result.ResetPeople();
2015-10-21 05:09:50 +00:00
2015-06-29 01:10:45 +00:00
FetchActors(result, actorsXmlPath);
}
/// <summary>
/// Downloads the series zip.
/// </summary>
2017-03-12 19:27:45 +00:00
internal async Task DownloadSeriesZip(string seriesId, string idType, string seriesName, int? seriesYear, string seriesDataPath, long? lastTvDbUpdateTime, string preferredMetadataLanguage, CancellationToken cancellationToken)
2015-04-16 14:59:39 +00:00
{
try
{
2017-03-12 19:27:45 +00:00
await DownloadSeriesZip(seriesId, idType, seriesName, seriesYear, seriesDataPath, lastTvDbUpdateTime, preferredMetadataLanguage, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
2015-04-16 14:59:39 +00:00
return;
}
catch (HttpException ex)
{
if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
{
throw;
}
}
if (!string.Equals(preferredMetadataLanguage, "en", StringComparison.OrdinalIgnoreCase))
{
2017-03-12 19:27:45 +00:00
await DownloadSeriesZip(seriesId, idType, seriesName, seriesYear, seriesDataPath, lastTvDbUpdateTime, "en", preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
2015-04-16 14:59:39 +00:00
}
}
2017-03-12 19:27:45 +00:00
private async Task DownloadSeriesZip(string seriesId, string idType, string seriesName, int? seriesYear, string seriesDataPath, long? lastTvDbUpdateTime, string preferredMetadataLanguage, string saveAsMetadataLanguage, CancellationToken cancellationToken)
{
2015-11-29 20:01:14 +00:00
if (string.IsNullOrWhiteSpace(seriesId))
{
throw new ArgumentNullException(nameof(seriesId));
2015-11-29 20:01:14 +00:00
}
2015-12-18 16:43:42 +00:00
if (!string.Equals(idType, "tvdb", StringComparison.OrdinalIgnoreCase))
{
2019-01-29 22:09:48 +00:00
seriesId = (await GetSeriesByRemoteId(seriesId, idType, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false)).ToString();
2015-12-18 16:43:42 +00:00
}
2017-03-12 19:27:45 +00:00
// If searching by remote id came up empty, then do a regular search
if (string.IsNullOrWhiteSpace(seriesId) && !string.IsNullOrWhiteSpace(seriesName))
{
var searchInfo = new SeriesInfo
{
Name = seriesName,
Year = seriesYear,
MetadataLanguage = preferredMetadataLanguage
};
var results = await GetSearchResults(searchInfo, cancellationToken).ConfigureAwait(false);
var result = results.FirstOrDefault();
if (result != null)
{
seriesId = result.GetProviderId(MetadataProviders.Tvdb);
}
}
2016-01-16 19:02:25 +00:00
if (string.IsNullOrWhiteSpace(seriesId))
{
throw new ArgumentNullException(nameof(seriesId));
2016-01-16 19:02:25 +00:00
}
2016-01-26 19:06:02 +00:00
var url = string.Format(SeriesGetZip, TVUtils.TvdbApiKey, seriesId, NormalizeLanguage(preferredMetadataLanguage));
2017-10-20 16:16:56 +00:00
using (var response = await _httpClient.SendAsync(new HttpRequestOptions
{
Url = url,
2017-01-05 18:09:12 +00:00
CancellationToken = cancellationToken,
BufferContent = false
2013-02-21 01:33:05 +00:00
2017-10-20 16:16:56 +00:00
}, "GET").ConfigureAwait(false))
{
2017-10-20 16:16:56 +00:00
using (var zipStream = response.Content)
{
2017-10-20 16:16:56 +00:00
// Delete existing files
DeleteXmlFiles(seriesDataPath);
// Copy to memory stream because we need a seekable stream
2018-09-12 17:26:21 +00:00
using (var ms = new MemoryStream())
2017-10-20 16:16:56 +00:00
{
await zipStream.CopyToAsync(ms).ConfigureAwait(false);
2013-02-21 01:33:05 +00:00
2017-10-20 16:16:56 +00:00
ms.Position = 0;
_zipClient.ExtractAllFromZip(ms, seriesDataPath, true);
}
}
}
2013-10-10 16:55:07 +00:00
// Sanitize all files, except for extracted episode files
2016-10-27 07:58:33 +00:00
foreach (var file in _fileSystem.GetFilePaths(seriesDataPath, true).ToList()
.Where(i => string.Equals(Path.GetExtension(i), ".xml", StringComparison.OrdinalIgnoreCase))
.Where(i => !Path.GetFileName(i).StartsWith("episode-", StringComparison.OrdinalIgnoreCase)))
2013-10-10 16:55:07 +00:00
{
await SanitizeXmlFile(file).ConfigureAwait(false);
}
2016-01-26 19:06:02 +00:00
var downloadLangaugeXmlFile = Path.Combine(seriesDataPath, NormalizeLanguage(preferredMetadataLanguage) + ".xml");
2015-04-19 03:35:17 +00:00
var saveAsLanguageXmlFile = Path.Combine(seriesDataPath, saveAsMetadataLanguage + ".xml");
if (!string.Equals(downloadLangaugeXmlFile, saveAsLanguageXmlFile, StringComparison.OrdinalIgnoreCase))
{
2019-01-26 21:31:59 +00:00
File.Copy(downloadLangaugeXmlFile, saveAsLanguageXmlFile, true);
2015-04-19 03:35:17 +00:00
}
await ExtractEpisodes(seriesDataPath, downloadLangaugeXmlFile, lastTvDbUpdateTime).ConfigureAwait(false);
2013-10-10 16:55:07 +00:00
}
2019-01-29 22:09:48 +00:00
private async Task<int> GetSeriesByRemoteId(string id, string idType, string language, CancellationToken cancellationToken)
2015-12-18 16:43:42 +00:00
{
2019-01-29 22:09:48 +00:00
_tvDbClient.AcceptedLanguage = NormalizeLanguage(language);
TvDbResponse<SeriesSearchResult[]> result;
2018-09-12 17:26:21 +00:00
if (string.Equals(idType, MetadataProviders.Zap2It.ToString(), StringComparison.OrdinalIgnoreCase))
{
2019-01-29 22:09:48 +00:00
result = await _tvDbClient.Search.SearchSeriesByZap2ItIdAsync(id, cancellationToken);
2018-09-12 17:26:21 +00:00
}
else
{
2019-01-29 22:09:48 +00:00
result = await _tvDbClient.Search.SearchSeriesByImdbIdAsync(id, cancellationToken);
2016-10-27 07:58:33 +00:00
}
2019-01-29 22:09:48 +00:00
return result.Data.First().Id;
2015-12-18 16:43:42 +00:00
}
2015-10-21 05:09:50 +00:00
internal static bool IsValidSeries(Dictionary<string, string> seriesProviderIds)
2014-02-03 05:35:43 +00:00
{
2019-01-29 22:09:48 +00:00
return seriesProviderIds.TryGetValue(MetadataProviders.Tvdb.ToString(), out _) ||
seriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out _) ||
seriesProviderIds.TryGetValue(MetadataProviders.Zap2It.ToString(), out _);
2015-10-21 05:09:50 +00:00
}
2019-01-29 22:09:48 +00:00
// TODO caching
2015-10-21 05:09:50 +00:00
private bool IsCacheValid(string seriesDataPath, string preferredMetadataLanguage)
{
try
{
2017-03-29 06:26:48 +00:00
var files = _fileSystem.GetFiles(seriesDataPath, new[] { ".xml" }, true, false)
2015-10-21 05:09:50 +00:00
.ToList();
2015-10-21 05:09:50 +00:00
var seriesXmlFilename = preferredMetadataLanguage + ".xml";
2017-08-26 07:03:33 +00:00
const int cacheHours = 12;
2015-10-21 05:09:50 +00:00
var seriesFile = files.FirstOrDefault(i => string.Equals(seriesXmlFilename, i.Name, StringComparison.OrdinalIgnoreCase));
// No need to check age if automatic updates are enabled
2017-08-26 07:03:33 +00:00
if (seriesFile == null || !seriesFile.Exists || (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(seriesFile)).TotalHours > cacheHours)
2015-10-21 05:09:50 +00:00
{
return false;
}
2015-10-21 05:09:50 +00:00
var actorsXml = files.FirstOrDefault(i => string.Equals("actors.xml", i.Name, StringComparison.OrdinalIgnoreCase));
// No need to check age if automatic updates are enabled
2017-08-26 07:03:33 +00:00
if (actorsXml == null || !actorsXml.Exists || (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(actorsXml)).TotalHours > cacheHours)
2015-10-21 05:09:50 +00:00
{
return false;
}
var bannersXml = files.FirstOrDefault(i => string.Equals("banners.xml", i.Name, StringComparison.OrdinalIgnoreCase));
// No need to check age if automatic updates are enabled
2017-08-26 07:03:33 +00:00
if (bannersXml == null || !bannersXml.Exists || (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(bannersXml)).TotalHours > cacheHours)
2015-10-21 05:09:50 +00:00
{
return false;
}
return true;
}
2016-10-27 07:58:33 +00:00
catch (FileNotFoundException)
{
2015-10-21 05:09:50 +00:00
return false;
}
2016-10-27 07:58:33 +00:00
catch (IOException)
2014-02-03 05:35:43 +00:00
{
2015-10-21 05:09:50 +00:00
return false;
2014-02-03 05:35:43 +00:00
}
}
2014-02-03 20:51:28 +00:00
/// <summary>
/// Finds the series.
/// </summary>
/// <param name="name">The name.</param>
2015-10-21 05:09:50 +00:00
/// <param name="year">The year.</param>
2015-02-20 18:27:01 +00:00
/// <param name="language">The language.</param>
2014-02-03 20:51:28 +00:00
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{System.String}.</returns>
2015-10-21 05:09:50 +00:00
private async Task<IEnumerable<RemoteSearchResult>> FindSeries(string name, int? year, string language, CancellationToken cancellationToken)
2014-08-19 01:42:53 +00:00
{
2019-01-29 22:09:48 +00:00
var results = await FindSeriesInternal(name, language, cancellationToken).ConfigureAwait(false);
2014-08-19 01:42:53 +00:00
if (results.Count == 0)
{
2014-11-16 22:46:01 +00:00
var parsedName = _libraryManager.ParseName(name);
var nameWithoutYear = parsedName.Name;
2014-08-19 01:42:53 +00:00
2015-02-20 18:27:01 +00:00
if (!string.IsNullOrWhiteSpace(nameWithoutYear) && !string.Equals(nameWithoutYear, name, StringComparison.OrdinalIgnoreCase))
2014-08-19 01:42:53 +00:00
{
2019-01-29 22:09:48 +00:00
results = await FindSeriesInternal(nameWithoutYear, language, cancellationToken).ConfigureAwait(false);
2014-08-19 01:42:53 +00:00
}
}
2015-10-21 05:09:50 +00:00
return results.Where(i =>
{
if (year.HasValue && i.ProductionYear.HasValue)
{
// Allow one year tolerance
return Math.Abs(year.Value - i.ProductionYear.Value) <= 1;
}
return true;
});
2014-08-19 01:42:53 +00:00
}
private async Task<List<RemoteSearchResult>> FindSeriesInternal(string name, string language, CancellationToken cancellationToken)
2013-10-24 17:49:24 +00:00
{
2019-01-29 22:09:48 +00:00
_tvDbClient.AcceptedLanguage = NormalizeLanguage(language);
var comparableName = GetComparableName(name);
2018-09-12 17:26:21 +00:00
var list = new List<Tuple<List<string>, RemoteSearchResult>>();
2019-01-29 22:09:48 +00:00
TvDbResponse<SeriesSearchResult[]> result = await _tvDbClient.Search.SearchSeriesByNameAsync(comparableName, cancellationToken);
2018-09-12 17:26:21 +00:00
2019-01-29 22:09:48 +00:00
foreach (var seriesSearchResult in result.Data)
2013-10-24 17:49:24 +00:00
{
2019-01-29 22:09:48 +00:00
var tvdbTitles = new List<string>
2017-10-20 16:16:56 +00:00
{
2019-01-29 22:09:48 +00:00
GetComparableName(seriesSearchResult.SeriesName)
};
tvdbTitles.AddRange(seriesSearchResult.Aliases.Select(GetComparableName));
2017-10-20 16:16:56 +00:00
2019-01-29 22:09:48 +00:00
DateTime.TryParse(seriesSearchResult.FirstAired, out var firstAired);
var remoteSearchResult = new RemoteSearchResult
{
Name = tvdbTitles.FirstOrDefault(),
ProductionYear = firstAired.Year,
SearchProviderName = Name,
ImageUrl = seriesSearchResult.Banner
2013-10-10 16:55:07 +00:00
2019-01-29 22:09:48 +00:00
};
// TODO requires another query
// remoteSearchResult.SetProviderId(MetadataProviders.Imdb, seriesSearchResult.Id);
remoteSearchResult.SetProviderId(MetadataProviders.Tvdb, seriesSearchResult.Id.ToString());
list.Add(new Tuple<List<string>, RemoteSearchResult>(tvdbTitles, remoteSearchResult));
}
2014-02-03 20:51:28 +00:00
2018-09-12 17:26:21 +00:00
return list
.OrderBy(i => i.Item1.Contains(comparableName, StringComparer.OrdinalIgnoreCase) ? 0 : 1)
.ThenBy(i => list.IndexOf(i))
.Select(i => i.Item2)
.ToList();
}
2013-10-10 16:55:07 +00:00
/// <summary>
2014-02-03 20:51:28 +00:00
/// The remove
2013-10-10 16:55:07 +00:00
/// </summary>
2014-02-03 20:51:28 +00:00
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>
2013-10-10 16:55:07 +00:00
/// <returns>System.String.</returns>
2016-10-27 07:58:33 +00:00
private string GetComparableName(string name)
2013-10-10 16:55:07 +00:00
{
2019-01-27 11:03:43 +00:00
name = name.ToLowerInvariant();
2016-10-27 07:58:33 +00:00
name = _localizationManager.NormalizeFormKD(name);
2014-02-03 20:51:28 +00:00
var sb = new StringBuilder();
foreach (var c in name)
2013-10-10 16:55:07 +00:00
{
2014-02-03 20:51:28 +00:00
if ((int)c >= 0x2B0 && (int)c <= 0x0333)
2013-10-10 16:55:07 +00:00
{
2019-01-07 23:27:46 +00:00
// skip char modifier and diacritics
2014-02-03 20:51:28 +00:00
}
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);
2013-10-10 16:55:07 +00:00
}
}
2014-02-03 20:51:28 +00:00
name = sb.ToString();
name = name.Replace(", the", "");
name = name.Replace("the ", " ");
name = name.Replace(" the ", " ");
2014-02-03 20:51:28 +00:00
string prevName;
do
{
2014-02-03 20:51:28 +00:00
prevName = name;
name = name.Replace(" ", " ");
} while (name.Length != prevName.Length);
2014-02-03 20:51:28 +00:00
return name.Trim();
}
2019-01-29 22:09:48 +00:00
private void FetchSeriesInfo(MetadataResult<Series> result, TvDbResponse<TvDbSharper.Dto.Series> seriesResponse, CancellationToken cancellationToken)
{
2019-01-29 22:09:48 +00:00
var episodeAirDates = new List<DateTime>();
var series = result.Item;
Series item = result.Item;
series.SetProviderId(MetadataProviders.Tvdb, seriesResponse.Data.Id.ToString());
series.Name = seriesResponse.Data.SeriesName;
series.Overview = (seriesResponse.Data.Overview ?? string.Empty).Trim();
// TODO result.ResultLanguage = (seriesResponse.Data. ?? string.Empty).Trim();
series.AirDays = TVUtils.GetAirDays(seriesResponse.Data.AirsDayOfWeek);
series.AirTime = seriesResponse.Data.AirsTime;
2019-01-29 22:09:48 +00:00
series.CommunityRating = (float?)seriesResponse.Data.SiteRating;
series.SetProviderId(MetadataProviders.Imdb, seriesResponse.Data.ImdbId);
series.SetProviderId(MetadataProviders.Zap2It, seriesResponse.Data.Zap2itId);
if (Enum.TryParse(seriesResponse.Data.Status, true, out SeriesStatus seriesStatus))
{
series.Status = seriesStatus;
}
2019-01-29 22:09:48 +00:00
if (DateTime.TryParse(seriesResponse.Data.FirstAired, out var date))
{
2019-01-29 22:09:48 +00:00
date = date.ToUniversalTime();
2014-02-03 20:51:28 +00:00
2019-01-29 22:09:48 +00:00
series.PremiereDate = date;
series.ProductionYear = date.Year;
}
2016-10-27 07:58:33 +00:00
2019-01-29 22:09:48 +00:00
series.RunTimeTicks = TimeSpan.FromMinutes(Convert.ToDouble(seriesResponse.Data.Runtime)).Ticks;
2016-10-27 07:58:33 +00:00
2019-01-29 22:09:48 +00:00
if (!string.IsNullOrWhiteSpace(val))
{
var vals = val
.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
.Select(i => i.Trim())
.Where(i => !string.IsNullOrWhiteSpace(i))
.ToList();
2019-01-29 22:09:48 +00:00
if (vals.Count > 0)
{
item.Genres = Array.Empty<string>();
foreach (var genre in vals)
{
item.AddGenre(genre);
}
}
}
2019-01-29 22:09:48 +00:00
var val = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(val))
{
2019-01-29 22:09:48 +00:00
var vals = val
.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
.Select(i => i.Trim())
.Where(i => !string.IsNullOrWhiteSpace(i))
.ToList();
if (vals.Count > 0)
{
item.SetStudios(vals);
}
}
// using (var fileStream = _fileSystem.GetFileStream(seriesXmlPath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
// {
// using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
// {
// // Use XmlReader for best performance
// using (var reader = XmlReader.Create(streamReader, settings))
// {
// reader.MoveToContent();
// reader.Read();
//
// // Loop through each element
// while (!reader.EOF && reader.ReadState == ReadState.Interactive)
// {
// cancellationToken.ThrowIfCancellationRequested();
//
// if (reader.NodeType == XmlNodeType.Element)
// {
// switch (reader.Name)
// {
// case "Series":
// {
// if (reader.IsEmptyElement)
// {
// reader.Read();
// continue;
// }
// using (var subtree = reader.ReadSubtree())
// {
// FetchDataFromSeriesNode(result, subtree, cancellationToken);
// }
// break;
// }
//
// case "Episode":
// {
// if (reader.IsEmptyElement)
// {
// reader.Read();
// continue;
// }
// using (var subtree = reader.ReadSubtree())
// {
// var date = GetFirstAiredDateFromEpisodeNode(subtree, cancellationToken);
//
// if (date.HasValue)
// {
// episiodeAirDates.Add(date.Value);
// }
// }
// break;
// }
//
// default:
// reader.Skip();
// break;
// }
// }
// else
// {
// reader.Read();
// }
// }
// }
// }
// }
if (result.Item.Status.HasValue && result.Item.Status.Value == SeriesStatus.Ended && episodeAirDates.Count > 0)
{
result.Item.EndDate = episodeAirDates.Max();
}
2014-02-03 20:51:28 +00:00
}
2014-02-03 20:51:28 +00:00
private DateTime? GetFirstAiredDateFromEpisodeNode(XmlReader reader, CancellationToken cancellationToken)
{
DateTime? airDate = null;
int? seasonNumber = null;
2014-02-03 20:51:28 +00:00
reader.MoveToContent();
2016-12-02 20:10:35 +00:00
reader.Read();
2014-02-03 20:51:28 +00:00
// Loop through each element
2016-12-03 21:46:06 +00:00
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
2014-02-03 20:51:28 +00:00
cancellationToken.ThrowIfCancellationRequested();
2014-02-03 20:51:28 +00:00
if (reader.NodeType == XmlNodeType.Element)
{
2014-02-03 20:51:28 +00:00
switch (reader.Name)
{
2014-02-03 20:51:28 +00:00
case "FirstAired":
{
var val = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(val))
{
if (DateTime.TryParse(val, out var date))
2014-02-03 20:51:28 +00:00
{
airDate = date.ToUniversalTime();
}
}
break;
}
case "SeasonNumber":
{
var val = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(val))
{
// int.TryParse is local aware, so it can be probamatic, force us culture
if (int.TryParse(val, NumberStyles.Integer, _usCulture, out var rval))
2014-02-03 20:51:28 +00:00
{
seasonNumber = rval;
}
}
break;
}
default:
reader.Skip();
break;
}
}
2016-12-02 20:10:35 +00:00
else
{
reader.Read();
}
}
2014-02-03 20:51:28 +00:00
if (seasonNumber.HasValue && seasonNumber.Value != 0)
{
return airDate;
}
2014-02-03 20:51:28 +00:00
return null;
}
2013-02-21 01:33:05 +00:00
/// <summary>
2014-02-03 20:51:28 +00:00
/// Fetches the actors.
/// </summary>
2015-06-29 01:10:45 +00:00
/// <param name="result">The result.</param>
2014-02-03 20:51:28 +00:00
/// <param name="actorsXmlPath">The actors XML path.</param>
2015-06-29 01:10:45 +00:00
private void FetchActors(MetadataResult<Series> result, string actorsXmlPath)
2013-02-21 01:33:05 +00:00
{
2016-10-27 07:58:33 +00:00
var settings = _xmlSettings.Create(false);
settings.CheckCharacters = false;
settings.IgnoreProcessingInstructions = true;
settings.IgnoreComments = true;
2016-10-27 07:58:33 +00:00
using (var fileStream = _fileSystem.GetFileStream(actorsXmlPath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
{
2016-10-27 07:58:33 +00:00
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
2016-10-27 07:58:33 +00:00
// Use XmlReader for best performance
using (var reader = XmlReader.Create(streamReader, settings))
{
2016-10-27 07:58:33 +00:00
reader.MoveToContent();
2016-12-02 20:10:35 +00:00
reader.Read();
2016-10-27 07:58:33 +00:00
// Loop through each element
2016-12-03 21:46:06 +00:00
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
2016-10-27 07:58:33 +00:00
if (reader.NodeType == XmlNodeType.Element)
{
2016-10-27 07:58:33 +00:00
switch (reader.Name)
{
case "Actor":
{
2016-12-03 23:57:34 +00:00
if (reader.IsEmptyElement)
{
reader.Read();
continue;
}
2016-10-27 07:58:33 +00:00
using (var subtree = reader.ReadSubtree())
{
FetchDataFromActorNode(result, subtree);
}
break;
}
2016-10-27 07:58:33 +00:00
default:
reader.Skip();
break;
2016-10-27 07:58:33 +00:00
}
}
2016-12-02 20:10:35 +00:00
else
{
reader.Read();
}
}
}
}
}
}
2013-02-21 01:33:05 +00:00
2014-02-03 20:51:28 +00:00
/// <summary>
/// Fetches the data from actor node.
/// </summary>
2015-06-29 01:10:45 +00:00
/// <param name="result">The result.</param>
2014-02-03 20:51:28 +00:00
/// <param name="reader">The reader.</param>
2015-06-29 01:10:45 +00:00
private void FetchDataFromActorNode(MetadataResult<Series> result, XmlReader reader)
{
reader.MoveToContent();
2014-02-03 20:51:28 +00:00
var personInfo = new PersonInfo();
2016-12-02 20:10:35 +00:00
reader.MoveToContent();
reader.Read();
// Loop through each element
2016-12-03 21:46:06 +00:00
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
2013-02-21 01:33:05 +00:00
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
2014-02-03 20:51:28 +00:00
case "Name":
{
2014-02-03 20:51:28 +00:00
personInfo.Name = (reader.ReadElementContentAsString() ?? string.Empty).Trim();
break;
}
2014-02-03 20:51:28 +00:00
case "Role":
{
personInfo.Role = (reader.ReadElementContentAsString() ?? string.Empty).Trim();
break;
2016-01-21 18:50:43 +00:00
}
case "id":
{
2016-12-02 20:10:35 +00:00
reader.Skip();
2016-01-21 18:50:43 +00:00
break;
}
case "Image":
{
var url = (reader.ReadElementContentAsString() ?? string.Empty).Trim();
if (!string.IsNullOrWhiteSpace(url))
{
personInfo.ImageUrl = TVUtils.BannerUrl + url;
}
break;
2014-02-03 20:51:28 +00:00
}
case "SortOrder":
{
2014-02-03 20:51:28 +00:00
var val = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(val))
{
2014-02-03 20:51:28 +00:00
// int.TryParse is local aware, so it can be probamatic, force us culture
if (int.TryParse(val, NumberStyles.Integer, _usCulture, out var rval))
2014-02-03 20:51:28 +00:00
{
personInfo.SortOrder = rval;
}
}
break;
}
2014-02-03 20:51:28 +00:00
default:
reader.Skip();
break;
}
}
2016-12-02 20:10:35 +00:00
else
{
reader.Read();
}
2014-02-03 20:51:28 +00:00
}
personInfo.Type = PersonType.Actor;
2015-02-20 18:27:01 +00:00
if (!string.IsNullOrWhiteSpace(personInfo.Name))
2014-02-03 20:51:28 +00:00
{
2015-07-24 02:48:10 +00:00
result.AddPerson(personInfo);
2014-02-03 20:51:28 +00:00
}
}
2019-01-29 22:09:48 +00:00
private void FetchDataFromSeriesNode(MetadataResult<Series> result, CancellationToken cancellationToken)
2014-02-03 20:51:28 +00:00
{
2019-01-29 22:09:48 +00:00
cancellationToken.ThrowIfCancellationRequested();
}
2013-09-15 17:34:48 +00:00
2014-02-03 20:51:28 +00:00
/// <summary>
/// Extracts info for each episode into invididual xml files so that they can be easily accessed without having to step through the entire series xml
/// </summary>
/// <param name="seriesDataPath">The series data path.</param>
/// <param name="xmlFile">The XML file.</param>
/// <param name="lastTvDbUpdateTime">The last tv db update time.</param>
/// <returns>Task.</returns>
private async Task ExtractEpisodes(string seriesDataPath, string xmlFile, long? lastTvDbUpdateTime)
{
2016-10-27 07:58:33 +00:00
var settings = _xmlSettings.Create(false);
2016-10-27 07:58:33 +00:00
settings.CheckCharacters = false;
settings.IgnoreProcessingInstructions = true;
settings.IgnoreComments = true;
using (var fileStream = _fileSystem.GetFileStream(xmlFile, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
2014-02-03 20:51:28 +00:00
{
2016-10-27 07:58:33 +00:00
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
2016-10-27 07:58:33 +00:00
// Use XmlReader for best performance
using (var reader = XmlReader.Create(streamReader, settings))
2013-02-21 01:33:05 +00:00
{
2016-10-27 07:58:33 +00:00
reader.MoveToContent();
2016-12-02 20:10:35 +00:00
reader.Read();
2016-10-27 07:58:33 +00:00
// Loop through each element
2016-12-03 21:46:06 +00:00
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
2014-02-03 20:51:28 +00:00
{
2016-10-27 07:58:33 +00:00
if (reader.NodeType == XmlNodeType.Element)
{
2016-10-27 07:58:33 +00:00
switch (reader.Name)
{
case "Episode":
{
var outerXml = reader.ReadOuterXml();
2016-10-27 07:58:33 +00:00
await SaveEpsiodeXml(seriesDataPath, outerXml, lastTvDbUpdateTime).ConfigureAwait(false);
break;
}
2016-10-27 07:58:33 +00:00
default:
reader.Skip();
break;
}
}
2016-12-02 20:10:35 +00:00
else
{
reader.Read();
}
2014-02-03 20:51:28 +00:00
}
2013-02-21 01:33:05 +00:00
}
}
}
}
2013-02-21 01:33:05 +00:00
2014-02-03 20:51:28 +00:00
private async Task SaveEpsiodeXml(string seriesDataPath, string xml, long? lastTvDbUpdateTime)
{
2016-10-27 07:58:33 +00:00
var settings = _xmlSettings.Create(false);
settings.CheckCharacters = false;
settings.IgnoreProcessingInstructions = true;
settings.IgnoreComments = true;
2014-02-03 20:51:28 +00:00
var seasonNumber = -1;
var episodeNumber = -1;
var absoluteNumber = -1;
var lastUpdateString = string.Empty;
2018-09-12 17:26:21 +00:00
var dvdSeasonNumber = -1;
var dvdEpisodeNumber = -1.0;
2014-02-03 20:51:28 +00:00
using (var streamReader = new StringReader(xml))
2013-09-15 17:34:48 +00:00
{
// Use XmlReader for best performance
using (var reader = XmlReader.Create(streamReader, settings))
{
2013-09-15 17:34:48 +00:00
reader.MoveToContent();
2016-12-02 20:10:35 +00:00
reader.Read();
2013-07-31 12:09:23 +00:00
2013-09-15 17:34:48 +00:00
// Loop through each element
2016-12-03 21:46:06 +00:00
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
2013-02-21 01:33:05 +00:00
{
2013-09-15 17:34:48 +00:00
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
2014-02-03 20:51:28 +00:00
case "lastupdated":
2013-09-15 17:34:48 +00:00
{
2014-02-03 20:51:28 +00:00
lastUpdateString = reader.ReadElementContentAsString();
break;
}
case "EpisodeNumber":
{
var val = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(val))
2013-09-15 17:34:48 +00:00
{
if (int.TryParse(val, NumberStyles.Integer, _usCulture, out var num))
2014-02-03 20:51:28 +00:00
{
episodeNumber = num;
}
}
break;
}
2018-09-12 17:26:21 +00:00
case "Combined_episodenumber":
{
var val = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(val))
{
if (float.TryParse(val, NumberStyles.Any, _usCulture, out var num))
2018-09-12 17:26:21 +00:00
{
dvdEpisodeNumber = num;
}
}
break;
}
case "Combined_season":
{
var val = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(val))
{
if (float.TryParse(val, NumberStyles.Any, _usCulture, out var num))
2018-09-12 17:26:21 +00:00
{
dvdSeasonNumber = Convert.ToInt32(num);
}
}
break;
}
2014-02-03 20:51:28 +00:00
case "absolute_number":
{
var val = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(val))
{
if (int.TryParse(val, NumberStyles.Integer, _usCulture, out var num))
2014-02-03 20:51:28 +00:00
{
absoluteNumber = num;
}
}
break;
}
case "SeasonNumber":
{
var val = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(val))
{
if (int.TryParse(val, NumberStyles.Integer, _usCulture, out var num))
2014-02-03 20:51:28 +00:00
{
seasonNumber = num;
}
2013-09-15 17:34:48 +00:00
}
break;
}
2014-02-03 20:51:28 +00:00
2013-09-15 17:34:48 +00:00
default:
reader.Skip();
break;
}
}
2016-12-02 20:10:35 +00:00
else
{
reader.Read();
}
2013-02-21 01:33:05 +00:00
}
}
2013-02-21 01:33:05 +00:00
}
2013-09-15 17:34:48 +00:00
2014-02-03 20:51:28 +00:00
var hasEpisodeChanged = true;
2015-02-20 18:27:01 +00:00
if (!string.IsNullOrWhiteSpace(lastUpdateString) && lastTvDbUpdateTime.HasValue)
2013-09-15 17:34:48 +00:00
{
if (long.TryParse(lastUpdateString, NumberStyles.Any, _usCulture, out var num))
2013-09-15 17:34:48 +00:00
{
2014-02-03 20:51:28 +00:00
hasEpisodeChanged = num >= lastTvDbUpdateTime.Value;
}
}
2014-02-03 20:51:28 +00:00
var file = Path.Combine(seriesDataPath, string.Format("episode-{0}-{1}.xml", seasonNumber, episodeNumber));
2014-02-03 20:51:28 +00:00
// Only save the file if not already there, or if the episode has changed
if (hasEpisodeChanged || !File.Exists(file))
2014-02-03 20:51:28 +00:00
{
2016-10-27 07:58:33 +00:00
using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
2014-02-03 20:51:28 +00:00
{
2016-10-27 07:58:33 +00:00
using (var writer = XmlWriter.Create(fileStream, new XmlWriterSettings
{
Encoding = Encoding.UTF8,
Async = true
}))
{
await writer.WriteRawAsync(xml).ConfigureAwait(false);
}
2013-09-15 17:34:48 +00:00
}
}
2014-02-03 20:51:28 +00:00
if (absoluteNumber != -1)
2013-09-15 17:34:48 +00:00
{
2014-02-03 20:51:28 +00:00
file = Path.Combine(seriesDataPath, string.Format("episode-abs-{0}.xml", absoluteNumber));
// Only save the file if not already there, or if the episode has changed
if (hasEpisodeChanged || !File.Exists(file))
2014-02-03 20:51:28 +00:00
{
2016-10-27 07:58:33 +00:00
using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
2014-02-03 20:51:28 +00:00
{
2016-10-27 07:58:33 +00:00
using (var writer = XmlWriter.Create(fileStream, new XmlWriterSettings
{
Encoding = Encoding.UTF8,
Async = true
}))
{
await writer.WriteRawAsync(xml).ConfigureAwait(false);
}
2014-02-03 20:51:28 +00:00
}
}
2013-09-15 17:34:48 +00:00
}
2018-09-12 17:26:21 +00:00
if (dvdSeasonNumber != -1 && dvdEpisodeNumber != -1 && (dvdSeasonNumber != seasonNumber || dvdEpisodeNumber != episodeNumber))
{
file = Path.Combine(seriesDataPath, string.Format("episode-dvd-{0}-{1}.xml", dvdSeasonNumber, dvdEpisodeNumber));
// Only save the file if not already there, or if the episode has changed
if (hasEpisodeChanged || !File.Exists(file))
2018-09-12 17:26:21 +00:00
{
using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
{
using (var writer = XmlWriter.Create(fileStream, new XmlWriterSettings
{
Encoding = Encoding.UTF8,
Async = true
}))
{
await writer.WriteRawAsync(xml).ConfigureAwait(false);
}
}
}
}
2013-09-15 17:34:48 +00:00
}
/// <summary>
2014-02-03 20:51:28 +00:00
/// Gets the series data path.
2013-02-21 01:33:05 +00:00
/// </summary>
2014-02-03 20:51:28 +00:00
/// <param name="appPaths">The app paths.</param>
2015-11-29 20:01:14 +00:00
/// <param name="seriesProviderIds">The series provider ids.</param>
2014-02-03 20:51:28 +00:00
/// <returns>System.String.</returns>
2015-11-29 20:01:14 +00:00
internal static string GetSeriesDataPath(IApplicationPaths appPaths, Dictionary<string, string> seriesProviderIds)
2013-02-21 01:33:05 +00:00
{
if (seriesProviderIds.TryGetValue(MetadataProviders.Tvdb.ToString(), out string seriesId) && !string.IsNullOrEmpty(seriesId))
2015-11-29 20:01:14 +00:00
{
var seriesDataPath = Path.Combine(GetSeriesDataPath(appPaths), seriesId);
return seriesDataPath;
}
2014-02-03 20:51:28 +00:00
2016-03-04 17:07:14 +00:00
if (seriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out seriesId) && !string.IsNullOrEmpty(seriesId))
2015-11-29 20:01:14 +00:00
{
var seriesDataPath = Path.Combine(GetSeriesDataPath(appPaths), seriesId);
return seriesDataPath;
}
2018-09-12 17:26:21 +00:00
if (seriesProviderIds.TryGetValue(MetadataProviders.Zap2It.ToString(), out seriesId) && !string.IsNullOrEmpty(seriesId))
{
var seriesDataPath = Path.Combine(GetSeriesDataPath(appPaths), seriesId);
return seriesDataPath;
}
2015-11-29 20:01:14 +00:00
return null;
2013-02-21 01:33:05 +00:00
}
2016-03-04 17:07:14 +00:00
public string GetSeriesXmlPath(Dictionary<string, string> seriesProviderIds, string language)
{
var seriesDataPath = GetSeriesDataPath(_config.ApplicationPaths, seriesProviderIds);
2019-01-27 11:03:43 +00:00
var seriesXmlFilename = language.ToLowerInvariant() + ".xml";
2016-03-04 17:07:14 +00:00
return Path.Combine(seriesDataPath, seriesXmlFilename);
}
2013-02-21 01:33:05 +00:00
/// <summary>
2014-02-03 20:51:28 +00:00
/// Gets the series data path.
2013-02-21 01:33:05 +00:00
/// </summary>
2014-02-03 20:51:28 +00:00
/// <param name="appPaths">The app paths.</param>
/// <returns>System.String.</returns>
internal static string GetSeriesDataPath(IApplicationPaths appPaths)
2013-02-21 01:33:05 +00:00
{
2014-03-05 02:59:59 +00:00
var dataPath = Path.Combine(appPaths.CachePath, "tvdb");
2013-02-21 01:33:05 +00:00
2014-02-03 20:51:28 +00:00
return dataPath;
}
2014-02-03 20:51:28 +00:00
private void DeleteXmlFiles(string path)
{
try
2013-02-21 01:33:05 +00:00
{
foreach (var file in _fileSystem.GetFilePaths(path, true)
2014-02-03 20:51:28 +00:00
.ToList())
{
_fileSystem.DeleteFile(file);
2014-02-03 20:51:28 +00:00
}
2013-02-21 01:33:05 +00:00
}
2016-10-27 07:58:33 +00:00
catch (IOException)
2013-02-21 01:33:05 +00:00
{
2014-02-03 20:51:28 +00:00
// No biggie
}
}
2014-02-03 20:51:28 +00:00
/// <summary>
/// Sanitizes the XML file.
/// </summary>
/// <param name="file">The file.</param>
/// <returns>Task.</returns>
private async Task SanitizeXmlFile(string file)
{
string validXml;
2016-10-25 19:02:04 +00:00
using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true))
2014-02-03 20:51:28 +00:00
{
using (var reader = new StreamReader(fileStream))
{
var xml = await reader.ReadToEndAsync().ConfigureAwait(false);
2014-02-03 20:51:28 +00:00
validXml = StripInvalidXmlCharacters(xml);
}
2013-02-21 01:33:05 +00:00
}
2016-10-25 19:02:04 +00:00
using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
{
2014-02-03 20:51:28 +00:00
using (var writer = new StreamWriter(fileStream))
{
await writer.WriteAsync(validXml).ConfigureAwait(false);
}
}
2013-02-21 01:33:05 +00:00
}
/// <summary>
2014-02-03 20:51:28 +00:00
/// Strips the invalid XML characters.
2013-02-21 01:33:05 +00:00
/// </summary>
2014-02-03 20:51:28 +00:00
/// <param name="inString">The in string.</param>
2013-02-21 01:33:05 +00:00
/// <returns>System.String.</returns>
2014-02-03 20:51:28 +00:00
public static string StripInvalidXmlCharacters(string inString)
2013-02-21 01:33:05 +00:00
{
2014-02-03 20:51:28 +00:00
if (inString == null) return null;
var sbOutput = new StringBuilder();
char ch;
for (int i = 0; i < inString.Length; i++)
2013-02-21 01:33:05 +00:00
{
2014-02-03 20:51:28 +00:00
ch = inString[i];
if ((ch >= 0x0020 && ch <= 0xD7FF) ||
(ch >= 0xE000 && ch <= 0xFFFD) ||
ch == 0x0009 ||
ch == 0x000A ||
ch == 0x000D)
2013-02-21 01:33:05 +00:00
{
2014-02-03 20:51:28 +00:00
sbOutput.Append(ch);
2013-02-21 01:33:05 +00:00
}
2014-02-03 20:51:28 +00:00
}
return sbOutput.ToString();
}
public string Name => "TheTVDB";
2014-02-15 16:36:09 +00:00
2015-09-19 21:25:19 +00:00
public async Task Identify(SeriesInfo info)
{
2015-10-21 05:09:50 +00:00
if (!string.IsNullOrWhiteSpace(info.GetProviderId(MetadataProviders.Tvdb)))
2014-08-19 01:42:53 +00:00
{
2015-10-21 05:09:50 +00:00
return;
}
2014-08-19 01:42:53 +00:00
2015-10-21 05:09:50 +00:00
var srch = await FindSeries(info.Name, info.Year, info.MetadataLanguage, CancellationToken.None).ConfigureAwait(false);
2014-08-19 01:42:53 +00:00
2015-10-21 05:09:50 +00:00
var entry = srch.FirstOrDefault();
if (entry != null)
{
var id = entry.GetProviderId(MetadataProviders.Tvdb);
info.SetProviderId(MetadataProviders.Tvdb, id);
2014-08-19 01:42:53 +00:00
}
}
public int Order => 0;
public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
{
2014-03-02 15:42:21 +00:00
return _httpClient.GetResponse(new HttpRequestOptions
{
CancellationToken = cancellationToken,
Url = url,
2017-01-05 18:09:12 +00:00
BufferContent = false
2014-03-02 15:42:21 +00:00
});
}
2013-02-21 01:33:05 +00:00
}
2016-04-21 05:13:33 +00:00
}