Cleanup and split SyncShows

This commit is contained in:
J2ghz 2016-10-02 13:04:45 +02:00
parent 66dce97b8c
commit 30a595bc6f
2 changed files with 113 additions and 92 deletions

View File

@ -1,30 +1,30 @@
using System.Globalization; namespace Trakt.ScheduledTasks
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommonIO;
using Trakt.Api;
using Trakt.Api.DataContracts.BaseModel;
using Trakt.Api.DataContracts.Users.Collection;
using Trakt.Api.DataContracts.Users.Watched;
using Trakt.Helpers;
using Trakt.Model;
namespace Trakt.ScheduledTasks
{ {
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommonIO;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
using Trakt.Api;
using Trakt.Api.DataContracts.BaseModel;
using Trakt.Api.DataContracts.Users.Collection;
using Trakt.Api.DataContracts.Users.Watched;
using Trakt.Helpers;
/// <summary> /// <summary>
/// Task that will Sync each users trakt.tv profile with their local library. This task will only include /// Task that will Sync each users trakt.tv profile with their local library. This task will only include
@ -120,24 +120,24 @@ namespace Trakt.ScheduledTasks
throw; throw;
} }
_logger.Info("Trakt.tv watched Movies count = " + traktWatchedMovies.Count()); _logger.Info("Trakt.tv watched Movies count = " + traktWatchedMovies.Count());
_logger.Info("Trakt.tv watched Shows count = " + traktWatchedShows.Count()); _logger.Info("Trakt.tv watched Shows count = " + traktWatchedShows.Count());
var mediaItems =
_libraryManager.GetItemList(
new InternalItemsQuery
{
IncludeItemTypes = new[] { typeof(Movie).Name, typeof(Episode).Name },
ExcludeLocationTypes = new[] { LocationType.Virtual }
})
.Where(i => _traktApi.CanSync(i, traktUser))
.OrderBy(
i =>
{
var episode = i as Episode;
var mediaItems = _libraryManager.GetItemList(new InternalItemsQuery return episode != null ? episode.Series.Id : i.Id;
{ }).ToList();
IncludeItemTypes = new[] { typeof(Movie).Name, typeof(Episode).Name },
ExcludeLocationTypes = new[] { LocationType.Virtual }
})
.Where(i => _traktApi.CanSync(i, traktUser))
.OrderBy(i =>
{
var episode = i as Episode;
return episode != null ? episode.Series.Id : i.Id;
})
.ToList();
// purely for progress reporting // purely for progress reporting
var percentPerItem = percentPerUser / mediaItems.Count; var percentPerItem = percentPerUser / mediaItems.Count;
@ -164,6 +164,7 @@ namespace Trakt.ScheduledTasks
// keep the highest play count // keep the highest play count
int playcount = Math.Max(matchedMovie.Plays, userData.PlayCount); int playcount = Math.Max(matchedMovie.Plays, userData.PlayCount);
// set movie playcount // set movie playcount
if (userData.PlayCount != playcount) if (userData.PlayCount != playcount)
{ {
@ -175,9 +176,7 @@ namespace Trakt.ScheduledTasks
if (!string.IsNullOrEmpty(matchedMovie.LastWatchedAt)) if (!string.IsNullOrEmpty(matchedMovie.LastWatchedAt))
{ {
var tLastPlayed = DateTime.Parse(matchedMovie.LastWatchedAt); var tLastPlayed = DateTime.Parse(matchedMovie.LastWatchedAt);
var latestPlayed = tLastPlayed > userData.LastPlayedDate var latestPlayed = tLastPlayed > userData.LastPlayedDate ? tLastPlayed : userData.LastPlayedDate;
? tLastPlayed
: userData.LastPlayedDate;
if (userData.LastPlayedDate != latestPlayed) if (userData.LastPlayedDate != latestPlayed)
{ {
userData.LastPlayedDate = latestPlayed; userData.LastPlayedDate = latestPlayed;
@ -189,7 +188,11 @@ namespace Trakt.ScheduledTasks
if (changed) if (changed)
{ {
await await
_userDataManager.SaveUserData(user.Id, movie, userData, UserDataSaveReason.Import, _userDataManager.SaveUserData(
user.Id,
movie,
userData,
UserDataSaveReason.Import,
cancellationToken); cancellationToken);
} }
} }
@ -210,8 +213,13 @@ namespace Trakt.ScheduledTasks
if (matchedShow != null) if (matchedShow != null)
{ {
var matchedSeason = matchedShow.Seasons var matchedSeason =
.FirstOrDefault(tSeason => tSeason.Number == (episode.ParentIndexNumber == 0 ? 0 : ((episode.ParentIndexNumber ?? 1) + (episode.Series.AnimeSeriesIndex ?? 1) - 1))); matchedShow.Seasons.FirstOrDefault(
tSeason =>
tSeason.Number
== (episode.ParentIndexNumber == 0
? 0
: ((episode.ParentIndexNumber ?? 1) + (episode.Series.AnimeSeriesIndex ?? 1) - 1)));
// if it's not a match then it means trakt doesn't know about the season, leave the watched state alone and move on // if it's not a match then it means trakt doesn't know about the season, leave the watched state alone and move on
if (matchedSeason != null) if (matchedSeason != null)
@ -220,7 +228,8 @@ namespace Trakt.ScheduledTasks
var userData = _userDataManager.GetUserData(user.Id, episode); var userData = _userDataManager.GetUserData(user.Id, episode);
bool changed = false; bool changed = false;
var matchedEpisode = matchedSeason.Episodes.FirstOrDefault(x => x.Number == (episode.IndexNumber ?? -1)); var matchedEpisode =
matchedSeason.Episodes.FirstOrDefault(x => x.Number == (episode.IndexNumber ?? -1));
if (matchedEpisode != null) if (matchedEpisode != null)
{ {
@ -236,6 +245,7 @@ namespace Trakt.ScheduledTasks
// keep the highest play count // keep the highest play count
int playcount = Math.Max(matchedEpisode.Plays, userData.PlayCount); int playcount = Math.Max(matchedEpisode.Plays, userData.PlayCount);
// set episode playcount // set episode playcount
if (userData.PlayCount != playcount) if (userData.PlayCount != playcount)
{ {
@ -255,7 +265,11 @@ namespace Trakt.ScheduledTasks
if (changed) if (changed)
{ {
await await
_userDataManager.SaveUserData(user.Id, episode, userData, UserDataSaveReason.Import, _userDataManager.SaveUserData(
user.Id,
episode,
userData,
UserDataSaveReason.Import,
cancellationToken); cancellationToken);
} }
} }
@ -273,17 +287,18 @@ namespace Trakt.ScheduledTasks
currentProgress += percentPerItem; currentProgress += percentPerItem;
progress.Report(currentProgress); progress.Report(currentProgress);
} }
//_logger.Info(syncItemFailures + " items not parsed");
// _logger.Info(syncItemFailures + " items not parsed");
} }
private string GetVerboseEpisodeData(Episode episode) private string GetVerboseEpisodeData(Episode episode)
{ {
string episodeString = ""; string episodeString = string.Empty;
episodeString += "Episode: " + (episode.ParentIndexNumber != null ? episode.ParentIndexNumber.ToString() : "null"); episodeString += "Episode: " + (episode.ParentIndexNumber != null ? episode.ParentIndexNumber.ToString() : "null");
episodeString += "x" + (episode.IndexNumber != null ? episode.IndexNumber.ToString() : "null"); episodeString += "x" + (episode.IndexNumber != null ? episode.IndexNumber.ToString() : "null");
episodeString += " '" + episode.Name + "' "; episodeString += " '" + episode.Name + "' ";
episodeString += "Series: '" + (episode.Series != null episodeString += "Series: '" + (episode.Series != null
? !String.IsNullOrWhiteSpace(episode.Series.Name) ? !string.IsNullOrWhiteSpace(episode.Series.Name)
? episode.Series.Name ? episode.Series.Name
: "null property" : "null property"
: "null class"); : "null class");

View File

@ -388,6 +388,51 @@
progress.Report(progPercent); progress.Report(progPercent);
} }
await SendEpisodeCollectionUpdates(true, traktUser, collectedEpisodes, progress, progPercent, percentPerItem, cancellationToken);
await SendEpisodePlaystateUpdates(true, traktUser, playedEpisodes, progress, progPercent, percentPerItem, cancellationToken);
await SendEpisodePlaystateUpdates(false, traktUser, unplayedEpisodes, progress, progPercent, percentPerItem, cancellationToken);
}
private async Task SendEpisodePlaystateUpdates(
bool seen,
TraktUser traktUser,
List<Episode> playedEpisodes,
IProgress<double> progress,
double progPercent,
double percentPerItem,
CancellationToken cancellationToken)
{
_logger.Info("Episodes to set " + (seen ? string.Empty : "un") + "watched: " + playedEpisodes.Count);
if (playedEpisodes.Count > 0)
{
try
{
var dataContracts =
await _traktApi.SendEpisodePlaystateUpdates(playedEpisodes, traktUser, seen, cancellationToken);
dataContracts?.ForEach(LogTraktResponseDataContract);
}
catch (Exception e)
{
_logger.ErrorException("Error updating episode play states", e);
}
// purely for progress reporting
progPercent += percentPerItem * playedEpisodes.Count;
progress.Report(progPercent);
}
}
private async Task SendEpisodeCollectionUpdates(
bool collected,
TraktUser traktUser,
List<Episode> collectedEpisodes,
IProgress<double> progress,
double progPercent,
double percentPerItem,
CancellationToken cancellationToken)
{
_logger.Info("Episodes to add to Collection: " + collectedEpisodes.Count); _logger.Info("Episodes to add to Collection: " + collectedEpisodes.Count);
if (collectedEpisodes.Count > 0) if (collectedEpisodes.Count > 0)
{ {
@ -395,7 +440,7 @@
{ {
var dataContracts = var dataContracts =
await await
_traktApi.SendLibraryUpdateAsync(collectedEpisodes, traktUser, cancellationToken, EventType.Add) _traktApi.SendLibraryUpdateAsync(collectedEpisodes, traktUser, cancellationToken, collected ? EventType.Add : EventType.Remove)
.ConfigureAwait(false); .ConfigureAwait(false);
if (dataContracts != null) if (dataContracts != null)
{ {
@ -418,47 +463,8 @@
progPercent += percentPerItem * collectedEpisodes.Count; progPercent += percentPerItem * collectedEpisodes.Count;
progress.Report(progPercent); progress.Report(progPercent);
} }
_logger.Info("Episodes to set watched: " + playedEpisodes.Count);
if (playedEpisodes.Count > 0)
{
try
{
var dataContracts =
await _traktApi.SendEpisodePlaystateUpdates(playedEpisodes, traktUser, true, cancellationToken);
dataContracts?.ForEach(LogTraktResponseDataContract);
}
catch (Exception e)
{
_logger.ErrorException("Error updating episode play states", e);
}
// purely for progress reporting
progPercent += percentPerItem * playedEpisodes.Count;
progress.Report(progPercent);
}
_logger.Info("Episodes to set unwatched: " + unplayedEpisodes.Count);
if (unplayedEpisodes.Count > 0)
{
try
{
var dataContracts =
await
_traktApi.SendEpisodePlaystateUpdates(unplayedEpisodes, traktUser, false, cancellationToken);
dataContracts?.ForEach(LogTraktResponseDataContract);
}
catch (Exception e)
{
_logger.ErrorException("Error updating episode play states", e);
}
// purely for progress reporting
progPercent += percentPerItem * unplayedEpisodes.Count;
progress.Report(progPercent);
}
} }
public string Name => "Sync library to trakt.tv"; public string Name => "Sync library to trakt.tv";
public string Category => "Trakt"; public string Category => "Trakt";