/
HeadlessAppLoader.java
373 lines (314 loc) · 13.2 KB
/
HeadlessAppLoader.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
package host.exp.exponent.headless;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import com.facebook.react.ReactPackage;
import com.facebook.react.common.MapBuilder;
import com.facebook.soloader.SoLoader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.unimodules.adapters.react.ReactModuleRegistryProvider;
import org.unimodules.core.interfaces.Package;
import org.unimodules.core.interfaces.SingletonModule;
import expo.loaders.provider.AppLoaderProvider;
import expo.loaders.provider.interfaces.AppLoaderInterface;
import expo.loaders.provider.interfaces.AppLoaderPackagesProviderInterface;
import expo.loaders.provider.interfaces.AppRecordInterface;
import host.exp.exponent.AppLoader;
import host.exp.exponent.Constants;
import host.exp.exponent.ExponentManifest;
import host.exp.exponent.RNObject;
import host.exp.exponent.experience.DetachedModuleRegistryAdapter;
import host.exp.exponent.kernel.ExponentUrls;
import host.exp.exponent.utils.AsyncCondition;
import host.exp.exponent.utils.ExpoActivityIds;
import host.exp.expoview.Exponent;
import versioned.host.exp.exponent.ExponentPackage;
import versioned.host.exp.exponent.ExponentPackageDelegate;
import versioned.host.exp.exponent.modules.universal.ExpoModuleRegistryAdapter;
import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread;
import static host.exp.exponent.kernel.KernelConstants.INTENT_URI_KEY;
import static host.exp.exponent.kernel.KernelConstants.IS_HEADLESS_KEY;
import static host.exp.exponent.kernel.KernelConstants.LINKING_URI_KEY;
import static host.exp.exponent.kernel.KernelConstants.MANIFEST_URL_KEY;
// @tsapeta: Most parts of this class was just copied from ReactNativeActivity and ExperienceActivity,
// however it allows launching apps in the background, without the activity.
// I've found it pretty hard to make just one implementation that can be used in both cases,
// so I decided to go with a copy until we refactor these activity classes.
public class HeadlessAppLoader implements AppLoaderInterface, Exponent.StartReactInstanceDelegate, ExponentPackageDelegate {
private static String READY_FOR_BUNDLE = "headlessAppReadyForBundle";
private static final Map<Integer, String> sActivityIdToBundleUrl = new HashMap<>();
private JSONObject mManifest;
private String mManifestUrl;
private String mSdkVersion;
private String mDetachSdkVersion;
private RNObject mReactInstanceManager = new RNObject("com.facebook.react.ReactInstanceManager");
private Context mContext;
private String mIntentUri;
private boolean mIsReadyForBundle;
private String mJSBundlePath;
private HeadlessAppRecord mAppRecord;
private AppLoaderProvider.Callback mCallback;
private int mActivityId;
public HeadlessAppLoader(Context context) {
mContext = context;
}
public static boolean hasBundleUrlForActivityId(int activityId) {
return activityId < -1 && sActivityIdToBundleUrl.containsKey(activityId);
}
public static String getBundleUrlForActivityId(int activityId) {
return sActivityIdToBundleUrl.get(activityId);
}
@Override
public AppRecordInterface loadApp(String appUrl, Map<String, Object> options, AppLoaderProvider.Callback callback) {
mManifestUrl = appUrl;
mAppRecord = new HeadlessAppRecord();
mCallback = callback;
mActivityId = ExpoActivityIds.getNextHeadlessActivityId();
new AppLoader(mManifestUrl, true) {
@Override
public void onOptimisticManifest(final JSONObject optimisticManifest) {
}
@Override
public void onManifestCompleted(final JSONObject manifest) {
Exponent.getInstance().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
String bundleUrl = ExponentUrls.toHttp(manifest.getString("bundleUrl"));
sActivityIdToBundleUrl.put(mActivityId, bundleUrl);
setManifest(mManifestUrl, manifest, bundleUrl);
} catch (JSONException e) {
mCallback.onComplete(false, new Exception(e.getMessage()));
}
}
});
}
@Override
public void onBundleCompleted(String localBundlePath) {
setBundle(localBundlePath);
}
@Override
public void emitEvent(JSONObject params) {
}
@Override
public void onError(Exception e) {
mCallback.onComplete(false, new Exception(e.getMessage()));
}
@Override
public void onError(String e) {
mCallback.onComplete(false, new Exception(e));
}
}.start();
return mAppRecord;
}
public void setManifest(String manifestUrl, final JSONObject manifest, final String bundleUrl) {
mManifestUrl = manifestUrl;
mManifest = manifest;
mSdkVersion = manifest.optString(ExponentManifest.MANIFEST_SDK_VERSION_KEY);
// Sometime we want to release a new version without adding a new .aar. Use TEMPORARY_ABI_VERSION
// to point to the unversioned code in ReactAndroid.
if (Constants.TEMPORARY_ABI_VERSION != null && Constants.TEMPORARY_ABI_VERSION.equals(mSdkVersion)) {
mSdkVersion = RNObject.UNVERSIONED;
}
mDetachSdkVersion = Constants.isStandaloneApp() ? RNObject.UNVERSIONED : mSdkVersion;
if (!RNObject.UNVERSIONED.equals(mSdkVersion)) {
boolean isValidVersion = false;
for (final String version : Constants.SDK_VERSIONS_LIST) {
if (version.equals(mSdkVersion)) {
isValidVersion = true;
break;
}
}
if (!isValidVersion) {
mCallback.onComplete(false, new Exception(mSdkVersion + " is not a valid SDK version."));
return;
}
}
soloaderInit();
// if we have an embedded initial url, we never need any part of this in the initial url
// passed to the JS, so we check for that and filter it out here.
// this can happen in dev mode on a detached app, for example, because the intent will have
// a url like customscheme://localhost:19000 but we don't care about the localhost:19000 part.
if (mIntentUri == null || mIntentUri.equals(Constants.INITIAL_URL)) {
if (Constants.SHELL_APP_SCHEME != null) {
mIntentUri = Constants.SHELL_APP_SCHEME + "://";
} else {
mIntentUri = mManifestUrl;
}
}
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mReactInstanceManager.isNotNull()) {
mReactInstanceManager.onHostDestroy();
mReactInstanceManager.assign(null);
}
if (isDebugModeEnabled()) {
mJSBundlePath = "";
startReactInstance();
} else {
mIsReadyForBundle = true;
AsyncCondition.notify(READY_FOR_BUNDLE);
}
}
});
}
public void setBundle(final String localBundlePath) {
if (!isDebugModeEnabled()) {
AsyncCondition.wait(READY_FOR_BUNDLE, new AsyncCondition.AsyncConditionListener() {
@Override
public boolean isReady() {
return mIsReadyForBundle;
}
@Override
public void execute() {
mJSBundlePath = localBundlePath;
startReactInstance();
AsyncCondition.remove(READY_FOR_BUNDLE);
}
});
}
}
public boolean isDebugModeEnabled() {
return ExponentManifest.isDebugModeEnabled(mManifest);
}
public void soloaderInit() {
if (mDetachSdkVersion != null) {
SoLoader.init(mContext, false);
}
}
// Override
@SuppressWarnings("unchecked")
private List<ReactPackage> reactPackages() {
if (!Constants.isStandaloneApp()) {
// Pass null if it's on Expo Client. In that case packages from ExperiencePackagePicker will be used instead.
return null;
}
try {
return ((AppLoaderPackagesProviderInterface<ReactPackage>) mContext.getApplicationContext()).getPackages();
} catch (ClassCastException e) {
e.printStackTrace();
return null;
}
}
// Override
@SuppressWarnings("unchecked")
public List<Package> expoPackages() {
if (!Constants.isStandaloneApp()) {
// Pass null if it's on Expo Client. In that case packages from ExperiencePackagePicker will be used instead.
return null;
}
try {
return ((AppLoaderPackagesProviderInterface) mContext.getApplicationContext()).getExpoPackages();
} catch (ClassCastException e) {
e.printStackTrace();
return null;
}
}
//region StartReactInstanceDelegate
@Override
public boolean isInForeground() {
return false;
}
@Override
public ExponentPackageDelegate getExponentPackageDelegate() {
return this;
}
@Override
public void handleUnreadNotifications(JSONArray unreadNotifications) {
}
//endregion
private void startReactInstance() {
Exponent.getInstance().testPackagerStatus(isDebugModeEnabled(), mManifest, new Exponent.PackagerStatusCallback() {
@Override
public void onSuccess() {
mReactInstanceManager = startReactInstance(HeadlessAppLoader.this, mIntentUri, mDetachSdkVersion, reactPackages(), expoPackages());
}
@Override
public void onFailure(final String errorMessage) {
mCallback.onComplete(false, new Exception(errorMessage));
}
});
}
private RNObject startReactInstance(final Exponent.StartReactInstanceDelegate delegate, final String mIntentUri, final String mSDKVersion,
final List<? extends Object> extraNativeModules, final List<Package> extraExpoPackages) {
String linkingUri = getLinkingUri();
Map<String, Object> experienceProperties = MapBuilder.<String, Object>of(
MANIFEST_URL_KEY, mManifestUrl,
LINKING_URI_KEY, linkingUri,
INTENT_URI_KEY, mIntentUri,
IS_HEADLESS_KEY, true
);
Exponent.InstanceManagerBuilderProperties instanceManagerBuilderProperties = new Exponent.InstanceManagerBuilderProperties();
instanceManagerBuilderProperties.application = (Application) mContext;
instanceManagerBuilderProperties.jsBundlePath = mJSBundlePath;
instanceManagerBuilderProperties.experienceProperties = experienceProperties;
instanceManagerBuilderProperties.expoPackages = extraExpoPackages;
instanceManagerBuilderProperties.exponentPackageDelegate = delegate.getExponentPackageDelegate();
instanceManagerBuilderProperties.manifest = mManifest;
instanceManagerBuilderProperties.singletonModules = ExponentPackage.getOrCreateSingletonModules(mContext, mManifest, extraExpoPackages);
RNObject versionedUtils = new RNObject("host.exp.exponent.VersionedUtils").loadVersion(mSDKVersion);
RNObject builder = versionedUtils.callRecursive("getReactInstanceManagerBuilder", instanceManagerBuilderProperties);
if (extraNativeModules != null) {
for (Object nativeModule : extraNativeModules) {
builder.call("addPackage", nativeModule);
}
}
if (delegate.isDebugModeEnabled()) {
String debuggerHost = mManifest.optString(ExponentManifest.MANIFEST_DEBUGGER_HOST_KEY);
String mainModuleName = mManifest.optString(ExponentManifest.MANIFEST_MAIN_MODULE_NAME_KEY);
Exponent.enableDeveloperSupport(mSDKVersion, debuggerHost, mainModuleName, builder);
}
RNObject reactInstanceManager = builder.callRecursive("build");
RNObject devSupportManager = mReactInstanceManager.callRecursive("getDevSupportManager");
if (devSupportManager != null) {
RNObject devSettings = devSupportManager.callRecursive("getDevSettings");
if (devSettings != null) {
devSettings.setField("exponentActivityId", mActivityId);
}
}
reactInstanceManager.call("createReactContextInBackground");
// keep a reference in app record, so it can be invalidated through AppRecord.invalidate()
mAppRecord.setReactInstanceManager(reactInstanceManager);
mCallback.onComplete(true, null);
return reactInstanceManager;
}
// deprecated in favor of Expo.Linking.makeUrl
// TODO: remove this
private String getLinkingUri() {
if (Constants.SHELL_APP_SCHEME != null) {
return Constants.SHELL_APP_SCHEME + "://";
} else {
Uri uri = Uri.parse(mManifestUrl);
String host = uri.getHost();
if (host != null && (host.equals("exp.host") || host.equals("expo.io") || host.equals("exp.direct") || host.equals("expo.test") ||
host.endsWith(".exp.host") || host.endsWith(".expo.io") || host.endsWith(".exp.direct") || host.endsWith(".expo.test"))) {
List<String> pathSegments = uri.getPathSegments();
Uri.Builder builder = uri.buildUpon();
builder.path(null);
for (String segment : pathSegments) {
if (ExponentManifest.DEEP_LINK_SEPARATOR.equals(segment)) {
break;
}
builder.appendEncodedPath(segment);
}
return builder.appendEncodedPath(ExponentManifest.DEEP_LINK_SEPARATOR_WITH_SLASH).build().toString();
} else {
return mManifestUrl;
}
}
}
@Override
public ExpoModuleRegistryAdapter getScopedModuleRegistryAdapterForPackages(List<Package> packages, List<SingletonModule> singletonModules) {
if (Constants.isStandaloneApp()) {
return new DetachedModuleRegistryAdapter(new ReactModuleRegistryProvider(packages, singletonModules));
} else {
return null;
}
}
}