-
Notifications
You must be signed in to change notification settings - Fork 114
/
SalesforceDroidGapActivity.java
583 lines (508 loc) · 21.2 KB
/
SalesforceDroidGapActivity.java
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
/*
* Copyright (c) 2011-present, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software in source and binary forms, with or
* without modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.androidsdk.phonegap.ui;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.URLUtil;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.auth.HttpAccess.NoNetworkException;
import com.salesforce.androidsdk.config.BootConfig;
import com.salesforce.androidsdk.config.LoginServerManager;
import com.salesforce.androidsdk.phonegap.app.SalesforceHybridSDKManager;
import com.salesforce.androidsdk.phonegap.util.SalesforceHybridLogger;
import com.salesforce.androidsdk.rest.ClientManager;
import com.salesforce.androidsdk.rest.ClientManager.AccountInfoNotFoundException;
import com.salesforce.androidsdk.rest.ClientManager.RestClientCallback;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.ui.SalesforceActivityDelegate;
import com.salesforce.androidsdk.ui.SalesforceActivityInterface;
import com.salesforce.androidsdk.util.AuthConfigUtil;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewEngine;
import org.apache.cordova.CordovaWebViewImpl;
import org.json.JSONObject;
import okhttp3.HttpUrl;
/**
* Class that defines the main activity for a PhoneGap-based application.
*/
public class SalesforceDroidGapActivity extends CordovaActivity implements SalesforceActivityInterface {
private static final String TAG = "SfDroidGapActivity";
// Delegate
private final SalesforceActivityDelegate delegate;
// Rest client
private RestClient client;
private ClientManager clientManager;
// Config
private BootConfig bootconfig;
private AuthConfigUtil.MyDomainAuthConfig authConfig;
// Web app loaded?
private boolean webAppLoaded = false;
public SalesforceDroidGapActivity() {
super();
delegate = new SalesforceActivityDelegate(this);
}
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
// Get bootconfig
bootconfig = BootConfig.getBootConfig(this);
// Get clientManager
clientManager = buildClientManager();
// Setup global stores and syncs defined in static configs
SalesforceHybridSDKManager.getInstance().setupGlobalStoreFromDefaultConfig();
SalesforceHybridSDKManager.getInstance().setupGlobalSyncsFromDefaultConfig();
// Delegate create
delegate.onCreate();
}
public ClientManager buildClientManager() {
return SalesforceHybridSDKManager.getInstance().getClientManager();
}
@Override
public void init() {
super.init();
EventsObservable.get().notifyEvent(EventType.GapWebViewCreateComplete, appView);
}
@Override
protected CordovaWebViewEngine makeWebViewEngine() {
final String className = SalesforceWebViewEngine.class.getCanonicalName();
preferences.set("webview", className);
return CordovaWebViewImpl.createEngine(this, preferences);
}
@Override
public void onResume() {
super.onResume();
// Fetches auth config if required.
try {
(new FetchAuthConfigTask()).execute();
} catch (Exception e) {
SalesforceHybridLogger.e(TAG, "Exception occurred while fetching auth config", e);
}
delegate.onResume(false);
// will call this.onResume(RestClient client) with a null client
}
@Override
public void onResume(RestClient c) {
// Called from delegate with null
// Get client (if already logged in)
try {
client = clientManager.peekRestClient();
} catch (AccountInfoNotFoundException e) {
client = null;
}
// Not logged in
if (client == null) {
if (!webAppLoaded) {
onResumeNotLoggedIn();
} else {
SalesforceHybridLogger.i(TAG, "onResume - unauthenticated web app already loaded");
}
}
// Logged in
else {
// Web app never loaded
if (!webAppLoaded) {
onResumeLoggedInNotLoaded();
}
// Web app already loaded
else {
SalesforceHybridLogger.i(TAG, "onResume - already logged in/web app already loaded");
}
}
}
/**
* Returns the auth config associated with the current login server, if it exists.
*
* @return Auth config.
*/
public AuthConfigUtil.MyDomainAuthConfig getAuthConfig() {
return authConfig;
}
/**
* Called when resuming activity and user is not authenticated
*/
private void onResumeNotLoggedIn() {
try {
BootConfig.validateBootConfig(bootconfig);
// Need to be authenticated
if (bootconfig.shouldAuthenticate()) {
// Online
if (SalesforceSDKManager.getInstance().hasNetwork()) {
SalesforceHybridLogger.i(TAG, "onResumeNotLoggedIn - should authenticate/online - authenticating");
authenticate(null);
}
// Offline
else {
SalesforceHybridLogger.w(TAG, "onResumeNotLoggedIn - should authenticate/offline - can not proceed");
loadErrorPage();
}
}
// Does not need to be authenticated
else {
// Local
if (bootconfig.isLocal()) {
SalesforceHybridLogger.i(TAG, "onResumeNotLoggedIn - should not authenticate/local start page - loading web app");
loadLocalStartPage();
}
// Remote
else {
SalesforceHybridLogger.w(TAG, "onResumeNotLoggedIn - should not authenticate/remote start page - loading web app");
loadRemoteStartPage(getUnauthenticatedStartPage(), false);
}
}
} catch (BootConfig.BootConfigException e) {
SalesforceHybridLogger.w(TAG, "onResumeNotLoggedIn - Boot config did not pass validation: "
+ e.getMessage()
+ " - cannot proceed");
loadErrorPage();
}
}
/**
* Called when resuming activity and user is authenticated but webview has not been loaded yet
*/
private void onResumeLoggedInNotLoaded() {
// Setup user stores and syncs defined in static configs
SalesforceHybridSDKManager.getInstance().setupUserStoreFromDefaultConfig();
SalesforceHybridSDKManager.getInstance().setupUserSyncsFromDefaultConfig();
// Local
if (bootconfig.isLocal()) {
SalesforceHybridLogger.i(TAG, "onResumeLoggedInNotLoaded - local start page - loading web app");
loadLocalStartPage();
}
// Remote
else {
// Online
if (SalesforceSDKManager.getInstance().hasNetwork()) {
SalesforceHybridLogger.i(TAG, "onResumeLoggedInNotLoaded - remote start page/online - loading web app");
loadRemoteStartPage(bootconfig.getStartPage(), true);
}
// Offline
else {
// Has cached version
if (SalesforceWebViewClientHelper.hasCachedAppHome(this)) {
SalesforceHybridLogger.i(TAG, "onResumeLoggedInNotLoaded - remote start page/offline/cached - loading cached web app");
loadCachedStartPage();
}
// No cached version
else {
SalesforceHybridLogger.i(TAG, "onResumeLoggedInNotLoaded - remote start page/offline/not cached - can not proceed");
loadErrorPage();
}
}
}
}
@Override
public void onPause() {
super.onPause();
delegate.onPause();
}
@Override
public void onDestroy() {
delegate.onDestroy();
super.onDestroy();
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
return delegate.onKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
}
/**
* Returns an instance of BootConfig.
*
* @return Instance of BootConfig.
*/
public BootConfig getBootConfig() {
return bootconfig;
}
/**
* Returns the unauthenticated start page from BootConfig.
*
* @return The unauthenticated start page
*/
protected String getUnauthenticatedStartPage() {
return bootconfig.getUnauthenticatedStartPage();
}
/**
* Returns an instance of RestClient.
*
* @return Instance of RestClient.
*/
public RestClient getRestClient() {
return client;
}
public void logout(CallbackContext callbackContext) {
SalesforceHybridLogger.i(TAG, "logout called");
SalesforceSDKManager.getInstance().logout(this);
if (callbackContext != null) {
callbackContext.success();
}
}
/**
* Get a RestClient and refresh the auth token
*
* @param callbackContext when not null credentials/errors are sent through to callbackContext.success()/error()
*/
public void authenticate(final CallbackContext callbackContext) {
SalesforceHybridLogger.i(TAG, "authenticate called");
clientManager.getRestClient(this, new RestClientCallback() {
@Override
public void authenticatedRestClient(RestClient client) {
if (client == null) {
SalesforceHybridLogger.i(TAG, "authenticate callback triggered with null client");
logout(null);
} else {
SalesforceHybridLogger.i(TAG, "authenticate callback triggered with actual client");
SalesforceDroidGapActivity.this.client = client;
/*
* Do a cheap REST call to refresh the access token if needed.
* If the login took place a while back (e.g. the already logged
* in application was restarted), then the returned session ID
* (access token) might be stale. This is not an issue if one
* uses exclusively RestClient for calling the server because
* it takes care of refreshing the access token when needed,
* but a stale session ID will cause the WebView to redirect
* to the web login.
*/
SalesforceDroidGapActivity.this.client.sendAsync(RestRequest.getRequestForUserInfo(), new AsyncRequestCallback() {
@Override
public void onSuccess(RestRequest request, RestResponse response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
/*
* The client instance being used here needs to be
* refreshed, to ensure we use the new access token.
*/
SalesforceDroidGapActivity.this.client = SalesforceDroidGapActivity.this.clientManager.peekRestClient();
getAuthCredentials(callbackContext);
}
});
}
@Override
public void onError(Exception exception) {
if (callbackContext != null) {
callbackContext.error(exception.getMessage());
}
}
});
}
}
});
}
/**
* Get json for credentials
*
* @param callbackContext
*/
public void getAuthCredentials(CallbackContext callbackContext) {
SalesforceHybridLogger.i(TAG, "getAuthCredentials called");
if (client != null) {
JSONObject credentials = client.getJSONCredentials();
if (callbackContext != null) {
callbackContext.success(credentials);
}
} else {
if (callbackContext != null) {
callbackContext.error("Never authenticated");
}
}
}
/**
* If an action causes a redirect to the login page, this method will be called.
* It causes the session to be refreshed and reloads url through the front door.
*
* @param url the page to load once the session has been refreshed.
*/
public void refresh(final String url) {
SalesforceHybridLogger.i(TAG, "refresh called");
/*
* If client is null at this point, authentication hasn't been performed yet.
* We need to trigger authentication, and recreate the webview in the
* callback, to load the page correctly. This handles some corner cases
* involving hitting the back button when authentication is in progress.
*/
if (client == null) {
clientManager.getRestClient(this, new RestClientCallback() {
@Override
public void authenticatedRestClient(RestClient client) {
recreate();
}
});
return;
}
client.sendAsync(RestRequest.getRequestForUserInfo(), new AsyncRequestCallback() {
@Override
public void onSuccess(RestRequest request, RestResponse response) {
SalesforceHybridLogger.i(TAG, "refresh callback - refresh succeeded");
runOnUiThread(new Runnable() {
@Override
public void run() {
/*
* The client instance being used here needs to be refreshed, to ensure we
* use the new access token. However, if the refresh token was revoked
* when the app was in the background, we need to catch that exception
* and trigger a proper logout to reset the state of this class.
*/
try {
SalesforceDroidGapActivity.this.client = SalesforceDroidGapActivity.this.clientManager.peekRestClient();
final String frontDoorUrl = getFrontDoorUrl(url, BootConfig.isAbsoluteUrl(url));
loadUrl(frontDoorUrl);
} catch (AccountInfoNotFoundException e) {
SalesforceHybridLogger.i(TAG, "User has been logged out.");
logout(null);
}
}
});
}
@Override
public void onError(Exception exception) {
SalesforceHybridLogger.w(TAG, "refresh callback - refresh failed", exception);
// Only logout if we are NOT offline
if (!(exception instanceof NoNetworkException)) {
logout(null);
}
}
});
}
/**
* Load local start page
*/
public void loadLocalStartPage() {
assert bootconfig.isLocal();
String startPage = bootconfig.getStartPage();
SalesforceHybridLogger.i(TAG, "loadLocalStartPage called - loading!");
loadUrl("file:///android_asset/www/" + startPage);
webAppLoaded = true;
}
/**
* Load remote start page (front-doored)
*/
public void loadRemoteStartPage() {
loadRemoteStartPage(bootconfig.getStartPage(), true);
}
/**
* Load the remote start page.
* @param startPageUrl The start page to load.
* @param loadThroughFrontDoor Whether or not to load through front-door.
*/
private void loadRemoteStartPage(String startPageUrl, boolean loadThroughFrontDoor) {
assert !bootconfig.isLocal();
String url = startPageUrl;
if (loadThroughFrontDoor) {
url = getFrontDoorUrl(url, BootConfig.isAbsoluteUrl(url));
}
SalesforceHybridLogger.i(TAG, "loadRemoteStartPage called - loading!");
loadUrl(url);
webAppLoaded = true;
}
/**
* Returns the front-doored URL of a URL passed in.
*
* @param url URL to be front-doored.
* @param isAbsUrl True - if the URL should be used as is, False - otherwise.
* @return Front-doored URL.
*/
public String getFrontDoorUrl(String url, boolean isAbsUrl) {
/*
* We need to use the absolute URL in some cases and relative URL in some
* other cases, because of differences between instance URL and community
* URL. Community URL can be custom and the logic of determining which
* URL to use is in the 'resolveUrl' method in 'ClientInfo'.
*/
url = (isAbsUrl ? url : client.getClientInfo().resolveUrl(url).toString());
final HttpUrl frontDoorUrl = HttpUrl.parse(client.getClientInfo().getInstanceUrlAsString()
+ "/secur/frontdoor.jsp?").newBuilder()
.addQueryParameter("sid", client.getAuthToken())
.addQueryParameter("retURL", url)
.addQueryParameter("display", "touch")
.build();
return frontDoorUrl.toString();
}
/**
* Load cached start page
*/
private void loadCachedStartPage() {
String url = SalesforceWebViewClientHelper.getAppHomeUrl(this);
loadUrl(url);
webAppLoaded = true;
}
/**
* Load error page
*/
public void loadErrorPage() {
String errorPage = bootconfig.getErrorPage();
SalesforceHybridLogger.i(TAG, "getErrorPageUrl called - local error page: " + errorPage);
loadUrl("file:///android_asset/www/" + errorPage);
}
/**
* Returns the WebView being used.
*
* @return WebView being used.
*/
public CordovaWebView getAppView() {
return appView;
}
@Override
public void onLogoutComplete() {
}
@Override
public void onUserSwitched() {
if (client != null) {
try {
RestClient currentClient = clientManager.peekRestClient();
if (currentClient != null && !currentClient.getClientInfo().userId.equals(client.getClientInfo().userId)) {
this.recreate();
}
} catch (AccountInfoNotFoundException e) {
SalesforceHybridLogger.i(TAG, "restartIfUserSwitched - no user account found");
}
}
}
private class FetchAuthConfigTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... nothings) {
final String loginServer = SalesforceHybridSDKManager.getInstance().getLoginServerManager().getSelectedLoginServer().url.trim();
if (loginServer.equals(LoginServerManager.PRODUCTION_LOGIN_URL) ||
loginServer.equals(LoginServerManager.SANDBOX_LOGIN_URL) ||
!URLUtil.isHttpsUrl(loginServer) || HttpUrl.parse(loginServer) == null) {
return null;
}
authConfig = AuthConfigUtil.getMyDomainAuthConfig(loginServer);
return null;
}
}
}