Search in sources :

Example 1 with InvalidCredentialsException

use of com.pokegoapi.exceptions.request.InvalidCredentialsException 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(null, 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 responseEnvelop;
        try (InputStream content = response.body().byteStream()) {
            responseEnvelop = ResponseEnvelope.parseFrom(content);
        } catch (IOException e) {
            // retrieved garbage from the server
            throw new RequestFailedException("Received malformed response : " + e);
        }
        if (responseEnvelop.getApiUrl() != null && responseEnvelop.getApiUrl().length() > 0) {
            apiEndpoint = "https://" + responseEnvelop.getApiUrl() + "/rpc";
        }
        if (responseEnvelop.hasAuthTicket()) {
            this.authTicket = responseEnvelop.getAuthTicket();
        }
        boolean empty = false;
        StatusCode statusCode = responseEnvelop.getStatusCode();
        if (statusCode != StatusCode.REDIRECT && statusCode != StatusCode.INVALID_AUTH_TOKEN) {
            for (int i = 0; i < responseEnvelop.getReturnsCount(); i++) {
                ByteString returned = responseEnvelop.getReturns(i);
                ServerRequest serverRequest = requests[i];
                if (returned != null) {
                    serverResponse.addResponse(serverRequest.getType(), returned);
                    if (serverRequest.getType() == RequestType.GET_PLAYER) {
                        if (GetPlayerResponse.parseFrom(returned).getBanned()) {
                            throw new BannedException("Cannot send request, your account has been banned!");
                        }
                    }
                } else {
                    empty = true;
                }
            }
        }
        for (int i = 0; i < responseEnvelop.getPlatformReturnsCount(); i++) {
            PlatformResponse platformResponse = responseEnvelop.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.getPlayerProfile().isBanned()) {
                    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);
            }
        }
        if (empty) {
            throw new RequestFailedException("Received empty response from server!");
        }
    } 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 2 with InvalidCredentialsException

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

the class PtcCredentialProvider method login.

/**
	 * Starts a login flow for pokemon.com (PTC) using a username and password,
	 * this uses pokemon.com's oauth endpoint and returns a usable AuthInfo without user interaction
	 *
	 * @param username PTC username
	 * @param password PTC password
	 * @param attempt the current attempt index
	 * @throws LoginFailedException if an exception occurs while attempting to log in
	 * @throws InvalidCredentialsException if invalid credentials are used
	 */
private void login(String username, String password, int attempt) throws LoginFailedException, InvalidCredentialsException {
    try {
        //TODO: stop creating an okhttp client per request
        Request get = new Request.Builder().url(LOGIN_URL).get().build();
        Response getResponse;
        try {
            getResponse = client.newCall(get).execute();
        } catch (IOException e) {
            throw new LoginFailedException("Failed to receive contents from server", e);
        }
        Moshi moshi = new Moshi.Builder().build();
        PtcAuthJson ptcAuth;
        try {
            String response = getResponse.body().string();
            ptcAuth = moshi.adapter(PtcAuthJson.class).fromJson(response);
        } catch (IOException e) {
            throw new LoginFailedException("Looks like the servers are down", e);
        }
        HttpUrl url = HttpUrl.parse(LOGIN_URL).newBuilder().addQueryParameter("lt", ptcAuth.getLt()).addQueryParameter("execution", ptcAuth.getExecution()).addQueryParameter("_eventId", "submit").addQueryParameter("username", username).addQueryParameter("password", password).build();
        RequestBody reqBody = RequestBody.create(null, new byte[0]);
        Request postRequest = new Request.Builder().url(url).method("POST", reqBody).build();
        // Need a new client for this to not follow redirects
        Response response;
        try {
            response = client.newBuilder().followRedirects(false).followSslRedirects(false).build().newCall(postRequest).execute();
        } catch (IOException e) {
            throw new LoginFailedException("Network failure", e);
        }
        String body;
        try {
            body = response.body().string();
        } catch (IOException e) {
            throw new LoginFailedException("Response body fetching failed", e);
        }
        if (body.length() > 0) {
            PtcError ptcError;
            try {
                ptcError = moshi.adapter(PtcError.class).fromJson(body);
            } catch (IOException e) {
                throw new LoginFailedException("Unmarshalling failure", e);
            }
            if (ptcError.getError() != null && ptcError.getError().length() > 0) {
                throw new InvalidCredentialsException(ptcError.getError());
            } else if (ptcError.getErrors().length > 0) {
                StringBuilder builder = new StringBuilder();
                String[] errors = ptcError.getErrors();
                for (int i = 0; i < errors.length - 1; i++) {
                    String error = errors[i];
                    builder.append("\"").append(error).append("\", ");
                }
                builder.append("\"").append(errors[errors.length - 1]).append("\"");
                throw new InvalidCredentialsException(builder.toString());
            }
        }
        String ticket = null;
        for (String location : response.headers("location")) {
            String[] ticketArray = location.split("ticket=");
            if (ticketArray.length > 1) {
                ticket = ticketArray[1];
            }
        }
        if (ticket == null) {
            throw new LoginFailedException("Failed to fetch token, body:" + body);
        }
        url = HttpUrl.parse(LOGIN_OAUTH).newBuilder().addQueryParameter("client_id", CLIENT_ID).addQueryParameter("redirect_uri", REDIRECT_URI).addQueryParameter("client_secret", CLIENT_SECRET).addQueryParameter("grant_type", "refreshToken").addQueryParameter("code", ticket).build();
        postRequest = new Request.Builder().url(url).method("POST", reqBody).build();
        try {
            response = client.newCall(postRequest).execute();
        } catch (IOException e) {
            throw new LoginFailedException("Network Failure ", e);
        }
        try {
            body = response.body().string();
        } catch (IOException e) {
            throw new LoginFailedException("Network failure", e);
        }
        String[] params;
        try {
            params = body.split("&");
            int expire = Integer.valueOf(params[1].split("=")[1]);
            tokenId = params[0].split("=")[1];
            expiresTimestamp = time.currentTimeMillis() + (expire * 1000 - REFRESH_TOKEN_BUFFER_TIME);
            unknown2 = expire;
            if (random.nextDouble() > 0.1) {
                unknown2 = UK2_VALUES[random.nextInt(UK2_VALUES.length)];
            }
        } catch (Exception e) {
            throw new LoginFailedException("Failed to fetch token, body:" + body);
        }
    } catch (LoginFailedException e) {
        if (shouldRetry && attempt < MAXIMUM_RETRIES) {
            login(username, password, ++attempt);
        }
    }
}
Also used : Moshi(com.squareup.moshi.Moshi) Request(okhttp3.Request) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) InvalidCredentialsException(com.pokegoapi.exceptions.request.InvalidCredentialsException) IOException(java.io.IOException) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) Response(okhttp3.Response) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) InvalidCredentialsException(com.pokegoapi.exceptions.request.InvalidCredentialsException) RequestBody(okhttp3.RequestBody)

Example 3 with InvalidCredentialsException

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

the class GoogleCredentialProvider method refreshToken.

/**
	 * Given the refresh token fetches a new access token and returns AuthInfo.
	 *
	 * @param refreshToken Refresh token persisted by the user after initial login
	 * @throws LoginFailedException if an exception occurs while attempting to log in
	 * @throws InvalidCredentialsException if invalid credentials are used
	 */
public void refreshToken(String refreshToken) throws LoginFailedException, InvalidCredentialsException {
    HttpUrl url = HttpUrl.parse(OAUTH_TOKEN_ENDPOINT).newBuilder().addQueryParameter("client_id", CLIENT_ID).addQueryParameter("client_secret", SECRET).addQueryParameter("refresh_token", refreshToken).addQueryParameter("grant_type", "refresh_token").build();
    //Empty request body
    RequestBody reqBody = RequestBody.create(null, new byte[0]);
    Request request = new Request.Builder().url(url).method("POST", reqBody).build();
    Response response = null;
    try {
        response = client.newCall(request).execute();
    } catch (IOException e) {
        throw new LoginFailedException("Network Request failed to fetch refreshed tokenId", e);
    }
    Moshi moshi = new Moshi.Builder().build();
    GoogleAuthTokenJson googleAuthTokenJson = null;
    try {
        googleAuthTokenJson = moshi.adapter(GoogleAuthTokenJson.class).fromJson(response.body().string());
        Log.d(TAG, "" + googleAuthTokenJson.getExpiresIn());
    } catch (IOException e) {
        throw new LoginFailedException("Failed to unmarshal the Json response to fetch refreshed tokenId", e);
    }
    if (googleAuthTokenJson.getError() != null) {
        throw new InvalidCredentialsException(googleAuthTokenJson.getError());
    } else {
        Log.d(TAG, "Refreshed Token " + googleAuthTokenJson.getIdToken());
        expiresTimestamp = System.currentTimeMillis() + (googleAuthTokenJson.getExpiresIn() * 1000 - REFRESH_TOKEN_BUFFER_TIME);
        tokenId = googleAuthTokenJson.getIdToken();
    }
}
Also used : Response(okhttp3.Response) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) Moshi(com.squareup.moshi.Moshi) InvalidCredentialsException(com.pokegoapi.exceptions.request.InvalidCredentialsException) Request(okhttp3.Request) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) RequestBody(okhttp3.RequestBody)

Aggregations

InvalidCredentialsException (com.pokegoapi.exceptions.request.InvalidCredentialsException)3 LoginFailedException (com.pokegoapi.exceptions.request.LoginFailedException)3 IOException (java.io.IOException)3 RequestBody (okhttp3.RequestBody)3 Response (okhttp3.Response)3 Moshi (com.squareup.moshi.Moshi)2 HttpUrl (okhttp3.HttpUrl)2 Request (okhttp3.Request)2 RequestEnvelope (POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope)1 PlatformRequest (POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope.PlatformRequest)1 ResponseEnvelope (POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope)1 PlatformResponse (POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope.PlatformResponse)1 StatusCode (POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope.StatusCode)1 Request (POGOProtos.Networking.Requests.RequestOuterClass.Request)1 GetPlayerResponse (POGOProtos.Networking.Responses.GetPlayerResponseOuterClass.GetPlayerResponse)1 ByteString (com.google.protobuf.ByteString)1 BadRequestException (com.pokegoapi.exceptions.request.BadRequestException)1 BannedException (com.pokegoapi.exceptions.request.BannedException)1 RequestFailedException (com.pokegoapi.exceptions.request.RequestFailedException)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1