Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup SyncLibraryTask #129

Merged
merged 3 commits into from
Oct 10, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Trakt/Api/TraktApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,18 @@ public TraktApi(IJsonSerializer jsonSerializer, ILogger logger, IHttpClient http
_logger = logger;
}

/// <summary>
/// Checks whether it's possible/allowed to sync a <see cref="BaseItem"/> for a <see cref="TraktUser"/>.
/// </summary>
/// <param name="item">
/// Item to check.
/// </param>
/// <param name="traktUser">
/// The trakt user to check for.
/// </param>
/// <returns>
/// <see cref="bool"/> indicates if it's possible/allowed to sync this item.
/// </returns>
public bool CanSync(BaseItem item, TraktUser traktUser)
{
if (item.Path == null || item.LocationType == LocationType.Virtual)
Expand Down Expand Up @@ -85,6 +97,7 @@ public bool CanSync(BaseItem item, TraktUser traktUser)

return false;
}

/// <summary>
/// Report to trakt.tv that a movie is being watched, or has been watched.
/// </summary>
Expand Down
15 changes: 3 additions & 12 deletions Trakt/Configuration/TraktConfigurationPage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@ class TraktConfigurationPage : IPluginConfigurationPage
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get { return "Trakt for MediaBrowser"; }
}
public string Name => "Trakt for MediaBrowser";

/// <summary>
/// Gets the HTML stream.
Expand All @@ -31,14 +28,8 @@ public Stream GetHtmlStream()
/// Gets the type of the configuration page.
/// </summary>
/// <value>The type of the configuration page.</value>
public ConfigurationPageType ConfigurationPageType
{
get { return ConfigurationPageType.PluginConfiguration; }
}
public ConfigurationPageType ConfigurationPageType => ConfigurationPageType.PluginConfiguration;

public IPlugin Plugin
{
get { return Trakt.Plugin.Instance; }
}
public IPlugin Plugin => Trakt.Plugin.Instance;
}
}
22 changes: 5 additions & 17 deletions Trakt/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,22 @@ namespace Trakt
{
public class Plugin : BasePlugin<PluginConfiguration>
{
public SemaphoreSlim TraktResourcePool = new SemaphoreSlim(2,2);
public SemaphoreSlim TraktResourcePool = new SemaphoreSlim(2, 2);

public Plugin(IApplicationPaths appPaths, IXmlSerializer xmlSerializer)
: base(appPaths, xmlSerializer)
{
Instance = this;
}

public override string Name
{
get { return "Trakt"; }
}

public override string Name => "Trakt";


public override string Description
{
get
{
return "Watch, rate and discover media using Trakt. The htpc just got more social";
}
}
=> "Watch, rate and discover media using Trakt. The htpc just got more social";

public static Plugin Instance { get; private set; }

public PluginConfiguration PluginConfiguration
{
get { return Configuration; }
}

public PluginConfiguration PluginConfiguration => Configuration;
}
}
132 changes: 69 additions & 63 deletions Trakt/ScheduledTasks/SyncFromTraktTask.cs
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
using System.Globalization;
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
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>
/// Task that will Sync each users trakt.tv profile with their local library. This task will only include
Expand Down Expand Up @@ -120,24 +120,24 @@ private async Task SyncTraktDataForUser(User user, double currentProgress, Cance
throw;
}


_logger.Info("Trakt.tv watched Movies count = " + traktWatchedMovies.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
{
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();
return episode != null ? episode.Series.Id : i.Id;
}).ToList();

// purely for progress reporting
var percentPerItem = percentPerUser / mediaItems.Count;
Expand All @@ -164,6 +164,7 @@ private async Task SyncTraktDataForUser(User user, double currentProgress, Cance

// keep the highest play count
int playcount = Math.Max(matchedMovie.Plays, userData.PlayCount);

// set movie playcount
if (userData.PlayCount != playcount)
{
Expand All @@ -175,9 +176,7 @@ private async Task SyncTraktDataForUser(User user, double currentProgress, Cance
if (!string.IsNullOrEmpty(matchedMovie.LastWatchedAt))
{
var tLastPlayed = DateTime.Parse(matchedMovie.LastWatchedAt);
var latestPlayed = tLastPlayed > userData.LastPlayedDate
? tLastPlayed
: userData.LastPlayedDate;
var latestPlayed = tLastPlayed > userData.LastPlayedDate ? tLastPlayed : userData.LastPlayedDate;
if (userData.LastPlayedDate != latestPlayed)
{
userData.LastPlayedDate = latestPlayed;
Expand All @@ -189,7 +188,11 @@ private async Task SyncTraktDataForUser(User user, double currentProgress, Cance
if (changed)
{
await
_userDataManager.SaveUserData(user.Id, movie, userData, UserDataSaveReason.Import,
_userDataManager.SaveUserData(
user.Id,
movie,
userData,
UserDataSaveReason.Import,
cancellationToken);
}
}
Expand All @@ -210,8 +213,13 @@ private async Task SyncTraktDataForUser(User user, double currentProgress, Cance

if (matchedShow != null)
{
var matchedSeason = matchedShow.Seasons
.FirstOrDefault(tSeason => tSeason.Number == (episode.ParentIndexNumber == 0 ? 0 : ((episode.ParentIndexNumber ?? 1) + (episode.Series.AnimeSeriesIndex ?? 1) - 1)));
var matchedSeason =
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 (matchedSeason != null)
Expand All @@ -220,7 +228,8 @@ private async Task SyncTraktDataForUser(User user, double currentProgress, Cance
var userData = _userDataManager.GetUserData(user.Id, episode);
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)
{
Expand All @@ -236,6 +245,7 @@ private async Task SyncTraktDataForUser(User user, double currentProgress, Cance

// keep the highest play count
int playcount = Math.Max(matchedEpisode.Plays, userData.PlayCount);

// set episode playcount
if (userData.PlayCount != playcount)
{
Expand All @@ -255,7 +265,11 @@ private async Task SyncTraktDataForUser(User user, double currentProgress, Cance
if (changed)
{
await
_userDataManager.SaveUserData(user.Id, episode, userData, UserDataSaveReason.Import,
_userDataManager.SaveUserData(
user.Id,
episode,
userData,
UserDataSaveReason.Import,
cancellationToken);
}
}
Expand All @@ -273,17 +287,18 @@ private async Task SyncTraktDataForUser(User user, double currentProgress, Cance
currentProgress += percentPerItem;
progress.Report(currentProgress);
}
//_logger.Info(syncItemFailures + " items not parsed");

// _logger.Info(syncItemFailures + " items not parsed");
}

private string GetVerboseEpisodeData(Episode episode)
{
string episodeString = "";
string episodeString = string.Empty;
episodeString += "Episode: " + (episode.ParentIndexNumber != null ? episode.ParentIndexNumber.ToString() : "null");
episodeString += "x" + (episode.IndexNumber != null ? episode.IndexNumber.ToString() : "null");
episodeString += " '" + episode.Name + "' ";
episodeString += "Series: '" + (episode.Series != null
? !String.IsNullOrWhiteSpace(episode.Series.Name)
? !string.IsNullOrWhiteSpace(episode.Series.Name)
? episode.Series.Name
: "null property"
: "null class");
Expand Down Expand Up @@ -370,25 +385,16 @@ public IEnumerable<ITaskTrigger> GetDefaultTriggers()
/// <summary>
///
/// </summary>
public string Name
{
get { return "Import playstates from Trakt.tv"; }
}
public string Name => "Import playstates from Trakt.tv";

/// <summary>
///
/// </summary>
public string Description
{
get { return "Sync Watched/Unwatched status from Trakt.tv for each MB3 user that has a configured Trakt account"; }
}
public string Description => "Sync Watched/Unwatched status from Trakt.tv for each MB3 user that has a configured Trakt account";

/// <summary>
///
/// </summary>
public string Category
{
get { return "Trakt"; }
}
public string Category => "Trakt";
}
}
Loading