@robono/calling-react-native 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/INCOMING-CALLS.md +68 -0
  3. package/README.md +8 -2
  4. package/RobonoCallingRuntime.podspec +1 -1
  5. package/SBOM.spdx.json +701 -365
  6. package/android/build.gradle +1 -0
  7. package/android/consumer-rules.pro +9 -0
  8. package/android/src/main/AndroidManifest.xml +9 -0
  9. package/android/src/main/java/com/robono/calling/CallingPackage.java +1 -1
  10. package/android/src/main/java/com/robono/calling/CallingRuntime.java +2 -2
  11. package/android/src/main/java/com/robono/calling/SystemCallActionReceiver.java +5 -0
  12. package/android/src/main/java/com/robono/calling/SystemCallActivity.java +25 -0
  13. package/android/src/main/java/com/robono/calling/SystemCallConnectionService.java +17 -0
  14. package/android/src/main/java/com/robono/calling/SystemCallMessagingService.java +19 -0
  15. package/android/src/main/java/com/robono/calling/SystemCallService.java +28 -0
  16. package/android/src/main/java/com/robono/calling/SystemCalling.java +95 -0
  17. package/app.plugin.cjs +11 -0
  18. package/dist/messenger.d.ts +43 -0
  19. package/dist/messenger.js +132 -0
  20. package/dist/native.d.ts +6 -0
  21. package/dist/native.js +35 -3
  22. package/dist/notifications.js +2 -2
  23. package/dist/runtime.d.ts +1 -1
  24. package/dist/runtime.js +2 -2
  25. package/dist/system-calling.d.ts +29 -0
  26. package/dist/system-calling.js +184 -0
  27. package/dist/versions.d.ts +2 -2
  28. package/dist/versions.js +2 -2
  29. package/dist/visual/RobonoIcon.js +2 -1
  30. package/ios/RobonoCallingRuntime.m +2 -1
  31. package/ios/RobonoSystemCalling.h +7 -0
  32. package/ios/RobonoSystemCalling.m +176 -0
  33. package/package.json +11 -2
  34. package/plugin/incoming-calls.cjs +14 -0
@@ -6,3 +6,4 @@ android {
6
6
  defaultConfig { minSdkVersion 24; consumerProguardFiles 'consumer-rules.pro' }
7
7
  }
8
8
  dependencies { implementation 'com.facebook.react:react-android' }
9
+ dependencies { implementation 'com.google.firebase:firebase-messaging:25.0.1' }
@@ -3,3 +3,12 @@
3
3
  public static com.oney.WebRTCModule.WebRTCModuleOptions getInstance();
4
4
  public boolean enableMediaProjectionService;
5
5
  }
6
+
7
+ # Expo 56 can ship notifications as a precompiled module rather than a Gradle
8
+ # project. Preserve the official forwarding delegate used by the call receiver.
9
+ -keep class expo.modules.notifications.service.delegates.FirebaseMessagingDelegate {
10
+ public <init>(android.content.Context);
11
+ public void onMessageReceived(com.google.firebase.messaging.RemoteMessage);
12
+ public void onNewToken(java.lang.String);
13
+ public void onDeletedMessages();
14
+ }
@@ -2,7 +2,16 @@
2
2
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
3
3
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
4
4
  <uses-permission android:name="android.permission.WAKE_LOCK" />
5
+ <uses-permission android:name="android.permission.MANAGE_OWN_CALLS" />
6
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_PHONE_CALL" />
7
+ <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
5
8
  <application>
6
9
  <service android:name="com.robono.calling.CallingService" android:exported="false" android:foregroundServiceType="microphone" android:stopWithTask="true" />
10
+ <service android:name="com.robono.calling.SystemCallConnectionService" android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE" android:exported="true">
11
+ <intent-filter><action android:name="android.telecom.ConnectionService" /></intent-filter>
12
+ </service>
13
+ <service android:name="com.robono.calling.SystemCallService" android:exported="false" android:foregroundServiceType="phoneCall" />
14
+ <receiver android:name="com.robono.calling.SystemCallActionReceiver" android:exported="false" />
15
+ <activity android:name="com.robono.calling.SystemCallActivity" android:exported="false" android:excludeFromRecents="true" android:launchMode="singleTop" android:theme="@android:style/Theme.Material.NoActionBar" />
7
16
  </application>
8
17
  </manifest>
@@ -9,7 +9,7 @@ import java.util.List;
9
9
 
10
10
  public final class CallingPackage implements ReactPackage {
11
11
  public List<NativeModule> createNativeModules(ReactApplicationContext context) {
12
- return Collections.singletonList(new CallingRuntime(context));
12
+ return java.util.Arrays.asList(new CallingRuntime(context),new SystemCalling(context));
13
13
  }
14
14
  public List<ViewManager> createViewManagers(ReactApplicationContext context) { return Collections.emptyList(); }
15
15
  }
@@ -35,7 +35,7 @@ public final class CallingRuntime extends ReactContextBaseJavaModule {
35
35
  @ReactMethod public void begin(String token, String title, String text, String channel, String endLabel, Promise promise) {
36
36
  main.post(() -> {
37
37
  ReactApplicationContext c = getReactApplicationContext();
38
- if (c.getLifecycleState() != LifecycleState.RESUMED || c.getCurrentActivity() == null) {
38
+ if ((c.getLifecycleState() != LifecycleState.RESUMED || c.getCurrentActivity() == null) && !SystemCalling.canCapture()) {
39
39
  promise.reject("open_app_to_start_call", "Open the app to start a call."); return;
40
40
  }
41
41
  if (c.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
@@ -50,7 +50,7 @@ public final class CallingRuntime extends ReactContextBaseJavaModule {
50
50
  @Override protected void onReceiveResult(int code, android.os.Bundle data) {
51
51
  if (settled[0]) { if (code == 0) CallingService.finish(token); return; }
52
52
  settled[0] = true; main.removeCallbacks(timeout);
53
- if (code == 0) promise.resolve(null);
53
+ if (code == 0) { if(SystemCalling.canCapture())c.stopService(new Intent(c,SystemCallService.class)); promise.resolve(null); }
54
54
  else promise.reject("calling_service_unavailable", "Call audio could not start.");
55
55
  }
56
56
  };
@@ -0,0 +1,5 @@
1
+ package com.robono.calling;
2
+ import android.content.*;
3
+ public final class SystemCallActionReceiver extends BroadcastReceiver {
4
+ @Override public void onReceive(Context c,Intent i){PendingResult result=goAsync();SystemCalling.hangup(i.getStringExtra("callId"),result::finish);}
5
+ }
@@ -0,0 +1,25 @@
1
+ package com.robono.calling;
2
+ import android.app.*;
3
+ import android.os.*;
4
+ import android.content.*;
5
+ import android.graphics.Color;
6
+ import android.view.*;
7
+ import android.widget.*;
8
+ /** Native lock-screen admission; the supplied Messenger owns the connected call. */
9
+ public final class SystemCallActivity extends Activity {
10
+ String id;final Handler clock=new Handler(Looper.getMainLooper());
11
+ final Runnable refresh=new Runnable(){public void run(){if(!SystemCalling.calls.containsKey(id)){finish();return;}clock.postDelayed(this,250);}};
12
+ static PendingIntent intent(Context c,String id,boolean answer){Intent i=new Intent(c,SystemCallActivity.class).setData(android.net.Uri.parse("robono-call:"+id+(answer?":answer":":open"))).putExtra("callId",id).putExtra("answer",answer).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);return PendingIntent.getActivity(c,(id+(answer?"answer":"open")).hashCode(),i,PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE);}
13
+ @Override public void onCreate(Bundle saved){super.onCreate(saved);if(Build.VERSION.SDK_INT>=27){setShowWhenLocked(true);setTurnScreenOn(true);}else getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);show(getIntent());}
14
+ @Override public void onNewIntent(Intent i){super.onNewIntent(i);setIntent(i);show(i);}
15
+ void show(Intent i){id=i.getStringExtra("callId");SystemCalling.Call call=SystemCalling.calls.get(id);if(call==null){finish();return;}if(i.getBooleanExtra("answer",false)||!"ringing".equals(call.state)){answer();return;}
16
+ LinearLayout layout=new LinearLayout(this);layout.setOrientation(LinearLayout.VERTICAL);layout.setGravity(Gravity.CENTER);int pad=(int)(32*getResources().getDisplayMetrics().density);layout.setPadding(pad,pad,pad,pad);layout.setBackgroundColor(SystemCalling.color("background","#080808"));
17
+ TextView brand=new TextView(this);brand.setText(getApplicationInfo().loadLabel(getPackageManager()));brand.setTextColor(SystemCalling.color("secondary","#aaaaaa"));brand.setTextSize(18);layout.addView(brand);
18
+ TextView name=new TextView(this);name.setText(call.name);name.setTextColor(SystemCalling.color("foreground","#fafafa"));name.setTextSize(30);name.setGravity(Gravity.CENTER);name.setPadding(0,pad,0,pad);layout.addView(name);
19
+ TextView kind=new TextView(this);kind.setText("video".equals(call.data.get("kind"))?SystemCalling.label("incomingVideo","Incoming video call"):SystemCalling.label("incoming","Incoming call"));kind.setTextColor(SystemCalling.color("secondary","#aaaaaa"));kind.setTextSize(18);layout.addView(kind);
20
+ Button accept=new Button(this);accept.setText(SystemCalling.label("answer","Answer"));accept.setTextColor(Color.WHITE);accept.setBackgroundTintList(android.content.res.ColorStateList.valueOf(SystemCalling.color("answer","#247949")));accept.setOnClickListener(v->answer());LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(-1,pad*2);lp.topMargin=pad;layout.addView(accept,lp);
21
+ Button decline=new Button(this);decline.setText(SystemCalling.label("decline","Decline"));decline.setTextColor(Color.WHITE);decline.setBackgroundTintList(android.content.res.ColorStateList.valueOf(SystemCalling.color("end","#bd2929")));decline.setOnClickListener(v->{SystemCalling.hangup(id);finish();});layout.addView(decline,new LinearLayout.LayoutParams(-1,pad*2));setContentView(layout);clock.removeCallbacks(refresh);clock.post(refresh);
22
+ }
23
+ void answer(){boolean ringing=SystemCalling.calls.containsKey(id)&&"ringing".equals(SystemCalling.calls.get(id).state);SystemCalling.answer(id);Intent launch=getPackageManager().getLaunchIntentForPackage(getPackageName());if(!ringing&&launch!=null){launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TOP);startActivity(launch);}finish();}
24
+ @Override public void onDestroy(){clock.removeCallbacksAndMessages(null);super.onDestroy();}
25
+ }
@@ -0,0 +1,17 @@
1
+ package com.robono.calling;
2
+ import android.telecom.*;
3
+ public final class SystemCallConnectionService extends ConnectionService {
4
+ @Override public Connection onCreateIncomingConnection(PhoneAccountHandle h,ConnectionRequest r){return SystemCalling.create(this,r);}
5
+ @Override public void onCreateIncomingConnectionFailed(PhoneAccountHandle h,ConnectionRequest r){String id=r.getExtras()==null?null:r.getExtras().getString("robonoCallId");SystemCalling.end(id,DisconnectCause.ERROR);}
6
+ }
7
+ final class SystemCallConnection extends Connection {
8
+ private final String id;private boolean muted;
9
+ SystemCallConnection(String id){this.id=id;}
10
+ @Override public void onShowIncomingCallUi(){SystemCalling.show(id);SystemCalling.event("incoming",SystemCalling.calls.get(id));}
11
+ @Override public void onAnswer(){SystemCalling.answer(id);}
12
+ @Override public void onAnswer(int video){onAnswer();}
13
+ @Override public void onReject(){SystemCalling.hangup(id);}
14
+ @Override public void onDisconnect(){SystemCalling.hangup(id);}
15
+ @Override public void onAbort(){onDisconnect();}
16
+ @Override public void onCallAudioStateChanged(CallAudioState state){if(muted!=state.isMuted()){muted=state.isMuted();SystemCalling.event("mute",SystemCalling.calls.get(id),java.util.Collections.singletonMap("muted",muted));}}
17
+ }
@@ -0,0 +1,19 @@
1
+ package com.robono.calling;
2
+ import android.content.Context;
3
+ import com.google.firebase.messaging.FirebaseMessagingService;
4
+ import com.google.firebase.messaging.RemoteMessage;
5
+ /** The Expo config plugin selects this receiver. Delegate all other messages and
6
+ * token/task events to Expo, including its precompiled-module distribution. */
7
+ public final class SystemCallMessagingService extends FirebaseMessagingService {
8
+ private Object delegate;
9
+ private void forward(String method,Class<?> type,Object value){
10
+ try{
11
+ Class<?> c=Class.forName("expo.modules.notifications.service.delegates.FirebaseMessagingDelegate");
12
+ if(delegate==null)delegate=c.getConstructor(Context.class).newInstance(this);
13
+ if(type==null)c.getMethod(method).invoke(delegate);else c.getMethod(method,type).invoke(delegate,value);
14
+ }catch(ReflectiveOperationException error){throw new IllegalStateException("The Robono Expo incoming-call receiver requires expo-notifications. Native hosts should forward calls from their existing Firebase receiver instead.",error);}
15
+ }
16
+ @Override public void onMessageReceived(RemoteMessage message){if(!SystemCalling.receive(this,message.getData()))forward("onMessageReceived",RemoteMessage.class,message);}
17
+ @Override public void onNewToken(String token){forward("onNewToken",String.class,token);}
18
+ @Override public void onDeletedMessages(){forward("onDeletedMessages",null,null);}
19
+ }
@@ -0,0 +1,28 @@
1
+ package com.robono.calling;
2
+ import android.app.*;
3
+ import android.content.*;
4
+ import android.content.pm.ServiceInfo;
5
+ import android.os.*;
6
+ import android.media.AudioAttributes;
7
+ import android.media.RingtoneManager;
8
+
9
+ public final class SystemCallService extends Service {
10
+ static final int NOTIFICATION=0x524253;
11
+ @Override public IBinder onBind(Intent intent){return null;}
12
+ @Override public int onStartCommand(Intent intent,int flags,int startId){
13
+ String id=intent==null?null:intent.getStringExtra("callId");SystemCalling.Call call=SystemCalling.calls.get(id);if(call==null){stopSelf();return START_NOT_STICKY;}
14
+ boolean ringing="ringing".equals(call.state);NotificationManager manager=getSystemService(NotificationManager.class);
15
+ String channel=ringing?"robono-system-incoming":"robono-system-ongoing";
16
+ if(Build.VERSION.SDK_INT>=26){NotificationChannel c=new NotificationChannel(channel,ringing?"Incoming calls":"Ongoing calls",ringing?NotificationManager.IMPORTANCE_HIGH:NotificationManager.IMPORTANCE_LOW);c.setSound(ringing?RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE):null,new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build());c.enableVibration(ringing);manager.createNotificationChannel(c);}
17
+ PendingIntent open=SystemCallActivity.intent(this,id,false),answer=SystemCallActivity.intent(this,id,true);
18
+ PendingIntent end=PendingIntent.getBroadcast(this,id.hashCode(),new Intent(this,SystemCallActionReceiver.class).setData(android.net.Uri.parse("robono-call:"+id)).putExtra("callId",id),PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE);
19
+ Notification.Builder b=Build.VERSION.SDK_INT>=26?new Notification.Builder(this,channel):new Notification.Builder(this);
20
+ b.setSmallIcon(android.R.drawable.stat_sys_phone_call).setContentTitle(call.name).setContentText(ringing?("video".equals(call.data.get("kind"))?SystemCalling.label("incomingVideo","Incoming video call"):SystemCalling.label("incoming","Incoming call")):SystemCalling.label("call","Call in progress")).setOngoing(true).setOnlyAlertOnce(true).setContentIntent(open).setCategory(Notification.CATEGORY_CALL).setVisibility(Notification.VISIBILITY_PRIVATE);
21
+ if(Build.VERSION.SDK_INT>=31){Person person=new Person.Builder().setName(call.name).setImportant(true).build();b.setStyle(ringing?Notification.CallStyle.forIncomingCall(person,end,answer):Notification.CallStyle.forOngoingCall(person,end));}
22
+ else {if(ringing)b.addAction(new Notification.Action.Builder(null,SystemCalling.label("answer","Answer"),answer).build());b.addAction(new Notification.Action.Builder(null,ringing?SystemCalling.label("decline","Decline"):SystemCalling.label("end","End call"),end).build());}
23
+ if(ringing){b.setFullScreenIntent(open,true);if(Build.VERSION.SDK_INT>=26)b.setTimeoutAfter(Math.max(1,call.expires-System.currentTimeMillis()));}
24
+ try{if(Build.VERSION.SDK_INT>=29)startForeground(NOTIFICATION,b.build(),ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL);else startForeground(NOTIFICATION,b.build());}catch(Exception e){SystemCalling.end(id,android.telecom.DisconnectCause.ERROR);stopSelf();}
25
+ return START_NOT_STICKY;
26
+ }
27
+ @Override public void onDestroy(){stopForeground(true);super.onDestroy();}
28
+ }
@@ -0,0 +1,95 @@
1
+ package com.robono.calling;
2
+
3
+ import android.Manifest;
4
+ import android.app.*;
5
+ import android.content.*;
6
+ import android.content.pm.PackageManager;
7
+ import android.net.Uri;
8
+ import android.os.*;
9
+ import android.telecom.*;
10
+ import com.facebook.react.bridge.*;
11
+ import com.facebook.react.modules.core.DeviceEventManagerModule;
12
+ import org.json.*;
13
+ import java.util.*;
14
+
15
+ /** Call metadata only. Customer credentials and media never enter a push payload. */
16
+ public final class SystemCalling extends ReactContextBaseJavaModule {
17
+ static final Handler MAIN=new Handler(Looper.getMainLooper());
18
+ static final Map<String,Call> calls=new LinkedHashMap<>();
19
+ static final Map<String,Long> ended=new LinkedHashMap<>();
20
+ static final List<Map<String,Object>> events=new ArrayList<>();
21
+ static ReactApplicationContext react;
22
+ static Context app;
23
+ static class Call {final String id;final Map<String,String> data;final long expires;String name,state="ringing";boolean authorized;SystemCallConnection connection;Call(String id,Map<String,String> data,long expires,String name){this.id=id;this.data=data;this.expires=expires;this.name=name;}}
24
+ public SystemCalling(ReactApplicationContext context){super(context);react=context;app=context.getApplicationContext();}
25
+ public String getName(){return "RobonoSystemCalling";}
26
+ static android.content.SharedPreferences prefs(Context c){return c.getSharedPreferences("robono.sdk.calls.v1",Context.MODE_PRIVATE);}
27
+ static String account(Context c){return prefs(c).getString("account",null);}
28
+ static String label(String key,String fallback){try{String text=new JSONObject(prefs(app).getString("appearance","{}")).optJSONObject("labels").optString(key,fallback);return text.length()>0&&text.length()<=200?text:fallback;}catch(Exception e){return fallback;}}
29
+ static int color(String key,String fallback){try{String text=new JSONObject(prefs(app).getString("appearance","{}")).optJSONObject("theme").optString(key,fallback);return android.graphics.Color.parseColor(text);}catch(Exception e){return android.graphics.Color.parseColor(fallback);}}
30
+ static boolean enabled(Context c){try{return c.getPackageManager().getApplicationInfo(c.getPackageName(),PackageManager.GET_META_DATA).metaData.getBoolean("com.robono.calling.SYSTEM_CALLING",false);}catch(Exception e){return false;}}
31
+ static PhoneAccountHandle handle(Context c){return new PhoneAccountHandle(new ComponentName(c,SystemCallConnectionService.class),"robono-sdk-calls");}
32
+ static void register(Context c){String name=c.getApplicationInfo().loadLabel(c.getPackageManager()).toString();c.getSystemService(TelecomManager.class).registerPhoneAccount(PhoneAccount.builder(handle(c),name).setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED).build());}
33
+ static void changed(){if(react!=null&&react.hasActiveReactInstance())react.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("RobonoSystemCallingEvent",Arguments.createMap());}
34
+ static void event(String kind,Call call){event(kind,call,Collections.emptyMap());}
35
+ static void event(String kind,Call call,Map<String,Object> extra){if(call==null)return;Map<String,Object> row=new HashMap<>(call.data);row.put("type",kind);row.put("eventId",UUID.randomUUID().toString());row.putAll(extra);events.add(row);while(events.size()>64)events.remove(0);changed();}
36
+ public static boolean receive(Context context,Map<String,String> data){
37
+ String event=data.get("event");if(event==null||!Arrays.asList("calling.incoming","calling.group_incoming","calling.dismissed","calling.group_dismissed").contains(event))return false;
38
+ // Existing custom clients without a system-call account retain their Expo router.
39
+ if(!enabled(context)||account(context)==null)return false;
40
+ MAIN.post(()->{
41
+ app=context.getApplicationContext();if(account(app)==null||!account(app).equals(data.get("accountScope")))return;
42
+ String id=data.get("call_id");try{UUID.fromString(id);}catch(Exception e){return;}
43
+ if(event.endsWith("dismissed")){Call call=calls.get(id);event("dismissed",call);if(!"answered".equals(data.get("reason"))||call==null||!call.authorized)end(id,DisconnectCause.REMOTE);return;}
44
+ long expiry;try{java.text.SimpleDateFormat format=new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX",Locale.US);format.setLenient(false);expiry=format.parse(data.get("ring_expires_at")).getTime();}catch(Exception e){return;}
45
+ if(expiry<=System.currentTimeMillis()||expiry>System.currentTimeMillis()+120000||ended.containsKey(id))return;
46
+ if(calls.containsKey(id)){if(data.get("decline_grant")!=null)calls.get(id).data.put("decline_grant",data.get("decline_grant"));return;}
47
+ if(!calls.isEmpty())return;
48
+ String name="Incoming call";try{name=new JSONObject(prefs(app).getString("names","{}")).optString(data.containsKey("conversation_id")?data.get("conversation_id"):data.get("connection_id"),name);}catch(Exception ignored){}
49
+ Call call=new Call(id,new HashMap<>(data),expiry,name);calls.put(id,call);
50
+ try{register(app);Bundle extras=new Bundle();extras.putString("robonoCallId",id);app.getSystemService(TelecomManager.class).addNewIncomingCall(handle(app),extras);
51
+ MAIN.postDelayed(()->{if(calls.get(id)==call&&"ringing".equals(call.state))end(id,DisconnectCause.MISSED);},expiry-System.currentTimeMillis());
52
+ }catch(Exception e){end(id,DisconnectCause.ERROR);}
53
+ });return true;
54
+ }
55
+ static void answer(String id){Call call=calls.get(id);if(call==null||!"ringing".equals(call.state))return;call.state="answering";event("answer",call);show(id);
56
+ Intent launch=app.getPackageManager().getLaunchIntentForPackage(app.getPackageName());if(launch!=null){launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TOP);try{app.startActivity(launch);}catch(RuntimeException ignored){}}
57
+ MAIN.postDelayed(()->{if(calls.get(id)==call&&"answering".equals(call.state)){event("end",call);end(id,DisconnectCause.ERROR);}},25000);
58
+ }
59
+ static void hangup(String id){hangup(id,()->{});}
60
+ static void hangup(String id,Runnable done){Call call=calls.get(id);if(call==null){done.run();return;}event("end",call);decline(call,done);end(id,DisconnectCause.LOCAL);}
61
+ static void decline(Call call,Runnable done){
62
+ String grant=call.data.get("decline_grant");if(grant==null||grant.length()>2048||"connected".equals(call.state)){done.run();return;}
63
+ new Thread(()->{java.net.HttpURLConnection connection=null;try{
64
+ connection=(java.net.HttpURLConnection)new java.net.URL("https://api.robono.com/v1/calling").openConnection();connection.setInstanceFollowRedirects(false);connection.setConnectTimeout(4000);connection.setReadTimeout(4000);connection.setRequestMethod("POST");connection.setRequestProperty("Content-Type","application/json");connection.setDoOutput(true);
65
+ byte[] body=new JSONObject().put("operation","decline-invitation").put("grant",grant).toString().getBytes(java.nio.charset.StandardCharsets.UTF_8);connection.setFixedLengthStreamingMode(body.length);try(java.io.OutputStream out=connection.getOutputStream()){out.write(body);}connection.getResponseCode();
66
+ }catch(Exception ignored){}finally{if(connection!=null)connection.disconnect();MAIN.post(done);}},"robono-decline-call").start();
67
+ }
68
+ static void end(String id,int reason){if(id==null)return;Call call=calls.remove(id);ended.put(id,System.currentTimeMillis());while(ended.size()>128)ended.remove(ended.keySet().iterator().next());if(call==null)return;
69
+ if(call.connection!=null){call.connection.setDisconnected(new DisconnectCause(reason));call.connection.destroy();}
70
+ if(app!=null&&calls.isEmpty()){app.stopService(new Intent(app,SystemCallService.class));app.getSystemService(NotificationManager.class).cancel(SystemCallService.NOTIFICATION);}
71
+ changed();
72
+ }
73
+ static boolean canCapture(){for(Call call:calls.values())if(call.authorized&&!"ringing".equals(call.state))return true;return false;}
74
+ static void show(String id){if(app==null||!calls.containsKey(id))return;try{Intent i=new Intent(app,SystemCallService.class).putExtra("callId",id);if(Build.VERSION.SDK_INT>=26)app.startForegroundService(i);else app.startService(i);}catch(Exception e){end(id,DisconnectCause.ERROR);}}
75
+ static Connection create(Context c,ConnectionRequest request){String id=request.getExtras()==null?null:request.getExtras().getString("robonoCallId");Call call=calls.get(id);
76
+ if(call==null||account(c)==null||!account(c).equals(call.data.get("accountScope")))return Connection.createFailedConnection(new DisconnectCause(DisconnectCause.ERROR));
77
+ SystemCallConnection connection=new SystemCallConnection(id);call.connection=connection;connection.setConnectionProperties(Connection.PROPERTY_SELF_MANAGED);connection.setConnectionCapabilities(Connection.CAPABILITY_MUTE);connection.setAudioModeIsVoip(true);connection.setCallerDisplayName(call.name,TelecomManager.PRESENTATION_ALLOWED);connection.setAddress(Uri.fromParts("robono",id,null),TelecomManager.PRESENTATION_ALLOWED);connection.setRinging();return connection;
78
+ }
79
+ static WritableMap state(Context c){WritableMap result=Arguments.createMap();result.putBoolean("enabled",enabled(c));result.putString("accountScope",account(c));List<Map<String,Object>> rows=new ArrayList<>();for(Call call:calls.values()){Map<String,Object> row=new HashMap<>();row.put("id",call.id);row.put("data",call.data);row.put("state",call.state);rows.add(row);}result.putArray("calls",Arguments.makeNativeArray(rows));return result;}
80
+ @ReactMethod public void configure(String scope,Promise promise){MAIN.post(()->{try{if(scope!=null&&!scope.matches("[a-f0-9]{64}"))throw new IllegalArgumentException("invalid_account");if(!Objects.equals(account(app),scope)){for(String id:new ArrayList<>(calls.keySet()))end(id,DisconnectCause.CANCELED);events.clear();prefs(app).edit().remove("names").remove("appearance").apply();}prefs(app).edit().putString("account",scope).apply();if(scope!=null&&enabled(app))register(app);promise.resolve(state(app));}catch(Exception e){promise.reject("system_calling_unavailable",e);}});}
81
+ @ReactMethod public void cacheContacts(String scope,ReadableMap names){MAIN.post(()->{if(Objects.equals(account(app),scope))prefs(app).edit().putString("names",new JSONObject(names.toHashMap()).toString()).apply();});}
82
+ @ReactMethod public void cacheAppearance(String scope,ReadableMap value){MAIN.post(()->{if(Objects.equals(account(app),scope))prefs(app).edit().putString("appearance",new JSONObject(value.toHashMap()).toString()).apply();});}
83
+ @ReactMethod public void state(Promise promise){MAIN.post(()->promise.resolve(state(app)));}
84
+ @ReactMethod public void clear(String scope,Promise promise){MAIN.post(()->{if(Objects.equals(account(app),scope)){for(String id:new ArrayList<>(calls.keySet()))end(id,DisconnectCause.CANCELED);events.clear();prefs(app).edit().remove("account").remove("names").remove("appearance").apply();}promise.resolve(null);});}
85
+ @ReactMethod public void drain(Promise promise){MAIN.post(()->{List<Map<String,Object>> rows=new ArrayList<>(events);events.clear();promise.resolve(Arguments.makeNativeArray(rows));});}
86
+ @ReactMethod public void receive(ReadableMap data){Map<String,String> values=new HashMap<>();for(Map.Entry<String,Object> e:data.toHashMap().entrySet())if(e.getValue() instanceof String)values.put(e.getKey(),(String)e.getValue());receive(app,values);}
87
+ @ReactMethod public void prepare(String id,Promise promise){MAIN.post(()->{Call call=calls.get(id);if(call==null){promise.reject("call_cancelled","The incoming call has ended.");return;}if(app.checkSelfPermission(Manifest.permission.RECORD_AUDIO)!=PackageManager.PERMISSION_GRANTED){promise.reject("microphone_permission_denied","Open the app and allow microphone access.");return;}call.authorized=true;if("ringing".equals(call.state))answer(id);promise.resolve(null);});}
88
+ @ReactMethod public void connected(String id){MAIN.post(()->{Call call=calls.get(id);if(call!=null){call.state="connected";if(call.connection!=null)call.connection.setActive();}});}
89
+ @ReactMethod public void end(String id){MAIN.post(()->end(id,DisconnectCause.REMOTE));}
90
+ @ReactMethod public void canCapture(Promise promise){MAIN.post(()->promise.resolve(canCapture()));}
91
+ @ReactMethod public void speaker(boolean speaker){MAIN.post(()->{for(Call call:calls.values())if(call.connection!=null)call.connection.setAudioRoute(speaker?CallAudioState.ROUTE_SPEAKER:CallAudioState.ROUTE_WIRED_OR_EARPIECE);});}
92
+ @ReactMethod public void addListener(String name){}
93
+ @ReactMethod public void removeListeners(double count){}
94
+ @Override public void invalidate(){if(react==getReactApplicationContext())react=null;super.invalidate();}
95
+ }
package/app.plugin.cjs CHANGED
@@ -1,13 +1,24 @@
1
1
  const {withInfoPlist, withAndroidManifest, createRunOncePlugin} = require('expo/config-plugins');
2
2
  function withCallingRuntime(config, options = {}) {
3
+ if(options.incomingCalls!==false)config=require('./plugin/incoming-calls.cjs').withIncomingCalls(config);
3
4
  if(options.screenSharing)config=require('./plugin/screensharing.cjs').withScreenSharing(config,typeof options.screenSharing==='object'?options.screenSharing:{});
4
5
  config = withInfoPlist(config, value => {
5
6
  if (options.video) value.modResults.NSCameraUsageDescription ||= options.cameraPermission || 'Allow camera access to make video calls.';
6
7
  value.modResults.UIBackgroundModes = [...new Set([...(value.modResults.UIBackgroundModes || []), 'audio'])];
8
+ if(options.incomingCalls!==false){value.modResults.RobonoSystemCallingEnabled=true;value.modResults.UIBackgroundModes=[...new Set([...value.modResults.UIBackgroundModes,'voip','remote-notification'])];}
9
+ else value.modResults.RobonoSystemCallingEnabled=false;
10
+ value.modResults.NSMicrophoneUsageDescription ||= options.microphonePermission || 'Allow microphone access to make and answer calls.';
7
11
  return value;
8
12
  });
9
13
  return withAndroidManifest(config, value => {
10
14
  const manifest = value.modResults.manifest;
15
+ const app=manifest.application?.[0];
16
+ if(app){
17
+ const meta=app['meta-data']||=[];const key='com.robono.calling.SYSTEM_CALLING';
18
+ const row=meta.find(v=>v.$['android:name']===key);const data={'android:name':key,'android:value':options.incomingCalls===false?'false':'true'};if(row)row.$=data;else meta.push({$:data});
19
+ app.service=(app.service||[]).filter(v=>v.$['android:name']!=='com.robono.calling.SystemCallMessagingService');
20
+ if(options.incomingCalls!==false)app.service.push({$:{'android:name':'com.robono.calling.SystemCallMessagingService','android:exported':'false'},'intent-filter':[{$:{'android:priority':'10'},action:[{$:{'android:name':'com.google.firebase.MESSAGING_EVENT'}}]}]});
21
+ }
11
22
  const permissions = manifest['uses-permission'] ||= [];
12
23
  for (const name of ['RECORD_AUDIO', 'MODIFY_AUDIO_SETTINGS', 'INTERNET', 'WAKE_LOCK', 'POST_NOTIFICATIONS', 'BLUETOOTH_CONNECT', ...(options.screenSharing?['FOREGROUND_SERVICE','FOREGROUND_SERVICE_MEDIA_PROJECTION']:[]), ...(options.video ? ['CAMERA'] : [])]) {
13
24
  const permission = `android.permission.${name}`;
@@ -0,0 +1,43 @@
1
+ import { type MessengerCallingTransport } from '@robono/calling/messenger';
2
+ import { type GroupCallingController } from './groups.js';
3
+ import { type CallingAppearance } from './appearance.js';
4
+ import type { CallingController, CallingOptions, Contact } from './types.js';
5
+ export interface MessengerCallingState {
6
+ direct: CallingController | null;
7
+ group: GroupCallingController | null;
8
+ appearance?: CallingAppearance;
9
+ features: MessengerCallingTransport['features'];
10
+ unanswered?: {
11
+ id: string;
12
+ conversationId: string;
13
+ };
14
+ loading: boolean;
15
+ error: string;
16
+ }
17
+ export interface MessengerCallAdapters extends Pick<CallingOptions, 'media' | 'audio'> {
18
+ attach?(controller: CallingController | GroupCallingController): () => void;
19
+ dispose?(): Promise<void>;
20
+ /** Browser audio is unlocked by the initiating tap, before any network wait. */
21
+ prime?(): void;
22
+ }
23
+ export interface MessengerCallingOptions {
24
+ request: (operation: string, input: Record<string, unknown>) => Promise<any>;
25
+ adapters: (appearance: CallingAppearance) => MessengerCallAdapters;
26
+ resolveContact?: (conversationId: string) => Contact | null;
27
+ resolveMember?: (appId: string, userId: string) => Contact | null;
28
+ onUnansweredCall?: CallingOptions['onUnansweredCall'];
29
+ }
30
+ /** Account-scoped calls. Owns renewal, listeners and cleanup across navigation. */
31
+ export declare function createMessengerCalling(options: MessengerCallingOptions): {
32
+ start: () => Promise<void>;
33
+ getSnapshot: () => MessengerCallingState;
34
+ subscribe(fn: () => void): () => void;
35
+ isActive: () => boolean;
36
+ reportError(message: string): void;
37
+ dismissUnanswered(): void;
38
+ notification(data: unknown, opened?: boolean): Promise<boolean>;
39
+ prime(): void;
40
+ call(conversationId: string, kind: "voice" | "video", group?: boolean): Promise<void>;
41
+ dispose(): Promise<void>;
42
+ };
43
+ export type MessengerCalling = ReturnType<typeof createMessengerCalling>;
@@ -0,0 +1,132 @@
1
+ import { createMessengerCallingTransport } from '@robono/calling/messenger';
2
+ import { createCallingController } from './index.js';
3
+ import { createGroupCallingController } from './groups.js';
4
+ import { validateCallingAppearance } from './appearance.js';
5
+ import { parseCallingNotification } from './notifications.js';
6
+ /** Account-scoped calls. Owns renewal, listeners and cleanup across navigation. */
7
+ export function createMessengerCalling(options) {
8
+ let state = { direct: null, group: null, features: { voice: false, video: false }, loading: false, error: '' };
9
+ let closed = false, pending = null, transport, timer;
10
+ let adapters = [], detach = [];
11
+ const dismissed = new Set();
12
+ const listeners = new Set();
13
+ const emit = (patch) => { state = { ...state, ...patch }; listeners.forEach(fn => fn()); };
14
+ const active = () => [state.direct, state.group].some(c => c && !['idle', 'error'].includes(c.getSnapshot().phase));
15
+ const release = async () => {
16
+ clearTimeout(timer);
17
+ const controllers = [state.direct, state.group], old = transport, owned = adapters;
18
+ transport = undefined;
19
+ adapters = [];
20
+ detach.splice(0).forEach(fn => fn());
21
+ emit({ direct: null, group: null });
22
+ await Promise.allSettled(controllers.map(c => c?.dispose()));
23
+ await Promise.allSettled(owned.map(a => a.dispose?.()));
24
+ await old?.dispose().catch(() => { });
25
+ };
26
+ const renew = () => {
27
+ clearTimeout(timer);
28
+ if (closed || !transport)
29
+ return;
30
+ timer = setTimeout(() => {
31
+ // Do not replace the controlling session in the middle of a call.
32
+ if (active()) {
33
+ timer = setTimeout(renew, 15000);
34
+ return;
35
+ }
36
+ void release().then(() => start()).catch(() => { });
37
+ }, Math.max(1000, Math.min(2147483647, transport.expiresAt - Date.now() - 60000)));
38
+ };
39
+ const start = () => {
40
+ if (closed)
41
+ return Promise.reject(Error('Calling has been closed.'));
42
+ if (pending)
43
+ return pending;
44
+ if (transport && Date.now() < transport.expiresAt && !state.direct?.client.closed && !state.group?.client.closed)
45
+ return Promise.resolve();
46
+ emit({ loading: true, error: '' });
47
+ pending = (async () => {
48
+ await release();
49
+ const session = await createMessengerCallingTransport({ request: options.request });
50
+ if (closed) {
51
+ await session.dispose();
52
+ return;
53
+ }
54
+ transport = session;
55
+ const appearance = validateCallingAppearance(session.appearance);
56
+ if (!session.features.voice && !session.features.video) {
57
+ emit({ appearance, features: session.features, loading: false });
58
+ renew();
59
+ return;
60
+ }
61
+ const make = () => { const adapter = options.adapters(appearance); adapters.push(adapter); return adapter; };
62
+ const directAdapter = make();
63
+ const direct = createCallingController({ ...directAdapter, request: session.request, appearanceRevision: session.revision, resolveContact: options.resolveContact, onUnansweredCall: call => { emit({ unanswered: { id: call.id, conversationId: call.connectionId } }); options.onUnansweredCall?.(call); } });
64
+ emit({ direct, appearance, features: session.features });
65
+ const directDetach = directAdapter.attach?.(direct);
66
+ if (directDetach)
67
+ detach.push(directDetach);
68
+ if (session.features.groups) {
69
+ const groupAdapter = make(), group = createGroupCallingController({ ...groupAdapter, request: session.request, appearanceRevision: session.revision, resolveGroup: options.resolveContact, resolveMember: options.resolveMember });
70
+ emit({ group });
71
+ const groupDetach = groupAdapter.attach?.(group);
72
+ if (groupDetach)
73
+ detach.push(groupDetach);
74
+ }
75
+ await Promise.all([direct.listen(), state.group?.listen()]);
76
+ if (closed) {
77
+ await release();
78
+ return;
79
+ }
80
+ emit({ loading: false, error: '' });
81
+ renew();
82
+ })().catch(async (error) => { await release(); if (!closed)
83
+ emit({ loading: false, error: 'Calls could not connect. Check your connection and try again.' }); throw error; }).finally(() => { pending = null; });
84
+ return pending;
85
+ };
86
+ return {
87
+ start, getSnapshot: () => state, subscribe(fn) { listeners.add(fn); return () => { listeners.delete(fn); }; },
88
+ isActive: active,
89
+ reportError(message) { if (!closed)
90
+ emit({ error: message }); },
91
+ dismissUnanswered() { emit({ unanswered: undefined }); },
92
+ async notification(data, opened = false) {
93
+ const event = parseCallingNotification(data) || parseCallingNotification(data, true);
94
+ if (!event || closed)
95
+ return false;
96
+ const isDismissed = event.sequence === 2 || Date.parse(event.ring_expires_at) <= Date.now();
97
+ if (isDismissed) {
98
+ dismissed.add(event.call_id);
99
+ if (dismissed.size > 100)
100
+ dismissed.delete(dismissed.values().next().value);
101
+ }
102
+ await start();
103
+ if (closed)
104
+ return false;
105
+ const controller = event.event.startsWith('calling.group_') ? state.group : state.direct;
106
+ if (!controller)
107
+ return false;
108
+ if (isDismissed || dismissed.has(event.call_id) || !opened) {
109
+ await controller.refresh();
110
+ return true;
111
+ }
112
+ await controller.openIncoming(event.call_id);
113
+ return true;
114
+ },
115
+ prime() { adapters.forEach(a => a.prime?.()); },
116
+ async call(conversationId, kind, group = false) {
117
+ // Retain the browser's user activation before awaiting admission.
118
+ adapters.forEach(a => a.prime?.());
119
+ await start();
120
+ if (active())
121
+ throw Error('Finish the current call first.');
122
+ if (!state.features[kind] || group && !state.group)
123
+ throw Error('This call type is not available.');
124
+ if (group)
125
+ await state.group.call(conversationId, { kind });
126
+ else
127
+ await state.direct.call(conversationId, undefined, { kind });
128
+ },
129
+ async dispose() { if (closed)
130
+ return; closed = true; clearTimeout(timer); await pending?.catch(() => { }); await release(); listeners.clear(); },
131
+ };
132
+ }
package/dist/native.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { CallAudio, MediaAdapter } from './types.js';
2
2
  import { type CallingAppearance } from './appearance.js';
3
3
  import type { CallRuntime } from './runtime.js';
4
4
  export interface NativeAdapterOptions {
5
+ systemCalling?: NativeSystemCallAudio;
5
6
  appearance?: CallingAppearance;
6
7
  /** Restore your app's ordinary playback/recording policy after each call. */
7
8
  restoreAudio(): Promise<void>;
@@ -11,6 +12,11 @@ export interface NativeAdapterOptions {
11
12
  /** Supplied native runtime, or your existing application's lifetime adapter. */
12
13
  runtime?: CallRuntime;
13
14
  }
15
+ export interface NativeSystemCallAudio {
16
+ active(): boolean;
17
+ prepare(): Promise<void>;
18
+ speaker(value: boolean): void;
19
+ }
14
20
  /** True while this adapter owns ringing or call audio. Use as the messaging audio session guard. */
15
21
  export declare function isNativeCallAudioActive(): boolean;
16
22
  /** Import this entry point only when choosing the supplied native audio adapter. */
package/dist/native.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createNativeCountdown } from './countdown-native.js';
2
- import { PermissionsAndroid, Platform, NativeModules } from 'react-native';
2
+ import { PermissionsAndroid, Platform, NativeModules, AppState } from 'react-native';
3
3
  import { mediaDevices, MediaStream, RTCPeerConnection } from 'react-native-webrtc';
4
4
  import InCallManager from 'react-native-incall-manager';
5
5
  import { createAudioPlayer, setAudioModeAsync } from 'expo-audio';
@@ -16,7 +16,7 @@ export function createNativeCallAdapters(options) {
16
16
  let players;
17
17
  const sounds = { ...callingSounds, ...options.appearance?.sounds };
18
18
  const owner = Symbol('calling-audio');
19
- let current = '', session = '', speaker = false, disposed = false;
19
+ let current = '', session = '', speaker = false, disposed = false, systemSession = false;
20
20
  let resumedFocus = false;
21
21
  // These cues share AVAudioSession with WebRTC. Expo's default pause/finish
22
22
  // deactivates that session when no Expo player is playing, without accounting
@@ -39,6 +39,10 @@ export function createNativeCallAdapters(options) {
39
39
  current = '';
40
40
  };
41
41
  const route = () => {
42
+ if (options.systemCalling?.active()) {
43
+ options.systemCalling.speaker(speaker);
44
+ return;
45
+ }
42
46
  // null restores automatic headset/Bluetooth routing; false forces earpiece.
43
47
  InCallManager.setForceSpeakerphoneOn((speaker ? true : null));
44
48
  };
@@ -71,6 +75,15 @@ export function createNativeCallAdapters(options) {
71
75
  audioOwner = owner;
72
76
  speaker = selected;
73
77
  const target = phase === 'incoming' ? 'ring' : 'call';
78
+ if (options.systemCalling?.active() && Platform.OS === 'ios') {
79
+ // CallKit owns AVAudioSession. Expo/InCallManager must not deactivate or
80
+ // replace it while the system is answering or routing the call.
81
+ systemSession = true;
82
+ session = target;
83
+ if (target === 'call')
84
+ route();
85
+ return;
86
+ }
74
87
  if (session !== target) {
75
88
  if (session === 'call')
76
89
  InCallManager.stop();
@@ -86,6 +99,8 @@ export function createNativeCallAdapters(options) {
86
99
  async play(kind, playback = {}) {
87
100
  pause();
88
101
  current = kind;
102
+ if (options.systemCalling?.active() && (playback.event === 'incoming' || Platform.OS === 'ios' && playback.event === 'connecting'))
103
+ return;
89
104
  if (playback.event === 'incoming' && !options.appearance && kind === 'ringing' && options.ringtone !== 'robono') {
90
105
  InCallManager.startRingtone('_DEFAULT_', [0, 350, 900], 'ambient', 0);
91
106
  return;
@@ -107,7 +122,9 @@ export function createNativeCallAdapters(options) {
107
122
  if (audioOwner !== owner)
108
123
  return;
109
124
  try {
110
- InCallManager.stop();
125
+ if (!systemSession)
126
+ InCallManager.stop();
127
+ systemSession = false;
111
128
  session = '';
112
129
  try {
113
130
  if (resumedFocus) {
@@ -191,6 +208,21 @@ export function createNativeCallAdapters(options) {
191
208
  if (result !== PermissionsAndroid.RESULTS.GRANTED)
192
209
  throw Error('microphone_permission_denied');
193
210
  }
211
+ if (options.systemCalling?.active())
212
+ await options.systemCalling.prepare();
213
+ // A lock-screen answer authorizes audio, never background camera capture.
214
+ // CallKit/Telecom opens the host; wait for its visible state before video.
215
+ const visible = () => AppState.currentState === 'active';
216
+ if (context?.kind === 'video' && !visible()) {
217
+ const deadline = Date.now() + 20000;
218
+ while (!visible()) {
219
+ if (!current())
220
+ throw Error('call_cancelled');
221
+ if (Date.now() >= deadline)
222
+ throw Error('open_app_to_start_video');
223
+ await new Promise(resolve => setTimeout(resolve, 100));
224
+ }
225
+ }
194
226
  if (Platform.OS === 'android' && context?.kind === 'video') {
195
227
  const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.CAMERA);
196
228
  if (!current())
@@ -33,9 +33,9 @@ export function parseCallingNotification(data, group = false) {
33
33
  return null;
34
34
  if (typeof p.ring_expires_at !== 'string' || !Number.isFinite(Date.parse(p.ring_expires_at)))
35
35
  return null;
36
- if (p.sequence !== (String(p.event).endsWith('incoming') ? 1 : 2))
36
+ if (![1, 2, '1', '2'].includes(p.sequence) || Number(p.sequence) !== (String(p.event).endsWith('incoming') ? 1 : 2))
37
37
  return null;
38
- return { ...(p.kind ? { kind: p.kind } : {}), event: p.event, event_id: p.event_id, call_id: p.call_id, connection_id: p.connection_id, ring_expires_at: p.ring_expires_at, sequence: p.sequence };
38
+ return { ...(p.kind ? { kind: p.kind } : {}), event: p.event, event_id: p.event_id, call_id: p.call_id, connection_id: p.connection_id, ring_expires_at: p.ring_expires_at, sequence: Number(p.sequence) };
39
39
  }
40
40
  /** Host retains its push provider, credentials and notification handler. */
41
41
  export function createCallingNotificationHandler(options) {
package/dist/runtime.d.ts CHANGED
@@ -24,5 +24,5 @@ export interface NativeRuntimeOptions {
24
24
  endLabel: string;
25
25
  onError(error: Error): void;
26
26
  }
27
- /** Optional native lifetime support. Does not install CallKit or incoming-call UI. */
27
+ /** Ongoing-call lifetime. System admission is owned by the system-calling entry. */
28
28
  export declare function createNativeCallRuntime(options: NativeRuntimeOptions): CallRuntime;
package/dist/runtime.js CHANGED
@@ -22,7 +22,7 @@ function finishCallTask(token) {
22
22
  callTasks.get(token)?.finish();
23
23
  callTasks.delete(token);
24
24
  }
25
- /** Optional native lifetime support. Does not install CallKit or incoming-call UI. */
25
+ /** Ongoing-call lifetime. System admission is owned by the system-calling entry. */
26
26
  export function createNativeCallRuntime(options) {
27
27
  const native = NativeModules.RobonoCallingRuntime;
28
28
  if (!native)
@@ -131,7 +131,7 @@ export function createNativeCallRuntime(options) {
131
131
  return;
132
132
  if (starting)
133
133
  return starting;
134
- if (AppState.currentState !== 'active')
134
+ if (AppState.currentState !== 'active' && !await NativeModules.RobonoSystemCalling?.canCapture())
135
135
  throw Error('open_app_to_start_call');
136
136
  const revision = ++generation;
137
137
  const callToken = token = `${owner}-${revision}`;