Skip to content

Send files directly between devices over the internet - no cloud storage, no size limits.

Add background transfer/send mode for android (#80)

Denis Lupookovb6487041a45a
diff --git a/apps/mobile/app.json b/apps/mobile/app.json
index 371de79..5c4796a 100644
--- a/apps/mobile/app.json
+++ b/apps/mobile/app.json
@@ -65,6 +65,9 @@
"android.permission.ACCESS_NETWORK_STATE",
"android.permission.ACCESS_WIFI_STATE",
"android.permission.CHANGE_WIFI_MULTICAST_STATE",
+ "android.permission.FOREGROUND_SERVICE",
+ "android.permission.FOREGROUND_SERVICE_DATA_SYNC",
+ "android.permission.POST_NOTIFICATIONS",
"android.permission.WAKE_LOCK"
],
"blockedPermissions": [
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index 53c187a..f5822bf 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -32,12 +32,13 @@ import { PairRequestBanner } from '../src/components/PairRequestBanner'
import { InviteBanner } from '../src/components/InviteBanner'
import { useAlterSendFonts } from '../src/theme/useAlterSendFonts'
import { startAppStateBridge } from '../src/lifecycle/appStateBridge'
+import { startBackgroundTransferService } from '../src/lifecycle/backgroundTransferService'
import { startDeepLinkHandler } from '../src/lifecycle/deepLinkHandler'
import { getSavedLocalePreference } from '../src/lifecycle/localePreferenceStorage'
import { isRelayEnabled } from '../src/lifecycle/relayStorage'
import { getMobileSystemLocales } from '../src/lifecycle/systemLocale'
import { ShareIntentHandler } from '../src/lifecycle/ShareIntentHandler'
-import { startPhotosCopyEffect } from '../src/transfer/receive'
+import { startDownloadRoutingEffect } from '../src/transfer/receive'
import { initSentry, captureException } from '../src/sentry'
SplashScreen.preventAutoHideAsync().catch(() => {})
@@ -52,7 +53,8 @@ mobileApi.worker
startAppStateBridge()
startPeerWatchdog()
startBackgroundReconnectEffect()
-startPhotosCopyEffect()
+startBackgroundTransferService()
+startDownloadRoutingEffect()
startDeepLinkHandler()
function MobileCrashScreen({ error, onRestart }: { error: Error; onRestart: () => void }) {
diff --git a/apps/mobile/modules/transfer-service/android/build.gradle b/apps/mobile/modules/transfer-service/android/build.gradle
new file mode 100644
index 0000000..2a1fd5e
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/android/build.gradle
@@ -0,0 +1,15 @@
+plugins {
+ id 'com.android.library'
+ id 'expo-module-gradle-plugin'
+}
+
+group = 'expo.modules'
+version = '1.0.0'
+
+android {
+ namespace "expo.modules.transferservice"
+ defaultConfig {
+ versionCode 1
+ versionName "1.0.0"
+ }
+}
diff --git a/apps/mobile/modules/transfer-service/android/src/main/AndroidManifest.xml b/apps/mobile/modules/transfer-service/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..2f399c4
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/android/src/main/AndroidManifest.xml
@@ -0,0 +1,15 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
+ <uses-permission android:name="android.permission.WAKE_LOCK"/>
+
+ <application>
+ <service
+ android:name="expo.modules.transferservice.TransferForegroundService"
+ android:enabled="true"
+ android:exported="false"
+ android:stopWithTask="true"
+ android:foregroundServiceType="dataSync"/>
+ </application>
+</manifest>
diff --git a/apps/mobile/modules/transfer-service/android/src/main/java/expo/modules/transferservice/TransferForegroundService.kt b/apps/mobile/modules/transfer-service/android/src/main/java/expo/modules/transferservice/TransferForegroundService.kt
new file mode 100644
index 0000000..7db7030
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/android/src/main/java/expo/modules/transferservice/TransferForegroundService.kt
@@ -0,0 +1,129 @@
+package expo.modules.transferservice
+
+import android.app.Service
+import android.content.Intent
+import android.content.pm.ServiceInfo
+import android.os.Build
+import android.os.Handler
+import android.os.IBinder
+import android.os.Looper
+import android.os.PowerManager
+import android.util.Log
+
+private const val LOG_TAG = "TransferService"
+private const val WAKE_LOCK_TAG = "AlterSend:transfer"
+private const val WAKE_LOCK_TIMEOUT_MS = 6L * 60 * 60 * 1000
+private const val IDLE_TIMEOUT_MS = 15L * 60 * 1000
+private const val TRANSFERRING_TIMEOUT_MS = 60L * 60 * 1000
+
+class TransferForegroundService : Service() {
+ private var wakeLock: PowerManager.WakeLock? = null
+ private val watchdog = Handler(Looper.getMainLooper())
+ private val stopWhenIdle = Runnable { stopSelf() }
+
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ val notifications = TransferNotification(this)
+ notifications.ensureChannel(intent?.getStringExtra(EXTRA_CHANNEL_NAME).orEmpty())
+
+ val notification = notifications.build(
+ intent?.getStringExtra(EXTRA_TITLE).orEmpty(),
+ intent?.getStringExtra(EXTRA_TEXT).orEmpty(),
+ intent?.getStringExtra(EXTRA_SUBTEXT).orEmpty(),
+ intent?.getIntExtra(EXTRA_PROGRESS, INDETERMINATE_PROGRESS) ?: INDETERMINATE_PROGRESS
+ )
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
+ startForeground(
+ TransferNotification.NOTIFICATION_ID,
+ notification,
+ ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
+ )
+ } else {
+ startForeground(TransferNotification.NOTIFICATION_ID, notification)
+ }
+
+ instance = this
+ isRunning = true
+ if (pendingTransferring) acquireWakeLock()
+ armStop(livenessTimeout())
+ return START_NOT_STICKY
+ }
+
+ private fun armStop(delayMs: Long) {
+ watchdog.post {
+ watchdog.removeCallbacks(stopWhenIdle)
+ watchdog.postDelayed(stopWhenIdle, delayMs)
+ }
+ }
+
+ override fun onTimeout(startId: Int, fgsType: Int) {
+ stopSelf()
+ }
+
+ override fun onDestroy() {
+ isRunning = false
+ instance = null
+ pendingTransferring = false
+ watchdog.removeCallbacks(stopWhenIdle)
+ releaseWakeLock()
+ try {
+ onStopped?.invoke()
+ } catch (err: Exception) {
+ Log.w(LOG_TAG, "failed to report service stop", err)
+ }
+ super.onDestroy()
+ }
+
+ private fun acquireWakeLock() {
+ if (wakeLock?.isHeld == true) return
+ val power = getSystemService(PowerManager::class.java) ?: return
+ wakeLock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG).apply {
+ setReferenceCounted(false)
+ acquire(WAKE_LOCK_TIMEOUT_MS)
+ }
+ }
+
+ private fun releaseWakeLock() {
+ if (wakeLock?.isHeld == true) wakeLock?.release()
+ wakeLock = null
+ }
+
+ companion object {
+ const val EXTRA_TITLE = "title"
+ const val EXTRA_TEXT = "text"
+ const val EXTRA_SUBTEXT = "subText"
+ const val EXTRA_PROGRESS = "progress"
+ const val EXTRA_CHANNEL_NAME = "channelName"
+ const val INDETERMINATE_PROGRESS = -1
+
+ @Volatile
+ var isRunning = false
+
+ @Volatile
+ var onStopped: (() -> Unit)? = null
+
+ @Volatile
+ private var instance: TransferForegroundService? = null
+
+ @Volatile
+ private var pendingTransferring = false
+
+ private fun livenessTimeout(): Long =
+ if (pendingTransferring) TRANSFERRING_TIMEOUT_MS else IDLE_TIMEOUT_MS
+
+ fun setTransferring(transferring: Boolean) {
+ pendingTransferring = transferring
+ val service = instance ?: return
+ if (transferring) service.acquireWakeLock() else service.releaseWakeLock()
+ service.armStop(livenessTimeout())
+ }
+
+ fun keepAlive() {
+ val service = instance ?: return
+ service.armStop(livenessTimeout())
+ if (pendingTransferring) service.acquireWakeLock()
+ }
+ }
+}
diff --git a/apps/mobile/modules/transfer-service/android/src/main/java/expo/modules/transferservice/TransferNotification.kt b/apps/mobile/modules/transfer-service/android/src/main/java/expo/modules/transferservice/TransferNotification.kt
new file mode 100644
index 0000000..af36639
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/android/src/main/java/expo/modules/transferservice/TransferNotification.kt
@@ -0,0 +1,90 @@
+package expo.modules.transferservice
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.os.Build
+
+class TransferNotification(private val context: Context) {
+ fun ensureChannel(channelName: String) {
+ val manager = context.getSystemService(NotificationManager::class.java) ?: return
+ val channel = NotificationChannel(
+ CHANNEL_ID,
+ channelName.ifEmpty { CHANNEL_ID },
+ NotificationManager.IMPORTANCE_LOW
+ ).apply {
+ setShowBadge(false)
+ enableVibration(false)
+ enableLights(false)
+ lockscreenVisibility = Notification.VISIBILITY_PRIVATE
+ }
+ manager.createNotificationChannel(channel)
+ }
+
+ fun build(title: String, text: String, subText: String, progress: Int): Notification {
+ val builder = Notification.Builder(context, CHANNEL_ID)
+ .setContentTitle(title)
+ .setContentText(text)
+ .setSmallIcon(R.drawable.ic_transfer_notification)
+ .setCategory(Notification.CATEGORY_PROGRESS)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .setShowWhen(false)
+
+ if (progress in 0..100) {
+ builder.setProgress(100, progress, false)
+ } else {
+ builder.setProgress(0, 0, true)
+ }
+
+ if (subText.isNotEmpty()) builder.setSubText(subText)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ builder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)
+ }
+ launchIntent()?.let { builder.setContentIntent(it) }
+
+ return builder.build()
+ }
+
+ fun buildCompleted(title: String, text: String): Notification {
+ val builder = Notification.Builder(context, CHANNEL_ID)
+ .setContentTitle(title)
+ .setSmallIcon(R.drawable.ic_transfer_notification)
+ .setCategory(Notification.CATEGORY_STATUS)
+ .setAutoCancel(true)
+ .setOnlyAlertOnce(true)
+
+ if (text.isNotEmpty()) builder.setContentText(text)
+ launchIntent()?.let { builder.setContentIntent(it) }
+
+ return builder.build()
+ }
+
+ private fun launchIntent(): PendingIntent? {
+ cachedLaunchIntent?.let { return it }
+
+ val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return null
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
+
+ val pending = PendingIntent.getActivity(
+ context,
+ 0,
+ intent,
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+ )
+ cachedLaunchIntent = pending
+ return pending
+ }
+
+ companion object {
+ const val CHANNEL_ID = "altersend.transfer"
+ const val NOTIFICATION_ID = 8341
+ const val COMPLETED_ID_BASE = 8400
+
+ @Volatile
+ private var cachedLaunchIntent: PendingIntent? = null
+ }
+}
diff --git a/apps/mobile/modules/transfer-service/android/src/main/java/expo/modules/transferservice/TransferNotificationContent.kt b/apps/mobile/modules/transfer-service/android/src/main/java/expo/modules/transferservice/TransferNotificationContent.kt
new file mode 100644
index 0000000..b80e330
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/android/src/main/java/expo/modules/transferservice/TransferNotificationContent.kt
@@ -0,0 +1,18 @@
+package expo.modules.transferservice
+
+import expo.modules.kotlin.records.Field
+import expo.modules.kotlin.records.Record
+
+class TransferNotificationContent : Record {
+ @Field
+ val title: String = ""
+
+ @Field
+ val text: String = ""
+
+ @Field
+ val subText: String = ""
+
+ @Field
+ val progress: Int = TransferForegroundService.INDETERMINATE_PROGRESS
+}
diff --git a/apps/mobile/modules/transfer-service/android/src/main/java/expo/modules/transferservice/TransferServiceModule.kt b/apps/mobile/modules/transfer-service/android/src/main/java/expo/modules/transferservice/TransferServiceModule.kt
new file mode 100644
index 0000000..09b46cf
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/android/src/main/java/expo/modules/transferservice/TransferServiceModule.kt
@@ -0,0 +1,91 @@
+package expo.modules.transferservice
+
+import android.annotation.SuppressLint
+import android.app.Notification
+import android.content.Context
+import android.content.Intent
+import androidx.core.app.NotificationManagerCompat
+import androidx.core.content.ContextCompat
+import expo.modules.kotlin.exception.Exceptions
+import expo.modules.kotlin.modules.Module
+import expo.modules.kotlin.modules.ModuleDefinition
+
+class TransferServiceModule : Module() {
+ override fun definition() = ModuleDefinition {
+ Name("TransferService")
+
+ Events(EVENT_STOPPED)
+
+ OnCreate {
+ TransferForegroundService.onStopped = { sendEvent(EVENT_STOPPED, mapOf<String, Any>()) }
+ }
+
+ OnDestroy {
+ TransferForegroundService.onStopped = null
+ }
+
+ AsyncFunction("start") { content: TransferNotificationContent, channelName: String ->
+ val context = requireContext()
+ val intent = Intent(context, TransferForegroundService::class.java).apply {
+ putExtra(TransferForegroundService.EXTRA_TITLE, content.title)
+ putExtra(TransferForegroundService.EXTRA_TEXT, content.text)
+ putExtra(TransferForegroundService.EXTRA_SUBTEXT, content.subText)
+ putExtra(TransferForegroundService.EXTRA_PROGRESS, content.progress)
+ putExtra(TransferForegroundService.EXTRA_CHANNEL_NAME, channelName)
+ }
+ ContextCompat.startForegroundService(context, intent)
+ }
+
+ AsyncFunction("update") { content: TransferNotificationContent ->
+ val context = requireContext()
+ if (TransferForegroundService.isRunning) {
+ TransferForegroundService.keepAlive()
+ post(context, content)
+ }
+ }
+
+ AsyncFunction("notifyCompleted") { title: String, text: String, channelName: String ->
+ val context = requireContext()
+ val manager = NotificationManagerCompat.from(context)
+ if (manager.areNotificationsEnabled()) {
+ val notifications = TransferNotification(context)
+ notifications.ensureChannel(channelName)
+ postCompleted(manager, notifications.buildCompleted(title, text))
+ }
+ }
+
+ AsyncFunction("setTransferring") { transferring: Boolean ->
+ TransferForegroundService.setTransferring(transferring)
+ }
+
+ AsyncFunction("stop") {
+ val context = requireContext()
+ context.stopService(Intent(context, TransferForegroundService::class.java))
+ NotificationManagerCompat.from(context).cancel(TransferNotification.NOTIFICATION_ID)
+ }
+ }
+
+ private fun requireContext(): Context =
+ appContext.reactContext ?: throw Exceptions.ReactContextLost()
+
+ @SuppressLint("MissingPermission")
+ private fun post(context: Context, content: TransferNotificationContent) {
+ val manager = NotificationManagerCompat.from(context)
+ if (!manager.areNotificationsEnabled()) return
+ manager.notify(
+ TransferNotification.NOTIFICATION_ID,
+ TransferNotification(context).build(content.title, content.text, content.subText, content.progress)
+ )
+ }
+
+ @SuppressLint("MissingPermission")
+ private fun postCompleted(manager: NotificationManagerCompat, notification: Notification) {
+ manager.notify(TransferNotification.COMPLETED_ID_BASE + completedCount++, notification)
+ }
+
+ private var completedCount = 0
+
+ private companion object {
+ const val EVENT_STOPPED = "onStopped"
+ }
+}
diff --git a/apps/mobile/modules/transfer-service/android/src/main/res/drawable/ic_transfer_notification.xml b/apps/mobile/modules/transfer-service/android/src/main/res/drawable/ic_transfer_notification.xml
new file mode 100644
index 0000000..2d3b7b1
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/android/src/main/res/drawable/ic_transfer_notification.xml
@@ -0,0 +1,9 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFFFF"
+ android:pathData="M16,17.01V10h-2v7.01h-3L15,21l4,-3.99h-3zM9,3L5,6.99h3V14h2V6.99h3L9,3z"/>
+</vector>
diff --git a/apps/mobile/modules/transfer-service/expo-module.config.json b/apps/mobile/modules/transfer-service/expo-module.config.json
new file mode 100644
index 0000000..148026e
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/expo-module.config.json
@@ -0,0 +1,6 @@
+{
+ "platforms": ["android"],
+ "android": {
+ "modules": ["expo.modules.transferservice.TransferServiceModule"]
+ }
+}
diff --git a/apps/mobile/modules/transfer-service/index.ts b/apps/mobile/modules/transfer-service/index.ts
new file mode 100644
index 0000000..00263fe
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/index.ts
@@ -0,0 +1,11 @@
+export {
+ INDETERMINATE_PROGRESS,
+ isTransferServiceAvailable,
+ notifyTransferCompleted,
+ onTransferServiceStopped,
+ setTransferServiceTransferring,
+ startTransferService,
+ stopTransferService,
+ updateTransferService,
+ type TransferNotificationContent
+} from './src/TransferServiceModule'
diff --git a/apps/mobile/modules/transfer-service/package.json b/apps/mobile/modules/transfer-service/package.json
new file mode 100644
index 0000000..89944c5
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/package.json
@@ -0,0 +1,5 @@
+{
+ "name": "transfer-service",
+ "version": "1.0.0",
+ "main": "index.ts"
+}
diff --git a/apps/mobile/modules/transfer-service/src/TransferServiceModule.ts b/apps/mobile/modules/transfer-service/src/TransferServiceModule.ts
new file mode 100644
index 0000000..c3db780
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/src/TransferServiceModule.ts
@@ -0,0 +1,62 @@
+import { requireOptionalNativeModule } from 'expo-modules-core'
+
+export const INDETERMINATE_PROGRESS = -1
+
+export interface TransferNotificationContent {
+ title: string
+ text: string
+ subText: string
+ progress: number
+}
+
+interface TransferServiceNativeModule {
+ start(content: TransferNotificationContent, channelName: string): Promise<void>
+ update(content: TransferNotificationContent): Promise<void>
+ notifyCompleted(title: string, text: string, channelName: string): Promise<void>
+ setTransferring(transferring: boolean): Promise<void>
+ stop(): Promise<void>
+ addListener(event: 'onStopped', listener: () => void): { remove: () => void }
+}
+
+const nativeModule = requireOptionalNativeModule<TransferServiceNativeModule>('TransferService')
+
+function withModule(call: (module: TransferServiceNativeModule) => Promise<void>): Promise<void> {
+ return nativeModule ? call(nativeModule) : Promise.resolve()
+}
+
+export function isTransferServiceAvailable(): boolean {
+ return nativeModule != null
+}
+
+export function startTransferService(
+ content: TransferNotificationContent,
+ channelName: string
+): Promise<void> {
+ return withModule((module) => module.start(content, channelName))
+}
+
+export function updateTransferService(content: TransferNotificationContent): Promise<void> {
+ return withModule((module) => module.update(content))
+}
+
+export function notifyTransferCompleted(
+ title: string,
+ text: string,
+ channelName: string
+): Promise<void> {
+ return withModule((module) => module.notifyCompleted(title, text, channelName))
+}
+
+export function setTransferServiceTransferring(transferring: boolean): Promise<void> {
+ return withModule((module) => module.setTransferring(transferring))
+}
+
+export function stopTransferService(): Promise<void> {
+ return withModule((module) => module.stop())
+}
+
+export function onTransferServiceStopped(listener: () => void): () => void {
+ if (!nativeModule) return () => {}
+ const subscription = nativeModule.addListener('onStopped', listener)
+ return () => subscription.remove()
+}
diff --git a/apps/mobile/src/api/mobileApi.ts b/apps/mobile/src/api/mobileApi.ts
index be0ae62..bbad6d6 100644
--- a/apps/mobile/src/api/mobileApi.ts
+++ b/apps/mobile/src/api/mobileApi.ts
@@ -7,10 +7,11 @@ import {
type TransferWorkerProcess,
type WorkerClient
} from '@altersend/core'
+import { isBackgroundTransferActive } from '@altersend/domain'
import Constants from 'expo-constants'
import { Directory, Paths } from 'expo-file-system'
import * as SecureStore from 'expo-secure-store'
-import { Platform } from 'react-native'
+import { AppState, Platform, type AppStateStatus } from 'react-native'
import { Worklet } from 'react-native-bare-kit'
import { isRelayEnabled } from '../lifecycle/relayStorage'
@@ -74,8 +75,14 @@ async function getWorkletArgs() {
return args
}
+type StatefulWorklet = Worklet & {
+ readonly started: boolean
+ readonly terminated: boolean
+ readonly suspended: boolean
+}
+
class MobileApi {
- private worklet: Worklet | null = null
+ private worklet: StatefulWorklet | null = null
private client: WorkerClient | null = null
private startPromise: Promise<void> | null = null
private readonly eventListeners = new Set<(event: RendererTransferEvent) => void>()
@@ -97,7 +104,8 @@ class MobileApi {
}
this.startPromise = (async () => {
- this.worklet = new Worklet()
+ this.worklet = new Worklet() as StatefulWorklet
+ this.worklet.update = (state) => this.applyWorkletLifecycle(state)
const source = Platform.select({
// eslint-disable-next-line @typescript-eslint/no-require-imports -- Metro resolves require() of bundle files to runtime resource IDs; ES6 import changes semantics
@@ -144,6 +152,31 @@ class MobileApi {
return this.startPromise
}
+ syncWorkletLifecycle = () => {
+ this.applyWorkletLifecycle(AppState.currentState)
+ }
+
+ resumeWorklet = () => {
+ const worklet = this.worklet
+ if (!worklet?.started || worklet.terminated) return
+ worklet.resume()
+ }
+
+ private applyWorkletLifecycle(state: AppStateStatus = AppState.currentState): void {
+ const worklet = this.worklet
+ if (!worklet?.started || worklet.terminated) return
+
+ if (state === 'active') {
+ worklet.resume()
+ return
+ }
+
+ if (state !== 'background' || worklet.suspended) return
+ if (isBackgroundTransferActive()) return
+
+ worklet.suspend()
+ }
+
onTransferEvent = (cb: (message: RendererTransferEvent) => void) => {
this.eventListeners.add(cb)
return () => {
diff --git a/apps/mobile/src/lifecycle/backgroundTransferNotification.ts b/apps/mobile/src/lifecycle/backgroundTransferNotification.ts
new file mode 100644
index 0000000..871ebe2
--- /dev/null
+++ b/apps/mobile/src/lifecycle/backgroundTransferNotification.ts
@@ -0,0 +1,106 @@
+import {
+ countSharedFiles,
+ formatFileSize,
+ formatItemsCount,
+ formatTransferRate,
+ getTransferRate,
+ type DownloadItemState,
+ type RateSample,
+ type SenderUploadItem,
+ type TransferActivity
+} from '@altersend/domain'
+import { translate } from '@altersend/locales'
+import {
+ INDETERMINATE_PROGRESS,
+ type TransferNotificationContent
+} from '@/modules/transfer-service'
+
+export interface CompletionNotification {
+ title: string
+ text: string
+}
+
+export function getChannelName(): string {
+ return translate('common:backgroundTransfer.channelName')
+}
+
+function describeItems(files: number, texts: number, bytes: number): string {
+ const label = formatItemsCount(files, texts, translate)
+ return bytes > 0 ? `${label} · ${formatFileSize(bytes)}` : label
+}
+
+export function buildSentNotification(
+ device: string | undefined,
+ items: SenderUploadItem[]
+): CompletionNotification {
+ const files = countSharedFiles(items)
+ const texts = items.length - files
+ const bytes = items.reduce((sum, item) => sum + (item.size ?? 0), 0)
+
+ return {
+ title: translate('common:backgroundTransfer.sentTo', {
+ device: device ?? translate('common:backgroundTransfer.someDevice')
+ }),
+ text: describeItems(files, texts, bytes)
+ }
+}
+
+export function buildReceivedNotification(
+ states: Record<string, DownloadItemState>,
+ bytes: number
+): CompletionNotification {
+ const saved = Object.values(states).filter((item) => item.status === 'completed').length
+ return {
+ title: translate('common:backgroundTransfer.received'),
+ text: describeItems(saved, 0, bytes)
+ }
+}
+
+function getTitle(activity: TransferActivity): string {
+ if (activity.phase === 'preparing') return translate('common:backgroundTransfer.preparing')
+ if (activity.role === 'sender') return translate('common:backgroundTransfer.sending')
+ return translate('common:backgroundTransfer.receiving')
+}
+
+function getWaitingText(activity: TransferActivity): string {
+ if (activity.receivedPeers.length > 0) {
+ return translate('common:backgroundTransfer.devicesReceived', {
+ count: activity.receivedPeers.length
+ })
+ }
+ if (activity.deviceCount > 0) {
+ return translate('common:backgroundTransfer.devicesConnected', { count: activity.deviceCount })
+ }
+ return translate('common:backgroundTransfer.waiting')
+}
+
+export function buildTransferNotification(
+ activity: TransferActivity,
+ samples: RateSample[]
+): TransferNotificationContent {
+ const title = getTitle(activity)
+
+ if (activity.phase === 'preparing') {
+ return { title, text: '', subText: '', progress: INDETERMINATE_PROGRESS }
+ }
+
+ if (activity.phase === 'waiting') {
+ return { title, text: getWaitingText(activity), subText: '', progress: INDETERMINATE_PROGRESS }
+ }
+
+ const rate = getTransferRate(samples, {
+ bytesTransferred: activity.bytesTransferred,
+ totalBytes: activity.totalBytes
+ })
+
+ return {
+ title,
+ text: translate('common:backgroundTransfer.progress', {
+ percent: activity.percent,
+ transferred: formatFileSize(activity.bytesTransferred),
+ total: formatFileSize(activity.totalBytes)
+ }),
+ subText: formatTransferRate(rate, translate) ?? '',
+ progress: activity.percent
+ }
+}
diff --git a/apps/mobile/src/lifecycle/backgroundTransferService.ts b/apps/mobile/src/lifecycle/backgroundTransferService.ts
new file mode 100644
index 0000000..8ef4996
--- /dev/null
+++ b/apps/mobile/src/lifecycle/backgroundTransferService.ts
@@ -0,0 +1,191 @@
+import {
+ getTransferActivity,
+ pushRateSample,
+ setBackgroundTransferActive,
+ transferStore,
+ type RateSample,
+ type TransferActivity,
+ type TransferSessionState
+} from '@altersend/domain'
+import { AppState, PermissionsAndroid, Platform } from 'react-native'
+import {
+ isTransferServiceAvailable,
+ notifyTransferCompleted,
+ onTransferServiceStopped,
+ setTransferServiceTransferring,
+ startTransferService,
+ stopTransferService,
+ updateTransferService
+} from '@/modules/transfer-service'
+import { mobileApi } from '../api/mobileApi'
+import { captureIn } from '../sentry'
+import {
+ buildReceivedNotification,
+ buildSentNotification,
+ buildTransferNotification,
+ getChannelName,
+ type CompletionNotification
+} from './backgroundTransferNotification'
+
+const MIN_UPDATE_INTERVAL_MS = 200
+const RATE_REFRESH_INTERVAL_MS = 1000
+const NOTIFICATION_PERMISSION_SDK = 33
+
+interface TransferSession {
+ lastUpdatedAt: number
+ lastStatus: string
+ lastPercent: number
+ lastPhase: TransferActivity['phase']
+ announced: Set<string>
+ samples: RateSample[]
+}
+
+function statusOf(activity: TransferActivity): string {
+ return [activity.phase, activity.role, activity.deviceCount, activity.receivedPeers.length].join(
+ ':'
+ )
+}
+
+let started = false
+let permissionRequested = false
+let session: TransferSession | null = null
+
+const report = (context: string) => captureIn(`backgroundTransferService.${context}`)
+
+async function requestNotificationPermission(): Promise<void> {
+ if (permissionRequested) return
+
+ const version = Platform.Version
+ if (typeof version === 'number' && version < NOTIFICATION_PERMISSION_SDK) return
+ if (AppState.currentState !== 'active') return
+
+ permissionRequested = true
+ await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS)
+}
+
+function begin(activity: TransferActivity, now: number): void {
+ const current: TransferSession = {
+ lastUpdatedAt: now,
+ lastStatus: statusOf(activity),
+ lastPercent: activity.percent,
+ lastPhase: activity.phase,
+ announced: new Set(activity.receivedPeers),
+ samples: pushRateSample([], activity.bytesTransferred, now)
+ }
+ session = current
+ setBackgroundTransferActive(true)
+ mobileApi.resumeWorklet()
+
+ setTransferServiceTransferring(activity.phase === 'transferring').catch(report('setTransferring'))
+ requestNotificationPermission().catch(report('permission'))
+
+ startTransferService(
+ buildTransferNotification(activity, current.samples),
+ getChannelName()
+ ).catch((error: unknown) => {
+ report('start')(error)
+ if (session === current) end()
+ })
+}
+
+function shouldRepaint(current: TransferSession, activity: TransferActivity, now: number): boolean {
+ if (statusOf(activity) !== current.lastStatus) return true
+ if (activity.phase !== 'transferring') return false
+
+ const elapsed = now - current.lastUpdatedAt
+ if (elapsed < MIN_UPDATE_INTERVAL_MS) return false
+ return activity.percent !== current.lastPercent || elapsed >= RATE_REFRESH_INTERVAL_MS
+}
+
+function syncWakeLock(current: TransferSession, activity: TransferActivity): void {
+ if (activity.phase === current.lastPhase) return
+
+ current.lastPhase = activity.phase
+ setTransferServiceTransferring(activity.phase === 'transferring').catch(report('setTransferring'))
+}
+
+function update(current: TransferSession, activity: TransferActivity, now: number): void {
+ syncWakeLock(current, activity)
+
+ current.lastUpdatedAt = now
+ current.lastStatus = statusOf(activity)
+ current.lastPercent = activity.percent
+ current.samples = pushRateSample(current.samples, activity.bytesTransferred, now)
+
+ updateTransferService(buildTransferNotification(activity, current.samples)).catch(
+ report('update')
+ )
+}
+
+function postCompletion({ title, text }: CompletionNotification): void {
+ notifyTransferCompleted(title, text, getChannelName()).catch(report('notifyCompleted'))
+}
+
+function announceSent(
+ current: TransferSession,
+ activity: TransferActivity,
+ state: TransferSessionState
+): void {
+ for (const peerKey of activity.receivedPeers) {
+ if (current.announced.has(peerKey)) continue
+ current.announced.add(peerKey)
+
+ postCompletion(
+ buildSentNotification(state.remember.peerDisplayNames[peerKey], state.uploadItems)
+ )
+ }
+}
+
+function announceReceived(activity: TransferActivity, state: TransferSessionState): void {
+ if (activity.role !== 'receiver' || activity.active || !activity.settled) return
+ if (activity.bytesTransferred <= 0) return
+
+ postCompletion(buildReceivedNotification(state.receiveDownloadStates, activity.bytesTransferred))
+}
+
+function end(): void {
+ session = null
+ setBackgroundTransferActive(false)
+ stopTransferService().catch(report('stop'))
+ mobileApi.syncWorkletLifecycle()
+}
+
+function evaluate(now: number): void {
+ const state = transferStore.getState()
+ const activity = getTransferActivity(state)
+ const current = session
+
+ if (!current) {
+ if (activity.active) begin(activity, now)
+ return
+ }
+
+ announceSent(current, activity, state)
+
+ if (!activity.active) {
+ announceReceived(activity, state)
+ end()
+ return
+ }
+
+ if (shouldRepaint(current, activity, now)) update(current, activity, now)
+}
+
+export function startBackgroundTransferService(): () => void {
+ if (started || !isTransferServiceAvailable()) return () => {}
+ started = true
+
+ const unsubscribeStore = transferStore.subscribe(() => evaluate(Date.now()))
+ const appStateSubscription = AppState.addEventListener('change', () => evaluate(Date.now()))
+ const unsubscribeService = onTransferServiceStopped(() => {
+ if (session) end()
+ })
+
+ return () => {
+ started = false
+ unsubscribeStore()
+ appStateSubscription.remove()
+ unsubscribeService()
+ if (session) end()
+ }
+}
diff --git a/apps/mobile/src/sentry.ts b/apps/mobile/src/sentry.ts
index dbbddf7..95eefa3 100644
--- a/apps/mobile/src/sentry.ts
+++ b/apps/mobile/src/sentry.ts
@@ -45,5 +45,9 @@ export function closeSentry(): void {
export function captureException(error: unknown, context?: string): void {
if (!isCrashReportingEnabled()) return
- Sentry.captureException(error, context ? { data: { context } } : undefined)
+ Sentry.captureException(error, context ? { extra: { context } } : undefined)
+}
+
+export function captureIn(context: string): (error: unknown) => void {
+ return (error) => captureException(error, context)
}
diff --git a/apps/mobile/src/transfer/receive/index.ts b/apps/mobile/src/transfer/receive/index.ts
index 79282b3..341744f 100644
--- a/apps/mobile/src/transfer/receive/index.ts
+++ b/apps/mobile/src/transfer/receive/index.ts
@@ -6,4 +6,4 @@ export { ReceiveInterruptedView } from './views/ReceiveInterruptedView'
export { ReceiveJoinView } from './views/ReceiveJoinView'
export { ReceiveReconnectingView } from './views/ReceiveReconnectingView'
export { openCompletedFile } from './utils/openCompletedFile'
-export { startPhotosCopyEffect } from './utils/photosCopyEffect'
+export { startDownloadRoutingEffect } from './utils/downloadRoutingEffect'
diff --git a/apps/mobile/src/transfer/receive/utils/downloadRoutingEffect.ts b/apps/mobile/src/transfer/receive/utils/downloadRoutingEffect.ts
new file mode 100644
index 0000000..ab0a213
--- /dev/null
+++ b/apps/mobile/src/transfer/receive/utils/downloadRoutingEffect.ts
@@ -0,0 +1,121 @@
+import {
+ dispatchToTransferStore,
+ transferStore,
+ type DownloadItemState,
+ type SaveDestination,
+ type TransferAction
+} from '@altersend/domain'
+import type { IncomingFileOffer } from '@altersend/core'
+import { handleDownloadedFile } from './downloadHandlers'
+import { buildCompletionToast } from './completionToast'
+import { pushToast } from '@/src/components/Toast'
+
+const TOAST_FLUSH_DELAY_MS = 1500
+
+let processed = new Set<string>()
+let pendingDestinations: SaveDestination[] = []
+let flushTimer: ReturnType<typeof setTimeout> | null = null
+
+function flushNow(): void {
+ if (flushTimer) {
+ clearTimeout(flushTimer)
+ flushTimer = null
+ }
+ if (pendingDestinations.length === 0) return
+ const destinations = pendingDestinations
+ pendingDestinations = []
+ const toast = buildCompletionToast({ destinations })
+ if (toast) pushToast(toast)
+}
+
+function scheduleFlush(): void {
+ if (flushTimer) clearTimeout(flushTimer)
+ flushTimer = setTimeout(() => {
+ flushTimer = null
+ flushNow()
+ }, TOAST_FLUSH_DELAY_MS)
+}
+
+async function routeOne(offerKey: string, savedTo: string, fileName: string): Promise<void> {
+ const routing = await handleDownloadedFile(savedTo, fileName)
+ const action: TransferAction = {
+ type: 'download_routed',
+ offerKey,
+ destination: routing.destination,
+ intendedDestination: routing.intended,
+ savedTo: routing.localPath
+ }
+ dispatchToTransferStore(action)
+ pendingDestinations.push(routing.destination)
+ scheduleFlush()
+}
+
+let started = false
+let unsubscribe: (() => void) | null = null
+let lastStates: Record<string, DownloadItemState> | null = null
+let lastOffers: IncomingFileOffer[] | null = null
+let offersById = new Map<string, IncomingFileOffer>()
+
+function indexOffers(offers: IncomingFileOffer[]): void {
+ if (offers === lastOffers) return
+ lastOffers = offers
+ offersById = new Map(offers.map((offer) => [offer.id, offer]))
+}
+
+function reset(): void {
+ lastStates = null
+ lastOffers = null
+ offersById = new Map()
+ processed = new Set()
+}
+
+function evaluate(state: ReturnType<typeof transferStore.getState>): void {
+ const { receiveDownloadStates, incomingFileOffers } = state
+ if (receiveDownloadStates === lastStates) return
+ lastStates = receiveDownloadStates
+
+ const entries = Object.entries(receiveDownloadStates)
+ if (entries.length === 0) {
+ if (processed.size > 0) flushNow()
+ reset()
+ return
+ }
+
+ indexOffers(incomingFileOffers)
+
+ for (const [offerKey, item] of entries) {
+ if (processed.has(offerKey)) continue
+ if (item.status !== 'completed') continue
+ if (item.destination !== undefined || !item.savedTo) continue
+
+ const offer = offersById.get(offerKey)
+ if (offer?.kind !== 'file') continue
+
+ processed.add(offerKey)
+ routeOne(offerKey, item.savedTo, offer.name).catch((err: unknown) => {
+ console.error('downloadRoutingEffect: routing failed for', offerKey, err)
+ })
+ }
+}
+
+function teardown(): void {
+ started = false
+ if (flushTimer) {
+ clearTimeout(flushTimer)
+ flushTimer = null
+ }
+ pendingDestinations = []
+ reset()
+ unsubscribe?.()
+ unsubscribe = null
+}
+
+export function startDownloadRoutingEffect(): () => void {
+ if (started) return teardown
+ started = true
+
+ evaluate(transferStore.getState())
+ unsubscribe = transferStore.subscribe(evaluate)
+
+ return teardown
+}
diff --git a/apps/mobile/src/transfer/receive/utils/photosCopyEffect.ts b/apps/mobile/src/transfer/receive/utils/photosCopyEffect.ts
deleted file mode 100644
index 88e5bf4..0000000
--- a/apps/mobile/src/transfer/receive/utils/photosCopyEffect.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import {
- dispatchToTransferStore,
- transferStore,
- type SaveDestination,
- type TransferAction
-} from '@altersend/domain'
-import { handleDownloadedFile } from './downloadHandlers'
-import { buildCompletionToast } from './completionToast'
-import { pushToast } from '@/src/components/Toast'
-
-const TOAST_FLUSH_DELAY_MS = 1500
-
-let processed = new Set<string>()
-let pendingDestinations: SaveDestination[] = []
-let flushTimer: ReturnType<typeof setTimeout> | null = null
-
-function flushNow(): void {
- if (flushTimer) {
- clearTimeout(flushTimer)
- flushTimer = null
- }
- if (pendingDestinations.length === 0) return
- const destinations = pendingDestinations
- pendingDestinations = []
- const toast = buildCompletionToast({ destinations })
- if (toast) pushToast(toast)
-}
-
-function scheduleFlush(): void {
- if (flushTimer) clearTimeout(flushTimer)
- flushTimer = setTimeout(() => {
- flushTimer = null
- flushNow()
- }, TOAST_FLUSH_DELAY_MS)
-}
-
-async function routeOne(offerKey: string, savedTo: string, fileName: string): Promise<void> {
- try {
- const routing = await handleDownloadedFile(savedTo, fileName)
- const action: TransferAction = {
- type: 'download_routed',
- offerKey,
- destination: routing.destination,
- intendedDestination: routing.intended,
- savedTo: routing.localPath
- }
- dispatchToTransferStore(action)
- pendingDestinations.push(routing.destination)
- scheduleFlush()
- } catch (err) {
- console.error('photosCopyEffect: routing failed for', offerKey, err)
- }
-}
-
-let started = false
-let unsubscribe: (() => void) | null = null
-
-export function startPhotosCopyEffect(): () => void {
- if (started) return unsubscribe ?? (() => {})
- started = true
-
- const evaluate = (state: ReturnType<typeof transferStore.getState>): void => {
- const { receiveDownloadStates, incomingFileOffers } = state
-
- if (Object.keys(receiveDownloadStates).length === 0) {
- if (processed.size > 0) {
- flushNow()
- processed = new Set()
- }
- return
- }
-
- for (const [offerKey, item] of Object.entries(receiveDownloadStates)) {
- if (item.status !== 'completed') continue
- if (item.destination !== undefined) continue
- if (processed.has(offerKey)) continue
- if (!item.savedTo) continue
-
- const offer = incomingFileOffers.find((f) => f.id === offerKey)
- if (offer?.kind !== 'file') continue
-
- processed.add(offerKey)
- void routeOne(offerKey, item.savedTo, offer.name)
- }
- }
-
- evaluate(transferStore.getState())
- unsubscribe = transferStore.subscribe(evaluate)
-
- return () => {
- started = false
- if (flushTimer) {
- clearTimeout(flushTimer)
- flushTimer = null
- }
- pendingDestinations = []
- processed = new Set()
- unsubscribe?.()
- unsubscribe = null
- }
-}
diff --git a/packages/domain/src/receive/downloadModel.ts b/packages/domain/src/receive/downloadModel.ts
index eb35bce..ccf5f76 100644
--- a/packages/domain/src/receive/downloadModel.ts
+++ b/packages/domain/src/receive/downloadModel.ts
@@ -1,6 +1,11 @@
import type { DownloadFileRequest, IncomingFileOffer, RendererTransferEvent } from '@altersend/core'
import { formatFileSize } from '../format'
-import { sumTransferRates, type TransferProgress, type TransferRate } from '../transfer/rate'
+import {
+ sumTransferRates,
+ toProgressPercent,
+ type TransferProgress,
+ type TransferRate
+} from '../transfer/rate'
export type DownloadStatus = 'idle' | 'downloading' | 'completed' | 'failed'
@@ -50,11 +55,6 @@ export function getOfferKey(file: IncomingFileOffer) {
return file.id
}
-function getProgressPercent(bytesTransferred: number, totalBytes: number) {
- if (totalBytes <= 0) return 0
- return Math.max(0, Math.min(100, Math.round((bytesTransferred / totalBytes) * 100)))
-}
-
function getRemainingBytes(
offers: IncomingFileOffer[],
states: Record<string, DownloadItemState>
@@ -118,7 +118,7 @@ export function getDownloadRowDisplay(
rateLabel?: string
): DownloadRowDisplay {
const totalBytes = state?.totalBytes || (file.kind === 'file' ? file.size : 0)
- const percent = getProgressPercent(state?.bytesTransferred ?? 0, totalBytes)
+ const percent = toProgressPercent(state?.bytesTransferred ?? 0, totalBytes)
const isCompleted = state?.status === 'completed'
const isActive = state?.status === 'downloading' && totalBytes > 0
@@ -434,7 +434,7 @@ export function getDownloadTotals(
bytesTransferred,
completedCount,
activeCount,
- percent: getProgressPercent(bytesTransferred, totalBytes)
+ percent: toProgressPercent(bytesTransferred, totalBytes)
}
}
diff --git a/packages/domain/src/send/shareModel.ts b/packages/domain/src/send/shareModel.ts
index 96925f1..0f1549b 100644
--- a/packages/domain/src/send/shareModel.ts
+++ b/packages/domain/src/send/shareModel.ts
@@ -1,4 +1,5 @@
import type { RendererTransferEvent } from '@altersend/core'
+import { toProgressPercent } from '../transfer/rate'
export interface PeerEvent {
id: string
@@ -94,7 +95,7 @@ export function applyPeerDownloadEvent(
}
}
-interface EventsSummary {
+export interface EventsSummary {
failed: PeerDownloadEvent | null
paused: PeerDownloadEvent | null
inFlight: PeerDownloadEvent | null
@@ -104,7 +105,7 @@ interface EventsSummary {
sumOfKnownTotals: number
}
-function summarizeEvents(events: PeerDownloadEvent[]): EventsSummary | null {
+export function summarizeEvents(events: PeerDownloadEvent[]): EventsSummary | null {
if (events.length === 0) return null
let failed: PeerDownloadEvent | null = null
@@ -190,9 +191,7 @@ export function derivePeerStatus(
if (inFlight) {
const totalForDisplay = expectedTotalBytes > 0 ? expectedTotalBytes : sumOfKnownTotals
const progressPercent =
- totalForDisplay > 0
- ? Math.max(0, Math.min(100, Math.round((transferredBytes / totalForDisplay) * 100)))
- : undefined
+ totalForDisplay > 0 ? toProgressPercent(transferredBytes, totalForDisplay) : undefined
return {
status: 'downloading',
completedCount,
diff --git a/packages/domain/src/transfer/activity.test.ts b/packages/domain/src/transfer/activity.test.ts
new file mode 100644
index 0000000..ec474db
--- /dev/null
+++ b/packages/domain/src/transfer/activity.test.ts
@@ -0,0 +1,354 @@
+import { describe, expect, it } from 'vitest'
+import type { IncomingFileOffer } from '@altersend/core'
+import { getTransferActivity } from './activity'
+import { initialTransferSessionState } from './reducer'
+import type { TransferSessionState } from './types'
+import type { DownloadItemState } from '../receive/downloadModel'
+import type { PeerDownloadEvent } from '../send/shareModel'
+
+const make = (overrides: Partial<TransferSessionState> = {}): TransferSessionState => ({
+ ...initialTransferSessionState,
+ ...overrides
+})
+
+const offer = (id: string, size = 1000): IncomingFileOffer => ({
+ id,
+ transferId: 'tx-1',
+ name: `${id}.bin`,
+ path: `/files/${id}.bin`,
+ size,
+ driveKey: 'drive-1',
+ kind: 'file'
+})
+
+const downloadState = (overrides: Partial<DownloadItemState> = {}): DownloadItemState => ({
+ status: 'idle',
+ bytesTransferred: 0,
+ totalBytes: 1000,
+ ...overrides
+})
+
+const peerEvent = (overrides: Partial<PeerDownloadEvent> = {}): PeerDownloadEvent => ({
+ id: 'peer-1:a',
+ peerKey: 'peer-1',
+ fileName: 'a.bin',
+ state: 'progress',
+ bytesTransferred: 500,
+ totalBytes: 1000,
+ updatedAt: 1,
+ ...overrides
+})
+
+describe('getTransferActivity', () => {
+ it('is idle without a role', () => {
+ expect(getTransferActivity(make()).active).toBe(false)
+ })
+
+ it('tracks receiver downloads in flight', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'receiver',
+ incomingFileOffers: [offer('a')],
+ receiveDownloadStates: {
+ a: downloadState({ status: 'downloading', bytesTransferred: 250 })
+ }
+ })
+ )
+
+ expect(activity.active).toBe(true)
+ expect(activity.role).toBe('receiver')
+ expect(activity.percent).toBe(25)
+ })
+
+ it('stays active between queued files so the service is not torn down mid-batch', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'receiver',
+ incomingFileOffers: [offer('a'), offer('b')],
+ receiveDownloadStates: {
+ a: downloadState({ status: 'completed', bytesTransferred: 1000 }),
+ b: downloadState({ queued: true })
+ }
+ })
+ )
+
+ expect(activity.active).toBe(true)
+ })
+
+ it('goes inactive once the receiver batch finishes and files are routed', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'receiver',
+ incomingFileOffers: [offer('a')],
+ receiveDownloadStates: {
+ a: downloadState({
+ status: 'completed',
+ bytesTransferred: 1000,
+ destination: 'filesystem'
+ })
+ }
+ })
+ )
+
+ expect(activity.active).toBe(false)
+ expect(activity.settled).toBe(true)
+ })
+
+ it('tracks sender uploads while a peer is downloading', () => {
+ const activity = getTransferActivity(
+ make({ role: 'sender', peerDownloads: { 'peer-1:a': peerEvent() } })
+ )
+
+ expect(activity.active).toBe(true)
+ expect(activity.role).toBe('sender')
+ expect(activity.percent).toBe(50)
+ })
+
+ it('measures a downloading peer against the whole share, not just its current file', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'sender',
+ uploadItems: [
+ { name: 'a', path: '/a', size: 1000, status: 'completed' },
+ { name: 'b', path: '/b', size: 1000, status: 'uploading' }
+ ],
+ peerDownloads: {
+ 'peer-1:a': peerEvent({ state: 'completed', bytesTransferred: 1000 }),
+ 'peer-1:b': peerEvent({ id: 'peer-1:b', fileName: 'b.bin', state: 'progress' })
+ }
+ })
+ )
+
+ expect(activity.phase).toBe('transferring')
+ expect(activity.percent).toBe(75)
+ })
+
+ it('scales the total by the number of peers actually downloading', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'sender',
+ connectedPeers: {
+ 'peer-1': { peerKey: 'peer-1', connectedAt: 1 },
+ 'peer-2': { peerKey: 'peer-2', connectedAt: 2 }
+ },
+ uploadItems: [{ name: 'a', path: '/a', size: 1000, status: 'uploading' }],
+ peerDownloads: {
+ 'peer-1:a': peerEvent(),
+ 'peer-2:a': peerEvent({ id: 'peer-2:a', peerKey: 'peer-2' })
+ }
+ })
+ )
+
+ expect(activity.deviceCount).toBe(2)
+ expect(activity.percent).toBe(50)
+ })
+
+ it('does not report a finished share as complete while still waiting for devices', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'sender',
+ draftPhase: 'ready',
+ connectedPeers: { 'peer-1': { peerKey: 'peer-1', connectedAt: 1 } },
+ uploadItems: [{ name: 'a', path: '/a', size: 1000, status: 'completed' }],
+ peerDownloads: {
+ 'peer-1:a': peerEvent({ state: 'completed', bytesTransferred: 1000 })
+ }
+ })
+ )
+
+ expect(activity.active).toBe(true)
+ expect(activity.phase).toBe('waiting')
+ expect(activity.deviceCount).toBe(1)
+ expect(activity.receivedPeers.length).toBe(1)
+ expect(activity.percent).toBe(0)
+ })
+
+ it('does not count a device that only received part of the share', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'sender',
+ draftPhase: 'ready',
+ uploadItems: [
+ { name: 'a', path: '/a', size: 1000, status: 'completed' },
+ { name: 'b', path: '/b', size: 1000, status: 'completed' }
+ ],
+ peerDownloads: {
+ 'peer-1:a': peerEvent({ state: 'completed', bytesTransferred: 1000 })
+ }
+ })
+ )
+
+ expect(activity.receivedPeers.length).toBe(0)
+ })
+
+ it('ignores text snippets when deciding a device received the share', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'sender',
+ draftPhase: 'ready',
+ uploadItems: [
+ { name: 'a', path: '/a', size: 1000, status: 'completed' },
+ { name: 'note', path: '/note', kind: 'text', content: 'hi', status: 'completed' }
+ ],
+ peerDownloads: {
+ 'peer-1:a': peerEvent({ state: 'completed', bytesTransferred: 1000 })
+ }
+ })
+ )
+
+ expect(activity.receivedPeers).toEqual(['peer-1'])
+ })
+
+ it('counts files with the same base name separately', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'sender',
+ draftPhase: 'ready',
+ uploadItems: [
+ { name: 'IMG.jpg', path: '/2024/IMG.jpg', size: 1000, status: 'completed' },
+ { name: 'IMG.jpg', path: '/2025/IMG.jpg', size: 1000, status: 'completed' }
+ ],
+ peerDownloads: {
+ 'peer-1:a': peerEvent({ state: 'completed', fileName: 'IMG.jpg' }),
+ 'peer-1:b': peerEvent({ id: 'peer-1:b', state: 'completed', fileName: 'IMG.jpg' })
+ }
+ })
+ )
+
+ expect(activity.receivedPeers).toEqual(['peer-1'])
+ })
+
+ it('stays in transferring between files rather than flipping to waiting', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'sender',
+ draftPhase: 'ready',
+ uploadItems: [
+ { name: 'a', path: '/a', size: 1000, status: 'completed' },
+ { name: 'b', path: '/b', size: 1000, status: 'uploading' }
+ ],
+ peerDownloads: {
+ 'peer-1:a': peerEvent({ state: 'completed', bytesTransferred: 1000 })
+ }
+ })
+ )
+
+ expect(activity.phase).toBe('transferring')
+ expect(activity.percent).toBe(50)
+ })
+
+ it('keeps the receiver active until saved files are routed', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'receiver',
+ incomingFileOffers: [offer('a')],
+ receiveDownloadStates: {
+ a: downloadState({ status: 'completed', bytesTransferred: 1000, savedTo: '/tmp/a' })
+ }
+ })
+ )
+
+ expect(activity.active).toBe(true)
+ })
+
+ it('leaves sender gaps unsettled so brief pauses keep the service alive', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'sender',
+ peerDownloads: {
+ 'peer-1:a': peerEvent({ state: 'completed', bytesTransferred: 1000 })
+ }
+ })
+ )
+
+ expect(activity.active).toBe(false)
+ expect(activity.settled).toBe(false)
+ })
+
+ it('leaves a failed receive unsettled so a reconnect has a grace window', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'receiver',
+ incomingFileOffers: [offer('a')],
+ receiveDownloadStates: {
+ a: downloadState({ status: 'failed', bytesTransferred: 400, resumable: true })
+ }
+ })
+ )
+
+ expect(activity.active).toBe(false)
+ expect(activity.settled).toBe(false)
+ })
+
+ it('never settles a sender that has no peer downloads yet', () => {
+ const activity = getTransferActivity(make({ role: 'sender' }))
+
+ expect(activity.active).toBe(false)
+ expect(activity.settled).toBe(false)
+ })
+
+ it('stays active while a share is published and waiting for a receiver', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'sender',
+ draftPhase: 'ready',
+ uploadItems: [{ name: 'a', path: '/a', size: 1000, status: 'completed' }]
+ })
+ )
+
+ expect(activity.active).toBe(true)
+ expect(activity.phase).toBe('waiting')
+ })
+
+ it('reports connected devices instead of progress when nobody is downloading', () => {
+ const activity = getTransferActivity(
+ make({
+ role: 'sender',
+ draftPhase: 'ready',
+ uploadItems: [{ name: 'a', path: '/a', size: 1000, status: 'completed' }],
+ connectedPeers: {
+ 'peer-1': { peerKey: 'peer-1', connectedAt: 1 },
+ 'peer-2': { peerKey: 'peer-2', connectedAt: 2, disconnectedAt: 3 }
+ }
+ })
+ )
+
+ expect(activity.active).toBe(true)
+ expect(activity.phase).toBe('waiting')
+ expect(activity.deviceCount).toBe(1)
+ })
+
+ it('does not keep a text-only share alive, since nothing is downloaded', () => {
+ const items = [
+ { name: 'note', path: '/note', kind: 'text' as const, status: 'completed' as const }
+ ]
+
+ expect(getTransferActivity(make({ draftPhase: 'preparing', uploadItems: items })).active).toBe(
+ false
+ )
+ expect(
+ getTransferActivity(make({ role: 'sender', draftPhase: 'ready', uploadItems: items })).active
+ ).toBe(false)
+ })
+
+ it('goes inactive once the share session is cleared', () => {
+ const activity = getTransferActivity(make({ role: 'sender', draftPhase: 'empty' }))
+
+ expect(activity.active).toBe(false)
+ })
+
+ it('reports staging as indeterminate progress', () => {
+ const activity = getTransferActivity(
+ make({
+ draftPhase: 'preparing',
+ uploadItems: [
+ { name: 'a', path: '/a', status: 'completed' },
+ { name: 'b', path: '/b', status: 'waiting' }
+ ]
+ })
+ )
+
+ expect(activity.active).toBe(true)
+ expect(activity.phase).toBe('preparing')
+ })
+})
diff --git a/packages/domain/src/transfer/activity.ts b/packages/domain/src/transfer/activity.ts
new file mode 100644
index 0000000..3da7469
--- /dev/null
+++ b/packages/domain/src/transfer/activity.ts
@@ -0,0 +1,152 @@
+import { getDownloadTotals } from '../receive/downloadModel'
+import { summarizeEvents, type PeerDownloadEvent } from '../send/shareModel'
+import type { SenderUploadItem } from '../send/draftTypes'
+import { toProgressPercent } from './rate'
+import type { TransferRole, TransferSessionState } from './types'
+
+export type TransferPhase = 'preparing' | 'waiting' | 'transferring'
+
+export interface TransferActivity {
+ active: boolean
+ settled: boolean
+ role: TransferRole | null
+ phase: TransferPhase
+ deviceCount: number
+ receivedPeers: string[]
+ percent: number
+ bytesTransferred: number
+ totalBytes: number
+}
+
+const IDLE: TransferActivity = {
+ active: false,
+ settled: true,
+ role: null,
+ phase: 'transferring',
+ deviceCount: 0,
+ receivedPeers: [],
+ percent: 0,
+ bytesTransferred: 0,
+ totalBytes: 0
+}
+
+function getPreparingActivity(items: SenderUploadItem[]): TransferActivity {
+ const completed = items.filter((item) => item.status === 'completed').length
+ return {
+ active: countSharedFiles(items) > 0,
+ settled: false,
+ role: 'sender',
+ phase: 'preparing',
+ deviceCount: 0,
+ receivedPeers: [],
+ percent: items.length > 0 ? Math.round((completed / items.length) * 100) : 0,
+ bytesTransferred: 0,
+ totalBytes: 0
+ }
+}
+
+export function countSharedFiles(items: SenderUploadItem[]): number {
+ return items.filter((item) => item.kind !== 'text').length
+}
+
+function countConnectedPeers(state: TransferSessionState): number {
+ return Object.values(state.connectedPeers).filter((peer) => peer.disconnectedAt === undefined)
+ .length
+}
+
+function getReceivedPeers(events: PeerDownloadEvent[], expectedFiles: number): string[] {
+ if (expectedFiles === 0) return []
+
+ const completed = new Map<string, Set<string>>()
+ for (const event of events) {
+ if (event.state !== 'completed') continue
+ const ids = completed.get(event.peerKey) ?? new Set<string>()
+ ids.add(event.id)
+ completed.set(event.peerKey, ids)
+ }
+
+ return [...completed.entries()]
+ .filter(([, ids]) => ids.size >= expectedFiles)
+ .map(([peerKey]) => peerKey)
+}
+
+function getSenderActivity(state: TransferSessionState): TransferActivity {
+ const deviceCount = countConnectedPeers(state)
+ const events = Object.values(state.peerDownloads)
+ const expectedFiles = countSharedFiles(state.uploadItems)
+ const receivedPeers = getReceivedPeers(events, expectedFiles)
+
+ const received = new Set(receivedPeers)
+ const busyPeers = new Set<string>()
+ for (const event of events) {
+ if (event.state === 'failed' || received.has(event.peerKey)) continue
+
+ const doneWithUnknownTotal = event.state === 'completed' && expectedFiles === 0
+ if (doneWithUnknownTotal) continue
+
+ busyPeers.add(event.peerKey)
+ }
+ const summary = summarizeEvents(events.filter((event) => busyPeers.has(event.peerKey)))
+
+ if (!summary) {
+ return {
+ active: state.draftPhase === 'ready' && expectedFiles > 0,
+ settled: false,
+ role: 'sender',
+ phase: 'waiting',
+ deviceCount,
+ receivedPeers,
+ percent: 0,
+ bytesTransferred: 0,
+ totalBytes: 0
+ }
+ }
+
+ const shareBytes = state.uploadItems.reduce((sum, item) => sum + (item.size ?? 0), 0)
+ const totalBytes = Math.max(shareBytes * busyPeers.size, summary.sumOfKnownTotals)
+
+ return {
+ active: true,
+ settled: false,
+ role: 'sender',
+ phase: 'transferring',
+ deviceCount,
+ receivedPeers,
+ percent: toProgressPercent(summary.transferredBytes, totalBytes),
+ bytesTransferred: summary.transferredBytes,
+ totalBytes
+ }
+}
+
+function getReceiverActivity(state: TransferSessionState): TransferActivity {
+ const totals = getDownloadTotals(state.incomingFileOffers, state.receiveDownloadStates)
+ let queued = false
+ let failed = false
+ let routing = false
+
+ for (const item of Object.values(state.receiveDownloadStates)) {
+ if (item.queued === true) queued = true
+ if (item.status === 'failed') failed = true
+ if (item.status === 'completed' && item.destination === undefined) routing = true
+ }
+
+ return {
+ active: totals.activeCount > 0 || queued || routing,
+ settled: !failed,
+ role: 'receiver',
+ phase: 'transferring',
+ deviceCount: state.peerCount,
+ receivedPeers: [],
+ percent: totals.percent,
+ bytesTransferred: totals.bytesTransferred,
+ totalBytes: totals.totalBytes
+ }
+}
+
+export function getTransferActivity(state: TransferSessionState): TransferActivity {
+ if (state.draftPhase === 'preparing') return getPreparingActivity(state.uploadItems)
+ if (state.role === 'receiver') return getReceiverActivity(state)
+ if (state.role === 'sender') return getSenderActivity(state)
+
+ return IDLE
+}
diff --git a/packages/domain/src/transfer/binding.test.ts b/packages/domain/src/transfer/binding.test.ts
new file mode 100644
index 0000000..563a17c
--- /dev/null
+++ b/packages/domain/src/transfer/binding.test.ts
@@ -0,0 +1,141 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { RendererTransferEvent } from '@altersend/core'
+import { bindTransferApi, discardPendingProgress } from './binding'
+import { initialTransferSessionState } from './reducer'
+import { transferStore } from './store'
+import { setAppActive } from './effects/appActive'
+
+const FILE_ID = 'file-1'
+
+const OFFER = {
+ id: FILE_ID,
+ transferId: 'tx-1',
+ name: 'a.bin',
+ path: 'a.bin',
+ size: 1000,
+ driveKey: 'drive-1',
+ kind: 'file'
+} as const
+
+function progressEvent(bytesTransferred: number): RendererTransferEvent {
+ return {
+ type: 'status',
+ state: 'download-progress',
+ fileId: FILE_ID,
+ file: 'a.bin',
+ path: 'a.bin',
+ bytesTransferred,
+ totalBytes: 1000
+ } as RendererTransferEvent
+}
+
+function terminalEvent(): RendererTransferEvent {
+ return {
+ type: 'status',
+ state: 'downloaded',
+ fileId: FILE_ID,
+ file: 'a.bin',
+ path: 'a.bin',
+ totalBytes: 1000,
+ savedTo: '/tmp/a.bin'
+ } as RendererTransferEvent
+}
+
+let emit: (event: RendererTransferEvent) => void
+let unbind: () => void
+
+function bytesInStore(): number {
+ return transferStore.getState().receiveDownloadStates[FILE_ID]?.bytesTransferred ?? -1
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ transferStore.setState(
+ { ...initialTransferSessionState, role: 'receiver', incomingFileOffers: [OFFER] },
+ true
+ )
+ unbind = bindTransferApi({
+ worker: { peersList: () => Promise.resolve([]) } as never,
+ startP2P: () => Promise.resolve(),
+ onTransferEvent: (cb) => {
+ emit = cb
+ return () => {}
+ }
+ })
+})
+
+afterEach(() => {
+ unbind()
+ discardPendingProgress()
+ setAppActive(true)
+ vi.useRealTimers()
+})
+
+describe('progress coalescing', () => {
+ it('defers progress behind a timer while the app is active', () => {
+ setAppActive(true)
+ emit(progressEvent(100))
+ expect(bytesInStore()).toBe(-1)
+
+ vi.advanceTimersByTime(100)
+ expect(bytesInStore()).toBe(100)
+ })
+
+ it('dispatches without a timer while the app is backgrounded', () => {
+ setAppActive(false)
+ emit(progressEvent(100))
+
+ expect(bytesInStore()).toBe(100)
+ })
+
+ it('rate limits background dispatches to the flush interval', () => {
+ setAppActive(false)
+ emit(progressEvent(100))
+ emit(progressEvent(200))
+
+ expect(bytesInStore()).toBe(100)
+ })
+
+ it('delivers a rate limited update without waiting for another event', () => {
+ setAppActive(false)
+ emit(progressEvent(100))
+ emit(progressEvent(200))
+
+ vi.advanceTimersByTime(100)
+
+ expect(bytesInStore()).toBe(200)
+ })
+
+ it('flushes pending progress when the clock steps backwards', () => {
+ setAppActive(false)
+ emit(progressEvent(100))
+
+ vi.setSystemTime(Date.now() - 60_000)
+ emit(progressEvent(200))
+
+ expect(bytesInStore()).toBe(200)
+ })
+
+ it('flushes pending progress before a terminal event', () => {
+ setAppActive(false)
+ emit(progressEvent(100))
+ vi.advanceTimersByTime(10)
+ emit(progressEvent(900))
+ emit(terminalEvent())
+
+ expect(transferStore.getState().receiveDownloadStates[FILE_ID]?.status).toBe('completed')
+ })
+
+ it('drops queued progress when the session disconnects', () => {
+ setAppActive(false)
+ emit(progressEvent(100))
+ vi.advanceTimersByTime(10)
+ emit(progressEvent(900))
+
+ emit({ type: 'status', state: 'disconnected', peers: 0 } as RendererTransferEvent)
+ setAppActive(true)
+ vi.advanceTimersByTime(1000)
+
+ expect(bytesInStore()).toBe(-1)
+ })
+})
diff --git a/packages/domain/src/transfer/binding.ts b/packages/domain/src/transfer/binding.ts
index 29767a8..917c49d 100644
--- a/packages/domain/src/transfer/binding.ts
+++ b/packages/domain/src/transfer/binding.ts
@@ -1,4 +1,5 @@
import { dispatchToTransferStore } from './store'
+import { getAppActive } from './effects/appActive'
import { getTransferDebugMessage, getTransferErrorCode } from './errors'
import { TRANSFER_ERROR_CODES } from './types'
import type { SharingStatusEvent } from '../send/draftModel'
@@ -58,6 +59,7 @@ function dispatchRendererEvent(event: RendererTransferEvent): void {
peer: event.peer
})
case 'role':
+ if (event.role === null) discardPendingProgress()
return dispatchToTransferStore({ type: 'role_changed', role: event.role })
case 'error':
return dispatchToTransferStore({
@@ -114,6 +116,7 @@ function dispatchRendererEvent(event: RendererTransferEvent): void {
const PROGRESS_FLUSH_MS = 100
const pendingProgress = new Map<string, () => void>()
let progressTimer: ReturnType<typeof setTimeout> | null = null
+let lastFlushAt = 0
function stopProgressTimer(): void {
if (!progressTimer) return
@@ -123,12 +126,24 @@ function stopProgressTimer(): void {
function queueProgress(key: string, dispatch: () => void): void {
pendingProgress.set(key, dispatch)
+
+ if (!getAppActive()) {
+ const elapsed = Date.now() - lastFlushAt
+ if (elapsed >= PROGRESS_FLUSH_MS || elapsed < 0) {
+ flushProgress()
+ return
+ }
+ if (!progressTimer) progressTimer = setTimeout(flushProgress, PROGRESS_FLUSH_MS - elapsed)
+ return
+ }
+
if (progressTimer) return
progressTimer = setTimeout(flushProgress, PROGRESS_FLUSH_MS)
}
function flushProgress(): void {
stopProgressTimer()
+ lastFlushAt = Date.now()
const pending = Array.from(pendingProgress.values())
pendingProgress.clear()
for (const dispatch of pending) dispatch()
@@ -136,6 +151,7 @@ function flushProgress(): void {
export function discardPendingProgress(): void {
stopProgressTimer()
+ lastFlushAt = 0
pendingProgress.clear()
}
@@ -200,6 +216,7 @@ function dispatchStatusEvent(event: StatusEvent): void {
case 'joining':
case 'joined':
case 'disconnected':
+ if (event.state === 'disconnected') discardPendingProgress()
return dispatchToTransferStore({
type: 'status_changed',
state: event.state,
diff --git a/packages/domain/src/transfer/effects/backgroundReconnectEffect.ts b/packages/domain/src/transfer/effects/backgroundReconnectEffect.ts
index f880eb2..09e82dc 100644
--- a/packages/domain/src/transfer/effects/backgroundReconnectEffect.ts
+++ b/packages/domain/src/transfer/effects/backgroundReconnectEffect.ts
@@ -1,5 +1,6 @@
import { dispatchToTransferStore, transferStore } from '../store'
import { subscribeAppActive } from './appActive'
+import { isBackgroundTransferActive } from './backgroundTransfer'
let started = false
let unsubscribe: (() => void) | null = null
@@ -9,7 +10,7 @@ export function startBackgroundReconnectEffect(): () => void {
started = true
unsubscribe = subscribeAppActive((active) => {
- if (active) return
+ if (active || isBackgroundTransferActive()) return
const state = transferStore.getState()
if (state.role === 'receiver' && state.incomingFileOffers.length > 0) {
dispatchToTransferStore({ type: 'reconnecting' })
diff --git a/packages/domain/src/transfer/effects/backgroundTransfer.ts b/packages/domain/src/transfer/effects/backgroundTransfer.ts
new file mode 100644
index 0000000..e43f62a
--- /dev/null
+++ b/packages/domain/src/transfer/effects/backgroundTransfer.ts
@@ -0,0 +1,9 @@
+let active = false
+
+export function setBackgroundTransferActive(value: boolean): void {
+ active = value
+}
+
+export function isBackgroundTransferActive(): boolean {
+ return active
+}
diff --git a/packages/domain/src/transfer/index.ts b/packages/domain/src/transfer/index.ts
index 9899458..83c557e 100644
--- a/packages/domain/src/transfer/index.ts
+++ b/packages/domain/src/transfer/index.ts
@@ -11,7 +11,9 @@ export {
type ErrorHandler
} from './binding'
export * from './rate'
+export * from './activity'
export * from './useTransferRates'
export * from './effects/appActive'
+export * from './effects/backgroundTransfer'
export * from './effects/peerWatchdog'
export * from './effects/backgroundReconnectEffect'
diff --git a/packages/domain/src/transfer/rate.ts b/packages/domain/src/transfer/rate.ts
index 2dc9f1e..f335284 100644
--- a/packages/domain/src/transfer/rate.ts
+++ b/packages/domain/src/transfer/rate.ts
@@ -17,6 +17,11 @@ export interface TransferProgress {
totalBytes: number
}
+export function toProgressPercent(bytesTransferred: number, totalBytes: number): number {
+ if (totalBytes <= 0) return 0
+ return Math.max(0, Math.min(100, Math.round((bytesTransferred / totalBytes) * 100)))
+}
+
export function pushRateSample(samples: RateSample[], bytes: number, at: number): RateSample[] {
const last = samples[samples.length - 1]
if (last && bytes < last.bytes) return [{ bytes, at }]
diff --git a/packages/locales/src/index.ts b/packages/locales/src/index.ts
index f9836ab..38c35d3 100644
--- a/packages/locales/src/index.ts
+++ b/packages/locales/src/index.ts
@@ -1,4 +1,5 @@
import { useTranslation as useReactTranslation } from 'react-i18next'
+import { i18nextInstance } from './i18n'
export { Trans } from 'react-i18next'
export * from './i18n'
export * from './locale'
@@ -6,13 +7,17 @@ export * from './resources'
export type { Resources } from './i18n-augmentation'
type TranslationOptions = Record<string, unknown>
+type Translator = (key: string, options?: TranslationOptions) => string
+
+export function translate(key: string, options?: TranslationOptions): string {
+ return (i18nextInstance.t as unknown as Translator)(key, options)
+}
export function useTranslation(namespaces?: string | string[]) {
const { t, i18n, ready } = useReactTranslation(namespaces as never)
- const translate = t as unknown as (key: string, options?: TranslationOptions) => string
return {
- t: translate,
+ t: t as unknown as Translator,
i18n,
ready
}
diff --git a/packages/locales/src/locales/de-DE/common.json b/packages/locales/src/locales/de-DE/common.json
index 1c7bdf3..d961182 100644
--- a/packages/locales/src/locales/de-DE/common.json
+++ b/packages/locales/src/locales/de-DE/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}} Min. {{seconds}} Sek.",
"durationHours": "{{hours}} Std.",
"durationHoursMinutes": "{{hours}} Std. {{minutes}} Min."
+ },
+ "backgroundTransfer": {
+ "channelName": "Dateiübertragungen",
+ "sending": "Dateien werden gesendet",
+ "receiving": "Dateien werden empfangen",
+ "preparing": "Dateien werden vorbereitet",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "Warten auf Empfänger",
+ "devicesConnected_one": "{{count}} Gerät verbunden",
+ "devicesConnected_other": "{{count}} Geräte verbunden",
+ "devicesReceived_one": "{{count}} Gerät hat empfangen · wartet",
+ "devicesReceived_other": "{{count}} Geräte haben empfangen · wartet",
+ "sentTo": "Dateien an {{device}} gesendet",
+ "someDevice": "ein Gerät",
+ "received": "Dateien empfangen"
}
}
diff --git a/packages/locales/src/locales/en-GB/common.json b/packages/locales/src/locales/en-GB/common.json
index c259e07..18c7c98 100644
--- a/packages/locales/src/locales/en-GB/common.json
+++ b/packages/locales/src/locales/en-GB/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}}m {{seconds}}s",
"durationHours": "{{hours}}h",
"durationHoursMinutes": "{{hours}}h {{minutes}}m"
+ },
+ "backgroundTransfer": {
+ "channelName": "File transfers",
+ "sending": "Sending files",
+ "receiving": "Receiving files",
+ "preparing": "Preparing files",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "Waiting for receiver",
+ "devicesConnected_one": "{{count}} device connected",
+ "devicesConnected_other": "{{count}} devices connected",
+ "devicesReceived_one": "{{count}} device received · waiting",
+ "devicesReceived_other": "{{count}} devices received · waiting",
+ "sentTo": "Files sent to {{device}}",
+ "someDevice": "a device",
+ "received": "Files received"
}
}
diff --git a/packages/locales/src/locales/en-US/common.json b/packages/locales/src/locales/en-US/common.json
index c259e07..18c7c98 100644
--- a/packages/locales/src/locales/en-US/common.json
+++ b/packages/locales/src/locales/en-US/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}}m {{seconds}}s",
"durationHours": "{{hours}}h",
"durationHoursMinutes": "{{hours}}h {{minutes}}m"
+ },
+ "backgroundTransfer": {
+ "channelName": "File transfers",
+ "sending": "Sending files",
+ "receiving": "Receiving files",
+ "preparing": "Preparing files",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "Waiting for receiver",
+ "devicesConnected_one": "{{count}} device connected",
+ "devicesConnected_other": "{{count}} devices connected",
+ "devicesReceived_one": "{{count}} device received · waiting",
+ "devicesReceived_other": "{{count}} devices received · waiting",
+ "sentTo": "Files sent to {{device}}",
+ "someDevice": "a device",
+ "received": "Files received"
}
}
diff --git a/packages/locales/src/locales/es-419/common.json b/packages/locales/src/locales/es-419/common.json
index dc0aa4c..7320e88 100644
--- a/packages/locales/src/locales/es-419/common.json
+++ b/packages/locales/src/locales/es-419/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}} min {{seconds}} s",
"durationHours": "{{hours}} h",
"durationHoursMinutes": "{{hours}} h {{minutes}} min"
+ },
+ "backgroundTransfer": {
+ "channelName": "Transferencias de archivos",
+ "sending": "Enviando archivos",
+ "receiving": "Recibiendo archivos",
+ "preparing": "Preparando archivos",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "Esperando al receptor",
+ "devicesConnected_one": "{{count}} dispositivo conectado",
+ "devicesConnected_other": "{{count}} dispositivos conectados",
+ "devicesReceived_one": "{{count}} dispositivo recibió · esperando",
+ "devicesReceived_other": "{{count}} dispositivos recibieron · esperando",
+ "sentTo": "Archivos enviados a {{device}}",
+ "someDevice": "un dispositivo",
+ "received": "Archivos recibidos"
}
}
diff --git a/packages/locales/src/locales/es-ES/common.json b/packages/locales/src/locales/es-ES/common.json
index 8e059b0..8ce6c36 100644
--- a/packages/locales/src/locales/es-ES/common.json
+++ b/packages/locales/src/locales/es-ES/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}} min {{seconds}} s",
"durationHours": "{{hours}} h",
"durationHoursMinutes": "{{hours}} h {{minutes}} min"
+ },
+ "backgroundTransfer": {
+ "channelName": "Transferencias de archivos",
+ "sending": "Enviando archivos",
+ "receiving": "Recibiendo archivos",
+ "preparing": "Preparando archivos",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "Esperando al receptor",
+ "devicesConnected_one": "{{count}} dispositivo conectado",
+ "devicesConnected_other": "{{count}} dispositivos conectados",
+ "devicesReceived_one": "{{count}} dispositivo recibió · esperando",
+ "devicesReceived_other": "{{count}} dispositivos recibieron · esperando",
+ "sentTo": "Archivos enviados a {{device}}",
+ "someDevice": "un dispositivo",
+ "received": "Archivos recibidos"
}
}
diff --git a/packages/locales/src/locales/fr-FR/common.json b/packages/locales/src/locales/fr-FR/common.json
index 7b5b19c..ed31b76 100644
--- a/packages/locales/src/locales/fr-FR/common.json
+++ b/packages/locales/src/locales/fr-FR/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}} min {{seconds}} s",
"durationHours": "{{hours}} h",
"durationHoursMinutes": "{{hours}} h {{minutes}} min"
+ },
+ "backgroundTransfer": {
+ "channelName": "Transferts de fichiers",
+ "sending": "Envoi des fichiers",
+ "receiving": "Réception des fichiers",
+ "preparing": "Préparation des fichiers",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "En attente du destinataire",
+ "devicesConnected_one": "{{count}} appareil connecté",
+ "devicesConnected_other": "{{count}} appareils connectés",
+ "devicesReceived_one": "{{count}} appareil a reçu · en attente",
+ "devicesReceived_other": "{{count}} appareils ont reçu · en attente",
+ "sentTo": "Fichiers envoyés à {{device}}",
+ "someDevice": "un appareil",
+ "received": "Fichiers reçus"
}
}
diff --git a/packages/locales/src/locales/it-IT/common.json b/packages/locales/src/locales/it-IT/common.json
index 88e0260..a7a2a7c 100644
--- a/packages/locales/src/locales/it-IT/common.json
+++ b/packages/locales/src/locales/it-IT/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}} min {{seconds}} s",
"durationHours": "{{hours}} h",
"durationHoursMinutes": "{{hours}} h {{minutes}} min"
+ },
+ "backgroundTransfer": {
+ "channelName": "Trasferimenti di file",
+ "sending": "Invio dei file in corso",
+ "receiving": "Ricezione dei file in corso",
+ "preparing": "Preparazione dei file",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "In attesa del destinatario",
+ "devicesConnected_one": "{{count}} dispositivo connesso",
+ "devicesConnected_other": "{{count}} dispositivi connessi",
+ "devicesReceived_one": "{{count}} dispositivo ha ricevuto · in attesa",
+ "devicesReceived_other": "{{count}} dispositivi hanno ricevuto · in attesa",
+ "sentTo": "File inviati a {{device}}",
+ "someDevice": "un dispositivo",
+ "received": "File ricevuti"
}
}
diff --git a/packages/locales/src/locales/ja-JP/common.json b/packages/locales/src/locales/ja-JP/common.json
index ab74696..a025101 100644
--- a/packages/locales/src/locales/ja-JP/common.json
+++ b/packages/locales/src/locales/ja-JP/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}}分{{seconds}}秒",
"durationHours": "{{hours}}時間",
"durationHoursMinutes": "{{hours}}時間{{minutes}}分"
+ },
+ "backgroundTransfer": {
+ "channelName": "ファイル転送",
+ "sending": "ファイルを送信中",
+ "receiving": "ファイルを受信中",
+ "preparing": "ファイルを準備中",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "受信者を待っています",
+ "devicesConnected_one": "{{count}}台のデバイスが接続中",
+ "devicesConnected_other": "{{count}}台のデバイスが接続中",
+ "devicesReceived_one": "{{count}}台が受信済み · 待機中",
+ "devicesReceived_other": "{{count}}台が受信済み · 待機中",
+ "sentTo": "{{device}}にファイルを送信しました",
+ "someDevice": "デバイス",
+ "received": "ファイルを受信しました"
}
}
diff --git a/packages/locales/src/locales/ko-KR/common.json b/packages/locales/src/locales/ko-KR/common.json
index a00e774..3201113 100644
--- a/packages/locales/src/locales/ko-KR/common.json
+++ b/packages/locales/src/locales/ko-KR/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}}분 {{seconds}}초",
"durationHours": "{{hours}}시간",
"durationHoursMinutes": "{{hours}}시간 {{minutes}}분"
+ },
+ "backgroundTransfer": {
+ "channelName": "파일 전송",
+ "sending": "파일 보내는 중",
+ "receiving": "파일 받는 중",
+ "preparing": "파일 준비 중",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "받는 사람 기다리는 중",
+ "devicesConnected_one": "{{count}}대 기기 연결됨",
+ "devicesConnected_other": "{{count}}대 기기 연결됨",
+ "devicesReceived_one": "{{count}}대 수신 완료 · 대기 중",
+ "devicesReceived_other": "{{count}}대 수신 완료 · 대기 중",
+ "sentTo": "{{device}}(으)로 파일을 보냈습니다",
+ "someDevice": "기기",
+ "received": "파일을 받았습니다"
}
}
diff --git a/packages/locales/src/locales/pt-BR/common.json b/packages/locales/src/locales/pt-BR/common.json
index 15b7db5..63e357f 100644
--- a/packages/locales/src/locales/pt-BR/common.json
+++ b/packages/locales/src/locales/pt-BR/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}} min {{seconds}} s",
"durationHours": "{{hours}} h",
"durationHoursMinutes": "{{hours}} h {{minutes}} min"
+ },
+ "backgroundTransfer": {
+ "channelName": "Transferências de arquivos",
+ "sending": "Enviando arquivos",
+ "receiving": "Recebendo arquivos",
+ "preparing": "Preparando arquivos",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "Aguardando o destinatário",
+ "devicesConnected_one": "{{count}} dispositivo conectado",
+ "devicesConnected_other": "{{count}} dispositivos conectados",
+ "devicesReceived_one": "{{count}} dispositivo recebeu · aguardando",
+ "devicesReceived_other": "{{count}} dispositivos receberam · aguardando",
+ "sentTo": "Arquivos enviados para {{device}}",
+ "someDevice": "um dispositivo",
+ "received": "Arquivos recebidos"
}
}
diff --git a/packages/locales/src/locales/ru-RU/common.json b/packages/locales/src/locales/ru-RU/common.json
index 601a5a0..4435a1a 100644
--- a/packages/locales/src/locales/ru-RU/common.json
+++ b/packages/locales/src/locales/ru-RU/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}} мин {{seconds}} с",
"durationHours": "{{hours}} ч",
"durationHoursMinutes": "{{hours}} ч {{minutes}} мин"
+ },
+ "backgroundTransfer": {
+ "channelName": "Передача файлов",
+ "sending": "Отправка файлов",
+ "receiving": "Получение файлов",
+ "preparing": "Подготовка файлов",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "Ожидание получателя",
+ "devicesConnected_one": "{{count}} устройство подключено",
+ "devicesConnected_other": "{{count}} устройства подключено",
+ "devicesReceived_one": "{{count}} устройство получило · ожидание",
+ "devicesReceived_other": "{{count}} устройства получили · ожидание",
+ "sentTo": "Файлы отправлены на {{device}}",
+ "someDevice": "устройство",
+ "received": "Файлы получены"
}
}
diff --git a/packages/locales/src/locales/zh-CN/common.json b/packages/locales/src/locales/zh-CN/common.json
index 8042e1b..30ff0ed 100644
--- a/packages/locales/src/locales/zh-CN/common.json
+++ b/packages/locales/src/locales/zh-CN/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}}分{{seconds}}秒",
"durationHours": "{{hours}}小时",
"durationHoursMinutes": "{{hours}}小时{{minutes}}分"
+ },
+ "backgroundTransfer": {
+ "channelName": "文件传输",
+ "sending": "正在发送文件",
+ "receiving": "正在接收文件",
+ "preparing": "正在准备文件",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "正在等待接收方",
+ "devicesConnected_one": "已连接 {{count}} 台设备",
+ "devicesConnected_other": "已连接 {{count}} 台设备",
+ "devicesReceived_one": "{{count}} 台设备已接收 · 等待中",
+ "devicesReceived_other": "{{count}} 台设备已接收 · 等待中",
+ "sentTo": "文件已发送至 {{device}}",
+ "someDevice": "某台设备",
+ "received": "文件已接收"
}
}
diff --git a/packages/locales/src/locales/zh-TW/common.json b/packages/locales/src/locales/zh-TW/common.json
index 169c115..816b595 100644
--- a/packages/locales/src/locales/zh-TW/common.json
+++ b/packages/locales/src/locales/zh-TW/common.json
@@ -96,5 +96,20 @@
"durationMinutesSeconds": "{{minutes}}分{{seconds}}秒",
"durationHours": "{{hours}}小時",
"durationHoursMinutes": "{{hours}}小時{{minutes}}分"
+ },
+ "backgroundTransfer": {
+ "channelName": "檔案傳輸",
+ "sending": "正在傳送檔案",
+ "receiving": "正在接收檔案",
+ "preparing": "正在準備檔案",
+ "progress": "{{percent}}% · {{transferred}} / {{total}}",
+ "waiting": "正在等待接收端",
+ "devicesConnected_one": "已連線 {{count}} 台裝置",
+ "devicesConnected_other": "已連線 {{count}} 台裝置",
+ "devicesReceived_one": "{{count}} 台裝置已接收 · 等待中",
+ "devicesReceived_other": "{{count}} 台裝置已接收 · 等待中",
+ "sentTo": "檔案已傳送至 {{device}}",
+ "someDevice": "某台裝置",
+ "received": "檔案已接收"
}
}