fix(mobile): keep calls active in background

This commit is contained in:
Erwan Leboucher committed 2026-07-29 16:02:22 +02:00
1 parent c6cb6fb126
commit 922e62df65
12 files changed
+173 -52

No files matched your search

+12
View File
@@ -3881,6 +3881,17 @@ dependencies = [
"objc2-core-foundation",
]
[[package]]
name = "objc2-avf-audio"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be"
dependencies = [
"bitflags 2.13.1",
"objc2",
"objc2-foundation",
]
[[package]]
name = "objc2-cloud-kit"
version = "0.3.2"
@@ -5365,6 +5376,7 @@ dependencies = [
"libloading 0.8.9",
"log",
"objc2",
"objc2-avf-audio",
"objc2-foundation",
"percent-encoding",
"regex",
+4
View File
@@ -129,6 +129,10 @@ tauri-plugin-sharekit = { git = "https://github.com/Choochmeque/tauri-plugin-sha
objc2 = "0.6"
objc2-foundation = { version = "0.3", features = ["NSFileManager", "NSString", "NSURL"] }
tauri-plugin-fs = "2"
objc2-avf-audio = { version = "0.3", default-features = false, features = [
"AVAudioSession",
"AVAudioSessionTypes",
] }
[target.'cfg(target_os = "android")'.dependencies]
tauri-plugin-android-fs = { version = "=28.4.0", features = ["legacy-storage-permission"] }
@@ -1,25 +1,57 @@
package moe.sable.client
import android.app.Notification
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
class CallForegroundService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
createNotificationChannel()
startForeground(NOTIFICATION_ID, buildNotification())
override fun onBind(intent: android.content.Intent?): IBinder? = null
override fun onStartCommand(intent: android.content.Intent?, flags: Int, startId: Int): Int {
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
Log.w(TAG, "Microphone permission is not granted; stopping foreground service")
stopSelf(startId)
return START_NOT_STICKY
}
try {
createNotificationChannel()
ServiceCompat.startForeground(
this,
NOTIFICATION_ID,
NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Call in progress")
.setContentText("Sable is using your microphone")
.setCategory(NotificationCompat.CATEGORY_CALL)
.setOngoing(true)
.setOnlyAlertOnce(true)
.build(),
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
} else {
0
}
)
} catch (error: Exception) {
Log.e(TAG, "Failed to start microphone foreground service", error)
stopSelf(startId)
return START_NOT_STICKY
}
return START_NOT_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
stopForeground(true)
stopForeground(STOP_FOREGROUND_REMOVE)
super.onDestroy()
}
@@ -34,19 +66,9 @@ class CallForegroundService : Service() {
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
}
private fun buildNotification(): Notification {
return NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_notification)
.setContentTitle("Call in progress")
.setContentText("Sable is keeping your call active")
.setCategory(Notification.CATEGORY_CALL)
.setOngoing(true)
.setOnlyAlertOnce(true)
.build()
}
companion object {
private const val CHANNEL_ID = "call_foreground"
private const val NOTIFICATION_ID = 1395
private companion object {
const val CHANNEL_ID = "call_foreground"
const val NOTIFICATION_ID = 1395
const val TAG = "CallForegroundService"
}
}
@@ -1,6 +1,8 @@
package moe.sable.client
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.media.AudioAttributes
import android.media.MediaPlayer
@@ -175,6 +177,22 @@ class MainActivity : TauriActivity() {
}
}
@JvmStatic
fun startCallForegroundServiceNative() {
val activity = checkNotNull(instance) { "MainActivity is unavailable" }
check(
ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED
) { "Microphone permission is not granted" }
ContextCompat.startForegroundService(activity, Intent(activity, CallForegroundService::class.java))
}
@JvmStatic
fun stopCallForegroundServiceNative() {
val activity = checkNotNull(instance) { "MainActivity is unavailable" }
activity.stopService(Intent(activity, CallForegroundService::class.java))
}
private fun isLight(color: Int): Boolean {
val luminance =
(0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255.0
@@ -210,23 +228,5 @@ class MainActivity : TauriActivity() {
}
}
@JvmStatic
fun startCallForegroundServiceNative() {
val activity = instance ?: return
activity.runOnUiThread {
ContextCompat.startForegroundService(
activity,
Intent(activity, CallForegroundService::class.java)
)
}
}
@JvmStatic
fun stopCallForegroundServiceNative() {
val activity = instance ?: return
activity.runOnUiThread {
activity.stopService(Intent(activity, CallForegroundService::class.java))
}
}
}
}
+3
View File
@@ -92,6 +92,9 @@ targets:
properties:
LSRequiresIPhoneOS: true
UILaunchStoryboardName: LaunchScreen
UIBackgroundModes: [audio]
NSMicrophoneUsageDescription: Sable uses your microphone for calls.
NSCameraUsageDescription: Sable uses your camera for video calls.
UIRequiredDeviceCapabilities: [arm64, metal]
UISupportedInterfaceOrientations:
- UIInterfaceOrientationPortrait
+22
View File
@@ -9,6 +9,9 @@ use std::sync::OnceLock;
use objc2::rc::{Allocated, Retained};
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
use objc2::{msg_send, sel};
use objc2_avf_audio::{
AVAudioSession, AVAudioSessionCategoryOptions, AVAudioSessionCategoryPlayAndRecord,
};
use tauri::webview::WebviewWindow;
extern "C-unwind" fn input_accessory_view_nil(_this: &AnyObject, _cmd: Sel) -> *mut AnyObject {
@@ -56,6 +59,25 @@ pub fn haptic_feedback(style: String) {
}
}
#[tauri::command]
pub fn activate_call_audio_session() -> Result<(), String> {
let session = unsafe { AVAudioSession::sharedInstance() };
unsafe {
session.setCategory_withOptions_error(
AVAudioSessionCategoryPlayAndRecord.expect("PlayAndRecord category is unavailable"),
AVAudioSessionCategoryOptions::DefaultToSpeaker,
)
}
.map_err(|error| error.to_string())?;
unsafe { session.setActive_error(true) }.map_err(|error| error.to_string())
}
#[tauri::command]
pub fn deactivate_call_audio_session() -> Result<(), String> {
let session = unsafe { AVAudioSession::sharedInstance() };
unsafe { session.setActive_error(false) }.map_err(|error| error.to_string())
}
pub fn hide_form_accessory_bar(window: &WebviewWindow<crate::BrowserEngine>) {
let _ = window.with_webview(|webview| unsafe {
let webview: *mut AnyObject = webview.inner().cast();
+4
View File
@@ -447,6 +447,10 @@ pub fn run() {
ios::haptic_feedback,
#[cfg(any(target_os = "android", target_os = "ios"))]
play_notification_sound,
#[cfg(target_os = "ios")]
ios::activate_call_audio_session,
#[cfg(target_os = "ios")]
ios::deactivate_call_audio_session,
#[cfg(desktop)]
desktop::download::save_download,
#[cfg(desktop)]
+17 -1
View File
@@ -1,7 +1,7 @@
/**
* Auto-generated TypeScript bindings for Tauri commands
* Generated by tauri-typegen v0.5.0
* Generated at: 2026-07-27T14:52:10.696863893+00:00
* Generated at: 2026-07-29T09:24:56.411984+00:00
* Generator: none
*
* Do not edit manually - regenerate using: cargo tauri-typegen generate
@@ -18,10 +18,18 @@ export async function abortNativeUpload(params: types.AbortNativeUploadParams):
return invoke('abort_native_upload', params);
}
export async function activateCallAudioSession(): Promise<void> {
return invoke('activate_call_audio_session');
}
export async function clearMediaSession(): Promise<void> {
return invoke('clear_media_session');
}
export async function deactivateCallAudioSession(): Promise<void> {
return invoke('deactivate_call_audio_session');
}
export async function exportDiagnostics(params: types.ExportDiagnosticsParams): Promise<string | null> {
return invoke('export_diagnostics', params);
}
@@ -98,10 +106,18 @@ export async function showSnapOverlay(): Promise<void> {
return invoke('show_snap_overlay');
}
export async function startCallForegroundService(): Promise<void> {
return invoke('start_call_foreground_service');
}
export async function startWindowTrackingWithTarget(params: types.StartWindowTrackingWithTargetParams): Promise<void> {
return invoke('start_window_tracking_with_target', params);
}
export async function stopCallForegroundService(): Promise<void> {
return invoke('stop_call_foreground_service');
}
export async function stopWindowTracking(): Promise<void> {
return invoke('stop_window_tracking');
}
+1 -1
View File
@@ -1,7 +1,7 @@
/**
* Auto-generated TypeScript bindings for Tauri commands
* Generated by tauri-typegen v0.5.0
* Generated at: 2026-07-26T18:31:24.510042400+00:00
* Generated at: 2026-07-29T09:24:56.415138+00:00
* Generator: none
*
* Do not edit manually - regenerate using: cargo tauri-typegen generate
+1 -1
View File
@@ -1,7 +1,7 @@
/**
* Auto-generated TypeScript bindings for Tauri commands
* Generated by tauri-typegen v0.5.0
* Generated at: 2026-07-26T18:31:24.510311700+00:00
* Generated at: 2026-07-29T09:24:56.415651+00:00
* Generator: none
*
* Do not edit manually - regenerate using: cargo tauri-typegen generate
+1 -1
View File
@@ -1,7 +1,7 @@
/**
* Auto-generated TypeScript bindings for Tauri commands
* Generated by tauri-typegen v0.5.0
* Generated at: 2026-07-26T18:31:24.507322700+00:00
* Generated at: 2026-07-29T09:24:56.409726+00:00
* Generator: none
*
* Do not edit manually - regenerate using: cargo tauri-typegen generate
+46 -8
View File
@@ -11,7 +11,7 @@ import {
} from 'matrix-widget-api';
import { CallWidgetDriver } from './CallWidgetDriver';
import { trimTrailingSlash } from '../../utils/common';
import { getWindowOrigin, isAndroidTauri } from '../../utils/platform';
import { getWindowOrigin, iosApp, isAndroidTauri } from '../../utils/platform';
import type { ElementCallThemeKind, ElementMediaStateDetail } from './types';
import { color, config } from 'folds';
import { ElementCallIntent, ElementWidgetActions } from './types';
@@ -46,6 +46,10 @@ export class CallEmbed {
public joined = false;
private initialMediaStateReceived = false;
private nativeCallRuntimeActive = false;
public readonly control: CallControl;
private readonly container: HTMLElement;
@@ -230,7 +234,9 @@ export class CallEmbed {
this.call.transport.reply(evt.detail as IWidgetApiRequest, {});
if (initialMediaEvent) {
initialMediaEvent = false;
this.initialMediaStateReceived = true;
this.control.applyState();
this.startNativeCallRuntime();
return;
}
this.control.onMediaState(evt as CustomEvent<ElementMediaStateDetail>);
@@ -356,7 +362,22 @@ export class CallEmbed {
*/
public dispose(): void {
debugLog.info('call', 'Disposing call widget', { roomId: this.roomId });
this.invokeForegroundService('stop_call_foreground_service');
if (this.nativeCallRuntimeActive && isAndroidTauri()) {
void invoke('stop_call_foreground_service').catch((error) => {
debugLog.error('call', 'Failed to stop call foreground service', {
roomId: this.roomId,
error: error instanceof Error ? error.message : String(error),
});
});
} else if (this.nativeCallRuntimeActive && iosApp()) {
void invoke('deactivate_call_audio_session').catch((error) => {
debugLog.error('call', 'Failed to deactivate call audio session', {
roomId: this.roomId,
error: error instanceof Error ? error.message : String(error),
});
});
}
this.nativeCallRuntimeActive = false;
this.disposables.forEach((disposable) => {
disposable();
});
@@ -375,16 +396,33 @@ export class CallEmbed {
this.call.transport.reply(evt.detail as IWidgetApiRequest, {});
debugLog.info('call', 'Call joined', { roomId: this.roomId });
this.joined = true;
this.invokeForegroundService('start_call_foreground_service');
this.startNativeCallRuntime();
this.applyStyles();
this.control.startObserving();
}
private invokeForegroundService(
command: 'start_call_foreground_service' | 'stop_call_foreground_service'
): void {
if (!isAndroidTauri()) return;
void invoke(command).catch(() => {});
private startNativeCallRuntime(): void {
if (!this.joined || !this.initialMediaStateReceived || this.nativeCallRuntimeActive) return;
if (isAndroidTauri()) {
this.nativeCallRuntimeActive = true;
void invoke('start_call_foreground_service').catch((error) => {
this.nativeCallRuntimeActive = false;
debugLog.error('call', 'Failed to start call foreground service', {
roomId: this.roomId,
error: error instanceof Error ? error.message : String(error),
});
});
} else if (iosApp()) {
this.nativeCallRuntimeActive = true;
void invoke('activate_call_audio_session').catch((error) => {
this.nativeCallRuntimeActive = false;
debugLog.error('call', 'Failed to activate call audio session', {
roomId: this.roomId,
error: error instanceof Error ? error.message : String(error),
});
});
}
}
private applyStyles(): void {