public static IEnumerable<EpisodeWatched> GetWatchedEpisodesFromTrakt(bool ignoreLastSyncTime = false)
{
// get from cache regardless of last sync time
if (ignoreLastSyncTime)
return WatchedEpisodes;
TraktLogger.Info("Getting current user watched episodes from trakt.tv");
// get the last time we did anything to our library online
var lastSyncActivities = LastSyncActivities;
// something bad happened e.g. site not available
if (lastSyncActivities == null || lastSyncActivities.Episodes == null)
return null;
// check the last time we have against the online time
// if the times are the same try to load from cache
if (lastSyncActivities.Episodes.Watched == TraktSettings.LastSyncActivities.Episodes.Watched)
{
var cachedItems = WatchedEpisodes;
if (cachedItems != null)
return cachedItems;
}
TraktLogger.Info("TV episode watched history cache is out of date, requesting updated data. Local Date = '{0}', Online Date = '{1}'", TraktSettings.LastSyncActivities.Episodes.Watched ?? "<empty>", lastSyncActivities.Episodes.Watched ?? "<empty>");
// we get from online, local cache is not up to date
var onlineItems = TraktAPI.TraktAPI.GetWatchedEpisodes();
if (onlineItems == null)
return null;
// convert trakt structure to more flat heirarchy (more managable)
TraktLogger.Debug("Converting list of watched episodes from trakt to internal data structure");
var episodesWatched = new List<EpisodeWatched>();
foreach (var show in onlineItems)
{
foreach(var season in show.Seasons)
{
foreach(var episode in season.Episodes)
{
episodesWatched.Add( new EpisodeWatched
{
ShowId = show.Show.Ids.Trakt,
ShowTvdbId = show.Show.Ids.Tvdb,
ShowImdbId = show.Show.Ids.Imdb,
ShowTitle = show.Show.Title,
ShowYear = show.Show.Year,
Number = episode.Number,
Season = season.Number,
Plays = episode.Plays,
WatchedAt = episode.WatchedAt
});
}
}
}
_WatchedEpisodes = episodesWatched;
// save to local file cache
SaveFileCache(EpisodesWatchedFile, _WatchedEpisodes.ToJSON());
// save new activity time for next time
TraktSettings.LastSyncActivities.Episodes.Watched = lastSyncActivities.Episodes.Watched;
return _WatchedEpisodes;
}