Skip to content
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
77 changes: 77 additions & 0 deletions core-android/src/main/java/io/ably/pubsub/push/FcmTopic.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package io.ably.pubsub.push;

import io.ably.pubsub.http.HttpRequester;
import io.ably.pubsub.http.PubSubBase;
import io.ably.pubsub.realtime.CompletionListener;
import io.ably.pubsub.types.AblyException;

/**
* A single FCM topic that this device can subscribe to or unsubscribe from.
* Obtained from {@link FcmTopics#get(String)}.
*/
public class FcmTopic {
/**
* The FCM topic name.
*/
public final String name;

private final PubSubBase rest;
private final Push push;

FcmTopic(PubSubBase rest, Push push, String name) {
this.rest = rest;
this.push = push;
this.name = name;
}

/**
* Subscribes this device to the topic. Subscribing when already subscribed succeeds.
* <p>
* If FCM rejects the device's registration token, Ably marks the device registration failed
* and the request fails; the device must then activate again.
*
* @throws AblyException
*/
public void subscribe() throws AblyException {
subscribeImpl().sync();
}

/**
* Asynchronously subscribes this device to the topic. See {@link #subscribe()}.
*
* @param listener A listener to be notified of success or failure.
* <p>
* This listener is invoked on a background thread.
*/
public void subscribeAsync(CompletionListener listener) {
subscribeImpl().async(new CompletionListener.ToCallback<>(listener));
}

/**
* Unsubscribes this device from the topic. Unsubscribing when not subscribed succeeds.
*
* @throws AblyException
*/
public void unsubscribe() throws AblyException {
unsubscribeImpl().sync();
}

/**
* Asynchronously unsubscribes this device from the topic. See {@link #unsubscribe()}.
*
* @param listener A listener to be notified of success or failure.
* <p>
* This listener is invoked on a background thread.
*/
public void unsubscribeAsync(CompletionListener listener) {
unsubscribeImpl().async(new CompletionListener.ToCallback<>(listener));
}

private HttpRequester.Request<Void> subscribeImpl() {
return push.localDeviceRequest((deviceId, headers) -> AdminFcmTopics.subscribeDeviceImpl(rest, headers, name, deviceId));
Comment thread
ttypic marked this conversation as resolved.
Resolved
}

private HttpRequester.Request<Void> unsubscribeImpl() {
return push.localDeviceRequest((deviceId, headers) -> AdminFcmTopics.unsubscribeDeviceImpl(rest, headers, name, deviceId));
}
}
65 changes: 65 additions & 0 deletions core-android/src/main/java/io/ably/pubsub/push/FcmTopics.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package io.ably.pubsub.push;

import io.ably.pubsub.http.HttpRequester;
import io.ably.pubsub.http.PubSubBase;
import io.ably.pubsub.types.AblyException;
import io.ably.pubsub.types.Callback;

/**
* Manages this device's FCM topic subscriptions.
* <p>
* FCM topics let FCM fan a single send out to every device subscribed to the topic. A topic exists
* once its first device subscribes; there is no create or delete call. Topic names must match
* {@code [a-zA-Z0-9-_.~%]{1,900}}. FCM allows at most 2,000 topic subscriptions per device and never
* removes them automatically, so unsubscribe when the device no longer needs a topic.
* <p>
* The device must be activated for push with FCM ({@link Push#activate()} must have completed) before
* using these methods. Requests authenticate as the device, so no push-admin capability is needed.
*/
public class FcmTopics {
private final PubSubBase rest;
private final Push push;

FcmTopics(PubSubBase rest, Push push) {
this.rest = rest;
this.push = push;
}

/**
* Returns an {@link FcmTopic} for subscribing this device to, or unsubscribing it from, the named topic.
* An empty topic name is reported as an {@link AblyException} by the operations on the returned object.
*
* @param topic The FCM topic name.
* @return An {@link FcmTopic} object.
*/
public FcmTopic get(String topic) {
return new FcmTopic(rest, push, topic);
}

/**
* Retrieves the names of the FCM topics this device is subscribed to,
* including any it subscribed to other than through Ably.
*
* @return The topic names.
* @throws AblyException
*/
public String[] list() throws AblyException {
return listImpl().sync();
}

/**
* Asynchronously retrieves the names of the FCM topics this device is subscribed to,
* including any it subscribed to other than through Ably.
*
* @param callback A callback returning the topic names.
* <p>
* This callback is invoked on a background thread.
*/
public void listAsync(Callback<String[]> callback) {
listImpl().async(callback);
}

private HttpRequester.Request<String[]> listImpl() {
return push.localDeviceRequest((deviceId, headers) -> AdminFcmTopics.listImpl(rest, headers, deviceId));
}
}
48 changes: 48 additions & 0 deletions core-android/src/main/java/io/ably/pubsub/push/Push.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import io.ably.pubsub.http.HttpRequester;
import io.ably.pubsub.http.HttpUtils;
import io.ably.pubsub.http.PubSubBase;
import io.ably.pubsub.http.PubSubHttpClient;
Expand All @@ -18,8 +19,14 @@
*/
public class Push extends PushBase {

/**
* An {@link FcmTopics} object, for managing this device's FCM topic subscriptions.
*/
public final FcmTopics fcmTopics;

public Push(PubSubBase rest) {
super(rest);
this.fcmTopics = new FcmTopics(rest, this);
}

/**
Expand Down Expand Up @@ -122,6 +129,47 @@ public LocalDevice getLocalDevice() throws AblyException {
return getActivationContext().getLocalDevice();
}

/**
* Returns the local device, failing if push activation has not completed, since the device has
* no ID or identity token to authenticate push requests with until then.
*/
LocalDevice requireActivatedDevice() throws AblyException {
LocalDevice localDevice = getLocalDevice();
if (localDevice == null || localDevice.deviceIdentityToken == null) {
// Alternatively, we could store a queue of pending subscriptions in the
// device storage. But then, in order to know if this subscription operation
// succeeded, you would have to add a BroadcastReceiver in AndroidManifest.xml.
// Arguably that encourages just ignoring any errors, and forcing you to listen
// to the broadcast after push.activate has finished before subscribing is
// more robust.
throw AblyException.fromThrowable(new Exception("cannot use device before PubSubHttpClient.push.activate has finished"));
}
return localDevice;
}

/**
* Builds a request for the local device, authenticated as it.
*/
interface LocalDeviceRequest<T> {
HttpRequester.Request<T> build(String deviceId, Param[] headers);
}

/**
* Builds a request authenticated as the local device, or a failed request if push activation has
* not completed. The device ID and identity headers come from the same device read, so they
* cannot disagree if the device is reset concurrently.
*/
<T> HttpRequester.Request<T> localDeviceRequest(LocalDeviceRequest<T> request) {
LocalDevice device;
try {
device = requireActivatedDevice();
} catch (AblyException e) {
return rest.http.failedRequest(e);
}
Param[] headers = HttpUtils.mergeHeaders(super.pushRequestHeaders(false), device.deviceIdentityHeaders());
return request.build(device.id, headers);
}

@Override
Param[] pushRequestHeaders(boolean forLocalDevice) {
Param[] headers = super.pushRequestHeaders(forLocalDevice);
Expand Down
12 changes: 1 addition & 11 deletions core-android/src/main/java/io/ably/pubsub/push/PushChannel.java
Original file line number Diff line number Diff line change
Expand Up @@ -249,16 +249,6 @@ protected String getClientId() throws AblyException {
}

protected DeviceDetails getDevice() throws AblyException {
LocalDevice localDevice = rest.push.getActivationContext().getLocalDevice();
if (localDevice == null || localDevice.deviceIdentityToken == null) {
// Alternatively, we could store a queue of pending subscriptions in the
// device storage. But then, in order to know if this subscription operation
// succeeded, you would have to add a BroadcastReceiver in AndroidManifest.xml.
// Arguably that encourages just ignoring any errors, and forcing you to listen
// to the broadcast after push.activate has finished before subscribing is
// more robust.
throw AblyException.fromThrowable(new Exception("cannot use device before PubSubHttpClient.push.activate has finished"));
}
return localDevice;
return rest.push.requireActivatedDevice();
}
}
40 changes: 38 additions & 2 deletions lib/src/main/java/io/ably/pubsub/http/HttpCore.java
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ private <T> T handleResponse(boolean credentialsIncluded, Response response, Res
}

if (response.statusCode >= 200 && response.statusCode < 300) {
return (responseHandler != null) ? responseHandler.handleResponse(response, null) : null;
return callResponseHandler(responseHandler, response, null);
}

/* get any in-body error details */
Expand Down Expand Up @@ -449,11 +449,35 @@ private <T> T handleResponse(boolean credentialsIncluded, Response response, Res
}
Log.e(TAG, "Error response from server: err = " + error);
if (responseHandler != null) {
return responseHandler.handleResponse(response, error);
return callResponseHandler(responseHandler, response, error);
}
throw AblyException.fromErrorInfo(error);
}

/**
* Runs a response handler, so that however it fails, the request fails with an AblyException.
* <p>
* An unchecked exception, such as a parse error, is wrapped: left alone it would skip the
* caller's error handling, and an async request's callback would never be called. And because
* the host has answered, a failure handling a successful response is never one that a fallback
* host can fix, so a server error the handler raises for it is not retried on another host.
*/
private static <T> T callResponseHandler(ResponseHandler<T> responseHandler, Response response, ErrorInfo error) throws AblyException {
if (responseHandler == null) {
return null;
}
try {
return responseHandler.handleResponse(response, error);
} catch (AblyException.HostFailedException e) {
if (error == null) {
throw new ResponseHandlingException(e, e.errorInfo);
}
throw e;
} catch (RuntimeException e) {
throw new ResponseHandlingException(e, ErrorInfo.fromThrowable(e));
}
}

/**
* Read the response for an HTTP request
*/
Expand Down Expand Up @@ -572,6 +596,18 @@ public String getHeaderField(String name) {
}
}

/**
* Exception signifying that a response could not be handled. The host answered, so unlike
* {@link AblyException.HostFailedException} it does not cause a retry on a fallback host.
*/
private static class ResponseHandlingException extends AblyException {
private static final long serialVersionUID = 1L;

ResponseHandlingException(Throwable throwable, ErrorInfo reason) {
super(throwable, reason);
}
}

/**
* Exception signifying that an httpCore request failed with a WWW-Authenticate response
*/
Expand Down
Loading
Loading