Thanks to visit codestin.com
Credit goes to github.com

Skip to content

abstract time behavior to allow mocking #277

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 27, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions src/main/java/com/pokegoapi/api/PokemonGo.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import com.pokegoapi.exceptions.RemoteServerException;
import com.pokegoapi.main.RequestHandler;
import com.pokegoapi.util.Log;
import com.pokegoapi.util.SystemTimeImpl;
import com.pokegoapi.util.Time;
import lombok.Getter;
import lombok.Setter;
import okhttp3.OkHttpClient;
Expand All @@ -32,6 +34,7 @@
public class PokemonGo {

private static final java.lang.String TAG = PokemonGo.class.getSimpleName();
private final Time time;
@Getter
RequestHandler requestHandler;
@Getter
Expand All @@ -49,24 +52,28 @@ public class PokemonGo {
@Getter
@Setter
private double altitude;

private CredentialProvider credentialProvider;

private RequestEnvelopeOuterClass.RequestEnvelope.AuthInfo authInfo;

/**
* Instantiates a new Pokemon go.
*
* @param client the client
* @param credentialProvider the credential provider
* @param client the http client
* @param time a time implementation
* @throws LoginFailedException When login fails
* @throws RemoteServerException When server fails
*/
public PokemonGo(CredentialProvider credentialProvider, OkHttpClient client)
public PokemonGo(CredentialProvider credentialProvider, OkHttpClient client, Time time)
throws LoginFailedException, RemoteServerException {

if (credentialProvider == null) {
throw new LoginFailedException("Credential Provider is null");
} else {
this.credentialProvider = credentialProvider;
}
this.time = time;

playerProfile = null;

Expand All @@ -82,6 +89,21 @@ public PokemonGo(CredentialProvider credentialProvider, OkHttpClient client)
map = new Map(this);
}

/**
* Instantiates a new Pokemon go.
* Deprecated: specify a time implementation
*
* @param credentialProvider the credential provider
* @param client the http client
* @throws LoginFailedException When login fails
* @throws RemoteServerException When server fails
*/
@Deprecated
public PokemonGo(CredentialProvider credentialProvider, OkHttpClient client)
throws LoginFailedException, RemoteServerException {
this(credentialProvider, client, new SystemTimeImpl());
}

/**
* Fetches valid AuthInfo
*
Expand Down Expand Up @@ -124,4 +146,8 @@ public void setLocation(double latitude, double longitude, double altitude) {
setLongitude(longitude);
setAltitude(altitude);
}

public long currentTimeMillis() {
return time.currentTimeMillis();
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/pokegoapi/api/gym/Battle.java
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public AttackGymResponse attack(int times) throws LoginFailedException, RemoteSe
BattleAction action = BattleAction
.newBuilder()
.setType(BattleActionTypeOuterClass.BattleActionType.ACTION_ATTACK)
.setActionStartMs(System.currentTimeMillis() + (100 * times))
.setActionStartMs(api.currentTimeMillis() + (100 * times))
.setDurationMs(500)
.setTargetIndex(-1)
.build();
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/pokegoapi/api/inventory/Inventories.java
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public void updateInventories(boolean forceUpdate) throws LoginFailedException,
}
}

lastInventoryUpdate = System.currentTimeMillis();
lastInventoryUpdate = api.currentTimeMillis();
}
}
}
4 changes: 2 additions & 2 deletions src/main/java/com/pokegoapi/api/map/Map.java
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ public MapObjects getMapObjects(List<Long> cellIds, double latitude, double long
public MapObjects getMapObjects(List<Long> cellIds) throws LoginFailedException, RemoteServerException {
GetMapObjectsMessage.Builder builder = GetMapObjectsMessage.newBuilder();

if (useCache && (System.currentTimeMillis() - lastMapUpdate > mapObjectsExpiry)) {
if (useCache && (api.currentTimeMillis() - lastMapUpdate > mapObjectsExpiry)) {
lastMapUpdate = 0;
cachedMapObjects = new MapObjects(api);
}
Expand Down Expand Up @@ -331,7 +331,7 @@ public FortType apply(FortData fortData) {
if (useCache) {
cachedMapObjects.update(result);
result = cachedMapObjects;
lastMapUpdate = System.currentTimeMillis();
lastMapUpdate = api.currentTimeMillis();
}

return result;
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/pokegoapi/api/map/fort/Pokestop.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public boolean canLoot() {
* @return the boolean
*/
public boolean canLoot(boolean ignoreDistance) {
boolean active = cooldownCompleteTimestampMs < System.currentTimeMillis();
boolean active = cooldownCompleteTimestampMs < api.currentTimeMillis();
if (!ignoreDistance) {
return active && inRange();
}
Expand Down Expand Up @@ -184,6 +184,6 @@ public FortDetails getDetails() throws LoginFailedException, RemoteServerExcepti
* @return lure status
*/
public boolean hasLurePokemon() {
return fortData.hasLureInfo() && fortData.getLureInfo().getLureExpiresTimestampMs() < System.currentTimeMillis();
return fortData.hasLureInfo() && fortData.getLureInfo().getLureExpiresTimestampMs() < api.currentTimeMillis();
}
}
11 changes: 9 additions & 2 deletions src/main/java/com/pokegoapi/api/pokemon/Pokemon.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import POGOProtos.Networking.Requests.RequestTypeOuterClass.RequestType;
import POGOProtos.Networking.Responses.EvolvePokemonResponseOuterClass.EvolvePokemonResponse;
import POGOProtos.Networking.Responses.NicknamePokemonResponseOuterClass.NicknamePokemonResponse;
import POGOProtos.Networking.Responses.RecycleInventoryItemResponseOuterClass;
import POGOProtos.Networking.Responses.ReleasePokemonResponseOuterClass.ReleasePokemonResponse;
import POGOProtos.Networking.Responses.ReleasePokemonResponseOuterClass.ReleasePokemonResponse.Result;
import POGOProtos.Networking.Responses.SetFavoritePokemonResponseOuterClass.SetFavoritePokemonResponse;
Expand Down Expand Up @@ -64,6 +63,13 @@ public class Pokemon {
// API METHODS //

// DELEGATE METHODS BELOW //

/**
* Creates a Pokemon object with helper functions around the proto.
*
* @param api the api to use
* @param proto the proto from the server
*/
public Pokemon(PokemonGo api, PokemonData proto) {
this.pgo = api;
this.proto = proto;
Expand Down Expand Up @@ -347,9 +353,10 @@ public String getEggIncubatorId() {
public long getCreationTimeMs() {
return proto.getCreationTimeMs();
}

/**
* Checks whether the Pokémon is set as favorite.
*
* @return true if the Pokémon is set as favorite
*/
public boolean isFavorite() {
Expand Down
69 changes: 55 additions & 14 deletions src/main/java/com/pokegoapi/auth/GoogleCredentialProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import com.pokegoapi.exceptions.LoginFailedException;
import com.pokegoapi.exceptions.RemoteServerException;
import com.pokegoapi.util.Log;
import com.pokegoapi.util.Time;
import com.pokegoapi.util.SystemTimeImpl;
import com.squareup.moshi.Moshi;
import lombok.Getter;
import okhttp3.HttpUrl;
Expand All @@ -42,6 +44,7 @@ public class GoogleCredentialProvider extends CredentialProvider {
private final OkHttpClient client;

private final OnGoogleLoginOAuthCompleteListener onGoogleLoginOAuthCompleteListener;
private final Time time;

private long expiresTimestamp;

Expand All @@ -54,30 +57,51 @@ public class GoogleCredentialProvider extends CredentialProvider {

/**
* Used for logging in when one has a persisted refreshToken.
* Deprecated: specify a Time implementation
*
* @param client OkHttp client
* @param refreshToken Refresh Token Persisted by user
* @throws LoginFailedException When login fails
* @param time a Time implementation
* @throws LoginFailedException When login fails
* @throws RemoteServerException When server fails
*/
public GoogleCredentialProvider(OkHttpClient client, String refreshToken)
public GoogleCredentialProvider(OkHttpClient client, String refreshToken, Time time)
throws LoginFailedException, RemoteServerException {
this.client = client;
this.refreshToken = refreshToken;
onGoogleLoginOAuthCompleteListener = null;
refreshToken(refreshToken);
authbuilder = AuthInfo.newBuilder();
this.time = time;
}

/**
* Used for logging in when one has a persisted refreshToken.
* Deprecated: specify a Time implementation
*
* @param client OkHttp client
* @param refreshToken Refresh Token Persisted by user
* @throws LoginFailedException When login fails
* @throws RemoteServerException When server fails
*/
@Deprecated
public GoogleCredentialProvider(OkHttpClient client, String refreshToken)
throws LoginFailedException, RemoteServerException {
this(client, refreshToken, new SystemTimeImpl());
}

/**
* Used for logging in when you dont have a persisted refresh token.
*
* @param client OkHttp client
* @param onGoogleLoginOAuthCompleteListener Callback to know verification url and also persist refresh token
* @throws LoginFailedException When login fails
* @param time a Time implementation
* @throws LoginFailedException When login fails
* @throws RemoteServerException When server fails
*/
public GoogleCredentialProvider(OkHttpClient client,
OnGoogleLoginOAuthCompleteListener onGoogleLoginOAuthCompleteListener)
throws LoginFailedException {
OnGoogleLoginOAuthCompleteListener onGoogleLoginOAuthCompleteListener, Time time)
throws LoginFailedException, RemoteServerException {
this.client = client;
if (onGoogleLoginOAuthCompleteListener != null) {
this.onGoogleLoginOAuthCompleteListener = onGoogleLoginOAuthCompleteListener;
Expand All @@ -86,6 +110,23 @@ public GoogleCredentialProvider(OkHttpClient client,
}
login();
authbuilder = AuthInfo.newBuilder();
this.time = time;
}

/**
* Used for logging in when you dont have a persisted refresh token.
* Deprecated: specify a Time implementation
*
* @param client OkHttp client
* @param onGoogleLoginOAuthCompleteListener Callback to know verification url and also persist refresh token
* @throws LoginFailedException When login fails
* @throws RemoteServerException When server fails
*/
@Deprecated
public GoogleCredentialProvider(OkHttpClient client,
OnGoogleLoginOAuthCompleteListener onGoogleLoginOAuthCompleteListener)
throws LoginFailedException, RemoteServerException {
this(client, onGoogleLoginOAuthCompleteListener, new SystemTimeImpl());
}

/**
Expand Down Expand Up @@ -126,7 +167,7 @@ public void refreshToken(String refreshToken) throws LoginFailedException, Remot
throw new LoginFailedException(googleAuthTokenJson.getError());
} else {
Log.d(TAG, "Refreshed Token " + googleAuthTokenJson.getIdToken());
expiresTimestamp = System.currentTimeMillis()
expiresTimestamp = time.currentTimeMillis()
+ (googleAuthTokenJson.getExpiresIn() * 1000 - REFRESH_TOKEN_BUFFER_TIME);
tokenId = googleAuthTokenJson.getIdToken();
}
Expand All @@ -135,7 +176,7 @@ public void refreshToken(String refreshToken) throws LoginFailedException, Remot
/**
* Starts a login flow for google using googles device oauth endpoint.
*/
public void login() throws LoginFailedException {
public void login() throws LoginFailedException, RemoteServerException {

HttpUrl url = HttpUrl.parse(OAUTH_ENDPOINT).newBuilder()
.addQueryParameter("client_id", CLIENT_ID)
Expand All @@ -153,7 +194,7 @@ public void login() throws LoginFailedException {
try {
response = client.newCall(request).execute();
} catch (IOException e) {
throw new LoginFailedException("Network Request failed to fetch tokenId", e);
throw new RemoteServerException("Network Request failed to fetch tokenId", e);
}

Moshi moshi = new Moshi.Builder().build();
Expand All @@ -163,7 +204,7 @@ public void login() throws LoginFailedException {
googleAuth = moshi.adapter(GoogleAuthJson.class).fromJson(response.body().string());
Log.d(TAG, "" + googleAuth.getExpiresIn());
} catch (IOException e) {
throw new LoginFailedException("Failed to unmarshell the Json response to fetch tokenId", e);
throw new RemoteServerException("Failed to unmarshell the Json response to fetch tokenId", e);
}
Log.d(TAG, "Get user to go to:"
+ googleAuth.getVerificationUrl()
Expand All @@ -176,16 +217,16 @@ public void login() throws LoginFailedException {
Thread.sleep(googleAuth.getInterval() * 1000);
}
} catch (InterruptedException e) {
throw new LoginFailedException("Sleeping was interrupted", e);
throw new RemoteServerException("Sleeping was interrupted", e);
} catch (IOException e) {
throw new LoginFailedException(e);
throw new RemoteServerException(e);
} catch (URISyntaxException e) {
throw new LoginFailedException(e);
throw new RemoteServerException(e);
}

Log.d(TAG, "Got token: " + googleAuthTokenJson.getIdToken());
onGoogleLoginOAuthCompleteListener.onTokenIdReceived(googleAuthTokenJson);
expiresTimestamp = System.currentTimeMillis()
expiresTimestamp = time.currentTimeMillis()
+ (googleAuthTokenJson.getExpiresIn() * 1000 - REFRESH_TOKEN_BUFFER_TIME);
tokenId = googleAuthTokenJson.getIdToken();
refreshToken = googleAuthTokenJson.getRefreshToken();
Expand Down Expand Up @@ -246,7 +287,7 @@ public AuthInfo getAuthInfo() throws LoginFailedException, RemoteServerException

@Override
public boolean isTokenIdExpired() {
if (System.currentTimeMillis() > expiresTimestamp) {
if (time.currentTimeMillis() > expiresTimestamp) {
return true;
} else {
return false;
Expand Down
Loading