Search in sources :

Example 11 with Movie

use of com.uwetrottmann.trakt5.entities.Movie in project SeriesGuide by UweTrottmann.

the class SgPicassoRequestHandler method load.

@Override
public Result load(Request request, int networkPolicy) throws IOException {
    String scheme = request.uri.getScheme();
    String host = request.uri.getHost();
    if (host == null)
        return null;
    if (SCHEME_SHOW_TMDB.equals(scheme)) {
        int showTmdbId = Integer.parseInt(host);
        String language = request.uri.getQueryParameter(QUERY_LANGUAGE);
        if (language == null || language.length() == 0) {
            language = DisplaySettings.LANGUAGE_EN;
        }
        TvShow showDetails = new TmdbTools2().getShowDetails(showTmdbId, language, context);
        if (showDetails != null) {
            String url = ImageTools.tmdbOrTvdbPosterUrl(showDetails.poster_path, context, false);
            if (url != null) {
                return loadFromNetwork(Uri.parse(url), networkPolicy);
            }
        }
    }
    if (SCHEME_MOVIE_TMDB.equals(scheme)) {
        int movieTmdbId = Integer.valueOf(host);
        MovieTools movieTools = SgApp.getServicesComponent(context).movieTools();
        Movie movieSummary = movieTools.getMovieSummary(movieTmdbId);
        if (movieSummary != null && movieSummary.poster_path != null) {
            final String imageUrl = TmdbSettings.getImageBaseUrl(context) + TmdbSettings.POSTER_SIZE_SPEC_W342 + movieSummary.poster_path;
            return loadFromNetwork(Uri.parse(imageUrl), networkPolicy);
        }
    }
    return null;
}
Also used : Movie(com.uwetrottmann.tmdb2.entities.Movie) TvShow(com.uwetrottmann.tmdb2.entities.TvShow) MovieTools(com.battlelancer.seriesguide.ui.movies.MovieTools) TmdbTools2(com.battlelancer.seriesguide.tmdbapi.TmdbTools2)

Example 12 with Movie

use of com.uwetrottmann.trakt5.entities.Movie in project SeriesGuide by UweTrottmann.

the class TraktRatingsSync method downloadForMovies.

/**
 * Downloads trakt movie ratings and applies the latest ones to the database.
 *
 * <p> To apply all ratings, set {@link TraktSettings#KEY_LAST_MOVIES_RATED_AT} to 0.
 */
public boolean downloadForMovies(OffsetDateTime ratedAt) {
    if (ratedAt == null) {
        Timber.e("downloadForMovies: null rated_at");
        return false;
    }
    long lastRatedAt = TraktSettings.getLastMoviesRatedAt(context);
    if (!TimeTools.isAfterMillis(ratedAt, lastRatedAt)) {
        // not initial sync, no ratings have changed
        Timber.d("downloadForMovies: no changes since %tF %tT", lastRatedAt, lastRatedAt);
        return true;
    }
    if (!TraktCredentials.get(context).hasCredentials()) {
        return false;
    }
    // download rated shows
    List<RatedMovie> ratedMovies;
    try {
        Response<List<RatedMovie>> response = traktSync.ratingsMovies(RatingsFilter.ALL, null, null, null).execute();
        if (response.isSuccessful()) {
            ratedMovies = response.body();
        } else {
            if (SgTrakt.isUnauthorized(context, response)) {
                return false;
            }
            Errors.logAndReport("get movie ratings", response);
            return false;
        }
    } catch (Exception e) {
        Errors.logAndReport("get movie ratings", e);
        return false;
    }
    if (ratedMovies == null) {
        Timber.e("downloadForMovies: null response");
        return false;
    }
    if (ratedMovies.isEmpty()) {
        Timber.d("downloadForMovies: no ratings on trakt");
        return true;
    }
    // trakt last activity rated_at timestamp is set after the rating timestamp
    // so include ratings that are a little older
    long ratedAtThreshold = lastRatedAt - 5 * DateUtils.MINUTE_IN_MILLIS;
    // go through ratings, latest first (trakt sends in that order)
    ArrayList<ContentProviderOperation> batch = new ArrayList<>();
    for (RatedMovie movie : ratedMovies) {
        if (movie.rating == null || movie.movie == null || movie.movie.ids == null || movie.movie.ids.tmdb == null) {
            // skip, can't handle
            continue;
        }
        if (movie.rated_at != null && TimeTools.isBeforeMillis(movie.rated_at, ratedAtThreshold)) {
            // no need to apply older ratings again
            break;
        }
        // if a movie does not exist, this update will do nothing
        ContentProviderOperation op = ContentProviderOperation.newUpdate(SeriesGuideContract.Movies.buildMovieUri(movie.movie.ids.tmdb)).withValue(SeriesGuideContract.Movies.RATING_USER, movie.rating.value).build();
        batch.add(op);
    }
    // apply database updates
    try {
        DBUtils.applyInSmallBatches(context, batch);
    } catch (OperationApplicationException e) {
        Timber.e(e, "downloadForMovies: database update failed");
        return false;
    }
    // save last rated instant
    long ratedAtTime = ratedAt.toInstant().toEpochMilli();
    PreferenceManager.getDefaultSharedPreferences(context).edit().putLong(TraktSettings.KEY_LAST_MOVIES_RATED_AT, ratedAtTime).apply();
    Timber.d("downloadForMovies: success, last rated_at %tF %tT", ratedAtTime, ratedAtTime);
    return true;
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) RatedMovie(com.uwetrottmann.trakt5.entities.RatedMovie) OperationApplicationException(android.content.OperationApplicationException) OperationApplicationException(android.content.OperationApplicationException)

Example 13 with Movie

use of com.uwetrottmann.trakt5.entities.Movie in project SeriesGuide by UweTrottmann.

the class TraktMovieSync method uploadFlagsNotOnTrakt.

/**
 * Uploads the given movies to the appropriate list(s)/history on Trakt.
 */
private boolean uploadFlagsNotOnTrakt(Set<Integer> toCollectOnTrakt, Set<Integer> toWatchlistOnTrakt, Set<Integer> toSetWatchedOnTrakt) {
    if (toCollectOnTrakt.size() == 0 && toWatchlistOnTrakt.size() == 0 && toSetWatchedOnTrakt.size() == 0) {
        Timber.d("uploadLists: nothing to upload");
        return true;
    }
    if (!AndroidUtils.isNetworkConnected(context)) {
        // Fail, no connection is available.
        return false;
    }
    // Upload.
    String action = "";
    SyncItems items = new SyncItems();
    Response<SyncResponse> response = null;
    try {
        if (toCollectOnTrakt.size() > 0) {
            List<SyncMovie> moviesToCollect = convertToSyncMovieList(toCollectOnTrakt);
            action = "add movies to collection";
            items.movies(moviesToCollect);
            response = traktSync.addItemsToCollection(items).execute();
        }
        if (response == null || response.isSuccessful()) {
            if (toWatchlistOnTrakt.size() > 0) {
                List<SyncMovie> moviesToWatchlist = convertToSyncMovieList(toWatchlistOnTrakt);
                action = "add movies to watchlist";
                items.movies(moviesToWatchlist);
                response = traktSync.addItemsToWatchlist(items).execute();
            }
        }
        if (response == null || response.isSuccessful()) {
            if (toSetWatchedOnTrakt.size() > 0) {
                List<SyncMovie> moviesToSetWatched = convertToSyncMovieList(toSetWatchedOnTrakt);
                // Note: not setting a watched date (because not having one),
                // so Trakt will use the movie release date.
                action = "add movies to watched history";
                items.movies(moviesToSetWatched);
                response = traktSync.addItemsToWatchedHistory(items).execute();
            }
        }
    } catch (Exception e) {
        Errors.logAndReport(action, e);
        return false;
    }
    if (response != null && !response.isSuccessful()) {
        if (SgTrakt.isUnauthorized(context, response)) {
            return false;
        }
        Errors.logAndReport(action, response);
        return false;
    }
    Timber.d("uploadLists: success, uploaded %s to collection, %s to watchlist, %s set watched", toCollectOnTrakt.size(), toWatchlistOnTrakt.size(), toSetWatchedOnTrakt.size());
    return true;
}
Also used : SyncItems(com.uwetrottmann.trakt5.entities.SyncItems) SyncResponse(com.uwetrottmann.trakt5.entities.SyncResponse) SyncMovie(com.uwetrottmann.trakt5.entities.SyncMovie) OperationApplicationException(android.content.OperationApplicationException)

Example 14 with Movie

use of com.uwetrottmann.trakt5.entities.Movie in project SeriesGuide by UweTrottmann.

the class MovieHistoryAdapter method getView.

@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
    // A ViewHolder keeps references to child views to avoid
    // unnecessary calls to findViewById() on each row.
    ViewHolder holder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.item_history_movie, parent, false);
        holder = new ViewHolder(convertView);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    HistoryEntry item = getItem(position);
    if (item == null) {
        // all bets are off!
        return convertView;
    }
    // movie title
    holder.title.setText(item.movie == null ? null : item.movie.title);
    // timestamp
    if (item.watched_at != null) {
        CharSequence timestamp = DateUtils.getRelativeTimeSpanString(item.watched_at.getMillis(), System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL);
        holder.timestamp.setText(timestamp);
    } else {
        holder.timestamp.setText(null);
    }
    // action type indicator
    if ("watch".equals(item.action)) {
        // marked watched
        holder.type.setImageResource(getResIdDrawableWatched());
    } else {
        // check-in, scrobble
        holder.type.setImageResource(getResIdDrawableCheckin());
    }
    return convertView;
}
Also used : HistoryEntry(com.uwetrottmann.trakt5.entities.HistoryEntry) NonNull(android.support.annotation.NonNull)

Example 15 with Movie

use of com.uwetrottmann.trakt5.entities.Movie in project SeriesGuide by UweTrottmann.

the class MovieLoader method loadInBackground.

@Override
public MovieDetails loadInBackground() {
    // try loading from trakt and tmdb, this might return a cached response
    MovieDetails details = app.getMovieTools().getMovieDetails(mTmdbId);
    // update local database
    updateLocalMovie(getContext(), details, mTmdbId);
    // fill in details from local database
    Cursor movieQuery = getContext().getContentResolver().query(Movies.buildMovieUri(mTmdbId), MovieQuery.PROJECTION, null, null, null);
    if (movieQuery == null || !movieQuery.moveToFirst() || movieQuery.getCount() < 1) {
        if (movieQuery != null) {
            movieQuery.close();
        }
        // ensure list flags and watched flag are false on failure
        // (assumption: movie not in db, it has the truth, so can't be in any lists or watched)
        details.inCollection = false;
        details.inWatchlist = false;
        details.isWatched = false;
        return details;
    }
    // set local state for watched, collected and watchlist status
    // assumption: local db has the truth for these
    details.inCollection = DBUtils.restoreBooleanFromInt(movieQuery.getInt(MovieQuery.IN_COLLECTION));
    details.inWatchlist = DBUtils.restoreBooleanFromInt(movieQuery.getInt(MovieQuery.IN_WATCHLIST));
    details.isWatched = DBUtils.restoreBooleanFromInt(movieQuery.getInt(MovieQuery.WATCHED));
    // also use local state of user rating
    details.userRating = movieQuery.getInt(MovieQuery.RATING_USER);
    // only overwrite other info if remote data failed to load
    if (details.traktRatings() == null) {
        details.traktRatings(new Ratings());
        details.traktRatings().rating = (double) movieQuery.getInt(MovieQuery.RATING_TRAKT);
        details.traktRatings().votes = movieQuery.getInt(MovieQuery.RATING_VOTES_TRAKT);
    }
    if (details.tmdbMovie() == null) {
        details.tmdbMovie(new Movie());
        details.tmdbMovie().imdb_id = movieQuery.getString(MovieQuery.IMDB_ID);
        details.tmdbMovie().title = movieQuery.getString(MovieQuery.TITLE);
        details.tmdbMovie().overview = movieQuery.getString(MovieQuery.OVERVIEW);
        details.tmdbMovie().poster_path = movieQuery.getString(MovieQuery.POSTER);
        details.tmdbMovie().runtime = movieQuery.getInt(MovieQuery.RUNTIME_MIN);
        details.tmdbMovie().vote_average = movieQuery.getDouble(MovieQuery.RATING_TMDB);
        details.tmdbMovie().vote_count = movieQuery.getInt(MovieQuery.RATING_VOTES_TMDB);
        // if stored release date is Long.MAX, movie has no release date
        long releaseDateMs = movieQuery.getLong(MovieQuery.RELEASED_UTC_MS);
        details.tmdbMovie().release_date = MovieTools.movieReleaseDateFrom(releaseDateMs);
    }
    // clean up
    movieQuery.close();
    return details;
}
Also used : Movie(com.uwetrottmann.tmdb2.entities.Movie) Cursor(android.database.Cursor) MovieDetails(com.battlelancer.seriesguide.items.MovieDetails) Ratings(com.uwetrottmann.trakt5.entities.Ratings)

Aggregations

Movie (com.uwetrottmann.tmdb2.entities.Movie)14 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 SyncMovie (com.uwetrottmann.trakt5.entities.SyncMovie)5 List (java.util.List)5 OperationApplicationException (android.content.OperationApplicationException)4 LinkedList (java.util.LinkedList)4 ContentProviderOperation (android.content.ContentProviderOperation)3 Nullable (androidx.annotation.Nullable)3 HistoryEntry (com.uwetrottmann.trakt5.entities.HistoryEntry)3 Intent (android.content.Intent)2 Nullable (android.support.annotation.Nullable)2 MovieDetails (com.battlelancer.seriesguide.ui.movies.MovieDetails)2 MovieList (com.uwetrottmann.seriesguide.backend.movies.model.MovieList)2 BaseMovie (com.uwetrottmann.trakt5.entities.BaseMovie)2 Comment (com.uwetrottmann.trakt5.entities.Comment)2 Episode (com.uwetrottmann.trakt5.entities.Episode)2 Friend (com.uwetrottmann.trakt5.entities.Friend)2 LastActivities (com.uwetrottmann.trakt5.entities.LastActivities)2 Ratings (com.uwetrottmann.trakt5.entities.Ratings)2