Skip to content

Commit

Permalink
Fixes to TBA episodes to work around TVDB bug
Browse files Browse the repository at this point in the history
  • Loading branch information
SirSparkles committed Jun 15, 2021
1 parent 9d6c2c7 commit a065ab5
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 47 deletions.
2 changes: 1 addition & 1 deletion TVRename/Model/CachedSeriesInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,7 @@ public void UpdateBanners(List<int> latestBannerIds)

public void AddEpisode([NotNull] Episode episode)
{
sourceEpisodes.TryAdd(episode.EpisodeId, episode);
sourceEpisodes.AddOrUpdate(episode.EpisodeId, episode,(i, episode1) => episode);
episode.SetSeriesSeason(this);
}

Expand Down
6 changes: 6 additions & 0 deletions TVRename/Model/Episode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -450,5 +450,11 @@ public void SetDirectors([NotNull] List<string> directors)
EpisodeDirector = string.Join("|", directors);
}
}

public bool HasAired()
{
LocalDateTime? dateTime = GetAirDateDt();
return dateTime.HasValue && dateTime.Value.InUtc().ToInstant().CompareTo(SystemClock.Instance.GetCurrentInstant()) < 0;
}
}
}
7 changes: 6 additions & 1 deletion TVRename/Sources/CacheHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -204,9 +204,14 @@ public static void MarkPlaceholdersDirty(this MediaCache cache)
{
// anything with a srv_lastupdated of 0 should be marked as dirty
// typically, this'll be placeholder cachedSeries
foreach (CachedSeriesInfo? ser in cache.CachedShowData.Values.Where(ser => ser.SrvLastUpdated == 0 || ser.Episodes.Count == 0))
foreach (CachedSeriesInfo? ser in cache.CachedShowData.Values.Where(ser => ser.SrvLastUpdated == 0 || ser.Episodes.Count == 0 || ser.Episodes.Any(e=>e.Name=="TBA" && e.HasAired())))
{
ser.Dirty = true;

foreach (Episode ep in ser.Episodes.Where(e => e.Name == "TBA" && e.HasAired()))
{
ep.Dirty = true;
}
}
}
}
Expand Down
103 changes: 60 additions & 43 deletions TVRename/Sources/TheTVDB/LocalCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -229,10 +229,15 @@ private void HandleConnectionProblem(bool showErrorMsgBox, WebException ex)
public bool GetUpdates(bool showErrorMsgBox, CancellationToken cts, IEnumerable<ISeriesSpecifier> ss)
{
Say("Validating TheTVDB cache");
foreach (ISeriesSpecifier downloadShow in ss.Where(downloadShow => !HasSeries(downloadShow.TvdbId)))
IEnumerable<ISeriesSpecifier> seriesSpecifiers = ss.ToList();
foreach (ISeriesSpecifier downloadShow in seriesSpecifiers.Where(downloadShow => downloadShow.Type==MediaConfiguration.MediaType.tv && !HasSeries(downloadShow.TvdbId)))
{
this.AddPlaceholderSeries(downloadShow);
}
foreach (ISeriesSpecifier downloadShow in seriesSpecifiers.Where(downloadShow => downloadShow.Type == MediaConfiguration.MediaType.movie && !HasMovie(downloadShow.TvdbId)))
{
this.AddPlaceholderMovie(downloadShow);
}

Say("Updates list from TVDB");

Expand Down Expand Up @@ -2157,25 +2162,7 @@ private void ReloadEpisodesV4(int code, Locale locale, CachedSeriesInfo si)
JToken episodeData = seasonInfo["data"]?["episodes"];
if (episodeData != null)
{
Parallel.ForEach(episodeData, x =>
{
try
{
(Episode newEp, Language bestLanguage) = GenerateEpisodeV4(x, code, si, locale);
AddTranslations(newEp,
API.GetEpisodeTranslationsV4(newEp.EpisodeId, bestLanguage.ThreeAbbreviation));

si.AddEpisode(newEp);
}
catch (SourceConnectivityException sce1)
{
LOGGER.Error(sce1);
}
catch (SourceConsistencyException sce1)
{
LOGGER.Error(sce1);
}
});
Parallel.ForEach(episodeData, x => { GenerateAddEpisodeV4(code, locale, si, x); });
}
}
catch (SourceConnectivityException sce)
Expand All @@ -2189,14 +2176,46 @@ private void ReloadEpisodesV4(int code, Locale locale, CachedSeriesInfo si)
});
}

private void GenerateAddEpisodeV4(int code, Locale locale, CachedSeriesInfo si, JToken x)
{
try
{
(Episode newEp, Language bestLanguage) = GenerateCoreEpisodeV4(x, code, si, locale);
AddTranslations(newEp,
API.GetEpisodeTranslationsV4(newEp.EpisodeId, bestLanguage.ThreeAbbreviation));

si.AddEpisode(newEp);
}
catch (SourceConnectivityException sce1)
{
LOGGER.Error(sce1);
}
catch (SourceConsistencyException sce1)
{
LOGGER.Error(sce1);
}
}

private void AddTranslations(Episode newEp, JObject downloadSeriesTranslationsJsonV4)
{
newEp.Name = downloadSeriesTranslationsJsonV4["data"]["name"]?.ToString() ?? string.Empty;
newEp.Overview = downloadSeriesTranslationsJsonV4["data"]["overview"]?.ToString() ?? string.Empty;
string? transName = downloadSeriesTranslationsJsonV4["data"]["name"]?.ToString();
newEp.Name = Translate(newEp.Name,transName);
string? transOverview = downloadSeriesTranslationsJsonV4["data"]["overview"]?.ToString();
newEp.Overview = Translate(newEp.Overview,transOverview);
//Set a language code on the SI?? si.lan ==downloadSeriesTranslationsJsonV4["data"]["language"].ToString();
}

private (Episode, Language) GenerateEpisodeV4(JToken episodeJson, int code, CachedSeriesInfo si, Locale locale)
private string Translate(string? originalName, string? transName)
{
if (transName.HasValue() && transName != "TBA")
return transName!;
if (originalName.HasValue() && originalName != "TBA")
return originalName!;

return transName ?? originalName ?? string.Empty;
}

private (Episode, Language) GenerateCoreEpisodeV4(JToken episodeJson, int code, CachedSeriesInfo si, Locale locale)
{
Episode x = new Episode(code, si)
{
Expand All @@ -2208,6 +2227,7 @@ private void AddTranslations(Episode newEp, JObject downloadSeriesTranslationsJs
AiredSeasonNumber = episodeJson["seasonNumber"].ToObject<int>(),
AiredEpNum = episodeJson["number"].ToObject<int>(),
Filename = episodeJson["image"].ToObject<string>(),
//todo srvlastupdated can be got from "lastUpdated": "2021-06-11 12:42:28",
};

return (x, GetAppropriateLanguage(episodeJson["nameTranslations"], locale));
Expand Down Expand Up @@ -2257,7 +2277,7 @@ private void ReloadEpisodes(int code, Locale locale, CachedSeriesInfo si)
try
{
//TODO - Establish whether this has any value?
UpdateEpisodeNow(code, prefLangEpisode, defltLangEpisode, si);
UpdateEpisodeNowv3(code, prefLangEpisode, defltLangEpisode, si);
}
catch (InvalidCastException ex)
{
Expand Down Expand Up @@ -2389,19 +2409,23 @@ private bool DownloadEpisodeNow(int seriesId, int episodeId, Locale locale, bool
JObject jsonResponseData = (JObject)jsonEpisodeResponse["data"] ??
throw new SourceConsistencyException("No Data in Ep Response",
TVDoc.ProviderType.TheTVDB);

if (TVSettings.Instance.TvdbVersion == ApiVersion.v4)
{
GenerateAddEpisodeV4(seriesId,locale,cachedSeriesInfo,jsonResponseData);
return true;
}
if (locale.IsDifferentLanguageToDefaultFor(TVDoc.ProviderType.TheTVDB))
{
JObject seriesDataDefaultLang = (JObject)jsonEpisodeDefaultLangResponse["data"];
return UpdateEpisodeNow(seriesId, jsonResponseData, seriesDataDefaultLang, cachedSeriesInfo);
return UpdateEpisodeNowv3(seriesId, jsonResponseData, seriesDataDefaultLang, cachedSeriesInfo);
}
else
{
return UpdateEpisodeNow(seriesId, jsonResponseData, null, cachedSeriesInfo);
return UpdateEpisodeNowv3(seriesId, jsonResponseData, null, cachedSeriesInfo);
}
}

private bool UpdateEpisodeNow(int seriesId, JToken jsonResponseData, JToken? seriesDataDefaultLang,
private bool UpdateEpisodeNowv3(int seriesId, JToken jsonResponseData, JToken? seriesDataDefaultLang,
CachedSeriesInfo si)
{
if (!Series.ContainsKey(seriesId))
Expand All @@ -2411,7 +2435,8 @@ private bool UpdateEpisodeNow(int seriesId, JToken jsonResponseData, JToken? ser

try
{
Episode e = seriesDataDefaultLang != null
Episode e =
seriesDataDefaultLang != null
? new Episode(seriesId, (JObject)jsonResponseData, (JObject)seriesDataDefaultLang, si)
: new Episode(seriesId, (JObject)jsonResponseData, si);

Expand Down Expand Up @@ -2451,7 +2476,7 @@ private static string EpisodeDescription(bool dvdOrder, int episodeId, Episode?

return $"S{ep.AiredSeasonNumber:00}E{ep.AiredEpNum:00}";
}

//todo remove this method
private void AddPlaceholderSeries(int tvdb, int tvmaze, int tmdb, Locale locale)
{
Series[tvdb] = new CachedSeriesInfo(tvdb, tvmaze, tmdb, locale, TVDoc.ProviderType.TheTVDB) { Dirty = true };
Expand Down Expand Up @@ -2561,6 +2586,7 @@ private bool EnsureSeriesUpdated(ISeriesSpecifier seriesd, bool bannersToo, bool
foreach (Episode e in collection.Where(e => e.Dirty && e.EpisodeId > 0))
{
extraEpisodes.TryAdd(e.EpisodeId, new ExtraEp(e.SeriesId, e.EpisodeId));
extraEpisodes[e.EpisodeId].Done = false;
}
}

Expand Down Expand Up @@ -2798,23 +2824,14 @@ private CachedMovieInfo GenerateMovieV4(JObject r, Locale locale, bool searchRes
TvdbCode = (int)r["tvdb_id"],
Slug = ((string)r["id"])?.Trim(),
PosterUrl = (string)r["image_url"],
Overview = (string)r["overview"],
Network = (string)r["network"],
Status = (string)r["status"],
IsSearchResultOnly = searchResult,
ShowLanguage = (string)r["primary_language"],
FirstAired = GenerateFirstAiredDate(r),
Name = Decode(r, "name") ?? FindTranslation(r, locale, "name_translated") ?? string.Empty,
Overview = Decode(r, "overview") ?? FindTranslation(r, locale, "overview_translated") ?? string.Empty,
};
int? year = r.Value<int?>("year");
if (year.HasValue)
{
si.FirstAired = new DateTime(year.Value, 1, 1);
}

string s = (string)r["name"];
if (s != null)
{
si.Name = System.Web.HttpUtility.HtmlDecode(s).Trim();
}

if (string.IsNullOrEmpty(si.Name))
{
Expand Down Expand Up @@ -2867,7 +2884,7 @@ private CachedSeriesInfo GenerateSeriesV4(JObject r, Locale locale, bool searchR
private string? FindTranslation(JObject r, Locale locale, string tag)
{
string langaugeCode = locale.LanguageToUse(TVDoc.ProviderType.TheTVDB).ThreeAbbreviation;
JToken languagesArray = r?[tag];
JToken languagesArray = r[tag];
if (languagesArray == null)
{
return null;
Expand Down
4 changes: 2 additions & 2 deletions TVRename/Utility/Helper/FileHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -747,11 +747,11 @@ public static bool IsValidDirectory(this string directoryName)
}

// see https://kodi.wiki/view/Naming_video_files/Movies#Split_Video_Files
private static List<string> ending = new List<string> { "part", "cd", "dvd", "pt", "disk", "disc" };
private static readonly List<string> Ending = new List<string> { "part", "cd", "dvd", "pt", "disk", "disc" };

public static bool IsDoublePartMovie(FileInfo f1, FileInfo f2)
{
return ending.Any(end => HasEnding(f1, f2, end));
return Ending.Any(end => HasEnding(f1, f2, end));
}

private static bool HasEnding(FileInfo f1, FileInfo f2, string part)
Expand Down

0 comments on commit a065ab5

Please sign in to comment.