xref: /expo/ios/Exponent/Kernel/Core/EXKernel.m (revision fa21c06b)
1// Copyright 2015-present 650 Industries. All rights reserved.
2
3#import "EXAnalytics.h"
4#import "EXAppState.h"
5#import "EXAppViewController.h"
6#import "EXBuildConstants.h"
7#import "EXKernel.h"
8#import "EXAppLoader.h"
9#import "EXKernelAppRecord.h"
10#import "EXKernelLinkingManager.h"
11#import "EXLinkingManager.h"
12#import "EXVersions.h"
13
14#import <React/RCTBridge+Private.h>
15#import <React/RCTEventDispatcher.h>
16#import <React/RCTModuleData.h>
17#import <React/RCTUtils.h>
18
19NS_ASSUME_NONNULL_BEGIN
20
21NSString *kEXKernelErrorDomain = @"EXKernelErrorDomain";
22NSString *kEXKernelShouldForegroundTaskEvent = @"foregroundTask";
23NSString * const kEXDeviceInstallUUIDKey = @"EXDeviceInstallUUIDKey";
24NSString * const kEXKernelClearJSCacheUserDefaultsKey = @"EXKernelClearJSCacheUserDefaultsKey";
25
26const NSUInteger kEXErrorCodeAppForbidden = 424242;
27
28@interface EXKernel () <EXKernelAppRegistryDelegate>
29
30@end
31
32// Protocol that should be implemented by all versions of EXAppState class.
33@protocol EXAppStateProtocol
34
35@property (nonatomic, strong, readonly) NSString *lastKnownState;
36
37- (void)setState:(NSString *)state;
38
39@end
40
41@implementation EXKernel
42
43+ (instancetype)sharedInstance
44{
45  static EXKernel *theKernel;
46  static dispatch_once_t once;
47  dispatch_once(&once, ^{
48    if (!theKernel) {
49      theKernel = [[EXKernel alloc] init];
50    }
51  });
52  return theKernel;
53}
54
55- (instancetype)init
56{
57  if (self = [super init]) {
58    // init app registry: keep track of RN bridges we are running
59    _appRegistry = [[EXKernelAppRegistry alloc] init];
60    _appRegistry.delegate = self;
61
62    // init service registry: classes which manage shared resources among all bridges
63    _serviceRegistry = [[EXKernelServiceRegistry alloc] init];
64
65    for (NSString *name in @[UIApplicationDidBecomeActiveNotification,
66                             UIApplicationDidEnterBackgroundNotification,
67                             UIApplicationDidFinishLaunchingNotification,
68                             UIApplicationWillResignActiveNotification,
69                             UIApplicationWillEnterForegroundNotification]) {
70
71      [[NSNotificationCenter defaultCenter] addObserver:self
72                                               selector:@selector(_handleAppStateDidChange:)
73                                                   name:name
74                                                 object:nil];
75    }
76    NSLog(@"Expo iOS Runtime Version %@", [EXBuildConstants sharedInstance].expoRuntimeVersion);
77  }
78  return self;
79}
80
81- (void)dealloc
82{
83  [[NSNotificationCenter defaultCenter] removeObserver:self];
84}
85
86#pragma mark - Misc
87
88+ (NSString *)deviceInstallUUID
89{
90  NSString *uuid = [[NSUserDefaults standardUserDefaults] stringForKey:kEXDeviceInstallUUIDKey];
91  if (!uuid) {
92    uuid = [[NSUUID UUID] UUIDString];
93    [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:kEXDeviceInstallUUIDKey];
94    [[NSUserDefaults standardUserDefaults] synchronize];
95  }
96  return uuid;
97}
98
99- (void)logAnalyticsEvent:(NSString *)eventId forAppRecord:(EXKernelAppRecord *)appRecord
100{
101  if (_appRegistry.homeAppRecord && appRecord == _appRegistry.homeAppRecord) {
102    return;
103  }
104  NSString *validatedSdkVersion = [[EXVersions sharedInstance] availableSdkVersionForManifest:appRecord.appLoader.manifest];
105  NSDictionary *props = (validatedSdkVersion) ? @{ @"SDK_VERSION": validatedSdkVersion } : @{};
106  [[EXAnalytics sharedInstance] logEvent:eventId
107                             manifestUrl:appRecord.appLoader.manifestUrl
108                         eventProperties:props];
109}
110
111#pragma mark - bridge registry delegate
112
113- (void)appRegistry:(EXKernelAppRegistry *)registry didRegisterAppRecord:(EXKernelAppRecord *)appRecord
114{
115  // forward to service registry
116  [_serviceRegistry appRegistry:registry didRegisterAppRecord:appRecord];
117}
118
119- (void)appRegistry:(EXKernelAppRegistry *)registry willUnregisterAppRecord:(EXKernelAppRecord *)appRecord
120{
121  // forward to service registry
122  [_serviceRegistry appRegistry:registry willUnregisterAppRecord:appRecord];
123}
124
125#pragma mark - Interfacing with JS
126
127- (void)sendUrl:(NSString *)urlString toAppRecord:(EXKernelAppRecord *)app
128{
129  // fire a Linking url event on this (possibly versioned) bridge
130  EXReactAppManager *appManager = app.appManager;
131  id linkingModule = [self nativeModuleForAppManager:appManager named:@"LinkingManager"];
132  if (!linkingModule) {
133    DDLogError(@"Could not find the Linking module to open URL (%@)", urlString);
134  } else if ([linkingModule respondsToSelector:@selector(dispatchOpenUrlEvent:)]) {
135    [linkingModule dispatchOpenUrlEvent:[NSURL URLWithString:urlString]];
136  } else {
137    DDLogError(@"Linking module doesn't support the API we use to open URL (%@)", urlString);
138  }
139  [self _moveAppToVisible:app];
140}
141
142- (id)nativeModuleForAppManager:(EXReactAppManager *)appManager named:(NSString *)moduleName
143{
144  id destinationBridge = appManager.reactBridge;
145
146  if ([destinationBridge respondsToSelector:@selector(batchedBridge)]) {
147    id batchedBridge = [destinationBridge batchedBridge];
148    id moduleData = [batchedBridge moduleDataForName:moduleName];
149
150    // React Native before SDK 11 didn't strip the "RCT" prefix from module names
151    if (!moduleData && ![moduleName hasPrefix:@"RCT"]) {
152      moduleData = [batchedBridge moduleDataForName:[@"RCT" stringByAppendingString:moduleName]];
153    }
154
155    if (moduleData) {
156      return [moduleData instance];
157    }
158  } else {
159    // bridge can be null if the record is in an error state and never created a bridge.
160    if (destinationBridge) {
161      DDLogError(@"Bridge does not support the API we use to get its underlying batched bridge");
162    }
163  }
164  return nil;
165}
166
167- (BOOL)sendNotification:(EXPendingNotification *)notification
168{
169  EXKernelAppRecord *destinationApp = [_appRegistry newestRecordWithExperienceId:notification.experienceId];
170  if (destinationApp) {
171    // send the body to the already-open experience
172    [self _dispatchJSEvent:@"Exponent.notification" body:notification.properties toApp:destinationApp];
173    [self _moveAppToVisible:destinationApp];
174    return YES;
175  } else {
176    // no app is currently running for this experience id.
177    // if we're Expo Client, we can query Home for a past experience in the user's history, and route the notification there.
178    if (_browserController) {
179      __weak typeof(self) weakSelf = self;
180      [_browserController getHistoryUrlForExperienceId:notification.experienceId completion:^(NSString *urlString) {
181        if (urlString) {
182          NSURL *url = [NSURL URLWithString:urlString];
183          if (url) {
184            [weakSelf createNewAppWithUrl:url initialProps:@{ @"notification": notification.properties }];
185          }
186        }
187      }];
188      // If we're here, there's no active app in appRegistry matching notification.experienceId
189      // and we are in Expo Client, since _browserController is not nil.
190      // If so, we can return YES (meaning "notification has been successfully dispatched")
191      // because we pass the notification as initialProps in completion handler
192      // of getHistoryUrlForExperienceId:. If urlString passed to completion handler is empty,
193      // the notification is forgotten (this is the expected behavior).
194      return YES;
195    }
196  }
197
198  return NO;
199}
200
201/**
202 *  If the bridge has a batchedBridge or parentBridge selector, posts the notification on that object as well.
203 */
204- (void)_postNotificationName: (NSNotificationName)name onAbstractBridge: (id)bridge
205{
206  [[NSNotificationCenter defaultCenter] postNotificationName:name object:bridge];
207  if ([bridge respondsToSelector:@selector(batchedBridge)]) {
208    [[NSNotificationCenter defaultCenter] postNotificationName:name object:[bridge batchedBridge]];
209  } else if ([bridge respondsToSelector:@selector(parentBridge)]) {
210    [[NSNotificationCenter defaultCenter] postNotificationName:name object:[bridge parentBridge]];
211  }
212}
213
214- (void)_dispatchJSEvent:(NSString *)eventName body:(NSDictionary *)eventBody toApp:(EXKernelAppRecord *)appRecord
215{
216  [appRecord.appManager.reactBridge enqueueJSCall:@"RCTDeviceEventEmitter.emit"
217                                             args:eventBody ? @[eventName, eventBody] : @[eventName]];
218}
219
220#pragma mark - App props
221
222- (nullable NSDictionary *)initialAppPropsFromLaunchOptions:(NSDictionary *)launchOptions
223{
224  return nil;
225}
226
227#pragma mark - App State
228
229- (EXKernelAppRecord *)createNewAppWithUrl:(NSURL *)url initialProps:(nullable NSDictionary *)initialProps
230{
231  NSString *recordId = [_appRegistry registerAppWithManifestUrl:url initialProps:initialProps];
232  EXKernelAppRecord *record = [_appRegistry recordForId:recordId];
233  [self _moveAppToVisible:record];
234  return record;
235}
236
237- (void)switchTasks
238{
239  if (!_browserController) {
240    return;
241  }
242
243  if (_visibleApp != _appRegistry.homeAppRecord) {
244    [EXUtil performSynchronouslyOnMainThread:^{
245      [self->_browserController toggleMenuWithCompletion:nil];
246    }];
247  } else {
248    EXKernelAppRegistry *appRegistry = [EXKernel sharedInstance].appRegistry;
249    for (NSString *recordId in appRegistry.appEnumerator) {
250      EXKernelAppRecord *record = [appRegistry recordForId:recordId];
251      // foreground the first thing we find
252      [self _moveAppToVisible:record];
253    }
254  }
255}
256
257- (void)reloadAppWithExperienceId:(NSString *)experienceId
258{
259  EXKernelAppRecord *appRecord = [_appRegistry newestRecordWithExperienceId:experienceId];
260  if (_browserController) {
261    [self createNewAppWithUrl:appRecord.appLoader.manifestUrl initialProps:nil];
262  } else if (_appRegistry.standaloneAppRecord && appRecord == _appRegistry.standaloneAppRecord) {
263    [appRecord.viewController refresh];
264  }
265}
266
267- (void)reloadAppFromCacheWithExperienceId:(NSString *)experienceId
268{
269  EXKernelAppRecord *appRecord = [_appRegistry newestRecordWithExperienceId:experienceId];
270  [appRecord.viewController reloadFromCache];
271}
272
273- (void)viewController:(__unused EXViewController *)vc didNavigateAppToVisible:(EXKernelAppRecord *)appRecord
274{
275  EXKernelAppRecord *appRecordPreviouslyVisible = _visibleApp;
276  if (appRecord != appRecordPreviouslyVisible) {
277    if (appRecordPreviouslyVisible) {
278      [appRecordPreviouslyVisible.viewController appStateDidBecomeInactive];
279      [self _postNotificationName:kEXKernelBridgeDidBackgroundNotification onAbstractBridge:appRecordPreviouslyVisible.appManager.reactBridge];
280      id<EXAppStateProtocol> appStateModule = [self nativeModuleForAppManager:appRecordPreviouslyVisible.appManager named:@"AppState"];
281      if (appStateModule != nil) {
282        [appStateModule setState:@"background"];
283      }
284    }
285    if (appRecord) {
286      [appRecord.viewController appStateDidBecomeActive];
287      [self _postNotificationName:kEXKernelBridgeDidForegroundNotification onAbstractBridge:appRecord.appManager.reactBridge];
288      id<EXAppStateProtocol> appStateModule = [self nativeModuleForAppManager:appRecord.appManager named:@"AppState"];
289      if (appStateModule != nil) {
290        [appStateModule setState:@"active"];
291      }
292      _visibleApp = appRecord;
293      [[EXAnalytics sharedInstance] logAppVisibleEvent];
294    } else {
295      _visibleApp = nil;
296    }
297
298    if (_visibleApp && _visibleApp != _appRegistry.homeAppRecord) {
299      [self _unregisterUnusedAppRecords];
300    }
301  }
302}
303
304- (void)_unregisterUnusedAppRecords
305{
306  for (NSString *recordId in _appRegistry.appEnumerator) {
307    EXKernelAppRecord *record = [_appRegistry recordForId:recordId];
308    if (record && record != _visibleApp) {
309      [_appRegistry unregisterAppWithRecordId:recordId];
310      break;
311    }
312  }
313}
314
315- (void)_handleAppStateDidChange:(NSNotification *)notification
316{
317  NSString *newState;
318
319  if ([notification.name isEqualToString:UIApplicationWillResignActiveNotification]) {
320    newState = @"inactive";
321  } else if ([notification.name isEqualToString:UIApplicationWillEnterForegroundNotification]) {
322    newState = @"background";
323  } else {
324    switch (RCTSharedApplication().applicationState) {
325      case UIApplicationStateActive:
326        newState = @"active";
327        break;
328      case UIApplicationStateBackground: {
329        newState = @"background";
330        break;
331      }
332      default: {
333        newState = @"unknown";
334        break;
335      }
336    }
337  }
338
339  if (_visibleApp) {
340    EXReactAppManager *appManager = _visibleApp.appManager;
341    id<EXAppStateProtocol> appStateModule = [self nativeModuleForAppManager:appManager named:@"AppState"];
342    NSString *lastKnownState;
343    if (appStateModule != nil) {
344      lastKnownState = [appStateModule lastKnownState];
345      [appStateModule setState:newState];
346    }
347    if (!lastKnownState || ![newState isEqualToString:lastKnownState]) {
348      if ([newState isEqualToString:@"active"]) {
349        [_visibleApp.viewController appStateDidBecomeActive];
350        [self _postNotificationName:kEXKernelBridgeDidForegroundNotification onAbstractBridge:appManager.reactBridge];
351      } else if ([newState isEqualToString:@"background"]) {
352        [_visibleApp.viewController appStateDidBecomeInactive];
353        [self _postNotificationName:kEXKernelBridgeDidBackgroundNotification onAbstractBridge:appManager.reactBridge];
354      }
355    }
356  }
357}
358
359- (void)_moveAppToVisible:(EXKernelAppRecord *)appRecord
360{
361  if (_browserController) {
362    [EXUtil performSynchronouslyOnMainThread:^{
363      [self->_browserController moveAppToVisible:appRecord];
364    }];
365  }
366}
367
368@end
369
370NS_ASSUME_NONNULL_END
371