private bool TestAccount(TraktAuthenticationToken token) { // test account by requesting the user settings var response = TraktAPI.TraktAPI.GetUserSettings(); if (response == null || response.User == null) { GUIUtils.ShowNotifyDialog(Translation.Error, Translation.FailedOnlineSettings); return(false); } else { // Save New Account Settings TraktSettings.Username = response.User.Username; TraktSettings.OnlineSettings = response; TraktSettings.AccountStatus = ConnectionState.Connected; InitProperties(); // clear caches // watchlists are stored by user so dont need clearing. GUINetwork.ClearCache(); GUICalendarTV.ClearCache(); GUIRecommendationsMovies.ClearCache(); GUIRecommendationsShows.ClearCache(); // clear any stored user data TraktCache.ClearSyncCache(); // persist settings TraktSettings.SaveSettings(false); return(true); } }
public void GetCollectedMovies(List <ITraktCollectionMovie> onlineCollectedMovies, ITraktSyncLastActivities onlineLastSyncActivities, int expectedCollectedMoviesCount) { // Arrange ITraktClient traktClient = Substitute.For <ITraktClient>(); traktClient.GetCollectedMovies().Returns(onlineCollectedMovies); traktClient.GetLastActivities().Returns(onlineLastSyncActivities); IFileOperations fileOperations = Substitute.For <IFileOperations>(); SetFileOperationsForFile(fileOperations, DataPath, FileName.LastActivity.Value); SetFileOperationsForFile(fileOperations, DataPath, FileName.CollectedMovies.Value); SetFileOperationsForFile(fileOperations, DataPath, FileName.WatchedMovies.Value); IMediaPortalServices mediaPortalServices = Substitute.For <IMediaPortalServices>(); mediaPortalServices.GetTraktUserHomePath().Returns(DataPath); // Act ITraktCache traktCache = new TraktCache(mediaPortalServices, traktClient, fileOperations); TraktMovies traktMovies = traktCache.RefreshMoviesCache(); // Assert int actualCollectedMoviesCount = traktMovies.Collected.Count(); Assert.Equal(expectedCollectedMoviesCount, actualCollectedMoviesCount); }
/// <summary> /// Stops scrobbing an episode on trakt.tv /// </summary> /// <param name="watched">Determines if we should force watched on stop</param> internal static bool StopScrobbleEpisode(VideoInfo videoInfo, bool watched = false) { // get scrobble data to send to api var scrobbleData = CreateEpisodeScrobbleData(videoInfo); if (scrobbleData == null) { return(false); } // force watched if (watched && scrobbleData.Progress < 80) { scrobbleData.Progress = 100; } var response = TraktAPI.TraktAPI.StopEpisodeScrobble(scrobbleData); if (response != null && response.Show != null) { // add to cache if (response.Action == "scrobble") { TraktCache.AddEpisodeToWatchHistory(response.Show, response.Episode); } else if (response.Action == "pause") { TraktCache.AddEpisodeToPausedData(response.Show, response.Episode, response.Progress); } } return(TraktLogger.LogTraktResponse(response)); }
public void StopScrobble() { if (CurrentMovie == null) { return; } var scrobbleData = CreateScrobbleData(CurrentMovie); // check if movie is considered 'watched' if (scrobbleData.Progress >= WatchedPercent) { ShowRateDialog(CurrentMovie); } var scrobbleMovie = new Thread((objScrobble) => { var tScrobbleData = objScrobble as TraktScrobbleMovie; if (tScrobbleData == null) { return; } TraktScrobbleResponse response = null; if (tScrobbleData.Progress >= WatchedPercent) { TraktLogger.Info("Sending 'stop' scrobble of movie to trakt.tv. Title = '{0}', Year = '{1}', IMDb ID = '{2}'", tScrobbleData.Movie.Title, tScrobbleData.Movie.Year, tScrobbleData.Movie.Ids.Imdb ?? "<empty>"); response = TraktAPI.TraktAPI.StopMovieScrobble(tScrobbleData); if (response != null && response.Movie != null && response.Action == "scrobble") { // add to cache TraktCache.AddMovieToWatchHistory(response.Movie); } } else { TraktLogger.Info("Sending 'pause' scrobble of movie to trakt.tv. Title = '{0}', Year = '{1}', IMDb ID = '{2}'", tScrobbleData.Movie.Title, tScrobbleData.Movie.Year, tScrobbleData.Movie.Ids.Imdb ?? "<empty>"); response = TraktAPI.TraktAPI.PauseMovieScrobble(tScrobbleData); if (response != null && response.Movie != null && response.Action == "pause") { // add to cache TraktCache.AddMovieToPausedData(response.Movie, response.Progress); } } TraktLogger.LogTraktResponse(response); }) { IsBackground = true, Name = "Scrobble" }; scrobbleMovie.Start(scrobbleData); CurrentMovie = null; }
public void SyncMediaToTrakt_Async() { if (SyncMovies() && SyncSeries()) { TestStatus = "[Trakt.SyncFinished]"; } IsSynchronizing = false; TraktCache.Save(); }
public TraktSetupModel() { _mediaPortalServices = new MediaPortalServices(); _traktClient = new TraktClientProxy(ApplicationId, SecretId, _mediaPortalServices.GetLogger()); _fileOperations = new FileOperations(); ITraktCache traktCache = new TraktCache(_mediaPortalServices, _traktClient, _fileOperations); _librarySynchronization = new LibrarySynchronization(_mediaPortalServices, _traktClient, traktCache, _fileOperations); }
internal static TraktSyncHandlerManager ResolveManager() { IMediaPortalServices mediaPortalServices = new MediaPortalServices(); IFileOperations fileOperations = new FileOperations(); ITraktClient traktClient = new TraktClientProxy(ApplicationId, SecretId, mediaPortalServices.GetLogger()); ITraktCache traktCache = new TraktCache(mediaPortalServices, traktClient, fileOperations); ILibrarySynchronization librarySynchronization = new LibrarySynchronization(mediaPortalServices, traktClient, traktCache, fileOperations); return(new TraktSyncHandlerManager(mediaPortalServices, librarySynchronization, fileOperations)); }
public void SyncCollectedMoviesToTrakt() { // Arrange IMediaPortalServices mediaPortalServices = Substitute.For <IMediaPortalServices>(); mediaPortalServices.MarkAsWatched(Arg.Any <MediaItem>()).Returns(true); mediaPortalServices.MarkAsUnWatched(Arg.Any <MediaItem>()).Returns(true); mediaPortalServices.GetTraktUserHomePath() .Returns(HomeUserPath); IList <MediaItem> collectedMovies = new List <MediaItem>(); IList <MediaLibraryMovie> savedMovies = new List <MediaLibraryMovie>(); string collectedMoviesPath = Path.Combine(mediaPortalServices.GetTraktUserHomePath(), FileName.MediaLibraryMovies.Value); if (File.Exists(collectedMoviesPath)) { string collectedMoviesJson = File.ReadAllText(collectedMoviesPath); savedMovies = JsonConvert.DeserializeObject <List <MediaLibraryMovie> >(collectedMoviesJson); } foreach (MediaLibraryMovie movie in savedMovies) { collectedMovies.Add(new MockedDatabaseMovie(new MediaLibraryMovie { Title = movie.Title, Imdb = movie.Imdb, Year = movie.Year, AddedToDb = movie.AddedToDb, LastPlayed = movie.LastPlayed, PlayCount = movie.PlayCount }).Movie); } IContentDirectory contentDirectory = Substitute.For <IContentDirectory>(); contentDirectory.SearchAsync(Arg.Any <MediaItemQuery>(), true, null, false).Returns(collectedMovies); mediaPortalServices.GetServerConnectionManager().ContentDirectory.Returns(contentDirectory); ILogger logger = Substitute.For <ILogger>(); ITraktClient traktClient = new TraktClientProxy(ApplicationId, SecretId, logger); ValidateAuthorization(traktClient, new FileOperations()); IFileOperations fileOperations = new FileOperations(); ITraktCache traktCache = new TraktCache(mediaPortalServices, traktClient, fileOperations); ILibrarySynchronization librarySynchronization = new LibrarySynchronization(mediaPortalServices, traktClient, traktCache, fileOperations); // Act TraktSyncMoviesResult result = librarySynchronization.SyncMovies(); // Assert Assert.NotNull(result); }
/// <summary> /// Shows the Rate Movie Dialog after playback has ended /// </summary> /// <param name="movie">The movie being rated</param> private void ShowRateDialog(IMDBMovie movie) { if (!TraktSettings.ShowRateDialogOnWatched) { return; } if (!TraktSettings.ShowRateDlgForPlaylists && PlayListPlayer.SingletonPlayer.CurrentPlaylistType == PlayListType.PLAYLIST_VIDEO) { return; } TraktLogger.Debug("Showing rate dialog for movie. Title = '{0}', Year = '{1}', IMDb ID = '{2}'", movie.Title, movie.Year, movie.IMDBNumber ?? "<empty>"); var rateThread = new Thread((o) => { var movieToRate = o as IMDBMovie; if (movieToRate == null) { return; } var rateObject = new TraktSyncMovieRated { Ids = new TraktMovieId { Imdb = movieToRate.IMDBNumber.ToNullIfEmpty() }, Title = movieToRate.Title, Year = movieToRate.Year, RatedAt = DateTime.UtcNow.ToISO8601(), }; // get the rating submitted to trakt.tv int rating = GUI.GUIUtils.ShowRateDialog <TraktSyncMovieRated>(rateObject); if (rating > 0) { // update local cache TraktCache.AddMovieToRatings(rateObject, rating); TraktLogger.Debug("Rating {0} ({1}) as {2}/10", movieToRate.Title, movie.Year, rating.ToString()); } else if (rating == 0) { TraktCache.RemoveMovieFromRatings(rateObject); } }) { Name = "Rate", IsBackground = true }; rateThread.Start(movie); }
private void AddItemToCollection(TraktListItem item) { if (SelectedType == TraktItemType.movie) { TraktHelper.AddMovieToCollection(item.Movie); } else if (SelectedType == TraktItemType.episode) { TraktHelper.AddEpisodeToCollection(item.Episode); TraktCache.AddEpisodeToCollection(item.Show, item.Episode); } }
private void RemoveItemFromCollection(TraktListItem item) { if (SelectedType == TraktItemType.movie) { TraktHelper.RemoveMovieFromCollection(item.Movie); } else if (SelectedType == TraktItemType.episode) { TraktHelper.RemoveEpisodeFromCollection(item.Episode); TraktCache.RemoveEpisodeFromCollection(item.Show, item.Episode); } }
private void AddItemToWatchList(TraktListItem item) { if (SelectedType == TraktItemType.movie) { TraktHelper.AddMovieToWatchList(item.Movie, true); } else if (SelectedType == TraktItemType.show) { TraktHelper.AddShowToWatchList(item.Show); } else if (SelectedType == TraktItemType.episode) { TraktHelper.AddEpisodeToWatchList(item.Episode); TraktCache.AddEpisodeToWatchlist(item.Show, item.Episode); } }
// keep all references to TraktPlugin in separate methods, so that methods that are called from GUIOnlineVideos don't throw an ecxeption it Trakt isn't loaded /* * for the time being: disabled because of too much requests to trakt in some cases * private static Dictionary<string, int> seriesTitleCache = new Dictionary<string, int>(); * private static bool SafeIsWatchedSeriesFuzzy(ITrackingInfo trackingInfo) * { * string cacheKey = trackingInfo.Title.ToLowerInvariant(); * if (!seriesTitleCache.ContainsKey(cacheKey)) * { * var shows = TraktAPI.SearchShows(cacheKey, 1); * var first = shows.FirstOrDefault(); * if (first != null && first.Show.Ids.Trakt.HasValue) * seriesTitleCache.Add(cacheKey, first.Show.Ids.Trakt.Value); * } * * if (seriesTitleCache.ContainsKey(cacheKey)) * { * int id = seriesTitleCache[cacheKey]; * { * var watchedEpisodes = TraktCache.GetWatchedEpisodesFromTrakt(true); * foreach (var episode in watchedEpisodes) * { * if (id == episode.ShowId && episode.Season == trackingInfo.Season && episode.Number == trackingInfo.Episode) * return true; * } * }; * }; * return false; * } */ private static bool SafeIsWatchedSeriesSimple(ITrackingInfo trackingInfo) { var watchedEpisodes = TraktCache.GetWatchedEpisodesFromTrakt(true); if (watchedEpisodes != null) { foreach (var episode in watchedEpisodes) { if (episode.ShowTitle.ToLowerInvariant() == trackingInfo.Title.ToLowerInvariant() && episode.Season == trackingInfo.Season && episode.Number == trackingInfo.Episode) { return(true); } } } return(false); }
private static bool SafeIsWatchedMovie(ITrackingInfo trackingInfo) { var watchedMovies = TraktCache.GetWatchedMoviesFromTrakt(true); if (watchedMovies != null) { foreach (var movies in watchedMovies) { if ((trackingInfo.Year == 0 || trackingInfo.Year == movies.Movie.Year) && (String.IsNullOrEmpty(trackingInfo.ID_IMDB) || String.IsNullOrEmpty(movies.Movie.Ids.Imdb) || trackingInfo.ID_IMDB == movies.Movie.Ids.Imdb) && trackingInfo.Title.ToLowerInvariant() == movies.Movie.Title.ToLowerInvariant()) { return(true); } } } return(false); }
private void EditList(TraktListDetail list) { GUIBackgroundTask.Instance.ExecuteInBackgroundAndCallback(() => { return(TraktAPI.TraktAPI.UpdateCustomList(list)); }, delegate(bool success, object result) { if (success) { var response = result as TraktListDetail; if (response == null) { // reload with new list TraktLists.ClearListCache(TraktSettings.Username); LoadLists(); var thread = new Thread((o) => { TraktCache.ClearCustomListCache(); // updated MovingPictures categories and filters menu if (TraktHelper.IsMovingPicturesAvailableAndEnabled) { TraktHandlers.MovingPictures.UpdateCategoriesMenu(SyncListType.CustomList); TraktHandlers.MovingPictures.UpdateFiltersMenu(SyncListType.CustomList); } }) { Name = "EditList", IsBackground = true }; thread.Start(); } else { GUIUtils.ShowNotifyDialog(Translation.Lists, Translation.FailedUpdateList); } } }, Translation.EditingList, true); }
private void DisconnectAccount() { TraktLogger.Info("Disconnecting Account: {0}", TraktSettings.Username); // clear account settings TraktSettings.Username = string.Empty; TraktSettings.Password = string.Empty; TraktSettings.AccountStatus = ConnectionState.Disconnected; InitProperties(); // clear caches // watchlists are stored by user so dont need clearing. GUINetwork.ClearCache(); GUICalendar.ClearCache(); GUIRecommendationsMovies.ClearCache(); GUIRecommendationsShows.ClearCache(); // clear any stored user data TraktCache.ClearSyncCache(); }
private static bool SafeIsWatchedMovie(ITrackingInfo trackingInfo) { var watchedMovies = TraktCache.GetWatchedMoviesFromTrakt(true); if (watchedMovies != null) { foreach (var movies in watchedMovies) { if (!String.IsNullOrEmpty(trackingInfo.ID_IMDB) && trackingInfo.ID_IMDB == movies.Movie.Ids.Imdb) { //if imdb is filled in and equal then match is found regardless of the rest of the properties return(true); } if ((trackingInfo.Year == 0 || trackingInfo.Year == movies.Movie.Year) && (String.IsNullOrEmpty(trackingInfo.ID_IMDB) || String.IsNullOrEmpty(movies.Movie.Ids.Imdb) || trackingInfo.ID_IMDB == movies.Movie.Ids.Imdb) && trackingInfo.Title.ToLowerInvariant() == movies.Movie.Title.ToLowerInvariant()) { return(true); } } } return(false); }
private void DisconnectAccount() { TraktLogger.Info("Revoking application access to trakt.tv account"); GUIBackgroundTask.Instance.ExecuteInBackgroundAndCallback(() => { TraktAPI.TraktAPI.RevokeToken(); return(true); }, delegate(bool success, object result) { if (success) { // clear account settings TraktSettings.Username = string.Empty; TraktSettings.UserAccessToken = string.Empty; TraktSettings.UserAccessTokenExpiry = string.Empty; TraktSettings.UserRefreshToken = string.Empty; TraktSettings.AccountStatus = ConnectionState.Disconnected; InitProperties(); // clear caches // watchlists are stored by user so dont need clearing. GUINetwork.ClearCache(); GUICalendarTV.ClearCache(); GUIRecommendationsMovies.ClearCache(); GUIRecommendationsShows.ClearCache(); // clear any stored user data TraktCache.ClearSyncCache(); // persist settings TraktSettings.SaveSettings(false); } }, Translation.AuthorizingApplication, false); }
public void SyncMediaToTrakt() { if (!IsSynchronizing) { ISettingsManager settingsManager = ServiceRegistration.Get <ISettingsManager>(); TraktSettings settings = settingsManager.Load <TraktSettings>(); if (!settings.IsAuthorized) { TestStatus = "[Trakt.NotAuthorized]"; TraktLogger.Error("Trakt.tv not authorized"); return; } if (!TraktCache.RefreshData()) { return; } IsSynchronizing = true; IThreadPool threadPool = ServiceRegistration.Get <IThreadPool>(); threadPool.Add(SyncMediaToTrakt_Async, ThreadPriority.BelowNormal); } }
public void StopScrobble() { if (CurrentVideo != null) { // onlinevideos can split videos into multiple parts // we only need to handle a pause event if the progress is less than 80% double position = g_Player.CurrentPosition; double duration = g_Player.Duration; if (duration != 0) { double progress = position / duration; if (progress < 0.8) { // send pause event to trakt.tv TraktLogger.Info("Playback stopped in OnlineVideos but video is not considered watched, Progress = '{0}%', Duration = '{1}', Current Position = '{2}'", Math.Round(progress * 100, 2), g_Player.Duration, g_Player.CurrentPosition); if (CurrentVideo.VideoKind == VideoKind.TvSeries) { var scrobbleEpisodeData = CreateEpisodeScrobbleData(CurrentVideo, Math.Round(progress * 100, 2)); var scrobbleThread = new Thread((objInfo) => { var response = TraktAPI.TraktAPI.PauseEpisodeScrobble(objInfo as TraktScrobbleEpisode); TraktLogger.LogTraktResponse(response); if (response != null && response.Code == 0) { // add episode paused to cache if (response.Action == "pause") { TraktCache.AddEpisodeToPausedData(response.Show, response.Episode, response.Progress); } } }) { IsBackground = true, Name = "Scrobble" }; scrobbleThread.Start(scrobbleEpisodeData); } else { var scrobbleMovieData = CreateMovieScrobbleData(CurrentVideo, Math.Round(progress * 100, 2)); var scrobbleThread = new Thread((objInfo) => { var response = TraktAPI.TraktAPI.PauseMovieScrobble(objInfo as TraktScrobbleMovie); TraktLogger.LogTraktResponse(response); if (response != null && response.Code == 0) { // add movie paused to cache if (response.Action == "pause") { TraktCache.AddMovieToPausedData(response.Movie, response.Progress); } } }) { IsBackground = true, Name = "Scrobble" }; scrobbleThread.Start(scrobbleMovieData); } } else { // either completely watched or finished watching part of a mult-part file TraktLogger.Info("Playback stopped in OnlineVideos, awaiting next playback event."); } } CurrentVideo = null; } return; }
public void SyncProgress() { if (!TraktSettings.SyncPlayback || SyncPlaybackInProgress) { return; } SyncPlaybackInProgress = true; TraktLogger.Info("My Videos Starting Playback Sync"); // get playback data from trakt string lastPausedAtMovie; var playbackData = TraktCache.GetPausedMovies(out lastPausedAtMovie); if (playbackData == null) { TraktLogger.Warning("Failed to get resume data from trakt.tv"); SyncPlaybackInProgress = false; return; } DateTime lastPausedItemProcessed; DateTime.TryParse(lastPausedAtMovie, out lastPausedItemProcessed); TraktLogger.Info("Found {0} movies on trakt.tv with resume data, processing paused movies after {1}", playbackData.Where(p => p.Type == "movie").Count(), lastPausedAtMovie); foreach (var item in playbackData.Where(p => p.Type == "movie")) { DateTime itemPausedAt; if (DateTime.TryParse(item.PausedAt, out itemPausedAt)) { // check if we need to process if (itemPausedAt <= lastPausedItemProcessed) { continue; } } // get movie from local database if it exists var movie = GetMovies().FirstOrDefault(m => ((m.IMDBNumber == item.Movie.Ids.Imdb) && !string.IsNullOrEmpty(item.Movie.Ids.Imdb) || m.Title.ToLowerInvariant() == item.Movie.Title.ToLowerInvariant() && m.Year == item.Movie.Year)); if (movie == null) { continue; } // if the local playtime is not known then skip if (movie.Duration <= 0) { TraktLogger.Warning("Skipping item with invalid runtime in database, Title = '{0}', Year = '{1}', IMDb ID = '{2}'", item.Movie.Title, item.Movie.Year, item.Movie.Ids.Imdb); continue; } // update the stop time based on percentage watched // the video database stores duration in seconds (runtime in minutes if duration not available) and stopTime in secs var resumeData = Convert.ToInt32(movie.Duration * (item.Progress / 100.0)) - TraktSettings.SyncResumeDelta; if (resumeData < 0) { resumeData = 0; } if (string.IsNullOrEmpty(movie.VideoFileName)) { TraktLogger.Warning("Skipping item with invalid filename in database, Title = '{0}', Year = '{1}', IMDb ID = '{2}'", item.Movie.Title, item.Movie.Year, item.Movie.Ids.Imdb); continue; } // if we are syncing on plugin entry we could possibly still be sending paused data to trakt // after stopping video (stopping video == re-entry to plugin), prevent possibly reverting stale resumed data // we already have updated resume data when stopping video in real-time if (TraktSettings.SyncPlaybackOnEnterPlugin && LastMovie != null && LastMovie.VideoFileName == movie.VideoFileName) { continue; } // check if movie is restricted if (TraktSettings.BlockedFilenames.Any(f => f == movie.VideoFileName) || TraktSettings.BlockedFolders.Any(f => f == Path.GetDirectoryName(movie.VideoFileName))) { TraktLogger.Info("Ignoring resume data sync for movie, filename/folder is ignored by user. Title = '{0}', Year = '{1}', IMDb ID = '{2}', Filename = '{3}'", item.Movie.Title, item.Movie.Year, item.Movie.Ids.Imdb, movie.VideoFileName); continue; } // Get FileId from filename int fileId = VideoDatabase.GetMovieId(movie.VideoFileName); // get current stop time for movie int currentResumeData = VideoDatabase.GetMovieStopTime(fileId); if (currentResumeData != resumeData) { // Note: will need to be a bit smarter for multi-part files (who the heck still does that!) TraktLogger.Info("Setting resume time '{0}' for movie, Title = '{1}', Year = '{2}', IMDb ID = '{3}'", new TimeSpan(0, 0, 0, resumeData), item.Movie.Title, item.Movie.Year, item.Movie.Ids.Imdb); VideoDatabase.SetMovieStopTime(fileId, resumeData); } } TraktLogger.Info("My Videos Playback Sync Completed"); SyncPlaybackInProgress = false; return; }
public void SyncLibrary() { TraktLogger.Info("My Videos Starting Library Sync"); #region Get online data from cache #region Get unwatched / watched movies from trakt.tv IEnumerable <TraktMovieWatched> traktWatchedMovies = null; var traktUnWatchedMovies = TraktCache.GetUnWatchedMoviesFromTrakt(); if (traktUnWatchedMovies == null) { TraktLogger.Error("Error getting unwatched movies from trakt server, unwatched and watched sync will be skipped"); } else { TraktLogger.Info("There are {0} unwatched movies since the last sync with trakt.tv", traktUnWatchedMovies.Count()); traktWatchedMovies = TraktCache.GetWatchedMoviesFromTrakt(); if (traktWatchedMovies == null) { TraktLogger.Error("Error getting watched movies from trakt server, watched sync will be skipped"); } else { TraktLogger.Info("There are {0} watched movies in trakt.tv library", traktWatchedMovies.Count()); } } #endregion #region Get collected movies from trakt.tv var traktCollectedMovies = TraktCache.GetCollectedMoviesFromTrakt(); if (traktCollectedMovies == null) { TraktLogger.Error("Error getting collected movies from trakt server"); } else { TraktLogger.Info("There are {0} collected movies in trakt.tv library", traktCollectedMovies.Count()); } #endregion #endregion // optionally do library sync if (TraktSettings.SyncLibrary) { var collectedMovies = GetMovies(); #region Remove Blocked Movies collectedMovies.RemoveAll(m => TraktSettings.BlockedFolders.Any(f => m.Path.ToLowerInvariant().Contains(f.ToLowerInvariant()))); List <int> blockedMovieIds = new List <int>(); foreach (string file in TraktSettings.BlockedFilenames) { int pathId = 0; int movieId = 0; // get a list of ids for blocked filenames // filename seems to always be empty for an IMDBMovie object! if (VideoDatabase.GetFile(file, out pathId, out movieId, false) > 0) { blockedMovieIds.Add(movieId); } } collectedMovies.RemoveAll(m => blockedMovieIds.Contains(m.ID)); #endregion #region Remove Movies with No IDs // Remove any movies that don't have any valid online ID's e.g. IMDb ID or TMDb ID. if (TraktSettings.SkipMoviesWithNoIdsOnSync) { TraktLogger.Info("Removing movies that contain no valid online ID from sync movie list"); collectedMovies.RemoveAll(m => !BasicHandler.IsValidImdb(m.IMDBNumber)); } #endregion #region Skipped Movies Check // Remove Skipped Movies from previous Sync //TODO //if (TraktSettings.SkippedMovies != null) //{ // // allow movies to re-sync again after 7-days in the case user has addressed issue ie. edited movie or added to themoviedb.org // if (TraktSettings.SkippedMovies.LastSkippedSync.FromEpoch() > DateTime.UtcNow.Subtract(new TimeSpan(7, 0, 0, 0))) // { // if (TraktSettings.SkippedMovies.Movies != null && TraktSettings.SkippedMovies.Movies.Count > 0) // { // TraktLogger.Info("Skipping {0} movies due to invalid data or movies don't exist on http://themoviedb.org. Next check will be {1}.", TraktSettings.SkippedMovies.Movies.Count, TraktSettings.SkippedMovies.LastSkippedSync.FromEpoch().Add(new TimeSpan(7, 0, 0, 0))); // foreach (var movie in TraktSettings.SkippedMovies.Movies) // { // TraktLogger.Info("Skipping movie, Title: {0}, Year: {1}, IMDb: {2}", movie.Title, movie.Year, movie.IMDBID); // MovieList.RemoveAll(m => (m.Title == movie.Title) && (m.Year.ToString() == movie.Year) && (m.IMDBNumber == movie.IMDBID)); // } // } // } // else // { // if (TraktSettings.SkippedMovies.Movies != null) TraktSettings.SkippedMovies.Movies.Clear(); // TraktSettings.SkippedMovies.LastSkippedSync = DateTime.UtcNow.ToEpoch(); // } //} #endregion #region Already Exists Movie Check // Remove Already-Exists Movies, these are typically movies that are using aka names and no IMDb/TMDb set // When we compare our local collection with trakt collection we have english only titles, so if no imdb/tmdb exists // we need to fallback to title matching. When we sync aka names are sometimes accepted if defined on themoviedb.org so we need to // do this to revent syncing these movies every sync interval. //TODO //if (TraktSettings.AlreadyExistMovies != null && TraktSettings.AlreadyExistMovies.Movies != null && TraktSettings.AlreadyExistMovies.Movies.Count > 0) //{ // TraktLogger.Debug("Skipping {0} movies as they already exist in trakt library but failed local match previously.", TraktSettings.AlreadyExistMovies.Movies.Count.ToString()); // var movies = new List<TraktMovieSync.Movie>(TraktSettings.AlreadyExistMovies.Movies); // foreach (var movie in movies) // { // Predicate<IMDBMovie> criteria = m => (m.Title == movie.Title) && (m.Year.ToString() == movie.Year) && (m.IMDBNumber == movie.IMDBID); // if (MovieList.Exists(criteria)) // { // TraktLogger.Debug("Skipping movie, Title: {0}, Year: {1}, IMDb: {2}", movie.Title, movie.Year, movie.IMDBID); // MovieList.RemoveAll(criteria); // } // else // { // // remove as we have now removed from our local collection or updated movie signature // if (TraktSettings.MoviePluginCount == 1) // { // TraktLogger.Debug("Removing 'AlreadyExists' movie, Title: {0}, Year: {1}, IMDb: {2}", movie.Title, movie.Year, movie.IMDBID); // TraktSettings.AlreadyExistMovies.Movies.Remove(movie); // } // } // } //} #endregion TraktLogger.Info("Found {0} movies available to sync in My Videos database", collectedMovies.Count); // get the movies that we have watched var watchedMovies = collectedMovies.Where(m => m.Watched > 0).ToList(); TraktLogger.Info("Found {0} watched movies available to sync in My Videos database", watchedMovies.Count); #region Mark movies as unwatched in local database if (traktUnWatchedMovies != null && traktUnWatchedMovies.Count() > 0) { foreach (var movie in traktUnWatchedMovies) { var localMovie = watchedMovies.FirstOrDefault(m => MovieMatch(m, movie)); if (localMovie == null) { continue; } TraktLogger.Info("Marking movie as unwatched in local database, movie is not watched on trakt.tv. Title = '{0}', Year = '{1}', IMDb ID = '{2}', TMDb ID = '{3}'", movie.Title, movie.Year.HasValue ? movie.Year.ToString() : "<empty>", movie.Ids.Imdb ?? "<empty>", movie.Ids.Tmdb.HasValue ? movie.Ids.Tmdb.ToString() : "<empty>"); localMovie.Watched = 0; IMDBMovie details = localMovie; VideoDatabase.SetMovieInfoById(localMovie.ID, ref details); VideoDatabase.SetMovieWatchedStatus(localMovie.ID, false, 0); } // update watched set watchedMovies = collectedMovies.Where(m => m.Watched > 0).ToList(); } #endregion #region Mark movies as watched in local database if (traktWatchedMovies != null && traktWatchedMovies.Count() > 0) { foreach (var twm in traktWatchedMovies) { var localMovie = collectedMovies.FirstOrDefault(m => MovieMatch(m, twm.Movie)); if (localMovie == null) { continue; } int iPercent; int iWatchedCount; bool localIsWatched = VideoDatabase.GetmovieWatchedStatus(localMovie.ID, out iPercent, out iWatchedCount); if (!localIsWatched || iWatchedCount < twm.Plays) { TraktLogger.Info("Updating local movie watched state / play count to match trakt.tv. Plays = '{0}', Title = '{1}', Year = '{2}', IMDb ID = '{3}', TMDb ID = '{4}'", twm.Plays, twm.Movie.Title, twm.Movie.Year.HasValue ? twm.Movie.Year.ToString() : "<empty>", twm.Movie.Ids.Imdb ?? "<empty>", twm.Movie.Ids.Tmdb.HasValue ? twm.Movie.Ids.Tmdb.ToString() : "<empty>"); if (localMovie.DateWatched == "0001-01-01 00:00:00") { DateTime dateWatched; if (DateTime.TryParse(twm.LastWatchedAt, out dateWatched)) { localMovie.DateWatched = dateWatched.ToString("yyyy-MM-dd HH:mm:ss"); } } localMovie.Watched = 1; localMovie.WatchedCount = twm.Plays; localMovie.WatchedPercent = iPercent; VideoDatabase.SetMovieWatchedCount(localMovie.ID, twm.Plays); VideoDatabase.SetMovieWatchedStatus(localMovie.ID, true, iPercent); IMDBMovie details = localMovie; VideoDatabase.SetMovieInfoById(localMovie.ID, ref details); } } } #endregion #region Add movies to watched history at trakt.tv if (traktWatchedMovies != null) { var syncWatchedMovies = new List <TraktSyncMovieWatched>(); TraktLogger.Info("Finding movies to add to trakt.tv watched history"); syncWatchedMovies = (from movie in watchedMovies where !traktWatchedMovies.ToList().Exists(c => MovieMatch(movie, c.Movie)) select new TraktSyncMovieWatched { Ids = new TraktMovieId { Imdb = movie.IMDBNumber.ToNullIfEmpty() }, Title = movie.Title, Year = movie.Year, WatchedAt = GetLastDateWatched(movie), }).ToList(); TraktLogger.Info("Adding {0} movies to trakt.tv watched history", syncWatchedMovies.Count); if (syncWatchedMovies.Count > 0) { // update local cache TraktCache.AddMoviesToWatchHistory(syncWatchedMovies); int pageSize = TraktSettings.SyncBatchSize; int pages = (int)Math.Ceiling((double)syncWatchedMovies.Count / pageSize); for (int i = 0; i < pages; i++) { TraktLogger.Info("Adding movies [{0}/{1}] to trakt.tv watched history", i + 1, pages); var pagedMovies = syncWatchedMovies.Skip(i * pageSize).Take(pageSize).ToList(); pagedMovies.ForEach(s => TraktLogger.Info("Adding movie to trakt.tv watched history. Title = '{0}', Year = '{1}', IMDb ID = '{2}', TMDb ID = '{3}', Date Watched = '{4}'", s.Title, s.Year.HasValue ? s.Year.ToString() : "<empty>", s.Ids.Imdb ?? "<empty>", s.Ids.Tmdb.HasValue ? s.Ids.Tmdb.ToString() : "<empty>", s.WatchedAt)); // remove title/year such that match against online ID only if (TraktSettings.SkipMoviesWithNoIdsOnSync) { pagedMovies.ForEach(m => { m.Title = null; m.Year = null; }); } var response = TraktAPI.TraktAPI.AddMoviesToWatchedHistory(new TraktSyncMoviesWatched { Movies = pagedMovies }); TraktLogger.LogTraktResponse <TraktSyncResponse>(response); // remove movies from cache which didn't succeed if (response != null && response.NotFound != null && response.NotFound.Movies.Count > 0) { TraktCache.RemoveMoviesFromWatchHistory(response.NotFound.Movies); } } } } #endregion #region Add movies to collection at trakt.tv if (traktCollectedMovies != null) { var syncCollectedMovies = new List <TraktSyncMovieCollected>(); TraktLogger.Info("Finding movies to add to trakt.tv collection"); syncCollectedMovies = (from movie in collectedMovies where !traktCollectedMovies.ToList().Exists(c => MovieMatch(movie, c.Movie)) select new TraktSyncMovieCollected { Ids = new TraktMovieId { Imdb = movie.IMDBNumber.ToNullIfEmpty() }, Title = movie.Title, Year = movie.Year, CollectedAt = movie.DateAdded.ToISO8601(), MediaType = GetMovieMediaType(movie), Resolution = GetMovieResolution(movie), AudioCodec = GetMovieAudioCodec(movie), AudioChannels = GetMovieAudioChannels(movie), Is3D = IsMovie3D(movie) }).ToList(); TraktLogger.Info("Adding {0} movies to trakt.tv collection", syncCollectedMovies.Count); if (syncCollectedMovies.Count > 0) { // update internal cache TraktCache.AddMoviesToCollection(syncCollectedMovies); int pageSize = TraktSettings.SyncBatchSize; int pages = (int)Math.Ceiling((double)syncCollectedMovies.Count / pageSize); for (int i = 0; i < pages; i++) { TraktLogger.Info("Adding movies [{0}/{1}] to trakt.tv collection", i + 1, pages); var pagedMovies = syncCollectedMovies.Skip(i * pageSize).Take(pageSize).ToList(); pagedMovies.ForEach(s => TraktLogger.Info("Adding movie to trakt.tv collection. Title = '{0}', Year = '{1}', IMDb ID = '{2}', TMDb ID = '{3}', Date Added = '{4}', MediaType = '{5}', Resolution = '{6}', Audio Codec = '{7}', Audio Channels = '{8}'", s.Title, s.Year.HasValue ? s.Year.ToString() : "<empty>", s.Ids.Imdb ?? "<empty>", s.Ids.Tmdb.HasValue ? s.Ids.Tmdb.ToString() : "<empty>", s.CollectedAt, s.MediaType ?? "<empty>", s.Resolution ?? "<empty>", s.AudioCodec ?? "<empty>", s.AudioChannels ?? "<empty>")); // remove title/year such that match against online ID only if (TraktSettings.SkipMoviesWithNoIdsOnSync) { pagedMovies.ForEach(m => { m.Title = null; m.Year = null; }); } var response = TraktAPI.TraktAPI.AddMoviesToCollecton(new TraktSyncMoviesCollected { Movies = pagedMovies }); TraktLogger.LogTraktResponse(response); // remove movies from cache which didn't succeed if (response != null && response.NotFound != null && response.NotFound.Movies.Count > 0) { TraktCache.RemoveMoviesFromCollection(response.NotFound.Movies); } } } } #endregion #region Remove movies no longer in collection from trakt.tv if (TraktSettings.KeepTraktLibraryClean && TraktSettings.MoviePluginCount == 1 && traktCollectedMovies != null) { var syncUnCollectedMovies = new List <TraktMovie>(); TraktLogger.Info("Finding movies to remove from trakt.tv collection"); // workout what movies that are in trakt collection that are not in local collection syncUnCollectedMovies = (from tcm in traktCollectedMovies where !collectedMovies.Exists(c => MovieMatch(c, tcm.Movie)) select new TraktMovie { Ids = tcm.Movie.Ids, Title = tcm.Movie.Title, Year = tcm.Movie.Year }).ToList(); TraktLogger.Info("Removing {0} movies from trakt.tv collection", syncUnCollectedMovies.Count); if (syncUnCollectedMovies.Count > 0) { // update local cache TraktCache.RemoveMoviesFromCollection(syncUnCollectedMovies); int pageSize = TraktSettings.SyncBatchSize; int pages = (int)Math.Ceiling((double)syncUnCollectedMovies.Count / pageSize); for (int i = 0; i < pages; i++) { TraktLogger.Info("Removing movies [{0}/{1}] from trakt.tv collection", i + 1, pages); var pagedMovies = syncUnCollectedMovies.Skip(i * pageSize).Take(pageSize).ToList(); pagedMovies.ForEach(s => TraktLogger.Info("Removing movie from trakt.tv collection, movie no longer exists locally. Title = '{0}', Year = '{1}', IMDb ID = '{2}', TMDb ID = '{3}'", s.Title, s.Year.HasValue ? s.Year.ToString() : "<empty>", s.Ids.Imdb ?? "<empty>", s.Ids.Tmdb.HasValue ? s.Ids.Tmdb.ToString() : "<empty>")); // remove title/year such that match against online ID only if (TraktSettings.SkipMoviesWithNoIdsOnSync) { pagedMovies.ForEach(m => { m.Title = null; m.Year = null; }); } var response = TraktAPI.TraktAPI.RemoveMoviesFromCollecton(new TraktSyncMovies { Movies = pagedMovies }); TraktLogger.LogTraktResponse(response); } } } #endregion } TraktLogger.Info("My Videos Library Sync Completed"); }
/// <summary> /// Shows the Rate Dialog after playback has ended /// </summary> /// <param name="episode">The item being rated</param> private void ShowRateDialog(ITrackingInfo videoInfo) { if (!TraktSettings.ShowRateDialogOnWatched) { return; } var rateThread = new Thread((objInfo) => { var itemToRate = objInfo as ITrackingInfo; if (itemToRate == null) { return; } int rating = -1; if (itemToRate.VideoKind == VideoKind.TvSeries) { TraktLogger.Info("Showing rate dialog for episode. Title = '{0}', Year = '{1}', IMDb ID = '{2}', TMDb ID = '{3}', Season = '{4}', Episode = '{5}'", itemToRate.Title, itemToRate.Year == 0 ? "<empty>" : itemToRate.Year.ToString(), itemToRate.ID_IMDB.ToLogString(), itemToRate.ID_TMDB.ToLogString(), itemToRate.Episode, itemToRate.Season); // this gets complicated when the episode IDs are not available! var rateObject = new TraktSyncShowRatedEx { Ids = new TraktShowId { Tvdb = itemToRate.ID_TVDB.ToNullableInt32(), Tmdb = itemToRate.ID_TMDB.ToNullableInt32() }, Title = itemToRate.Title, Year = itemToRate.Year > 0 ? (int?)itemToRate.Year : null, Seasons = new List <TraktSyncShowRatedEx.Season> { new TraktSyncShowRatedEx.Season { Number = (int)itemToRate.Season, Episodes = new List <TraktSyncShowRatedEx.Season.Episode> { new TraktSyncShowRatedEx.Season.Episode { Number = (int)itemToRate.Episode, RatedAt = DateTime.UtcNow.ToISO8601() } } } } }; // get the rating submitted to trakt rating = GUIUtils.ShowRateDialog <TraktSyncShowRatedEx>(rateObject); // add episode rated to cache if (rating > 0) { TraktCache.AddEpisodeToRatings( new TraktShow { Ids = rateObject.Ids, Title = rateObject.Title, Year = rateObject.Year, }, new TraktEpisode { Ids = new TraktEpisodeId(), Season = rateObject.Seasons[0].Number, Number = rateObject.Seasons[0].Episodes[0].Number }, rating ); } } else if (itemToRate.VideoKind == VideoKind.Movie) { TraktLogger.Info("Showing rate dialog for movie. Title = '{0}', Year = '{1}', IMDb Id = '{2}', TMDb ID = '{3}'", itemToRate.Title, itemToRate.Year, itemToRate.ID_IMDB.ToLogString(), itemToRate.ID_TMDB.ToLogString()); var rateObject = new TraktSyncMovieRated { Ids = new TraktMovieId { Imdb = itemToRate.ID_IMDB, Tmdb = itemToRate.ID_TMDB.ToNullableInt32() }, Title = itemToRate.Title, Year = (int)itemToRate.Year, RatedAt = DateTime.UtcNow.ToISO8601() }; // get the rating submitted to trakt rating = GUIUtils.ShowRateDialog <TraktSyncMovieRated>(rateObject); // add movie rated to cache if (rating > 0) { TraktCache.AddMovieToRatings(rateObject, rating); } else { TraktCache.RemoveMovieFromRatings(rateObject); } } }) { Name = "Rate", IsBackground = true }; rateThread.Start(videoInfo); }
protected override void OnShowContextMenu() { var selectedItem = this.Facade.SelectedListItem; if (selectedItem == null) { return; } var selectedEpisode = selectedItem.TVTag as TraktEpisodeSummary; if (selectedEpisode == null) { return; } var dlg = (IDialogbox)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU); if (dlg == null) { return; } dlg.Reset(); dlg.SetHeading(GUIUtils.PluginName()); GUIListItem listItem = null; listItem = new GUIListItem(Translation.Trailers); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Trailers; if (selectedEpisode.IsWatched(Show)) { listItem = new GUIListItem(Translation.MarkAsUnWatched); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.MarkAsUnWatched; } else { listItem = new GUIListItem(Translation.MarkAsWatched); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.MarkAsWatched; } if (selectedEpisode.IsCollected(Show)) { listItem = new GUIListItem(Translation.RemoveFromLibrary); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.RemoveFromLibrary; } else { listItem = new GUIListItem(Translation.AddToLibrary); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.AddToLibrary; } if (selectedEpisode.IsWatchlisted()) { listItem = new GUIListItem(Translation.RemoveFromWatchList); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.RemoveFromWatchList; } else { listItem = new GUIListItem(Translation.AddEpisodeToWatchList); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.AddToWatchList; } // Add to Custom List listItem = new GUIListItem(Translation.AddToList); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.AddToList; // Rate listItem = new GUIListItem(Translation.Rate + "..."); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Rate; // Shouts listItem = new GUIListItem(Translation.Comments); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Shouts; // Change Layout listItem = new GUIListItem(Translation.ChangeLayout); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.ChangeLayout; if (TraktHelper.IsMpNZBAvailableAndEnabled) { // Search for show with mpNZB listItem = new GUIListItem(Translation.SearchWithMpNZB); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.SearchWithMpNZB; } if (TraktHelper.IsMyTorrentsAvailableAndEnabled) { // Search for show with MyTorrents listItem = new GUIListItem(Translation.SearchTorrent); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.SearchTorrent; } // Show Context Menu dlg.DoModal(GUIWindowManager.ActiveWindow); if (dlg.SelectedId < 0) { return; } switch (dlg.SelectedId) { case ((int)ContextMenuItem.Trailers): GUICommon.ShowTVShowTrailersMenu(Show, selectedEpisode); break; case ((int)ContextMenuItem.MarkAsWatched): TraktHelper.AddEpisodeToWatchHistory(selectedEpisode); TraktCache.AddEpisodeToWatchHistory(Show, selectedEpisode); Facade.SelectedListItem.IsPlayed = true; OnEpisodeSelected(Facade.SelectedListItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.MarkAsUnWatched): TraktHelper.RemoveEpisodeFromWatchHistory(selectedEpisode); TraktCache.RemoveEpisodeFromWatchHistory(Show, selectedEpisode); Facade.SelectedListItem.IsPlayed = false; OnEpisodeSelected(Facade.SelectedListItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.AddToLibrary): TraktHelper.AddEpisodeToCollection(selectedEpisode); TraktCache.AddEpisodeToCollection(Show, selectedEpisode); OnEpisodeSelected(selectedItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.RemoveFromLibrary): TraktHelper.RemoveEpisodeFromCollection(selectedEpisode); TraktCache.RemoveEpisodeFromCollection(Show, selectedEpisode); OnEpisodeSelected(selectedItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.AddToWatchList): TraktHelper.AddEpisodeToWatchList(selectedEpisode); TraktCache.AddEpisodeToWatchlist(Show, selectedEpisode); OnEpisodeSelected(selectedItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.RemoveFromWatchList): TraktHelper.RemoveEpisodeFromWatchList(selectedEpisode); OnEpisodeSelected(selectedItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.Rate): GUICommon.RateEpisode(Show, selectedEpisode); OnEpisodeSelected(Facade.SelectedListItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.AddToList): TraktHelper.AddRemoveEpisodeInUserList(selectedEpisode, false); break; case ((int)ContextMenuItem.Shouts): TraktHelper.ShowEpisodeShouts(Show, selectedEpisode); break; case ((int)ContextMenuItem.ChangeLayout): CurrentLayout = GUICommon.ShowLayoutMenu(CurrentLayout, PreviousSelectedIndex); break; case ((int)ContextMenuItem.SearchWithMpNZB): string loadingParam = string.Format("search:{0} S{1}E{2}", Show.Title, selectedEpisode.Season.ToString("D2"), selectedEpisode.Number.ToString("D2")); GUIWindowManager.ActivateWindow((int)ExternalPluginWindows.MpNZB, loadingParam); break; case ((int)ContextMenuItem.SearchTorrent): string loadPar = string.Format("{0} S{1}E{2}", Show.Title, selectedEpisode.Season.ToString("D2"), selectedEpisode.Number.ToString("D2")); GUIWindowManager.ActivateWindow((int)ExternalPluginWindows.MyTorrents, loadPar); break; default: break; } base.OnShowContextMenu(); }
private string CreateLookupKey(TraktCache.Episode episode) { string show = null; if (episode.ShowTvdbId != null) { show = episode.ShowTvdbId.Value.ToString(); } else if (episode.ShowImdbId != null) { show = episode.ShowImdbId; } else { if (episode.ShowTitle == null) return episode.GetHashCode().ToString(); show = episode.ShowTitle + "_" + episode.ShowYear ?? string.Empty; } return string.Format("{0}_{1}_{2}", show, episode.Season, episode.Number); }
private bool EpisodeMatch(DBEpisode localEpisode, TraktCache.Episode onlineEpisode) { // check if we can match by TVDb ID, this is the best and logical first choice if (onlineEpisode.ShowTvdbId != null && onlineEpisode.ShowTvdbId > 0) { return localEpisode[DBOnlineEpisode.cSeriesID] == onlineEpisode.ShowTvdbId && localEpisode[DBOnlineEpisode.cSeasonIndex] == onlineEpisode.Season && localEpisode[DBOnlineEpisode.cEpisodeIndex] == onlineEpisode.Number; } // next try show IMDb ID else if (BasicHandler.IsValidImdb(onlineEpisode.ShowImdbId)) { var show = Helper.getCorrespondingSeries(localEpisode[DBOnlineEpisode.cSeriesID]); if (show == null) return false; return BasicHandler.GetProperImdbId(show[DBOnlineSeries.cIMDBID]) == onlineEpisode.ShowImdbId && localEpisode[DBOnlineEpisode.cSeasonIndex] == onlineEpisode.Season && localEpisode[DBOnlineEpisode.cEpisodeIndex] == onlineEpisode.Number; } // finially lookup by Title / Year else { var show = Helper.getCorrespondingSeries(localEpisode[DBOnlineEpisode.cSeriesID]); if (show == null) return false; return BasicHandler.IsTitleMatch(show[DBOnlineSeries.cOriginalName], onlineEpisode.ShowTitle, show.Year.ToNullableInt32()) && show.Year.ToNullableInt32() == onlineEpisode.ShowYear && localEpisode[DBOnlineEpisode.cSeasonIndex] == onlineEpisode.Season && localEpisode[DBOnlineEpisode.cEpisodeIndex] == onlineEpisode.Number; } }
private void CopyList(TraktListDetail sourceList, TraktList newList) { var copyList = new CopyList { Username = CurrentUser, Source = sourceList, Destination = newList }; var copyThread = new Thread((obj) => { var copyParams = obj as CopyList; // first create new list TraktLogger.Info("Creating new list online. Privacy = '{0}', Name = '{1}'", copyParams.Destination.Privacy, copyParams.Destination.Name); var response = TraktAPI.TraktAPI.CreateCustomList(copyParams.Destination); if (response == null || response.Ids == null) { TraktLogger.Error("Failed to create user list. List Name = '{0}'", copyParams.Destination.Name); return; } // get items from other list var userListItems = TraktAPI.TraktAPI.GetUserListItems(copyParams.Source.User.Ids.Slug, copyParams.Source.Ids.Trakt.ToString(), "min"); if (userListItems == null) { TraktLogger.Error("Failed to get user list items. List Name = '{0}', ID = '{1}'", copyParams.Destination.Name, copyParams.Source.Ids.Trakt); return; } // copy items to new list var itemsToAdd = new TraktSyncAll(); foreach (var item in userListItems) { var listItem = new TraktListItem(); listItem.Type = item.Type; switch (item.Type) { case "movie": if (itemsToAdd.Movies == null) { itemsToAdd.Movies = new List <TraktMovie>(); } itemsToAdd.Movies.Add(new TraktMovie { Ids = item.Movie.Ids }); break; case "show": if (itemsToAdd.Shows == null) { itemsToAdd.Shows = new List <TraktShow>(); } itemsToAdd.Shows.Add(new TraktShow { Ids = item.Show.Ids }); break; case "season": if (itemsToAdd.Seasons == null) { itemsToAdd.Seasons = new List <TraktSeason>(); } itemsToAdd.Seasons.Add(new TraktSeason { Ids = item.Season.Ids }); break; case "episode": if (itemsToAdd.Episodes == null) { itemsToAdd.Episodes = new List <TraktEpisode>(); } itemsToAdd.Episodes.Add(new TraktEpisode { Ids = item.Episode.Ids }); break; case "person": if (itemsToAdd.People == null) { itemsToAdd.People = new List <TraktPerson>(); } itemsToAdd.People.Add(new TraktPerson { Ids = item.Person.Ids }); break; } } // add items to the list var ItemsAddedResponse = TraktAPI.TraktAPI.AddItemsToList("me", response.Ids.Trakt.ToString(), itemsToAdd); if (ItemsAddedResponse != null) { TraktLists.ClearListCache(TraktSettings.Username); TraktCache.ClearCustomListCache(); // updated MovingPictures categories and filters menu if (TraktHelper.IsMovingPicturesAvailableAndEnabled) { MovingPictures.UpdateCategoriesMenu(SyncListType.CustomList); MovingPictures.UpdateFiltersMenu(SyncListType.CustomList); } } }) { Name = "CopyList", IsBackground = true }; copyThread.Start(copyList); }
/// <summary> /// Shows the Rate Dialog after playback has ended /// </summary> /// <param name="episode">The item being rated</param> internal static void ShowRateDialog(VideoInfo videoInfo) { if (!TraktSettings.ShowRateDialogOnWatched) { return; // not enabled } TraktLogger.Debug("Showing rate dialog for '{0}'", videoInfo.Title); var rateThread = new System.Threading.Thread((o) => { var itemToRate = o as VideoInfo; if (itemToRate == null) { return; } int rating = 0; if (itemToRate.Type == VideoType.Series) { var rateObject = new TraktSyncShowRatedEx { Title = itemToRate.Title, Year = itemToRate.Year.ToNullableInt32(), Seasons = new List <TraktSyncShowRatedEx.Season> { new TraktSyncShowRatedEx.Season { Number = itemToRate.SeasonIdx.ToInt(), Episodes = new List <TraktSyncShowRatedEx.Season.Episode> { new TraktSyncShowRatedEx.Season.Episode { Number = itemToRate.EpisodeIdx.ToInt(), RatedAt = DateTime.UtcNow.ToISO8601() } } } } }; // get the rating submitted to trakt rating = GUIUtils.ShowRateDialog <TraktSyncShowRatedEx>(rateObject); // add episode rated to cache if (rating > 0) { TraktCache.AddEpisodeToRatings( new TraktShow { Ids = new TraktShowId(), Title = rateObject.Title, Year = rateObject.Year, }, new TraktEpisode { Ids = new TraktEpisodeId(), Season = rateObject.Seasons[0].Number, Number = rateObject.Seasons[0].Episodes[0].Number }, rating ); } } else if (itemToRate.Type == VideoType.Movie) { var rateObject = new TraktSyncMovieRated { Ids = new TraktMovieId(), Title = itemToRate.Title, Year = itemToRate.Year.ToNullableInt32(), RatedAt = DateTime.UtcNow.ToISO8601() }; // get the rating submitted to trakt rating = GUIUtils.ShowRateDialog <TraktSyncMovieRated>(rateObject); // add movie rated to cache if (rating > 0) { TraktCache.AddMovieToRatings(rateObject, rating); } else { TraktCache.RemoveMovieFromRatings(rateObject); } } if (rating > 0) { TraktLogger.Debug("Rating {0} as {1}/10", itemToRate.Title, rating.ToString()); } }) { Name = "Rate", IsBackground = true }; rateThread.Start(videoInfo); }
protected override void OnShowContextMenu() { if (GUIBackgroundTask.Instance.IsBusy) { return; } GUIListItem selectedItem = this.Facade.SelectedListItem; if (selectedItem == null) { return; } var selectedEpisodeSummary = selectedItem.TVTag as TraktEpisodeSummaryEx; if (selectedEpisodeSummary == null) { return; } var selectedEpisode = selectedEpisodeSummary.Episode; if (selectedEpisode == null) { return; } var selectedShow = selectedEpisodeSummary.Show; if (selectedShow == null) { return; } IDialogbox dlg = (IDialogbox)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU); if (dlg == null) { return; } dlg.Reset(); dlg.SetHeading(GUIUtils.PluginName()); GUIListItem listItem = null; // Show Season Information listItem = new GUIListItem(Translation.ShowSeasonInfo); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.ShowSeasonInfo; if (!selectedEpisode.IsWatchlisted()) { listItem = new GUIListItem(Translation.AddToWatchList); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.AddToWatchList; } else { listItem = new GUIListItem(Translation.RemoveFromWatchList); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.RemoveFromWatchList; } // Add to Custom List listItem = new GUIListItem(Translation.AddToList); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.AddToList; // Mark As Watched if (!selectedEpisode.IsWatched(selectedShow)) { listItem = new GUIListItem(Translation.MarkAsWatched); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.MarkAsWatched; } // Mark As UnWatched if (selectedEpisode.IsWatched(selectedShow)) { listItem = new GUIListItem(Translation.MarkAsUnWatched); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.MarkAsUnWatched; } // Add to Library // Don't allow if it will be removed again on next sync // movie could be part of a DVD collection if (!selectedEpisode.IsCollected(selectedShow) && !TraktSettings.KeepTraktLibraryClean) { listItem = new GUIListItem(Translation.AddToLibrary); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.AddToLibrary; } if (selectedEpisode.IsCollected(selectedShow)) { listItem = new GUIListItem(Translation.RemoveFromLibrary); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.RemoveFromLibrary; } // Related Shows listItem = new GUIListItem(Translation.RelatedShows); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Related; // Rate Episode listItem = new GUIListItem(Translation.RateEpisode); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Rate; // Shouts listItem = new GUIListItem(Translation.Comments); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Shouts; if (TraktHelper.IsTrailersAvailableAndEnabled) { // Trailers listItem = new GUIListItem(Translation.Trailers); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Trailers; } // Change Layout listItem = new GUIListItem(Translation.ChangeLayout); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.ChangeLayout; if (!selectedEpisode.IsCollected(selectedShow) && TraktHelper.IsMpNZBAvailableAndEnabled) { // Search for movie with mpNZB listItem = new GUIListItem(Translation.SearchWithMpNZB); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.SearchWithMpNZB; } if (!selectedEpisode.IsCollected(selectedShow) && TraktHelper.IsMyTorrentsAvailableAndEnabled) { // Search for movie with MyTorrents listItem = new GUIListItem(Translation.SearchTorrent); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.SearchTorrent; } // Show Context Menu dlg.DoModal(GUIWindowManager.ActiveWindow); if (dlg.SelectedId < 0) { return; } switch (dlg.SelectedId) { case ((int)ContextMenuItem.ShowSeasonInfo): GUIWindowManager.ActivateWindow((int)TraktGUIWindows.ShowSeasons, selectedShow.ToJSON()); break; case ((int)ContextMenuItem.MarkAsWatched): TraktHelper.AddEpisodeToWatchHistory(selectedEpisode); TraktCache.AddEpisodeToWatchHistory(selectedShow, selectedEpisode); selectedItem.IsPlayed = true; OnEpisodeSelected(selectedItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.MarkAsUnWatched): TraktHelper.RemoveEpisodeFromWatchHistory(selectedEpisode); TraktCache.RemoveEpisodeFromWatchHistory(selectedShow, selectedEpisode); selectedItem.IsPlayed = false; OnEpisodeSelected(selectedItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.AddToWatchList): TraktHelper.AddEpisodeToWatchList(selectedEpisode); TraktCache.AddEpisodeToWatchlist(selectedShow, selectedEpisode); OnEpisodeSelected(selectedItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.RemoveFromWatchList): TraktHelper.RemoveEpisodeFromWatchList(selectedEpisode); OnEpisodeSelected(selectedItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.AddToList): TraktHelper.AddRemoveEpisodeInUserList(selectedEpisode, false); break; case ((int)ContextMenuItem.Trailers): GUICommon.ShowTVShowTrailersMenu(selectedShow, selectedEpisode); break; case ((int)ContextMenuItem.AddToLibrary): TraktHelper.AddEpisodeToCollection(selectedEpisode); TraktCache.AddEpisodeToCollection(selectedShow, selectedEpisode); OnEpisodeSelected(selectedItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.RemoveFromLibrary): TraktHelper.RemoveEpisodeFromCollection(selectedEpisode); TraktCache.RemoveEpisodeFromCollection(selectedShow, selectedEpisode); OnEpisodeSelected(selectedItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.Related): TraktHelper.ShowRelatedShows(selectedShow); break; case ((int)ContextMenuItem.Rate): GUICommon.RateEpisode(selectedShow, selectedEpisode); OnEpisodeSelected(selectedItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.Shouts): TraktHelper.ShowEpisodeShouts(selectedShow, selectedEpisode); break; case ((int)ContextMenuItem.ChangeLayout): CurrentLayout = GUICommon.ShowLayoutMenu(CurrentLayout, PreviousSelectedIndex); break; case ((int)ContextMenuItem.SearchWithMpNZB): string loadingParam = string.Format("search:{0} S{1}E{2}", selectedShow.Title, selectedEpisode.Season.ToString("D2"), selectedEpisode.Number.ToString("D2")); GUIWindowManager.ActivateWindow((int)ExternalPluginWindows.MpNZB, loadingParam); break; case ((int)ContextMenuItem.SearchTorrent): string loadPar = string.Format("{0} S{1}E{2}", selectedShow.Title, selectedEpisode.Season.ToString("D2"), selectedEpisode.Number.ToString("D2")); GUIWindowManager.ActivateWindow((int)ExternalPluginWindows.MyTorrents, loadPar); break; default: break; } base.OnShowContextMenu(); }
private void TestAccount(TraktAuthentication account) { TraktUserToken response = null; if (NewAccount) { // No longer supported with v2 API. //if (lblTestConnect != null) // GUIControl.SetControlLabel(GetID, lblTestConnect.GetID, Translation.CreatingAccount); //GUIWindowManager.Process(); //response = TraktAPI.v1.TraktAPI.CreateAccount(account); } else { if (lblTestConnect != null) { GUIControl.SetControlLabel(GetID, lblTestConnect.GetID, Translation.SigningIntoAccount); } GUIWindowManager.Process(); response = TraktAPI.TraktAPI.Login(account.ToJSON()); } if (response == null || string.IsNullOrEmpty(response.Token)) { GUIUtils.ShowNotifyDialog(Translation.Error, Translation.FailedLogin); if (lblTestConnect != null) { GUIControl.SetControlLabel(GetID, lblTestConnect.GetID, string.Empty); } } else { // Save User Token TraktAPI.TraktAPI.UserToken = response.Token; // Save New Account Settings TraktSettings.Username = account.Username; TraktSettings.Password = account.Password; if (!TraktSettings.UserLogins.Exists(u => u.Username == TraktSettings.Username)) { TraktSettings.UserLogins.Add(new TraktAuthentication { Username = TraktSettings.Username, Password = TraktSettings.Password }); } TraktSettings.AccountStatus = ConnectionState.Connected; HideAccountControls(); InitProperties(); // clear caches // watchlists are stored by user so dont need clearing. GUINetwork.ClearCache(); GUICalendar.ClearCache(); GUIRecommendationsMovies.ClearCache(); GUIRecommendationsShows.ClearCache(); // clear any stored user data TraktCache.ClearSyncCache(); } }
protected override void OnShowContextMenu() { var dlg = (IDialogbox)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU); if (dlg == null) { return; } dlg.Reset(); dlg.SetHeading(GUIUtils.PluginName()); var selectedItem = Facade.SelectedListItem as GUIEpisodeListItem; if (selectedItem == null) { return; } var calendarItem = selectedItem.TVTag as TraktShowCalendar; if (calendarItem == null) { return; } // Create Views Menu Item var listItem = new GUIListItem(Translation.ChangeView); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.View; // Start Date listItem = new GUIListItem(Translation.StartDate + "..."); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.StartDate; // Max Days listItem = new GUIListItem(Translation.MaxDays + "..."); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.MaxDays; // Show Season Information listItem = new GUIListItem(Translation.ShowSeasonInfo); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.ShowSeasonInfo; // Hide Show listItem = new GUIListItem(Translation.HideShow); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.HideShow; // Hide Season //listItem = new GUIListItem(Translation.HideSeason); //dlg.Add(listItem); //listItem.ItemId = (int)ContextMenuItem.HideSeason; // Related Shows listItem = new GUIListItem(Translation.RelatedShows); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Related; // Rate listItem = new GUIListItem(Translation.Rate + "..."); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Rate; // Mark As Watched if (!calendarItem.Episode.IsWatched(calendarItem.Show)) { listItem = new GUIListItem(Translation.MarkAsWatched); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.MarkAsWatched; } // Mark As UnWatched if (calendarItem.Episode.IsWatched(calendarItem.Show)) { listItem = new GUIListItem(Translation.MarkAsUnWatched); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.MarkAsUnWatched; } // Add/Remove Show Watchlist if (!calendarItem.Show.IsWatchlisted()) { listItem = new GUIListItem(Translation.AddShowToWatchList); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.AddShowToWatchList; } else { listItem = new GUIListItem(Translation.RemoveShowFromWatchList); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.RemoveShowFromWatchList; } // Add/Remove Episode Watchlist if (!calendarItem.Episode.IsWatchlisted()) { listItem = new GUIListItem(Translation.AddEpisodeToWatchList); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.AddEpisodeToWatchList; } else { listItem = new GUIListItem(Translation.RemoveEpisodeFromWatchList); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.RemoveEpisodeFromWatchList; } // Add Show to Custom List listItem = new GUIListItem(Translation.AddShowToList + "..."); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.AddShowToList; // Add Episode to Custom List listItem = new GUIListItem(Translation.AddEpisodeToList + "..."); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.AddEpisodeToList; // Shouts listItem = new GUIListItem(Translation.Comments); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Shouts; // Add/Remove Libary if (!calendarItem.Episode.IsCollected(calendarItem.Show)) { listItem = new GUIListItem(Translation.AddToLibrary); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.AddToLibrary; } else { listItem = new GUIListItem(Translation.RemoveFromLibrary); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.RemoveFromLibrary; } // Cast and Crew listItem = new GUIListItem(Translation.Cast); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Cast; listItem = new GUIListItem(Translation.Crew); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Crew; if (TraktHelper.IsTrailersAvailableAndEnabled) { listItem = new GUIListItem(Translation.Trailers); dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.Trailers; } // Watchlist Filter if (CurrentCalendar == CalendarType.UserShows) { if (TraktSettings.CalendarHideTVShowsInWatchList) { listItem = new GUIListItem(Translation.ShowTVShowsInWatchlist); } else { listItem = new GUIListItem(Translation.HideTVShowsInWatchlist); } dlg.Add(listItem); listItem.ItemId = (int)ContextMenuItem.WatchlistFilter; } // Show Context Menu dlg.DoModal(GUIWindowManager.ActiveWindow); if (dlg.SelectedId < 0) { return; } switch (dlg.SelectedId) { case ((int)ContextMenuItem.View): ShowViewMenu(); break; case ((int)ContextMenuItem.StartDate): ShowStartDateMenu(); break; case ((int)ContextMenuItem.MaxDays): ShowMaxDaysMenu(); break; case ((int)ContextMenuItem.HideShow): TraktHelper.AddHiddenShow(calendarItem.Show, "calendar"); FilterHiddenShows = true; LoadCalendar(); break; case ((int)ContextMenuItem.HideSeason): break; case ((int)ContextMenuItem.ShowSeasonInfo): GUIWindowManager.ActivateWindow((int)TraktGUIWindows.ShowSeasons, calendarItem.Show.ToJSON()); break; case ((int)ContextMenuItem.Related): TraktHelper.ShowRelatedShows(calendarItem.Show); break; case ((int)ContextMenuItem.Shouts): TraktHelper.ShowEpisodeShouts(calendarItem.Show, calendarItem.Episode); break; case ((int)ContextMenuItem.Rate): GUICommon.RateEpisode(calendarItem.Show, calendarItem.Episode); OnEpisodeSelected(Facade.SelectedListItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.MarkAsWatched): TraktHelper.AddEpisodeToWatchHistory(calendarItem.Episode); TraktCache.AddEpisodeToWatchHistory(calendarItem.Show, calendarItem.Episode); Facade.SelectedListItem.IsPlayed = true; OnEpisodeSelected(Facade.SelectedListItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.MarkAsUnWatched): TraktHelper.RemoveEpisodeFromWatchHistory(calendarItem.Episode); TraktCache.RemoveEpisodeFromWatchHistory(calendarItem.Show, calendarItem.Episode); Facade.SelectedListItem.IsPlayed = false; OnEpisodeSelected(Facade.SelectedListItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.AddShowToWatchList): TraktHelper.AddShowToWatchList(calendarItem.Show); OnEpisodeSelected(Facade.SelectedListItem, Facade); GUIWatchListShows.ClearCache(TraktSettings.Username); break; case ((int)ContextMenuItem.AddEpisodeToWatchList): TraktHelper.AddEpisodeToWatchList(calendarItem.Episode); TraktCache.AddEpisodeToWatchlist(calendarItem.Show, calendarItem.Episode); OnEpisodeSelected(Facade.SelectedListItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); GUIWatchListShows.ClearCache(TraktSettings.Username); break; case ((int)ContextMenuItem.RemoveShowFromWatchList): TraktHelper.RemoveShowFromWatchList(calendarItem.Show); OnEpisodeSelected(Facade.SelectedListItem, Facade); GUIWatchListShows.ClearCache(TraktSettings.Username); break; case ((int)ContextMenuItem.RemoveEpisodeFromWatchList): TraktHelper.RemoveEpisodeFromWatchList(calendarItem.Episode); OnEpisodeSelected(Facade.SelectedListItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); GUIWatchListShows.ClearCache(TraktSettings.Username); break; case ((int)ContextMenuItem.AddEpisodeToList): TraktHelper.AddRemoveEpisodeInUserList(calendarItem.Episode, false); break; case ((int)ContextMenuItem.AddShowToList): TraktHelper.AddRemoveShowInUserList(calendarItem.Show, false); break; case ((int)ContextMenuItem.AddToLibrary): TraktHelper.AddEpisodeToCollection(calendarItem.Episode); TraktCache.AddEpisodeToCollection(calendarItem.Show, calendarItem.Episode); OnEpisodeSelected(Facade.SelectedListItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.RemoveFromLibrary): TraktHelper.RemoveEpisodeFromCollection(calendarItem.Episode); TraktCache.RemoveEpisodeFromCollection(calendarItem.Show, calendarItem.Episode); OnEpisodeSelected(Facade.SelectedListItem, Facade); (Facade.SelectedListItem as GUIEpisodeListItem).Images.NotifyPropertyChanged("Screen"); break; case ((int)ContextMenuItem.Cast): GUICreditsShow.Show = calendarItem.Show; GUICreditsShow.Type = GUICreditsShow.CreditType.Cast; GUICreditsShow.Fanart = TmdbCache.GetShowBackdropFilename(selectedItem.Images.ShowImages); GUIWindowManager.ActivateWindow((int)TraktGUIWindows.CreditsShow); break; case ((int)ContextMenuItem.Crew): GUICreditsShow.Show = calendarItem.Show; GUICreditsShow.Type = GUICreditsShow.CreditType.Crew; GUICreditsShow.Fanart = TmdbCache.GetShowBackdropFilename(selectedItem.Images.ShowImages); GUIWindowManager.ActivateWindow((int)TraktGUIWindows.CreditsShow); break; case ((int)ContextMenuItem.Trailers): if (calendarItem != null) { GUICommon.ShowTVShowTrailersMenu(calendarItem.Show, calendarItem.Episode); } break; case ((int)ContextMenuItem.WatchlistFilter): TraktSettings.CalendarHideTVShowsInWatchList = !TraktSettings.CalendarHideTVShowsInWatchList; SetHideWatchlisted(); LoadCalendar(); break; default: break; } base.OnShowContextMenu(); }
private void StartSync() { SetSyncControlProperties(true); var syncThread = new Thread(() => { if (TraktSettings.AccountStatus != ConnectionState.Connected) { // stop sync SetSyncControlProperties(false); TraktSettings.AccountStatus = ConnectionState.Pending; return; } TraktLogger.Info("Library and Playback Sync started for all enabled plugins"); // get data from online and store in cache so its readily available for plugin sync // data will also be used in user activity feed on the dashboard if (!TraktCache.RefreshData()) { return; } foreach (var item in clbPlugins.CheckedItems) { try { switch (item.ToString()) { case "Moving Pictures": var movingPictures = new MovingPictures(TraktSettings.MovingPictures); movingPictures.SyncLibrary(); movingPictures.SyncProgress(); break; case "MP-TVSeries": var tvSeries = new TVSeries(TraktSettings.TVSeries); tvSeries.SyncLibrary(); tvSeries.SyncProgress(); break; case "My Videos": var myVideos = new MyVideos(TraktSettings.MyVideos); myVideos.SyncLibrary(); myVideos.SyncProgress(); break; case "My Films": var myFilms = new MyFilmsHandler(TraktSettings.MyFilms); myFilms.SyncLibrary(); myFilms.SyncProgress(); break; } } catch (Exception ex) { TraktLogger.Error("Error synchronising library, Plugin = '{0}', Error = '{1}'", item.ToString(), ex.Message); continue; } } // save user activity cache TraktCache.Save(); TraktLogger.Info("Library and Playback Sync completed for all enabled plugins"); SetSyncControlProperties(false); if (SilentMode || AutoCloseAfterSync) { CloseConfig(); } }) { Name = "Sync", IsBackground = true }; syncThread.Start(); }