Search in sources :

Example 26 with RequestFailedException

use of com.pokegoapi.exceptions.request.RequestFailedException in project PokeGOAPI-Java by Grover-c13.

the class PlayerProfile method encounterTutorialComplete.

/**
 * Encounter tutorial complete. In other words, catch the first Pokémon
 *
 * @throws RequestFailedException if an exception occurred while sending requests
 */
public void encounterTutorialComplete() throws RequestFailedException {
    StarterPokemon starter = StarterPokemon.random();
    List<TutorialListener> listeners = api.getListeners(TutorialListener.class);
    for (TutorialListener listener : listeners) {
        StarterPokemon pokemon = listener.selectStarter(api);
        if (pokemon != null) {
            starter = pokemon;
            break;
        }
    }
    final EncounterTutorialCompleteMessage.Builder builder = EncounterTutorialCompleteMessage.newBuilder().setPokemonId(starter.pokemon);
    ServerRequest request = new ServerRequest(RequestType.ENCOUNTER_TUTORIAL_COMPLETE, builder.build());
    api.requestHandler.sendServerRequests(request, true);
    final GetPlayerMessage getPlayerReqMsg = GetPlayerMessage.newBuilder().setPlayerLocale(playerLocale.getPlayerLocale()).build();
    request = new ServerRequest(RequestType.GET_PLAYER, getPlayerReqMsg);
    api.requestHandler.sendServerRequests(request, true);
    try {
        updateProfile(GetPlayerResponse.parseFrom(request.getData()));
    } catch (InvalidProtocolBufferException e) {
        throw new RequestFailedException(e);
    }
}
Also used : GetPlayerMessage(POGOProtos.Networking.Requests.Messages.GetPlayerMessageOuterClass.GetPlayerMessage) EncounterTutorialCompleteMessage(POGOProtos.Networking.Requests.Messages.EncounterTutorialCompleteMessageOuterClass.EncounterTutorialCompleteMessage) TutorialListener(com.pokegoapi.api.listener.TutorialListener) RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) ServerRequest(com.pokegoapi.main.ServerRequest) StarterPokemon(com.pokegoapi.api.pokemon.StarterPokemon)

Example 27 with RequestFailedException

use of com.pokegoapi.exceptions.request.RequestFailedException in project PokeGOAPI-Java by Grover-c13.

the class PlayerProfile method acceptLevelUpRewards.

/**
 * Accept the rewards granted and the items unlocked by gaining a trainer level up. Rewards are retained by the
 * server until a player actively accepts them.
 * The rewarded items are automatically inserted into the players item bag.
 *
 * @param level the trainer level that you want to accept the rewards for
 * @return a PlayerLevelUpRewards object containing information about the items rewarded and unlocked for this level
 * @throws RequestFailedException if an exception occurred while sending requests
 * @throws InsufficientLevelException if you have not yet reached the desired level
 * @see PlayerLevelUpRewards
 */
public PlayerLevelUpRewards acceptLevelUpRewards(int level) throws RequestFailedException {
    // Check if we even have achieved this level yet
    if (level > stats.getLevel()) {
        throw new InsufficientLevelException();
    }
    LevelUpRewardsMessage msg = LevelUpRewardsMessage.newBuilder().setLevel(level).build();
    ServerRequest serverRequest = new ServerRequest(RequestType.LEVEL_UP_REWARDS, msg);
    api.requestHandler.sendServerRequests(serverRequest, true);
    LevelUpRewardsResponse response;
    try {
        response = LevelUpRewardsResponse.parseFrom(serverRequest.getData());
    } catch (InvalidProtocolBufferException e) {
        throw new RequestFailedException(e);
    }
    // Add the awarded items to our bag
    ItemBag bag = api.inventories.itemBag;
    bag.addAwardedItems(response);
    // Build a new rewards object and return it
    return new PlayerLevelUpRewards(response);
}
Also used : InsufficientLevelException(com.pokegoapi.exceptions.InsufficientLevelException) LevelUpRewardsMessage(POGOProtos.Networking.Requests.Messages.LevelUpRewardsMessageOuterClass.LevelUpRewardsMessage) RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) ServerRequest(com.pokegoapi.main.ServerRequest) LevelUpRewardsResponse(POGOProtos.Networking.Responses.LevelUpRewardsResponseOuterClass.LevelUpRewardsResponse) ItemBag(com.pokegoapi.api.inventory.ItemBag)

Example 28 with RequestFailedException

use of com.pokegoapi.exceptions.request.RequestFailedException in project PokeGOAPI-Java by Grover-c13.

the class ItemTemplates method updatePage.

/**
 * Updates {@link ItemTemplate} pages recursively
 *
 * @param api the current api
 * @param page the current page index
 * @param timestamp the timestamp of this page
 * @param loadTime the time at which the templates started loading
 * @throws RequestFailedException if the page update is not successfully sent
 */
private void updatePage(PokemonGo api, int page, long timestamp, long loadTime) throws RequestFailedException {
    DownloadItemTemplatesMessage message = DownloadItemTemplatesMessage.newBuilder().setPaginate(true).setPageOffset(page).setPageTimestamp(timestamp).build();
    ServerRequest request = new ServerRequest(RequestType.DOWNLOAD_ITEM_TEMPLATES, message);
    api.requestHandler.sendServerRequests(request, true);
    try {
        DownloadItemTemplatesResponse response = DownloadItemTemplatesResponse.parseFrom(request.getData());
        provider.updateTemplates(response, loadTime);
        if (response.getResult() == Result.PAGE) {
            updatePage(api, response.getPageOffset(), response.getTimestampMs(), loadTime);
        }
    } catch (IOException e) {
        throw new RequestFailedException(e);
    }
}
Also used : RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) DownloadItemTemplatesMessage(POGOProtos.Networking.Requests.Messages.DownloadItemTemplatesMessageOuterClass.DownloadItemTemplatesMessage) DownloadItemTemplatesResponse(POGOProtos.Networking.Responses.DownloadItemTemplatesResponseOuterClass.DownloadItemTemplatesResponse) IOException(java.io.IOException) ServerRequest(com.pokegoapi.main.ServerRequest)

Example 29 with RequestFailedException

use of com.pokegoapi.exceptions.request.RequestFailedException in project PokeGOAPI-Java by Grover-c13.

the class RequestHandler method sendInternal.

/**
 * Sends an already built request envelope
 *
 * @param serverResponse the response to append to
 * @param requests list of ServerRequests to be sent
 * @param platformRequests list of ServerPlatformRequests to be sent
 * @param builder the request envelope builder
 * @throws RequestFailedException if this message fails to send
 */
private ServerResponse sendInternal(ServerResponse serverResponse, ServerRequest[] requests, ServerPlatformRequest[] platformRequests, RequestEnvelope.Builder builder) throws RequestFailedException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    RequestEnvelope request = builder.build();
    try {
        request.writeTo(stream);
    } catch (IOException e) {
        Log.wtf(TAG, "Failed to write request to bytearray ouput stream. This should never happen", e);
    }
    RequestBody body = RequestBody.create(BINARY_MEDIA, stream.toByteArray());
    okhttp3.Request httpRequest = new okhttp3.Request.Builder().url(apiEndpoint).post(body).build();
    try (Response response = client.newCall(httpRequest).execute()) {
        if (response.code() != 200) {
            throw new RequestFailedException("Got a unexpected http code : " + response.code());
        }
        ResponseEnvelope responseEnvelope;
        try (InputStream content = response.body().byteStream()) {
            responseEnvelope = ResponseEnvelope.parseFrom(content);
        } catch (IOException e) {
            // retrieved garbage from the server
            throw new RequestFailedException("Received malformed response : " + e);
        }
        if (responseEnvelope.getApiUrl() != null && responseEnvelope.getApiUrl().length() > 0) {
            apiEndpoint = "https://" + responseEnvelope.getApiUrl() + "/rpc";
        }
        if (responseEnvelope.hasAuthTicket()) {
            authTicket = responseEnvelope.getAuthTicket();
        }
        StatusCode statusCode = responseEnvelope.getStatusCode();
        if (requests.length > 0) {
            for (int i = 0; i < responseEnvelope.getReturnsCount(); i++) {
                ByteString returned = responseEnvelope.getReturns(i);
                ServerRequest serverRequest = requests[i];
                if (returned != null) {
                    serverResponse.addResponse(serverRequest.type, returned);
                    if (serverRequest.type == RequestType.GET_PLAYER) {
                        if (GetPlayerResponse.parseFrom(returned).getBanned()) {
                            throw new BannedException("Cannot send request, your account has been banned!");
                        }
                    }
                } else {
                    throw new RequestFailedException("Received empty response from server");
                }
            }
        }
        for (int i = 0; i < responseEnvelope.getPlatformReturnsCount(); i++) {
            PlatformResponse platformResponse = responseEnvelope.getPlatformReturns(i);
            ByteString returned = platformResponse.getResponse();
            if (returned != null) {
                serverResponse.addResponse(platformResponse.getType(), returned);
            }
        }
        if (statusCode != StatusCode.OK && statusCode != StatusCode.OK_RPC_URL_IN_RESPONSE) {
            if (statusCode == StatusCode.INVALID_AUTH_TOKEN) {
                try {
                    authTicket = null;
                    api.getAuthInfo(true);
                    return sendInternal(serverResponse, requests, platformRequests);
                } catch (LoginFailedException | InvalidCredentialsException e) {
                    throw new RequestFailedException("Failed to refresh auth token!", e);
                } catch (RequestFailedException e) {
                    throw new RequestFailedException("Failed to send request with refreshed auth token!", e);
                }
            } else if (statusCode == StatusCode.REDIRECT) {
                // API_ENDPOINT was not correctly set, should be at this point, though, so redo the request
                return sendInternal(serverResponse, requests, platformRequests, builder);
            } else if (statusCode == StatusCode.BAD_REQUEST) {
                if (api.playerProfile.banned) {
                    throw new BannedException("Cannot send request, your account has been banned!");
                } else {
                    throw new BadRequestException("A bad request was sent!");
                }
            } else {
                throw new RequestFailedException("Failed to send request: " + statusCode);
            }
        }
    } catch (IOException e) {
        throw new RequestFailedException(e);
    } catch (RequestFailedException e) {
        throw e;
    }
    return serverResponse;
}
Also used : InputStream(java.io.InputStream) ByteString(com.google.protobuf.ByteString) PlatformRequest(POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope.PlatformRequest) Request(POGOProtos.Networking.Requests.RequestOuterClass.Request) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) StatusCode(POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope.StatusCode) PlatformResponse(POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope.PlatformResponse) Response(okhttp3.Response) GetPlayerResponse(POGOProtos.Networking.Responses.GetPlayerResponseOuterClass.GetPlayerResponse) ResponseEnvelope(POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) InvalidCredentialsException(com.pokegoapi.exceptions.request.InvalidCredentialsException) BannedException(com.pokegoapi.exceptions.request.BannedException) RequestEnvelope(POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope) BadRequestException(com.pokegoapi.exceptions.request.BadRequestException) PlatformResponse(POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope.PlatformResponse) RequestBody(okhttp3.RequestBody)

Example 30 with RequestFailedException

use of com.pokegoapi.exceptions.request.RequestFailedException in project PokeGOAPI-Java by Grover-c13.

the class RequestHandler method sendServerRequests.

/**
 * Sends a single ServerRequest
 *
 * @param request the request to send
 * @param commons whether this request should include commons
 * @return the result from this request
 * @throws RequestFailedException if an exception occurred while sending requests
 */
public ByteString sendServerRequests(ServerRequest request, boolean commons) throws RequestFailedException {
    ServerRequestEnvelope envelope = ServerRequestEnvelope.create(request, api, commons);
    AsyncHelper.toBlocking(sendAsyncServerRequests(envelope));
    try {
        return request.getData();
    } catch (InvalidProtocolBufferException e) {
        throw new RequestFailedException(e);
    }
}
Also used : RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException)

Aggregations

RequestFailedException (com.pokegoapi.exceptions.request.RequestFailedException)50 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)39 ServerRequest (com.pokegoapi.main.ServerRequest)37 ByteString (com.google.protobuf.ByteString)10 OkHttpClient (okhttp3.OkHttpClient)9 PokemonGo (com.pokegoapi.api.PokemonGo)7 PtcCredentialProvider (com.pokegoapi.auth.PtcCredentialProvider)7 HashProvider (com.pokegoapi.util.hash.HashProvider)7 ArrayList (java.util.ArrayList)6 TutorialListener (com.pokegoapi.api.listener.TutorialListener)4 Pokemon (com.pokegoapi.api.pokemon.Pokemon)4 GetPlayerMessage (POGOProtos.Networking.Requests.Messages.GetPlayerMessageOuterClass.GetPlayerMessage)3 Item (com.pokegoapi.api.inventory.Item)3 ItemBag (com.pokegoapi.api.inventory.ItemBag)3 Point (com.pokegoapi.api.map.Point)3 IOException (java.io.IOException)3 PokemonFamilyId (POGOProtos.Enums.PokemonFamilyIdOuterClass.PokemonFamilyId)2 PokemonId (POGOProtos.Enums.PokemonIdOuterClass.PokemonId)2 TutorialState (POGOProtos.Enums.TutorialStateOuterClass.TutorialState)2 LevelUpRewardsMessage (POGOProtos.Networking.Requests.Messages.LevelUpRewardsMessageOuterClass.LevelUpRewardsMessage)2