private void CreateList(TraktList list)
        {
            GUIBackgroundTask.Instance.ExecuteInBackgroundAndCallback(() =>
            {
                return(TraktAPI.TraktAPI.CreateCustomList(list));
            },
                                                                      delegate(bool success, object result)
            {
                if (success)
                {
                    var response = result as TraktListDetail;
                    if (response != null)
                    {
                        // add to MovingPictures categories and filters menu
                        if (TraktHelper.IsMovingPicturesAvailableAndEnabled)
                        {
                            // not very thread safe if we tried to add more than one before response!
                            TraktHandlers.MovingPictures.AddCustomListNode(list.Name);
                        }

                        // reload with new list
                        TraktLists.ClearListCache(TraktSettings.Username);
                        LoadLists();
                    }
                    else
                    {
                        GUIUtils.ShowNotifyDialog(Translation.Lists, Translation.FailedCreateList);
                    }
                }
            }, Translation.CreatingList, true);
        }
Beispiel #2
0
        public async Task <TraktList> Update(TraktList model)
        {
            _appDbContext.TraktLists.Update(model);
            await _appDbContext.SaveChangesAsync();

            return(model);
        }
        private void DeleteList(TraktUserList list)
        {
            if (!GUIUtils.ShowYesNoDialog(Translation.Lists, Translation.ConfirmDeleteList, false))
            {
                return;
            }

            GUIBackgroundTask.Instance.ExecuteInBackgroundAndCallback(() =>
            {
                TraktLogger.Info("Deleting list '{0}'", list.Name);
                TraktList deleteList = new TraktList {
                    UserName = TraktSettings.Username, Password = TraktSettings.Password, Slug = list.Slug
                };
                return(TraktAPI.TraktAPI.ListDelete(deleteList));
            },
                                                                      delegate(bool success, object result)
            {
                if (success)
                {
                    TraktResponse response = result as TraktResponse;
                    TraktLogger.LogTraktResponse <TraktResponse>(response);
                    if (response.Status == "success")
                    {
                        // reload with new list
                        TraktLists.ClearCache(TraktSettings.Username);
                        LoadLists();
                    }
                    else
                    {
                        GUIUtils.ShowNotifyDialog(Translation.Lists, response.Error);
                    }
                }
            }, Translation.DeletingList, true);
        }
 private void EditList(TraktList list)
 {
     GUIBackgroundTask.Instance.ExecuteInBackgroundAndCallback(() =>
     {
         return(TraktAPI.TraktAPI.ListUpdate(list));
     },
                                                               delegate(bool success, object result)
     {
         if (success)
         {
             TraktResponse response = result as TraktResponse;
             TraktLogger.LogTraktResponse <TraktResponse>(response);
             if (response.Status == "success")
             {
                 // reload with new list
                 TraktLists.ClearCache(TraktSettings.Username);
                 LoadLists();
             }
             else
             {
                 GUIUtils.ShowNotifyDialog(Translation.Lists, response.Error);
             }
         }
     }, Translation.EditingList, true);
 }
Beispiel #5
0
        public async Task <TraktList> Create(TraktList model)
        {
            await PrepareForApiRequest(model.Owner);

            var response = await _traktClient.Users.CreateCustomListAsync(
                "me",
                model.Name,
                $"{Constants.LIST_Description}\r\n\r\n{model.GetDescriptionText()}",
                TraktAccessScope.Public,
                false,
                false
                );

            if (!response.IsSuccess)
            {
                throw response.Exception;
            }

            model.Id            = response.Value.Ids.Trakt;
            model.Slug          = response.Value.Ids.Slug;
            model.LastProcessed = DateTime.Now;
            model.Process       = true;

            return(model);
        }
        public async Task <TraktList> Create(TraktList model)
        {
            appDbContext.TraktLists.Add(model);
            await appDbContext.SaveChangesAsync();

            return(model);
        }
Beispiel #7
0
        private async Task GetMovies(TraktList model, IList <ITraktMovie> list, uint?page = 0)
        {
            var result = await _traktClient.Users.GetCustomListItemsAsync(
                model.Owner.UserName,
                model.Slug,
                TraktListItemType.Movie,
                new TraktExtendedInfo().SetMetadata(),
                new TraktPagedParameters(
                    page,
                    _traktApiConfiguration.FetchLimitList
                    )
                );

            if (!result.IsSuccess)
            {
                throw result.Exception;
            }

            foreach (var traktSearchResult in result.Value)
            {
                list.Add(traktSearchResult.Movie);
            }

            if (result.PageCount > page)
            {
                await Task.Delay(_traktApiConfiguration.DelayList);
                await GetMovies(model, list, page + 1);
            }
        }
Beispiel #8
0
 public TraktItem(TraktSearchResult searchResult)
 {
     if (searchResult.Type == TraktSearchResultType.Movie)
     {
         Type  = TraktItemType.Movie;
         Movie = searchResult.Movie;
     }
     else if (searchResult.Type == TraktSearchResultType.Show)
     {
         Type = TraktItemType.Show;
         Show = searchResult.Show;
     }
     else if (searchResult.Type == TraktSearchResultType.Episode)
     {
         Type    = TraktItemType.Episode;
         Show    = searchResult.Show;
         Episode = searchResult.Episode;
     }
     else if (searchResult.Type == TraktSearchResultType.List)
     {
         Type = TraktItemType.List;
         Show = searchResult.Show;
         List = searchResult.List;
     }
 }
Beispiel #9
0
        public async Task <IList <ITraktShow> > ShowSearch(TraktList model)
        {
            var list = new List <ITraktShow>();

            await ShowSearch(model, list);

            return(list);
        }
Beispiel #10
0
        public async Task <IList <ITraktMovie> > MovieSearch(TraktList model)
        {
            var list = new List <ITraktMovie>();

            await MovieSearch(model, list);

            return(list);
        }
Beispiel #11
0
        public async Task <TraktList> Create(TraktList model)
        {
            model = await _traktListApiRepository.Create(model);

            model = await _traktListDbRepository.Create(model);

            return(model);
        }
Beispiel #12
0
        public async Task Delete(TraktList model, bool onlyLocal = true)
        {
            await _traktListDbRepository.Delete(model);

            if (!onlyLocal)
            {
                await _traktListApiRepository.Delete(model);
            }
        }
Beispiel #13
0
        public async Task <TraktList> Update(TraktList model, bool api = false)
        {
            if (api)
            {
                await _traktListApiRepository.Update(model);
            }

            return(await _traktListDbRepository.Update(model));
        }
        public async Task <TraktList> Create(TraktList model)
        {
            appDbContext.TraktLists.Add(model);
            await appDbContext.SaveChangesAsync();


            // Just return couse we get the id from trakt
            return(model);
        }
        public async Task <TraktList> Update(TraktList model)
        {
            appDbContext.TraktLists.Update(model);
            await appDbContext.SaveChangesAsync();


            // Just return couse we do sanatizing before
            return(model);
        }
Beispiel #16
0
        public async Task <IList <ITraktShow> > GetShows(TraktList model)
        {
            await PrepareForApiRequest(model.Owner);

            var result = new List <ITraktShow>();

            await GetShows(model, result);

            return(result);
        }
Beispiel #17
0
        /// <summary>Create an instance of <see cref="TraktList"/> from an ID</summary>
        /// <param name="listId">The list ID</param>
        /// <returns>See summary</returns>
        public static TraktList FromId(int listId)
        {
            var ret = new TraktList {
                Ids = new TraktListIds {
                    Trakt = listId
                }
            };

            return(ret);
        }
        public async Task Test_TraktCommentsModule_PostListComment_ArgumentExceptions()
        {
            ITraktList list = new TraktList
            {
                Ids = new TraktListIds
                {
                    Trakt = 2228577,
                    Slug  = "oscars-2016"
                }
            };

            ITraktListCommentPost listCommentPost = new TraktListCommentPost
            {
                List    = list,
                Comment = COMMENT_TEXT
            };

            string postJson = await TestUtility.SerializeObject(listCommentPost);

            postJson.Should().NotBeNullOrEmpty();

            TraktClient client = TestUtility.GetOAuthMockClient(POST_LIST_COMMENT_URI, postJson, COMMENT_POST_RESPONSE_JSON);

            Func <Task <TraktResponse <ITraktCommentPostResponse> > > act = () => client.Comments.PostListCommentAsync(null, COMMENT_TEXT);

            act.Should().Throw <ArgumentNullException>();

            list.Ids = null;

            act = () => client.Comments.PostListCommentAsync(list, COMMENT_TEXT);
            act.Should().Throw <ArgumentNullException>();

            list.Ids = new TraktListIds();

            act = () => client.Comments.PostListCommentAsync(list, COMMENT_TEXT);
            act.Should().Throw <ArgumentException>();

            list.Ids = new TraktListIds
            {
                Trakt = 2228577,
                Slug  = "oscars-2016"
            };

            act = () => client.Comments.PostListCommentAsync(list, null);
            act.Should().Throw <ArgumentException>();

            act = () => client.Comments.PostListCommentAsync(list, string.Empty);
            act.Should().Throw <ArgumentException>();

            const string comment = "one two three four";

            act = () => client.Comments.PostListCommentAsync(list, comment);
            act.Should().Throw <ArgumentOutOfRangeException>();
        }
 /// <summary>Add a new comment to a list. If you add a review, it needs to be at least 200 words. Also make sure to allow and encourage spoilers to be indicated in your app.</summary>
 /// <param name="list">The list</param>
 /// <param name="comment">The comment</param>
 /// <param name="spoiler">Set to <c>true</c> if the comment contains spoilers</param>
 /// <param name="review">Set to <c>true</c> if the comment is a review</param>
 /// <returns>See summary</returns>
 public async Task <TraktComment> PostListCommentAsync(TraktList list, string comment, bool?spoiler = null, bool?review = null)
 {
     return(await SendAsync(new TraktCommentsPostListRequest(Client) {
         RequestBody = new TraktListComment {
             List = list,
             Comment = comment,
             Spoiler = spoiler,
             Review = review
         }
     }));
 }
Beispiel #20
0
        /// <summary>Create an instance of <see cref="TraktList"/> from an ID</summary>
        /// <param name="listId">The list ID</param>
        /// <returns>See summary</returns>
        public static TraktList FromId(string listId)
        {
            if (string.IsNullOrEmpty(listId))
            {
                throw new ArgumentException("listId not set", "listId");
            }
            var ret = new TraktList {
                Ids = new TraktListIds {
                    Slug = listId
                }
            };

            return(ret);
        }
        public async Task RemoveShows(IEnumerable <ITraktShow> shows, TraktList list)
        {
            await PrepareForApiRequest(list.Owner);

            var result = await _traktClient.Users.RemoveCustomListItemsAsync(
                list.Owner.UserName,
                list.Slug,
                TraktUserCustomListItemsPost.Builder().AddShows(shows).Build()
                );

            if (!result.IsSuccess)
            {
                throw result.Exception;
            }
        }
        public async Task AddMovies(IList <ITraktMovie> movies, TraktList list)
        {
            await PrepareForApiRequest(list.Owner);

            var result = await _traktClient.Users.AddCustomListItemsAsync(
                list.Owner.UserName,
                list.Slug,
                TraktUserCustomListItemsPost.Builder().AddMovies(movies).Build()
                );

            if (!result.IsSuccess)
            {
                throw result.Exception;
            }
        }
Beispiel #23
0
        public async Task <TraktList> Update(TraktList model)
        {
            await PrepareForApiRequest(model.Owner);

            await _traktClient.Users.UpdateCustomListAsync(
                "me",
                model.Id.ToString(),
                model.Name,
                $"{Constants.LIST_Description}\r\n\r\n{model.GetDescriptionText()}",
                TraktAccessScope.Public,
                false,
                false
                );

            return(model);
        }
Beispiel #24
0
        public async Task AddShows(IList <ITraktShow> shows, TraktList list)
        {
            await PrepareForApiRequest(list.Owner);

            var result = await _traktClient.Users.AddCustomListItemsAsync(
                list.Owner.UserName,
                list.Slug,
                TraktUserCustomListItemsPost.Builder().AddShows(shows).Build()
                );

            if (!result.IsSuccess)
            {
                throw result.Exception;
            }

            list.Items += result.Value.Added.Shows;
        }
Beispiel #25
0
        public async Task RemoveMovies(IEnumerable <ITraktMovie> movies, TraktList list)
        {
            await PrepareForApiRequest(list.Owner);

            var result = await _traktClient.Users.RemoveCustomListItemsAsync(
                list.Owner.UserName,
                list.Slug,
                TraktUserCustomListItemsPost.Builder().AddMovies(movies).Build()
                );

            if (!result.IsSuccess)
            {
                throw result.Exception;
            }

            list.Items -= result.Value.Deleted.Movies;
        }
        private void ValidateList(TraktList list)
        {
            if (list == null)
            {
                throw new ArgumentNullException(nameof(list), "list must not be null");
            }

            if (list.Ids == null)
            {
                throw new ArgumentNullException(nameof(list.Ids), "list ids must not be null");
            }

            if (!list.Ids.HasAnyId)
            {
                throw new ArgumentException("list ids have no valid id", nameof(list.Ids));
            }
        }
        public async Task Execute(uint param)
        {
            try
            {
                traktList = await _traktService.Get(param, true);

                traktList.ScanState = ScanState.Updating;

                await _traktService.Update(traktList);

                var found = await _traktService.ShowSearch(traktList);

                var existing = await _traktService.GetShows(traktList);

                var remove = existing.Except(found, new TraktShowComparer()).ToList();
                var add    = found.Except(existing, new TraktShowComparer()).ToList();

                if (add.Any())
                {
                    foreach (var toAddChunk in add.ChunkBy(500))
                    {
                        await _traktService.AddShows(toAddChunk, traktList);
                    }
                }

                if (remove.Any())
                {
                    foreach (var toRemoveChunk in remove.ChunkBy(500))
                    {
                        await _traktService.RemoveShows(toRemoveChunk, traktList);
                    }
                }

                traktList.LastProcessed = DateTime.Now;
            }
            catch (TraktListNotFoundException)
            {
                await _traktService.Delete(new TraktList { Id = param });
            }
            finally
            {
                traktList.ScanState = ScanState.None;

                await _traktService.Update(traktList);
            }
        }
Beispiel #28
0
        private async Task GetShows(TraktList model, IList <ITraktShow> list, uint?page = 0)
        {
            var result = await _traktClient.Users.GetCustomListItemsAsync(
                model.Owner.UserName,
                model.Id.ToString(),
                TraktListItemType.Show,
                new TraktExtendedInfo().SetMetadata(),
                new TraktPagedParameters(
                    page,
                    _traktApiConfiguration.FetchLimitList
                    )
                );

            if (!result.IsSuccess)
            {
                throw result.Exception;
            }

            foreach (var traktSearchResult in result.Value)
            {
                if (traktSearchResult.Show.Year.HasValue && traktSearchResult.Show.Year.ToString().Length == 1)
                {
                    traktSearchResult.Show.Year *= 1000;
                }

                if (traktSearchResult.Show.Year.HasValue && traktSearchResult.Show.Year.ToString().Length == 2)
                {
                    traktSearchResult.Show.Year *= 100;
                }

                if (traktSearchResult.Show.Year.HasValue && traktSearchResult.Show.Year.ToString().Length == 3)
                {
                    traktSearchResult.Show.Year *= 10;
                }


                list.Add(traktSearchResult.Show);
            }

            if (result.PageCount > page)
            {
                await Task.Delay(_traktApiConfiguration.DelayList);
                await GetShows(model, list, page + 1);
            }
        }
Beispiel #29
0
        public void Queue(TraktList list, bool queueNext = false, bool forceRefresh = false)
        {
            switch (list.Type)
            {
            case ListType.Movie:
                MovieList(list, queueNext, forceRefresh);

                break;

            case ListType.Show:
                ShowList(list, queueNext, forceRefresh);

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Beispiel #30
0
        public async Task <ITraktShow> ShowSearch(TraktList model, string name, int year)
        {
            var result = await _traktClient.Search.GetTextQueryResultsAsync(
                TraktSearchResultType.Show,
                name,
                null,
                new TraktSearchFilter(year, year),
                new TraktExtendedInfo().SetFull(),
                new TraktPagedParameters(null, 1)
                );

            if (!result.IsSuccess)
            {
                throw result.Exception;
            }

            return(result.Value.FirstOrDefault()?.Show);
        }
Beispiel #31
0
        public void ImportRatings()
        {
            mImportCancelled = false;

            var lRateItems = new List<Dictionary<string, string>>();
            var lWatchlistItems = new List<Dictionary<string, string>>();
            var lCustomLists = new Dictionary<string, List<Dictionary<string, string>>>();

            #region Parse Ratings CSV
            UIUtils.UpdateStatus("Reading IMDb ratings export...");
            if (mImportCsvRatings && !ParseCSVFile(mRatingsFileCsv, out lRateItems))
            {
                UIUtils.UpdateStatus("Failed to parse IMDb ratings file!", true);
                Thread.Sleep(2000);
                return;
            }
            if (mImportCancelled) return;
            #endregion

            #region Parse Watchlist CSV
            UIUtils.UpdateStatus("Reading IMDb watchlist export...");
            if (mImportCsvWatchlist && !ParseCSVFile(mWatchlistFileCsv, out lWatchlistItems))
            {
                UIUtils.UpdateStatus("Failed to parse IMDb watchlist file!", true);
                Thread.Sleep(2000);
                return;
            }
            if (mImportCancelled) return;
            #endregion

            #region Parse Custom List CSVs
            UIUtils.UpdateStatus("Reading IMDb custom lists export...");
            if (mImportCsvCustomLists)
            {
                foreach(var list in mCustomListsCsvs)
                {
                    UIUtils.UpdateStatus("Reading IMDb custom list '{0}' export...", list);
                    var lCustomList = new List<Dictionary<string, string>>();

                    if (!ParseCSVFile(list, out lCustomList))
                    {
                        UIUtils.UpdateStatus("Failed to parse IMDb custom list file!", true);
                        Thread.Sleep(2000);
                        return;
                    }

                    lCustomLists.Add(list, lCustomList);
                }
            }
            if (mImportCancelled) return;
            #endregion

            #region Import Rated Movies
            var lMovies = lRateItems.Where(r => r[IMDbFieldMapping.cType].ItemType() == IMDbType.Movie && !string.IsNullOrEmpty(r[IMDbFieldMapping.cRating])).ToList();
            FileLog.Info("Found {0} movie ratings in CSV file", lMovies.Count);
            if (lMovies.Any())
            {
                UIUtils.UpdateStatus("Retrieving existing movie ratings from trakt.tv");
                var lCurrentUserMovieRatings = TraktAPI.GetRatedMovies();

                if (lCurrentUserMovieRatings != null)
                {
                    UIUtils.UpdateStatus("Found {0} user movie ratings on trakt.tv", lCurrentUserMovieRatings.Count());
                    // Filter out movies to rate from existing ratings online
                    lMovies.RemoveAll(m => lCurrentUserMovieRatings.Any(c => c.Movie.Ids.ImdbId == m[IMDbFieldMapping.cIMDbID]));
                }

                UIUtils.UpdateStatus("Importing {0} new movie ratings to trakt.tv", lMovies.Count());

                if (lMovies.Count > 0)
                {
                    int pageSize = AppSettings.BatchSize;
                    int pages = (int)Math.Ceiling((double)lMovies.Count / pageSize);
                    for (int i = 0; i < pages; i++)
                    {
                        UIUtils.UpdateStatus("Importing page {0}/{1} IMDb rated movies...", i + 1, pages);

                        TraktSyncResponse response = TraktAPI.AddMoviesToRatings(Helper.GetRateMoviesData(lMovies.Skip(i * pageSize).Take(pageSize)));
                        if (response == null)
                        {
                            UIUtils.UpdateStatus("Error importing IMDb movie ratings to trakt.tv", true);
                            Thread.Sleep(2000);
                        }
                        else if (response.NotFound.Movies.Count > 0)
                        {
                            UIUtils.UpdateStatus("Unable to sync ratings for {0} movies as they're not found on trakt.tv!", response.NotFound.Movies.Count);
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled) return;
                    }
                }
            }
            if (mImportCancelled) return;
            #endregion

            #region Import Rated TV Shows
            var lShows = lRateItems.Where(r => r[IMDbFieldMapping.cType].ItemType() == IMDbType.Show && !string.IsNullOrEmpty(r[IMDbFieldMapping.cRating])).ToList();
            FileLog.Info("Found {0} tv show ratings in CSV file", lShows.Count);
            if (lShows.Any())
            {
                UIUtils.UpdateStatus("Retrieving existing tv show ratings from trakt.tv");
                var currentUserShowRatings = TraktAPI.GetRatedShows();

                if (currentUserShowRatings != null)
                {
                    UIUtils.UpdateStatus("Found {0} user tv show ratings on trakt.tv", currentUserShowRatings.Count());
                    // Filter out shows to rate from existing ratings online
                    lShows.RemoveAll(s => currentUserShowRatings.Any(c => (c.Show.Ids.ImdbId == s[IMDbFieldMapping.cIMDbID]) || (c.Show.Title == s[IMDbFieldMapping.cTitle] && c.Show.Year.ToString() == s[IMDbFieldMapping.cYear])));
                }

                UIUtils.UpdateStatus("Importing {0} tv show ratings to trakt.tv", lShows.Count());

                if (lShows.Count > 0)
                {
                    int pageSize = AppSettings.BatchSize;
                    int pages = (int)Math.Ceiling((double)lShows.Count / pageSize);
                    for (int i = 0; i < pages; i++)
                    {
                        UIUtils.UpdateStatus("Importing page {0}/{1} IMDb rated shows...", i + 1, pages);

                        TraktSyncResponse response = TraktAPI.AddShowsToRatings(Helper.GetRateShowsData(lShows.Skip(i * pageSize).Take(pageSize)));
                        if (response == null)
                        {
                            UIUtils.UpdateStatus("Error importing IMDb tv show ratings to trakt.tv", true);
                            Thread.Sleep(2000);
                        }
                        else if (response.NotFound.Shows.Count > 0)
                        {
                            UIUtils.UpdateStatus("Unable to sync ratings for {0} shows as they're not found on trakt.tv!", response.NotFound.Shows.Count);
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled) return;
                    }
                }
            }
            if (mImportCancelled) return;
            #endregion

            #region Import Rated Episodes
            var lImdbEpisodes = new List<IMDbEpisode>();
            var lImdbCsvEpisodes = lRateItems.Where(r => r[IMDbFieldMapping.cType].ItemType() == IMDbType.Episode).ToList();
            FileLog.Info("Found {0} tv episode ratings in CSV file", lImdbCsvEpisodes.Count);
            if (lImdbCsvEpisodes.Any())
            {
                // we can't rely on the imdb id as trakt most likely wont have the info for episodes

                // search and cache all series info needed for syncing
                // use the tvdb API to first search for each unique series name
                // then GetSeries by TVDb ID to get a list of all episodes
                // each episode will have TVDb ID which we can use for syncing.

                lImdbEpisodes.AddRange(lImdbCsvEpisodes.Select(Helper.GetIMDbEpisodeFromTVDb).Where(imdbEpisode => imdbEpisode != null));

                UIUtils.UpdateStatus("Retrieving existing tv episode ratings from trakt.tv");
                var currentUserEpisodeRatings = TraktAPI.GetRatedEpisodes();

                if (currentUserEpisodeRatings != null)
                {
                    UIUtils.UpdateStatus("Found {0} user tv episode ratings on trakt.tv", currentUserEpisodeRatings.Count());

                    // Filter out episodes to rate from existing ratings online
                    lImdbEpisodes.RemoveAll(e => currentUserEpisodeRatings.Any(c => c.Episode.Ids.TvdbId == e.TvdbId || c.Episode.Ids.ImdbId == e.ImdbId));
                }

                UIUtils.UpdateStatus("Importing {0} episode ratings to trakt.tv", lImdbEpisodes.Count());

                if (lImdbEpisodes.Count > 0)
                {
                    int pageSize = AppSettings.BatchSize;
                    int pages = (int)Math.Ceiling((double)lImdbEpisodes.Count / pageSize);
                    for (int i = 0; i < pages; i++)
                    {
                        var episodesRated = Helper.GetTraktEpisodeRateData(lImdbEpisodes.Skip(i * pageSize).Take(pageSize));

                        UIUtils.UpdateStatus("Importing page {0}/{1} IMDb rated episodes...", i + 1, pages);

                        var response = TraktAPI.AddsEpisodesToRatings(episodesRated);
                        if (response == null)
                        {
                            UIUtils.UpdateStatus("Error importing IMDb episodes ratings to trakt.tv", true);
                            Thread.Sleep(2000);
                        }
                        else if (response.NotFound.Episodes.Count > 0)
                        {
                            UIUtils.UpdateStatus("Unable to sync ratings for {0} IMDb episodes as they're not found on trakt.tv!", response.NotFound.Episodes.Count);
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled) return;
                    }
                }
            }
            if (mImportCancelled) return;
            #endregion

            #region Mark Rated Items as Watched
            IEnumerable<TraktMoviePlays> lWatchedTraktMovies = null;

            if (AppSettings.MarkAsWatched)
            {
                #region Movies
                // compare all movies rated against what's not watched on trakt
                lMovies = lRateItems.Where(r => r[IMDbFieldMapping.cType].ItemType() == IMDbType.Movie).ToList();
                FileLog.Info("Found {0} movies in CSV file", lMovies.Count);
                if (lMovies.Count > 0)
                {
                    // get watched movies from trakt.tv
                    UIUtils.UpdateStatus("Requesting watched movies from trakt...");
                    lWatchedTraktMovies = TraktAPI.GetWatchedMovies();
                    if (lWatchedTraktMovies == null)
                    {
                        UIUtils.UpdateStatus("Failed to get watched movies from trakt.tv, skipping watched movie import", true);
                        Thread.Sleep(2000);
                    }
                    else
                    {
                        if (mImportCancelled) return;

                        UIUtils.UpdateStatus("Found {0} watched movies on trakt", lWatchedTraktMovies.Count());
                        UIUtils.UpdateStatus("Filtering out watched movies that are already watched on trakt.tv");

                        lMovies.RemoveAll(w => lWatchedTraktMovies.FirstOrDefault(t => t.Movie.Ids.ImdbId == w[IMDbFieldMapping.cIMDbID] || (t.Movie.Title.ToLowerInvariant() == w[IMDbFieldMapping.cTitle] && t.Movie.Year.ToString() == w[IMDbFieldMapping.cYear])) != null);

                        // mark all rated movies as watched
                        UIUtils.UpdateStatus("Importing {0} IMDb movies as watched...", lMovies.Count);

                        int pageSize = AppSettings.BatchSize;
                        int pages = (int)Math.Ceiling((double)lMovies.Count / pageSize);
                        for (int i = 0; i < pages; i++)
                        {
                            UIUtils.UpdateStatus("Importing page {0}/{1} IMDb movies as watched...", i + 1, pages);

                            var response = TraktAPI.AddMoviesToWatchedHistory(Helper.GetSyncWatchedMoviesData(lMovies.Skip(i * pageSize).Take(pageSize).ToList()));
                            if (response == null)
                            {
                                UIUtils.UpdateStatus("Failed to send watched status for IMDb movies to trakt.tv", true);
                                Thread.Sleep(2000);
                            }
                            else if (response.NotFound.Movies.Count > 0)
                            {
                                UIUtils.UpdateStatus("Unable to sync watched states for {0} movies as they're not found on trakt.tv!", response.NotFound.Movies.Count);
                                Thread.Sleep(1000);
                            }
                            if (mImportCancelled) return;
                        }
                    }
                }
                #endregion

                #region Episodes
                if (lImdbEpisodes != null && lImdbEpisodes.Any())
                {
                    int pageSize = AppSettings.BatchSize;
                    int pages = (int)Math.Ceiling((double)lImdbEpisodes.Count / pageSize);
                    for (int i = 0; i < pages; i++)
                    {
                        var episodesWatched = Helper.GetTraktEpisodeWatchedData(lImdbEpisodes.Skip(i * pageSize).Take(pageSize));

                        UIUtils.UpdateStatus("Importing page {0}/{1} IMDb watched episodes...", i + 1, pages);

                        var response = TraktAPI.AddEpisodesToWatchedHistory(episodesWatched);
                        if (response == null)
                        {
                            UIUtils.UpdateStatus("Error importing IMDb episodes as watched to trakt.tv", true);
                            Thread.Sleep(2000);
                        }
                        else if (response.NotFound.Episodes.Count > 0)
                        {
                            UIUtils.UpdateStatus("Unable to sync {0} IMDb episodes as watched, as they're not found on trakt.tv!", response.NotFound.Episodes.Count);
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled) return;
                    }
                }
                #endregion
            }
            #endregion

            #region Import Watchlist Movies
            lMovies = lWatchlistItems.Where(r => r[IMDbFieldMapping.cType].ItemType() == IMDbType.Movie).ToList();
            FileLog.Info("Found {0} movies watchlisted in CSV file", lMovies.Count);
            if (lMovies.Any())
            {
                UIUtils.UpdateStatus("Requesting existing watchlist movies from trakt...");
                var watchlistTraktMovies = TraktAPI.GetWatchlistMovies();
                if (watchlistTraktMovies != null)
                {
                    UIUtils.UpdateStatus("Found {0} watchlist movies on trakt", watchlistTraktMovies.Count());
                    UIUtils.UpdateStatus("Filtering out watchlist movies that are already in watchlist on trakt.tv");
                    lMovies.RemoveAll(w => watchlistTraktMovies.FirstOrDefault(t => t.Movie.Ids.ImdbId == w[IMDbFieldMapping.cIMDbID] || (t.Movie.Title.ToLowerInvariant() == w[IMDbFieldMapping.cTitle] && t.Movie.Year.ToString() == w[IMDbFieldMapping.cYear])) != null);
                }

                if (AppSettings.IgnoreWatchedForWatchlist && lMovies.Count > 0)
                {
                    UIUtils.UpdateStatus("Requesting watched movies from trakt...");

                    // get watched movies from trakt so we don't import movies into watchlist that are already watched
                    if (lWatchedTraktMovies != null)
                    {
                        lWatchedTraktMovies = TraktAPI.GetWatchedMovies();
                        if (lWatchedTraktMovies == null)
                        {
                            UIUtils.UpdateStatus("Failed to get watched movies from trakt.tv", true);
                            Thread.Sleep(2000);
                        }
                    }

                    if (lWatchedTraktMovies != null)
                    {
                        UIUtils.UpdateStatus("Found {0} watched movies on trakt", lWatchedTraktMovies.Count());
                        UIUtils.UpdateStatus("Filtering out watchlist movies that are watched on trakt.tv");

                        // remove movies from sync list which are watched already
                        lMovies.RemoveAll(w => lWatchedTraktMovies.FirstOrDefault(t => t.Movie.Ids.ImdbId == w[IMDbFieldMapping.cIMDbID] || (t.Movie.Title.ToLowerInvariant() == w[IMDbFieldMapping.cTitle] && t.Movie.Year.ToString() == w[IMDbFieldMapping.cYear])) != null);
                    }
                }

                // add movies to watchlist
                UIUtils.UpdateStatus("Importing {0} IMDb watchlist movies to trakt.tv...", lMovies.Count());

                int pageSize = AppSettings.BatchSize;
                int pages = (int)Math.Ceiling((double)lMovies.Count / pageSize);
                for (int i = 0; i < pages; i++)
                {
                    UIUtils.UpdateStatus("Importing page {0}/{1} IMDb watchlist movies...", i + 1, pages);

                    var response = TraktAPI.AddMoviesToWatchlist(Helper.GetSyncMoviesData(lMovies.Skip(i * pageSize).Take(pageSize).ToList()));
                    if (response == null)
                    {
                        UIUtils.UpdateStatus("Failed to send watchlist for IMDb movies", true);
                        Thread.Sleep(2000);
                    }
                    else if (response.NotFound.Movies.Count > 0)
                    {
                        UIUtils.UpdateStatus("Unable to sync watchlist for {0} movies as they're not found on trakt.tv!", response.NotFound.Movies.Count);
                        Thread.Sleep(1000);
                    }

                    if (mImportCancelled) return;
                }
            }
            if (mImportCancelled) return;
            #endregion

            #region Import Watchlist TV Shows
            IEnumerable<TraktShowPlays> watchedTraktShows = null;
            lShows = lWatchlistItems.Where(r => r[IMDbFieldMapping.cType].ItemType() == IMDbType.Show).ToList();
            FileLog.Info("Found {0} tv shows watchlisted in CSV file", lShows.Count);
            if (lShows.Any())
            {
                UIUtils.UpdateStatus("Requesting existing watchlist shows from trakt...");
                var watchlistTraktShows = TraktAPI.GetWatchlistShows();
                if (watchlistTraktShows != null)
                {
                    UIUtils.UpdateStatus("Found {0} watchlist shows on trakt", watchlistTraktShows.Count());
                    UIUtils.UpdateStatus("Filtering out watchlist shows that are already in watchlist on trakt.tv");
                    lShows.RemoveAll(w => watchlistTraktShows.FirstOrDefault(t => t.Show.Ids.ImdbId == w[IMDbFieldMapping.cIMDbID] || (t.Show.Title.ToLowerInvariant() == w[IMDbFieldMapping.cTitle].ToLowerInvariant() && t.Show.Year.ToString() == w[IMDbFieldMapping.cYear])) != null);
                }

                if (AppSettings.IgnoreWatchedForWatchlist && lShows.Count > 0)
                {
                    UIUtils.UpdateStatus("Requesting watched shows from trakt...");

                    // get watched movies from trakt so we don't import shows into watchlist that are already watched
                    watchedTraktShows = TraktAPI.GetWatchedShows();
                    if (watchedTraktShows != null)
                    {
                        UIUtils.UpdateStatus("Found {0} watched shows on trakt", watchedTraktShows.Count());
                        UIUtils.UpdateStatus("Filtering out watchlist shows containing watched episodes on trakt.tv.");

                        // remove shows from sync list which are watched already
                        lShows.RemoveAll(w => watchedTraktShows.FirstOrDefault(t => (t.Show.Ids.ImdbId == w[IMDbFieldMapping.cIMDbID]) || (t.Show.Title.ToLowerInvariant() == w[IMDbFieldMapping.cTitle].ToLowerInvariant() && t.Show.Year.ToString() == w[IMDbFieldMapping.cYear])) != null);
                    }
                }

                // add shows to watchlist
                UIUtils.UpdateStatus("Importing {0} IMDb watchlist shows to trakt.tv...", lShows.Count());

                int pageSize = AppSettings.BatchSize;
                int pages = (int)Math.Ceiling((double)lShows.Count / pageSize);
                for (int i = 0; i < pages; i++)
                {
                    UIUtils.UpdateStatus("Importing page {0}/{1} IMDb watchlist shows...", i + 1, pages);

                    var response = TraktAPI.AddShowsToWatchlist(Helper.GetSyncShowsData(lShows.Skip(i * pageSize).Take(pageSize)));
                    if (response == null)
                    {
                        UIUtils.UpdateStatus("Failed to send watchlist for IMDb tv shows", true);
                        Thread.Sleep(2000);
                    }
                    else if (response.NotFound.Shows.Count > 0)
                    {
                        UIUtils.UpdateStatus("Unable to sync watchlist for {0} shows as they're not found on trakt.tv!", response.NotFound.Shows.Count);
                        Thread.Sleep(1000);
                    }

                    if (mImportCancelled) return;
                }
            }
            if (mImportCancelled) return;
            #endregion

            #region Import Watchlist Episodes
            lImdbEpisodes.Clear();
            lImdbCsvEpisodes = lWatchlistItems.Where(r => r[IMDbFieldMapping.cType].ItemType() == IMDbType.Episode).ToList();
            FileLog.Info("Found {0} tv episodes watchlisted in CSV file", lImdbCsvEpisodes.Count);
            if (lImdbCsvEpisodes.Any())
            {
                UIUtils.UpdateStatus("Found {0} IMDb watchlist episodes", lImdbCsvEpisodes.Count());

                lImdbEpisodes.AddRange(lImdbCsvEpisodes.Select(Helper.GetIMDbEpisodeFromTVDb).Where(imdbEpisode => imdbEpisode != null));

                // filter out existing watchlist episodes
                UIUtils.UpdateStatus("Requesting existing watchlist episodes from trakt...");
                var watchlistTraktEpisodes = TraktAPI.GetWatchlistEpisodes();
                if (watchlistTraktEpisodes != null)
                {
                    UIUtils.UpdateStatus("Found {0} watchlist episodes on trakt", watchlistTraktEpisodes.Count());
                    UIUtils.UpdateStatus("Filtering out watchlist episodes that are already in watchlist on trakt.tv");
                    lImdbEpisodes.RemoveAll(e => watchlistTraktEpisodes.FirstOrDefault(w => w.Episode.Ids.ImdbId == e.ImdbId || w.Episode.Ids.TvdbId == e.TvdbId) != null);
                }

                if (AppSettings.IgnoreWatchedForWatchlist && lImdbEpisodes.Count > 0)
                {
                    // we already might have it from the shows sync
                    if (watchedTraktShows == null)
                    {
                        UIUtils.UpdateStatus("Requesting watched episodes from trakt...");

                        // get watched episodes from trakt so we don't import episodes into watchlist that are already watched
                        watchedTraktShows = TraktAPI.GetWatchedShows();
                    }

                    if (watchedTraktShows != null)
                    {
                        UIUtils.UpdateStatus("Filtering out watchlist episodes containing watched episodes on trakt.tv");

                        lImdbEpisodes.RemoveAll(e => watchedTraktShows.Where(s => s.Show.Ids.ImdbId == e.ImdbId)
                                                                         .Any(s => s.Seasons.Exists(se => se.Number == e.SeasonNumber && se.Episodes.Exists(ep => ep.Number == e.EpisodeNumber))));
                    }
                }

                UIUtils.UpdateStatus("Importing {0} episodes in watchlist to trakt.tv", lImdbEpisodes.Count());

                if (lImdbEpisodes.Count > 0)
                {
                    int pageSize = AppSettings.BatchSize;
                    int pages = (int)Math.Ceiling((double)lImdbEpisodes.Count / pageSize);
                    for (int i = 0; i < pages; i++)
                    {
                        UIUtils.UpdateStatus("Importing page {0}/{1} IMDb watchlist episodes...", i + 1, pages);

                        var response = TraktAPI.AddEpisodesToWatchlist(Helper.GetTraktEpisodeData(lImdbEpisodes.Skip(i * pageSize).Take(pageSize)));
                        if (response == null)
                        {
                            UIUtils.UpdateStatus("Error importing IMDb episode watchlist to trakt.tv", true);
                            Thread.Sleep(2000);
                        }
                        else if (response.NotFound.Episodes.Count > 0)
                        {
                            UIUtils.UpdateStatus("Unable to sync watchlist for {0} IMDb episodes as they're not found on trakt.tv!", response.NotFound.Episodes.Count);
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled) return;
                    }
                }
            }
            #endregion

            #region Import Custom Lists
            if (lCustomLists.Count > 0)
            {
                UIUtils.UpdateStatus("Requesting custom lists from trakt...");
                var lTraktCustomLists = TraktAPI.GetCustomLists();
                if (lTraktCustomLists == null)
                {
                    UIUtils.UpdateStatus("Error requesting custom lists from trakt.tv", true);
                    Thread.Sleep(2000);
                    return;
                }

                UIUtils.UpdateStatus("Found {0} custom lists on trakt.tv", lTraktCustomLists.Count());

                foreach (var list in lCustomLists)
                {
                    bool lListCreated = false;
                    string lListName = Path.GetFileNameWithoutExtension(list.Key);

                    // create the list if we don't have it
                    TraktListDetail lTraktCustomList = lTraktCustomLists.FirstOrDefault(l => l.Name == lListName);

                    if (lTraktCustomList == null)
                    {
                        UIUtils.UpdateStatus("Creating new custom list '{0}' on trakt.tv", lListName);
                        var lTraktList = new TraktList
                        {
                            Name = lListName,
                            DisplayNumbers = true,
                        };

                        lTraktCustomList = TraktAPI.CreateCustomList(lTraktList);
                        if (lTraktCustomList == null)
                        {
                            UIUtils.UpdateStatus("Error creating custom list on trakt.tv, skipping list creation", true);
                            Thread.Sleep(2000);
                            continue;
                        }

                        lListCreated = true;
                    }

                    // get the CSV list items parsed
                    var lIMDbListItems = list.Value;

                    var lImdbListMovies = lIMDbListItems.Where(l => l.ItemType() == IMDbType.Movie).ToList();
                    var lImdbListShows = lIMDbListItems.Where(l => l.ItemType() == IMDbType.Show).ToList();

                    // if the list already exists, get current items for list
                    if (!lListCreated)
                    {
                        lTraktCustomList = lTraktCustomLists.FirstOrDefault(l => l.Name == lListName);

                        UIUtils.UpdateStatus("Requesting existing custom list '{0}' items from trakt...", lListName);
                        var lTraktListItems = TraktAPI.GetCustomListItems(lTraktCustomList.Ids.Trakt.ToString());
                        if (lTraktListItems == null)
                        {
                            UIUtils.UpdateStatus("Error requesting custom list items on trakt.tv, skipping list creation", true);
                            Thread.Sleep(2000);
                            continue;
                        }

                        // filter out existing items from CSV so we don't send again
                        FileLog.Info("Filtering out existing items from IMDb list '{0}' so we don't send again to trakt.tv", lListName);
                        lImdbListMovies.RemoveAll(d => d.ItemType() == IMDbType.Movie && lTraktListItems.FirstOrDefault(l => l.Movie.Ids.ImdbId == d[IMDbFieldMapping.cIMDbID]) != null);
                        lImdbListShows.RemoveAll(d => d.ItemType() == IMDbType.Show && lTraktListItems.FirstOrDefault(l => l.Show.Ids.ImdbId == d[IMDbFieldMapping.cIMDbID]) != null);
                    }

                    #region Movies

                    UIUtils.UpdateStatus("Importing {0} movies into {1} custom list...", lImdbListMovies.Count(), lListName);

                    int pageSize = AppSettings.BatchSize;
                    int pages = (int)Math.Ceiling((double)lImdbListMovies.Count / pageSize);
                    for (int i = 0; i < pages; i++)
                    {
                        UIUtils.UpdateStatus("Importing page {0}/{1} IMDb custom list movies...", i + 1, pages);

                        // create list sync object to hold list items
                        var lTraktMovieSync = new TraktSyncAll
                        {
                            Movies = Helper.GetSyncMoviesData(lImdbListMovies.Skip(i * pageSize).Take(pageSize).ToList()).Movies
                        };

                        var response = TraktAPI.AddItemsToList(lTraktCustomList.Ids.Trakt.ToString(), lTraktMovieSync);
                        if (response == null)
                        {
                            UIUtils.UpdateStatus("Failed to send custom list items for IMDb movies", true);
                            Thread.Sleep(2000);
                        }
                        else if (response.NotFound.Movies.Count > 0)
                        {
                            UIUtils.UpdateStatus("Unable to sync custom list items for {0} movies as they're not found on trakt.tv!", response.NotFound.Movies.Count);
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled) return;
                    }
                    #endregion

                    #region Shows

                    UIUtils.UpdateStatus("Importing {0} shows into {1} custom list...", lImdbListShows.Count(), lListName);

                    pageSize = AppSettings.BatchSize;
                    pages = (int)Math.Ceiling((double)lImdbListShows.Count / pageSize);
                    for (int i = 0; i < pages; i++)
                    {
                        UIUtils.UpdateStatus("Importing page {0}/{1} IMDb custom list shows...", i + 1, pages);

                        // create list sync object to hold list items
                        var lTraktShowSync = new TraktSyncAll
                        {
                            Shows = Helper.GetSyncShowsData(lImdbListShows.Skip(i * pageSize).Take(pageSize).ToList()).Shows
                        };

                        var response = TraktAPI.AddItemsToList(lTraktCustomList.Ids.Trakt.ToString(), lTraktShowSync);
                        if (response == null)
                        {
                            UIUtils.UpdateStatus("Failed to send custom list items for IMDb shows", true);
                            Thread.Sleep(2000);
                        }
                        else if (response.NotFound.Shows.Count > 0)
                        {
                            UIUtils.UpdateStatus("Unable to sync custom list items for {0} shows as they're not found on trakt.tv!", response.NotFound.Shows.Count);
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled) return;
                    }

                    #endregion
                }
            }
            #endregion
        }
Beispiel #32
0
 public static TraktListDetail CreateCustomList(TraktList list, string username = "******")
 {
     var response = TraktWeb.PostToTrakt(string.Format(TraktURIs.UserListAdd, username), list.ToJSON());
     return response.FromJSON<TraktListDetail>();
 }