/** * Deletes the current registration token. * * @param instanceId The instance ID which generated the registration token. * @param senderId The sender ID to revoke the registration token from. * @return A task that can be resolved upon deletion of the token. */ private Task<Void> deleteRegistrationToken(final InstanceID instanceId, final String senderId) { final TaskCompletionSource<Void> future = new TaskCompletionSource<>(); new AsyncTask<Object, Integer, String>() { @Override protected String doInBackground(final Object[] ignored) { try { instanceId.deleteToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE); } catch (final IOException e) { Log.e(TAG, "Error deleting GCM registration token", e); future.setException(e); return null; } future.setResult(null); return null; } }.execute(); return future.getTask(); }
/** * Gets or creates a registration token. * * @param instanceId The instance ID which should generate the registration token. * @param senderId The sender ID to generate the registration token for. * @return A task that can be resolved upon creating/retrieval of the token. */ private Task<String> getRegistrationToken(final InstanceID instanceId, final String senderId) { final TaskCompletionSource<String> future = new TaskCompletionSource<>(); new AsyncTask<Object, Integer, String>() { @Override protected String doInBackground(final Object[] ignored) { final String registrationToken; try { registrationToken = instanceId.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE); } catch (final IOException e) { Log.e(TAG, "Error getting GCM registration token", e); future.setException(e); return null; } future.setResult(registrationToken); return null; } }.execute(); return future.getTask(); }
public Task<Map<DatabaseReference, DataSnapshot>> start() { // Create a Task<DataSnapshot> to trigger in response to each database listener. // final ArrayList<Task<DataSnapshot>> tasks = new ArrayList<>(refs.size()); for (final DatabaseReference ref : refs) { final TaskCompletionSource<DataSnapshot> source = new TaskCompletionSource<>(); final ValueEventListener listener = new MyValueEventListener(ref, source); ref.addListenerForSingleValueEvent(listener); listeners.put(ref, listener); tasks.add(source.getTask()); } // Return a single Task that triggers when all queries are complete. It contains // a map of all original DatabaseReferences originally given here to their resulting // DataSnapshot. // return Tasks.whenAll(tasks).continueWith(new Continuation<Void, Map<DatabaseReference, DataSnapshot>>() { @Override public Map<DatabaseReference, DataSnapshot> then(@NonNull Task<Void> task) throws Exception { task.getResult(); return new HashMap<>(snaps); } }); }
/** * Subscribes the client to a specific topic. * /topics/ prefix is not necessary. * * @param topic The topic to subscribe to * * @return A task that can resolved upon subscribing. */ public Task<Void> subscribeToTopic(final String topic) { final GcmPubSub pubSub = GcmPubSub.getInstance(getContext()); final String topicKey = String.format("/topics/%s", topic); final InstanceID instanceId = InstanceID.getInstance(getContext()); final TaskCompletionSource<Void> future = new TaskCompletionSource<>(); getRegistrationToken(instanceId, _info.getSenderId()).addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull final Task<String> task) { if (!task.isSuccessful()) { future.setException(task.getException()); } new AsyncTask<Object, Integer, String>() { @Override protected String doInBackground(final Object[] ignored) { try { pubSub.subscribe(task.getResult(), topicKey, null); } catch (final IOException e) { Log.e(TAG, "Error subscribing to " + topicKey, e); future.setException(e); return null; } future.setResult(null); return null; } }.execute(); } }); return future.getTask(); }
/** * Subscribes the client to a specific topic. * /topics/ prefix is not necessary. * * @param topic The topic to unsubscribe from * * @return A task that can resolved upon subscribing. */ public Task<Void> unsubscribeFromTopic(final String topic) { final GcmPubSub pubSub = GcmPubSub.getInstance(getContext()); final String topicKey = String.format("/topics/%s", topic); final InstanceID instanceId = InstanceID.getInstance(getContext()); final TaskCompletionSource<Void> future = new TaskCompletionSource<>(); getRegistrationToken(instanceId, _info.getSenderId()).addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull final Task<String> task) { if (!task.isSuccessful()) { future.setException(task.getException()); } new AsyncTask<Object, Integer, String>() { @Override protected String doInBackground(final Object[] ignored) { try { pubSub.unsubscribe(task.getResult(), topicKey); } catch (final IOException e) { Log.e(TAG, "Error unsubscribing from " + topicKey, e); future.setException(e); return null; } future.setResult(null); return null; } }.execute(); } }); return future.getTask(); }
/** * Registers the current user using email and password. * * @param email email for the given user * @param password password for the given user * @return A task containing whether or not registration was successful. */ public Task<Boolean> register(@NonNull String email, @NonNull String password) { final EmailPasswordAuthProvider provider = new EmailPasswordAuthProvider(email, password); final TaskCompletionSource<Boolean> future = new TaskCompletionSource<>(); final String url = String.format( "%s/%s", getResourcePath(routes.AUTH), routes.USERPASS_REGISTER ); final JsonStringRequest request = new JsonStringRequest( Request.Method.POST, url, getAuthRequest(provider.getRegistrationPayload()).toJson(), new Response.Listener<String>() { @Override public void onResponse(final String response) { future.setResult(response != null); } }, new Response.ErrorListener() { @Override public void onErrorResponse(final VolleyError error) { Log.e(TAG, "Error while logging in with auth provider", error); future.setException(parseRequestError(error)); } } ); request.setTag(this); _queue.add(request); return future.getTask(); }
/** * Confirm a newly registered email in this context * * @param token confirmation token emailed to new user * @param tokenId confirmation tokenId emailed to new user * @return A task containing whether or not the email was confirmed successfully */ public Task<Boolean> emailConfirm(@NonNull final String token, @NonNull final String tokenId) { final TaskCompletionSource<Boolean> future = new TaskCompletionSource<>(); final String url = String.format( "%s/%s", getResourcePath(routes.AUTH), routes.USERPASS_CONFIRM ); final Document params = new Document(); params.put("token", token); params.put("tokenId", tokenId); final JsonStringRequest request = new JsonStringRequest( Request.Method.POST, url, params.toJson(), new Response.Listener<String>() { @Override public void onResponse(final String response) { future.setResult(response != null); } }, new Response.ErrorListener() { @Override public void onErrorResponse(final VolleyError error) { Log.e(TAG, "Error while confirming email", error); future.setException(parseRequestError(error)); } } ); request.setTag(this); _queue.add(request); return future.getTask(); }
/** * Send a confirmation email for a newly registered user * * @param email email address of user * @return A task containing whether or not the email was sent successfully. */ public Task<Boolean> sendEmailConfirm(@NonNull final String email) { final TaskCompletionSource<Boolean> future = new TaskCompletionSource<>(); final String url = String.format( "%s/%s", getResourcePath(routes.AUTH), routes.USERPASS_CONFIRM_SEND ); final JsonStringRequest request = new JsonStringRequest( Request.Method.POST, url, new Document("email", email).toJson(), new Response.Listener<String>() { @Override public void onResponse(final String response) { future.setResult(response != null); } }, new Response.ErrorListener() { @Override public void onErrorResponse(final VolleyError error) { Log.e(TAG, "Error while sending confirmation email", error); future.setException(parseRequestError(error)); } } ); request.setTag(this); _queue.add(request); return future.getTask(); }
/** * Send a reset password email to a given email address * * @param email email address to reset password for * @return A task containing whether or not the reset email was sent successfully */ public Task<Boolean> sendResetPassword(@NonNull final String email) { final TaskCompletionSource<Boolean> future = new TaskCompletionSource<>(); final String url = String.format( "%s/%s", getResourcePath(routes.AUTH), routes.USERPASS_RESET_SEND ); final JsonStringRequest request = new JsonStringRequest( Request.Method.POST, url, new Document("email", email).toJson(), new Response.Listener<String>() { @Override public void onResponse(final String response) { future.setResult(response != null); } }, new Response.ErrorListener() { @Override public void onErrorResponse(final VolleyError error) { Log.e(TAG, "Error while sending reset password email", error); future.setException(parseRequestError(error)); } } ); request.setTag(this); _queue.add(request); return future.getTask(); }
private Task<String> getLineAccessCode(final Activity activity) { final TaskCompletionSource<String> source = new TaskCompletionSource<>(); // STEP 1: User logins with LINE and get their LINE access token LineSdkContext sdkContext = LineSdkContextManager.getSdkContext(); LineAuthManager authManager = sdkContext.getAuthManager(); LineLoginFuture loginFuture = authManager.login(activity); loginFuture.addFutureListener(new LineLoginFutureListener() { @Override public void loginComplete(LineLoginFuture future) { switch(future.getProgress()) { case SUCCESS: //Login successfully String lineAccessToken = future.getAccessToken().accessToken; Log.d(TAG, "LINE Access token = " + lineAccessToken); source.setResult(lineAccessToken); break; case CANCELED: // Login canceled by user Exception e = new Exception("User cancelled LINE Login."); source.setException(e); break; default: // Error Throwable cause = future.getCause(); if (cause instanceof LineSdkLoginException) { LineSdkLoginException loginException = (LineSdkLoginException) cause; Log.e(TAG, loginException.getMessage()); source.setException(loginException); } else { source.setException(new Exception("Unknown error occurred in LINE SDK.")); } break; } } }); return source.getTask(); }
private Task<String> getFirebaseAuthToken(Context context, final String lineAccessToken) { final TaskCompletionSource<String> source = new TaskCompletionSource<>(); // STEP 2: Exchange LINE access token for Firebase Custom Auth token HashMap<String, String> validationObject = new HashMap<>(); validationObject.put("token", lineAccessToken); // Exchange LINE Access Token for Firebase Auth Token Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { String firebaseToken = response.getString("firebase_token"); Log.d(TAG, "Firebase Token = " + firebaseToken); source.setResult(firebaseToken); } catch (Exception e) { source.setException(e); } } }; Response.ErrorListener errorListener = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, error.toString()); source.setException(error); } }; JsonObjectRequest fbTokenRequest = new JsonObjectRequest( Request.Method.POST, mLineAcessscodeVerificationEndpoint, new JSONObject(validationObject), responseListener, errorListener); NetworkSingleton.getInstance(context).addToRequestQueue(fbTokenRequest); return source.getTask(); }
/** * * @param kakaoAccessToken Access token retrieved after successful Kakao Login * @return Task object that will call validation server and retrieve firebase token */ private Task<String> getFirebaseJwt(final String kakaoAccessToken) { final TaskCompletionSource<String> source = new TaskCompletionSource<>(); RequestQueue queue = Volley.newRequestQueue(this); String url = getResources().getString(R.string.validation_server_domain) + "/verifyToken"; HashMap<String, String> validationObject = new HashMap<>(); validationObject.put("token", kakaoAccessToken); JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(validationObject), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { String firebaseToken = response.getString("firebase_token"); source.setResult(firebaseToken); } catch (Exception e) { source.setException(e); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, error.toString()); source.setException(error); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("token", kakaoAccessToken); return params; } }; queue.add(request); return source.getTask(); }
public Task<Status> signOut() { final TaskCompletionSource<Status> statusTask = new TaskCompletionSource<>(); getConnectedApiTask().addOnCompleteListener(new ExceptionForwarder<>( statusTask, new OnSuccessListener<Bundle>() { @Override public void onSuccess(Bundle status) { Auth.GoogleSignInApi.signOut(mClient) .setResultCallback(new TaskResultCaptor<>(statusTask)); } })); return statusTask.getTask(); }
public Task<Status> disableAutoSignIn() { final TaskCompletionSource<Status> statusTask = new TaskCompletionSource<>(); getConnectedApiTask().addOnCompleteListener(new ExceptionForwarder<>( statusTask, new OnSuccessListener<Bundle>() { @Override public void onSuccess(Bundle status) { Auth.CredentialsApi.disableAutoSignIn(mClient) .setResultCallback(new TaskResultCaptor<>(statusTask)); } })); return statusTask.getTask(); }
public Task<Status> delete(final Credential credential) { final TaskCompletionSource<Status> statusTask = new TaskCompletionSource<>(); getConnectedApiTask().addOnCompleteListener(new ExceptionForwarder<>( statusTask, new OnSuccessListener<Bundle>() { @Override public void onSuccess(Bundle status) { Auth.CredentialsApi.delete(mClient, credential) .setResultCallback(new TaskResultCaptor<>(statusTask)); } })); return statusTask.getTask(); }
/** * Returns a task that will complete when given file is closed. Returns immediately if the * file is not open. * * @param filename - the file name in question. */ public Task<Result> waitForClosed(String filename) { final TaskCompletionSource<Result> taskCompletionSource = new TaskCompletionSource<>(); final CountDownLatch latch; synchronized (this) { latch = opened.get(filename); } if (latch == null) { taskCompletionSource.setResult(null); return taskCompletionSource.getTask(); } new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { Result result = new CountDownTask(latch).await(); taskCompletionSource.setResult(result); return null; } }.execute(); return taskCompletionSource.getTask(); }
@NonNull private Task<Void> setIsOpeningTask(String filename) { TaskCompletionSource<Void> source = new TaskCompletionSource<>(); if (isAlreadyOpen(filename)) { source.setException(new IllegalStateException(filename + " is already open!")); } else if (isAlreadyClosing(filename)) { source.setException(new IllegalStateException(filename + " is current closing!")); } else { setIsOpening(filename); source.setResult(null); } return source.getTask(); }
@NonNull private Task<Void> setIsClosingTask(String filename) { TaskCompletionSource<Void> source = new TaskCompletionSource<>(); if (!isAlreadyOpen(filename)) { source.setException(new IllegalStateException(filename + " is already closed!")); } else if (isAlreadyClosing(filename)) { source.setException(new IllegalStateException(filename + " is current closing!")); } else { setIsClosing(filename); source.setResult(null); } return source.getTask(); }
/** * Logs the current user in using a specific auth provider. * * @param authProvider The provider that will handle the login. * @return A task containing an {@link AuthInfo} session that can be resolved on completion of log in. */ public Task<String> logInWithProvider(AuthProvider authProvider) { if (isAuthenticated()) { Log.d(TAG, "Already logged in. Returning cached token"); return Tasks.forResult(_auth.getAuthInfo().getUserId()); } final TaskCompletionSource<String> future = new TaskCompletionSource<>(); final JsonStringRequest request = new JsonStringRequest( Request.Method.POST, getResourcePath(routes.getAuthProvidersLoginRoute(authProvider.getType())), getAuthRequest(authProvider).toJson(), new Response.Listener<String>() { @Override public void onResponse(final String response) { try { _auth = new Auth( StitchClient.this, _objMapper.readValue(response, AuthInfo.class)); final RefreshTokenHolder refreshToken = _objMapper.readValue(response, RefreshTokenHolder.class); _preferences.edit().putString(PREF_AUTH_JWT_NAME, response).apply(); _preferences.edit().putString(PREF_AUTH_REFRESH_TOKEN_NAME, refreshToken.getToken()).apply(); _preferences.edit().putString(PREF_DEVICE_ID_NAME, _auth.getAuthInfo().getDeviceId()).apply(); future.setResult(_auth.getAuthInfo().getUserId()); onLogin(); } catch (final IOException e) { Log.e(TAG, "Error parsing auth response", e); future.setException(new StitchException(e)); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(final VolleyError error) { Log.e(TAG, "Error while logging in with auth provider", error); future.setException(parseRequestError(error)); } }); request.setTag(this); _queue.add(request); return future.getTask(); }
/** * Reset a given user's password * * @param token token associated with this user * @param tokenId id of the token associated with this user * @return A task containing whether or not the reset was successful */ public Task<Boolean> resetPassword(@NonNull final String token, @NonNull final String tokenId, @NonNull final String password) { final TaskCompletionSource<Boolean> future = new TaskCompletionSource<>(); final String url = String.format( "%s/%s", getResourcePath(routes.AUTH), routes.USERPASS_RESET ); final Document params = new Document(); params.put(RegistrationFields.TOKEN, token); params.put(RegistrationFields.TOKEN_ID, tokenId); params.put(RegistrationFields.PASSWORD, password); final JsonStringRequest request = new JsonStringRequest( Request.Method.POST, url, params.toJson(), new Response.Listener<String>() { @Override public void onResponse(final String response) { future.setResult(response != null); } }, new Response.ErrorListener() { @Override public void onErrorResponse(final VolleyError error) { Log.e(TAG, "Error while reseting password", error); future.setException(parseRequestError(error)); } } ); request.setTag(this); _queue.add(request); return future.getTask(); }
/** * Gets all available auth providers for the current app. * * @return A task containing {@link AvailableAuthProviders} that can be resolved on completion * of the request. */ public Task<AvailableAuthProviders> getAuthProviders() { final TaskCompletionSource<AvailableAuthProviders> future = new TaskCompletionSource<>(); final String url = getResourcePath(routes.AUTH_PROVIDERS); final JsonArrayRequest request = new JsonArrayRequest( Request.Method.GET, url, new Response.Listener<JSONArray>() { @Override public void onResponse(final JSONArray response) { final AvailableAuthProviders.Builder builder = new AvailableAuthProviders.Builder(); for (int i = 0; i < response.length(); i++) { try { JSONObject info = response.getJSONObject(i); switch (info.getString("type")) { case FacebookAuthProviderInfo.FQ_NAME: final FacebookAuthProviderInfo fbInfo = _objMapper.readValue(info.toString(), FacebookAuthProviderInfo.class); builder.withFacebook(fbInfo); break; case GoogleAuthProviderInfo.FQ_NAME: final GoogleAuthProviderInfo googleInfo = _objMapper.readValue(info.toString(), GoogleAuthProviderInfo.class); builder.withGoogle(googleInfo); break; case AnonymousAuthProviderInfo.FQ_NAME: final AnonymousAuthProviderInfo anonInfo = _objMapper.readValue(info.toString(), AnonymousAuthProviderInfo.class); builder.withAnonymous(anonInfo); break; case EmailPasswordAuthProviderInfo.FQ_NAME: final EmailPasswordAuthProviderInfo emailPassInfo = _objMapper.readValue(info.toString(), EmailPasswordAuthProviderInfo.class); builder.withEmailPass(emailPassInfo); break; case CustomAuthProviderInfo.FQ_NAME: final CustomAuthProviderInfo customAuthProviderInfo = _objMapper.readValue(info.toString(), CustomAuthProviderInfo.class); builder.withCustomAuth(customAuthProviderInfo); } } catch (JSONException | IOException e) { Log.e( TAG, "Error while getting auth provider info", e); future.setException(e); return; } } future.setResult(builder.build()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(final VolleyError error) { Log.e(TAG, "Error while getting auth provider info", error); future.setException(parseRequestError(error)); } }); request.setTag(this); _queue.add(request); return future.getTask(); }
/** * Executes a network request against the app. * * @param method The HTTP method to use. * @param resource The resource to target. * @param body The JSON body to include in the request. * @param refreshOnFailure Whether or not to refresh the access token if it expires. * @param useRefreshToken Whether or not to use the refresh token over the access token. * @return A task containing the body of the network response that can be resolved on completion * of the network request. */ Task<String> executeRequest( final int method, final String resource, final String body, final boolean refreshOnFailure, final boolean useRefreshToken ) { ensureAuthenticated(); final String url = getResourcePath(resource); final String rawToken = useRefreshToken ? getRefreshToken() : _auth.getAuthInfo().getAccessToken(); final TaskCompletionSource<String> future = new TaskCompletionSource<>(); if (!useRefreshToken) { final DecodedJWT token = new DecodedJWT(rawToken); if (token.isExpired()) { handleInvalidSession(method, resource, body, future); return future.getTask(); } } final AuthenticatedJsonStringRequest request = new AuthenticatedJsonStringRequest( method, url, body, Collections.singletonMap( Headers.AUTHORIZATION, GetAuthorizationBearer(rawToken)), new Response.Listener<String>() { @Override public void onResponse(final String response) { future.setResult(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(final VolleyError error) { final StitchException.StitchRequestException e = parseRequestError(error); if (e instanceof StitchException.StitchServiceException) { if (((StitchException.StitchServiceException) e).getErrorCode() == ErrorCode.INVALID_SESSION) { if (!refreshOnFailure) { clearAuth(); future.setException(e); return; } handleInvalidSession(method, resource, body, future); return; } } future.setException(e); } }); request.setTag(this); _queue.add(request); return future.getTask(); }
public TriggerTaskValueEventListener(@NonNull final TaskCompletionSource<DataSnapshot> source) { this.source = source; }
public MyValueEventListener(DatabaseReference ref, TaskCompletionSource<DataSnapshot> taskSource) { this.ref = ref; this.taskSource = taskSource; }
public TaskResultCaptor(TaskCompletionSource<R> source) { mSource = source; }
public ExceptionForwarder(TaskCompletionSource source, OnSuccessListener<TResult> listener) { mSource = source; mListener = listener; }