Giter Site home page Giter Site logo

trakt-java's Introduction

Pull requests (e.g. support for more API endpoints, bug fixes) are welcome!

trakt-java

An (unofficial) Java library to use the Trakt v2 API built with retrofit 2.

Trakt API methods are grouped into service objects which can be centrally managed by a TraktV2 instance. It will act as a factory for all the services and will automatically initialize them with the given API key (OAuth client id) and optionally a given user access token.

Usage

Available on Maven Central

Change Log

Add the following dependency to your Gradle project:

implementation("com.uwetrottmann.trakt5:trakt-java:6.15.0")

Or for Maven:

<dependency>
  <groupId>com.uwetrottmann.trakt5</groupId>
  <artifactId>trakt-java</artifactId>
  <version>6.15.0</version>
</dependency>

Android

This library ships Java 8 bytecode. This requires Android Gradle Plugin 3.2.x or newer.

This library depends on threetenbp. To avoid issues on Android exclude the dependency and include ThreeTenABP instead:

implementation("com.uwetrottmann.trakt5:trakt-java:<latest-version>") {
  exclude(group = "org.threeten", module = "threetenbp") // using ThreeTenABP instead
}
implementation("com.jakewharton.threetenabp:threetenabp:<latest-version>")

Example

Use like any other retrofit2 based service. At least a Trakt API key, which for Trakt is currently the same as the OAuth 2.0 client ID, has to be supplied. Optionally, a user OAuth accessToken(token) can be supplied.

See the TraktV2 class for some helper methods to handle the OAuth flow.

TraktV2 trakt = new TraktV2("api_key");
Shows traktShows = trakt.shows();
try {
    // Get trending shows
    Response<List<TrendingShow>> response = traktShows.trending(1, null, Extended.FULL).execute();
    if (response.isSuccessful()) {
        List<TrendingShow> shows = response.body();
        for (TrendingShow trending : shows) {
            System.out.println("Title: " + trending.show.title);
        }
    } else {
        if (TraktV2.isUnauthorized(response)) {
            // authorization required, supply a valid OAuth access token
        } else {
            // the request failed for some other reason
        }
    }
} catch (Exception e) {
    // see execute() API docs 
}

For Kotlin, to make a Call suspend use retrofit's awaitResponse() instead of execute():

try {
    val response = traktShows.trending(1, null, Extended.FULL).awaitResponse()
    if (response.isSuccessful) {
        val shows = response.body()
    }
} catch (e: Exception) {
    // see execute() API docs
}

See test cases in src/test/ for more examples and the retrofit website for configuration options.

Proguard / R8

It is likely not every method in this library is used, so it is probably useful to strip unused ones with Proguard. Apply the Proguard rules for retrofit.

The specific rules for this library are already bundled into the release which can be interpreted by R8 automatically, ProGuard users must manually add the rules.

License

This work by Uwe Trottmann is licensed under the Apache License 2.0.

Contributors and changes are tracked by Git.

Do not just copy, make it better.

trakt-java's People

Contributors

albodelu avatar courville avatar defhead avatar dependabot[bot] avatar florianmski avatar goooler avatar hrk avatar jakewharton avatar kilianb avatar larsg310 avatar leinad87 avatar mattkranzler5 avatar mlaggner avatar mmarco94 avatar oprisnik avatar porzione avatar riksmithns avatar samicemalone avatar srggsf avatar uwetrottmann avatar yacsrk avatar zelkami avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

trakt-java's Issues

Support Users > Watchlist

I am missing the possibility how to get a users watchlisted movies.
Any hints how to do that?

Thank you.

Use @Query/@Path instead of @EncodedQuery/@EncodedPath

@EncodedQuery is deprecated in favor of a @Query parameter. @EncodedPath is deprecated in favor of a @Path parameter.

// e.g.
@EncodedQuery("extended")
// should become
@Query(value="extended", encodeValue=false)

@EncodedPath("rating")
// should become
@Path(value="rating", encode=false)

List privacy settings are sent in all-caps instead of lowercase

Because of the ListPrivacy enum names (e.g. PUBLIC), the "privacy" value for List Creation (e.g. trakt.users().createList()) gets sent to Trakt as privacy: "PUBLIC" instead of privacy: "public". Trakt ignores this, so all lists created are set to default (private).

This is an annoying one because you can't name an enum value "public" for obvious reasons.

I fixed this in my local by removing ListPrivacy altogether and just using a String for privacy values, but I'm not sure that's the ideal fix.

Gradle Support

Any reason why this built using maven and not gradle? If I were to convert this to gradle would you merge?

Better error handling

Hi
just started using this API.
Works great so far - thanks! ๐Ÿ‘

But the error handling mostly does not work :(
When specifying an invalid API key, or password, retrofit throws an exception instead of filling the response.

ActionResponse ar = trakt.movieService().library(new Movies(myMovies));

retrofit.RetrofitError: null
    at retrofit.RetrofitError.httpError(RetrofitError.java:37) ~[retrofit.jar:na]
    at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:414) ~[retrofit.jar:na]
    at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:284) ~[retrofit.jar:na]
    at $Proxy25.library(Unknown Source) ~[na:na]

same for

List<Movie> traktMovies = trakt.userService().libraryMoviesWatched(userName, Extended.MIN);

: HTTP/1.1 401 Unauthorized
{"status":"failure","error":"invalid API key"}

where i dont have any response object (i can see the correct error in the json body)

brgds
Myron

Unsupported class file major version 63

Build tivi with Java 19:

> Transform trakt.jar (project :api:trakt) with DexingWithClasspathTransform
AGPBI: {"kind":"error","text":"java.lang.IllegalArgumentException: Unsupported class file major version 63","sources":[{"file":"/Users/goooler/StudioProjects/tivi/api/trakt/build/libs/trakt.jar"}],"tool":"D8"}

> Transform tmdb.jar (project :api:tmdb) with DexingWithClasspathTransform
AGPBI: {"kind":"error","text":"java.lang.IllegalArgumentException: Unsupported class file major version 63","sources":[{"file":"/Users/goooler/StudioProjects/tivi/api/tmdb/build/libs/tmdb.jar"}],"tool":"D8"}

Clean up entities

  • Merge Watchlisted* entities into their relevant Base* entity.
  • ...

Noob issue

Hi, Im trying to use your library on android.
But im failing to do so.

I'm calling this on create, because I though with okhttp and retrofit I would need Async task. is it so?

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TraktV2 manager = new TraktV2();
        manager.setAccessToken(token);
        manager.movies().trending(1,3, Extended.DEFAULT_MIN);
    }

But i'm getting:

 java.lang.RuntimeException: Unable to start activity ComponentInfo{lopesdasilva.mt_tests.myapplication/lopesdasilva.mt_tests.myapplication.MainActivity}: retrofit.RetrofitError
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
          (...)
     Caused by: retrofit.RetrofitError
            at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:395)
            at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
            (...)
     Caused by: android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
            at java.net.InetAddress.getAllByName(InetAddress.java:215)
            at com.squareup.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
            at com.squareup.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:259)
            at com.squareup.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:233)
            (...)

Thanks for your time and work

List of episodes method missing

There doesn't appear to be any methods to retrieve a list of episodes for a given season, ie.
make a call like /shows/19792/seasons/1/episodes and return a list of Episode entity objects.

Port to retrofit

https://github.com/square/retrofit

  • Initial tests with new RequestInterceptor look very good.
  • Port service manager.
  • in progress Port existing endpoints, add new ones. Move endpoints required by SeriesGuide first, expand to more later.

Add last_x_at properties on progress methods

API changes of 2015-04-08

  • /shows/:id/progress/collection includes last_collected_at for the show, and collected_at for each episode.
  • /shows/:id/progress/watched includes last_watched_at for the show and each episode.

SocketException when trying to get access token

I'm getting this exception frequently (but not every time) when trying to retrieve an access token after already getting an authorization code. Any ideas?

org.apache.oltu.oauth2.common.exception.OAuthSystemException: java.net.SocketException: Socket is closed
            at com.uwetrottmann.trakt.v2.TraktHttpClient.execute(TraktHttpClient.java:77)
            at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:65)
            at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:55)
            at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:71)
            at com.uwetrottmann.trakt.v2.TraktV2.getAccessToken(TraktV2.java:135)

API does not support usernames with periods in them

The API (e.g. /users/:user/friends) might return a username that contains a period ., e.g. Prof.JensDrehbares.

However, calling any /user method with this username will result in an error or unexpected response, as the API expects periods to be encoded as dashes -, e.g. Prof-JensDrehbares.

Asked Justin on Google+ about documentation of any other possible character replacments.

Pagination on "Sync ratings" endpoints is not possible

Hello,

Trakt API allows to paginate through "[GET] /sync/ratings/" endpoint but it's not possible to accomplish that using trakt-java API. Theses methods take only "rating" and "extended" parameters:

    @GET("sync/ratings/movies{rating}")
    Call<List<RatedMovie>> ratingsMovies(
            @Path(value = "rating", encoded = true) RatingsFilter filter,
            @Query(value = "extended", encoded = true) Extended extended
    );

    @GET("sync/ratings/shows{rating}")
    Call<List<RatedShow>> ratingsShows(
            @Path(value = "rating", encoded = true) RatingsFilter filter,
            @Query(value = "extended", encoded = true) Extended extended
    );

    @GET("sync/ratings/seasons{rating}")
    Call<List<RatedSeason>> ratingsSeasons(
            @Path(value = "rating", encoded = true) RatingsFilter filter,
            @Query(value = "extended", encoded = true) Extended extended
    );

    @GET("sync/ratings/episodes{rating}")
    Call<List<RatedEpisode>> ratingsEpisodes(
            @Path(value = "rating", encoded = true) RatingsFilter filter,
            @Query(value = "extended", encoded = true) Extended extended
    );

Is there an explanation for that?

Thank you.

Show data is null

I have a method to search and find shows given an input, and that works perfectly. It finds the show, I'm able to print show.title, show.year, and show.overview. Those all work great. But everything else is coming to me as null.

show.language
show.country
show.homepage

^ These 3 as well as others I assume are coming as null.... When I look at the trakt api on apiary it doesn't even look like they give some of this data through the api so I'm wondering how I get it here. Are these options just left in there from a time when they existed or are they planned or something like this? I'm not sure how to get this working

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.