Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Send files between PC and phone
Beed814c98b1a2d
diff --git a/README.md b/README.mdindex ab375ca..1a47dca 100644--- a/README.md+++ b/README.md@@ -78,6 +78,11 @@ place and tested; the user-facing features of Phase 1 come next.the phone, send it with the Quick Settings tile, the share sheet or a buttonin the app (Android lets only the app in front read the clipboard).Passwords that password managers mark private are never sent.+- **Files** in both directions, at Wi-Fi speed. On the PC, drop files on the+ window or pick them; on the phone, share them from any app or pick them in+ Nectarlink. They land in `Downloads\Nectarlink` on the PC and+ `Download/Nectarlink` on the phone, with progress, cancelling, and transfers+ that pick up where they left off after a dropped connection.- **Capability matrix**: both apps compute which features work for a pair ofdevices and what would enable the rest, so the interface never offerssomething that can't work.@@ -89,7 +94,7 @@ place and tested; the user-facing features of Phase 1 come next.connection service, and an identity key protected by the Android Keystore.- **Command-line client** for development and testing (`nectarlink`).-**Next (Phase 1)**: file transfer (and images on the clipboard), media+**Next (Phase 1)**: "Send to phone" in Explorer, images on the clipboard, mediacontrols, notification filters and history, and a Windows installer. Mirroring, messages, calls and the otherfeatures in the plan follow in later phases.diff --git a/android/README.md b/android/README.mdindex ed13d83..5096a3e 100644--- a/android/README.md+++ b/android/README.md@@ -41,7 +41,10 @@ sources; nothing generated is checked in except the theme tokens- `clipboard/`: sending text to the PC (share sheet, Quick Settings tile,the connection notification's button) through `SendActivity`, which readsthe clipboard once it has focus, as Android requires; and writing text a- PC sent.+ PC sent. `SendActivity` also takes shared files.+- `files/`: opening files to send, publishing received files to+ Download/Nectarlink (MediaStore on Android 10+), and the transfer+ notifications with progress and Cancel.- `service/ConnectionService`: a "connected device" foreground service thatkeeps the phone reachable and holds the Wi-Fi multicast lock localdiscovery needs.diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex d577139..ad071b3 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -73,10 +73,30 @@<intent-filter><action android:name="android.intent.action.SEND" /><category android:name="android.intent.category.DEFAULT" />- <data android:mimeType="text/plain" />+ <data android:mimeType="*/*" />+ </intent-filter>+ <intent-filter>+ <action android:name="android.intent.action.SEND_MULTIPLE" />+ <category android:name="android.intent.category.DEFAULT" />+ <data android:mimeType="*/*" /></intent-filter></activity>+ <receiver+ android:name=".files.TransferNotifications$CancelReceiver"+ android:exported="false" />++ <!-- Opening received files on Android 8–9 (later versions use MediaStore). -->+ <provider+ android:name="androidx.core.content.FileProvider"+ android:authorities="${applicationId}.files"+ android:exported="false"+ android:grantUriPermissions="true">+ <meta-data+ android:name="android.support.FILE_PROVIDER_PATHS"+ android:resource="@xml/file_paths" />+ </provider>+<serviceandroid:name=".clipboard.ClipboardTileService"android:exported="true"diff --git a/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.ktindex f61ae27..38fbf83 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt@@ -2,10 +2,13 @@package app.nectarlink.android.clipboardimport android.app.Activity+import android.app.AlertDialogimport android.content.Contextimport android.content.Intent+import android.net.Uriimport android.os.Bundleimport android.widget.Toast+import androidx.core.content.IntentCompatimport app.nectarlink.android.NectarlinkApplicationimport app.nectarlink.android.Rimport kotlinx.coroutines.CoroutineScope@@ -15,9 +18,9 @@ import kotlinx.coroutines.cancelimport kotlinx.coroutines.launch/**- * Sends text to the connected PCs, without a screen of its own: text shared- * from another app, or the clipboard (from the Quick Settings tile or the- * connection notification). Android lets only the focused app read the+ * Sends to the connected PCs, without a screen of its own: files or text+ * shared from another app, or the clipboard (from the Quick Settings tile or+ * the connection notification). Android lets only the focused app read the* clipboard, which is why this is an activity: it reads once it has focus.*/class SendActivity : Activity() {@@ -26,13 +29,47 @@ class SendActivity : Activity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)- if (intent?.action == Intent.ACTION_SEND) {- val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()- if (text.isNullOrBlank()) finishWith(getString(R.string.clip_nothing_shared)) else send(text)+ val intent = intent ?: return finish()+ when (intent.action) {+ Intent.ACTION_SEND -> {+ val stream = IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)+ val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()+ when {+ stream != null -> sendFiles(listOf(stream))+ !text.isNullOrBlank() -> send(text)+ else -> finishWith(getString(R.string.clip_nothing_shared))+ }+ }+ Intent.ACTION_SEND_MULTIPLE -> {+ val streams = IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)+ if (streams.isNullOrEmpty()) finishWith(getString(R.string.transfer_nothing)) else sendFiles(streams)+ }}// The clipboard is read in onWindowFocusChanged.}+ /** Files go to one PC: the connected one, or the one the user picks. */+ private fun sendFiles(uris: List<Uri>) {+ sent = true+ val core = (application as NectarlinkApplication).core+ val pcs = core.state.value.devices.filter { it.online }+ when (pcs.size) {+ 0 -> finishWith(getString(R.string.clip_no_pc))+ 1 -> {+ core.sendFiles(pcs[0].id, uris)+ finishWith(getString(R.string.transfer_sending, pcs[0].name))+ }+ else -> AlertDialog.Builder(this)+ .setTitle(R.string.transfer_pick_pc)+ .setItems(pcs.map { it.name }.toTypedArray()) { _, which ->+ core.sendFiles(pcs[which].id, uris)+ finishWith(getString(R.string.transfer_sending, pcs[which].name))+ }+ .setOnCancelListener { finish() }+ .show()+ }+ }+override fun onWindowFocusChanged(hasFocus: Boolean) {super.onWindowFocusChanged(hasFocus)if (!hasFocus || sent || intent?.action != ACTION_SEND_CLIPBOARD) returndiff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.ktindex a603faf..b367f09 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt@@ -5,7 +5,11 @@ import android.content.Contextimport android.net.wifi.WifiManagerimport android.service.notification.NotificationListenerServiceimport android.util.Log+import android.net.Uriimport app.nectarlink.android.BuildConfig+import app.nectarlink.android.files.OutgoingFiles+import app.nectarlink.android.files.ReceivedFiles+import app.nectarlink.android.files.TransferNotificationsimport app.nectarlink.android.Rimport app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.core.Event@@ -16,6 +20,9 @@ import app.nectarlink.core.NodeOptionsimport app.nectarlink.core.Notificationimport app.nectarlink.core.PairingFailureimport app.nectarlink.core.PowerLevel+import app.nectarlink.core.Transfer+import app.nectarlink.core.TransferDirection+import app.nectarlink.core.TransferStatusimport app.nectarlink.core.initLoggingimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers@@ -86,6 +93,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerappVersion = BuildConfig.VERSION_NAME,power = PowerLevel.BASIC,awayMode = false,+ downloadsDir = context.cacheDir.resolve("received").absolutePath,)val started = try {NectarlinkNode.start(options, platform, KeystoreKeyProtector(), this@Core)@@ -148,6 +156,50 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListeneroverride fun onEvent(event: Event) {_state.update { it.reduce(event) }+ if (event is Event.Transfer) onTransfer(event.transfer)+ }++ // ---- Files ----++ private fun onTransfer(transfer: Transfer) {+ val pc = _state.value.nameOf(transfer.deviceId).orEmpty()+ TransferNotifications.update(context, transfer, pc)+ val done = transfer.status as? TransferStatus.Done ?: return+ if (transfer.direction != TransferDirection.INCOMING) return+ // Out of the app's cache, into Downloads, then tell the user.+ scope.launch(Dispatchers.IO) {+ val published = done.saved.mapNotNull { ReceivedFiles.publish(context, java.io.File(it)) }+ TransferNotifications.received(context, transfer, published, pc)+ }+ }++ /**+ * Sends picked or shared files to a PC; problems arrive as messages.+ * The files are opened right away: Android's permission to read a+ * shared item ends with the activity that received it.+ */+ fun sendFiles(pcId: String, uris: List<Uri>) {+ val files = OutgoingFiles.open(context, uris)+ if (files.isEmpty()) {+ _messages.tryEmit(context.getString(R.string.transfer_nothing))+ return+ }+ scope.launch(Dispatchers.IO) {+ startJob?.join()+ val node = node ?: return@launch+ try {+ node.sendFiles(pcId, files)+ } catch (e: NectarlinkException) {+ val name = _state.value.nameOf(pcId).orEmpty()+ _messages.tryEmit(+ if (e is NectarlinkException.Denied) context.getString(R.string.transfer_off_for, name) else describe(e),+ )+ }+ }+ }++ fun cancelTransfer(id: String) {+ node?.cancelTransfer(id)}// ---- Clipboard ----diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.ktindex bc400a8..df98a14 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt@@ -8,6 +8,7 @@ import app.nectarlink.core.Linkimport app.nectarlink.core.PairedDeviceimport app.nectarlink.core.PairingFailureimport app.nectarlink.core.PowerLevel+import app.nectarlink.core.Transfer/** Whether the core is running. */sealed interface CoreStatus {@@ -59,6 +60,8 @@ data class CoreState(val notificationAccess: Boolean = false,/** Whether Android lets Nectarlink run unrestricted in the background. */val backgroundUnrestricted: Boolean = true,+ /** File transfers, newest first (running ones and the latest finished). */+ val transfers: List<Transfer> = emptyList(),) {fun device(id: String): Device? = devices.firstOrNull { it.id == id }@@ -98,12 +101,29 @@ data class CoreState(is Event.NotificationsReset, is Event.NotificationPosted, is Event.NotificationRemoved -> this// Android shows its own "copied" confirmation.is Event.ClipboardReceived -> this+ is Event.Transfer -> copy(transfers = withTransfer(event.transfer))+ }++ private fun withTransfer(transfer: Transfer): List<Transfer> {+ val updated = if (transfers.any { it.id == transfer.id }) {+ transfers.map { if (it.id == transfer.id) transfer else it }+ } else {+ listOf(transfer) + transfers+ }+ val finished = updated.filter { it.isFinished() }.take(MAX_FINISHED_TRANSFERS).toSet()+ return updated.filter { !it.isFinished() || it in finished }}private fun update(id: String, change: (Device) -> Device): CoreState =copy(devices = devices.map { if (it.id == id) change(it) else it })}+/** Finished transfers kept on Home. */+const val MAX_FINISHED_TRANSFERS = 5++fun Transfer.isFinished(): Boolean =+ status !is app.nectarlink.core.TransferStatus.Running && status !is app.nectarlink.core.TransferStatus.Waiting+internal fun PairedDevice.toDevice() = Device(id = id,name = info.name,diff --git a/android/app/src/main/kotlin/app/nectarlink/android/files/OutgoingFiles.kt b/android/app/src/main/kotlin/app/nectarlink/android/files/OutgoingFiles.ktnew file mode 100644index 0000000..8514fea--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/files/OutgoingFiles.kt@@ -0,0 +1,23 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.files++import android.content.Context+import android.net.Uri+import android.provider.OpenableColumns+import app.nectarlink.core.FileToSend++/** Files the user picked or shared, as the core takes them: name and an open descriptor. */+internal object OutgoingFiles {+ /** Skips items that can't be opened (the result says how many were). */+ fun open(context: Context, uris: List<Uri>): List<FileToSend> = uris.mapNotNull { uri ->+ val fd = runCatching { context.contentResolver.openFileDescriptor(uri, "r") }.getOrNull() ?: return@mapNotNull null+ FileToSend.Fd(name = displayName(context, uri), fd = fd.detachFd())+ }++ private fun displayName(context: Context, uri: Uri): String =+ runCatching {+ context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->+ if (cursor.moveToFirst()) cursor.getString(0) else null+ }+ }.getOrNull() ?: uri.lastPathSegment?.substringAfterLast('/') ?: "file"+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/files/ReceivedFiles.kt b/android/app/src/main/kotlin/app/nectarlink/android/files/ReceivedFiles.ktnew file mode 100644index 0000000..2e34e8f--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/files/ReceivedFiles.kt@@ -0,0 +1,71 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.files++import android.content.ContentValues+import android.content.Context+import android.net.Uri+import android.os.Build+import android.os.Environment+import android.provider.MediaStore+import android.webkit.MimeTypeMap+import androidx.annotation.RequiresApi+import androidx.core.content.FileProvider+import java.io.File++/**+ * Files from a PC land in the app's cache first (the core writes them+ * there); this puts them where the user finds them: Download/Nectarlink.+ */+internal object ReceivedFiles {+ /** A received file where the user can open it. */+ data class Published(val uri: Uri, val name: String, val mime: String)++ fun mimeOf(name: String): String =+ MimeTypeMap.getSingleton().getMimeTypeFromExtension(name.substringAfterLast('.', "").lowercase())+ ?: "application/octet-stream"++ /** Moves a received file into Downloads; `null` if that failed (the file stays where it is). */+ fun publish(context: Context, file: File): Published? = runCatching {+ val mime = mimeOf(file.name)+ val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ toMediaStore(context, file, mime)+ } else {+ toAppDownloads(context, file)+ }+ file.delete()+ Published(uri, file.name, mime)+ }.getOrNull()++ @RequiresApi(Build.VERSION_CODES.Q)+ private fun toMediaStore(context: Context, file: File, mime: String): Uri {+ val resolver = context.contentResolver+ val values = ContentValues().apply {+ put(MediaStore.MediaColumns.DISPLAY_NAME, file.name)+ put(MediaStore.MediaColumns.MIME_TYPE, mime)+ put(MediaStore.MediaColumns.RELATIVE_PATH, "${Environment.DIRECTORY_DOWNLOADS}/Nectarlink")+ put(MediaStore.MediaColumns.IS_PENDING, 1)+ }+ val uri = checkNotNull(resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values))+ try {+ checkNotNull(resolver.openOutputStream(uri)).use { out -> file.inputStream().use { it.copyTo(out) } }+ resolver.update(uri, ContentValues().apply { put(MediaStore.MediaColumns.IS_PENDING, 0) }, null, null)+ } catch (e: Exception) {+ resolver.delete(uri, null, null)+ throw e+ }+ return uri+ }++ /** Android 8–9: the app's own Downloads folder, shared through a FileProvider. */+ private fun toAppDownloads(context: Context, file: File): Uri {+ val dir = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "Nectarlink").apply { mkdirs() }+ var target = File(dir, file.name)+ var n = 2+ while (target.exists()) {+ target = File(dir, "${file.nameWithoutExtension} ($n)${file.extension.let { if (it.isEmpty()) "" else ".$it" }}")+ n+++ }+ file.copyTo(target)+ return FileProvider.getUriForFile(context, "${context.packageName}.files", target)+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/files/TransferNotifications.kt b/android/app/src/main/kotlin/app/nectarlink/android/files/TransferNotifications.ktnew file mode 100644index 0000000..1e7f07c--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/files/TransferNotifications.kt@@ -0,0 +1,145 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.files++import android.Manifest+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import androidx.core.content.ContextCompat+import app.nectarlink.android.NectarlinkApplication+import app.nectarlink.android.R+import app.nectarlink.core.Transfer+import app.nectarlink.core.TransferDirection+import app.nectarlink.core.TransferStatus++/**+ * Transfers in the notification shade: progress with Cancel while one+ * runs, and "Received" (tap to open) when files from a PC are saved.+ */+internal object TransferNotifications {+ private const val CHANNEL_PROGRESS = "transfers"+ private const val CHANNEL_RECEIVED = "received"+ const val ACTION_CANCEL = "app.nectarlink.action.CANCEL_TRANSFER"+ const val EXTRA_ID = "transfer"++ fun createChannels(context: Context) {+ val manager = context.getSystemService(NotificationManager::class.java)+ manager.createNotificationChannel(+ NotificationChannel(CHANNEL_PROGRESS, context.getString(R.string.channel_transfers), NotificationManager.IMPORTANCE_LOW),+ )+ manager.createNotificationChannel(+ NotificationChannel(CHANNEL_RECEIVED, context.getString(R.string.channel_received), NotificationManager.IMPORTANCE_DEFAULT),+ )+ }++ private fun idOf(transfer: Transfer) = transfer.id.hashCode()++ private fun title(context: Context, transfer: Transfer): String = when (transfer.names.size) {+ 1 -> transfer.names[0]+ else -> context.resources.getQuantityString(R.plurals.transfer_files, transfer.names.size, transfer.names.size)+ }++ /** Shows or updates a running transfer, or removes it once it ended. */+ fun update(context: Context, transfer: Transfer, pcName: String) {+ if (!allowed(context)) return+ val manager = NotificationManagerCompat.from(context)+ val status = transfer.status+ if (status !is TransferStatus.Running && status !is TransferStatus.Waiting) {+ manager.cancel(idOf(transfer))+ if (status is TransferStatus.Failed) failed(context, transfer, pcName)+ return+ }+ val incoming = transfer.direction == TransferDirection.INCOMING+ val text = when {+ status is TransferStatus.Waiting -> context.getString(R.string.transfer_waiting, pcName)+ incoming -> context.getString(R.string.transfer_receiving, pcName)+ else -> context.getString(R.string.transfer_sending, pcName)+ }+ val percent = if (transfer.total == 0uL) 100 else (transfer.done.toDouble() / transfer.total.toDouble() * 100).toInt()+ val cancel = PendingIntent.getBroadcast(+ context,+ idOf(transfer),+ Intent(context, CancelReceiver::class.java).setAction(ACTION_CANCEL).putExtra(EXTRA_ID, transfer.id),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ val notification = NotificationCompat.Builder(context, CHANNEL_PROGRESS)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(title(context, transfer))+ .setContentText(text)+ .setProgress(100, percent, status is TransferStatus.Waiting)+ .setOngoing(true)+ .setOnlyAlertOnce(true)+ .setSilent(true)+ .setCategory(NotificationCompat.CATEGORY_PROGRESS)+ .addAction(0, context.getString(R.string.action_cancel), cancel)+ .build()+ post(context, idOf(transfer), notification)+ }++ /** Files from a PC are saved: tap to open (the first one). */+ fun received(context: Context, transfer: Transfer, files: List<ReceivedFiles.Published>, pcName: String) {+ if (!allowed(context) || files.isEmpty()) return+ val first = files[0]+ val open = Intent(Intent.ACTION_VIEW)+ .setDataAndType(first.uri, first.mime)+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)+ val tap = PendingIntent.getActivity(+ context, idOf(transfer), Intent.createChooser(open, null).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ val notification = NotificationCompat.Builder(context, CHANNEL_RECEIVED)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(+ if (files.size == 1) first.name else context.resources.getQuantityString(R.plurals.transfer_files, files.size, files.size),+ )+ .setContentText(context.getString(R.string.transfer_received_from, pcName))+ .setContentIntent(tap)+ .setAutoCancel(true)+ .build()+ post(context, idOf(transfer), notification)+ }++ private fun failed(context: Context, transfer: Transfer, pcName: String) {+ val reason = (transfer.status as? TransferStatus.Failed)?.reason+ val text = when (reason) {+ "denied" -> context.getString(R.string.transfer_denied, pcName)+ "unreachable" -> context.getString(R.string.transfer_unreachable, pcName)+ "noSpace" -> context.getString(R.string.transfer_no_space)+ else -> context.getString(R.string.transfer_failed)+ }+ val notification = NotificationCompat.Builder(context, CHANNEL_RECEIVED)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(title(context, transfer))+ .setContentText(text)+ .setAutoCancel(true)+ .build()+ post(context, idOf(transfer), notification)+ }++ private fun allowed(context: Context) =+ android.os.Build.VERSION.SDK_INT < 33 ||+ ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED++ private fun post(context: Context, id: Int, notification: android.app.Notification) {+ if (android.os.Build.VERSION.SDK_INT >= 33 &&+ ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED+ ) {+ return+ }+ NotificationManagerCompat.from(context).notify(id, notification)+ }++ /** "Cancel" on a progress notification. */+ class CancelReceiver : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ val id = intent.getStringExtra(EXTRA_ID) ?: return+ (context.applicationContext as NectarlinkApplication).core.cancelTransfer(id)+ }+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.ktindex 27c8162..d20c52a 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt@@ -36,6 +36,7 @@ class ConnectionService : LifecycleService() {override fun onCreate() {super.onCreate()createChannels(this)+ app.nectarlink.android.files.TransferNotifications.createChannels(this)val core = (application as NectarlinkApplication).corestartInForeground(core.state.value)multicastLock = getSystemService(WifiManager::class.java)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.ktindex f06129b..366bd39 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt@@ -157,7 +157,15 @@ private fun App(core: Core, state: CoreState, preferences: Preferences) {) { padding ->val modifier = Modifier.fillMaxSize().padding(padding)when (tab) {- Tab.Home -> HomeScreen(state, core::ring, core::stopRinging, onPairNew = { pairing = true }, modifier = modifier)+ Tab.Home -> HomeScreen(+ state,+ core::ring,+ core::stopRinging,+ onPairNew = { pairing = true },+ onSendFiles = core::sendFiles,+ onCancelTransfer = core::cancelTransfer,+ modifier = modifier,+ )Tab.Settings -> SettingsScreen(state = state,appearance = preferences.appearance.collectAsStateWithLifecycle().value,diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.ktindex 7e4f72a..1901423 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt@@ -1,7 +1,15 @@// SPDX-License-Identifier: GPL-3.0-or-laterpackage app.nectarlink.android.ui.home+import android.net.Uriimport android.text.format.DateUtils+import android.text.format.Formatter+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.material3.LinearProgressIndicator+import androidx.compose.material3.TextButton+import androidx.compose.ui.text.style.TextOverflowimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column@@ -32,6 +40,7 @@ import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.pluralStringResourceimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.unit.dpimport app.nectarlink.android.R@@ -39,6 +48,10 @@ import app.nectarlink.android.clipboard.SendActivityimport app.nectarlink.android.core.BackgroundAccessimport app.nectarlink.android.core.CoreStateimport app.nectarlink.android.core.Device+import app.nectarlink.android.core.isFinished+import app.nectarlink.core.Transfer+import app.nectarlink.core.TransferDirection+import app.nectarlink.core.TransferStatusimport app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.core.Link@@ -52,6 +65,8 @@ fun HomeScreen(onRing: (id: String, on: Boolean) -> Unit,onStopRinging: () -> Unit,onPairNew: () -> Unit,+ onSendFiles: (pcId: String, uris: List<Uri>) -> Unit,+ onCancelTransfer: (id: String) -> Unit,modifier: Modifier = Modifier,) {LazyColumn(@@ -92,7 +107,10 @@ fun HomeScreen() { context.startActivity(NotificationListener.settingsIntent(context)) }}}- items(state.devices, key = { it.id }) { device -> PcCard(device, onRing) }+ items(state.devices, key = { it.id }) { device -> PcCard(device, onRing, onSendFiles) }+ if (state.transfers.isNotEmpty()) {+ item { TransfersCard(state, onCancelTransfer) }+ }}}@@ -126,7 +144,10 @@ private fun RingingBanner(from: String, onStop: () -> Unit) {}@Composable-private fun PcCard(device: Device, onRing: (String, Boolean) -> Unit) {+private fun PcCard(device: Device, onRing: (String, Boolean) -> Unit, onSendFiles: (String, List<Uri>) -> Unit) {+ val pickFiles = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->+ if (uris.isNotEmpty()) onSendFiles(device.id, uris)+ }var ringing by remember(device.id) { mutableStateOf(false) }Surface(shape = MaterialTheme.shapes.extraLarge,@@ -166,7 +187,7 @@ private fun PcCard(device: Device, onRing: (String, Boolean) -> Unit) {}Spacer(Modifier.height(20.dp))val context = LocalContext.current- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {Button(enabled = device.online,onClick = {@@ -182,7 +203,59 @@ private fun PcCard(device: Device, onRing: (String, Boolean) -> Unit) {) {Text(stringResource(R.string.action_send_clipboard))}+ FilledTonalButton(enabled = device.online, onClick = { pickFiles.launch(arrayOf("*/*")) }) {+ Text(stringResource(R.string.action_send_files))+ }+ }+ }+ }+}++/** Running transfers and the latest finished ones. */+@Composable+private fun TransfersCard(state: CoreState, onCancel: (String) -> Unit) {+ Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.surfaceContainer) {+ Column(Modifier.fillMaxWidth().padding(20.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) {+ Text(stringResource(R.string.transfers_title), style = MaterialTheme.typography.titleMedium)+ state.transfers.forEach { transfer -> TransferRow(transfer, state.nameOf(transfer.deviceId).orEmpty(), onCancel) }+ }+ }+}++@Composable+private fun TransferRow(transfer: Transfer, pc: String, onCancel: (String) -> Unit) {+ val incoming = transfer.direction == TransferDirection.INCOMING+ val status = transfer.status+ val title = if (transfer.names.size == 1) transfer.names[0] else pluralStringResource(R.plurals.transfer_files, transfer.names.size, transfer.names.size)+ val detail = when (status) {+ is TransferStatus.Waiting -> stringResource(R.string.transfer_waiting, pc)+ is TransferStatus.Running ->+ stringResource(if (incoming) R.string.transfer_receiving else R.string.transfer_sending, pc) ++ " · " + Formatter.formatShortFileSize(LocalContext.current, transfer.done.toLong()) ++ " / " + Formatter.formatShortFileSize(LocalContext.current, transfer.total.toLong())+ is TransferStatus.Done ->+ if (incoming) stringResource(R.string.transfer_received_from, pc) else stringResource(R.string.transfer_sent_to, pc)+ is TransferStatus.Cancelled -> stringResource(R.string.transfer_cancelled)+ is TransferStatus.Failed -> when (status.reason) {+ "denied" -> stringResource(R.string.transfer_denied, pc)+ "unreachable" -> stringResource(R.string.transfer_unreachable, pc)+ "noSpace" -> stringResource(R.string.transfer_no_space)+ else -> stringResource(R.string.transfer_failed)+ }+ }+ Row(verticalAlignment = Alignment.CenterVertically) {+ Column(Modifier.weight(1f)) {+ Text(title, style = MaterialTheme.typography.titleSmall, maxLines = 1, overflow = TextOverflow.Ellipsis)+ if (!transfer.isFinished()) {+ Spacer(Modifier.height(6.dp))+ val progress = if (transfer.total == 0uL) 1f else (transfer.done.toDouble() / transfer.total.toDouble()).toFloat()+ LinearProgressIndicator(progress = { progress }, modifier = Modifier.fillMaxWidth())}+ Spacer(Modifier.height(4.dp))+ Text(detail, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ if (!transfer.isFinished()) {+ TextButton(onClick = { onCancel(transfer.id) }) { Text(stringResource(R.string.action_cancel)) }}}}diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 7110370..525d164 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -57,6 +57,23 @@<string name="notifications_restricted">Switch greyed out? Open App info, tap ⋮, choose “Allow restricted settings”, then try again.</string><string name="action_allow">Allow</string><string name="clip_share_label">Send to PC</string>+ <string name="channel_transfers">File transfers</string>+ <string name="channel_received">Received files</string>+ <string name="action_send_files">Send files</string>+ <string name="transfers_title">Transfers</string>+ <string name="transfer_sending">Sending to %1$s</string>+ <string name="transfer_receiving">Receiving from %1$s</string>+ <string name="transfer_waiting">Waiting for %1$s</string>+ <string name="transfer_received_from">From %1$s · in Download/Nectarlink</string>+ <string name="transfer_sent_to">Sent to %1$s</string>+ <string name="transfer_cancelled">Cancelled</string>+ <string name="transfer_denied">%1$s doesn’t accept files from this phone.</string>+ <string name="transfer_unreachable">Couldn’t reach %1$s.</string>+ <string name="transfer_no_space">There isn’t enough space.</string>+ <string name="transfer_failed">The transfer didn’t go through.</string>+ <string name="transfer_nothing">Those files can’t be opened.</string>+ <string name="transfer_off_for">Files are turned off for %1$s.</string>+ <string name="transfer_pick_pc">Send to which PC?</string><string name="clip_tile_label">Send clipboard</string><string name="action_send_clipboard">Send clipboard</string><string name="clip_sent_to">Sent to %1$s</string>@@ -101,4 +118,8 @@<string name="notification_connected_many">Connected to %1$d PCs</string><string name="notification_waiting">Waiting for your PC</string><string name="notification_not_paired">Not paired with a PC yet</string>+ <plurals name="transfer_files">+ <item quantity="one">%1$d file</item>+ <item quantity="other">%1$d files</item>+ </plurals></resources>diff --git a/android/app/src/main/res/xml/file_paths.xml b/android/app/src/main/res/xml/file_paths.xmlnew file mode 100644index 0000000..f9fad49--- /dev/null+++ b/android/app/src/main/res/xml/file_paths.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<!-- Received files on Android 8–9 (see files/ReceivedFiles.kt). -->+<paths>+ <external-files-path name="received" path="Download/Nectarlink/" />+</paths>diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex 62bde94..be6d4b1 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -9,9 +9,9 @@ use std::{io::Write, net::SocketAddr, path::PathBuf, sync::Arc, time::Duration};use anyhow::{Context, Result, bail};use clap::{Parser, Subcommand, ValueEnum};use nectarlink_core::{- Battery, ConnectionPath, DeviceId, DeviceInfo, DeviceKind, FeatureState, LinkState, Node, NodeConfig,- NodeEvent, Notification, NotificationAction, NotificationError, PairedDevice, PairingEvent, Platform,- PowerLevel,+ Battery, ConnectionPath, DeviceId, DeviceInfo, DeviceKind, Direction, FeatureState, FileSource,+ LinkState, Node, NodeConfig, NodeEvent, Notification, NotificationAction, NotificationError,+ OutgoingFile, PairedDevice, PairingEvent, Platform, PowerLevel, TransferState,features::{Effort, FEATURES, Role, UnsupportedReason, Upgrade, UpgradeAction},};use tokio::sync::broadcast::error::RecvError;@@ -111,6 +111,12 @@ enum Command {},/// Stay online and print events until Ctrl+C.Run,+ /// Send files to a paired device and wait until they've arrived.+ Send {+ device: String,+ #[arg(required = true)]+ files: Vec<PathBuf>,+ },/// Put text on a paired device's clipboard.Clip { device: String, text: String },/// Dismiss a phone's notification (`run` prints the keys).@@ -284,6 +290,11 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {node.ring(id, !off).await.context("ring failed")?;println!("{}", if *off { "Stopped ringing." } else { "Ringing…" });}+ Command::Send { device, files } => {+ let id = resolve(node, device)?;+ wait_until_online(node, id).await?;+ send_files(node, id, files).await?;+ }Command::Clip { device, text } => {let id = resolve(node, device)?;wait_until_online(node, id).await?;@@ -441,6 +452,39 @@ async fn confirm_code(code: String) -> Result<bool> {.await?}+/// Sends files and shows progress until they've arrived.+async fn send_files(node: &Node, device: DeviceId, paths: &[PathBuf]) -> Result<()> {+ let mut events = node.events();+ let files = paths+ .iter()+ .map(|path| OutgoingFile {+ name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),+ source: FileSource::Path(path.clone()),+ })+ .collect();+ let id = node.send_files(device, files).await.context("can't send")?;+ loop {+ match events.recv().await {+ Ok(NodeEvent::Transfer(t)) if t.id == id => match t.state {+ TransferState::Done { .. } => {+ println!("\rSent {} file(s), {} bytes. ", t.names.len(), t.total);+ return Ok(());+ }+ TransferState::Failed(why) => bail!("transfer failed: {why:?}"),+ TransferState::Cancelled => bail!("transfer cancelled"),+ TransferState::Waiting => print!("\rWaiting for the device… "),+ TransferState::Running => {+ let percent = (t.done * 100).checked_div(t.total).unwrap_or(100);+ print!("\rSending… {percent}% ");+ }+ },+ Ok(_) | Err(RecvError::Lagged(_)) => {}+ Err(RecvError::Closed) => bail!("node stopped"),+ }+ std::io::stdout().flush()?;+ }+}+async fn watch(node: &Node) -> Result<()> {println!("Online as {}. Press Ctrl+C to stop.", node.device_id());for d in node.paired_devices()? {@@ -507,6 +551,17 @@ fn print_event(node: &Node, event: &NodeEvent) {NodeEvent::NotificationRemoved { device, .. } => {println!("{}: a notification went away", name(device))}+ NodeEvent::ClipboardReceived { device } => println!("{}: sent its clipboard", name(device)),+ NodeEvent::Transfer(t) if t.direction == Direction::Incoming => match &t.state {+ TransferState::Done { saved } => {+ for path in saved {+ println!("{}: received {}", name(&t.device), path.display());+ }+ }+ TransferState::Failed(why) => println!("{}: a transfer failed ({why:?})", name(&t.device)),+ TransferState::Cancelled => println!("{}: a transfer was cancelled", name(&t.device)),+ _ => {}+ },_ => {}}}diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rsindex 2516b66..b71a31a 100644--- a/core/nectarlink-core/src/config.rs+++ b/core/nectarlink-core/src/config.rs@@ -27,6 +27,9 @@ pub struct NodeConfig {/// How the device key is protected at rest. `None` uses the platform/// default (DPAPI on Windows).pub key_protector: Option<std::sync::Arc<dyn KeyProtector>>,+ /// Where received files go once complete. `None`: a `received` folder+ /// in `data_dir`.+ pub downloads_dir: Option<PathBuf>,}impl NodeConfig {@@ -40,6 +43,7 @@ impl NodeConfig {lan_discovery: true,port: 0,key_protector: None,+ downloads_dir: None,}}}@@ -54,6 +58,7 @@ impl fmt::Debug for NodeConfig {.field("away_mode", &self.away_mode).field("lan_discovery", &self.lan_discovery).field("port", &self.port)+ .field("downloads_dir", &self.downloads_dir).finish_non_exhaustive()}}diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rsindex ceb3983..97392da 100644--- a/core/nectarlink-core/src/events.rs+++ b/core/nectarlink-core/src/events.rs@@ -6,7 +6,7 @@ use nectarlink_protocol::{messages::{Battery, DeviceInfo, Notification, PowerLevel},};-use crate::features::CapabilityMatrix;+use crate::{features::CapabilityMatrix, transfer::Transfer};/// How a session is currently carried.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -119,4 +119,6 @@ pub enum NodeEvent {ClipboardReceived {device: DeviceId,},+ /// A file transfer started, progressed or finished.+ Transfer(Transfer),}diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rsindex d21ac87..c46f6f3 100644--- a/core/nectarlink-core/src/features.rs+++ b/core/nectarlink-core/src/features.rs@@ -329,6 +329,7 @@ pub const DEVICE_TOGGLES: &[(&str, bool)] = &[("messages", true),("calls", true),("clipboard", true),+ ("files", true),("photos", true),("pc_actions", true),// Browsing the PC's files from anywhere is opt-in.@@ -606,7 +607,11 @@ pub const FEATURES: &[FeatureDef] = &[FeatureDef {id: "files.send",group: FeatureGroup::Files,- requires: &[phone("files.transfer", UPDATE), desktop("files.transfer", UPDATE)],+ requires: &[+ phone("files.transfer", UPDATE),+ desktop("files.transfer", UPDATE),+ DeviceToggle("files"),+ ],partial: None,},FeatureDef {diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex 32a065d..327c2ad 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -17,6 +17,7 @@ mod notifications;mod pairing;mod session;mod store;+mod transfer;pub use config::{NodeConfig, NoopPlatform, Platform};pub use error::{Error, Result, Side};@@ -34,6 +35,9 @@ pub use nectarlink_protocol::{};pub use node::Node;pub use notifications::NotificationError;+pub use transfer::{+ Direction, FileSource, OutgoingFile, Transfer, TransferFailure, TransferState, safe_file_name,+};pub(crate) fn device_id(key: &iroh::PublicKey) -> DeviceId {DeviceId(*key.as_bytes())diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex 7cdc382..a844199 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -37,6 +37,7 @@ use crate::{pairing::{self, PairingState},session::{self, CLOSE_DUPLICATE, CLOSE_NORMAL, REQUEST_TIMEOUT, Session},store::Store,+ transfer,};const DIAL_TIMEOUT: Duration = Duration::from_secs(15);@@ -52,7 +53,7 @@ const EVENT_CAPACITY: usize = 512;const IDLE_TIMEOUT: Duration = Duration::from_secs(8);/// Capabilities every build offers.-const BASE_CAPABILITIES: &[&str] = &["core.ping", "device.battery", "device.ring"];+const BASE_CAPABILITIES: &[&str] = &["core.ping", "device.battery", "device.ring", "files.transfer"];/// This device's mutable description, sent to peers.#[derive(Debug, Clone)]@@ -101,6 +102,11 @@ pub(crate) struct Shared {memory: MemoryLookup,/// This device's notifications, when it mirrors them (phones).pub notifications: Feed,+ pub data_dir: std::path::PathBuf,+ /// Where received files go.+ pub downloads_dir: std::path::PathBuf,+ /// Running transfers, to cancel them.+ transfers: Mutex<HashMap<String, CancellationToken>>,/// The node's runtime, for work started from non-async callers.runtime: tokio::runtime::Handle,}@@ -121,6 +127,19 @@ impl Shared {let _ = self.events.send(event);}+ /// Where partly received files wait until complete.+ pub fn incoming_dir(&self) -> std::path::PathBuf {+ self.data_dir.join("incoming")+ }++ pub fn register_transfer(&self, id: &str, cancel: CancellationToken) {+ lock(&self.transfers).insert(id.to_owned(), cancel);+ }++ pub fn unregister_transfer(&self, id: &str) {+ lock(&self.transfers).remove(id);+ }+/// Every connected device's session.pub fn live_sessions(&self) -> Vec<Arc<Session>> {lock(&self.sessions).values().filter(|s| s.is_alive()).cloned().collect()@@ -515,7 +534,17 @@ impl Node {let saved = if config.port == 0 { Ports::load(&config.data_dir) } else { None };let wanted =if config.port != 0 { Some(Ports { v4: config.port, v6: Some(config.port) }) } else { saved };- let endpoint = match bind_endpoint(&config, secret.clone(), wanted).await {+ // Right after a restart the previous process may still be letting go+ // of the ports, so try them for a moment before taking others.+ let mut bound = bind_endpoint(&config, secret.clone(), wanted).await;+ for _ in 0..PORT_RETRIES {+ if bound.is_ok() || wanted.is_none() {+ break;+ }+ tokio::time::sleep(PORT_RETRY_DELAY).await;+ bound = bind_endpoint(&config, secret.clone(), wanted).await;+ }+ let endpoint = match bound {Ok(endpoint) => endpoint,Err(e) if config.port == 0 && wanted.is_some() => {tracing::info!(error = %e, "saved ports unavailable; using others");@@ -559,6 +588,9 @@ impl Node {away_mode: config.away_mode,memory,notifications: Feed::default(),+ data_dir: config.data_dir.clone(),+ downloads_dir: config.downloads_dir.clone().unwrap_or_else(|| config.data_dir.join("received")),+ transfers: Mutex::new(HashMap::new()),runtime: tokio::runtime::Handle::current(),});@@ -571,6 +603,9 @@ impl Node {.accept(ALPN_PAIR, PairProtocol(Arc::downgrade(&shared))).spawn();+ let incoming = shared.incoming_dir();+ tokio::task::spawn_blocking(move || transfer::clean_incoming(&incoming));+for peer in shared.store.list_peers()? {shared.remember_addrs(&peer.id, &peer.last_addrs);shared.start_supervisor(peer.id);@@ -786,6 +821,22 @@ impl Node {}}+ // ---- Files (docs/protocol/files.md) ----++ /// Sends files to a paired device; returns the transfer's ID. Progress+ /// and the outcome arrive as [`NodeEvent::Transfer`]; the transfer+ /// waits for the device to connect and resumes after interruptions.+ pub async fn send_files(&self, peer: DeviceId, files: Vec<transfer::OutgoingFile>) -> Result<String> {+ transfer::send(&self.shared, peer, files).await+ }++ /// Cancels a transfer in either direction. Unknown IDs are ignored.+ pub fn cancel_transfer(&self, id: &str) {+ if let Some(cancel) = lock(&self.shared.transfers).get(id) {+ cancel.cancel();+ }+ }+// ---- Clipboard (docs/protocol/clipboard.md) ----/// Puts text on a paired device's clipboard. Fails with@@ -886,6 +937,9 @@ impl Node {}const PORT_FILE: &str = "port";+/// Retrying the saved ports: 5 × 200 ms.+const PORT_RETRIES: usize = 5;+const PORT_RETRY_DELAY: Duration = Duration::from_millis(200);/// The UDP ports the endpoint listens on, remembered across restarts.#[derive(Debug, Clone, Copy, PartialEq, Eq)]diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rsindex 03539f0..d2107e1 100644--- a/core/nectarlink-core/src/session.rs+++ b/core/nectarlink-core/src/session.rs@@ -166,6 +166,7 @@ impl Session {_ = writer(send, outbox_rx) => {}_ = reader(&s, recv, &weak) => {}_ = heartbeat(&s, &weak) => {}+ _ = streams(&s, &weak) => {}_ = s.conn.closed() => {}}cancel.cancel();@@ -350,6 +351,14 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->Ok(())}+/// Streams the other device opens (file transfers), each handled on its own.+async fn streams(session: &Arc<Session>, shared: &Weak<Shared>) {+ while let Ok((send, recv)) = session.conn.accept_bi().await {+ let Some(shared) = shared.upgrade() else { return };+ tokio::spawn(crate::transfer::accept_stream(shared, session.clone(), send, recv));+ }+}+async fn heartbeat(session: &Arc<Session>, shared: &Weak<Shared>) {let started = Instant::now();let mut interval = tokio::time::interval(HEARTBEAT_INTERVAL);diff --git a/core/nectarlink-core/src/transfer.rs b/core/nectarlink-core/src/transfer.rsnew file mode 100644index 0000000..cbd7c12--- /dev/null+++ b/core/nectarlink-core/src/transfer.rs@@ -0,0 +1,656 @@+// SPDX-License-Identifier: MPL-2.0+//! The files service (docs/protocol/files.md): sending files to a paired+//! device on a stream of their own, receiving them, progress, cancelling,+//! and resuming after a dropped connection.++use std::{+ path::{Path, PathBuf},+ sync::Arc,+ time::{Duration, Instant},+};++use iroh::endpoint::{ReadError, RecvStream, SendStream, VarInt, WriteError};+use nectarlink_protocol::{+ DeviceId, Envelope, ErrorCode,+ messages::{+ ErrorBody, FileEntry, FilesAccept, FilesOffer, StreamHeader, files, is_valid_file_name, types,+ },+ read_frame, write_frame,+};+use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};+use tokio_util::sync::CancellationToken;++use crate::{Error, Result, events::NodeEvent, node::Shared, session::Session};++/// The device toggle that allows files for a device.+pub(crate) const TOGGLE: &str = "files";++/// How long a sender keeps trying to reach the device before giving up.+const RETRY_FOR: Duration = Duration::from_secs(10 * 60);+/// Waiting for the other side's answer or confirmation.+const REPLY_TIMEOUT: Duration = Duration::from_secs(30);+/// Progress events, at most this often per transfer.+const PROGRESS_EVERY: Duration = Duration::from_millis(200);+/// Partly received files are kept this long for resuming.+const KEEP_PARTIAL: Duration = Duration::from_secs(60 * 60);+const CHUNK: usize = 256 * 1024;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Direction {+ Outgoing,+ Incoming,+}++/// Why a transfer didn't complete.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum TransferFailure {+ /// The other device has files turned off for this one.+ Denied,+ /// The other device couldn't be reached for a while.+ Unreachable,+ /// The receiving device ran out of space.+ NoSpace,+ /// Stopped by this device shutting down; partly received files are kept,+ /// so it can still resume.+ Interrupted,+ /// Anything else; for logs, never holds file names.+ Other(String),+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum TransferState {+ /// Waiting for the other device: to connect (sending), or to continue+ /// after the connection dropped (receiving; the sender resumes it).+ Waiting,+ Running,+ /// Received files are where `saved` says (one path per file).+ Done {+ saved: Vec<PathBuf>,+ },+ Failed(TransferFailure),+ Cancelled,+}++impl TransferState {+ pub fn is_finished(&self) -> bool {+ matches!(self, TransferState::Done { .. } | TransferState::Failed(_) | TransferState::Cancelled)+ }+}++/// A transfer as the UI shows it.+#[derive(Clone, PartialEq, Eq)]+pub struct Transfer {+ pub id: String,+ pub device: DeviceId,+ pub direction: Direction,+ /// File names, in order.+ pub names: Vec<String>,+ /// Bytes in total and done so far.+ pub total: u64,+ pub done: u64,+ pub state: TransferState,+}++/// Never prints file names (protocol v0 §11).+impl std::fmt::Debug for Transfer {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Transfer")+ .field("id", &self.id)+ .field("direction", &self.direction)+ .field("files", &self.names.len())+ .field("done", &self.done)+ .field("total", &self.total)+ .field("state", &self.state)+ .finish()+ }+}++/// A file to send.+#[derive(Debug)]+pub struct OutgoingFile {+ /// The name the other device sees (no path).+ pub name: String,+ pub source: FileSource,+}++#[derive(Debug)]+pub enum FileSource {+ Path(PathBuf),+ /// An open file (e.g. a descriptor the Android app got for a shared+ /// item). Must be seekable for resuming.+ File(std::fs::File),+}++/// A file name the spec allows, from whatever the sender has.+pub fn safe_file_name(name: &str) -> String {+ let base = name.rsplit(['/', '\\']).next().unwrap_or(name);+ let mut clean: String =+ base.chars().map(|c| if c.is_control() { '_' } else { c }).collect::<String>().trim().to_owned();+ while clean.len() > files::MAX_NAME_BYTES {+ clean.pop();+ }+ if is_valid_file_name(&clean) { clean } else { "file".into() }+}++/// `dir/name`, or `dir/name (2).ext` and so on if that's taken.+pub(crate) fn unique_path(dir: &Path, name: &str) -> PathBuf {+ let first = dir.join(name);+ if !first.exists() {+ return first;+ }+ let (stem, ext) = match name.rfind('.') {+ Some(dot) if dot > 0 => (&name[..dot], &name[dot..]),+ _ => (name, ""),+ };+ (2..).map(|n| dir.join(format!("{stem} ({n}){ext}"))).find(|p| !p.exists()).expect("some name is free")+}++fn new_id() -> String {+ const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";+ (0..24).map(|_| ALPHABET[rand::random_range(0..ALPHABET.len())] as char).collect()+}++/// Publishes a transfer's progress, at most every [`PROGRESS_EVERY`].+struct Reporter {+ shared: Arc<Shared>,+ transfer: Transfer,+ last: Instant,+}++impl Reporter {+ fn new(shared: Arc<Shared>, transfer: Transfer) -> Reporter {+ Reporter { shared, transfer, last: Instant::now() - PROGRESS_EVERY }+ }++ fn set(&mut self, state: TransferState) {+ self.transfer.state = state;+ self.shared.emit(NodeEvent::Transfer(self.transfer.clone()));+ self.last = Instant::now();+ }++ fn progress(&mut self, done: u64) {+ self.transfer.done = done;+ if self.last.elapsed() >= PROGRESS_EVERY {+ self.set(self.transfer.state.clone());+ }+ }+}++// ---- Sending ----++/// Starts sending files; progress and the outcome arrive as+/// [`NodeEvent::Transfer`]. Returns the transfer's ID.+pub(crate) async fn send(shared: &Arc<Shared>, peer: DeviceId, files: Vec<OutgoingFile>) -> Result<String> {+ if files.is_empty() || files.len() > files::MAX_FILES {+ return Err(Error::Protocol("send between 1 and 1000 files".into()));+ }+ if !shared.store.is_paired(&peer)? {+ return Err(Error::NotPaired);+ }+ if !shared.toggle_on(&peer, TOGGLE) {+ return Err(Error::Denied);+ }+ let mut opened = Vec::with_capacity(files.len());+ for file in files {+ let handle = match file.source {+ FileSource::Path(path) => std::fs::File::open(path)?,+ FileSource::File(handle) => handle,+ };+ let size = handle.metadata()?.len();+ opened.push((safe_file_name(&file.name), size, tokio::fs::File::from_std(handle)));+ }+ let transfer = Transfer {+ id: new_id(),+ device: peer,+ direction: Direction::Outgoing,+ names: opened.iter().map(|(name, ..)| name.clone()).collect(),+ total: opened.iter().map(|(_, size, _)| *size).fold(0, u64::saturating_add),+ done: 0,+ state: TransferState::Waiting,+ };+ let id = transfer.id.clone();+ // The user's cancel only: shutting down interrupts a transfer (so it+ // can resume later), it doesn't cancel it.+ let cancel = CancellationToken::new();+ shared.register_transfer(&id, cancel.clone());+ let mut reporter = Reporter::new(shared.clone(), transfer);+ reporter.set(TransferState::Waiting);+ tokio::spawn(async move {+ let state = send_until_done(&mut reporter, opened, &cancel).await;+ reporter.set(state);+ reporter.shared.unregister_transfer(&reporter.transfer.id);+ });+ Ok(id)+}++enum Attempt {+ Done,+ Cancelled,+ Fatal(TransferFailure),+ /// The connection failed; try again once it's back.+ Retry,+}++async fn send_until_done(+ reporter: &mut Reporter,+ mut files: Vec<(String, u64, tokio::fs::File)>,+ cancel: &CancellationToken,+) -> TransferState {+ let peer = reporter.transfer.device;+ let shutdown = reporter.shared.cancel.clone();+ let mut give_up_at = Instant::now() + RETRY_FOR;+ loop {+ if cancel.is_cancelled() {+ return TransferState::Cancelled;+ }+ if shutdown.is_cancelled() {+ return TransferState::Failed(TransferFailure::Interrupted);+ }+ let Some(session) = reporter.shared.session(&peer) else {+ if Instant::now() >= give_up_at {+ return TransferState::Failed(TransferFailure::Unreachable);+ }+ if reporter.transfer.state != TransferState::Waiting {+ reporter.set(TransferState::Waiting);+ }+ tokio::select! {+ _ = cancel.cancelled() => return TransferState::Cancelled,+ _ = shutdown.cancelled() => return TransferState::Failed(TransferFailure::Interrupted),+ _ = tokio::time::sleep(Duration::from_secs(1)) => continue,+ }+ };+ match attempt(reporter, &session, &mut files, cancel).await {+ Attempt::Done => return TransferState::Done { saved: Vec::new() },+ Attempt::Cancelled => return TransferState::Cancelled,+ Attempt::Fatal(failure) => return TransferState::Failed(failure),+ Attempt::Retry => {+ // Made it this far: give the device a fresh window to come back.+ give_up_at = Instant::now() + RETRY_FOR;+ tracing::debug!(id = %reporter.transfer.id, "transfer interrupted; will resume");+ reporter.set(TransferState::Waiting);+ tokio::select! {+ _ = cancel.cancelled() => return TransferState::Cancelled,+ _ = tokio::time::sleep(Duration::from_secs(1)) => {}+ }+ }+ }+ }+}++async fn attempt(+ reporter: &mut Reporter,+ session: &Session,+ files: &mut [(String, u64, tokio::fs::File)],+ cancel: &CancellationToken,+) -> Attempt {+ let Ok((mut send, mut recv)) = session.conn.open_bi().await else { return Attempt::Retry };+ let header = StreamHeader { svc: files::SERVICE.into(), op: files::OP_SEND.into(), v: files::VERSION };+ let offer = FilesOffer {+ id: reporter.transfer.id.clone(),+ files: files.iter().map(|(name, size, _)| FileEntry { name: name.clone(), size: *size }).collect(),+ };+ let (Ok(header), Ok(offer)) =+ (Envelope::new(types::STREAM, &header), Envelope::new(files::OFFER, &offer))+ else {+ return Attempt::Fatal(TransferFailure::Other("can't encode the offer".into()));+ };+ if write_frame(&mut send, &header.to_cbor()).await.is_err()+ || write_frame(&mut send, &offer.to_cbor()).await.is_err()+ {+ return Attempt::Retry;+ }+ let have = match read_reply(&mut recv, cancel).await {+ Reply::Envelope(env) if env.t == files::ACCEPT => match env.body::<FilesAccept>() {+ Ok(accept) if accept.have.len() == files.len() => accept.have,+ _ => return Attempt::Fatal(TransferFailure::Other("bad answer to the offer".into())),+ },+ Reply::Envelope(env) => return Attempt::Fatal(refusal(&env)),+ Reply::Cancelled => {+ let _ = send.reset(VarInt::from_u32(files::CANCELLED));+ return Attempt::Cancelled;+ }+ Reply::Failed => return Attempt::Retry,+ };++ reporter.set(TransferState::Running);+ let mut done: u64 = files.iter().zip(&have).map(|((_, size, _), have)| (*have).min(*size)).sum();+ reporter.progress(done);+ let mut buf = vec![0u8; CHUNK];+ for ((_, size, file), have) in files.iter_mut().zip(&have) {+ let start = (*have).min(*size);+ if file.seek(std::io::SeekFrom::Start(start)).await.is_err() {+ return Attempt::Fatal(TransferFailure::Other("can't read a file".into()));+ }+ let mut left = *size - start;+ while left > 0 {+ let want = buf.len().min(usize::try_from(left).unwrap_or(usize::MAX));+ let read = tokio::select! {+ _ = cancel.cancelled() => {+ let _ = send.reset(VarInt::from_u32(files::CANCELLED));+ return Attempt::Cancelled;+ }+ read = file.read(&mut buf[..want]) => read,+ };+ let n = match read {+ Ok(0) => {+ return Attempt::Fatal(TransferFailure::Other("a file got shorter while sending".into()));+ }+ Ok(n) => n,+ Err(e) => {+ return Attempt::Fatal(TransferFailure::Other(format!(+ "can't read a file: {}",+ e.kind()+ )));+ }+ };+ let written = tokio::select! {+ _ = cancel.cancelled() => {+ let _ = send.reset(VarInt::from_u32(files::CANCELLED));+ return Attempt::Cancelled;+ }+ written = send.write_all(&buf[..n]) => written,+ };+ if let Err(e) = written {+ return match e {+ WriteError::Stopped(code) => stopped(code),+ _ => Attempt::Retry,+ };+ }+ left -= n as u64;+ done += n as u64;+ reporter.progress(done);+ }+ }+ if send.finish().is_err() {+ return Attempt::Retry;+ }+ match read_reply(&mut recv, cancel).await {+ Reply::Envelope(env) if env.t == files::DONE => Attempt::Done,+ Reply::Envelope(env) => Attempt::Fatal(refusal(&env)),+ Reply::Cancelled => Attempt::Cancelled,+ Reply::Failed => Attempt::Retry,+ }+}++/// What a stream reset with `code` by the receiver means.+fn stopped(code: VarInt) -> Attempt {+ match u32::try_from(code.into_inner()).unwrap_or(u32::MAX) {+ files::CANCELLED => Attempt::Cancelled,+ c if c == ErrorCode::Busy.close_code() => Attempt::Fatal(TransferFailure::NoSpace),+ c if c == ErrorCode::Denied.close_code() => Attempt::Fatal(TransferFailure::Denied),+ _ => Attempt::Retry,+ }+}++fn refusal(env: &Envelope) -> TransferFailure {+ match env.body::<ErrorBody>().map(|e| e.code) {+ Ok(ErrorCode::Denied) => TransferFailure::Denied,+ Ok(ErrorCode::Busy) => TransferFailure::NoSpace,+ Ok(code) => TransferFailure::Other(format!("refused: {code}")),+ Err(_) => TransferFailure::Other(format!("unexpected {}", env.t)),+ }+}++enum Reply {+ Envelope(Envelope),+ Cancelled,+ Failed,+}++async fn read_reply(recv: &mut RecvStream, cancel: &CancellationToken) -> Reply {+ let frame = tokio::select! {+ _ = cancel.cancelled() => return Reply::Cancelled,+ frame = tokio::time::timeout(REPLY_TIMEOUT, read_frame(recv)) => frame,+ };+ match frame {+ Ok(Ok(Some(bytes))) => Envelope::from_cbor(&bytes).map_or(Reply::Failed, Reply::Envelope),+ Ok(Err(nectarlink_protocol::ProtocolError::Io(e))) if is_cancel(&e) => Reply::Cancelled,+ _ => Reply::Failed,+ }+}++/// Whether an I/O error from a stream is the other side cancelling.+fn is_cancel(e: &std::io::Error) -> bool {+ e.get_ref().and_then(|inner| inner.downcast_ref::<ReadError>()).is_some_and(+ |r| matches!(r, ReadError::Reset(code) if code.into_inner() == u64::from(files::CANCELLED)),+ )+}++// ---- Receiving ----++/// Handles a stream the other device opened (its header not yet read).+pub(crate) async fn accept_stream(+ shared: Arc<Shared>,+ session: Arc<Session>,+ mut send: SendStream,+ mut recv: RecvStream,+) {+ let header = match tokio::time::timeout(REPLY_TIMEOUT, read_frame(&mut recv)).await {+ Ok(Ok(Some(bytes))) => {+ Envelope::from_cbor(&bytes).ok().and_then(|e| e.expect_body::<StreamHeader>(types::STREAM).ok())+ }+ _ => None,+ };+ match header {+ Some(h) if h.svc == files::SERVICE && h.op == files::OP_SEND && h.v == files::VERSION => {+ receive(shared, session.peer, send, recv).await;+ }+ _ => {+ let reply = Envelope::error(ErrorCode::Unsupported, "unknown stream");+ let _ = write_frame(&mut send, &reply.to_cbor()).await;+ let _ = send.finish();+ }+ }+}++async fn refuse(send: &mut SendStream, code: ErrorCode, msg: &str) {+ let _ = write_frame(send, &Envelope::error(code, msg).to_cbor()).await;+ let _ = send.finish();+}++async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendStream, mut recv: RecvStream) {+ let offer = match tokio::time::timeout(REPLY_TIMEOUT, read_frame(&mut recv)).await {+ Ok(Ok(Some(bytes))) => {+ Envelope::from_cbor(&bytes).ok().and_then(|e| e.expect_body::<FilesOffer>(files::OFFER).ok())+ }+ _ => None,+ };+ let Some(offer) = offer.filter(FilesOffer::is_valid) else {+ return refuse(&mut send, ErrorCode::BadMessage, "invalid offer").await;+ };+ if !shared.toggle_on(&peer, TOGGLE) {+ return refuse(&mut send, ErrorCode::Denied, "files are off for this device").await;+ }+ let dir = shared.incoming_dir().join(&offer.id);+ if let Err(e) = tokio::fs::create_dir_all(&dir).await {+ tracing::warn!(error = %e, "can't store incoming files");+ return refuse(&mut send, ErrorCode::Internal, "can't store files").await;+ }+ let part = |i: usize| dir.join(format!("{i}.part"));+ let mut have = Vec::with_capacity(offer.files.len());+ for (i, file) in offer.files.iter().enumerate() {+ let len = tokio::fs::metadata(part(i)).await.map(|m| m.len()).unwrap_or(0);+ have.push(len.min(file.size));+ }+ let Ok(accept) = Envelope::new(files::ACCEPT, &FilesAccept { have: have.clone() }) else { return };+ if write_frame(&mut send, &accept.to_cbor()).await.is_err() {+ return;+ }++ let cancel = CancellationToken::new();+ shared.register_transfer(&offer.id, cancel.clone());+ let transfer = Transfer {+ id: offer.id.clone(),+ device: peer,+ direction: Direction::Incoming,+ names: offer.files.iter().map(|f| f.name.clone()).collect(),+ total: offer.total_size(),+ done: have.iter().sum(),+ state: TransferState::Running,+ };+ let mut reporter = Reporter::new(shared.clone(), transfer);+ reporter.set(TransferState::Running);+ let state = match receive_bytes(&mut reporter, &offer, &have, &part, &mut send, &mut recv, &cancel).await+ {+ Ok(()) => match store(&shared, &offer, &part, &dir).await {+ Ok(saved) => {+ let _ = write_frame(&mut send, &Envelope::empty(files::DONE).to_cbor()).await;+ let _ = send.finish();+ // Let the confirmation reach the sender before the stream goes.+ let _ = tokio::time::timeout(Duration::from_secs(2), send.stopped()).await;+ TransferState::Done { saved }+ }+ Err(e) => {+ tracing::warn!(error = %e, "can't save received files");+ refuse(&mut send, ErrorCode::Internal, "can't save files").await;+ TransferState::Failed(TransferFailure::Other(format!("can't save: {}", e.kind())))+ }+ },+ Err(state) => {+ if state == TransferState::Cancelled {+ let _ = tokio::fs::remove_dir_all(&dir).await;+ }+ state+ }+ };+ reporter.set(state);+ shared.unregister_transfer(&offer.id);+}++#[allow(clippy::too_many_arguments)]+async fn receive_bytes(+ reporter: &mut Reporter,+ offer: &FilesOffer,+ have: &[u64],+ part: &impl Fn(usize) -> PathBuf,+ send: &mut SendStream,+ recv: &mut RecvStream,+ cancel: &CancellationToken,+) -> std::result::Result<(), TransferState> {+ let mut done: u64 = have.iter().sum();+ for (i, (file, have)) in offer.files.iter().zip(have).enumerate() {+ let mut out =+ tokio::fs::OpenOptions::new().create(true).append(true).open(part(i)).await.map_err(|e| {+ TransferState::Failed(TransferFailure::Other(format!("can't write: {}", e.kind())))+ })?;+ // A part file longer than the file (it changed) starts over.+ if *have < out.metadata().await.map(|m| m.len()).unwrap_or(0) {+ out.set_len(*have).await.ok();+ }+ let mut left = file.size - have;+ while left > 0 {+ let max = CHUNK.min(usize::try_from(left).unwrap_or(usize::MAX));+ let chunk = tokio::select! {+ _ = cancel.cancelled() => {+ let _ = recv.stop(VarInt::from_u32(files::CANCELLED));+ let _ = send.reset(VarInt::from_u32(files::CANCELLED));+ return Err(TransferState::Cancelled);+ }+ chunk = recv.read_chunk(max) => chunk,+ };+ let bytes = match chunk {+ Ok(Some(bytes)) => bytes,+ Ok(None) => return Err(TransferState::Waiting),+ Err(ReadError::Reset(code)) if code.into_inner() == u64::from(files::CANCELLED) => {+ return Err(TransferState::Cancelled);+ }+ // The connection dropped: the sender resumes when it's back.+ Err(_) => return Err(TransferState::Waiting),+ };+ if let Err(e) = out.write_all(&bytes).await {+ let no_space = e.kind() == std::io::ErrorKind::StorageFull;+ let code = if no_space { ErrorCode::Busy } else { ErrorCode::Internal };+ let _ = recv.stop(VarInt::from_u32(code.close_code()));+ return Err(TransferState::Failed(if no_space {+ TransferFailure::NoSpace+ } else {+ TransferFailure::Other(format!("can't write: {}", e.kind()))+ }));+ }+ left -= bytes.len() as u64;+ done += bytes.len() as u64;+ reporter.progress(done);+ }+ out.flush().await.ok();+ }+ Ok(())+}++/// Moves complete files where the user finds them; returns their paths.+async fn store(+ shared: &Shared,+ offer: &FilesOffer,+ part: &impl Fn(usize) -> PathBuf,+ dir: &Path,+) -> std::io::Result<Vec<PathBuf>> {+ let target = shared.downloads_dir.clone();+ let names: Vec<String> = offer.files.iter().map(|f| f.name.clone()).collect();+ let parts: Vec<PathBuf> = (0..names.len()).map(part).collect();+ let dir = dir.to_owned();+ tokio::task::spawn_blocking(move || {+ std::fs::create_dir_all(&target)?;+ let mut saved = Vec::with_capacity(names.len());+ for (name, part) in names.iter().zip(parts) {+ let to = unique_path(&target, name);+ if std::fs::rename(&part, &to).is_err() {+ // Another volume: copy, then drop the part file.+ std::fs::copy(&part, &to)?;+ std::fs::remove_file(&part)?;+ }+ saved.push(to);+ }+ let _ = std::fs::remove_dir_all(&dir);+ Ok(saved)+ })+ .await+ .map_err(std::io::Error::other)?+}++/// Deletes partly received files nobody resumed in time.+pub(crate) fn clean_incoming(dir: &Path) {+ let Ok(entries) = std::fs::read_dir(dir) else { return };+ for entry in entries.flatten() {+ let stale = entry+ .metadata()+ .and_then(|m| m.modified())+ .is_ok_and(|t| t.elapsed().unwrap_or_default() > KEEP_PARTIAL);+ if stale {+ let _ = std::fs::remove_dir_all(entry.path());+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn names_are_made_safe() {+ assert_eq!(safe_file_name("photo.jpg"), "photo.jpg");+ assert_eq!(safe_file_name(r"C:\Users\x\report.pdf"), "report.pdf");+ assert_eq!(safe_file_name("../../etc/passwd"), "passwd");+ assert_eq!(safe_file_name("a\nb"), "a_b");+ assert_eq!(safe_file_name(".."), "file");+ assert_eq!(safe_file_name(""), "file");+ assert!(safe_file_name(&"é".repeat(300)).len() <= files::MAX_NAME_BYTES);+ }++ #[test]+ fn taken_names_get_a_number() {+ let dir = tempfile::tempdir().unwrap();+ assert_eq!(unique_path(dir.path(), "a.txt"), dir.path().join("a.txt"));+ std::fs::write(dir.path().join("a.txt"), "x").unwrap();+ std::fs::write(dir.path().join("a (2).txt"), "x").unwrap();+ assert_eq!(unique_path(dir.path(), "a.txt"), dir.path().join("a (3).txt"));+ std::fs::write(dir.path().join("README"), "x").unwrap();+ assert_eq!(unique_path(dir.path(), "README"), dir.path().join("README (2)"));+ std::fs::write(dir.path().join(".env"), "x").unwrap();+ assert_eq!(unique_path(dir.path(), ".env"), dir.path().join(".env (2)"));+ }++ #[test]+ fn ids_are_valid() {+ assert!(nectarlink_protocol::messages::is_valid_transfer_id(&new_id()));+ assert_ne!(new_id(), new_id());+ }+}diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex f470588..203bc99 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -9,9 +9,10 @@ use std::{};use nectarlink_core::{- Battery, DeviceInfo, DeviceKind, Error, FeatureState, LinkState, Node, NodeConfig, NodeEvent,- Notification, NotificationAction, NotificationError, PairingEvent, PairingFailure, PairingUri,- PlainKeyProtector, Platform, PowerLevel,+ Battery, DeviceInfo, DeviceKind, Direction, Error, FeatureState, FileSource, LinkState, Node, NodeConfig,+ NodeEvent, Notification, NotificationAction, NotificationError, OutgoingFile, PairingEvent,+ PairingFailure, PairingUri, PlainKeyProtector, Platform, PowerLevel, Transfer, TransferFailure,+ TransferState,features::{Effort, Upgrade, UpgradeAction},};use tempfile::TempDir;@@ -350,7 +351,13 @@ async fn reconnects_after_a_restart() {let TestDevice { node: old_node, dir, .. } = phone;drop(old_node);let mut phone = start_in(dir, "Pixel", DeviceKind::Phone).await;- assert_eq!(ports(phone.node.direct_addrs().await), old_ports, "the port is kept across restarts");+ // The port is kept, unless something else took it in the meantime+ // (other tests run in parallel); then any free port is fine.+ let new_ports = ports(phone.node.direct_addrs().await);+ if new_ports != old_ports {+ let taken = old_ports.iter().any(|p| std::net::UdpSocket::bind(("0.0.0.0", *p)).is_err());+ assert!(taken, "the port is kept across restarts when it's free: {old_ports:?} -> {new_ports:?}");+ }assert_eq!(phone.node.device_id(), phone_id, "identity survives the restart");assert_eq!(phone.node.paired_devices().unwrap().len(), 1, "pairing survives the restart");@@ -577,3 +584,161 @@ async fn clipboard_text_goes_both_ways_with_consent() {let huge = "x".repeat(nectarlink_core::CLIP_MAX_BYTES + 1);assert!(matches!(pc.node.send_clipboard(phone_id, huge).await, Err(Error::TooLarge)));}++/// Deterministic, incompressible-looking test data.+fn data(len: usize, seed: u64) -> Vec<u8> {+ let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;+ (0..len)+ .map(|_| {+ x ^= x << 13;+ x ^= x >> 7;+ x ^= x << 17;+ x as u8+ })+ .collect()+}++fn outgoing(dir: &std::path::Path, name: &str, contents: &[u8]) -> OutgoingFile {+ let path = dir.join(name);+ std::fs::write(&path, contents).unwrap();+ OutgoingFile { name: name.into(), source: FileSource::Path(path) }+}++/// Waits for a transfer to reach a state matching `pick`.+async fn wait_transfer<T>(+ dev: &mut TestDevice,+ id: &str,+ what: &str,+ mut pick: impl FnMut(&Transfer) -> Option<T>,+) -> T {+ wait_for(dev, what, |e| match e {+ NodeEvent::Transfer(t) if t.id == id => pick(t),+ _ => None,+ })+ .await+}++fn saved(t: &Transfer) -> Option<Vec<std::path::PathBuf>> {+ match &t.state {+ TransferState::Done { saved } => Some(saved.clone()),+ TransferState::Failed(f) => panic!("transfer failed: {f:?}"),+ TransferState::Cancelled => panic!("transfer cancelled"),+ _ => None,+ }+}++#[tokio::test(flavor = "multi_thread")]+async fn files_arrive_intact_under_free_names() {+ let mut pc = device("Desktop", DeviceKind::Desktop).await;+ let mut phone = device("Pixel", DeviceKind::Phone).await;+ pair_qr(&mut pc, &mut phone).await;+ let phone_id = phone.node.device_id();+ let src = tempfile::tempdir().unwrap();+ let big = data(3 * 1024 * 1024 + 17, 1);+ let small = b"hello".to_vec();++ // The phone already has a "notes.txt".+ let downloads = phone.dir.path().join("received");+ std::fs::create_dir_all(&downloads).unwrap();+ std::fs::write(downloads.join("notes.txt"), "old").unwrap();++ let files = vec![outgoing(src.path(), "video.bin", &big), outgoing(src.path(), "notes.txt", &small)];+ let id = with_timeout("send", pc.node.send_files(phone_id, files)).await.expect("send starts");++ let received = wait_transfer(&mut phone, &id, "received", |t| {+ assert_eq!(t.direction, Direction::Incoming);+ assert_eq!(t.names, ["video.bin", "notes.txt"]);+ saved(t)+ })+ .await;+ assert_eq!(received, [downloads.join("video.bin"), downloads.join("notes (2).txt")]);+ assert_eq!(std::fs::read(&received[0]).unwrap(), big);+ assert_eq!(std::fs::read(&received[1]).unwrap(), small);+ assert_eq!(std::fs::read(downloads.join("notes.txt")).unwrap(), b"old", "existing files are kept");++ let sent = wait_transfer(&mut pc, &id, "sent", |t| {+ assert_eq!(t.direction, Direction::Outgoing);+ saved(t).map(|_| t.done)+ })+ .await;+ assert_eq!(sent, big.len() as u64 + 5);+ assert!(+ std::fs::read_dir(phone.dir.path().join("incoming")).unwrap().next().is_none(),+ "no partial files are left"+ );+}++#[tokio::test(flavor = "multi_thread")]+async fn files_need_the_toggle_and_can_be_cancelled() {+ let mut pc = device("Desktop", DeviceKind::Desktop).await;+ let mut phone = device("Pixel", DeviceKind::Phone).await;+ pair_qr(&mut pc, &mut phone).await;+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());+ let src = tempfile::tempdir().unwrap();++ // The phone doesn't take files from this PC.+ phone.node.set_device_toggle(pc_id, "files", false).unwrap();+ let id = pc.node.send_files(phone_id, vec![outgoing(src.path(), "a.txt", b"a")]).await.unwrap();+ let state =+ wait_transfer(&mut pc, &id, "refused", |t| t.state.is_finished().then(|| t.state.clone())).await;+ assert_eq!(state, TransferState::Failed(TransferFailure::Denied));+ phone.node.set_device_toggle(pc_id, "files", true).unwrap();+ // This PC doesn't send files to the phone.+ pc.node.set_device_toggle(phone_id, "files", false).unwrap();+ assert!(matches!(+ pc.node.send_files(phone_id, vec![outgoing(src.path(), "b.txt", b"b")]).await,+ Err(Error::Denied)+ ));+ pc.node.set_device_toggle(phone_id, "files", true).unwrap();++ // Cancelled by the receiver as soon as bytes flow.+ let big = data(64 * 1024 * 1024, 2);+ let id = pc.node.send_files(phone_id, vec![outgoing(src.path(), "big.bin", &big)]).await.unwrap();+ wait_transfer(&mut phone, &id, "receiving", |t| {+ (t.state == TransferState::Running && t.done > 0).then_some(())+ })+ .await;+ phone.node.cancel_transfer(&id);+ let on_phone =+ wait_transfer(&mut phone, &id, "cancelled here", |t| t.state.is_finished().then(|| t.state.clone()))+ .await;+ let on_pc =+ wait_transfer(&mut pc, &id, "cancelled there", |t| t.state.is_finished().then(|| t.state.clone()))+ .await;+ assert_eq!((on_phone, on_pc), (TransferState::Cancelled, TransferState::Cancelled));+ assert!(!phone.dir.path().join("received").join("big.bin").exists());+}++#[tokio::test(flavor = "multi_thread")]+async fn transfers_resume_after_the_receiver_restarts() {+ let mut pc = device("Desktop", DeviceKind::Desktop).await;+ let mut phone = device("Pixel", DeviceKind::Phone).await;+ pair_qr(&mut pc, &mut phone).await;+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());+ let src = tempfile::tempdir().unwrap();+ let big = data(96 * 1024 * 1024, 3);+ let id = pc.node.send_files(phone_id, vec![outgoing(src.path(), "big.bin", &big)]).await.unwrap();++ // The phone goes away part way through.+ let before = wait_transfer(&mut phone, &id, "receiving", |t| (t.done > 0).then_some(t.done)).await;+ phone.node.shutdown().await;+ let TestDevice { node, dir, .. } = phone;+ drop(node);+ let interrupted = std::fs::metadata(dir.path().join("incoming").join(&id).join("0.part")).unwrap().len();+ assert!(interrupted >= before && interrupted < big.len() as u64, "{interrupted} of {}", big.len());+ wait_transfer(&mut pc, &id, "waiting for the phone", |t| {+ (t.state == TransferState::Waiting).then_some(())+ })+ .await;++ // Back again: the transfer continues where it stopped.+ let mut phone = start_in(dir, "Pixel", DeviceKind::Phone).await;+ let resumed_at =+ wait_transfer(&mut phone, &id, "resumed", |t| (t.state == TransferState::Running).then_some(t.done))+ .await;+ assert!(resumed_at >= interrupted, "resumed at {resumed_at}, had {interrupted}");+ let received = wait_transfer(&mut phone, &id, "received", saved).await;+ assert_eq!(std::fs::read(&received[0]).unwrap(), big);+ wait_transfer(&mut pc, &id, "sent", saved).await;+ let _ = pc_id;+}diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex e97fd1b..bf402b0 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -172,6 +172,65 @@ impl std::fmt::Debug for Notification {}}+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]+pub enum TransferDirection {+ Outgoing,+ Incoming,+}++#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]+pub enum TransferStatus {+ /// Waiting for the other device (to connect, or to continue).+ Waiting,+ Running,+ /// `saved`: where received files are, one path per file (empty when+ /// sending).+ Done {+ saved: Vec<String>,+ },+ /// `reason`: "denied", "unreachable", "noSpace", "interrupted" or+ /// "other".+ Failed {+ reason: String,+ },+ Cancelled,+}++/// A file transfer (docs/protocol/files.md).+#[derive(Clone, PartialEq, Eq, uniffi::Record)]+pub struct Transfer {+ pub id: String,+ /// The other device.+ pub device_id: String,+ pub direction: TransferDirection,+ pub names: Vec<String>,+ pub total: u64,+ pub done: u64,+ pub status: TransferStatus,+}++/// Never prints file names (protocol v0 §11).+impl std::fmt::Debug for Transfer {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Transfer").field("id", &self.id).field("status", &self.status).finish_non_exhaustive()+ }+}++/// A file to send.+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]+pub enum FileToSend {+ /// An open, readable descriptor (Android: from a content URI). The core+ /// takes ownership and closes it.+ Fd {+ name: String,+ fd: i32,+ },+ Path {+ name: String,+ path: String,+ },+}+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]pub struct DeviceToggle {pub name: String,@@ -245,6 +304,10 @@ pub enum Event {ClipboardReceived {id: String,},+ /// A file transfer started, progressed or finished.+ Transfer {+ transfer: Transfer,+ },}#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]@@ -480,6 +543,66 @@ impl From<Notification> for core::Notification {}}+impl From<core::Transfer> for Transfer {+ fn from(t: core::Transfer) -> Self {+ Transfer {+ id: t.id,+ device_id: t.device.to_string(),+ direction: match t.direction {+ core::Direction::Outgoing => TransferDirection::Outgoing,+ core::Direction::Incoming => TransferDirection::Incoming,+ },+ names: t.names,+ total: t.total,+ done: t.done,+ status: match t.state {+ core::TransferState::Waiting => TransferStatus::Waiting,+ core::TransferState::Running => TransferStatus::Running,+ core::TransferState::Done { saved } => TransferStatus::Done {+ saved: saved.into_iter().map(|p| p.to_string_lossy().into_owned()).collect(),+ },+ core::TransferState::Failed(failure) => TransferStatus::Failed {+ reason: match failure {+ core::TransferFailure::Denied => "denied",+ core::TransferFailure::Unreachable => "unreachable",+ core::TransferFailure::NoSpace => "noSpace",+ core::TransferFailure::Interrupted => "interrupted",+ core::TransferFailure::Other(_) => "other",+ }+ .into(),+ },+ core::TransferState::Cancelled => TransferStatus::Cancelled,+ },+ }+ }+}++fn file_to_send(file: FileToSend) -> Result<core::OutgoingFile> {+ Ok(match file {+ FileToSend::Path { name, path } => {+ core::OutgoingFile { name, source: core::FileSource::Path(path.into()) }+ }+ #[cfg(unix)]+ FileToSend::Fd { name, fd } => {+ use std::os::fd::FromRawFd;+ if fd < 0 {+ return Err(NectarlinkError::Internal { reason: "invalid file descriptor".into() });+ }+ // SAFETY: the caller hands over an open descriptor it no longer+ // uses (documented on `FileToSend::Fd`); the File closes it.+ #[allow(unsafe_code)]+ let file = unsafe { std::fs::File::from_raw_fd(fd) };+ core::OutgoingFile { name, source: core::FileSource::File(file) }+ }+ #[cfg(not(unix))]+ FileToSend::Fd { .. } => {+ return Err(NectarlinkError::Internal {+ reason: "file descriptors exist only on Android".into(),+ });+ }+ })+}+fn upgrade(u: core::features::Upgrade) -> Upgrade {let (action, target) = u.action.describe();Upgrade { action: action.into(), target, minutes: u.effort.minutes() }@@ -543,6 +666,7 @@ impl From<NodeEvent> for Event {Event::NotificationRemoved { id: device.to_string(), key }}NodeEvent::ClipboardReceived { device } => Event::ClipboardReceived { id: device.to_string() },+ NodeEvent::Transfer(t) => Event::Transfer { transfer: t.into() },}}}@@ -676,6 +800,9 @@ pub struct NodeOptions {pub power: PowerLevel,/// Allow connections through relays when away from home.pub away_mode: bool,+ /// Where received files are put once complete (the app then moves them+ /// where the user finds them).+ pub downloads_dir: String,}/// The Nectarlink engine. One per app process.@@ -724,6 +851,7 @@ impl NectarlinkNode {NodeConfig::new(PathBuf::from(options.data_dir), options.device.into(), options.app_version);config.power = options.power.into();config.away_mode = options.away_mode;+ config.downloads_dir = Some(PathBuf::from(options.downloads_dir));config.key_protector = Some(Arc::new(KeyProtectorAdapter(key_protector)));let node = runtime.block_on(Node::start(config, Arc::new(PlatformAdapter(platform))))?;@@ -826,6 +954,22 @@ impl NectarlinkNode {Ok(self.node.set_device_toggle(parse_id(&id)?, &name, enabled)?)}+ // ---- Files ----++ /// Sends files to a paired PC; returns the transfer's ID. Progress+ /// arrives as `Event::Transfer`.+ pub async fn send_files(&self, id: String, files: Vec<FileToSend>) -> Result<String> {+ let id = parse_id(&id)?;+ let files = files.into_iter().map(file_to_send).collect::<Result<Vec<_>>>()?;+ let node = self.node.clone();+ self.run(async move { Ok(node.send_files(id, files).await?) }).await+ }++ /// Cancels a transfer in either direction.+ pub fn cancel_transfer(&self, transfer_id: String) {+ self.node.cancel_transfer(&transfer_id);+ }+// ---- Clipboard ----/// Puts text on a paired PC's clipboard.diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 3805bde..a893d69 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -317,6 +317,83 @@ impl std::fmt::Debug for NotifyAction {}}+// ---- Files (docs/protocol/files.md) ----++/// The files service and its one operation, for stream headers.+pub mod files {+ pub const SERVICE: &str = "files";+ pub const OP_SEND: &str = "send";+ pub const VERSION: u32 = 1;+ pub const OFFER: &str = "files.offer";+ pub const ACCEPT: &str = "files.accept";+ pub const DONE: &str = "files.done";+ /// Stream reset code for a cancelled transfer.+ pub const CANCELLED: u32 = 10;+ pub const MAX_FILES: usize = 1000;+ pub const MAX_NAME_BYTES: usize = 255;+}++/// One file of an offer.+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct FileEntry {+ pub name: String,+ pub size: u64,+}++/// Never prints the name (protocol v0 §11).+impl std::fmt::Debug for FileEntry {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("FileEntry").field("size", &self.size).finish_non_exhaustive()+ }+}++/// Body of `files.offer`.+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct FilesOffer {+ pub id: String,+ pub files: Vec<FileEntry>,+}++/// Never prints file names (protocol v0 §11).+impl std::fmt::Debug for FilesOffer {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("FilesOffer").field("id", &self.id).field("files", &self.files.len()).finish()+ }+}++/// Body of `files.accept`: bytes already received, per file.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct FilesAccept {+ pub have: Vec<u64>,+}++/// Whether a name is a plain file name the spec allows (no path, no+/// control characters, not `.` or `..`).+pub fn is_valid_file_name(name: &str) -> bool {+ !name.is_empty()+ && name.len() <= files::MAX_NAME_BYTES+ && name != "."+ && name != ".."+ && !name.chars().any(|c| c == '/' || c == '\\' || c.is_control())+}++/// Whether a transfer ID is 16–64 of `[A-Za-z0-9_-]`.+pub fn is_valid_transfer_id(id: &str) -> bool {+ (16..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')+}++impl FilesOffer {+ pub fn is_valid(&self) -> bool {+ is_valid_transfer_id(&self.id)+ && (1..=files::MAX_FILES).contains(&self.files.len())+ && self.files.iter().all(|f| is_valid_file_name(&f.name))+ }++ pub fn total_size(&self) -> u64 {+ self.files.iter().map(|f| f.size).fold(0, u64::saturating_add)+ }+}+// ---- Clipboard (docs/protocol/clipboard.md) ----/// Largest clipboard text sent or accepted, in UTF-8 bytes.@@ -463,6 +540,22 @@ mod tests {assert!(!format!("{action:?}").contains("secret"));}+ #[test]+ fn file_offers_are_validated() {+ let offer = |id: &str, names: &[&str]| FilesOffer {+ id: id.into(),+ files: names.iter().map(|n| FileEntry { name: (*n).into(), size: 1 }).collect(),+ };+ assert!(offer("abcdefghijklmnop", &["photo.jpg", "Résumé (final).pdf"]).is_valid());+ for bad in ["", ".", "..", "a/b", "a\\b", "x\u{0}y", "tab\there"] {+ assert!(!offer("abcdefghijklmnop", &[bad]).is_valid(), "{bad:?}");+ }+ assert!(!offer("short", &["a"]).is_valid(), "IDs are 16+ characters");+ assert!(!offer("abcdefghijklmnop!", &["a"]).is_valid());+ assert!(!offer("abcdefghijklmnop", &[]).is_valid(), "at least one file");+ assert!(!format!("{:?}", offer("abcdefghijklmnop", &["secret.pdf"])).contains("secret"));+ }+#[test]fn power_level_wire_names() {let env = Envelope::new("x", &PowerLevel::NotApplicable).unwrap();diff --git a/desktop/app/build.rs b/desktop/app/build.rsindex cfa6d91..3e4ad33 100644--- a/desktop/app/build.rs+++ b/desktop/app/build.rs@@ -33,6 +33,7 @@ const QML: &[&str] = &["qml/components/StatusDot.qml","qml/components/Toast.qml","qml/components/Toggle.qml",+ "qml/components/TransferItem.qml","qml/components/Txt.qml","qml/pages/HomePage.qml","qml/pages/PairingPanel.qml",@@ -81,6 +82,7 @@ fn main() {"src/bridge/notifications.rs","src/bridge/pairing.rs","src/bridge/prefs.rs",+ "src/bridge/transfers.rs",]).build();diff --git a/desktop/app/qml/components/LockChip.qml b/desktop/app/qml/components/LockChip.qmlindex 72fbd87..0fd0dcd 100644--- a/desktop/app/qml/components/LockChip.qml+++ b/desktop/app/qml/components/LockChip.qml@@ -13,7 +13,10 @@ Rectangle {let what = ""switch (s.action) {case "raisePower": what = s.target === "elevated" ? qsTr("Elevated") : qsTr("Assist"); break- case "grantPermission": what = qsTr("Permission"); break+ case "grantPermission":+ what = feature.target === "notification_access" ? qsTr("Allow notification access on the phone")+ : qsTr("Allow it on the phone")+ breakcase "enableAddon": what = qsTr("Add-on"); breakcase "enablePath": what = qsTr("Away mode"); breakcase "enableToggle": what = qsTr("Turned off"); breakdiff --git a/desktop/app/qml/components/TransferItem.qml b/desktop/app/qml/components/TransferItem.qmlnew file mode 100644index 0000000..32b2f17--- /dev/null+++ b/desktop/app/qml/components/TransferItem.qml@@ -0,0 +1,132 @@+// SPDX-License-Identifier: GPL-3.0-or-later+import QtQuick+import app.nectarlink++// One file transfer: direction, name, progress and speed, and what can be+// done with it (cancel while it runs; open or show what arrived).+Item {+ id: item+ required property string transferId+ required property string deviceName+ required property bool incoming+ required property string title+ required property real total+ required property real done+ required property real progress+ required property real rate+ required property string status+ required property string reason+ required property string savedPath++ readonly property bool active: status === "waiting" || status === "running"++ implicitHeight: column.height + 20++ function size(bytes) {+ if (bytes < 1024) return qsTr("%1 B").arg(Math.round(bytes))+ const units = ["KB", "MB", "GB", "TB"]+ let value = bytes / 1024+ let unit = 0+ while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++ }+ return (value < 10 ? value.toFixed(1) : Math.round(value)) + " " + units[unit]+ }++ function detail() {+ switch (status) {+ case "waiting":+ return item.incoming ? qsTr("Paused; continues when %1 is back").arg(item.deviceName)+ : qsTr("Waiting for %1").arg(item.deviceName)+ case "running":+ return qsTr("%1 of %2").arg(size(done)).arg(size(total))+ + (rate > 0 ? " · " + qsTr("%1/s").arg(size(rate)) : "")+ case "done":+ return item.incoming ? qsTr("From %1 · %2").arg(item.deviceName).arg(size(total))+ : qsTr("Sent to %1 · %2").arg(item.deviceName).arg(size(total))+ case "cancelled":+ return qsTr("Cancelled")+ default:+ switch (reason) {+ case "denied": return qsTr("%1 doesn't accept files from this PC").arg(item.deviceName)+ case "unreachable": return qsTr("Couldn't reach %1").arg(item.deviceName)+ case "noSpace": return qsTr("Not enough space on %1").arg(item.deviceName)+ default: return qsTr("Didn't go through")+ }+ }+ }++ Row {+ id: row+ x: 4; y: 10+ width: parent.width - 8+ spacing: 12++ Rectangle {+ width: 32; height: 32+ radius: Theme.graphite ? Theme.radiusSm : 16+ color: Theme.graphite ? "transparent" : Theme.secondaryContainer+ border.width: Theme.graphite ? 1 : 0+ border.color: Theme.outlineVariant+ Icon {+ anchors.centerIn: parent+ width: 18; height: 18+ path: item.incoming ? Icons.folder : Icons.send+ color: Theme.graphite ? Theme.surfaceContent : Theme.secondaryContainerContent+ }+ }++ Column {+ id: column+ width: row.width - 32 - actions.width - row.spacing * 2+ spacing: 6+ Txt { width: parent.width; role: "title"; size: 14; text: item.title }+ // Progress, while there's progress to show.+ Rectangle {+ width: parent.width+ height: 4+ radius: 2+ visible: item.active+ color: Theme.surfaceContainerHighest+ Rectangle {+ height: parent.height+ radius: parent.radius+ width: parent.width * Math.max(0, Math.min(1, item.progress))+ color: Theme.primary+ opacity: item.status === "waiting" ? 0.45 : 1+ Behavior on width { NumberAnimation { duration: Theme.reduceMotion ? 0 : 180 } }+ }+ }+ Txt {+ width: parent.width+ role: "bodySmall"+ muted: true+ color: item.status === "failed" ? Theme.error : Theme.surfaceContentVariant+ text: item.detail()+ }+ }++ Row {+ id: actions+ anchors.verticalCenter: parent.verticalCenter+ spacing: 4+ Button {+ visible: item.status === "done" && item.incoming && item.savedPath.length > 0+ variant: "text"+ size: "sm"+ text: qsTr("Open")+ onClicked: TransferList.open(item.transferId)+ }+ IconButton {+ visible: item.status === "done" && item.incoming && item.savedPath.length > 0+ iconPath: Icons.folder+ label: qsTr("Show in folder")+ onClicked: TransferList.showInFolder(item.transferId)+ }+ IconButton {+ visible: item.active+ iconPath: Icons.close+ label: qsTr("Cancel")+ onClicked: TransferList.cancel(item.transferId)+ }+ }+ }+}diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qmlindex 8376e76..662ba05 100644--- a/desktop/app/qml/pages/HomePage.qml+++ b/desktop/app/qml/pages/HomePage.qml@@ -1,5 +1,6 @@// SPDX-License-Identifier: GPL-3.0-or-laterimport QtQuick+import QtQuick.Dialogsimport app.nectarlink// Home: the paired phone at a glance (status, battery, power level) and@@ -9,6 +10,10 @@ Item {id: pageproperty bool active: trueproperty int current: 0+ // The device shown, for dropped files.+ property string currentDeviceId+ property string currentDeviceName+ property bool currentCanReceive: falsesignal pairRequestedopacity: active ? 1 : 0@@ -79,6 +84,48 @@ Item {}}+ // Files dragged onto the page are sent to the device on screen.+ DropArea {+ id: drop+ anchors.fill: parent+ enabled: page.currentCanReceive+ onEntered: (drag) => drag.accepted = drag.hasUrls+ onDropped: (drag) => {+ if (drag.hasUrls) {+ TransferList.send(page.currentDeviceId, drag.urls.map(url => url.toString()))+ drag.accept(Qt.CopyAction)+ }+ }+ }+ Rectangle {+ anchors.fill: parent+ anchors.margins: Theme.contentPadding / 2+ radius: Theme.radiusXl+ visible: opacity > 0+ opacity: drop.containsDrag ? 1 : 0+ Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }+ color: Qt.rgba(Theme.primaryContainer.r, Theme.primaryContainer.g, Theme.primaryContainer.b, 0.92)+ border.width: 2+ border.color: Theme.primary+ Column {+ anchors.centerIn: parent+ spacing: 12+ Icon {+ anchors.horizontalCenter: parent.horizontalCenter+ width: 40; height: 40+ stroke: 1.6+ path: Icons.send+ color: Theme.primaryContainerContent+ }+ Txt {+ anchors.horizontalCenter: parent.horizontalCenter+ role: "headline"+ color: Theme.primaryContainerContent+ text: qsTr("Drop to send to %1").arg(page.currentDeviceName)+ }+ }+ }+component DeviceHome: Row {id: homerequired property string deviceId@@ -95,6 +142,16 @@ Item {required property real lastSeenrequired property real pairedAt+ // Dropped files go to the device on screen.+ Binding { target: page; property: "currentDeviceId"; value: home.deviceId; when: home.visible }+ Binding { target: page; property: "currentDeviceName"; value: home.name; when: home.visible }+ Binding {+ target: page+ property: "currentCanReceive"+ value: home.feature("files.send").state === "available"+ when: home.visible+ }+// Re-read capabilities whenever any matrix changes.function feature(id) {return AppController.capsRevision >= 0 ? AppController.featureState(deviceId, id) : ({})@@ -224,10 +281,62 @@ Item {ActionTile {width: actions.tileWidthtitle: qsTr("Send files")- subtitle: qsTr("Or drop anywhere")+ subtitle: qsTr("Or drop them here")iconPath: Icons.sendfeature: home.feature("files.send")- ready: false+ onClicked: filePicker.open()+ }+ }+ FileDialog {+ id: filePicker+ title: qsTr("Send to %1").arg(home.name)+ fileMode: FileDialog.OpenFiles+ onAccepted: TransferList.send(home.deviceId, selectedFiles.map(url => url.toString()))+ }++ // ---- Transfers ----+ Card {+ width: parent.width+ visible: TransferList.count > 0+ Column {+ width: parent.width+ spacing: 4+ Item {+ width: parent.width+ height: Math.max(transfersHeader.height, clearTransfers.height)+ Txt {+ id: transfersHeader+ anchors.verticalCenter: parent.verticalCenter+ role: "label"+ muted: true+ text: qsTr("Transfers")+ }+ Button {+ id: clearTransfers+ anchors.right: parent.right+ visible: TransferList.count > TransferList.active+ variant: "text"+ size: "sm"+ text: qsTr("Clear finished")+ onClicked: TransferList.clearFinished()+ }+ }+ ListView {+ id: transferList+ width: parent.width+ height: contentHeight+ interactive: false+ model: TransferList+ delegate: TransferItem { width: transferList.width }+ add: Transition {+ enabled: !Theme.reduceMotion+ NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 200 }+ }+ displaced: Transition {+ enabled: !Theme.reduceMotion+ NumberAnimation { property: "y"; duration: 220; easing.type: Easing.OutCubic }+ }+ }}}diff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rsindex 6b15a4f..f167d52 100644--- a/desktop/app/src/bridge/mod.rs+++ b/desktop/app/src/bridge/mod.rs@@ -17,6 +17,8 @@ pub mod notifications;pub mod pairing;#[allow(unsafe_code)]pub mod prefs;+#[allow(unsafe_code)]+pub mod transfers;use std::{pin::Pin,diff --git a/desktop/app/src/bridge/transfers.rs b/desktop/app/src/bridge/transfers.rsnew file mode 100644index 0000000..d7a680e--- /dev/null+++ b/desktop/app/src/bridge/transfers.rs@@ -0,0 +1,340 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! `TransferList`: file transfers (newest first) as a Qt list model, plus+//! the commands QML runs on them.++use std::{path::PathBuf, pin::Pin};++use cxx_qt::{CxxQtType, Threading};+use cxx_qt_lib::{+ QByteArray, QHash, QHashPair_i32_QByteArray, QList, QModelIndex, QString, QStringList, QUrl, QVariant,+};+use nectarlink_core::{Direction, TransferFailure, TransferState};++use super::{Edit, diff};+use crate::{+ core_host,+ state::{Changes, TransferView},+ transfers,+};++#[cxx_qt::bridge]+pub mod qobject {+ unsafe extern "C++" {+ include!(<QtCore/QAbstractListModel>);+ type QAbstractListModel;++ include!("cxx-qt-lib/qmodelindex.h");+ type QModelIndex = cxx_qt_lib::QModelIndex;+ include!("cxx-qt-lib/qvariant.h");+ type QVariant = cxx_qt_lib::QVariant;+ include!("cxx-qt-lib/qhash.h");+ type QHash_i32_QByteArray = cxx_qt_lib::QHash<cxx_qt_lib::QHashPair_i32_QByteArray>;+ include!("cxx-qt-lib/qlist.h");+ type QList_i32 = cxx_qt_lib::QList<i32>;+ include!("cxx-qt-lib/qstring.h");+ type QString = cxx_qt_lib::QString;+ include!("cxx-qt-lib/qstringlist.h");+ type QStringList = cxx_qt_lib::QStringList;+ }++ unsafe extern "RustQt" {+ #[qobject]+ #[base = QAbstractListModel]+ #[qml_element]+ #[qml_singleton]+ #[qproperty(i32, count)]+ /// Transfers still waiting or running.+ #[qproperty(i32, active)]+ type TransferList = super::TransferListRust;+ }++ // Inherited from QAbstractListModel.+ unsafe extern "RustQt" {+ #[inherit]+ #[cxx_name = "beginInsertRows"]+ unsafe fn begin_insert_rows(+ self: Pin<&mut TransferList>,+ parent: &QModelIndex,+ first: i32,+ last: i32,+ );+ #[inherit]+ #[cxx_name = "endInsertRows"]+ unsafe fn end_insert_rows(self: Pin<&mut TransferList>);+ #[inherit]+ #[cxx_name = "beginRemoveRows"]+ unsafe fn begin_remove_rows(+ self: Pin<&mut TransferList>,+ parent: &QModelIndex,+ first: i32,+ last: i32,+ );+ #[inherit]+ #[cxx_name = "endRemoveRows"]+ unsafe fn end_remove_rows(self: Pin<&mut TransferList>);+ #[inherit]+ fn index(self: &TransferList, row: i32, column: i32, parent: &QModelIndex) -> QModelIndex;++ #[inherit]+ #[qsignal]+ #[cxx_name = "dataChanged"]+ fn data_changed(+ self: Pin<&mut TransferList>,+ top_left: &QModelIndex,+ bottom_right: &QModelIndex,+ roles: &QList_i32,+ );+ }++ unsafe extern "RustQt" {+ #[qinvokable]+ #[cxx_override]+ fn data(self: &TransferList, index: &QModelIndex, role: i32) -> QVariant;+ #[qinvokable]+ #[cxx_override]+ #[cxx_name = "roleNames"]+ fn role_names(self: &TransferList) -> QHash_i32_QByteArray;+ #[qinvokable]+ #[cxx_override]+ #[cxx_name = "rowCount"]+ fn row_count(self: &TransferList, parent: &QModelIndex) -> i32;++ /// Sends files (as `file:` URLs, from a picker or a drop) to a device.+ #[qinvokable]+ fn send(self: &TransferList, device: &QString, urls: &QStringList);+ #[qinvokable]+ fn cancel(self: &TransferList, id: &QString);+ /// Opens what a finished incoming transfer saved (its first file).+ #[qinvokable]+ fn open(self: &TransferList, id: &QString);+ #[qinvokable]+ #[cxx_name = "showInFolder"]+ fn show_in_folder(self: &TransferList, id: &QString);+ #[qinvokable]+ #[cxx_name = "clearFinished"]+ fn clear_finished(self: &TransferList);+ }++ impl cxx_qt::Threading for TransferList {}+ impl cxx_qt::Initialize for TransferList {}+}++#[derive(Debug, Clone, PartialEq)]+struct Row {+ view: TransferView,+ device_name: String,+}++#[derive(Default)]+pub struct TransferListRust {+ count: i32,+ active: i32,+ rows: Vec<Row>,+}++/// Model roles (Qt::UserRole + n).+const ROLES: &[&str] = &[+ "transferId",+ "deviceId",+ "deviceName",+ "incoming",+ "title",+ "fileCount",+ "total",+ "done",+ "progress",+ "rate",+ "status",+ "reason",+ "savedPath",+];+const USER_ROLE: i32 = 0x0100;++fn role_value(row: &Row, role: &str) -> QVariant {+ let text = |s: &str| QVariant::from(&QString::from(s));+ let t = &row.view.transfer;+ match role {+ "transferId" => text(&t.id),+ "deviceId" => text(&t.device.to_string()),+ "deviceName" => text(&row.device_name),+ "incoming" => QVariant::from(&(t.direction == Direction::Incoming)),+ "title" => text(&match t.names.as_slice() {+ [one] => one.clone(),+ [first, rest @ ..] => format!("{first} and {} more", rest.len()),+ [] => String::new(),+ }),+ "fileCount" => QVariant::from(&i32::try_from(t.names.len()).unwrap_or(i32::MAX)),+ "total" => QVariant::from(&(t.total as f64)),+ "done" => QVariant::from(&(t.done as f64)),+ "progress" => QVariant::from(&if t.total == 0 { 1.0 } else { t.done as f64 / t.total as f64 }),+ "rate" => QVariant::from(&row.view.rate),+ "status" => text(match t.state {+ TransferState::Waiting => "waiting",+ TransferState::Running => "running",+ TransferState::Done { .. } => "done",+ TransferState::Failed(_) => "failed",+ TransferState::Cancelled => "cancelled",+ }),+ "reason" => text(match &t.state {+ TransferState::Failed(TransferFailure::Denied) => "denied",+ TransferState::Failed(TransferFailure::Unreachable) => "unreachable",+ TransferState::Failed(TransferFailure::NoSpace) => "noSpace",+ TransferState::Failed(TransferFailure::Interrupted) => "interrupted",+ TransferState::Failed(TransferFailure::Other(_)) => "other",+ _ => "",+ }),+ "savedPath" => text(&saved_path(row).map(|p| p.to_string_lossy().into_owned()).unwrap_or_default()),+ _ => QVariant::default(),+ }+}++fn saved_path(row: &Row) -> Option<PathBuf> {+ match &row.view.transfer.state {+ TransferState::Done { saved } => saved.first().cloned(),+ _ => None,+ }+}++impl cxx_qt::Initialize for qobject::TransferList {+ fn initialize(self: Pin<&mut Self>) {+ super::subscribe(self.qt_thread(), Changes::TRANSFERS | Changes::DEVICES, Self::refresh);+ }+}++impl qobject::TransferList {+ fn refresh(mut self: Pin<&mut Self>) {+ let new: Vec<Row> = core_host::host().hub.read(|s| {+ s.transfers+ .iter()+ .map(|view| Row {+ device_name: s.name_of(&view.transfer.device).unwrap_or_default(),+ view: view.clone(),+ })+ .collect()+ });+ let root = QModelIndex::default();+ for edit in diff(&self.rows, &new, |r| r.view.transfer.id.clone()) {+ match edit {+ Edit::Remove(row) => {+ let r = row as i32;+ // SAFETY: row exists; begin/end are balanced.+ unsafe {+ self.as_mut().begin_remove_rows(&root, r, r);+ self.as_mut().rust_mut().rows.remove(row);+ self.as_mut().end_remove_rows();+ }+ }+ Edit::Insert(row) => {+ let r = row as i32;+ // SAFETY: row <= len; begin/end are balanced.+ unsafe {+ self.as_mut().begin_insert_rows(&root, r, r);+ self.as_mut().rust_mut().rows.insert(row, new[row].clone());+ self.as_mut().end_insert_rows();+ }+ }+ Edit::Change(row) => {+ self.as_mut().rust_mut().rows[row] = new[row].clone();+ let index = self.index(row as i32, 0, &root);+ self.as_mut().data_changed(&index, &index, &QList::default());+ }+ }+ }+ let count = self.rows.len() as i32;+ let active = self.rows.iter().filter(|r| !r.view.transfer.state.is_finished()).count() as i32;+ self.as_mut().set_count(count);+ self.set_active(active);+ }++ pub fn data(&self, index: &QModelIndex, role: i32) -> QVariant {+ let row = usize::try_from(index.row()).ok();+ let role = usize::try_from(role - USER_ROLE).ok().and_then(|r| ROLES.get(r));+ match (row.and_then(|r| self.rows.get(r)), role) {+ (Some(row), Some(role)) => role_value(row, role),+ _ => QVariant::default(),+ }+ }++ pub fn role_names(&self) -> QHash<QHashPair_i32_QByteArray> {+ let mut roles = QHash::<QHashPair_i32_QByteArray>::default();+ for (i, name) in ROLES.iter().enumerate() {+ roles.insert(USER_ROLE + i as i32, QByteArray::from(*name));+ }+ roles+ }++ pub fn row_count(&self, _parent: &QModelIndex) -> i32 {+ self.rows.len() as i32+ }++ pub fn send(&self, device: &QString, urls: &QStringList) {+ let Some(device) = super::parse_device(device) else { return };+ let paths: Vec<PathBuf> = QList::<QString>::from(urls)+ .iter()+ .filter_map(|url| QUrl::from(url).to_local_file().map(|path| String::from(&path)))+ .filter(|path| !path.is_empty())+ .map(PathBuf::from)+ .collect();+ transfers::send(device, paths);+ }++ pub fn cancel(&self, id: &QString) {+ transfers::cancel(&String::from(id));+ }++ fn row(&self, id: &QString) -> Option<&Row> {+ let id = String::from(id);+ self.rows.iter().find(|r| r.view.transfer.id == id)+ }++ pub fn open(&self, id: &QString) {+ if let Some(path) = self.row(id).and_then(saved_path) {+ transfers::open(&path);+ }+ }++ pub fn show_in_folder(&self, id: &QString) {+ if let Some(path) = self.row(id).and_then(saved_path) {+ transfers::show_in_folder(&path);+ }+ }++ pub fn clear_finished(&self) {+ core_host::host().hub.update(|s| s.clear_finished_transfers());+ }+}++#[cfg(test)]+mod tests {+ use std::time::Instant;++ use nectarlink_core::{DeviceId, Transfer};++ use super::*;++ #[test]+ fn roles_describe_the_transfer() {+ let row = Row {+ view: TransferView {+ transfer: Transfer {+ id: "t".into(),+ device: DeviceId([3; 32]),+ direction: Direction::Incoming,+ names: vec!["a.jpg".into(), "b.jpg".into(), "c.jpg".into()],+ total: 400,+ done: 100,+ state: TransferState::Done { saved: vec![PathBuf::from(r"C:\Downloads\a.jpg")] },+ },+ rate: 0.0,+ sampled: Instant::now(),+ },+ device_name: "Pixel".into(),+ };+ let text = |role| role_value(&row, role).value::<QString>().map(String::from).unwrap_or_default();+ assert_eq!(text("title"), "a.jpg and 2 more");+ assert_eq!(text("status"), "done");+ assert_eq!(text("savedPath"), r"C:\Downloads\a.jpg");+ assert_eq!(role_value(&row, "progress").value::<f64>(), Some(0.25));+ assert_eq!(role_value(&row, "incoming").value::<bool>(), Some(true));+ }+}diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rsindex 321c645..57bd5e7 100644--- a/desktop/app/src/core_host.rs+++ b/desktop/app/src/core_host.rs@@ -65,7 +65,8 @@ pub fn start(data_dir: PathBuf, platform: Arc<dyn Platform>) -> std::io::Result<async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {let host = host();- let config = NodeConfig::new(&data_dir, this_device(), env!("CARGO_PKG_VERSION"));+ let mut config = NodeConfig::new(&data_dir, this_device(), env!("CARGO_PKG_VERSION"));+ config.downloads_dir = Some(downloads_dir());let node = match Node::start(config, platform).await {Ok(node) => node,Err(e) => {@@ -108,6 +109,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {crate::notifications::apply(&event);crate::notifications::update_toasts(&event);crate::clipboard::on_event(&event);+ crate::transfers::on_event(&event);}Err(RecvError::Lagged(missed)) => {// Resynchronize what can be re-read; transient events are lost.@@ -121,6 +123,11 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {}}+/// Where files from phones go: `Downloads\Nectarlink`.+pub fn downloads_dir() -> PathBuf {+ dirs::download_dir().unwrap_or_else(|| host().data_dir.join("received")).join("Nectarlink")+}+/// How this PC presents itself to phones.fn this_device() -> DeviceInfo {let name = hostname::get().ok().and_then(|h| h.into_string().ok()).unwrap_or_else(|| "Windows PC".into());diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rsindex 867e36c..740af80 100644--- a/desktop/app/src/main.rs+++ b/desktop/app/src/main.rs@@ -18,6 +18,7 @@ mod palette;mod qr;mod settings;mod state;+mod transfers;mod win;use std::{diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rsindex d60ae97..f57cd48 100644--- a/desktop/app/src/notifications.rs+++ b/desktop/app/src/notifications.rs@@ -112,6 +112,17 @@ fn show(device: DeviceId, n: &Notification) {/// What the user did with a toast.pub fn on_toast(event: ToastEvent) {+ // Received-file toasts: open the file, or show it in its folder.+ match &event {+ ToastEvent::Opened { device, key } if device == crate::transfers::TOAST_GROUP => {+ return crate::transfers::open(std::path::Path::new(key));+ }+ ToastEvent::Action { device, key, .. } if device == crate::transfers::TOAST_GROUP => {+ return crate::transfers::show_in_folder(std::path::Path::new(key));+ }+ ToastEvent::Dismissed { device, .. } if device == crate::transfers::TOAST_GROUP => return,+ _ => {}+ }match event {ToastEvent::Opened { .. } => crate::bridge::app::request_activation(),ToastEvent::Action { device, key, action } => run_action(&device, key, action, None),diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rsindex 90732ba..506f4e3 100644--- a/desktop/app/src/state.rs+++ b/desktop/app/src/state.rs@@ -7,12 +7,12 @@ use std::{collections::HashMap,path::PathBuf,sync::{Arc, Mutex, MutexGuard},- time::SystemTime,+ time::{Instant, SystemTime},};use nectarlink_core::{Battery, CapabilityMatrix, DeviceId, DeviceInfo, DiscoveredDevice, LinkState, NodeEvent, Notification,- PairedDevice, PairingEvent, PairingFailure, PowerLevel,+ PairedDevice, PairingEvent, PairingFailure, PowerLevel, Transfer, TransferState,};/// Which parts of the state changed, so listeners refresh only what they show.@@ -28,6 +28,7 @@ impl Changes {pub const CAPABILITIES: Changes = Changes(1 << 4);pub const RINGING: Changes = Changes(1 << 5);pub const NOTIFICATIONS: Changes = Changes(1 << 6);+ pub const TRANSFERS: Changes = Changes(1 << 7);pub fn is_empty(self) -> bool {self.0 == 0@@ -132,6 +133,19 @@ pub struct SentReply {pub pending: bool,}+/// A file transfer as the UI shows it.+#[derive(Debug, Clone, PartialEq)]+pub struct TransferView {+ pub transfer: Transfer,+ /// Recent speed, bytes per second (0 when not running).+ pub rate: f64,+ /// When progress was last reported.+ pub(crate) sampled: Instant,+}++/// Finished transfers kept in the list.+pub const MAX_FINISHED_TRANSFERS: usize = 20;+/// The most notifications kept; the oldest go first.pub const MAX_NOTIFICATIONS: usize = 200;@@ -153,6 +167,8 @@ pub struct AppState {pub app_icons: HashMap<String, PathBuf>,/// Replies sent from this PC, per notification, oldest first.pub replies: HashMap<(DeviceId, String), Vec<SentReply>>,+ /// File transfers, newest first.+ pub transfers: Vec<TransferView>,}impl AppState {@@ -288,7 +304,45 @@ impl AppState {}// Feedback only (see crate::clipboard); nothing to keep.NodeEvent::ClipboardReceived { .. } => Changes::NONE,+ NodeEvent::Transfer(transfer) => self.update_transfer(transfer.clone(), Instant::now()),+ }+ }++ /// Adds or updates a transfer, keeping a smoothed speed.+ pub fn update_transfer(&mut self, transfer: Transfer, now: Instant) -> Changes {+ match self.transfers.iter_mut().find(|t| t.transfer.id == transfer.id) {+ Some(view) => {+ let elapsed = now.saturating_duration_since(view.sampled).as_secs_f64();+ let running = transfer.state == TransferState::Running;+ if running && elapsed > 0.0 && transfer.done >= view.transfer.done {+ let instant = (transfer.done - view.transfer.done) as f64 / elapsed;+ // Smoothed, so the number doesn't jump around.+ view.rate = if view.rate == 0.0 { instant } else { view.rate * 0.7 + instant * 0.3 };+ } else if !running {+ view.rate = 0.0;+ }+ view.sampled = now;+ view.transfer = transfer;+ }+ None => self.transfers.insert(0, TransferView { transfer, rate: 0.0, sampled: now }),}+ // Keep every unfinished transfer and the latest finished ones.+ let mut finished = 0;+ self.transfers.retain(|t| {+ if !t.transfer.state.is_finished() {+ return true;+ }+ finished += 1;+ finished <= MAX_FINISHED_TRANSFERS+ });+ Changes::TRANSFERS+ }++ /// Forgets finished transfers.+ pub fn clear_finished_transfers(&mut self) -> Changes {+ let before = self.transfers.len();+ self.transfers.retain(|t| !t.transfer.state.is_finished());+ if self.transfers.len() == before { Changes::NONE } else { Changes::TRANSFERS }}/// Records a reply on its way to the phone.@@ -606,6 +660,39 @@ mod tests {assert!(s.replies.is_empty());}+ fn transfer(id: &str, done: u64, state: TransferState) -> Transfer {+ Transfer {+ id: id.into(),+ device: DeviceId([1; 32]),+ direction: nectarlink_core::Direction::Outgoing,+ names: vec!["a.bin".into()],+ total: 1000,+ done,+ state,+ }+ }++ #[test]+ fn transfers_update_in_place_with_a_speed() {+ let mut s = AppState::default();+ let t0 = Instant::now();+ s.update_transfer(transfer("a", 0, TransferState::Running), t0);+ s.update_transfer(transfer("b", 0, TransferState::Waiting), t0);+ assert_eq!(s.transfers.iter().map(|t| t.transfer.id.as_str()).collect::<Vec<_>>(), ["b", "a"]);+ s.update_transfer(transfer("a", 500, TransferState::Running), t0 + std::time::Duration::from_secs(1));+ let a = s.transfers.iter().find(|t| t.transfer.id == "a").unwrap();+ assert_eq!((a.transfer.done, a.rate), (500, 500.0));+ s.update_transfer(transfer("a", 1000, TransferState::Done { saved: Vec::new() }), t0);+ assert_eq!(s.transfers[1].rate, 0.0, "no speed once finished");++ assert_eq!(s.clear_finished_transfers(), Changes::TRANSFERS);+ assert_eq!(s.transfers.len(), 1, "the waiting one stays");+ for i in 0..(MAX_FINISHED_TRANSFERS + 5) {+ s.update_transfer(transfer(&i.to_string(), 1000, TransferState::Cancelled), t0);+ }+ assert_eq!(s.transfers.len(), MAX_FINISHED_TRANSFERS + 1);+ }+#[test]fn the_feed_is_bounded() {let mut s = AppState::default();diff --git a/desktop/app/src/transfers.rs b/desktop/app/src/transfers.rsnew file mode 100644index 0000000..44f013e--- /dev/null+++ b/desktop/app/src/transfers.rs@@ -0,0 +1,92 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! File transfers on this PC (docs/protocol/files.md): sending what the+//! user picks or drops, opening what arrived, and a Windows notification+//! when files from a phone are saved.++use std::path::{Path, PathBuf};++use nectarlink_core::{DeviceId, Direction, Error, FileSource, NodeEvent, OutgoingFile, TransferState};++use crate::{+ bridge::app::{describe, show_message},+ core_host,+ win::toast::{self, Toast},+};++/// The toast "device" for received-file notifications; their key is the+/// saved file's path.+pub const TOAST_GROUP: &str = "files";+/// The "Show in folder" toast action.+pub const ACTION_SHOW: &str = "show";++/// Sends files to a device; the transfer list shows how it goes.+pub fn send(device: DeviceId, paths: Vec<PathBuf>) {+ let Some(node) = core_host::node() else { return };+ let files: Vec<OutgoingFile> = paths+ .into_iter()+ .filter(|p| p.is_file())+ .map(|path| OutgoingFile {+ name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),+ source: FileSource::Path(path),+ })+ .collect();+ if files.is_empty() {+ show_message("Folders can't be sent yet; pick files instead.");+ return;+ }+ core_host::spawn(async move {+ match node.send_files(device, files).await {+ Ok(_) => {}+ Err(Error::Denied) => show_message("Files are turned off for that device."),+ Err(e) => show_message(describe(&e)),+ }+ });+}++pub fn cancel(id: &str) {+ if let Some(node) = core_host::node() {+ node.cancel_transfer(id);+ }+}++/// Opens a received file with its app.+pub fn open(path: &Path) {+ if let Err(e) = std::process::Command::new("explorer").arg(path).spawn() {+ tracing::warn!(error = %e, "can't open a received file");+ }+}++/// Shows a received file in File Explorer, selected.+pub fn show_in_folder(path: &Path) {+ let mut select = std::ffi::OsString::from("/select,");+ select.push(path);+ if let Err(e) = std::process::Command::new("explorer").arg(select).spawn() {+ tracing::warn!(error = %e, "can't show a received file");+ }+}++/// A Windows notification when files from a phone are saved.+pub fn on_event(event: &NodeEvent) {+ let NodeEvent::Transfer(t) = event else { return };+ if t.direction != Direction::Incoming {+ return;+ }+ let TransferState::Done { saved } = &t.state else { return };+ let Some(first) = saved.first() else { return };+ let device = core_host::host().hub.read(|s| s.name_of(&t.device)).unwrap_or_else(|| "your phone".into());+ let title = match saved.len() {+ 1 => first.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),+ n => format!("{n} files"),+ };+ toast::show(Toast {+ device: TOAST_GROUP.into(),+ key: first.to_string_lossy().into_owned(),+ title,+ body: format!("From {device}, saved in Downloads\\Nectarlink"),+ attribution: "Nectarlink".into(),+ icon: None,+ actions: vec![(ACTION_SHOW.into(), "Show in folder".into())],+ reply: None,+ silent: false,+ });+}diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.mdindex 0c40a33..76234b5 100644--- a/docs/protocol/capabilities.md+++ b/docs/protocol/capabilities.md@@ -21,7 +21,7 @@ capability is missing.| `core.ping` | Answers `ping` | always offered || `device.battery` | Sends `event.battery` | always offered || `device.ring` | Rings on `device.ring`, even on silent | always offered |-| `files.transfer` | Sends and receives files | app update |+| `files.transfer` | Sends and receives files ([files service](files.md)) | app update || `media.control` | Exposes its media sessions for remote control (phone: needs notification access) | phone: notification access · desktop: app update |## Phonediff --git a/docs/protocol/files.md b/docs/protocol/files.mdnew file mode 100644index 0000000..5b3e15b--- /dev/null+++ b/docs/protocol/files.md@@ -0,0 +1,73 @@+# Files service (protocol v0)++> Status: **draft.** Builds on [protocol v0](v0.md); breaking changes are+> allowed until v1. License: CC BY 4.0.++Sends files between paired devices, in either direction, with progress,+cancellation and resuming after a dropped connection.++## 1. Capability++| ID | Offered by | Meaning |+|---|---|---|+| `files.transfer` | both | Sends and receives files |++## 2. A transfer++Each transfer runs on its own bidirectional stream (v0 §4), so it never+holds up the control stream. The sender opens it and writes the stream+header, then an offer:++```+t = "stream" b = { svc: "files", op: "send", v: 1 }+t = "files.offer" b = {+ id: text, // Transfer ID: 16–64 bytes of [A-Za-z0-9_-], the same on every retry+ files: [ { name: text, size: uint } ], // 1–1,000 files, in order+}+```++`name` is a file name only (no path), 1–255 bytes, without `/`, `\`, NUL+or control characters, and not `.` or `..`. Receivers **MUST** reject an+offer that breaks these rules with `BAD_MESSAGE`, and still pick their own+safe name for writing (see §4).++The receiver answers on the same stream:++```+t = "files.accept" b = { have: [uint] } // bytes already received, per file+```++or `error` (`DENIED`: the user turned files off for this device; `BUSY`:+not enough space or too many transfers) and closes the stream.++The sender then writes the files' bytes, raw and back to back: for each+file, from `have[i]` to its `size`. A file whose `have` equals its `size`+contributes nothing. The sender then finishes its side of the stream.++When the receiver has every byte, it stores the files and answers:++```+t = "files.done"+```++The transfer has succeeded once the sender reads `files.done`. Anything+else (a reset, a closed connection, a missing `done`) means it didn't.++## 3. Cancelling and resuming++- Either side cancels by resetting the stream (QUIC `RESET_STREAM` or+ `STOP_SENDING`, application code 10, "cancelled").+- A transfer interrupted any other way (the connection dropped) is resumed+ by offering it again with the **same `id`** when the devices reconnect.+ The receiver keeps partly received files for a transfer for at least an+ hour and reports their length in `have`. A sender **MUST** use a new `id`+ if any file changed in between.++## 4. Receiving safely++- Files are written to a private folder first and moved to where the user+ finds them (the Downloads folder) only once complete.+- A name that already exists there gets a number: `photo (2).jpg`.+- A device accepts files only from paired devices with the `files` toggle+ on. A receiver that runs out of space resets the stream.+- Implementations **MUST NOT** log file names (v0 §11).diff --git a/docs/protocol/v0.md b/docs/protocol/v0.mdindex 86b8e97..08a766b 100644--- a/docs/protocol/v0.md+++ b/docs/protocol/v0.md@@ -7,8 +7,8 @@ This document specifies how two Nectarlink devices find each other, pair,connect and exchange messages. Version 0 covers the Phase 0 scope: identity,pairing, the session handshake, capabilities, heartbeat and the first events(device info, battery, ping). Feature services are specified in separate-documents that build on this one: [notifications](notifications.md) and-[clipboard](clipboard.md) so far; files and mirroring follow.+documents that build on this one: [notifications](notifications.md),+[clipboard](clipboard.md) and [files](files.md) so far; mirroring follows.Key words **MUST**, **SHOULD** and **MAY** are used as in RFC 2119.