Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Send whole folders, both ways
Bee29ed1d5cc2e8
diff --git a/README.md b/README.mdindex 4d7b8a0..abc263a 100644--- a/README.md+++ b/README.md@@ -83,10 +83,10 @@ place and tested; the user-facing features of Phase 1 come next.phone. From the phone, send them with the Quick Settings tile, the sharesheet or a button in the app (Android lets only the app in front read theclipboard). 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, pick them, or right-click them in File Explorer and choose- **Send to** and your phone (a notification follows the transfer); on the- phone, share them from any app or pick them in Nectarlink. They land in `Downloads\Nectarlink` on the PC and+- **Files and folders** in both directions, at Wi-Fi speed. On the PC, drop+ them on the window, pick them, or right-click them in File Explorer and+ choose **Send to** and your phone (a notification follows the transfer);+ 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 transfersthat pick up where they left off after a dropped connection.- **Media** both ways: what plays on the phone shows on the PC, in the app anddiff --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 f12fadd..9546dea 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@@ -18,6 +18,7 @@ import app.nectarlink.android.Rimport app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.core.Eventimport app.nectarlink.core.EventListener+import app.nectarlink.core.FileToSendimport app.nectarlink.core.Linkimport app.nectarlink.core.NectarlinkExceptionimport app.nectarlink.core.NectarlinkNode@@ -194,7 +195,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerif (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)) }+ val published = done.saved.flatMap { ReceivedFiles.publish(context, java.io.File(it)) }TransferNotifications.received(context, transfer, published, pc)}}@@ -204,8 +205,25 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener* 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)+ fun sendFiles(pcId: String, uris: List<Uri>) = send(pcId, OutgoingFiles.open(context, uris))++ /** Sends a folder the user picked, with everything in it. */+ fun sendFolder(pcId: String, tree: Uri) {+ scope.launch(Dispatchers.IO) {+ val files = try {+ OutgoingFiles.openFolder(context, tree)+ } catch (_: OutgoingFiles.TooManyFiles) {+ _messages.tryEmit(context.getString(R.string.transfer_too_many))+ return@launch+ } catch (e: Exception) {+ Log.w(TAG, "can't read a picked folder", e)+ emptyList()+ }+ send(pcId, files)+ }+ }++ private fun send(pcId: String, files: List<FileToSend>) {if (files.isEmpty()) {_messages.tryEmit(context.getString(R.string.transfer_nothing))returndiff --git a/android/app/src/main/kotlin/app/nectarlink/android/files/OutgoingFiles.kt b/android/app/src/main/kotlin/app/nectarlink/android/files/OutgoingFiles.ktindex 8514fea..d8bc75a 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/files/OutgoingFiles.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/files/OutgoingFiles.kt@@ -3,6 +3,10 @@ package app.nectarlink.android.filesimport android.content.Contextimport android.net.Uri+import android.os.Build+import android.os.ParcelFileDescriptor+import android.provider.DocumentsContract+import android.provider.DocumentsContract.Documentimport android.provider.OpenableColumnsimport app.nectarlink.core.FileToSend@@ -11,13 +15,77 @@ 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())+ FileToSend.Fd(name = displayName(context, uri), fd = fd.detachFd(), folder = null)}+ /** Why a folder can't be sent. */+ class TooManyFiles : Exception("too many files")++ /**+ * Everything in a folder the user picked (`OpenDocumentTree`), with+ * where each file is in it. Empty folders are left out. Every file is+ * opened now, so there's a limit on how many.+ */+ fun openFolder(context: Context, tree: Uri): List<FileToSend> {+ val rootId = DocumentsContract.getTreeDocumentId(tree)+ val rootName = query(context, DocumentsContract.buildDocumentUriUsingTree(tree, rootId)).firstOrNull()?.name+ val files = mutableListOf<FileToSend>()+ try {+ walk(context, tree, rootId, safeName(rootName ?: "Folder"), depth = 1, files)+ } catch (e: Exception) {+ // Close what was opened before giving up.+ files.filterIsInstance<FileToSend.Fd>().forEach { runCatching { ParcelFileDescriptor.adoptFd(it.fd).close() } }+ throw e+ }+ return files+ }++ private data class Child(val id: String, val name: String, val folder: Boolean)++ private fun walk(context: Context, tree: Uri, parentId: String, folder: String, depth: Int, out: MutableList<FileToSend>) {+ if (depth > MAX_DEPTH) throw TooManyFiles()+ val children = query(context, DocumentsContract.buildChildDocumentsUriUsingTree(tree, parentId)).sortedBy { it.name }+ for (child in children) {+ val name = safeName(child.name)+ if (child.folder) {+ walk(context, tree, child.id, "$folder/$name", depth + 1, out)+ } else {+ if (out.size >= maxFiles) throw TooManyFiles()+ val uri = DocumentsContract.buildDocumentUriUsingTree(tree, child.id)+ val fd = runCatching { context.contentResolver.openFileDescriptor(uri, "r") }.getOrNull() ?: continue+ out += FileToSend.Fd(name = name, fd = fd.detachFd(), folder = folder)+ }+ }+ }++ private fun query(context: Context, uri: Uri): List<Child> {+ val columns = arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_DISPLAY_NAME, Document.COLUMN_MIME_TYPE)+ return context.contentResolver.query(uri, columns, null, null, null)?.use { cursor ->+ buildList {+ while (cursor.moveToNext()) {+ val id = cursor.getString(0) ?: continue+ add(Child(id, cursor.getString(1) ?: "file", cursor.getString(2) == Document.MIME_TYPE_DIR))+ }+ }+ }.orEmpty()+ }++ /** A name without the characters folder paths use; the core checks the rest. */+ private fun safeName(name: String): String =+ name.replace('/', '_').replace('\\', '_').trim().ifEmpty { "file" }.take(200)+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"++ private const val MAX_DEPTH = 32++ /**+ * Each file stays open until it's sent. Android 9 and later allow an+ * app tens of thousands of open files; Android 8 only about a thousand.+ */+ private val maxFiles = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) 5000 else 500}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.ktindex 2e34e8f..d662997 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/files/ReceivedFiles.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/files/ReceivedFiles.kt@@ -24,25 +24,40 @@ internal object ReceivedFiles {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 {+ /**+ * Moves a received file, or a folder with everything in it, into+ * Downloads. Returns what's there now; a file that failed stays where+ * it is and is left out.+ */+ fun publish(context: Context, item: File): List<Published> =+ if (item.isDirectory) {+ item.walkTopDown().filter { it.isFile }.mapNotNull { file ->+ val folder = file.parentFile!!.relativeTo(item.parentFile!!).invariantSeparatorsPath+ publishFile(context, file, folder)+ }.toList().also { item.deleteRecursively() }+ } else {+ listOfNotNull(publishFile(context, item, folder = null))+ }++ /** `folder`: where it goes in Download/Nectarlink (`Trip/Day 1`). */+ private fun publishFile(context: Context, file: File, folder: String?): Published? = runCatching {val mime = mimeOf(file.name)val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {- toMediaStore(context, file, mime)+ toMediaStore(context, file, mime, folder)} else {- toAppDownloads(context, file)+ toAppDownloads(context, file, folder)}file.delete()Published(uri, file.name, mime)}.getOrNull()@RequiresApi(Build.VERSION_CODES.Q)- private fun toMediaStore(context: Context, file: File, mime: String): Uri {+ private fun toMediaStore(context: Context, file: File, mime: String, folder: String?): Uri {val resolver = context.contentResolverval 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.RELATIVE_PATH, listOfNotNull(Environment.DIRECTORY_DOWNLOADS, "Nectarlink", folder).joinToString("/"))put(MediaStore.MediaColumns.IS_PENDING, 1)}val uri = checkNotNull(resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values))@@ -57,8 +72,9 @@ internal object ReceivedFiles {}/** 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() }+ private fun toAppDownloads(context: Context, file: File, folder: String?): Uri {+ val base = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "Nectarlink")+ val dir = (if (folder == null) base else File(base, folder)).apply { mkdirs() }var target = File(dir, file.name)var n = 2while (target.exists()) {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.ktindex 1e7f07c..d82785d 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/files/TransferNotifications.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/files/TransferNotifications.kt@@ -2,6 +2,7 @@package app.nectarlink.android.filesimport android.Manifest+import android.app.DownloadManagerimport android.app.NotificationChannelimport android.app.NotificationManagerimport android.app.PendingIntent@@ -40,10 +41,7 @@ internal object TransferNotifications {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)- }+ private fun title(context: Context, transfer: Transfer): String = transferTitle(context.resources, transfer)/** Shows or updates a running transfer, or removes it once it ended. */fun update(context: Context, transfer: Transfer, pcName: String) {@@ -82,22 +80,28 @@ internal object TransferNotifications {post(context, idOf(transfer), notification)}- /** Files from a PC are saved: tap to open (the first one). */+ /**+ * Files from a PC are saved: tap to open the first one, or the+ * Downloads list when a folder came.+ */fun received(context: Context, transfer: Transfer, files: List<ReceivedFiles.Published>, pcName: String) {if (!allowed(context) || files.isEmpty()) returnval 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 open = if (transfer.files.toInt() == transfer.names.size) {+ Intent.createChooser(+ Intent(Intent.ACTION_VIEW).setDataAndType(first.uri, first.mime).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION),+ null,+ )+ } else {+ Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)+ }val tap = PendingIntent.getActivity(- context, idOf(transfer), Intent.createChooser(open, null).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ context, idOf(transfer), open.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),- )+ .setContentTitle(title(context, transfer)).setContentText(context.getString(R.string.transfer_received_from, pcName)).setContentIntent(tap).setAutoCancel(true)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/files/TransferTitle.kt b/android/app/src/main/kotlin/app/nectarlink/android/files/TransferTitle.ktnew file mode 100644index 0000000..d3db25b--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/files/TransferTitle.kt@@ -0,0 +1,16 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.files++import android.content.res.Resources+import app.nectarlink.android.R+import app.nectarlink.core.Transfer++/** What a transfer is called: its file or folder's name, or how many. */+internal fun transferTitle(resources: Resources, transfer: Transfer): String {+ val count = transfer.names.size+ return when {+ count == 1 -> transfer.names[0]+ transfer.files.toInt() == count -> resources.getQuantityString(R.plurals.transfer_files, count, count)+ else -> resources.getQuantityString(R.plurals.transfer_items, count, count)+ }+}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 db703ef..c8ae648 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@@ -171,6 +171,7 @@ private fun App(core: Core, state: CoreState, preferences: Preferences) {onPower = core::pcPower,updater = (LocalContext.current.applicationContext as NectarlinkApplication).updater,onSendFiles = core::sendFiles,+ onSendFolder = core::sendFolder,onCancelTransfer = core::cancelTransfer,modifier = modifier,)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 513f028..43406fa 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@@ -41,7 +41,6 @@ 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@@ -51,6 +50,7 @@ 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.files.transferTitleimport app.nectarlink.android.core.isFinishedimport app.nectarlink.core.Transferimport app.nectarlink.core.TransferDirection@@ -76,6 +76,7 @@ fun HomeScreen(onPower: (pcId: String, sleep: Boolean) -> Unit,updater: AppUpdater,onSendFiles: (pcId: String, uris: List<Uri>) -> Unit,+ onSendFolder: (pcId: String, tree: Uri) -> Unit,onCancelTransfer: (id: String) -> Unit,modifier: Modifier = Modifier,) {@@ -134,7 +135,7 @@ fun HomeScreen() { context.startActivity(NotificationListener.settingsIntent(context)) }}}- items(state.devices, key = { it.id }) { device -> PcCard(device, onRing, onSendFiles, onPower) }+ items(state.devices, key = { it.id }) { device -> PcCard(device, onRing, onSendFiles, onSendFolder, onPower) }if (state.transfers.isNotEmpty()) {item { TransfersCard(state, onCancelTransfer) }}@@ -175,11 +176,15 @@ private fun PcCard(device: Device,onRing: (String, Boolean) -> Unit,onSendFiles: (String, List<Uri>) -> Unit,+ onSendFolder: (String, Uri) -> Unit,onPower: (String, Boolean) -> Unit,) {val pickFiles = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->if (uris.isNotEmpty()) onSendFiles(device.id, uris)}+ val pickFolder = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { tree ->+ if (tree != null) onSendFolder(device.id, tree)+ }var ringing by remember(device.id) { mutableStateOf(false) }Surface(shape = MaterialTheme.shapes.extraLarge,@@ -238,6 +243,9 @@ private fun PcCard(FilledTonalButton(enabled = device.online, onClick = { pickFiles.launch(arrayOf("*/*")) }) {Text(stringResource(R.string.action_send_files))}+ FilledTonalButton(enabled = device.online, onClick = { pickFolder.launch(null) }) {+ Text(stringResource(R.string.action_send_folder))+ }if (device.has("device.pc_actions")) {OutlinedButton(enabled = device.online, onClick = { onPower(device.id, false) }) {Text(stringResource(R.string.action_lock_pc))@@ -266,7 +274,7 @@ private fun TransfersCard(state: CoreState, onCancel: (String) -> Unit) {private fun TransferRow(transfer: Transfer, pc: String, onCancel: (String) -> Unit) {val incoming = transfer.direction == TransferDirection.INCOMINGval 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 title = transferTitle(LocalContext.current.resources, transfer)val detail = when (status) {is TransferStatus.Waiting -> stringResource(R.string.transfer_waiting, pc)is TransferStatus.Running ->diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex c90bad7..557443f 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -66,6 +66,8 @@<string name="media_next">Next</string><string name="media_previous">Previous</string><string name="action_send_files">Send files</string>+ <string name="action_send_folder">Send a folder</string>+ <string name="transfer_too_many">That folder has too many files to send at once.</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>@@ -154,4 +156,8 @@<item quantity="one">%1$d file</item><item quantity="other">%1$d files</item></plurals>+ <plurals name="transfer_items">+ <item quantity="one">%1$d item</item>+ <item quantity="other">%1$d items</item>+ </plurals></resources>diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex f19c432..25b66d8 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -9,10 +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, Direction, FeatureState, FileSource,- LinkState, MediaAction, MediaError, MediaPlayer, Node, NodeConfig, NodeEvent, Notification,- NotificationAction, NotificationError, OutgoingFile, PairedDevice, PairingEvent, Platform, PowerAction,- PowerLevel, TransferState,+ Battery, ConnectionPath, DeviceId, DeviceInfo, DeviceKind, Direction, FeatureState, LinkState,+ MediaAction, MediaError, MediaPlayer, Node, NodeConfig, NodeEvent, Notification, NotificationAction,+ NotificationError, PairedDevice, PairingEvent, Platform, PowerAction, PowerLevel, TransferState,features::{Effort, FEATURES, Role, UnsupportedReason, Upgrade, UpgradeAction},};use tokio::sync::broadcast::error::RecvError;@@ -617,19 +616,13 @@ async fn confirm_code(code: String) -> Result<bool> {/// 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 files = nectarlink_core::outgoing_paths(paths).context("can't read what to send")?;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);+ println!("\rSent {} file(s), {} bytes. ", t.files, t.total);return Ok(());}TransferState::Failed(why) => bail!("transfer failed: {why:?}"),diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex 9039dae..c7d790b 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -44,7 +44,8 @@ pub use nectarlink_protocol::{pub use node::Node;pub use notifications::NotificationError;pub use transfer::{- Direction, FileSource, OutgoingFile, Transfer, TransferFailure, TransferState, safe_file_name,+ Direction, FileSource, OutgoingFile, Transfer, TransferFailure, TransferState, outgoing_paths,+ safe_file_name,};pub(crate) fn device_id(key: &iroh::PublicKey) -> DeviceId {diff --git a/core/nectarlink-core/src/transfer.rs b/core/nectarlink-core/src/transfer.rsindex 745f86f..e327b10 100644--- a/core/nectarlink-core/src/transfer.rs+++ b/core/nectarlink-core/src/transfer.rs@@ -4,6 +4,7 @@//! and resuming after a dropped connection.use std::{+ collections::HashMap,path::{Path, PathBuf},sync::Arc,time::{Duration, Instant},@@ -14,7 +15,8 @@ use iroh::endpoint::{ReadError, RecvStream, SendStream, VarInt, WriteError};use nectarlink_protocol::{DeviceId, Envelope, ErrorCode,messages::{- ErrorBody, FileEntry, FilesAccept, FilesOffer, StreamHeader, clip, files, is_valid_file_name, types,+ ErrorBody, FileEntry, FilesAccept, FilesOffer, StreamHeader, clip, files, is_valid_file_name,+ is_valid_folder, types,},read_frame, write_frame,};@@ -71,7 +73,8 @@ pub enum TransferState {/// after the connection dropped (receiving; the sender resumes it).Waiting,Running,- /// Received files are where `saved` says (one path per file).+ /// Received files are where `saved` says: one path per item, each+ /// file and each sent folder (as [`Transfer::names`] lists them).Done {saved: Vec<PathBuf>,},@@ -91,8 +94,10 @@ pub struct Transfer {pub id: String,pub device: DeviceId,pub direction: Direction,- /// File names, in order.+ /// What was sent, as the user picked it: file and folder names, in order.pub names: Vec<String>,+ /// How many files that is (a folder's files included).+ pub files: usize,/// Bytes in total and done so far.pub total: u64,pub done: u64,@@ -105,7 +110,8 @@ impl std::fmt::Debug for Transfer {f.debug_struct("Transfer").field("id", &self.id).field("direction", &self.direction)- .field("files", &self.names.len())+ .field("items", &self.names.len())+ .field("files", &self.files).field("done", &self.done).field("total", &self.total).field("state", &self.state)@@ -118,9 +124,102 @@ impl std::fmt::Debug for Transfer {pub struct OutgoingFile {/// The name the other device sees (no path).pub name: String,+ /// The folder it's in, when sending a folder: `/`-separated names,+ /// starting with the sent folder's own.+ pub folder: Option<String>,pub source: FileSource,}+/// The files to send for paths the user picked: files as they are, and+/// folders with everything in them (empty folders and links aside).+pub fn outgoing_paths(paths: &[PathBuf]) -> Result<Vec<OutgoingFile>> {+ let mut out = Vec::new();+ for path in paths {+ let meta = std::fs::symlink_metadata(path)?;+ if meta.is_dir() {+ let name =+ path.file_name().map_or_else(|| "Folder".into(), |n| safe_file_name(&n.to_string_lossy()));+ add_folder(path, &name, 1, &mut out)?;+ } else if meta.is_file() {+ let name =+ path.file_name().map_or_else(|| "file".into(), |n| safe_file_name(&n.to_string_lossy()));+ out.push(OutgoingFile { name, folder: None, source: FileSource::Path(path.clone()) });+ }+ if out.len() > files::MAX_FILES {+ return Err(Error::TooLarge);+ }+ }+ Ok(out)+}++fn add_folder(dir: &Path, folder: &str, depth: usize, out: &mut Vec<OutgoingFile>) -> Result<()> {+ if depth > files::MAX_FOLDER_DEPTH || folder.len() > files::MAX_FOLDER_BYTES {+ return Err(Error::TooLarge);+ }+ let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<std::io::Result<_>>()?;+ entries.sort_by_key(std::fs::DirEntry::file_name);+ for entry in entries {+ // Not followed: links (and junctions) could lead anywhere.+ let kind = entry.file_type()?;+ let name = safe_file_name(&entry.file_name().to_string_lossy());+ if kind.is_dir() {+ add_folder(&entry.path(), &format!("{folder}/{name}"), depth + 1, out)?;+ } else if kind.is_file() {+ out.push(OutgoingFile {+ name,+ folder: Some(folder.to_owned()),+ source: FileSource::Path(entry.path()),+ });+ if out.len() > files::MAX_FILES {+ return Err(Error::TooLarge);+ }+ }+ }+ Ok(())+}++/// What a transfer's files are, as the user picked them: each file outside+/// a folder, and each folder once.+fn items(entries: &[FileEntry]) -> Vec<String> {+ let mut items: Vec<String> = Vec::new();+ let mut last_folder: Option<&str> = None;+ for entry in entries {+ match entry.folder.as_deref().map(|f| f.split('/').next().unwrap_or(f)) {+ Some(top) if last_folder == Some(top) => {}+ Some(top) => {+ items.push(top.to_owned());+ last_folder = Some(top);+ }+ None => {+ items.push(entry.name.clone());+ last_folder = None;+ }+ }+ }+ items+}++/// A name Windows can store: no reserved device names (`CON`, `COM1`…),+/// characters it rejects, or trailing dots and spaces.+fn storable_name(name: &str) -> String {+ let mut clean: String = name+ .chars()+ .map(|c| if matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*') { '_' } else { c })+ .collect();+ while clean.ends_with(['.', ' ']) {+ clean.pop();+ }+ let stem = clean.split('.').next().unwrap_or("").trim_end().to_ascii_uppercase();+ let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")+ || (stem.len() == 4+ && (stem.starts_with("COM") || stem.starts_with("LPT"))+ && stem.as_bytes()[3].is_ascii_digit());+ if reserved {+ clean.insert(0, '_');+ }+ if clean.is_empty() { "file".into() } else { clean }+}+#[derive(Debug)]pub enum FileSource {Path(PathBuf),@@ -190,7 +289,7 @@ impl Reporter {/// [`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()));+ return Err(Error::Protocol("send between 1 and 5000 files".into()));}if !shared.store.is_paired(&peer)? {return Err(Error::NotPaired);@@ -200,19 +299,35 @@ pub(crate) async fn send(shared: &Arc<Shared>, peer: DeviceId, files: Vec<Outgoi}let mut opened = Vec::with_capacity(files.len());for file in files {+ if file.folder.as_deref().is_some_and(|f| !is_valid_folder(f)) {+ return Err(Error::Protocol("invalid folder name".into()));+ }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 entry = FileEntry {+ name: safe_file_name(&file.name),+ size: handle.metadata()?.len(),+ folder: file.folder,+ };+ opened.push((entry, tokio::fs::File::from_std(handle)));+ }+ let entries: Vec<FileEntry> = opened.iter().map(|(entry, _)| entry.clone()).collect();+ let id = new_id();+ // The whole offer has to fit in one frame.+ let offer = Envelope::new(files::OFFER, &FilesOffer { id: id.clone(), files: entries.clone() })+ .map_err(|e| Error::Protocol(e.to_string()))?;+ if offer.to_cbor().len() > nectarlink_protocol::MAX_FRAME_LEN {+ return Err(Error::TooLarge);}let transfer = Transfer {- id: new_id(),+ 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),+ names: items(&entries),+ files: entries.len(),+ total: entries.iter().map(|e| e.size).fold(0, u64::saturating_add),done: 0,state: TransferState::Waiting,};@@ -241,7 +356,7 @@ enum Attempt {async fn send_until_done(reporter: &mut Reporter,- mut files: Vec<(String, u64, tokio::fs::File)>,+ mut files: Vec<(FileEntry, tokio::fs::File)>,cancel: &CancellationToken,) -> TransferState {let peer = reporter.transfer.device;@@ -288,14 +403,14 @@ async fn send_until_done(async fn attempt(reporter: &mut Reporter,session: &Session,- files: &mut [(String, u64, tokio::fs::File)],+ files: &mut [(FileEntry, 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(),+ files: files.iter().map(|(entry, _)| entry.clone()).collect(),};let (Ok(header), Ok(offer)) =(Envelope::new(types::STREAM, &header), Envelope::new(files::OFFER, &offer))@@ -321,17 +436,17 @@ async fn attempt(};reporter.set(TransferState::Running);- let mut done: u64 = files.iter().zip(&have).map(|((_, size, _), have)| (*have).min(*size)).sum();+ let mut done: u64 = files.iter().zip(&have).map(|((entry, _), have)| (*have).min(entry.size)).sum();reporter.progress(done);// What's left of each file, read on a thread of its own that keeps a// few blocks ready; it stops when this attempt ends and drops them.let mut plan = Vec::with_capacity(files.len());- for ((_, size, file), have) in files.iter().zip(&have) {- let start = (*have).min(*size);+ for ((entry, file), have) in files.iter().zip(&have) {+ let start = (*have).min(entry.size);let Ok(clone) = file.try_clone().await else {return Attempt::Fatal(TransferFailure::Other("can't read a file".into()));};- plan.push((clone.into_std().await, start, *size - start));+ plan.push((clone.into_std().await, start, entry.size - start));}let (blocks, mut ready) = tokio::sync::mpsc::channel(READ_AHEAD);tokio::task::spawn_blocking(move || read_ahead(plan, &blocks));@@ -490,7 +605,8 @@ async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendStream, mutid: offer.id.clone(),device: peer,direction: Direction::Incoming,- names: offer.files.iter().map(|f| f.name.clone()).collect(),+ names: items(&offer.files),+ files: offer.files.len(),total: offer.total_size(),done: have.iter().sum(),state: TransferState::Running,@@ -648,20 +764,45 @@ async fn store(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 entries = offer.files.clone();+ let parts: Vec<PathBuf> = (0..entries.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);+ // A sent folder lands under a name of its own: `Trip`, or+ // `Trip (2)` when there already is one.+ let mut folders: HashMap<String, PathBuf> = HashMap::new();+ let mut saved = Vec::with_capacity(entries.len());+ for (entry, part) in entries.iter().zip(parts) {+ let at = match entry.folder.as_deref() {+ None => target.clone(),+ Some(folder) => {+ let mut names = folder.split('/').map(storable_name);+ let top = names.next().unwrap_or_else(|| "Folder".into());+ let mut at = match folders.get(&top) {+ Some(at) => at.clone(),+ None => {+ let at = unique_path(&target, &top);+ std::fs::create_dir(&at)?;+ folders.insert(top, at.clone());+ saved.push(at.clone());+ at+ }+ };+ at.extend(names);+ std::fs::create_dir_all(&at)?;+ at+ }+ };+ let to = unique_path(&at, &storable_name(&entry.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);+ if entry.folder.is_none() {+ saved.push(to);+ }}let _ = std::fs::remove_dir_all(&dir);Ok(saved)@@ -712,6 +853,49 @@ mod tests {assert_eq!(unique_path(dir.path(), ".env"), dir.path().join(".env (2)"));}+ #[test]+ fn names_windows_can_store() {+ assert_eq!(storable_name("photo.jpg"), "photo.jpg");+ assert_eq!(storable_name("CON"), "_CON");+ assert_eq!(storable_name("nul.txt"), "_nul.txt");+ assert_eq!(storable_name("com1"), "_com1");+ assert_eq!(storable_name("COMPUTER"), "COMPUTER");+ assert_eq!(storable_name("what?: \"x\"."), "what__ _x_");+ assert_eq!(storable_name(". "), "file");+ }++ #[test]+ fn items_are_files_and_folders() {+ let entry = |name: &str, folder: Option<&str>| FileEntry {+ name: name.into(),+ size: 1,+ folder: folder.map(Into::into),+ };+ let entries = [+ entry("a.txt", None),+ entry("1.jpg", Some("Trip")),+ entry("2.jpg", Some("Trip/Day 2")),+ entry("b.txt", None),+ entry("x", Some("Other")),+ ];+ assert_eq!(items(&entries), ["a.txt", "Trip", "b.txt", "Other"]);+ }++ #[test]+ fn folders_are_walked() {+ let dir = tempfile::tempdir().unwrap();+ let trip = dir.path().join("Trip");+ std::fs::create_dir_all(trip.join("Day 1")).unwrap();+ std::fs::create_dir_all(trip.join("empty")).unwrap();+ std::fs::write(trip.join("Day 1").join("b.jpg"), "b").unwrap();+ std::fs::write(trip.join("a.jpg"), "a").unwrap();+ std::fs::write(dir.path().join("note.txt"), "n").unwrap();+ let files = outgoing_paths(&[dir.path().join("note.txt"), trip]).unwrap();+ let listed: Vec<(&str, Option<&str>)> =+ files.iter().map(|f| (f.name.as_str(), f.folder.as_deref())).collect();+ assert_eq!(listed, [("note.txt", None), ("b.jpg", Some("Trip/Day 1")), ("a.jpg", Some("Trip"))]);+ }+#[test]fn ids_are_valid() {assert!(nectarlink_protocol::messages::is_valid_transfer_id(&new_id()));diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex c080396..8c4a00e 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -834,7 +834,7 @@ fn data(len: usize, seed: u64) -> Vec<u8> {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) }+ OutgoingFile { name: name.into(), folder: None, source: FileSource::Path(path) }}/// Waits for a transfer to reach a state matching `pick`.@@ -901,6 +901,38 @@ async fn files_arrive_intact_under_free_names() {);}+#[tokio::test(flavor = "multi_thread")]+async fn folders_arrive_with_their_layout() {+ 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 trip = src.path().join("Trip");+ std::fs::create_dir_all(trip.join("Day 1")).unwrap();+ std::fs::write(trip.join("Day 1").join("beach.jpg"), b"sand").unwrap();+ std::fs::write(trip.join("notes.txt"), b"fun").unwrap();+ std::fs::write(src.path().join("ticket.pdf"), b"pdf").unwrap();++ // The phone already has a "Trip" folder: this one becomes "Trip (2)".+ let downloads = phone.dir.path().join("received");+ std::fs::create_dir_all(downloads.join("Trip")).unwrap();++ let files = nectarlink_core::outgoing_paths(&[trip, src.path().join("ticket.pdf")]).unwrap();+ 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.names, ["Trip", "ticket.pdf"]);+ assert_eq!(t.files, 3);+ saved(t)+ })+ .await;+ let folder = downloads.join("Trip (2)");+ assert_eq!(received, [folder.clone(), downloads.join("ticket.pdf")]);+ assert_eq!(std::fs::read(folder.join("Day 1").join("beach.jpg")).unwrap(), b"sand");+ assert_eq!(std::fs::read(folder.join("notes.txt")).unwrap(), b"fun");+ assert!(std::fs::read_dir(downloads.join("Trip")).unwrap().next().is_none(), "the old folder is untouched");+}+#[tokio::test(flavor = "multi_thread")]async fn files_need_the_toggle_and_can_be_cancelled() {let mut pc = device("Desktop", DeviceKind::Desktop).await;diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex d51375f..f99bd1b 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -285,7 +285,8 @@ 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+ /// `saved`: where received files are, one path per item in `names`:+ /// each file, and each sent folder (empty when/// sending).Done {saved: Vec<String>,@@ -305,7 +306,10 @@ pub struct Transfer {/// The other device.pub device_id: String,pub direction: TransferDirection,+ /// What was sent: file and folder names, in order.pub names: Vec<String>,+ /// How many files that is (folders' files included).+ pub files: u32,pub total: u64,pub done: u64,pub status: TransferStatus,@@ -326,10 +330,14 @@ pub enum FileToSend {Fd {name: String,fd: i32,+ /// The folder it's in, when sending a folder: `/`-separated names,+ /// starting with the folder's own (`Trip/Day 1`).+ folder: Option<String>,},Path {name: String,path: String,+ folder: Option<String>,},}@@ -663,6 +671,7 @@ impl From<core::Transfer> for Transfer {core::Direction::Incoming => TransferDirection::Incoming,},names: t.names,+ files: u32::try_from(t.files).unwrap_or(u32::MAX),total: t.total,done: t.done,status: match t.state {@@ -689,11 +698,11 @@ impl From<core::Transfer> for Transfer {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()) }+ FileToSend::Path { name, path, folder } => {+ core::OutgoingFile { name, folder, source: core::FileSource::Path(path.into()) }}#[cfg(unix)]- FileToSend::Fd { name, fd } => {+ FileToSend::Fd { name, fd, folder } => {use std::os::fd::FromRawFd;if fd < 0 {return Err(NectarlinkError::Internal { reason: "invalid file descriptor".into() });@@ -702,7 +711,7 @@ fn file_to_send(file: FileToSend) -> Result<core::OutgoingFile> {// 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) }+ core::OutgoingFile { name, folder, source: core::FileSource::File(file) }}#[cfg(not(unix))]FileToSend::Fd { .. } => {diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 2c50ab7..2287f21 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -478,8 +478,11 @@ pub mod files {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_FILES: usize = 5000;pub const MAX_NAME_BYTES: usize = 255;+ /// A file's folder: at most this many bytes and this many levels.+ pub const MAX_FOLDER_BYTES: usize = 1024;+ pub const MAX_FOLDER_DEPTH: usize = 32;}/// One file of an offer.@@ -487,6 +490,10 @@ pub mod files {pub struct FileEntry {pub name: String,pub size: u64,+ /// The folder the file is in when a folder is sent: `/`-separated+ /// names, starting with the sent folder's own (`Trip/Day 1`).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub folder: Option<String>,}/// Never prints the name (protocol v0 §11).@@ -526,6 +533,14 @@ pub fn is_valid_file_name(name: &str) -> bool {&& !name.chars().any(|c| c == '/' || c == '\\' || c.is_control())}+/// Whether a folder is 1–32 valid names joined by `/`, in at most+/// [`files::MAX_FOLDER_BYTES`].+pub fn is_valid_folder(folder: &str) -> bool {+ folder.len() <= files::MAX_FOLDER_BYTES+ && folder.split('/').count() <= files::MAX_FOLDER_DEPTH+ && folder.split('/').all(is_valid_file_name)+}+/// 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'-')@@ -535,7 +550,10 @@ 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))+ && self+ .files+ .iter()+ .all(|f| is_valid_file_name(&f.name) && f.folder.as_deref().is_none_or(is_valid_folder))}pub fn total_size(&self) -> u64 {@@ -723,7 +741,7 @@ mod tests {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(),+ files: names.iter().map(|n| FileEntry { name: (*n).into(), size: 1, folder: None }).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"] {@@ -735,6 +753,26 @@ mod tests {assert!(!format!("{:?}", offer("abcdefghijklmnop", &["secret.pdf"])).contains("secret"));}+ #[test]+ fn folders_are_validated() {+ let offer = |folder: &str| FilesOffer {+ id: "abcdefghijklmnop".into(),+ files: vec![FileEntry { name: "a.jpg".into(), size: 1, folder: Some(folder.into()) }],+ };+ for good in ["Trip", "Trip/Day 1", "Trip/Day 1/raw"] {+ assert!(offer(good).is_valid(), "{good:?}");+ }+ for bad in ["", "/Trip", "Trip/", "Trip//x", "Trip/..", "./x", "a\\b", "x\u{0}"] {+ assert!(!offer(bad).is_valid(), "{bad:?}");+ }+ assert!(!offer(&vec!["d"; files::MAX_FOLDER_DEPTH + 1].join("/")).is_valid());+ // Without a folder, the field isn't sent at all.+ let plain = FileEntry { name: "a".into(), size: 1, folder: None };+ let env = Envelope::new("x", &plain).unwrap();+ assert!(!format!("{:?}", env.b).contains("folder"));+ assert!(!format!("{:?}", offer("Secret")).contains("Secret"));+ }+#[test]fn power_level_wire_names() {let env = Envelope::new("x", &PowerLevel::NotApplicable).unwrap();diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qmlindex 7ec4627..138776f 100644--- a/desktop/app/qml/pages/HomePage.qml+++ b/desktop/app/qml/pages/HomePage.qml@@ -285,6 +285,9 @@ Item {iconPath: Icons.sendfeature: home.feature("files.send")onClicked: filePicker.open()+ sideIcon: Icons.folder+ sideLabel: qsTr("Send a folder")+ onSideClicked: folderPicker.open()}}FileDialog {@@ -293,6 +296,11 @@ Item {fileMode: FileDialog.OpenFilesonAccepted: TransferList.send(home.deviceId, selectedFiles.map(url => url.toString()))}+ FolderDialog {+ id: folderPicker+ title: qsTr("Send a folder to %1").arg(home.name)+ onAccepted: TransferList.send(home.deviceId, [selectedFolder.toString()])+ }// ---- Transfers ----Card {@@ -688,7 +696,11 @@ Item {property bool active: false// False until this PC implements the action (shown as coming soon).property bool ready: true+ // A second, smaller action in the corner (e.g. "Send a folder").+ property string sideIcon+ property string sideLabelsignal clicked+ signal sideClickedreadonly property bool available: feature.state === "available" && ready@@ -747,5 +759,15 @@ Item {}HoverHandler { id: hover; cursorShape: tile.available ? Qt.PointingHandCursor : Qt.ArrowCursor }TapHandler { id: tap; enabled: tile.available; onTapped: tile.clicked() }+ IconButton {+ anchors.right: parent.right+ anchors.top: parent.top+ anchors.margins: 8+ visible: tile.sideIcon.length > 0 && tile.available+ iconPath: tile.sideIcon+ label: tile.sideLabel+ iconColor: tile.ink+ onClicked: tile.sideClicked()+ }}}diff --git a/desktop/app/src/bridge/transfers.rs b/desktop/app/src/bridge/transfers.rsindex d7a680e..63bb2eb 100644--- a/desktop/app/src/bridge/transfers.rs+++ b/desktop/app/src/bridge/transfers.rs@@ -163,7 +163,7 @@ fn role_value(row: &Row, role: &str) -> QVariant {[first, rest @ ..] => format!("{first} and {} more", rest.len()),[] => String::new(),}),- "fileCount" => QVariant::from(&i32::try_from(t.names.len()).unwrap_or(i32::MAX)),+ "fileCount" => QVariant::from(&i32::try_from(t.files).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 }),@@ -321,6 +321,7 @@ mod tests {device: DeviceId([3; 32]),direction: Direction::Incoming,names: vec!["a.jpg".into(), "b.jpg".into(), "c.jpg".into()],+ files: 3,total: 400,done: 100,state: TransferState::Done { saved: vec![PathBuf::from(r"C:\Downloads\a.jpg")] },diff --git a/desktop/app/src/send_to.rs b/desktop/app/src/send_to.rsindex 851b62c..e6cd11c 100644--- a/desktop/app/src/send_to.rs+++ b/desktop/app/src/send_to.rs@@ -15,9 +15,7 @@ use std::{time::{Duration, Instant},};-use nectarlink_core::{- DeviceId, Error, FileSource, NodeEvent, OutgoingFile, Transfer, TransferFailure, TransferState,-};+use nectarlink_core::{DeviceId, Error, NodeEvent, Transfer, TransferFailure, TransferState};use crate::{bridge::app::{describe, request_activation},@@ -201,8 +199,6 @@ pub fn handle(request: Request) {#[derive(Debug)]struct Tracked {device_name: String,- /// Folders were in the selection; they aren't sent.- skipped_folders: bool,shown: Option<(Instant, Progress)>,}@@ -221,24 +217,22 @@ fn send(device: String, paths: Vec<PathBuf>) {let Some((id, name)) = name else {return failed("Couldn't send", "That device isn't paired with this PC anymore.");};- let (files, folders): (Vec<PathBuf>, Vec<PathBuf>) = paths.into_iter().partition(|p| p.is_file());- if files.is_empty() {- let body = if folders.is_empty() {- "Those files can't be found."- } else {- "Folders can't be sent yet. Choose the files in them instead."- };- return failed(&format!("Couldn't send to {name}"), body);- }- let outgoing = files- .into_iter()- .map(|path| OutgoingFile {- name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),- source: FileSource::Path(path),- })- .collect();+ let outgoing = match tokio::task::spawn_blocking(move || nectarlink_core::outgoing_paths(&paths))+ .await+ {+ Ok(Ok(files)) if !files.is_empty() => files,+ Ok(Ok(_)) => {+ return failed(&format!("Couldn't send to {name}"), "There's nothing to send in there.");+ }+ Ok(Err(Error::TooLarge)) => {+ return failed(&format!("Couldn't send to {name}"), "That's too many files to send at once.");+ }+ Ok(Err(_)) | Err(_) => {+ return failed(&format!("Couldn't send to {name}"), "Those files can't be read.");+ }+ };match node.send_files(id, outgoing).await {- Ok(transfer_id) => track(transfer_id, name, !folders.is_empty()),+ Ok(transfer_id) => track(transfer_id, name),Err(Error::Denied) => failed(&format!("Couldn't send to {name}"),"Files are turned off for this device. Turn them on in Nectarlink.",@@ -264,10 +258,10 @@ fn failed(title: &str, body: &str) {});}-fn track(id: String, device_name: String, skipped_folders: bool) {+fn track(id: String, device_name: String) {let mut tracked = lock(&TRACKED);let map = tracked.get_or_insert_default();- map.insert(id.clone(), Tracked { device_name, skipped_folders, shown: None });+ map.insert(id.clone(), Tracked { device_name, shown: None });// Events before this point went to the hub only; catch up from there.let now = core_host::host().hub@@ -288,10 +282,7 @@ pub fn on_event(event: &NodeEvent) {fn update(map: &mut HashMap<String, Tracked>, transfer: &Transfer) {let Some(tracked) = map.get_mut(&transfer.id) else { return };- let title = match transfer.names.as_slice() {- [one] => one.clone(),- names => format!("{} files", names.len()),- };+ let title = crate::transfers::title(transfer);let device = tracked.device_name.clone();let finished = |title: String, body: String| Toast {device: TOAST_GROUP.into(),@@ -334,11 +325,7 @@ fn update(map: &mut HashMap<String, Tracked>, transfer: &Transfer) {tracked.shown = Some((Instant::now(), progress));}TransferState::Done { .. } => {- let mut body = format!("Sent to {device}");- if tracked.skipped_folders {- body.push_str(". Folders were left out.");- }- toast::show(finished(title, body));+ toast::show(finished(title, format!("Sent to {device}")));map.remove(&transfer.id);}TransferState::Failed(failure) => {diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rsindex b01e0e7..6d02469 100644--- a/desktop/app/src/state.rs+++ b/desktop/app/src/state.rs@@ -835,6 +835,7 @@ mod tests {device: DeviceId([1; 32]),direction: nectarlink_core::Direction::Outgoing,names: vec!["a.bin".into()],+ files: 1,total: 1000,done,state,diff --git a/desktop/app/src/transfers.rs b/desktop/app/src/transfers.rsindex a71ff43..d9512ef 100644--- a/desktop/app/src/transfers.rs+++ b/desktop/app/src/transfers.rs@@ -5,7 +5,7 @@use std::path::{Path, PathBuf};-use nectarlink_core::{DeviceId, Direction, Error, FileSource, NodeEvent, OutgoingFile, TransferState};+use nectarlink_core::{DeviceId, Direction, Error, NodeEvent, Transfer, TransferState};use crate::{bridge::app::{describe, show_message},@@ -19,22 +19,26 @@ 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.+/// What a transfer is called: its file or folder's name, or how many.+pub fn title(t: &Transfer) -> String {+ match t.names.as_slice() {+ [one] => one.clone(),+ names if names.len() == t.files => format!("{} files", names.len()),+ names => format!("{} items", names.len()),+ }+}++/// Sends files and folders 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 {+ let files = match tokio::task::spawn_blocking(move || nectarlink_core::outgoing_paths(&paths)).await {+ Ok(Ok(files)) if !files.is_empty() => files,+ Ok(Ok(_)) => return show_message("There's nothing to send in there."),+ Ok(Err(Error::TooLarge)) => return show_message("That's too many files to send at once."),+ Ok(Err(e)) => return show_message(describe(&e)),+ Err(_) => return,+ };match node.send_files(device, files).await {Ok(_) => {}Err(Error::Denied) => show_message("Files are turned off for that device."),@@ -49,14 +53,14 @@ pub fn cancel(id: &str) {}}-/// Opens a received file with its app.+/// Opens a received file with its app (or a folder in File Explorer).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.+/// Shows a received file or folder in File Explorer, selected.pub fn show_in_folder(path: &Path) {let mut select = std::ffi::OsString::from("/select,");select.push(path);@@ -74,10 +78,7 @@ pub fn on_event(event: &NodeEvent) {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"),- };+ let title = title(t);toast::show(Toast {device: TOAST_GROUP.into(),key: first.to_string_lossy().into_owned(),diff --git a/docs/protocol/files.md b/docs/protocol/files.mdindex 5b3e15b..cbfc871 100644--- a/docs/protocol/files.md+++ b/docs/protocol/files.md@@ -3,8 +3,8 @@> 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.+Sends files and folders between paired devices, in either direction, with+progress, cancellation and resuming after a dropped connection.## 1. Capability@@ -22,14 +22,27 @@ 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+ files: [ {+ name: text, // The file's name+ size: uint,+ ? folder: text, // Only for files in a sent folder (see below)+ } ], // 1–5,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).+or control characters, and not `.` or `..`.++**Folders.** A sent folder is its files, each with `folder`: where the file+is, as names joined by `/`, starting with the sent folder's own (`Trip`,+`Trip/Day 1`). Each name follows the rules for `name`; there are at most 32+of them, in at most 1,024 bytes. A folder's files are listed together.+Empty folders aren't sent.++Receivers **MUST** reject an offer that breaks these rules with+`BAD_MESSAGE`, and still pick their own safe names for writing (see §4). The+whole offer is one frame (v0 §3), which limits how many files with long+names fit in it.The receiver answers on the same stream:@@ -67,7 +80,11 @@ else (a reset, a closed connection, a missing `done`) means it didn't.- Files are written to a private folder first and moved to where the userfinds them (the Downloads folder) only once complete.-- A name that already exists there gets a number: `photo (2).jpg`.+- A name that already exists there gets a number: `photo (2).jpg`. A sent+ folder gets a new folder of its own the same way (`Trip (2)`); nothing+ is ever added to a folder that was already there.+- Names the receiving system can't store (on Windows: `CON`, `NUL`, `?`,+ trailing dots…) are changed to ones it can.- A device accepts files only from paired devices with the `files` toggleon. A receiver that runs out of space resets the stream.- Implementations **MUST NOT** log file names (v0 §11).