/
Exponent.java
685 lines (559 loc) · 22.7 KB
/
Exponent.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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
// Copyright 2015-present 650 Industries. All rights reserved.
package host.exp.expoview;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.os.UserManager;
import android.provider.Settings;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import com.facebook.common.internal.ByteStreams;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.stetho.Stetho;
import com.raizlabs.android.dbflow.config.FlowManager;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.io.output.TeeOutputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.security.Provider;
import java.security.Security;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.unimodules.core.interfaces.Package;
import org.unimodules.core.interfaces.SingletonModule;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;
import host.exp.exponent.ABIVersion;
import host.exp.exponent.ActivityResultListener;
import host.exp.exponent.Constants;
import host.exp.exponent.ExpoHandler;
import host.exp.exponent.ExponentManifest;
import host.exp.exponent.RNObject;
import host.exp.exponent.analytics.Analytics;
import host.exp.exponent.analytics.EXL;
import host.exp.exponent.di.NativeModuleDepsProvider;
import host.exp.exponent.kernel.ExperienceId;
import host.exp.exponent.kernel.ExponentUrls;
import host.exp.exponent.kernel.KernelConstants;
import host.exp.exponent.network.ExpoHttpCallback;
import host.exp.exponent.network.ExpoResponse;
import host.exp.exponent.network.ExponentHttpClient;
import host.exp.exponent.network.ExponentNetwork;
import host.exp.exponent.storage.ExponentSharedPreferences;
import host.exp.exponent.utils.PermissionsHelper;
import versioned.host.exp.exponent.ExponentPackageDelegate;
public class Exponent {
private static final String TAG = Exponent.class.getSimpleName();
private static final String PACKAGER_RUNNING = "running";
private static Exponent sInstance;
private Context mContext;
private Application mApplication;
private Activity mActivity;
private Map<String, String> mBundleStrings = new HashMap<>();
public String getBundleSource(final String path) {
synchronized (mBundleStrings) {
if (mBundleStrings.containsKey(path)) {
final String result = mBundleStrings.get(path);
mBundleStrings.remove(path);
return result;
} else {
return null;
}
}
}
@Inject
ExponentNetwork mExponentNetwork;
@Inject
ExponentManifest mExponentManifest;
@Inject
ExponentSharedPreferences mExponentSharedPreferences;
@Inject
ExpoHandler mExpoHandler;
public static void initialize(Context context, Application application) {
if (sInstance == null) {
new Exponent(context, application);
}
}
public static Exponent getInstance() {
return sInstance;
}
private Exponent(Context context, Application application) {
sInstance = this;
mContext = context;
mApplication = application;
// Ensure Spongy Castle installed so the security providers don't change
// non-deterministically during the process's lifetime
Exponent.getBouncyCastleProvider();
NativeModuleDepsProvider.initialize(application);
NativeModuleDepsProvider.getInstance().inject(Exponent.class, this);
// Verifying SSL certs is slow on Android, so send an HTTPS request to our server as early as possible.
// This speeds up the manifest request in a shell app from ~500ms to ~250ms.
try {
mExponentNetwork.getClient().call(new Request.Builder().url(Constants.API_HOST + "/status").build(), new ExpoHttpCallback() {
@Override
public void onFailure(IOException e) {
EXL.d(TAG, e.toString());
}
@Override
public void onResponse(ExpoResponse response) throws IOException {
ExponentNetwork.flushResponse(response);
EXL.d(TAG, "Loaded exp.host status page.");
}
});
} catch (Throwable e) {
EXL.e(TAG, e);
}
// Fixes Android memory leak
try {
UserManager.class.getMethod("get", Context.class).invoke(null, context);
} catch (Throwable e) {
EXL.testError(e);
}
try {
Fresco.initialize(context);
} catch (RuntimeException e) {
EXL.testError(e);
}
// Amplitude
Analytics.initializeAmplitude(context, application);
// TODO: profile this
FlowManager.init(context);
if (ExpoViewBuildConfig.DEBUG) {
Stetho.initializeWithDefaults(context);
}
if (!ExpoViewBuildConfig.DEBUG) {
// There are a few places in RN code that throw NetworkOnMainThreadException.
// WebsocketJavaScriptExecutor.connectInternal closes a websocket on the main thread.
// Shouldn't actually block the ui since it's fire and forget so not high priority to fix the root cause.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
public void setCurrentActivity(Activity activity) {
mActivity = activity;
}
public Activity getCurrentActivity() {
return mActivity;
}
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
new Handler(mContext.getMainLooper()).post(action);
} else {
action.run();
}
}
private String mGCMSenderId;
public void setGCMSenderId(final String senderId) {
mGCMSenderId = senderId;
}
public String getGCMSenderId() {
return mGCMSenderId;
}
public interface PermissionsListener {
void permissionsGranted();
void permissionsDenied();
}
private List<ActivityResultListener> mActivityResultListeners = new ArrayList<>();
private PermissionsHelper mPermissionsHelper;
public boolean getPermissions(String permissions, ExperienceId experienceId) {
return new PermissionsHelper(experienceId).getPermissions(permissions);
}
public boolean requestPermissions(PermissionsListener listener, String[] permissions,
ExperienceId experienceId, String experienceName) {
mPermissionsHelper = new PermissionsHelper(experienceId);
return mPermissionsHelper.requestPermissions(listener, permissions, experienceName);
}
public void requestExperiencePermissions(PermissionsListener listener, String[] permissions,
ExperienceId experienceId, String experienceName) {
new PermissionsHelper(experienceId).requestExperiencePermissions(listener, permissions, experienceName);
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (permissions.length > 0 && grantResults.length > 0 && mPermissionsHelper != null) {
mPermissionsHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
mPermissionsHelper = null;
}
}
public static class InstanceManagerBuilderProperties {
public Application application;
public String jsBundlePath;
public RNObject linkingPackage;
public Map<String, Object> experienceProperties;
public List<Package> expoPackages;
public ExponentPackageDelegate exponentPackageDelegate;
public JSONObject manifest;
public List<SingletonModule> singletonModules;
}
public void addActivityResultListener(ActivityResultListener listener) {
mActivityResultListeners.add(listener);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
for (ActivityResultListener listener : mActivityResultListeners) {
listener.onActivityResult(requestCode, resultCode, data);
}
}
public Application getApplication() {
return mApplication;
}
public static void logException(Throwable throwable) {
if (!ExpoViewBuildConfig.DEBUG) {
try {
Crashlytics.logException(throwable);
} catch (Throwable e) {
Log.e(TAG, e.toString());
}
}
}
private static Provider sBouncyCastleProvider;
public static synchronized Provider getBouncyCastleProvider() {
if (sBouncyCastleProvider == null) {
sBouncyCastleProvider = new BouncyCastleProvider();
Security.insertProviderAt(sBouncyCastleProvider, 1);
}
return sBouncyCastleProvider;
}
public String encodeExperienceId(final String manifestId) throws UnsupportedEncodingException {
return URLEncoder.encode("experience-" + manifestId, "UTF-8");
}
/*
*
* Bundle loading
*
*/
public interface BundleListener {
void onBundleLoaded(String localBundlePath);
void onError(Exception e);
}
// `id` must be URL encoded. Returns true if found cached bundle.
public boolean loadJSBundle(final JSONObject manifest, final String urlString, final String id, String abiVersion, final BundleListener bundleListener) {
return loadJSBundle(manifest, urlString, id, abiVersion, bundleListener, false);
}
public boolean loadJSBundle(JSONObject manifest, final String urlString, final String id, String abiVersion, final BundleListener bundleListener, boolean shouldForceNetwork) {
return loadJSBundle(manifest, urlString, id, abiVersion, bundleListener, shouldForceNetwork, false);
}
public boolean loadJSBundle(JSONObject manifest, final String urlString, final String id, String abiVersion, final BundleListener bundleListener, boolean shouldForceNetwork, boolean shouldForceCache) {
if (!id.equals(KernelConstants.KERNEL_BUNDLE_ID)) {
Analytics.markEvent(Analytics.TimedEvent.STARTED_FETCHING_BUNDLE);
}
if (manifest == null) {
manifest = new JSONObject();
}
boolean isDeveloping = manifest.has("developer");
if (isDeveloping) {
// This is important for running locally with no-dev
shouldForceNetwork = true;
}
// The bundle is cached in two places:
// 1. The OkHttp cache (which lives in internal storage)
// 2. Written to our own file (in cache dir)
// Ideally we'd take the OkHttp response and send the InputStream directly to RN but RN doesn't
// support that right now so we need to write the response to a file.
// getCacheDir() doesn't work here! Some phones clean the file up in between when we check
// file.exists() and when we feed it into React Native!
// TODO: clean up files here!
final String fileName = KernelConstants.BUNDLE_FILE_PREFIX + id + Integer.toString(urlString.hashCode()) + '-' + abiVersion;
final File directory = new File(mContext.getFilesDir(), abiVersion);
if (!directory.exists()) {
directory.mkdir();
}
try {
Request.Builder requestBuilder = KernelConstants.KERNEL_BUNDLE_ID.equals(id)
// TODO(eric): remove once home bundle is loaded normally
? ExponentUrls.addExponentHeadersToUrl(urlString)
: new Request.Builder().url(urlString);
if (shouldForceNetwork) {
requestBuilder.cacheControl(CacheControl.FORCE_NETWORK);
}
Request request = requestBuilder.build();
// Use OkHttpClient with long read timeout for dev bundles
ExponentHttpClient.SafeCallback callback = new ExponentHttpClient.SafeCallback() {
@Override
public void onFailure(IOException e) {
bundleListener.onError(e);
}
@Override
public void onResponse(ExpoResponse response) {
if (!response.isSuccessful()) {
String body = "(could not render body)";
try {
body = response.body().string();
} catch (IOException e) {
EXL.e(TAG, e);
}
bundleListener.onError(new Exception("Bundle return code: " + response.code() +
". With body: " + body));
return;
}
if (!id.equals(KernelConstants.KERNEL_BUNDLE_ID)) {
Analytics.markEvent(Analytics.TimedEvent.FINISHED_FETCHING_BUNDLE);
}
try {
if (!id.equals(KernelConstants.KERNEL_BUNDLE_ID)) {
Analytics.markEvent(Analytics.TimedEvent.STARTED_WRITING_BUNDLE);
}
final File sourceFile = new File(directory, fileName);
boolean hasCachedSourceFile = false;
if (response.networkResponse() == null || response.networkResponse().code() == KernelConstants.HTTP_NOT_MODIFIED) {
// If we're getting a cached response don't rewrite the file to disk.
EXL.d(TAG, "Got cached OkHttp response for " + urlString);
if (sourceFile.exists()) {
hasCachedSourceFile = true;
EXL.d(TAG, "Have cached source file for " + urlString);
}
}
if (!hasCachedSourceFile) {
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
TeeOutputStream teeOutputStream = null;
try {
EXL.d(TAG, "Do not have cached source file for " + urlString);
inputStream = response.body().byteStream();
fileOutputStream = new FileOutputStream(sourceFile);
byteArrayOutputStream = new ByteArrayOutputStream();
// Multiplex the stream. Write both to file and string.
teeOutputStream = new TeeOutputStream(fileOutputStream, byteArrayOutputStream);
ByteStreams.copy(inputStream, teeOutputStream);
teeOutputStream.flush();
mBundleStrings.put(sourceFile.getAbsolutePath(), byteArrayOutputStream.toString());
fileOutputStream.flush();
fileOutputStream.getFD().sync();
} finally {
IOUtils.closeQuietly(teeOutputStream);
IOUtils.closeQuietly(fileOutputStream);
IOUtils.closeQuietly(byteArrayOutputStream);
IOUtils.closeQuietly(inputStream);
}
}
if (!id.equals(KernelConstants.KERNEL_BUNDLE_ID)) {
Analytics.markEvent(Analytics.TimedEvent.FINISHED_WRITING_BUNDLE);
}
if (Constants.WRITE_BUNDLE_TO_LOG) {
printSourceFile(sourceFile.getAbsolutePath());
}
mExpoHandler.post(new Runnable() {
@Override
public void run() {
bundleListener.onBundleLoaded(sourceFile.getAbsolutePath());
}
});
} catch (Exception e) {
bundleListener.onError(e);
}
}
@Override
public void onCachedResponse(ExpoResponse response, boolean isEmbedded) {
EXL.d(TAG, "Using cached or embedded response.");
onResponse(response);
}
};
if (shouldForceCache) {
mExponentNetwork.getLongTimeoutClient().tryForcedCachedResponse(request.url().toString(), request, callback, null, null);
} else if (shouldForceNetwork) {
mExponentNetwork.getLongTimeoutClient().callSafe(request, callback);
} else {
mExponentNetwork.getLongTimeoutClient().callDefaultCache(request, callback);
}
} catch (Exception e) {
bundleListener.onError(e);
}
// Guess whether we'll use the cache based on whether the source file is saved.
final File sourceFile = new File(directory, fileName);
return sourceFile.exists();
}
private void printSourceFile(String path) {
EXL.d(KernelConstants.BUNDLE_TAG, "Printing bundle:");
InputStream inputStream = null;
try {
inputStream = new FileInputStream(path);
InputStreamReader inputReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputReader);
String line;
do {
line = bufferedReader.readLine();
EXL.d(KernelConstants.BUNDLE_TAG, line);
} while (line != null);
} catch (Exception e) {
EXL.e(KernelConstants.BUNDLE_TAG, e.toString());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
EXL.e(KernelConstants.BUNDLE_TAG, e.toString());
}
}
}
}
public static int getPort(String url) {
if (!url.contains("://")) {
url = "http://" + url;
}
Uri uri = Uri.parse(url);
int port = uri.getPort();
if (port == -1) {
return 80;
} else {
return port;
}
}
public static String getHostname(String url) {
if (!url.contains("://")) {
url = "http://" + url;
}
Uri uri = Uri.parse(url);
return uri.getHost();
}
public static void enableDeveloperSupport(String sdkVersion, String debuggerHost, String mainModuleName,
RNObject builder) {
if (!debuggerHost.isEmpty() && !mainModuleName.isEmpty()) {
try {
RNObject fieldObject = new RNObject("com.facebook.react.modules.systeminfo.AndroidInfoHelpers");
fieldObject.loadVersion(builder.version());
String debuggerHostHostname = getHostname(debuggerHost);
int debuggerHostPort = getPort(debuggerHost);
Field deviceField = fieldObject.rnClass().getDeclaredField("DEVICE_LOCALHOST");
deviceField.setAccessible(true);
deviceField.set(null, debuggerHostHostname);
Field genymotionField = fieldObject.rnClass().getDeclaredField("GENYMOTION_LOCALHOST");
genymotionField.setAccessible(true);
genymotionField.set(null, debuggerHostHostname);
Field emulatorField = fieldObject.rnClass().getDeclaredField("EMULATOR_LOCALHOST");
emulatorField.setAccessible(true);
emulatorField.set(null, debuggerHostHostname);
Field debugServerHostPortField = fieldObject.rnClass().getDeclaredField("DEBUG_SERVER_HOST_PORT");
debugServerHostPortField.setAccessible(true);
debugServerHostPortField.set(null, debuggerHostPort);
Field inspectorProxyPortField = fieldObject.rnClass().getDeclaredField("INSPECTOR_PROXY_PORT");
inspectorProxyPortField.setAccessible(true);
inspectorProxyPortField.set(null, debuggerHostPort);
builder.callRecursive("setUseDeveloperSupport", true);
builder.callRecursive("setJSMainModulePath", mainModuleName);
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
}
}
private static boolean hasDeclaredField(Class clazz, String field) {
try {
clazz.getDeclaredField(field);
return true;
} catch (NoSuchFieldException e) {
return false;
}
}
public interface PackagerStatusCallback {
void onSuccess();
void onFailure(String errorMessage);
}
public void testPackagerStatus(final boolean isDebug, final JSONObject mManifest, final PackagerStatusCallback callback) {
if (!isDebug) {
callback.onSuccess();
return;
}
final String debuggerHost = mManifest.optString(ExponentManifest.MANIFEST_DEBUGGER_HOST_KEY);
mExponentNetwork.getNoCacheClient().newCall(new Request.Builder().url("http://" + debuggerHost + "/status").build()).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
EXL.d(TAG, e.toString());
callback.onFailure("Packager is not running at http://" + debuggerHost);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseString = response.body().string();
if (responseString.contains(PACKAGER_RUNNING)) {
runOnUiThread(new Runnable() {
@Override
public void run() {
callback.onSuccess();
}
});
} else {
callback.onFailure("Packager is not running at http://" + debuggerHost);
}
}
});
}
public interface StartReactInstanceDelegate {
boolean isDebugModeEnabled();
boolean isInForeground();
ExponentPackageDelegate getExponentPackageDelegate();
void handleUnreadNotifications(JSONArray unreadNotifications);
}
public boolean shouldRequestDrawOverOtherAppsPermission() {
return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(mContext));
}
public void preloadManifestAndBundle(final String manifestUrl) {
try {
mExponentManifest.fetchManifest(manifestUrl, new ExponentManifest.ManifestListener() {
@Override
public void onCompleted(JSONObject manifest) {
try {
String bundleUrl = manifest.getString(ExponentManifest.MANIFEST_BUNDLE_URL_KEY);
preloadBundle(
manifest,
manifestUrl,
bundleUrl,
manifest.getString(ExponentManifest.MANIFEST_ID_KEY),
manifest.getString(ExponentManifest.MANIFEST_SDK_VERSION_KEY));
} catch (JSONException e) {
EXL.e(TAG, e);
} catch (Exception e) {
// Don't let any errors through
EXL.e(TAG, "Couldn't preload bundle: " + e.toString());
}
}
@Override
public void onError(Exception e) {
EXL.e(TAG, "Couldn't preload manifest: " + e.toString());
}
@Override
public void onError(String e) {
EXL.e(TAG, "Couldn't preload manifest: " + e);
}
});
} catch (Throwable e) {
EXL.e(TAG, "Couldn't preload manifest: " + e.toString());
}
}
private void preloadBundle(final JSONObject manifest, final String manifestUrl, final String bundleUrl, final String id, final String sdkVersion) {
try {
Exponent.getInstance().loadJSBundle(manifest, bundleUrl, Exponent.getInstance().encodeExperienceId(id), sdkVersion, new Exponent.BundleListener() {
@Override
public void onError(Exception e) {
EXL.e(TAG, "Couldn't preload bundle: " + e.toString());
}
@Override
public void onBundleLoaded(String localBundlePath) {
EXL.d(TAG, "Successfully preloaded manifest and bundle for " + manifestUrl + " " + bundleUrl);
}
}, true);
} catch (UnsupportedEncodingException e) {
EXL.e(TAG, "Couldn't encode preloaded bundle id: " + e.toString());
}
}
}