@robono/calling-react-native 0.5.0 → 0.7.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 (37) hide show
  1. package/CHANGELOG.md +9 -1
  2. package/INCOMING-CALLS.md +68 -0
  3. package/README.md +8 -2
  4. package/RobonoCallingRuntime.podspec +1 -1
  5. package/SBOM.spdx.json +708 -372
  6. package/android/build.gradle +1 -0
  7. package/android/consumer-rules.pro +13 -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/CallingPictureInPicture.java +102 -0
  11. package/android/src/main/java/com/robono/calling/CallingRuntime.java +2 -2
  12. package/android/src/main/java/com/robono/calling/SystemCallActionReceiver.java +5 -0
  13. package/android/src/main/java/com/robono/calling/SystemCallActivity.java +25 -0
  14. package/android/src/main/java/com/robono/calling/SystemCallConnectionService.java +17 -0
  15. package/android/src/main/java/com/robono/calling/SystemCallMessagingService.java +19 -0
  16. package/android/src/main/java/com/robono/calling/SystemCallService.java +28 -0
  17. package/android/src/main/java/com/robono/calling/SystemCalling.java +95 -0
  18. package/app.plugin.cjs +19 -0
  19. package/dist/components.d.ts +4 -0
  20. package/dist/components.js +5 -4
  21. package/dist/messenger.d.ts +1 -0
  22. package/dist/messenger.js +2 -0
  23. package/dist/native-video.js +18 -1
  24. package/dist/native.d.ts +6 -0
  25. package/dist/native.js +35 -3
  26. package/dist/runtime.d.ts +1 -1
  27. package/dist/runtime.js +2 -2
  28. package/dist/system-calling.d.ts +29 -0
  29. package/dist/system-calling.js +184 -0
  30. package/dist/versions.d.ts +1 -1
  31. package/dist/versions.js +1 -1
  32. package/ios/RobonoCallingRuntime.m +3 -1
  33. package/ios/RobonoSystemCalling.h +7 -0
  34. package/ios/RobonoSystemCalling.m +176 -0
  35. package/package.json +6 -1
  36. package/plugin/incoming-calls.cjs +14 -0
  37. package/plugin/picture-in-picture.cjs +26 -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,16 @@
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
+ }
15
+
16
+ # Optional WebRTC renderer uses its normal public manager, including its thread and release handling.
17
+ -keep class com.oney.WebRTCModule.WebRTCView { public <init>(android.content.Context); public void setObjectFit(java.lang.String); }
18
+ -keep class com.oney.WebRTCModule.RTCVideoViewManager { public <init>(); public void setStreamURL(com.oney.WebRTCModule.WebRTCView,java.lang.String); }
@@ -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),new CallingPictureInPicture(context));
13
13
  }
14
14
  public List<ViewManager> createViewManagers(ReactApplicationContext context) { return Collections.emptyList(); }
15
15
  }
@@ -0,0 +1,102 @@
1
+ package com.robono.calling;
2
+
3
+ import android.app.Activity;
4
+ import android.app.Application;
5
+ import android.app.PictureInPictureParams;
6
+ import android.os.Build;
7
+ import android.os.Bundle;
8
+ import android.os.Handler;
9
+ import android.os.Looper;
10
+ import android.graphics.Color;
11
+ import android.view.View;
12
+ import android.view.ViewGroup;
13
+ import android.widget.FrameLayout;
14
+ import com.facebook.react.bridge.*;
15
+ import java.lang.ref.WeakReference;
16
+ import java.util.IdentityHashMap;
17
+
18
+ /** Uses the existing activity: Android forbids starting a new activity after Home. */
19
+ public final class CallingPictureInPicture extends ReactContextBaseJavaModule implements Application.ActivityLifecycleCallbacks {
20
+ private static WeakReference<CallingPictureInPicture> instance = new WeakReference<>(null);
21
+ private final Handler handler = new Handler(Looper.getMainLooper());
22
+ private final IdentityHashMap<View,Integer> hidden = new IdentityHashMap<>();
23
+ private WeakReference<Activity> owner = new WeakReference<>(null);
24
+ private String streamURL, renderedURL;
25
+ private int width=9,height=16,sourceTag;
26
+ private FrameLayout mainCover;
27
+ private FrameLayout overlay;
28
+ private View renderer;
29
+ private Object manager;
30
+ private Class<?> videoView;
31
+ private boolean launching;
32
+ private final Runnable observe = new Runnable(){public void run(){
33
+ Activity activity=owner.get();
34
+ if(activity==null||activity.isDestroyed()||!activity.isInPictureInPictureMode())release();
35
+ else handler.postDelayed(this,250);
36
+ }};
37
+ public CallingPictureInPicture(ReactApplicationContext context){super(context);instance=new WeakReference<>(this);((Application)context.getApplicationContext()).registerActivityLifecycleCallbacks(this);}
38
+ @Override public String getName(){return "RobonoCallingPictureInPicture";}
39
+ @ReactMethod public void setSource(String url,int sourceWidth,int sourceHeight,boolean enabled,int reactTag,Promise promise){
40
+ UiThreadUtil.runOnUiThread(()->{
41
+ sourceTag=reactTag;
42
+ streamURL=enabled&&url!=null&&!url.isEmpty()?url:null;
43
+ if(sourceWidth>0&&sourceHeight>0){width=sourceWidth;height=sourceHeight;}
44
+ Activity activity=owner.get();
45
+ if(streamURL==null){
46
+ // Keep the opaque cover until Android has removed the pinned window.
47
+ detachVideo();
48
+ if(activity!=null&&Build.VERSION.SDK_INT>=26&&activity.isInPictureInPictureMode())activity.moveTaskToBack(true);
49
+ else release();
50
+ }else if(renderer!=null){try{refreshSource();if(activity!=null)activity.setPictureInPictureParams(params());}catch(Exception e){stop();}}
51
+ promise.resolve(Build.VERSION.SDK_INT>=26);
52
+ });
53
+ }
54
+ @ReactMethod public void status(Promise promise){UiThreadUtil.runOnUiThread(()->{Activity activity=owner.get();WritableMap state=Arguments.createMap();state.putBoolean("available",Build.VERSION.SDK_INT>=26&&getReactApplicationContext().getPackageManager().hasSystemFeature("android.software.picture_in_picture"));state.putBoolean("ready",streamURL!=null);state.putBoolean("active",activity!=null&&Build.VERSION.SDK_INT>=26&&activity.isInPictureInPictureMode());state.putBoolean("launching",launching);promise.resolve(state);});}
55
+ @ReactMethod public void enter(Promise promise){UiThreadUtil.runOnUiThread(()->promise.resolve(launch(getCurrentActivity())));}
56
+ public static void onUserLeaveHint(Activity activity){CallingPictureInPicture module=instance.get();if(module!=null)module.launch(activity);}
57
+ private PictureInPictureParams params(){double value=(double)width/height;android.util.Rational ratio=value<0.418?new android.util.Rational(9,21):value>2.39?new android.util.Rational(21,9):new android.util.Rational(width,height);return new PictureInPictureParams.Builder().setAspectRatio(ratio).build();}
58
+ private boolean launch(Activity activity){
59
+ if(Build.VERSION.SDK_INT<26||streamURL==null||launching||overlay!=null||activity==null||activity.isFinishing()||activity.isInPictureInPictureMode())return false;
60
+ if(!activity.getPackageManager().hasSystemFeature("android.software.picture_in_picture"))return false;
61
+ try{
62
+ launching=true;owner=new WeakReference<>(activity);
63
+ videoView=Class.forName("com.oney.WebRTCModule.WebRTCView");
64
+ renderer=(View)videoView.getConstructor(android.content.Context.class).newInstance(getReactApplicationContext());
65
+ manager=Class.forName("com.oney.WebRTCModule.RTCVideoViewManager").getConstructor().newInstance();
66
+ videoView.getMethod("setObjectFit",String.class).invoke(renderer,"contain");
67
+ ViewGroup decor=(ViewGroup)activity.getWindow().getDecorView();
68
+ ViewGroup sourceRoot=decor;
69
+ if(sourceTag>0){
70
+ com.facebook.react.bridge.UIManager ui=com.facebook.react.uimanager.UIManagerHelper.getUIManagerForReactTag(getReactApplicationContext(),sourceTag);
71
+ View original=ui==null?null:ui.resolveView(sourceTag);
72
+ if(original!=null&&original.getRootView() instanceof ViewGroup)sourceRoot=(ViewGroup)original.getRootView();
73
+ }
74
+ if(sourceRoot!=decor){
75
+ coverChildren(decor);
76
+ mainCover=new FrameLayout(activity);mainCover.setBackgroundColor(Color.BLACK);decor.addView(mainCover,new ViewGroup.LayoutParams(-1,-1));
77
+ }
78
+ decor=sourceRoot;
79
+ overlay=new FrameLayout(activity);overlay.setBackgroundColor(Color.BLACK);
80
+ overlay.addView(renderer,new FrameLayout.LayoutParams(-1,-1));
81
+ // Hide every original child, including native host navigation. Restore exact visibility afterward.
82
+ coverChildren(decor);
83
+ decor.addView(overlay,new ViewGroup.LayoutParams(-1,-1));refreshSource();
84
+ boolean entered=activity.enterPictureInPictureMode(params());launching=false;
85
+ if(!entered){release();return false;}
86
+ handler.postDelayed(observe,250);return true;
87
+ }catch(Exception error){android.util.Log.w("RobonoCallingPiP","Unable to enter picture-in-picture",error);release();return false;}
88
+ }
89
+ private void coverChildren(ViewGroup decor){for(int i=0;i<decor.getChildCount();i++){View child=decor.getChildAt(i);hidden.put(child,child.getVisibility());child.setVisibility(View.INVISIBLE);}}
90
+ private void refreshSource()throws Exception{if(renderer!=null&&streamURL!=null&&!streamURL.equals(renderedURL)){manager.getClass().getMethod("setStreamURL",videoView,String.class).invoke(manager,renderer,streamURL);renderedURL=streamURL;}}
91
+ private void detachVideo(){if(renderer!=null){try{manager.getClass().getMethod("setStreamURL",videoView,String.class).invoke(manager,renderer,null);}catch(Exception ignored){}if(renderer.getParent() instanceof ViewGroup)((ViewGroup)renderer.getParent()).removeView(renderer);}renderer=null;manager=null;renderedURL=null;}
92
+ private void stop(){Activity activity=owner.get();detachVideo();if(activity!=null&&Build.VERSION.SDK_INT>=26&&activity.isInPictureInPictureMode()){activity.moveTaskToBack(true);handler.removeCallbacks(observe);handler.postDelayed(observe,250);}else release();}
93
+ private void release(){handler.removeCallbacks(observe);detachVideo();if(overlay!=null&&overlay.getParent() instanceof ViewGroup)((ViewGroup)overlay.getParent()).removeView(overlay);overlay=null;if(mainCover!=null&&mainCover.getParent() instanceof ViewGroup)((ViewGroup)mainCover.getParent()).removeView(mainCover);mainCover=null;for(java.util.Map.Entry<View,Integer> entry:hidden.entrySet())entry.getKey().setVisibility(entry.getValue());hidden.clear();owner.clear();launching=false;}
94
+ @Override public void onActivityResumed(Activity activity){if(activity==owner.get()&&Build.VERSION.SDK_INT>=26&&!activity.isInPictureInPictureMode()&&!launching)release();}
95
+ @Override public void onActivityDestroyed(Activity activity){if(activity==owner.get())release();}
96
+ @Override public void onActivityCreated(Activity activity,Bundle state){}
97
+ @Override public void onActivityStarted(Activity activity){}
98
+ @Override public void onActivityPaused(Activity activity){}
99
+ @Override public void onActivityStopped(Activity activity){}
100
+ @Override public void onActivitySaveInstanceState(Activity activity,Bundle state){}
101
+ @Override public void invalidate(){((Application)getReactApplicationContext().getApplicationContext()).unregisterActivityLifecycleCallbacks(this);UiThreadUtil.runOnUiThread(()->{streamURL=null;stop();if(instance.get()==this)instance=new WeakReference<>(null);});super.invalidate();}
102
+ }
@@ -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,32 @@
1
1
  const {withInfoPlist, withAndroidManifest, createRunOncePlugin} = require('expo/config-plugins');
2
2
  function withCallingRuntime(config, options = {}) {
3
+ if(options.video&&options.pictureInPicture!==false)config=require('./plugin/picture-in-picture.cjs').withCallPictureInPicture(config);
4
+ if(options.incomingCalls!==false)config=require('./plugin/incoming-calls.cjs').withIncomingCalls(config);
3
5
  if(options.screenSharing)config=require('./plugin/screensharing.cjs').withScreenSharing(config,typeof options.screenSharing==='object'?options.screenSharing:{});
4
6
  config = withInfoPlist(config, value => {
7
+ value.modResults.RobonoPictureInPictureEnabled=options.video===true&&options.pictureInPicture!==false;
5
8
  if (options.video) value.modResults.NSCameraUsageDescription ||= options.cameraPermission || 'Allow camera access to make video calls.';
6
9
  value.modResults.UIBackgroundModes = [...new Set([...(value.modResults.UIBackgroundModes || []), 'audio'])];
10
+ if(options.incomingCalls!==false){value.modResults.RobonoSystemCallingEnabled=true;value.modResults.UIBackgroundModes=[...new Set([...value.modResults.UIBackgroundModes,'voip','remote-notification'])];}
11
+ else value.modResults.RobonoSystemCallingEnabled=false;
12
+ value.modResults.NSMicrophoneUsageDescription ||= options.microphonePermission || 'Allow microphone access to make and answer calls.';
7
13
  return value;
8
14
  });
9
15
  return withAndroidManifest(config, value => {
10
16
  const manifest = value.modResults.manifest;
17
+ const app=manifest.application?.[0];
18
+ if(app){
19
+ if(options.video&&options.pictureInPicture!==false){
20
+ const main=app.activity?.find(activity=>activity['intent-filter']?.some(filter=>filter.action?.some(action=>action.$['android:name']==='android.intent.action.MAIN')));
21
+ if(!main)throw Error('Calling picture-in-picture requires a main Android activity.');
22
+ main.$['android:supportsPictureInPicture']='true';main.$['android:resizeableActivity']='true';
23
+ main.$['android:configChanges']=[...new Set([...(main.$['android:configChanges']||'').split('|').filter(Boolean),'screenSize','smallestScreenSize','screenLayout','orientation'])].join('|');
24
+ }
25
+ const meta=app['meta-data']||=[];const key='com.robono.calling.SYSTEM_CALLING';
26
+ 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});
27
+ app.service=(app.service||[]).filter(v=>v.$['android:name']!=='com.robono.calling.SystemCallMessagingService');
28
+ 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'}}]}]});
29
+ }
11
30
  const permissions = manifest['uses-permission'] ||= [];
12
31
  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
32
  const permission = `android.permission.${name}`;
@@ -66,6 +66,8 @@ export interface CallingScreenComponents {
66
66
  ActionButton?: ComponentType<CallingActionButtonProps>;
67
67
  }
68
68
  export interface CallingScreenProps {
69
+ /** Allow the connected remote video to use the operating system floating window. */
70
+ pictureInPicture?: boolean;
69
71
  state: CallingState;
70
72
  appearance?: CallingAppearance;
71
73
  onScreenShare?(): void;
@@ -76,6 +78,7 @@ export interface CallingScreenProps {
76
78
  stream: MediaStream;
77
79
  local: boolean;
78
80
  screen?: boolean;
81
+ pictureInPicture?: boolean;
79
82
  style: StyleProp<ViewStyle>;
80
83
  }): ReactNode;
81
84
  onResume?(): void;
@@ -94,6 +97,7 @@ export interface CallingScreenProps {
94
97
  components?: CallingScreenComponents;
95
98
  }
96
99
  export interface CallingUIValue {
100
+ pictureInPicture: boolean;
97
101
  renderVideo?: CallingScreenProps['renderVideo'];
98
102
  state: Readonly<CallingState>;
99
103
  appearance?: CallingAppearance;
@@ -52,7 +52,7 @@ export function CallingUIProvider({ children, ...props }) {
52
52
  };
53
53
  const fontFamily = Platform.OS === 'ios' ? design.fontFamily.ios : Platform.OS === 'android' ? design.fontFamily.android : design.fontFamily.web;
54
54
  const value = {
55
- state: s, renderVideo: props.renderVideo, appearance: props.appearance, theme: c, labels: t, design,
55
+ state: s, pictureInPicture: props.pictureInPicture !== false, renderVideo: props.renderVideo, appearance: props.appearance, theme: c, labels: t, design,
56
56
  insets: props.insets || safeArea, components: props.components || {},
57
57
  title: s.contact?.name || t.contact,
58
58
  status: s.phase === 'connected' ? duration : s.phase === 'error' || s.phase === 'idle' ? '' : s.phase === 'incoming' && s.kind === 'video' ? t.incomingVideo : t[s.phase],
@@ -164,12 +164,13 @@ const styles = StyleSheet.create({
164
164
  });
165
165
  /** Video uses the same SDK layout, labels and controls on native and web. */
166
166
  export function CallingVideo({ style } = {}) {
167
- const { state, renderVideo, theme, typography, labels, design } = useCallingUI();
167
+ const { state, renderVideo, pictureInPicture, theme, typography, labels, design } = useCallingUI();
168
168
  const [area, setArea] = useState({ width: 0, height: 0 });
169
169
  if (state.group && ['outgoing', 'connecting', 'connected', 'held'].includes(state.phase)) {
170
170
  const members = state.groupMembers?.filter(m => !['left', 'declined'].includes(m.state)) ?? [], sharing = members.find(m => m.sharing);
171
+ const pipMember = members.find(m => !m.local && !m.held && m.sharing && m.stream) ?? members.find(m => !m.local && !m.held && m.stream);
171
172
  const tile = (member, tileStyle, compact = false) => _jsxs(View, { style: [{ flex: 1, minHeight: 60, overflow: 'hidden', borderRadius: 12, backgroundColor: theme.control, alignItems: 'center', justifyContent: 'center' }, tileStyle], children: [state.kind === 'video' && member.stream && renderVideo && !member.held && state.phase !== 'held' && (member.sharing || !member.local || state.cameraEnabled !== false)
172
- ? renderVideo({ stream: member.stream, local: !!member.local, screen: member.sharing, style: { position: 'absolute', width: '100%', height: '100%' } })
173
+ ? renderVideo({ stream: member.stream, local: !!member.local, screen: member.sharing, pictureInPicture: pictureInPicture && state.phase === 'connected' && member === pipMember, style: { position: 'absolute', width: '100%', height: '100%' } })
173
174
  : design.presentation.showAvatar && _jsx(View, { style: { width: compact ? 36 : avatarSize, height: compact ? 36 : avatarSize, borderRadius: 40, backgroundColor: theme.background, alignItems: 'center', justifyContent: 'center' }, children: member.avatarUri ? _jsx(Image, { source: { uri: member.avatarUri }, style: { width: compact ? 36 : avatarSize, height: compact ? 36 : avatarSize, borderRadius: 40 } }) : _jsx(Text, { style: [typography(28), { color: theme.accent }], children: member.name.slice(0, 1) }) }), _jsx(View, { style: { position: 'absolute', bottom: 8, left: 8, maxWidth: '90%', borderRadius: 6, paddingHorizontal: 8, paddingVertical: 4, backgroundColor: '#000000b0' }, children: _jsxs(Text, { numberOfLines: 1, style: [typography(12), { color: '#ffffff', textAlign: 'left' }], children: [member.name, member.sharing ? ' · ' + labels.sharingScreen : '', member.held ? ' · ' + labels.held : member.state === 'invited' ? ' · ' + labels.outgoing : ''] }) })] }, member.id);
174
175
  const landscape = area.width > area.height;
175
176
  const columns = Math.max(1, Math.min(members.length, landscape && area.width > 700 && members.length > 4 ? 4 : landscape || members.length > 2 ? 2 : 1));
@@ -180,6 +181,6 @@ export function CallingVideo({ style } = {}) {
180
181
  if (state.kind !== 'video' || !['outgoing', 'connecting', 'connected', 'held'].includes(state.phase) || !renderVideo)
181
182
  return null;
182
183
  const visible = !['held', 'idle', 'error'].includes(state.phase);
183
- return _jsxs(View, { style: [{ flex: 1, minHeight: 100, borderRadius: 16, overflow: 'hidden', backgroundColor: theme.control }, style], children: [visible && state.remoteStream ? renderVideo({ stream: state.remoteStream, local: false, screen: state.remoteScreenSharing, style: { width: '100%', height: '100%' } }) :
184
+ return _jsxs(View, { style: [{ flex: 1, minHeight: 100, borderRadius: 16, overflow: 'hidden', backgroundColor: theme.control }, style], children: [visible && state.remoteStream ? renderVideo({ stream: state.remoteStream, local: false, screen: state.remoteScreenSharing, pictureInPicture: pictureInPicture && state.phase === 'connected', style: { width: '100%', height: '100%' } }) :
184
185
  _jsxs(View, { style: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 16 }, children: [_jsx(CallingAvatar, { size: 80 }), _jsx(Text, { style: [typography(16), { color: theme.secondary }], children: state.phase === 'held' ? labels.held : labels.connecting })] }), visible && (state.screenSharing || state.remoteScreenSharing) && _jsx(Text, { style: [typography(13), { position: 'absolute', top: 8, left: 8, padding: 6, borderRadius: 5, color: '#ffffff', backgroundColor: '#000000b0' }], children: labels.sharingScreen }), visible && state.localStream && (state.screenSharing || state.cameraEnabled !== false) && _jsx(View, { style: { position: 'absolute', right: 10, bottom: 10, width: 86, height: 114, borderRadius: 10, overflow: 'hidden' }, children: renderVideo({ stream: state.displayStream || state.localStream, local: true, screen: state.screenSharing, style: { width: '100%', height: '100%' } }) })] });
185
186
  }
@@ -33,6 +33,7 @@ export declare function createMessengerCalling(options: MessengerCallingOptions)
33
33
  getSnapshot: () => MessengerCallingState;
34
34
  subscribe(fn: () => void): () => void;
35
35
  isActive: () => boolean;
36
+ reportError(message: string): void;
36
37
  dismissUnanswered(): void;
37
38
  notification(data: unknown, opened?: boolean): Promise<boolean>;
38
39
  prime(): void;
package/dist/messenger.js CHANGED
@@ -86,6 +86,8 @@ export function createMessengerCalling(options) {
86
86
  return {
87
87
  start, getSnapshot: () => state, subscribe(fn) { listeners.add(fn); return () => { listeners.delete(fn); }; },
88
88
  isActive: active,
89
+ reportError(message) { if (!closed)
90
+ emit({ error: message }); },
89
91
  dismissUnanswered() { emit({ unanswered: undefined }); },
90
92
  async notification(data, opened = false) {
91
93
  const event = parseCallingNotification(data) || parseCallingNotification(data, true);
@@ -1,7 +1,24 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useEffect, useState, useRef } from 'react';
3
+ import { NativeModules, Platform, findNodeHandle } from 'react-native';
2
4
  import { RTCView } from 'react-native-webrtc';
3
5
  import { CallingOverlay } from './screens.js';
4
- export const renderNativeCallVideo = ({ stream, local, screen, style }) => _jsx(RTCView, { streamURL: stream.toURL(), mirror: local && !screen, objectFit: screen ? "contain" : "cover", zOrder: local ? 1 : 0, style: style });
6
+ function NativeCallVideo({ stream, local, screen, style, pictureInPicture }) {
7
+ const view = useRef(null);
8
+ const url = stream.toURL();
9
+ const [size, setSize] = useState(screen ? { width: 16, height: 9 } : { width: 9, height: 16 });
10
+ useEffect(() => {
11
+ if (Platform.OS === 'android' && pictureInPicture && !local)
12
+ void NativeModules.RobonoCallingPictureInPicture?.setSource(url, size.width, size.height, true, findNodeHandle(view.current) ?? 0).catch(() => { });
13
+ }, [url, pictureInPicture, local, size.width, size.height]);
14
+ useEffect(() => () => {
15
+ if (Platform.OS === 'android' && pictureInPicture && !local)
16
+ void NativeModules.RobonoCallingPictureInPicture?.setSource('', 9, 16, false, 0).catch(() => { });
17
+ }, [url, pictureInPicture, local]);
18
+ return _jsx(RTCView, { ref: view, streamURL: url, onDimensionsChange: event => { const { width, height } = event.nativeEvent; if (width > 0 && height > 0)
19
+ setSize(previous => previous.width === width && previous.height === height ? previous : { width, height }); }, mirror: local && !screen, objectFit: screen ? "contain" : "cover", zOrder: local ? 1 : 0, style: style, iosPIP: Platform.OS === 'ios' && !local && pictureInPicture && NativeModules.RobonoCallingRuntime?.pictureInPictureEnabled !== false ? { enabled: true, startAutomatically: true, stopAutomatically: true, preferredSize: screen ? { width: 640, height: 360 } : { width: 360, height: 640 } } : { enabled: false } });
20
+ }
21
+ export const renderNativeCallVideo = props => _jsx(NativeCallVideo, { ...props });
5
22
  /** Optional complete native screen; the calling engine can also use your UI. */
6
23
  export function NativeCallingOverlay(props) {
7
24
  return _jsx(CallingOverlay, { ...props, renderVideo: props.renderVideo || renderNativeCallVideo });
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. */