Пример #1
0
        public async Task Test_TraktScrobbleModule_PauseEpisodeWithShow_And_AppDate()
        {
            ITraktEpisodeScrobblePost episodePauseScrobblePost = new TraktEpisodeScrobblePost
            {
                Episode  = Episode,
                Show     = Show,
                Progress = PAUSE_PROGRESS,
                AppDate  = APP_BUILD_DATE.ToTraktDateString()
            };

            string postJson = await TestUtility.SerializeObject(episodePauseScrobblePost);

            postJson.Should().NotBeNullOrEmpty();

            TraktClient client = TestUtility.GetOAuthMockClient(SCROBBLE_PAUSE_URI, postJson, EPISODE_PAUSE_SCROBBLE_POST_RESPONSE_JSON);

            TraktResponse <ITraktEpisodeScrobblePostResponse> response =
                await client.Scrobble.PauseEpisodeWithShowAsync(Episode, Show, PAUSE_PROGRESS, null, APP_BUILD_DATE);

            response.Should().NotBeNull();
            response.IsSuccess.Should().BeTrue();
            response.HasValue.Should().BeTrue();
            response.Value.Should().NotBeNull();

            ITraktEpisodeScrobblePostResponse responseValue = response.Value;

            responseValue.Id.Should().Be(0);
            responseValue.Action.Should().Be(TraktScrobbleActionType.Pause);
            responseValue.Progress.Should().Be(PAUSE_PROGRESS);
            responseValue.Sharing.Should().NotBeNull();
            responseValue.Sharing.Twitter.Should().BeTrue();
            responseValue.Sharing.Tumblr.Should().BeFalse();
            responseValue.Episode.Should().NotBeNull();
            responseValue.Episode.SeasonNumber.Should().Be(1);
            responseValue.Episode.Number.Should().Be(1);
            responseValue.Episode.Title.Should().Be("Pilot");
            responseValue.Episode.Ids.Should().NotBeNull();
            responseValue.Episode.Ids.Trakt.Should().Be(16U);
            responseValue.Episode.Ids.Tvdb.Should().Be(349232U);
            responseValue.Episode.Ids.Imdb.Should().Be("tt0959621");
            responseValue.Episode.Ids.Tmdb.Should().Be(62085U);
            responseValue.Episode.Ids.TvRage.Should().Be(637041U);
            responseValue.Show.Title.Should().Be("Breaking Bad");
            responseValue.Show.Year.Should().Be(2008);
            responseValue.Show.Ids.Should().NotBeNull();
            responseValue.Show.Ids.Trakt.Should().Be(1U);
            responseValue.Show.Ids.Slug.Should().Be("breaking-bad");
            responseValue.Show.Ids.Tvdb.Should().Be(81189U);
            responseValue.Show.Ids.Imdb.Should().Be("tt0903747");
            responseValue.Show.Ids.Tmdb.Should().Be(1396U);
            responseValue.Show.Ids.TvRage.Should().Be(18164U);
        }
Пример #2
0
        public async Task Test_TraktCertificationsModule_GetShowCertifications()
        {
            TraktClient client = TestUtility.GetMockClient(GET_SHOW_CERTIFICATIONS_URI, GET_SHOW_CERTIFICATIONS_JSON);
            TraktResponse <ITraktCertifications> response = await client.Certifications.GetShowCertificationsAsync();

            response.Should().NotBeNull();
            response.IsSuccess.Should().BeTrue();
            response.Value.Should().NotBeNull();
            response.HasValue.Should().BeTrue();
            response.Exception.Should().BeNull();

            ITraktCertifications certifications = response.Value;

            certifications.US.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(7);

            ITraktCertification[] certificationsUS = certifications.US.ToArray();

            certificationsUS[0].Should().NotBeNull();
            certificationsUS[0].Name.Should().Be("TV-Y");
            certificationsUS[0].Slug.Should().Be("tv-y");
            certificationsUS[0].Description.Should().Be("All Children");

            certificationsUS[1].Should().NotBeNull();
            certificationsUS[1].Name.Should().Be("TV-Y7");
            certificationsUS[1].Slug.Should().Be("tv-y7");
            certificationsUS[1].Description.Should().Be("Older Children - Ages 7+ Recommended");

            certificationsUS[2].Should().NotBeNull();
            certificationsUS[2].Name.Should().Be("TV-G");
            certificationsUS[2].Slug.Should().Be("tv-g");
            certificationsUS[2].Description.Should().Be("All Ages");

            certificationsUS[3].Should().NotBeNull();
            certificationsUS[3].Name.Should().Be("TV-PG");
            certificationsUS[3].Slug.Should().Be("tv-pg");
            certificationsUS[3].Description.Should().Be("Parental Guidance Suggested");

            certificationsUS[4].Should().NotBeNull();
            certificationsUS[4].Name.Should().Be("TV-14");
            certificationsUS[4].Slug.Should().Be("tv-14");
            certificationsUS[4].Description.Should().Be("Parents Strongly Cautioned - Ages 14+ Recommended");

            certificationsUS[5].Should().NotBeNull();
            certificationsUS[5].Name.Should().Be("TV-MA");
            certificationsUS[5].Slug.Should().Be("tv-ma");
            certificationsUS[5].Description.Should().Be("tv-ma");

            certificationsUS[6].Should().NotBeNull();
            certificationsUS[6].Name.Should().Be("Not Rated");
            certificationsUS[6].Slug.Should().Be("nr");
            certificationsUS[6].Description.Should().Be("Not Rated");
        }
Пример #3
0
        private async Task TryToDeviceAuthenticate(IDatabase database)
        {
            TraktResponse <ITraktAuthorization> authorization = await Client.Authentication.PollForAuthorizationAsync();

            if (authorization.HasValue && authorization.Value.IsValid)
            {
                SaveAuthToken(database, new TraktToken {
                    AccessToken = authorization.Value.AccessToken, RefreshToken = authorization.Value.RefreshToken
                });

                Console.WriteLine("-------------- Authentication successful --------------");
            }
        }
Пример #4
0
        /// <summary>
        /// Gets the trakt episode library for a user
        /// </summary>
        /// <param name="user">The user to get</param>
        /// <returns>The trakt episode library</returns>
        public static IEnumerable <TraktLibraryShow> GetLibraryEpisodesForUser(string user)
        {
            // Getting user's 'library' episodes from trakt
            string showsForUser = Transmit(string.Format(TraktURIs.GETUserEpisodesCollection, user), GetUserAuthentication());

            // if we timeout we will return an error response
            TraktResponse response = showsForUser.FromJSON <TraktResponse>();

            if (response == null || response.Error != null)
            {
                return(null);
            }
            return(showsForUser.FromJSONArray <TraktLibraryShow>());
        }
Пример #5
0
        private void UnfollowUser(TraktUser user)
        {
            Thread unfollowUserThread = new Thread(delegate(object obj)
            {
                TraktResponse response = TraktAPI.TraktAPI.NetworkUnFollow(CreateNetworkData(user));
                TraktLogger.LogTraktResponse <TraktResponse>(response);
            })
            {
                IsBackground = true,
                Name         = "UnfollowUser"
            };

            unfollowUserThread.Start(user);
        }
Пример #6
0
        private void DenyFollowerRequest(TraktUser user)
        {
            Thread denyFollowerRequest = new Thread(delegate(object obj)
            {
                TraktResponse response = TraktAPI.TraktAPI.NetworkDeny(CreateNetworkData(user));
                TraktLogger.LogTraktResponse <TraktResponse>(response);
            })
            {
                IsBackground = true,
                Name         = "DenyFollowerRequest"
            };

            denyFollowerRequest.Start(user);
        }
Пример #7
0
        private void ApproveFollowerRequest(TraktUser user, bool followBack = false)
        {
            Thread approveFollowerThread = new Thread(delegate(object obj)
            {
                TraktResponse response = TraktAPI.TraktAPI.NetworkApprove(CreateNetworkData(user, followBack));
                TraktLogger.LogTraktResponse <TraktResponse>(response);
            })
            {
                IsBackground = true,
                Name         = "FollowerRequest"
            };

            approveFollowerThread.Start(user);
        }
Пример #8
0
        public async Task Test_TraktUsersModule_AddCustomListItems_With_Type()
        {
            string postJson = await TestUtility.SerializeObject(AddCustomListItemsPost);

            postJson.Should().NotBeNullOrEmpty();

            TraktClient client = TestUtility.GetOAuthMockClient(
                $"{ADD_CUSTOM_LIST_ITEMS_URI}/{LIST_ITEM_TYPE.UriName}",
                postJson, CUSTOM_LIST_ITEMS_POST_RESPONSE_JSON);

            TraktResponse <ITraktUserCustomListItemsPostResponse> response =
                await client.Users.AddCustomListItemsAsync(USERNAME, LIST_ID, AddCustomListItemsPost, LIST_ITEM_TYPE);

            response.Should().NotBeNull();
            response.IsSuccess.Should().BeTrue();
            response.HasValue.Should().BeTrue();
            response.Value.Should().NotBeNull();

            ITraktUserCustomListItemsPostResponse responseValue = response.Value;

            responseValue.Added.Should().NotBeNull();
            responseValue.Added.Movies.Should().Be(1);
            responseValue.Added.Shows.Should().Be(1);
            responseValue.Added.Seasons.Should().Be(1);
            responseValue.Added.Episodes.Should().Be(2);
            responseValue.Added.People.Should().Be(1);

            responseValue.Existing.Should().NotBeNull();
            responseValue.Existing.Movies.Should().Be(0);
            responseValue.Existing.Shows.Should().Be(0);
            responseValue.Existing.Seasons.Should().Be(0);
            responseValue.Existing.Episodes.Should().Be(0);
            responseValue.Existing.People.Should().Be(0);

            responseValue.NotFound.Should().NotBeNull();
            responseValue.NotFound.Movies.Should().NotBeNull().And.HaveCount(1);

            ITraktPostResponseNotFoundMovie[] movies = responseValue.NotFound.Movies.ToArray();

            movies[0].Ids.Should().NotBeNull();
            movies[0].Ids.Trakt.Should().Be(0);
            movies[0].Ids.Slug.Should().BeNullOrEmpty();
            movies[0].Ids.Imdb.Should().Be("tt0000111");
            movies[0].Ids.Tmdb.Should().BeNull();

            responseValue.NotFound.Shows.Should().NotBeNull().And.BeEmpty();
            responseValue.NotFound.Seasons.Should().NotBeNull().And.BeEmpty();
            responseValue.NotFound.Episodes.Should().NotBeNull().And.BeEmpty();
            responseValue.NotFound.People.Should().NotBeNull().And.BeEmpty();
        }
Пример #9
0
        public async Task Test_TraktAuthenticationModule_CheckIfAuthorizationIsExpiredOrWasRevoked_With_Authorization_Failed_Revoked_AutoRefresh()
        {
            string authorizationJson = await TestUtility.SerializeObject(MockAuthorization);

            authorizationJson.Should().NotBeNullOrEmpty();

            TraktClient client = TestUtility.GetAuthenticationMockClient();

            // First response, if authorization was revoked
            TestUtility.AddMockExpectationResponse((TestHttpClientProvider)client.HttpClientProvider, CHECK_ACCESS_TOKEN_URI, HttpStatusCode.Unauthorized);

            // Second response for autoRefresh == true
            TestUtility.AddMockExpectationResponse((TestHttpClientProvider)client.HttpClientProvider, GET_AUTHORIZATION_URI, MockAuthorizationRefreshPostContent, authorizationJson);

            Pair <bool, TraktResponse <ITraktAuthorization> > responseValues = await client.Authentication.CheckIfAuthorizationIsExpiredOrWasRevokedAsync(MockAuthorization, true);

            TestUtility.VerifyNoOutstandingExpectations((TestHttpClientProvider)client.HttpClientProvider);

            responseValues.Should().NotBeNull();
            responseValues.First.Should().BeTrue();

            TraktResponse <ITraktAuthorization> response = responseValues.Second;

            response.Should().NotBeNull();
            response.IsSuccess.Should().BeTrue();
            response.HasValue.Should().BeTrue();
            response.Value.Should().NotBeNull();

            ITraktAuthorization responseAuthorization = response.Value;

            responseAuthorization.Should().NotBeNull();
            responseAuthorization.AccessToken.Should().Be(MockAuthorization.AccessToken);
            responseAuthorization.TokenType.Should().Be(MockAuthorization.TokenType);
            responseAuthorization.ExpiresInSeconds.Should().Be(MockAuthorization.ExpiresInSeconds);
            responseAuthorization.RefreshToken.Should().Be(MockAuthorization.RefreshToken);
            responseAuthorization.Scope.Should().Be(MockAuthorization.Scope);
            responseAuthorization.CreatedAt.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(1800));
            responseAuthorization.IsExpired.Should().BeFalse();

            ITraktAuthorization clientAccessToken = client.Authorization;

            clientAccessToken.Should().NotBeNull();
            clientAccessToken.AccessToken.Should().Be(responseAuthorization.AccessToken);
            clientAccessToken.TokenType.Should().Be(responseAuthorization.TokenType);
            clientAccessToken.ExpiresInSeconds.Should().Be(responseAuthorization.ExpiresInSeconds);
            clientAccessToken.RefreshToken.Should().Be(responseAuthorization.RefreshToken);
            clientAccessToken.Scope.Should().Be(responseAuthorization.Scope);
            clientAccessToken.CreatedAt.Should().Be(responseAuthorization.CreatedAt);
            clientAccessToken.IsExpired.Should().BeFalse();
        }
Пример #10
0
        public ITraktSyncCollectionRemovePostResponse RemoveCollectionItems(ITraktSyncCollectionPost collectionRemovePost)
        {
            ITraktResponse <ITraktSyncCollectionRemovePostResponse> response = new TraktResponse <ITraktSyncCollectionRemovePostResponse>();

            try
            {
                response = Task.Run(() => base.Sync.RemoveCollectionItemsAsync(collectionRemovePost)).Result;
            }
            catch (AggregateException aggregateException)
            {
                UnwrapAggregateException(aggregateException);
            }
            return(response.Value);
        }
Пример #11
0
        public ITraktSyncHistoryRemovePostResponse RemoveWatchedHistoryItems(ITraktSyncHistoryRemovePost historyRemovePost)
        {
            ITraktResponse <ITraktSyncHistoryRemovePostResponse> response = new TraktResponse <ITraktSyncHistoryRemovePostResponse>();

            try
            {
                response = Task.Run(() => base.Sync.RemoveWatchedHistoryItemsAsync(historyRemovePost)).Result;
            }
            catch (AggregateException aggregateException)
            {
                UnwrapAggregateException(aggregateException);
            }
            return(response.Value);
        }
Пример #12
0
        public ITraktAuthorization GetAuthorization(string code)
        {
            ITraktResponse <ITraktAuthorization> response = new TraktResponse <ITraktAuthorization>();

            try
            {
                response = Task.Run(() => base.Authentication.GetAuthorizationAsync(code)).Result;
            }
            catch (AggregateException aggregateException)
            {
                UnwrapAggregateException(aggregateException);
            }
            return(response.Value);
        }
Пример #13
0
        public async Task Test_TraktSyncModule_GetLastActivities()
        {
            TraktClient client = TestUtility.GetOAuthMockClient(GET_LAST_ACTIVITIES_URI, LAST_ACTIVITIES_JSON);
            TraktResponse <ITraktSyncLastActivities> response = await client.Sync.GetLastActivitiesAsync();

            response.Should().NotBeNull();
            response.IsSuccess.Should().BeTrue();
            response.HasValue.Should().BeTrue();
            response.Value.Should().NotBeNull();

            ITraktSyncLastActivities responseValue = response.Value;

            responseValue.All.Should().Be(DateTime.Parse("2014-11-20T07:01:32.378Z").ToUniversalTime());
            responseValue.Movies.Should().NotBeNull();
            responseValue.Movies.WatchedAt.Should().Be(DateTime.Parse("2014-11-19T21:42:41.823Z").ToUniversalTime());
            responseValue.Movies.CollectedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.243Z").ToUniversalTime());
            responseValue.Movies.RatedAt.Should().Be(DateTime.Parse("2014-11-19T18:32:29.459Z").ToUniversalTime());
            responseValue.Movies.WatchlistedAt.Should().Be(DateTime.Parse("2014-11-19T21:42:41.844Z").ToUniversalTime());
            responseValue.Movies.CommentedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.250Z").ToUniversalTime());
            responseValue.Movies.PausedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.250Z").ToUniversalTime());
            responseValue.Movies.HiddenAt.Should().Be(DateTime.Parse("2016-08-20T06:51:30.000Z").ToUniversalTime());

            responseValue.Episodes.Should().NotBeNull();
            responseValue.Episodes.WatchedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.305Z").ToUniversalTime());
            responseValue.Episodes.CollectedAt.Should().Be(DateTime.Parse("2014-11-19T22:02:41.308Z").ToUniversalTime());
            responseValue.Episodes.RatedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.310Z").ToUniversalTime());
            responseValue.Episodes.WatchlistedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.321Z").ToUniversalTime());
            responseValue.Episodes.CommentedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.325Z").ToUniversalTime());
            responseValue.Episodes.PausedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.250Z").ToUniversalTime());

            responseValue.Shows.Should().NotBeNull();
            responseValue.Shows.RatedAt.Should().Be(DateTime.Parse("2014-11-19T19:50:58.557Z").ToUniversalTime());
            responseValue.Shows.WatchlistedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.262Z").ToUniversalTime());
            responseValue.Shows.CommentedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.281Z").ToUniversalTime());
            responseValue.Shows.HiddenAt.Should().Be(DateTime.Parse("2016-08-20T06:51:30.000Z").ToUniversalTime());

            responseValue.Seasons.Should().NotBeNull();
            responseValue.Seasons.RatedAt.Should().Be(DateTime.Parse("2014-11-19T19:54:24.537Z").ToUniversalTime());
            responseValue.Seasons.WatchlistedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.297Z").ToUniversalTime());
            responseValue.Seasons.CommentedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.301Z").ToUniversalTime());
            responseValue.Seasons.HiddenAt.Should().Be(DateTime.Parse("2016-08-20T06:51:30.000Z").ToUniversalTime());

            responseValue.Comments.Should().NotBeNull();
            responseValue.Comments.LikedAt.Should().Be(DateTime.Parse("2014-11-20T03:38:09.122Z").ToUniversalTime());

            responseValue.Lists.Should().NotBeNull();
            responseValue.Lists.LikedAt.Should().Be(DateTime.Parse("2014-11-20T00:36:48.506Z").ToUniversalTime());
            responseValue.Lists.UpdatedAt.Should().Be(DateTime.Parse("2014-11-20T06:52:18.837Z").ToUniversalTime());
            responseValue.Lists.CommentedAt.Should().Be(DateTime.Parse("2014-11-20T06:51:30.250Z").ToUniversalTime());
        }
Пример #14
0
        private async Task <TraktResponse <TResponseContentType> > QuerySingleItemAsync <TResponseContentType>(ExtendedHttpRequestMessage requestMessage, bool isCheckinRequest = false, CancellationToken cancellationToken = default)
        {
            HttpResponseMessage responseMessage = null;

            try
            {
                responseMessage = await ExecuteRequestAsync(requestMessage, isCheckinRequest, cancellationToken).ConfigureAwait(false);

                DebugAsserter.AssertResponseMessageIsNotNull(responseMessage);
                DebugAsserter.AssertHttpResponseCodeIsNotExpected(responseMessage.StatusCode, HttpStatusCode.NoContent, DebugAsserter.SINGLE_ITEM_RESPONSE_PRECONDITION_INVALID_STATUS_CODE);
                Stream responseContentStream = await ResponseMessageHelper.GetResponseContentStreamAsync(responseMessage).ConfigureAwait(false);

                DebugAsserter.AssertResponseContentStreamIsNotNull(responseContentStream);
                IObjectJsonReader <TResponseContentType> objectJsonReader = JsonFactoryContainer.CreateObjectReader <TResponseContentType>();
                DebugAsserter.AssertObjectJsonReaderIsNotNull(objectJsonReader);
                TResponseContentType contentObject = await objectJsonReader.ReadObjectAsync(responseContentStream, cancellationToken).ConfigureAwait(false);

                bool hasValue = !EqualityComparer <TResponseContentType> .Default.Equals(contentObject, default);

                var response = new TraktResponse <TResponseContentType>
                {
                    IsSuccess = true,
                    HasValue  = hasValue,
                    Value     = contentObject
                };

                if (responseMessage.Headers != null)
                {
                    ResponseHeaderParser.ParseResponseHeaderValues(response, responseMessage.Headers);
                }

                return(response);
            }
            catch (Exception ex)
            {
                if (_client.Configuration.ThrowResponseExceptions)
                {
                    throw;
                }

                return(new TraktResponse <TResponseContentType> {
                    IsSuccess = false, Exception = ex
                });
            }
            finally
            {
                responseMessage?.Dispose();
            }
        }
        public async Task Test_TraktSyncModule_AddPersonalRecommendations()
        {
            string postJson = await TestUtility.SerializeObject(AddRecommendationsPost);

            postJson.Should().NotBeNullOrEmpty();

            TraktClient client = TestUtility.GetOAuthMockClient(ADD_RECOMMENDATIONS_URI, postJson, RECOMMENDATIONS_POST_RESPONSE_JSON);
            TraktResponse <ITraktSyncRecommendationsPostResponse> response = await client.Sync.AddPersonalRecommendationsAsync(AddRecommendationsPost);

            response.Should().NotBeNull();
            response.IsSuccess.Should().BeTrue();
            response.HasValue.Should().BeTrue();
            response.Value.Should().NotBeNull();

            ITraktSyncRecommendationsPostResponse responseValue = response.Value;

            responseValue.Added.Should().NotBeNull();
            responseValue.Added.Movies.Should().Be(1);
            responseValue.Added.Shows.Should().Be(2);

            responseValue.Existing.Should().NotBeNull();
            responseValue.Existing.Movies.Should().Be(3);
            responseValue.Existing.Shows.Should().Be(4);

            responseValue.NotFound.Should().NotBeNull();

            responseValue.NotFound.Movies.Should().NotBeNull().And.HaveCount(1);

            ITraktSyncRecommendationsPostMovie[] notFoundMovies = responseValue.NotFound.Movies.ToArray();

            notFoundMovies[0].Should().NotBeNull();
            notFoundMovies[0].Ids.Should().NotBeNull();
            notFoundMovies[0].Ids.Trakt.Should().Be(0U);
            notFoundMovies[0].Ids.Slug.Should().BeNull();
            notFoundMovies[0].Ids.Imdb.Should().Be("tt0000111");
            notFoundMovies[0].Ids.Tmdb.Should().BeNull();

            responseValue.NotFound.Shows.Should().NotBeNull().And.HaveCount(1);

            ITraktSyncRecommendationsPostShow[] notFoundShows = responseValue.NotFound.Shows.ToArray();

            notFoundShows[0].Should().NotBeNull();
            notFoundShows[0].Ids.Should().NotBeNull();
            notFoundShows[0].Ids.Trakt.Should().Be(0U);
            notFoundShows[0].Ids.Slug.Should().BeNull();
            notFoundShows[0].Ids.Imdb.Should().Be("tt0000222");
            notFoundShows[0].Ids.Tvdb.Should().BeNull();
            notFoundShows[0].Ids.Tmdb.Should().BeNull();
        }
        public async Task Test_TraktSyncModule_AddCollectionItems()
        {
            string postJson = await TestUtility.SerializeObject(AddCollectionItemsPost);

            postJson.Should().NotBeNullOrEmpty();

            TraktClient client = TestUtility.GetOAuthMockClient(ADD_COLLECTION_ITEMS_URI, postJson, COLLECTION_POST_RESPONSE_JSON);
            TraktResponse <ITraktSyncCollectionPostResponse> response = await client.Sync.AddCollectionItemsAsync(AddCollectionItemsPost);

            response.Should().NotBeNull();
            response.IsSuccess.Should().BeTrue();
            response.HasValue.Should().BeTrue();
            response.Value.Should().NotBeNull();

            ITraktSyncCollectionPostResponse responseValue = response.Value;

            responseValue.Added.Should().NotBeNull();
            responseValue.Added.Movies.Should().Be(1);
            responseValue.Added.Episodes.Should().Be(12);
            responseValue.Added.Shows.Should().NotHaveValue();
            responseValue.Added.Seasons.Should().NotHaveValue();

            responseValue.Updated.Should().NotBeNull();
            responseValue.Updated.Movies.Should().Be(3);
            responseValue.Updated.Episodes.Should().Be(1);
            responseValue.Updated.Shows.Should().NotHaveValue();
            responseValue.Updated.Seasons.Should().NotHaveValue();

            responseValue.Existing.Should().NotBeNull();
            responseValue.Existing.Movies.Should().Be(2);
            responseValue.Existing.Episodes.Should().Be(0);
            responseValue.Existing.Shows.Should().NotHaveValue();
            responseValue.Existing.Seasons.Should().NotHaveValue();

            responseValue.NotFound.Should().NotBeNull();
            responseValue.NotFound.Movies.Should().NotBeNull().And.HaveCount(1);

            ITraktPostResponseNotFoundMovie[] movies = responseValue.NotFound.Movies.ToArray();

            movies[0].Ids.Should().NotBeNull();
            movies[0].Ids.Trakt.Should().Be(0);
            movies[0].Ids.Slug.Should().BeNullOrEmpty();
            movies[0].Ids.Imdb.Should().Be("tt0000111");
            movies[0].Ids.Tmdb.Should().BeNull();

            responseValue.NotFound.Shows.Should().NotBeNull().And.BeEmpty();
            responseValue.NotFound.Seasons.Should().NotBeNull().And.BeEmpty();
            responseValue.NotFound.Episodes.Should().NotBeNull().And.BeEmpty();
        }
Пример #17
0
        public async Task Test_TraktShowsModule_ResetShowWatchedProgress_With_ResetAt()
        {
            string postJson = await TestUtility.SerializeObject(ResetWatchedProgressPost);

            postJson.Should().NotBeNullOrEmpty();

            TraktClient client = TestUtility.GetOAuthMockClient(RESET_SHOW_WATCHED_PROGRESS_URI, postJson, RESET_WATCHED_PROGRESS_POST_RESPONSE_JSON);
            TraktResponse <ITraktShowResetWatchedProgressPost> response = await client.Shows.ResetShowWatchedProgressAsync(SHOW_ID, RESET_WATCHED_PROGRESS_AT);

            response.Should().NotBeNull();
            response.IsSuccess.Should().BeTrue();
            response.HasValue.Should().BeTrue();
            response.Value.Should().NotBeNull();
            response.Value.ResetAt.Should().Be(DateTime.Parse("2022-01-23T21:12:25.000Z").ToUniversalTime());
        }
Пример #18
0
        public async Task <bool> CheckAuthent(IDatabase database, string deviceToken)
        {
            TraktResponse <ITraktAuthorization> authorization = await Client.Authentication.GetAuthorizationAsync(deviceToken);

            if (authorization.HasValue && authorization.Value.IsValid)
            {
                SaveAuthToken(database, new TraktToken {
                    AccessToken = authorization.Value.AccessToken, RefreshToken = authorization.Value.RefreshToken
                });

                return(true);
            }

            return(false);
        }
Пример #19
0
        public ITraktUserSettings GetTraktUserSettings()
        {
            ITraktResponse <ITraktUserSettings> response = new TraktResponse <ITraktUserSettings>();

            try
            {
                response = Task.Run(() => base.Users.GetSettingsAsync()).Result;
            }
            catch (AggregateException aggregateException)
            {
                UnwrapAggregateException(aggregateException);
            }

            return(response.Value);
        }
Пример #20
0
        public ITraktSyncLastActivities GetLastActivities()
        {
            ITraktResponse <ITraktSyncLastActivities> response = new TraktResponse <ITraktSyncLastActivities>();

            try
            {
                response = Task.Run(() => base.Sync.GetLastActivitiesAsync()).Result;
            }
            catch (AggregateException aggregateException)
            {
                UnwrapAggregateException(aggregateException);
            }

            return(response.Value);
        }
Пример #21
0
        public bool Scrobble(string filename)
        {
            // check movie is from my films
            if (CurrentMovie == null)
            {
                return(false);
            }

            StopScrobble();

            // create 15 minute timer to send watching status
            #region scrobble timer
            TraktTimer = new Timer(new TimerCallback((stateInfo) =>
            {
                Thread.CurrentThread.Name = "Scrobble";

                MFMovie currentMovie = stateInfo as MFMovie;

                TraktLogger.Info("Scrobbling Movie {0}", currentMovie.Title);

                double duration = g_Player.Duration;
                double progress = 0.0;

                // get current progress of player (in seconds) to work out percent complete
                if (duration > 0.0)
                {
                    progress = (g_Player.CurrentPosition / duration) * 100.0;
                }

                // create Scrobbling Data
                TraktMovieScrobble scrobbleData = CreateScrobbleData(currentMovie);
                if (scrobbleData == null)
                {
                    return;
                }

                // set duration/progress in scrobble data
                scrobbleData.Duration = Convert.ToInt32(duration / 60).ToString();
                scrobbleData.Progress = Convert.ToInt32(progress).ToString();

                // set watching status on trakt
                TraktResponse response = TraktAPI.TraktAPI.ScrobbleMovieState(scrobbleData, TraktScrobbleStates.watching);
                TraktAPI.TraktAPI.LogTraktResponse(response);
            }), CurrentMovie, 3000, 900000);
            #endregion

            return(true);
        }
Пример #22
0
        public ITraktEpisodeScrobblePostResponse StopScrobbleEpisode(ITraktEpisode episode, ITraktShow traktShow, float progress, string appVersion = null,
                                                                     DateTime?appBuildDate = null)
        {
            ITraktResponse <ITraktEpisodeScrobblePostResponse> response = new TraktResponse <ITraktEpisodeScrobblePostResponse>();

            try
            {
                response = Task.Run(() => base.Scrobble.StopEpisodeWithShowAsync(episode, traktShow, progress, appVersion, appBuildDate)).Result;
            }
            catch (AggregateException aggregateException)
            {
                UnwrapAggregateException(aggregateException);
            }

            return(response.Value);
        }
Пример #23
0
        public ITraktMovieScrobblePostResponse StopScrobbleMovie(ITraktMovie movie, float progress, string appVersion = null,
                                                                 DateTime?appBuildDate = null)
        {
            ITraktResponse <ITraktMovieScrobblePostResponse> response = new TraktResponse <ITraktMovieScrobblePostResponse>();

            try
            {
                response = Task.Run(() => base.Scrobble.StopMovieAsync(movie, progress, appVersion, appBuildDate)).Result;
            }
            catch (AggregateException aggregateException)
            {
                UnwrapAggregateException(aggregateException);
            }

            return(response.Value);
        }
Пример #24
0
        public static async Task <ProfiloModel> GetInfoUserAsync()
        {
            TraktResponse <ITraktUser> traktUser = await client.Users.GetUserProfileAsync("me", new TraktExtendedInfo().SetFull());

            var userInfo = traktUser.Value;

            ProfiloModel profiloModel = new ProfiloModel()
            {
                Nome     = userInfo.Name,
                Username = userInfo.Username,
                Citta    = userInfo.Location,
                Eta      = userInfo.Age,
            };

            return(profiloModel);
        }
Пример #25
0
        public async Task Test_TraktAuthenticationModule_PollForAuthorization_Polling()
        {
            string authorizationJson = await TestUtility.SerializeObject(MockAuthorization);

            authorizationJson.Should().NotBeNullOrEmpty();

            TraktClient client = TestUtility.GetAuthenticationMockClient();

            client.Authentication.Device = MockDevice;

            // First response: BadRequest => polling
            TestUtility.AddMockExpectationResponse((TestHttpClientProvider)client.HttpClientProvider, POLL_FOR_AUTHORIZATION_URI, MockAuthorizationPollingPostContent, authorizationJson, HttpStatusCode.BadRequest);

            // Second response: Ok => success
            TestUtility.AddMockExpectationResponse((TestHttpClientProvider)client.HttpClientProvider, POLL_FOR_AUTHORIZATION_URI, MockAuthorizationPollingPostContent, authorizationJson, HttpStatusCode.OK);

            TraktResponse <ITraktAuthorization> response = await client.Authentication.PollForAuthorizationAsync();

            TestUtility.VerifyNoOutstandingExpectations((TestHttpClientProvider)client.HttpClientProvider);

            response.Should().NotBeNull();
            response.IsSuccess.Should().BeTrue();
            response.HasValue.Should().BeTrue();
            response.Value.Should().NotBeNull();

            ITraktAuthorization responseAuthorization = response.Value;

            responseAuthorization.Should().NotBeNull();
            responseAuthorization.AccessToken.Should().Be(MockAuthorization.AccessToken);
            responseAuthorization.TokenType.Should().Be(MockAuthorization.TokenType);
            responseAuthorization.ExpiresInSeconds.Should().Be(MockAuthorization.ExpiresInSeconds);
            responseAuthorization.RefreshToken.Should().Be(MockAuthorization.RefreshToken);
            responseAuthorization.Scope.Should().Be(MockAuthorization.Scope);
            responseAuthorization.CreatedAt.Should().BeCloseTo(DateTime.UtcNow, CLOSE_TO_PRECISION);
            responseAuthorization.IsExpired.Should().BeFalse();

            ITraktAuthorization clientAuthorization = client.Authorization;

            clientAuthorization.Should().NotBeNull();
            clientAuthorization.AccessToken.Should().Be(responseAuthorization.AccessToken);
            clientAuthorization.TokenType.Should().Be(responseAuthorization.TokenType);
            clientAuthorization.ExpiresInSeconds.Should().Be(responseAuthorization.ExpiresInSeconds);
            clientAuthorization.RefreshToken.Should().Be(responseAuthorization.RefreshToken);
            clientAuthorization.Scope.Should().Be(responseAuthorization.Scope);
            clientAuthorization.CreatedAt.Should().Be(responseAuthorization.CreatedAt);
            clientAuthorization.IsExpired.Should().BeFalse();
        }
Пример #26
0
        private void OnWatchedMovie(MFMovie movie)
        {
            if (TraktSettings.AccountStatus != ConnectionState.Connected)
            {
                return;
            }

            CurrentMovie = null;

            if (!TraktSettings.BlockedFilenames.Contains(movie.File) && !TraktSettings.BlockedFolders.Any(f => movie.File.ToLowerInvariant().Contains(f.ToLowerInvariant())))
            {
                Thread scrobbleMovie = new Thread(delegate(object obj)
                {
                    MFMovie watchedMovie = obj as MFMovie;
                    if (watchedMovie == null)
                    {
                        return;
                    }

                    // show trakt rating dialog
                    ShowRateDialog(watchedMovie);

                    TraktLogger.Info("My Films movie considered watched: '{0}'", watchedMovie.Title);

                    // get scrobble data to send to api
                    TraktMovieScrobble scrobbleData = CreateScrobbleData(watchedMovie);
                    if (scrobbleData == null)
                    {
                        return;
                    }

                    // set duration/progress in scrobble data
                    scrobbleData.Duration = Convert.ToInt32(g_Player.Duration / 60).ToString();
                    scrobbleData.Progress = "100";

                    TraktResponse response = TraktAPI.TraktAPI.ScrobbleMovieState(scrobbleData, TraktScrobbleStates.scrobble);
                    TraktAPI.TraktAPI.LogTraktResponse(response);
                    // UpdateRecommendations();
                })
                {
                    IsBackground = true,
                    Name         = "Scrobble"
                };

                scrobbleMovie.Start(movie);
            }
        }
        public async Task Test_TraktCommentsModule_PostSeasonComment_Complete()
        {
            ITraktSeasonCommentPost seasonCommentPost = new TraktSeasonCommentPost
            {
                Season  = Season,
                Comment = COMMENT_TEXT,
                Spoiler = SPOILER,
                Sharing = SHARING
            };

            string postJson = await TestUtility.SerializeObject(seasonCommentPost);

            postJson.Should().NotBeNullOrEmpty();

            TraktClient client = TestUtility.GetOAuthMockClient(POST_SEASON_COMMENT_URI, postJson, COMMENT_POST_RESPONSE_JSON);
            TraktResponse <ITraktCommentPostResponse> response = await client.Comments.PostSeasonCommentAsync(Season, COMMENT_TEXT, SPOILER, SHARING);

            response.Should().NotBeNull();
            response.IsSuccess.Should().BeTrue();
            response.HasValue.Should().BeTrue();
            response.Value.Should().NotBeNull();

            ITraktCommentPostResponse responseValue = response.Value;

            responseValue.Id.Should().Be(COMMENT_ID);
            responseValue.ParentId.Should().Be(0U);
            responseValue.CreatedAt.Should().Be(DateTime.Parse("2014-08-04T06:46:01.996Z").ToUniversalTime());
            responseValue.Comment.Should().Be("Oh, I wasn't really listening.");
            responseValue.Spoiler.Should().BeFalse();
            responseValue.Review.Should().BeFalse();
            responseValue.Replies.Should().Be(0);
            responseValue.Likes.Should().Be(0);
            responseValue.UserRating.Should().NotHaveValue();
            responseValue.User.Should().NotBeNull();
            responseValue.User.Username.Should().Be("sean");
            responseValue.User.IsPrivate.Should().BeFalse();
            responseValue.User.Name.Should().Be("Sean Rudford");
            responseValue.User.IsVIP.Should().BeTrue();
            responseValue.User.IsVIP_EP.Should().BeFalse();
            responseValue.Sharing.Should().NotBeNull();
            responseValue.Sharing.Facebook.Should().BeTrue();
            responseValue.Sharing.Twitter.Should().BeTrue();
            responseValue.Sharing.Tumblr.Should().BeFalse();
            responseValue.Sharing.Medium.Should().BeTrue();
        }
        public async Task Test_TraktUsersModule_CreateCustomList_Complete()
        {
            ITraktUserCustomListPost createListPost = new TraktUserCustomListPost
            {
                Name           = LIST_NAME,
                Description    = DESCRIPTION,
                Privacy        = PRIVACY,
                DisplayNumbers = DISPLAY_NUMBERS,
                AllowComments  = ALLOW_COMMENTS
            };

            string postJson = await TestUtility.SerializeObject(createListPost);

            postJson.Should().NotBeNullOrEmpty();

            TraktClient client = TestUtility.GetOAuthMockClient(CREATE_CUSTOM_LIST_URI, postJson, LIST_JSON);

            TraktResponse <ITraktList> response =
                await client.Users.CreateCustomListAsync(USERNAME, LIST_NAME, DESCRIPTION, PRIVACY,
                                                         DISPLAY_NUMBERS, ALLOW_COMMENTS);

            response.Should().NotBeNull();
            response.IsSuccess.Should().BeTrue();
            response.HasValue.Should().BeTrue();
            response.Value.Should().NotBeNull();

            ITraktList responseValue = response.Value;

            responseValue.Name.Should().Be("Star Wars in machete order");
            responseValue.Description.Should().Be("Next time you want to introduce someone to Star Wars for the first time, watch the films with them in this order: IV, V, II, III, VI.");
            responseValue.Privacy.Should().Be(TraktAccessScope.Public);
            responseValue.DisplayNumbers.Should().BeTrue();
            responseValue.AllowComments.Should().BeFalse();
            responseValue.SortBy.Should().Be("rank");
            responseValue.SortHow.Should().Be("asc");
            responseValue.CreatedAt.Should().Be(DateTime.Parse("2014-10-11T17:00:54.000Z").ToUniversalTime());
            responseValue.UpdatedAt.Should().Be(DateTime.Parse("2014-11-09T17:00:54.000Z").ToUniversalTime());
            responseValue.ItemCount.Should().Be(5);
            responseValue.CommentCount.Should().Be(1);
            responseValue.Likes.Should().Be(2);
            responseValue.Ids.Should().NotBeNull();
            responseValue.Ids.Trakt.Should().Be(55);
            responseValue.Ids.Slug.Should().Be("star-wars-in-machete-order");
            responseValue.User.Should().NotBeNull();
        }
        public async Task Test_TraktScrobbleModule_StopEpisode_Complete()
        {
            ITraktEpisodeScrobblePost episodeStopScrobblePost = new TraktEpisodeScrobblePost
            {
                Episode    = Episode,
                Progress   = STOP_PROGRESS,
                AppVersion = APP_VERSION,
                AppDate    = APP_BUILD_DATE.ToTraktDateString()
            };

            string postJson = await TestUtility.SerializeObject(episodeStopScrobblePost);

            postJson.Should().NotBeNullOrEmpty();

            TraktClient client = TestUtility.GetOAuthMockClient(SCROBBLE_STOP_URI, postJson, EPISODE_STOP_SCROBBLE_POST_RESPONSE_JSON);

            TraktResponse <ITraktEpisodeScrobblePostResponse> response =
                await client.Scrobble.StopEpisodeAsync(Episode, STOP_PROGRESS, APP_VERSION, APP_BUILD_DATE);

            response.Should().NotBeNull();
            response.IsSuccess.Should().BeTrue();
            response.HasValue.Should().BeTrue();
            response.Value.Should().NotBeNull();

            ITraktEpisodeScrobblePostResponse responseValue = response.Value;

            responseValue.Id.Should().Be(3373536623);
            responseValue.Action.Should().Be(TraktScrobbleActionType.Stop);
            responseValue.Progress.Should().Be(STOP_PROGRESS);
            responseValue.Sharing.Should().NotBeNull();
            responseValue.Sharing.Facebook.Should().BeTrue();
            responseValue.Sharing.Twitter.Should().BeTrue();
            responseValue.Sharing.Tumblr.Should().BeFalse();
            responseValue.Episode.Should().NotBeNull();
            responseValue.Episode.SeasonNumber.Should().Be(1);
            responseValue.Episode.Number.Should().Be(1);
            responseValue.Episode.Title.Should().Be("Pilot");
            responseValue.Episode.Ids.Should().NotBeNull();
            responseValue.Episode.Ids.Trakt.Should().Be(16U);
            responseValue.Episode.Ids.Tvdb.Should().Be(349232U);
            responseValue.Episode.Ids.Imdb.Should().Be("tt0959621");
            responseValue.Episode.Ids.Tmdb.Should().Be(62085U);
            responseValue.Episode.Ids.TvRage.Should().Be(637041U);
        }
        public async Task <Pair <bool, TraktResponse <ITraktAuthorization> > > CheckIfAuthorizationIsExpiredOrWasRevokedAsync(bool autoRefresh = false, CancellationToken cancellationToken = default)
        {
            if (_client.Authorization.IsExpired)
            {
                return(new Pair <bool, TraktResponse <ITraktAuthorization> >(true, new TraktResponse <ITraktAuthorization>()));
            }

            bool throwResponseExceptions = true;

            try
            {
                throwResponseExceptions = _client.Configuration.ThrowResponseExceptions;
                _client.Configuration.ThrowResponseExceptions = true;
                await _client.Sync.GetLastActivitiesAsync(cancellationToken).ConfigureAwait(false);
            }
            catch (TraktAuthorizationException)
            {
                if (!autoRefresh)
                {
                    return(new Pair <bool, TraktResponse <ITraktAuthorization> >(true, new TraktResponse <ITraktAuthorization>()));
                }

                var request = new AuthorizationRefreshRequest
                {
                    RequestBody = new AuthorizationRefreshRequestBody
                    {
                        ClientId     = _client.ClientId,
                        ClientSecret = _client.ClientSecret,
                        RefreshToken = _client.Authorization.RefreshToken,
                        RedirectUri  = _client.Authentication.RedirectUri
                    }
                };

                TraktResponse <ITraktAuthorization> response = await RefreshAuthorizationAsync(request, cancellationToken).ConfigureAwait(false);

                return(new Pair <bool, TraktResponse <ITraktAuthorization> >(response.IsSuccess, response));
            }
            finally
            {
                _client.Configuration.ThrowResponseExceptions = throwResponseExceptions;
            }

            return(new Pair <bool, TraktResponse <ITraktAuthorization> >(false, new TraktResponse <ITraktAuthorization>()));
        }