Search in sources :

Example 1 with SgRoomDatabase

use of com.battlelancer.seriesguide.provider.SgRoomDatabase in project SeriesGuide by UweTrottmann.

the class TraktCommentsLoader method loadInBackground.

@Override
public Result loadInBackground() {
    // movie comments?
    int movieTmdbId = args.getInt(InitBundle.MOVIE_TMDB_ID);
    if (movieTmdbId != 0) {
        Integer movieTraktId = movieTools.lookupTraktId(movieTmdbId);
        if (movieTraktId != null) {
            if (movieTraktId == -1) {
                return buildResultFailure(R.string.trakt_error_not_exists);
            }
            try {
                Response<List<Comment>> response = traktMovies.get().comments(String.valueOf(movieTraktId), 1, PAGE_SIZE, Extended.FULL).execute();
                if (response.isSuccessful()) {
                    return buildResultSuccess(response.body());
                } else {
                    Errors.logAndReport("get movie comments", response);
                }
            } catch (Exception e) {
                Errors.logAndReport("get movie comments", e);
            }
        }
        return buildResultFailureWithOfflineCheck();
    }
    // episode comments?
    long episodeId = args.getLong(InitBundle.EPISODE_ID);
    if (episodeId != 0) {
        // look up episode number, season and show id
        SgRoomDatabase database = SgRoomDatabase.getInstance(getContext());
        SgEpisode2Numbers episode = database.sgEpisode2Helper().getEpisodeNumbers(episodeId);
        if (episode == null) {
            Timber.e("Failed to get episode %d", episodeId);
            return buildResultFailure(R.string.unknown);
        }
        // look up show trakt id
        Integer showTraktId = ShowTools.getShowTraktId(getContext(), episode.getShowId());
        if (showTraktId == null) {
            Timber.e("Failed to get show %d", episode.getShowId());
            return buildResultFailure(R.string.trakt_error_not_exists);
        }
        try {
            Response<List<Comment>> response = traktEpisodes.get().comments(String.valueOf(showTraktId), episode.getSeason(), episode.getEpisodenumber(), 1, PAGE_SIZE, Extended.FULL).execute();
            if (response.isSuccessful()) {
                return buildResultSuccess(response.body());
            } else {
                Errors.logAndReport("get episode comments", response);
            }
        } catch (Exception e) {
            Errors.logAndReport("get episode comments", e);
        }
        return buildResultFailureWithOfflineCheck();
    }
    // show comments!
    long showId = args.getLong(InitBundle.SHOW_ID);
    Integer showTraktId = ShowTools.getShowTraktId(getContext(), showId);
    if (showTraktId == null) {
        return buildResultFailure(R.string.trakt_error_not_exists);
    }
    try {
        Response<List<Comment>> response = traktShows.get().comments(String.valueOf(showTraktId), 1, PAGE_SIZE, Extended.FULL).execute();
        if (response.isSuccessful()) {
            return buildResultSuccess(response.body());
        } else {
            Errors.logAndReport("get show comments", response);
        }
    } catch (Exception e) {
        Errors.logAndReport("get show comments", e);
    }
    return buildResultFailureWithOfflineCheck();
}
Also used : SgRoomDatabase(com.battlelancer.seriesguide.provider.SgRoomDatabase) SgEpisode2Numbers(com.battlelancer.seriesguide.provider.SgEpisode2Numbers) List(java.util.List)

Example 2 with SgRoomDatabase

use of com.battlelancer.seriesguide.provider.SgRoomDatabase in project SeriesGuide by UweTrottmann.

the class RateEpisodeTask method buildTraktSyncItems.

@Nullable
@Override
protected SyncItems buildTraktSyncItems() {
    SgRoomDatabase database = SgRoomDatabase.getInstance(getContext());
    SgEpisode2Numbers episode = database.sgEpisode2Helper().getEpisodeNumbers(episodeId);
    if (episode == null)
        return null;
    int showTmdbId = database.sgShow2Helper().getShowTmdbId(episode.getShowId());
    if (showTmdbId == 0)
        return null;
    return new SyncItems().shows(new SyncShow().id(ShowIds.tmdb(showTmdbId)).seasons(new SyncSeason().number(episode.getSeason()).episodes(new SyncEpisode().number(episode.getEpisodenumber()).rating(getRating()))));
}
Also used : SyncEpisode(com.uwetrottmann.trakt5.entities.SyncEpisode) SyncItems(com.uwetrottmann.trakt5.entities.SyncItems) SgRoomDatabase(com.battlelancer.seriesguide.provider.SgRoomDatabase) SgEpisode2Numbers(com.battlelancer.seriesguide.provider.SgEpisode2Numbers) SyncShow(com.uwetrottmann.trakt5.entities.SyncShow) SyncSeason(com.uwetrottmann.trakt5.entities.SyncSeason) Nullable(androidx.annotation.Nullable)

Example 3 with SgRoomDatabase

use of com.battlelancer.seriesguide.provider.SgRoomDatabase in project SeriesGuide by UweTrottmann.

the class HexagonEpisodeSync method downloadChangedFlags.

/**
 * Downloads all episodes changed since the last time this was called and applies changes to
 * the database.
 */
public boolean downloadChangedFlags(@NonNull Map<Integer, Long> tmdbIdsToShowIds) {
    long currentTime = System.currentTimeMillis();
    SgRoomDatabase database = SgRoomDatabase.getInstance(context);
    DateTime lastSyncTime = new DateTime(HexagonSettings.getLastEpisodesSyncTime(context));
    Timber.d("downloadChangedFlags: since %s", lastSyncTime);
    List<SgCloudEpisode> episodes;
    String cursor = null;
    boolean hasMoreEpisodes = true;
    Map<Long, ShowLastWatchedInfo> showIdsToLastWatched = new HashMap<>();
    while (hasMoreEpisodes) {
        try {
            // get service each time to check if auth was removed
            Episodes episodesService = hexagonTools.getEpisodesService();
            if (episodesService == null) {
                return false;
            }
            Episodes.GetSgEpisodes request = episodesService.getSgEpisodes().setUpdatedSince(// use default server limit
            lastSyncTime);
            if (!TextUtils.isEmpty(cursor)) {
                request.setCursor(cursor);
            }
            SgCloudEpisodeList response = request.execute();
            if (response == null) {
                // we're done here
                Timber.d("downloadChangedFlags: response was null, done here");
                break;
            }
            episodes = response.getEpisodes();
            // check for more items
            if (response.getCursor() != null) {
                cursor = response.getCursor();
            } else {
                hasMoreEpisodes = false;
            }
        } catch (IOException | IllegalArgumentException e) {
            // Note: JSON parser may throw IllegalArgumentException.
            Errors.logAndReportHexagon("get updated episodes", e);
            return false;
        }
        if (episodes == null || episodes.size() == 0) {
            // nothing to do here
            break;
        }
        // build batch of episode flag updates
        ArrayList<SgEpisode2UpdateByNumber> batch = new ArrayList<>();
        for (SgCloudEpisode episode : episodes) {
            Integer showTmdbId = episode.getShowTmdbId();
            Long showId = tmdbIdsToShowIds.get(showTmdbId);
            if (showId == null) {
                // ignore, show not added on this device
                continue;
            }
            Integer watchedFlag = episode.getWatchedFlag();
            Integer playsOrNull = null;
            if (watchedFlag != null) {
                if (watchedFlag == EpisodeFlags.WATCHED) {
                    // Note: plays may be null for legacy data. Protect against invalid data.
                    if (episode.getPlays() != null && episode.getPlays() >= 1) {
                        playsOrNull = episode.getPlays();
                    } else {
                        playsOrNull = 1;
                    }
                } else {
                    // Skipped or not watched.
                    playsOrNull = 0;
                }
                // record the latest last watched time and episode ID for a show
                if (!EpisodeTools.isUnwatched(watchedFlag)) {
                    ShowLastWatchedInfo lastWatchedInfo = showIdsToLastWatched.get(showId);
                    // episodes returned in reverse chrono order, so just get the first time
                    if (lastWatchedInfo == null && episode.getUpdatedAt() != null) {
                        long updatedAtMs = episode.getUpdatedAt().getValue();
                        showIdsToLastWatched.put(showId, new ShowLastWatchedInfo(updatedAtMs, episode.getSeasonNumber(), episode.getEpisodeNumber()));
                    }
                }
            }
            batch.add(new SgEpisode2UpdateByNumber(showId, episode.getEpisodeNumber(), episode.getSeasonNumber(), watchedFlag, playsOrNull, episode.getIsInCollection()));
        }
        // execute database update
        database.sgEpisode2Helper().updateWatchedAndCollectedByNumber(batch);
    }
    if (!showIdsToLastWatched.isEmpty()) {
        // Note: it is possible that this overwrites a more recently watched episode,
        // however, the next sync should contain this episode and restore it.
        database.sgShow2Helper().updateLastWatchedMsIfLaterAndLastWatchedEpisodeId(showIdsToLastWatched, database.sgEpisode2Helper());
    }
    // store new last sync time
    PreferenceManager.getDefaultSharedPreferences(context).edit().putLong(HexagonSettings.KEY_LAST_SYNC_EPISODES, currentTime).apply();
    return true;
}
Also used : SgCloudEpisode(com.uwetrottmann.seriesguide.backend.episodes.model.SgCloudEpisode) SgRoomDatabase(com.battlelancer.seriesguide.provider.SgRoomDatabase) HashMap(java.util.HashMap) SgCloudEpisodeList(com.uwetrottmann.seriesguide.backend.episodes.model.SgCloudEpisodeList) ArrayList(java.util.ArrayList) IOException(java.io.IOException) DateTime(com.google.api.client.util.DateTime) SgEpisode2UpdateByNumber(com.battlelancer.seriesguide.provider.SgEpisode2UpdateByNumber) Episodes(com.uwetrottmann.seriesguide.backend.episodes.Episodes)

Example 4 with SgRoomDatabase

use of com.battlelancer.seriesguide.provider.SgRoomDatabase in project SeriesGuide by UweTrottmann.

the class EpisodeWatchedJob method getLastWatchedEpisodeId.

private long getLastWatchedEpisodeId(Context context) {
    if (!EpisodeTools.isUnwatched(getFlagValue())) {
        // watched or skipped episode
        return episodeId;
    } else {
        // changed episode to not watched
        // don't change last watched episode by default
        long lastWatchedId = -1;
        // if modified episode is identical to last watched one (e.g. was just watched),
        // find an appropriate last watched episode
        SgRoomDatabase database = SgRoomDatabase.getInstance(context);
        long lastWatchedEpisodeId = database.sgShow2Helper().getShowLastWatchedEpisodeId(getShowId());
        // identical to last watched episode?
        if (episodeId == lastWatchedEpisodeId) {
            if (getEpisode().getSeason() == 0) {
                // keep last watched (= this episode) if we got a special
                return -1;
            }
            // re-set if we don't find one
            lastWatchedId = 0;
            // get newest watched before this one
            long previousWatchedEpisodeId = database.sgEpisode2Helper().getPreviousWatchedEpisodeOfShow(getShowId(), getEpisode().getSeason(), getEpisode().getEpisodenumber());
            if (previousWatchedEpisodeId > 0) {
                lastWatchedId = previousWatchedEpisodeId;
            }
        }
        return lastWatchedId;
    }
}
Also used : SgRoomDatabase(com.battlelancer.seriesguide.provider.SgRoomDatabase)

Example 5 with SgRoomDatabase

use of com.battlelancer.seriesguide.provider.SgRoomDatabase in project SeriesGuide by UweTrottmann.

the class TraktTask method doCheckInAction.

private TraktResponse doCheckInAction() {
    TraktV2 trakt = SgApp.getServicesComponent(context).trakt();
    try {
        retrofit2.Response response;
        String message = args.getString(InitBundle.MESSAGE);
        switch(action) {
            case CHECKIN_EPISODE:
                {
                    // Check in using show Trakt ID
                    // and season and episode number (likely most reliable).
                    long episodeId = args.getLong(InitBundle.EPISODE_ID);
                    SgRoomDatabase database = SgRoomDatabase.getInstance(context);
                    SgEpisode2Numbers episode = database.sgEpisode2Helper().getEpisodeNumbers(episodeId);
                    if (episode == null) {
                        Timber.e("Failed to get episode %d", episodeId);
                        return buildErrorResponse();
                    }
                    Integer showTraktId = ShowTools.getShowTraktId(context, episode.getShowId());
                    if (showTraktId == null) {
                        Timber.e("Failed to get show %d", episode.getShowId());
                        return buildErrorResponse();
                    }
                    SyncEpisode traktEpisode = new SyncEpisode().season(episode.getSeason()).number(episode.getEpisodenumber());
                    Show traktShow = new Show();
                    traktShow.ids = ShowIds.trakt(showTraktId);
                    EpisodeCheckin checkin = new EpisodeCheckin.Builder(traktEpisode, APP_VERSION, null).show(traktShow).message(message).build();
                    response = trakt.checkin().checkin(checkin).execute();
                    break;
                }
            case CHECKIN_MOVIE:
                {
                    int movieTmdbId = args.getInt(InitBundle.MOVIE_TMDB_ID);
                    MovieCheckin checkin = new MovieCheckin.Builder(new SyncMovie().id(MovieIds.tmdb(movieTmdbId)), APP_VERSION, null).message(message).build();
                    response = trakt.checkin().checkin(checkin).execute();
                    break;
                }
            default:
                throw new IllegalArgumentException("check-in action unknown.");
        }
        if (response.isSuccessful()) {
            return new TraktResponse(true, context.getString(R.string.checkin_success_trakt, args.getString(InitBundle.TITLE)));
        } else {
            // check if the user wants to check-in, but there is already a check-in in progress
            CheckinError checkinError = trakt.checkForCheckinError(response);
            if (checkinError != null) {
                OffsetDateTime expiresAt = checkinError.expires_at;
                int waitTimeMin = expiresAt == null ? -1 : (int) ((expiresAt.toInstant().toEpochMilli() - System.currentTimeMillis()) / 1000);
                return new CheckinBlockedResponse(waitTimeMin);
            } else // check if item does not exist on trakt (yet)
            if (response.code() == 404) {
                return new TraktResponse(false, context.getString(R.string.trakt_error_not_exists));
            } else if (SgTrakt.isUnauthorized(context, response)) {
                return new TraktResponse(false, context.getString(R.string.trakt_error_credentials));
            } else {
                Errors.logAndReport("check-in", response);
            }
        }
    } catch (Exception e) {
        Errors.logAndReport("check-in", e);
    }
    // return generic failure message
    return buildErrorResponse();
}
Also used : CheckinError(com.uwetrottmann.trakt5.entities.CheckinError) SyncEpisode(com.uwetrottmann.trakt5.entities.SyncEpisode) SgRoomDatabase(com.battlelancer.seriesguide.provider.SgRoomDatabase) EpisodeCheckin(com.uwetrottmann.trakt5.entities.EpisodeCheckin) SuppressLint(android.annotation.SuppressLint) MovieCheckin(com.uwetrottmann.trakt5.entities.MovieCheckin) TraktV2(com.uwetrottmann.trakt5.TraktV2) OffsetDateTime(org.threeten.bp.OffsetDateTime) SgEpisode2Numbers(com.battlelancer.seriesguide.provider.SgEpisode2Numbers) SyncMovie(com.uwetrottmann.trakt5.entities.SyncMovie) Show(com.uwetrottmann.trakt5.entities.Show)

Aggregations

SgRoomDatabase (com.battlelancer.seriesguide.provider.SgRoomDatabase)5 SgEpisode2Numbers (com.battlelancer.seriesguide.provider.SgEpisode2Numbers)3 SyncEpisode (com.uwetrottmann.trakt5.entities.SyncEpisode)2 SuppressLint (android.annotation.SuppressLint)1 Nullable (androidx.annotation.Nullable)1 SgEpisode2UpdateByNumber (com.battlelancer.seriesguide.provider.SgEpisode2UpdateByNumber)1 DateTime (com.google.api.client.util.DateTime)1 Episodes (com.uwetrottmann.seriesguide.backend.episodes.Episodes)1 SgCloudEpisode (com.uwetrottmann.seriesguide.backend.episodes.model.SgCloudEpisode)1 SgCloudEpisodeList (com.uwetrottmann.seriesguide.backend.episodes.model.SgCloudEpisodeList)1 TraktV2 (com.uwetrottmann.trakt5.TraktV2)1 CheckinError (com.uwetrottmann.trakt5.entities.CheckinError)1 EpisodeCheckin (com.uwetrottmann.trakt5.entities.EpisodeCheckin)1 MovieCheckin (com.uwetrottmann.trakt5.entities.MovieCheckin)1 Show (com.uwetrottmann.trakt5.entities.Show)1 SyncItems (com.uwetrottmann.trakt5.entities.SyncItems)1 SyncMovie (com.uwetrottmann.trakt5.entities.SyncMovie)1 SyncSeason (com.uwetrottmann.trakt5.entities.SyncSeason)1 SyncShow (com.uwetrottmann.trakt5.entities.SyncShow)1 IOException (java.io.IOException)1