xref: /expo/ios/Exponent/Kernel/Core/EXKernel.m (revision e7ac6e4f)
10fbf6a33SBen Roth// Copyright 2015-present 650 Industries. All rights reserved.
20fbf6a33SBen Roth
30fbf6a33SBen Roth#import "EXAnalytics.h"
40fbf6a33SBen Roth#import "EXAppState.h"
50187d3b3SBen Roth#import "EXAppViewController.h"
6e791dcdeSBen Roth#import "EXBuildConstants.h"
70fbf6a33SBen Roth#import "EXFrame.h"
80fbf6a33SBen Roth#import "EXKernel.h"
9928bc3baSBen Roth#import "EXKernelAppLoader.h"
1089c6c39cSEric Samelson#import "EXKernelAppRecord.h"
11b05926a2SBen Roth#import "EXKernelLinkingManager.h"
120fbf6a33SBen Roth#import "EXLinkingManager.h"
130fbf6a33SBen Roth#import "EXVersions.h"
140fbf6a33SBen Roth
150fbf6a33SBen Roth#import <React/RCTBridge+Private.h>
160fbf6a33SBen Roth#import <React/RCTEventDispatcher.h>
170fbf6a33SBen Roth#import <React/RCTModuleData.h>
180fbf6a33SBen Roth#import <React/RCTUtils.h>
190fbf6a33SBen Roth
200fbf6a33SBen RothNS_ASSUME_NONNULL_BEGIN
210fbf6a33SBen Roth
220fbf6a33SBen RothNSString *kEXKernelErrorDomain = @"EXKernelErrorDomain";
230fbf6a33SBen RothNSString *kEXKernelShouldForegroundTaskEvent = @"foregroundTask";
240fbf6a33SBen RothNSString * const kEXDeviceInstallUUIDKey = @"EXDeviceInstallUUIDKey";
250fbf6a33SBen RothNSString * const kEXKernelClearJSCacheUserDefaultsKey = @"EXKernelClearJSCacheUserDefaultsKey";
260fbf6a33SBen Roth
2789c6c39cSEric Samelson@interface EXKernel () <EXKernelAppRegistryDelegate>
280fbf6a33SBen Roth
290fbf6a33SBen Roth@end
300fbf6a33SBen Roth
310fbf6a33SBen Roth@implementation EXKernel
320fbf6a33SBen Roth
330fbf6a33SBen Roth+ (instancetype)sharedInstance
340fbf6a33SBen Roth{
350fbf6a33SBen Roth  static EXKernel *theKernel;
360fbf6a33SBen Roth  static dispatch_once_t once;
370fbf6a33SBen Roth  dispatch_once(&once, ^{
380fbf6a33SBen Roth    if (!theKernel) {
390fbf6a33SBen Roth      theKernel = [[EXKernel alloc] init];
400fbf6a33SBen Roth    }
410fbf6a33SBen Roth  });
420fbf6a33SBen Roth  return theKernel;
430fbf6a33SBen Roth}
440fbf6a33SBen Roth
450fbf6a33SBen Roth- (instancetype)init
460fbf6a33SBen Roth{
470fbf6a33SBen Roth  if (self = [super init]) {
4889c6c39cSEric Samelson    // init app registry: keep track of RN bridges we are running
4989c6c39cSEric Samelson    _appRegistry = [[EXKernelAppRegistry alloc] init];
5089c6c39cSEric Samelson    _appRegistry.delegate = self;
519f8d9b9dSBen Roth
529f8d9b9dSBen Roth    // init service registry: classes which manage shared resources among all bridges
53d7f51e5eSBen Roth    _serviceRegistry = [[EXKernelServiceRegistry alloc] init];
549f8d9b9dSBen Roth
550fbf6a33SBen Roth    for (NSString *name in @[UIApplicationDidBecomeActiveNotification,
560fbf6a33SBen Roth                             UIApplicationDidEnterBackgroundNotification,
570fbf6a33SBen Roth                             UIApplicationDidFinishLaunchingNotification,
580fbf6a33SBen Roth                             UIApplicationWillResignActiveNotification,
590fbf6a33SBen Roth                             UIApplicationWillEnterForegroundNotification]) {
600fbf6a33SBen Roth
610fbf6a33SBen Roth      [[NSNotificationCenter defaultCenter] addObserver:self
620fbf6a33SBen Roth                                               selector:@selector(_handleAppStateDidChange:)
630fbf6a33SBen Roth                                                   name:name
640fbf6a33SBen Roth                                                 object:nil];
650fbf6a33SBen Roth    }
662c229102SBen Roth    NSLog(@"Expo iOS Runtime Version %@", [EXBuildConstants sharedInstance].expoRuntimeVersion);
670fbf6a33SBen Roth  }
680fbf6a33SBen Roth  return self;
690fbf6a33SBen Roth}
700fbf6a33SBen Roth
710fbf6a33SBen Roth- (void)dealloc
720fbf6a33SBen Roth{
730fbf6a33SBen Roth  [[NSNotificationCenter defaultCenter] removeObserver:self];
740fbf6a33SBen Roth}
750fbf6a33SBen Roth
765daa5350SBen Roth#pragma mark - Misc
775daa5350SBen Roth
780fbf6a33SBen Roth+ (NSString *)deviceInstallUUID
790fbf6a33SBen Roth{
800fbf6a33SBen Roth  NSString *uuid = [[NSUserDefaults standardUserDefaults] stringForKey:kEXDeviceInstallUUIDKey];
810fbf6a33SBen Roth  if (!uuid) {
820fbf6a33SBen Roth    uuid = [[NSUUID UUID] UUIDString];
830fbf6a33SBen Roth    [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:kEXDeviceInstallUUIDKey];
840fbf6a33SBen Roth    [[NSUserDefaults standardUserDefaults] synchronize];
850fbf6a33SBen Roth  }
860fbf6a33SBen Roth  return uuid;
870fbf6a33SBen Roth}
880fbf6a33SBen Roth
899f8d9b9dSBen Roth#pragma mark - bridge registry delegate
909f8d9b9dSBen Roth
9189c6c39cSEric Samelson- (void)appRegistry:(EXKernelAppRegistry *)registry didRegisterAppRecord:(EXKernelAppRecord *)appRecord
929f8d9b9dSBen Roth{
939f8d9b9dSBen Roth  // forward to service registry
9489c6c39cSEric Samelson  [_serviceRegistry appRegistry:registry didRegisterAppRecord:appRecord];
959f8d9b9dSBen Roth}
969f8d9b9dSBen Roth
9789c6c39cSEric Samelson- (void)appRegistry:(EXKernelAppRegistry *)registry willUnregisterAppRecord:(EXKernelAppRecord *)appRecord
989f8d9b9dSBen Roth{
999f8d9b9dSBen Roth  // forward to service registry
10089c6c39cSEric Samelson  [_serviceRegistry appRegistry:registry willUnregisterAppRecord:appRecord];
1019f8d9b9dSBen Roth}
1029f8d9b9dSBen Roth
103f5e2fbc5SBen Roth#pragma mark - Interfacing with JS
104f5e2fbc5SBen Roth
105f5e2fbc5SBen Roth- (void)sendUrl:(NSString *)urlString toAppRecord:(EXKernelAppRecord *)app
106f5e2fbc5SBen Roth{
107f5e2fbc5SBen Roth  // fire a Linking url event on this (possibly versioned) bridge
108f5e2fbc5SBen Roth  EXReactAppManager *appManager = app.appManager;
109f5e2fbc5SBen Roth  id linkingModule = [self nativeModuleForAppManager:appManager named:@"LinkingManager"];
110f5e2fbc5SBen Roth  if (!linkingModule) {
111f5e2fbc5SBen Roth    DDLogError(@"Could not find the Linking module to open URL (%@)", urlString);
112f5e2fbc5SBen Roth  } else if ([linkingModule respondsToSelector:@selector(dispatchOpenUrlEvent:)]) {
113f5e2fbc5SBen Roth    [linkingModule dispatchOpenUrlEvent:[NSURL URLWithString:urlString]];
114f5e2fbc5SBen Roth  } else {
115f5e2fbc5SBen Roth    DDLogError(@"Linking module doesn't support the API we use to open URL (%@)", urlString);
116f5e2fbc5SBen Roth  }
117*e7ac6e4fSBen Roth  [self _moveAppToVisible:app];
118f5e2fbc5SBen Roth}
1190fbf6a33SBen Roth
1205daa5350SBen Roth- (id)nativeModuleForAppManager:(EXReactAppManager *)appManager named:(NSString *)moduleName
1210fbf6a33SBen Roth{
1220fbf6a33SBen Roth  id destinationBridge = appManager.reactBridge;
1230fbf6a33SBen Roth
1240fbf6a33SBen Roth  if ([destinationBridge respondsToSelector:@selector(batchedBridge)]) {
1250fbf6a33SBen Roth    id batchedBridge = [destinationBridge batchedBridge];
1260fbf6a33SBen Roth    id moduleData = [batchedBridge moduleDataForName:moduleName];
1270fbf6a33SBen Roth
1280fbf6a33SBen Roth    // React Native before SDK 11 didn't strip the "RCT" prefix from module names
1290fbf6a33SBen Roth    if (!moduleData && ![moduleName hasPrefix:@"RCT"]) {
1300fbf6a33SBen Roth      moduleData = [batchedBridge moduleDataForName:[@"RCT" stringByAppendingString:moduleName]];
1310fbf6a33SBen Roth    }
1320fbf6a33SBen Roth
1330fbf6a33SBen Roth    if (moduleData) {
1340fbf6a33SBen Roth      return [moduleData instance];
1350fbf6a33SBen Roth    }
1360fbf6a33SBen Roth  } else {
137d2210950SBen Roth    // bridge can be null if the record is in an error state and never created a bridge.
138d2210950SBen Roth    if (destinationBridge) {
1390fbf6a33SBen Roth      DDLogError(@"Bridge does not support the API we use to get its underlying batched bridge");
1400fbf6a33SBen Roth    }
141d2210950SBen Roth  }
1420fbf6a33SBen Roth  return nil;
1430fbf6a33SBen Roth}
1440fbf6a33SBen Roth
145c67a7dcdSBen Roth- (void)sendNotification:(NSDictionary *)notifBody
146c67a7dcdSBen Roth      toExperienceWithId:(NSString *)destinationExperienceId
147c67a7dcdSBen Roth          fromBackground:(BOOL)isFromBackground
148c67a7dcdSBen Roth                isRemote:(BOOL)isRemote
149c67a7dcdSBen Roth{
150c67a7dcdSBen Roth  EXKernelAppRecord *destinationApp = [_appRegistry newestRecordWithExperienceId:destinationExperienceId];
151c67a7dcdSBen Roth
152c67a7dcdSBen Roth  // if the notification came from the background, in most but not all cases, this means the user acted on an iOS notification
153c67a7dcdSBen Roth  // and caused the app to launch.
154c67a7dcdSBen Roth  // From SO:
155c67a7dcdSBen Roth  // > Note that "App opened from Notification" will be a false positive if the notification is sent while the user is on a different
156c67a7dcdSBen Roth  // > screen (for example, if they pull down the status bar and then receive a notification from your app).
157c67a7dcdSBen Roth  NSDictionary *bodyWithOrigin = @{
158c67a7dcdSBen Roth                                   @"origin": (isFromBackground) ? @"selected" : @"received",
159c67a7dcdSBen Roth                                   @"remote": @(isRemote),
160c67a7dcdSBen Roth                                   @"data": notifBody,
161c67a7dcdSBen Roth                                   };
162c67a7dcdSBen Roth  if (destinationApp) {
163c67a7dcdSBen Roth    // send the body to the already-open experience
164c67a7dcdSBen Roth    [self _dispatchJSEvent:@"Exponent.notification" body:bodyWithOrigin toApp:destinationApp];
165*e7ac6e4fSBen Roth    [self _moveAppToVisible:destinationApp];
166c67a7dcdSBen Roth  } else {
167c67a7dcdSBen Roth    // no app is currently running for this experience id.
168c67a7dcdSBen Roth    // if we're Expo Client, we can query Home for a past experience in the user's history, and route the notification there.
169c67a7dcdSBen Roth    if (_browserController) {
170c67a7dcdSBen Roth      __weak typeof(self) weakSelf = self;
171c67a7dcdSBen Roth      [_browserController getHistoryUrlForExperienceId:destinationExperienceId completion:^(NSString *urlString) {
172c67a7dcdSBen Roth        if (urlString) {
173c67a7dcdSBen Roth          NSURL *url = [NSURL URLWithString:urlString];
174c67a7dcdSBen Roth          if (url) {
175c67a7dcdSBen Roth            [weakSelf createNewAppWithUrl:url initialProps:@{ @"notification": bodyWithOrigin }];
176c67a7dcdSBen Roth          }
177c67a7dcdSBen Roth        }
178c67a7dcdSBen Roth      }];
179c67a7dcdSBen Roth    }
180c67a7dcdSBen Roth  }
181c67a7dcdSBen Roth}
182c67a7dcdSBen Roth
1830fbf6a33SBen Roth/**
1840fbf6a33SBen Roth *  If the bridge has a batchedBridge or parentBridge selector, posts the notification on that object as well.
1850fbf6a33SBen Roth */
1860fbf6a33SBen Roth- (void)_postNotificationName: (NSNotificationName)name onAbstractBridge: (id)bridge
1870fbf6a33SBen Roth{
1880fbf6a33SBen Roth  [[NSNotificationCenter defaultCenter] postNotificationName:name object:bridge];
1890fbf6a33SBen Roth  if ([bridge respondsToSelector:@selector(batchedBridge)]) {
1900fbf6a33SBen Roth    [[NSNotificationCenter defaultCenter] postNotificationName:name object:[bridge batchedBridge]];
1910fbf6a33SBen Roth  } else if ([bridge respondsToSelector:@selector(parentBridge)]) {
1920fbf6a33SBen Roth    [[NSNotificationCenter defaultCenter] postNotificationName:name object:[bridge parentBridge]];
1930fbf6a33SBen Roth  }
1940fbf6a33SBen Roth}
1950fbf6a33SBen Roth
196c67a7dcdSBen Roth- (void)_dispatchJSEvent:(NSString *)eventName body:(NSDictionary *)eventBody toApp:(EXKernelAppRecord *)appRecord
197f148175aSBen Roth{
198c67a7dcdSBen Roth  [appRecord.appManager.reactBridge enqueueJSCall:@"RCTDeviceEventEmitter.emit"
199c67a7dcdSBen Roth                                             args:eventBody ? @[eventName, eventBody] : @[eventName]];
2000fbf6a33SBen Roth}
2010fbf6a33SBen Roth
2028a7f6184SBen Roth#pragma mark - App State
2038e3c2ccdSBen Roth
20489fd6b24SBen Roth- (EXKernelAppRecord *)createNewAppWithUrl:(NSURL *)url initialProps:(nullable NSDictionary *)initialProps
205f5e2fbc5SBen Roth{
206c67a7dcdSBen Roth  NSString *recordId = [_appRegistry registerAppWithManifestUrl:url initialProps:initialProps];
207f5e2fbc5SBen Roth  EXKernelAppRecord *record = [_appRegistry recordForId:recordId];
208*e7ac6e4fSBen Roth  [self _moveAppToVisible:record];
20989fd6b24SBen Roth  return record;
210f5e2fbc5SBen Roth}
211f5e2fbc5SBen Roth
2127f6367d0SBen Roth- (void)switchTasks
2130fbf6a33SBen Roth{
2147f6367d0SBen Roth  if (!_browserController) {
2157f6367d0SBen Roth    return;
2166f62abf2SBen Roth  }
2176f62abf2SBen Roth
2187f6367d0SBen Roth  if (_visibleApp != _appRegistry.homeAppRecord) {
2197f6367d0SBen Roth    [EXUtil performSynchronouslyOnMainThread:^{
2207f6367d0SBen Roth      [_browserController toggleMenu];
2217f6367d0SBen Roth    }];
222b05926a2SBen Roth  } else {
2237f6367d0SBen Roth    EXKernelAppRegistry *appRegistry = [EXKernel sharedInstance].appRegistry;
2247f6367d0SBen Roth    for (NSString *recordId in appRegistry.appEnumerator) {
2257f6367d0SBen Roth      EXKernelAppRecord *record = [appRegistry recordForId:recordId];
2267f6367d0SBen Roth      // foreground the first thing we find
227*e7ac6e4fSBen Roth      [self _moveAppToVisible:record];
2287f6367d0SBen Roth    }
2297f6367d0SBen Roth  }
2307f6367d0SBen Roth}
2317f6367d0SBen Roth
232928bc3baSBen Roth- (void)reloadAppWithExperienceId:(NSString *)experienceId
233928bc3baSBen Roth{
234928bc3baSBen Roth  EXKernelAppRecord *appRecord = [_appRegistry newestRecordWithExperienceId:experienceId];
235928bc3baSBen Roth  if (_browserController) {
236928bc3baSBen Roth    [self createNewAppWithUrl:appRecord.appLoader.manifestUrl initialProps:nil];
237928bc3baSBen Roth  } else if (_appRegistry.standaloneAppRecord && appRecord == _appRegistry.standaloneAppRecord) {
238928bc3baSBen Roth    [appRecord.viewController refresh];
239928bc3baSBen Roth  }
240928bc3baSBen Roth}
241928bc3baSBen Roth
242*e7ac6e4fSBen Roth- (void)viewController:(__unused EXViewController *)vc didNavigateAppToVisible:(EXKernelAppRecord *)appRecord
2437f6367d0SBen Roth{
2447f6367d0SBen Roth  EXKernelAppRecord *appRecordPreviouslyVisible = _visibleApp;
2457f6367d0SBen Roth  if (appRecord != appRecordPreviouslyVisible) {
2467f6367d0SBen Roth    if (appRecordPreviouslyVisible) {
247*e7ac6e4fSBen Roth      [appRecordPreviouslyVisible.viewController appStateDidBecomeInactive];
2487f6367d0SBen Roth      [self _postNotificationName:kEXKernelBridgeDidBackgroundNotification onAbstractBridge:appRecordPreviouslyVisible.appManager.reactBridge];
2497f6367d0SBen Roth      id appStateModule = [self nativeModuleForAppManager:appRecordPreviouslyVisible.appManager named:@"AppState"];
2500fbf6a33SBen Roth      if ([appStateModule respondsToSelector:@selector(setState:)]) {
2510fbf6a33SBen Roth        [appStateModule setState:@"background"];
2520fbf6a33SBen Roth      }
2530fbf6a33SBen Roth    }
2547f6367d0SBen Roth    if (appRecord) {
255*e7ac6e4fSBen Roth      [appRecord.viewController appStateDidBecomeActive];
2567f6367d0SBen Roth      [self _postNotificationName:kEXKernelBridgeDidForegroundNotification onAbstractBridge:appRecord.appManager.reactBridge];
2577f6367d0SBen Roth      id appStateModule = [self nativeModuleForAppManager:appRecord.appManager named:@"AppState"];
2580fbf6a33SBen Roth      if ([appStateModule respondsToSelector:@selector(setState:)]) {
2590fbf6a33SBen Roth        [appStateModule setState:@"active"];
2600fbf6a33SBen Roth      }
2617f6367d0SBen Roth      _visibleApp = appRecord;
2627f6367d0SBen Roth      [[EXAnalytics sharedInstance] logKernelAppVisibleEvent];
2630fbf6a33SBen Roth    } else {
2647f6367d0SBen Roth      _visibleApp = nil;
2657f6367d0SBen Roth    }
2667f6367d0SBen Roth
2677f6367d0SBen Roth    if (_visibleApp && _visibleApp != _appRegistry.homeAppRecord) {
2687f6367d0SBen Roth      [self _unregisterUnusedAppRecords];
2697f6367d0SBen Roth    }
2707f6367d0SBen Roth  }
2717f6367d0SBen Roth}
2727f6367d0SBen Roth
2737f6367d0SBen Roth- (void)_unregisterUnusedAppRecords
2747f6367d0SBen Roth{
2757f6367d0SBen Roth  for (NSString *recordId in _appRegistry.appEnumerator) {
2767f6367d0SBen Roth    EXKernelAppRecord *record = [_appRegistry recordForId:recordId];
2777f6367d0SBen Roth    if (record && record != _visibleApp) {
2787f6367d0SBen Roth      [_appRegistry unregisterAppWithRecordId:recordId];
2797f6367d0SBen Roth      break;
2800fbf6a33SBen Roth    }
2810fbf6a33SBen Roth  }
282b05926a2SBen Roth}
2830fbf6a33SBen Roth
2840fbf6a33SBen Roth- (void)_handleAppStateDidChange:(NSNotification *)notification
2850fbf6a33SBen Roth{
2860fbf6a33SBen Roth  NSString *newState;
2870fbf6a33SBen Roth
2880fbf6a33SBen Roth  if ([notification.name isEqualToString:UIApplicationWillResignActiveNotification]) {
2890fbf6a33SBen Roth    newState = @"inactive";
2900fbf6a33SBen Roth  } else if ([notification.name isEqualToString:UIApplicationWillEnterForegroundNotification]) {
2910fbf6a33SBen Roth    newState = @"background";
2920fbf6a33SBen Roth  } else {
2930fbf6a33SBen Roth    switch (RCTSharedApplication().applicationState) {
2940fbf6a33SBen Roth      case UIApplicationStateActive:
2950fbf6a33SBen Roth        newState = @"active";
2960fbf6a33SBen Roth        break;
2970fbf6a33SBen Roth      case UIApplicationStateBackground: {
2980fbf6a33SBen Roth        newState = @"background";
2990fbf6a33SBen Roth        break;
3000fbf6a33SBen Roth      }
3010fbf6a33SBen Roth      default: {
3020fbf6a33SBen Roth        newState = @"unknown";
3030fbf6a33SBen Roth        break;
3040fbf6a33SBen Roth      }
3050fbf6a33SBen Roth    }
3060fbf6a33SBen Roth  }
3070fbf6a33SBen Roth
3087f6367d0SBen Roth  if (_visibleApp) {
3097f6367d0SBen Roth    EXReactAppManager *appManager = _visibleApp.appManager;
3105daa5350SBen Roth    id appStateModule = [self nativeModuleForAppManager:appManager named:@"AppState"];
3110fbf6a33SBen Roth    NSString *lastKnownState;
3120fbf6a33SBen Roth    if ([appStateModule respondsToSelector:@selector(lastKnownState)]) {
3130fbf6a33SBen Roth      lastKnownState = [appStateModule lastKnownState];
3140fbf6a33SBen Roth    }
3150fbf6a33SBen Roth    if ([appStateModule respondsToSelector:@selector(setState:)]) {
3160fbf6a33SBen Roth      [appStateModule setState:newState];
3170fbf6a33SBen Roth    }
3180fbf6a33SBen Roth    if (!lastKnownState || ![newState isEqualToString:lastKnownState]) {
3190fbf6a33SBen Roth      if ([newState isEqualToString:@"active"]) {
320*e7ac6e4fSBen Roth        [_visibleApp.viewController appStateDidBecomeActive];
3217f6367d0SBen Roth        [self _postNotificationName:kEXKernelBridgeDidForegroundNotification onAbstractBridge:appManager.reactBridge];
3220fbf6a33SBen Roth      } else if ([newState isEqualToString:@"background"]) {
323*e7ac6e4fSBen Roth        [_visibleApp.viewController appStateDidBecomeInactive];
3247f6367d0SBen Roth        [self _postNotificationName:kEXKernelBridgeDidBackgroundNotification onAbstractBridge:appManager.reactBridge];
3250fbf6a33SBen Roth      }
3260fbf6a33SBen Roth    }
3270fbf6a33SBen Roth  }
3280fbf6a33SBen Roth}
3290fbf6a33SBen Roth
330*e7ac6e4fSBen Roth- (void)_moveAppToVisible:(EXKernelAppRecord *)appRecord
331*e7ac6e4fSBen Roth{
332*e7ac6e4fSBen Roth  if (_browserController) {
333*e7ac6e4fSBen Roth    [EXUtil performSynchronouslyOnMainThread:^{
334*e7ac6e4fSBen Roth      [_browserController moveAppToVisible:appRecord];
335*e7ac6e4fSBen Roth    }];
336*e7ac6e4fSBen Roth  }
337*e7ac6e4fSBen Roth}
338*e7ac6e4fSBen Roth
3390fbf6a33SBen Roth@end
3400fbf6a33SBen Roth
3410fbf6a33SBen RothNS_ASSUME_NONNULL_END
342