summaryrefslogtreecommitdiffstats
path: root/mobile/android/services/src/main/java/org/mozilla/gecko/push/autopush/AutopushClient.java
blob: 8edd92f9eb52578b64f191e3ce03ac05f7cd76b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko.push.autopush;

import android.text.TextUtils;

import org.mozilla.gecko.Locales;
import org.mozilla.gecko.fxa.FxAccountConstants;
import org.mozilla.gecko.push.RegisterUserAgentResponse;
import org.mozilla.gecko.push.SubscribeChannelResponse;
import org.mozilla.gecko.sync.ExtendedJSONObject;
import org.mozilla.gecko.sync.net.AuthHeaderProvider;
import org.mozilla.gecko.sync.net.BaseResource;
import org.mozilla.gecko.sync.net.BaseResourceDelegate;
import org.mozilla.gecko.sync.net.BearerAuthHeaderProvider;
import org.mozilla.gecko.sync.net.Resource;
import org.mozilla.gecko.sync.net.SyncResponse;
import org.mozilla.gecko.sync.net.SyncStorageResponse;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.util.Locale;
import java.util.concurrent.Executor;

import ch.boye.httpclientandroidlib.HttpEntity;
import ch.boye.httpclientandroidlib.HttpHeaders;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.client.ClientProtocolException;
import ch.boye.httpclientandroidlib.client.methods.HttpRequestBase;
import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient;


/**
 * Interact with the autopush endpoint HTTP API.
 * <p/>
 * The API is a Mozilla-proprietary interface, and not even specified to Mozilla's usual ad-hoc standards.
 * This client is written against a work-in-progress, un-deployed upstream commit.
 */
public class AutopushClient {
    protected static final String LOG_TAG = AutopushClient.class.getSimpleName();

    protected static final String ACCEPT_HEADER = "application/json;charset=utf-8";
    protected static final String TYPE = "gcm";

    protected static final String JSON_KEY_UAID = "uaid";
    protected static final String JSON_KEY_SECRET = "secret";
    protected static final String JSON_KEY_CHANNEL_ID = "channelID";
    protected static final String JSON_KEY_ENDPOINT = "endpoint";

    protected static final String[] REGISTER_USER_AGENT_RESPONSE_REQUIRED_STRING_FIELDS = new String[] { JSON_KEY_UAID, JSON_KEY_SECRET, JSON_KEY_CHANNEL_ID, JSON_KEY_ENDPOINT };
    protected static final String[] REGISTER_CHANNEL_RESPONSE_REQUIRED_STRING_FIELDS = new String[] { JSON_KEY_CHANNEL_ID, JSON_KEY_ENDPOINT };

    public static final String JSON_KEY_CODE = "code";
    public static final String JSON_KEY_ERRNO = "errno";
    public static final String JSON_KEY_ERROR = "error";
    public static final String JSON_KEY_MESSAGE = "message";

    protected static final String[] requiredErrorStringFields = { JSON_KEY_ERROR, JSON_KEY_MESSAGE };
    protected static final String[] requiredErrorLongFields = { JSON_KEY_CODE, JSON_KEY_ERRNO };

    /**
     * The server's URI.
     * <p>
     * We assume throughout that this ends with a trailing slash (and guarantee as
     * much in the constructor).
     */
    public final String serverURI;

    protected final Executor executor;

    public AutopushClient(String serverURI, Executor executor) {
        if (serverURI == null) {
            throw new IllegalArgumentException("Must provide a server URI.");
        }
        if (executor == null) {
            throw new IllegalArgumentException("Must provide a non-null executor.");
        }
        this.serverURI = serverURI.endsWith("/") ? serverURI : serverURI + "/";
        if (!this.serverURI.endsWith("/")) {
            throw new IllegalArgumentException("Constructed serverURI must end with a trailing slash: " + this.serverURI);
        }
        this.executor = executor;
    }

    /**
     * A legal autopush server URL includes a sender ID embedded into it.  Extract it.
     *
     * @return a non-null non-empty sender ID.
     * @throws AutopushClientException on failure.
     */
    public String getSenderIDFromServerURI() throws AutopushClientException {
        // Turn "https://updates-autopush-dev.stage.mozaws.net/v1/gcm/829133274407/" into "829133274407".
        final String[] parts = serverURI.split("/", -1); // The -1 keeps the trailing empty part.
        if (parts.length < 3) {
            throw new AutopushClientException("Could not get sender ID from autopush server URI: " + serverURI);
        }
        if (!TextUtils.isEmpty(parts[parts.length - 1])) {
            // We guarantee a trailing slash, so we should always have an empty part at the tail.
            throw new AutopushClientException("Could not get sender ID from autopush server URI: " + serverURI);
        }
        if (!TextUtils.equals("gcm", parts[parts.length - 3])) {
            // We should always have /gcm/senderID/.
            throw new AutopushClientException("Could not get sender ID from autopush server URI: " + serverURI);
        }
        final String senderID = parts[parts.length - 2];
        if (TextUtils.isEmpty(senderID)) {
            // Something is horribly wrong -- we have /gcm//.  Abort.
            throw new AutopushClientException("Could not get sender ID from autopush server URI: " + serverURI);
        }
        return senderID;
    }

    /**
     * Process a typed value extracted from a successful response (in an
     * endpoint-dependent way).
     */
    public interface RequestDelegate<T> {
        void handleError(Exception e);
        void handleFailure(AutopushClientException e);
        void handleSuccess(T result);
    }

    /**
     * Intepret a response from the autopush server.
     * <p>
     * Throw an appropriate exception on errors; otherwise, return the response's
     * status code.
     *
     * @return response's HTTP status code.
     * @throws AutopushClientException
     */
    public static int validateResponse(HttpResponse response) throws AutopushClientException {
        final int status = response.getStatusLine().getStatusCode();
        if (200 <= status && status <= 299) {
            return status;
        }
        long code;
        long errno;
        String error;
        String message;
        String info;
        ExtendedJSONObject body;
        try {
            body = new SyncStorageResponse(response).jsonObjectBody();
            // TODO: The service doesn't do the right thing yet :(
            // body.throwIfFieldsMissingOrMisTyped(requiredErrorStringFields, String.class);
            body.throwIfFieldsMissingOrMisTyped(requiredErrorLongFields, Long.class);
            // Would throw above if missing; the -1 defaults quiet NPE warnings.
            code = body.getLong(JSON_KEY_CODE, -1);
            errno = body.getLong(JSON_KEY_ERRNO, -1);
            error = body.getString(JSON_KEY_ERROR);
            message = body.getString(JSON_KEY_MESSAGE);
        } catch (Exception e) {
            throw new AutopushClientException.AutopushClientMalformedResponseException(response);
        }
        throw new AutopushClientException.AutopushClientRemoteException(response, code, errno, error, message, body);
    }

    protected <T> void invokeHandleError(final RequestDelegate<T> delegate, final Exception e) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                delegate.handleError(e);
            }
        });
    }

    protected <T> void post(BaseResource resource, final ExtendedJSONObject requestBody, final RequestDelegate<T> delegate) {
        try {
            if (requestBody == null) {
                resource.post((HttpEntity) null);
            } else {
                resource.post(requestBody);
            }
        } catch (Exception e) {
            invokeHandleError(delegate, e);
            return;
        }
    }

    /**
     * Translate resource callbacks into request callbacks invoked on the provided
     * executor.
     * <p>
     * Override <code>handleSuccess</code> to parse the body of the resource
     * request and call the request callback. <code>handleSuccess</code> is
     * invoked via the executor, so you don't need to delegate further.
     */
    protected abstract class ResourceDelegate<T> extends BaseResourceDelegate {
        protected abstract void handleSuccess(final int status, HttpResponse response, final ExtendedJSONObject body);

        protected final String secret;
        protected final RequestDelegate<T> delegate;

        /**
         * Create a delegate for an un-authenticated resource.
         */
        public ResourceDelegate(final Resource resource, final String secret, final RequestDelegate<T> delegate) {
            super(resource);
            this.delegate = delegate;
            this.secret = secret;
        }

        @Override
        public AuthHeaderProvider getAuthHeaderProvider() {
            if (secret != null) {
                return new BearerAuthHeaderProvider(secret);
            }
            return null;
        }

        @Override
        public String getUserAgent() {
            return FxAccountConstants.USER_AGENT;
        }

        @Override
        public void handleHttpResponse(HttpResponse response) {
            try {
                final int status = validateResponse(response);
                invokeHandleSuccess(status, response);
            } catch (AutopushClientException e) {
                invokeHandleFailure(e);
            }
        }

        protected void invokeHandleFailure(final AutopushClientException e) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    delegate.handleFailure(e);
                }
            });
        }

        protected void invokeHandleSuccess(final int status, final HttpResponse response) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        ExtendedJSONObject body = new SyncResponse(response).jsonObjectBody();
                        ResourceDelegate.this.handleSuccess(status, response, body);
                    } catch (Exception e) {
                        delegate.handleError(e);
                    }
                }
            });
        }

        @Override
        public void handleHttpProtocolException(final ClientProtocolException e) {
            invokeHandleError(delegate, e);
        }

        @Override
        public void handleHttpIOException(IOException e) {
            invokeHandleError(delegate, e);
        }

        @Override
        public void handleTransportException(GeneralSecurityException e) {
            invokeHandleError(delegate, e);
        }

        @Override
        public void addHeaders(HttpRequestBase request, DefaultHttpClient client) {
            super.addHeaders(request, client);

            // The basics.
            final Locale locale = Locale.getDefault();
            request.addHeader(HttpHeaders.ACCEPT_LANGUAGE, Locales.getLanguageTag(locale));
            request.addHeader(HttpHeaders.ACCEPT, ACCEPT_HEADER);
        }
    }

    public void registerUserAgent(final String token, RequestDelegate<RegisterUserAgentResponse> delegate) {
        BaseResource resource;
        try {
            resource = new BaseResource(new URI(serverURI + "registration"));
        } catch (URISyntaxException e) {
            invokeHandleError(delegate, e);
            return;
        }

        resource.delegate = new ResourceDelegate<RegisterUserAgentResponse>(resource, null, delegate) {
            @Override
            public void handleSuccess(int status, HttpResponse response, ExtendedJSONObject body) {
                try {
                    body.throwIfFieldsMissingOrMisTyped(REGISTER_USER_AGENT_RESPONSE_REQUIRED_STRING_FIELDS, String.class);
                    final String uaid = body.getString(JSON_KEY_UAID);
                    final String secret = body.getString(JSON_KEY_SECRET);
                    delegate.handleSuccess(new RegisterUserAgentResponse(uaid, secret));
                    return;
                } catch (Exception e) {
                    delegate.handleError(e);
                    return;
                }
            }
        };

        final ExtendedJSONObject body = new ExtendedJSONObject();
        body.put("type", TYPE);
        body.put("token", token);

        resource.post(body);
    }

    public void reregisterUserAgent(final String uaid, final String secret, final String token, RequestDelegate<Void> delegate) {
        final BaseResource resource;
        try {
            resource = new BaseResource(new URI(serverURI + "registration/" + uaid));
        } catch (Exception e) {
            invokeHandleError(delegate, e);
            return;
        }

        resource.delegate = new ResourceDelegate<Void>(resource, secret, delegate) {
            @Override
            public void handleSuccess(int status, HttpResponse response, ExtendedJSONObject body) {
                try {
                    delegate.handleSuccess(null);
                    return;
                } catch (Exception e) {
                    delegate.handleError(e);
                    return;
                }
            }
        };

        final ExtendedJSONObject body = new ExtendedJSONObject();
        body.put("type", TYPE);
        body.put("token", token);

        resource.put(body);
    }


    public void subscribeChannel(final String uaid, final String secret, final String appServerKey, RequestDelegate<SubscribeChannelResponse> delegate) {
        final BaseResource resource;
        try {
            resource = new BaseResource(new URI(serverURI + "registration/" + uaid + "/subscription"));
        } catch (Exception e) {
            invokeHandleError(delegate, e);
            return;
        }

        resource.delegate = new ResourceDelegate<SubscribeChannelResponse>(resource, secret, delegate) {
            @Override
            public void handleSuccess(int status, HttpResponse response, ExtendedJSONObject body) {
                try {
                    body.throwIfFieldsMissingOrMisTyped(REGISTER_CHANNEL_RESPONSE_REQUIRED_STRING_FIELDS, String.class);
                    final String channelID = body.getString(JSON_KEY_CHANNEL_ID);
                    final String endpoint = body.getString(JSON_KEY_ENDPOINT);
                    delegate.handleSuccess(new SubscribeChannelResponse(channelID, endpoint));
                    return;
                } catch (Exception e) {
                    delegate.handleError(e);
                    return;
                }
            }
        };

        final ExtendedJSONObject body = new ExtendedJSONObject();
        body.put("key", appServerKey);
        resource.post(body);
    }

    public void unsubscribeChannel(final String uaid, final String secret, final String channelID, RequestDelegate<Void> delegate) {
        final BaseResource resource;
        try {
            resource = new BaseResource(new URI(serverURI + "registration/" + uaid + "/subscription/" + channelID));
        } catch (Exception e) {
            invokeHandleError(delegate, e);
            return;
        }

        resource.delegate = new ResourceDelegate<Void>(resource, secret, delegate) {
            @Override
            public void handleSuccess(int status, HttpResponse response, ExtendedJSONObject body) {
                delegate.handleSuccess(null);
            }
        };

        resource.delete();
    }

    public void unregisterUserAgent(final String uaid, final String secret, RequestDelegate<Void> delegate) {
        final BaseResource resource;
        try {
            resource = new BaseResource(new URI(serverURI + "registration/" + uaid));
        } catch (Exception e) {
            invokeHandleError(delegate, e);
            return;
        }

        resource.delegate = new ResourceDelegate<Void>(resource, secret, delegate) {
            @Override
            public void handleSuccess(int status, HttpResponse response, ExtendedJSONObject body) {
                delegate.handleSuccess(null);
            }
        };

        resource.delete();
    }
}