From 70b18a6aa6afc62d3ef87c85af4633a37246cfdf Mon Sep 17 00:00:00 2001 From: Nigel <201522880+Page011@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:27:24 +1100 Subject: [PATCH 1/5] Local Tugboat 0.2.0: any file type, drag onto the PC window, no expiry hold - Any file type syncs both ways. Photos and videos keep the content check; everything else is a File item (type icon, name, size, Open). Shortcut and folder-setting files (.lnk, .url, .scf, .library-ms, .searchConnector-ms, desktop.ini, autorun.inf) never sync and are listed as REFUSED. - Files the PC receives carry the Windows "downloaded from elsewhere" mark (Zone.Identifier, zone 3), written before the file appears in the library; if the mark cannot be written the file waits with an error instead of arriving unmarked. - Drag files onto the PC window to copy them into the folder being viewed (Inbox by default), with progress and a result banner. Folders are not copied. - Items expire on time even when no device has confirmed them (the expiry hold and the "waiting" state are gone). - Phone storage guard: downloads stop below the reserve and the phone shows PHONE STORAGE LOW. - Android: share any file into Tugboat, open files with the default app through a content URI, real file names shown to other apps, rotation no longer cuts a video recording. - Fixes: expired QR shows PAIRING CODE EXPIRED, last seen refreshes on every sync change, file times kept across restarts. - Protocol version 2: a 0.1.x device sees "Update Tugboat on the " instead of syncing silently wrong. - Versions 0.2.0 (Android version code 4); schema v2 with backup. --- Cargo.lock | 8 +- Cargo.toml | 2 +- apps/android/FFI.md | 34 +- apps/android/app/build.gradle.kts | 4 +- apps/android/app/src/main/AndroidManifest.xml | 12 +- .../main/java/app/localtugboat/Background.kt | 4 +- .../java/app/localtugboat/CameraScreen.kt | 9 + .../main/java/app/localtugboat/Components.kt | 25 + .../src/main/java/app/localtugboat/Core.kt | 7 +- .../src/main/java/app/localtugboat/Export.kt | 25 +- .../src/main/java/app/localtugboat/Files.kt | 158 ++++ .../src/main/java/app/localtugboat/Gallery.kt | 14 +- .../src/main/java/app/localtugboat/Import.kt | 66 +- .../main/java/app/localtugboat/PairingText.kt | 69 +- .../java/app/localtugboat/ShareActivity.kt | 7 +- .../main/java/app/localtugboat/SnapService.kt | 29 +- .../java/app/localtugboat/SnapViewModel.kt | 19 +- .../src/main/java/app/localtugboat/Texts.kt | 25 +- .../src/main/java/app/localtugboat/UiLogic.kt | 30 +- .../src/main/java/app/localtugboat/Viewer.kt | 60 +- .../app/src/main/res/drawable/ic_file.xml | 9 + .../src/main/res/drawable/ic_file_archive.xml | 9 + .../src/main/res/drawable/ic_file_audio.xml | 9 + .../app/src/main/res/drawable/ic_file_doc.xml | 9 + .../Adversarial020SecurityTest.kt | 68 ++ .../app/localtugboat/Adversarial020Test.kt | 54 ++ .../test/java/app/localtugboat/AnyFileTest.kt | 313 ++++++++ .../java/app/localtugboat/PairingTextTest.kt | 10 +- .../test/java/app/localtugboat/TextsTest.kt | 38 +- .../test/java/app/localtugboat/UiLogicTest.kt | 67 +- apps/desktop/package.json | 2 +- apps/desktop/src-tauri/src/backend.rs | 96 ++- apps/desktop/src-tauri/src/bindings.rs | 12 +- apps/desktop/src-tauri/src/commands.rs | 35 + apps/desktop/src-tauri/src/drop.rs | 237 ++++++ apps/desktop/src-tauri/src/lib.rs | 2 + apps/desktop/src-tauri/src/library/config.rs | 22 +- apps/desktop/src-tauri/src/library/mod.rs | 18 +- .../src-tauri/src/library/placement.rs | 76 +- .../src-tauri/src/library/reconcile.rs | 345 +++++++-- apps/desktop/src-tauri/src/library/tests.rs | 713 +++++++++++++++++- apps/desktop/src-tauri/src/shell.rs | 34 +- apps/desktop/src-tauri/src/tray.rs | 2 +- apps/desktop/src-tauri/src/winfs.rs | 110 ++- apps/desktop/src-tauri/tauri.conf.json | 2 +- .../tests/adversarial_020_library.rs | 211 ++++++ .../tests/adversarial_020_security.rs | 259 +++++++ apps/desktop/src-tauri/tests/backend_e2e.rs | 79 ++ apps/desktop/src-tauri/tests/versions.rs | 18 + apps/desktop/src/App.svelte | 9 +- apps/desktop/src/lib/Banners.svelte | 18 +- apps/desktop/src/lib/Bin.svelte | 3 +- apps/desktop/src/lib/DropOverlay.svelte | 68 ++ apps/desktop/src/lib/Gallery.svelte | 17 +- apps/desktop/src/lib/ItemTile.svelte | 24 +- apps/desktop/src/lib/Pair.svelte | 4 +- apps/desktop/src/lib/Settings.svelte | 4 +- apps/desktop/src/lib/StatusBar.svelte | 27 + apps/desktop/src/lib/api.ts | 15 +- apps/desktop/src/lib/app.svelte.ts | 41 +- apps/desktop/src/lib/banners.test.ts | 32 +- apps/desktop/src/lib/banners.ts | 24 +- apps/desktop/src/lib/bindings/DropLine.ts | 7 + apps/desktop/src/lib/bindings/DropProgress.ts | 7 + apps/desktop/src/lib/bindings/DropReport.ts | 11 + apps/desktop/src/lib/bindings/DropState.ts | 6 + apps/desktop/src/lib/bindings/ItemState.ts | 2 +- apps/desktop/src/lib/bindings/ItemView.ts | 9 +- .../desktop/src/lib/bindings/LibraryStatus.ts | 7 +- apps/desktop/src/lib/bindings/MediaKind.ts | 2 +- .../desktop/src/lib/bindings/NotSyncedFile.ts | 2 +- apps/desktop/src/lib/bindings/SyncStatus.ts | 9 +- apps/desktop/src/lib/drop.test.ts | 66 ++ apps/desktop/src/lib/drop.ts | 50 ++ apps/desktop/src/lib/format.test.ts | 51 +- apps/desktop/src/lib/format.ts | 41 +- apps/desktop/src/lib/icons.ts | 36 +- crates/core/bindings/ItemState.ts | 2 +- crates/core/bindings/ItemView.ts | 9 +- crates/core/bindings/MediaKind.ts | 2 +- crates/core/bindings/SyncStatus.ts | 9 +- crates/core/examples/fake_pc.rs | 33 +- crates/core/examples/fake_phone.rs | 77 +- crates/core/src/bin.rs | 169 ++++- crates/core/src/db.rs | 109 ++- crates/core/src/error.rs | 9 +- crates/core/src/events.rs | 7 +- crates/core/src/expiry.rs | 99 ++- crates/core/src/facade.rs | 151 +++- crates/core/src/folders.rs | 18 +- crates/core/src/merge.rs | 65 +- crates/core/src/model.rs | 16 +- crates/core/src/names.rs | 447 ++++++++++- crates/core/src/ops.rs | 279 +++++-- crates/core/src/placement.rs | 39 +- crates/core/src/schema/v2.sql | 79 ++ crates/core/src/store.rs | 122 ++- crates/core/src/sync/engine.rs | 2 +- crates/core/src/sync/net.rs | 179 ++++- crates/core/src/sync/pair.rs | 29 +- crates/core/src/sync/wire.rs | 10 +- crates/core/tests/adversarial_020_core.rs | 135 ++++ crates/core/tests/adversarial_020_security.rs | 139 ++++ crates/core/tests/any_file.rs | 432 +++++++++++ crates/core/tests/common/mod.rs | 70 +- crates/core/tests/engine.rs | 2 +- crates/core/tests/pairing_flow.rs | 20 +- crates/core/tests/robust.rs | 6 +- crates/core/tests/two_cores.rs | 72 +- crates/ffi/src/error.rs | 8 +- crates/ffi/src/lib.rs | 47 +- crates/ffi/tests/phone_flow.rs | 20 +- crates/net/src/pairing.rs | 22 +- crates/net/src/tests/pairing.rs | 7 +- 114 files changed, 6349 insertions(+), 650 deletions(-) create mode 100644 apps/android/app/src/main/java/app/localtugboat/Files.kt create mode 100644 apps/android/app/src/main/res/drawable/ic_file.xml create mode 100644 apps/android/app/src/main/res/drawable/ic_file_archive.xml create mode 100644 apps/android/app/src/main/res/drawable/ic_file_audio.xml create mode 100644 apps/android/app/src/main/res/drawable/ic_file_doc.xml create mode 100644 apps/android/app/src/test/java/app/localtugboat/Adversarial020SecurityTest.kt create mode 100644 apps/android/app/src/test/java/app/localtugboat/Adversarial020Test.kt create mode 100644 apps/android/app/src/test/java/app/localtugboat/AnyFileTest.kt create mode 100644 apps/desktop/src-tauri/src/drop.rs create mode 100644 apps/desktop/src-tauri/tests/adversarial_020_library.rs create mode 100644 apps/desktop/src-tauri/tests/adversarial_020_security.rs create mode 100644 apps/desktop/src-tauri/tests/versions.rs create mode 100644 apps/desktop/src/lib/DropOverlay.svelte create mode 100644 apps/desktop/src/lib/bindings/DropLine.ts create mode 100644 apps/desktop/src/lib/bindings/DropProgress.ts create mode 100644 apps/desktop/src/lib/bindings/DropReport.ts create mode 100644 apps/desktop/src/lib/bindings/DropState.ts create mode 100644 apps/desktop/src/lib/drop.test.ts create mode 100644 apps/desktop/src/lib/drop.ts create mode 100644 crates/core/src/schema/v2.sql create mode 100644 crates/core/tests/adversarial_020_core.rs create mode 100644 crates/core/tests/adversarial_020_security.rs create mode 100644 crates/core/tests/any_file.rs diff --git a/Cargo.lock b/Cargo.lock index 03ab101..de25acf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6447,7 +6447,7 @@ dependencies = [ [[package]] name = "tugboat-core" -version = "0.1.0" +version = "0.2.0" dependencies = [ "blake3", "fs4", @@ -6468,7 +6468,7 @@ dependencies = [ [[package]] name = "tugboat-desktop" -version = "0.1.0" +version = "0.2.0" dependencies = [ "blake3", "fs4", @@ -6500,7 +6500,7 @@ dependencies = [ [[package]] name = "tugboat-ffi" -version = "0.1.0" +version = "0.2.0" dependencies = [ "getrandom 0.4.3", "hex", @@ -6517,7 +6517,7 @@ dependencies = [ [[package]] name = "tugboat-net" -version = "0.1.0" +version = "0.2.0" dependencies = [ "blake3", "fs4", diff --git a/Cargo.toml b/Cargo.toml index ac79a78..14711ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/net", "crates/core", "crates/ffi", "apps/desktop/src-tauri"] exclude = ["spike"] [workspace.package] -version = "0.1.0" +version = "0.2.0" edition = "2021" rust-version = "1.85" license = "Apache-2.0" diff --git a/apps/android/FFI.md b/apps/android/FFI.md index e1f3953..704959d 100644 --- a/apps/android/FFI.md +++ b/apps/android/FFI.md @@ -85,7 +85,7 @@ throw; every other method carries `@Throws(SnapException::class)` in the generat | `open` | Logging, database (backup, migrate; a newer database is refused with `NewerDatabase`), default folders Inbox / Keep / Unsorted, one Bin sweep, event pump, ticker (Bin sweep and pairing expiry at the core's next due time, at most 60 s apart). Does not touch the network. | | `deviceId` | This phone's public key, 64 hex chars. | | `logPath` | Current log file. `.1` and `.2` are the older rotated files (5 MB each, three kept). "Export log" shares all that exist, oldest first. | -| `freeSpaceBytes` | Free bytes on the volume holding phone copies, for the storage guard banner against `Settings.storageGuardBytes`. Core does not enforce the guard yet (M4): the banner is the app's. | +| `freeSpaceBytes` | Free bytes on the volume holding phone copies. Used for Settings' storage line and for refusing a shared file that does not fit. The storage guard itself is enforced by the core since 0.2.0 (downloads stop below `Settings.storageGuardBytes`); the banner follows `SyncStatus.storageLow`, not this number. | | `startNetwork(mdns)` | Starts the endpoint (binds `0.0.0.0`, random UDP port) and the connect loop to the paired PC (cached addresses first, `mdns` = then look it up by name). `Invalid` if already started. | | `stopNetwork` | Stops it. | | `reconnectNow` | Wi-Fi changed or app came to the front: dial the PC now instead of waiting out the back-off (up to 30 s). Safe any time. | @@ -169,11 +169,11 @@ data class PairingPreview( data class NewFile( var srcPath: kotlin.String, // file the app owns; core copies it, the caller deletes it - var name: kotlin.String, // display name; extension and magic bytes must agree + var name: kotlin.String, // display name. Any type: a photo/video extension must match its bytes, every other name (or none) is a plain File. Shortcut and folder-setting names are refused var folderId: kotlin.String?, // null = Inbox var capturedAtMs: kotlin.Long, var geo: GeoFix?, - var thumbPath: kotlin.String?, // JPEG, longest side 512 px, made by the app + var thumbPath: kotlin.String?, // JPEG, longest side 512 px, made by the app. Photos and videos only: the core ignores it for a File var imported: kotlin.Boolean // false = camera shot, true = Share > Tugboat ) @@ -188,8 +188,9 @@ data class SyncStatus( var state: SyncState, var peerName: kotlin.String?, var lastSyncedAt: kotlin.Long?, // unix ms, "Synced 10s ago" - var waiting: kotlin.UInt, // items waiting for the PC's receipt ("3 waiting") - var downloading: kotlin.UInt, + var waiting: kotlin.UInt, // held here, not in the Bin, no receipt from the PC yet ("3 waiting"); nothing is held back for it: items expire on time + var downloading: kotlin.UInt, // items that wait on the PC (Pending here) + var storageLow: kotlin.Boolean, // 0.2.0: the storage guard is holding downloads back (red banner: "PHONE STORAGE LOW - 37 items wait on the PC") var message: kotlin.String? // one line for REFUSED / PAUSED / "PC NOT TOLD YET ..." ) @@ -206,7 +207,7 @@ data class Settings( ```kotlin enum class FolderKind { INBOX, KEEP, UNSORTED, USER } -enum class MediaKind { IMAGE, VIDEO } +enum class MediaKind { IMAGE, VIDEO, FILE } // FILE (0.2.0) = any other file type: icon tile, no thumbnail enum class LocalFileState { PENDING, PRESENT, BINNED, PURGED, LOST, REFUSED } enum class SyncState { UNPAIRED, OFFLINE, CONNECTING, SYNCING, SYNCED, PAUSED, REFUSED } enum class ActivityAction { @@ -220,7 +221,6 @@ sealed class ItemStateInfo { data class Expired(val binnedAtMs: kotlin.Long) : ItemStateInfo() // in the Bin, expired object Kept : ItemStateInfo() // pinned: "Kept" object FolderKeep : ItemStateInfo() // folder never expires: "Keep" - object Waiting : ItemStateInfo() // PC has not confirmed the file: "Waiting for PC" data class Live(val expiresAtMs: kotlin.Long) : ItemStateInfo() // "Expires in 5h" } @@ -274,7 +274,8 @@ sealed class SnapException(message: String) : kotlin.Exception(message) { class NotFound(message: String) class InvalidName(message: String) class Invalid(message: String) // rule broken: unknown/deleted folder, restore of a non-Bin item, bad setting - class NotMedia(message: String) // not a supported photo/video (extension or magic bytes) + class NotMedia(message: String) // a photo/video extension whose bytes are not one (an exe renamed .jpg) + class Refused(message: String) // 0.2.0: always-refused name (.lnk .url .scf .library-ms .searchConnector-ms, desktop.ini, autorun.inf) or over 16 GB class FileGone(message: String) class NotPaired(message: String) class AlreadyPaired(message: String) @@ -296,16 +297,27 @@ sealed class SnapException(message: String) : kotlin.Exception(message) { class Pairing(message: String) // any other pairing failure } ``` -Onboarding mapping: `PairBadPayload` = "That is not a Tugboat code"; `PairExpired` = show a new -QR on the PC; `PairSecretReused` = "already used"; `NetTimeout` / `NetUnreachable` = +Onboarding mapping: `PairBadPayload` = "That is not a Tugboat code" (only this); `PairExpired` = the core's +"PAIRING CODE EXPIRED - show a new QR". The PC opens a NEW pairing window when the old one runs out, so +an old QR can also come back as `PairBadSecret` or `PairNotOpen`: the app reads the payload's expiry +(`inspectPairingPayload`, before dialing) and shows the expired text when its time has passed by the +phone's clock (`Texts.pairFailure(..., codeExpired)`); `PairSecretReused` = "already used"; `NetTimeout` / `NetUnreachable` = "PC not found: same Wi-Fi? Local network allowed?"; `PairConfirmTimeout`, `PairCancelled` = retry. Typed checks pinned by `crates/ffi/tests/phone_flow.rs`: `addFile` of a missing file is `Io` -(message names the file), of an exe renamed `.jpg` is `NotMedia`, into an unknown folder is +(message names the file), of an exe renamed `.jpg` is `NotMedia`, of `x.lnk` is `Refused`, into an unknown folder is `Invalid`; a malformed id is `InvalidInput`; junk to `pairWith` is `PairBadPayload`; `unpair` with nothing paired is `NotPaired`; `saveSettings` with `binDays = 0` is `Invalid`. +## Name rules (0.2.0) + +Top-level functions, the same code the PC runs, so the app keeps no copy of the rules: +`namesExtOf(name)` (lowercase extension or ""), `namesIsRefused(name)`, `namesRefusedText()`. +`ShareNames` calls them through the `NameRules` interface (a JVM test cannot load the .so, so tests +pass a stand-in). `ItemInfo.neverReachedPeer` = in the Bin because it expired before the PC confirmed it +(shown as "NOT ON PC"). + ## Build `apps\android\build-rust.cmd` (cmd.exe, from anywhere): host build with the bindgen binary, diff --git a/apps/android/app/build.gradle.kts b/apps/android/app/build.gradle.kts index ed58324..6a0bc73 100644 --- a/apps/android/app/build.gradle.kts +++ b/apps/android/app/build.gradle.kts @@ -11,8 +11,8 @@ android { applicationId = providers.gradleProperty("tugboat.applicationId").get() minSdk = 31 targetSdk = 37 - versionCode = 3 - versionName = "0.1.1" + versionCode = 4 + versionName = "0.2.0" // Only the two ABIs build-rust.cmd produces: arm64-v8a (phone) and x86_64 (emulator). ndk { abiFilters += listOf("arm64-v8a", "x86_64") } } diff --git a/apps/android/app/src/main/AndroidManifest.xml b/apps/android/app/src/main/AndroidManifest.xml index 691fa10..0ab8ecd 100644 --- a/apps/android/app/src/main/AndroidManifest.xml +++ b/apps/android/app/src/main/AndroidManifest.xml @@ -59,7 +59,8 @@ - + - - + - - + @@ -108,8 +107,9 @@ android:name="com.google.android.datatransport.runtime.scheduling.jobscheduling.AlarmManagerSchedulerBroadcastReceiver" tools:node="remove" /> + diff --git a/apps/android/app/src/main/java/app/localtugboat/Background.kt b/apps/android/app/src/main/java/app/localtugboat/Background.kt index 7a181ef..3103cf2 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Background.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Background.kt @@ -22,7 +22,7 @@ object ServiceGate { val p = core.phone() val wanted = p.pairedPc() != null && p.settings().stayConnected KLog.log(c, "start check ($why): wanted=$wanted running=${core.serviceRunning}") - if (wanted && !core.serviceRunning) SnapService.start(c) + if (wanted && !core.serviceRunning) SnapService.start(c, why) wanted } catch (e: Exception) { core.reportError("start check ($why) failed: ${e.message}") @@ -69,7 +69,7 @@ class CatchUpWorker(c: Context, p: WorkerParameters) : CoroutineWorker(c, p) { if (p.settings().stayConnected && !core.serviceRunning) { if (Perms.batteryExempt(app)) { KLog.log(app, "worker: service not running, restarting it") - SnapService.start(app) + SnapService.start(app, "worker") } else { KLog.log(app, "worker: service not running and not exempt from battery optimisation, cannot restart it") } diff --git a/apps/android/app/src/main/java/app/localtugboat/CameraScreen.kt b/apps/android/app/src/main/java/app/localtugboat/CameraScreen.kt index 4d682fd..b5d15a2 100644 --- a/apps/android/app/src/main/java/app/localtugboat/CameraScreen.kt +++ b/apps/android/app/src/main/java/app/localtugboat/CameraScreen.kt @@ -145,6 +145,15 @@ fun CameraScreen(vm: SnapViewModel, ui: UiState, banners: List LightSystemIcons() + // Rotating the phone recreates the activity (no configChanges), which unbinds CameraX and ends the recording. + // So the orientation is locked for exactly as long as a recording runs, and released the moment it ends or the screen leaves. + val activity = androidx.activity.compose.LocalActivity.current + val isRecording = recording != null + DisposableEffect(isRecording, activity) { + if (isRecording) activity?.requestedOrientation = UiLogic.recordingOrientation(true) + onDispose { if (isRecording) activity?.requestedOrientation = UiLogic.recordingOrientation(false) } + } + // Location only while this screen is visible (while-in-use permission, never background). LifecycleResumeEffect(tracker) { tracker.start()?.let { KLog.log(ctx, "location not started: $it") } diff --git a/apps/android/app/src/main/java/app/localtugboat/Components.kt b/apps/android/app/src/main/java/app/localtugboat/Components.kt index f219bec..a9651d4 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Components.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Components.kt @@ -154,6 +154,31 @@ fun ThumbImage(path: String?, desc: String?, modifier: Modifier = Modifier, scal } } +@DrawableRes +fun fileIcon(ext: String): Int = when (FileRules.glyph(ext)) { + FileGlyph.DOCUMENT -> R.drawable.ic_file_doc + FileGlyph.ARCHIVE -> R.drawable.ic_file_archive + FileGlyph.AUDIO -> R.drawable.ic_file_audio + FileGlyph.OTHER -> R.drawable.ic_file +} + +/** What a file that is not a photo or video shows where a thumbnail would be: type icon, name, "PDF, 1.2 MB". */ +@Composable +fun FileFace(item: uniffi.tugboat_ffi.ItemInfo, modifier: Modifier = Modifier) { + val cs = MaterialTheme.colorScheme + Column( + modifier.background(cs.surfaceVariant).padding(start = 6.dp, end = 6.dp, top = 6.dp, bottom = 30.dp), + horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, + ) { + Ico(fileIcon(item.ext), null, tint = cs.onSurfaceVariant, size = 28) + Text( + FileRules.displayName(item.name, item.ext), style = MaterialTheme.typography.labelMedium, color = cs.onSurface, + maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = androidx.compose.ui.text.style.TextAlign.Center, + ) + Text(FileRules.meta(item.ext, item.size.toLong()), style = MaterialTheme.typography.labelSmall, color = cs.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } +} + /** * Bottom sheet to pick a folder. [autoLabel] non-null adds a first row (the rule-based choice). * [currentId] gets a check mark and a "Current" word, so the choice is not colour or icon alone. diff --git a/apps/android/app/src/main/java/app/localtugboat/Core.kt b/apps/android/app/src/main/java/app/localtugboat/Core.kt index 3c5bca8..a8c6319 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Core.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Core.kt @@ -67,7 +67,9 @@ class Core(private val app: Application) { // Runs on a Rust runtime thread: record and return, never call back into the core. when (event) { is FfiEvent.Sync -> _status.value = event.status - is FfiEvent.Error -> reportError("${event.kind}: ${event.message}") + // The storage guard already has its own red banner (status.storageLow, with the count): a second amber one + // with the raw "storage_low:" text only repeats it and outlives it. It stays in the log. + is FfiEvent.Error -> if (event.kind == STORAGE_LOW_KIND) KLog.log(app, "core: ${event.kind}: ${event.message}") else reportError("${event.kind}: ${event.message}") else -> {} } _events.tryEmit(event) @@ -196,5 +198,8 @@ class Core(private val app: Application) { companion object { const val BURST_MS = 30_000L const val PAUSE_MS = 120_000L + + /** FfiEvent.Error kind the core uses when the storage guard turns on (the banner shows it already). */ + const val STORAGE_LOW_KIND = "storage_low" } } diff --git a/apps/android/app/src/main/java/app/localtugboat/Export.kt b/apps/android/app/src/main/java/app/localtugboat/Export.kt index 53874a7..99b74af 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Export.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Export.kt @@ -47,14 +47,12 @@ object LogExport { /** Share and "Save to phone gallery" for one item. */ object ItemExport { - /** Share sheet for the held file. Throws IOException with a readable message when the file is not on this phone. */ + /** + * Share sheet for the held file. The URI carries the item's real name, so the receiving app does not see + * `.ext`. Throws IOException with a readable message when the file is not on this phone. + */ fun shareIntent(c: Context, item: ItemInfo): Intent { - val path = item.path ?: throw IOException("File is not on this phone yet") - val uri = try { - FileProvider.getUriForFile(c, authority(c), File(path)) - } catch (e: IllegalArgumentException) { - throw IOException("This file cannot be shared from the Bin. Restore it first") - } + val uri = ItemFileProvider.uriFor(c, item) return Intent.createChooser( Intent(Intent.ACTION_SEND).setType(mimeOf(item)).putExtra(Intent.EXTRA_STREAM, uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION), "Share", @@ -66,6 +64,7 @@ object ItemExport { * The copy leaves Tugboat's control: it never expires. Blocking. Throws IOException. */ fun saveToGallery(c: Context, item: ItemInfo): Uri { + if (item.kind == uniffi.tugboat_ffi.MediaKind.FILE) throw IOException("Only photos and videos go to the phone gallery") val src = File(item.path ?: throw IOException("File is not on this phone yet")) val video = item.kind == uniffi.tugboat_ffi.MediaKind.VIDEO val collection = if (video) MediaStore.Video.Media.EXTERNAL_CONTENT_URI else MediaStore.Images.Media.EXTERNAL_CONTENT_URI @@ -90,15 +89,5 @@ object ItemExport { } } - private fun mimeOf(item: ItemInfo): String = when (item.ext.lowercase()) { - "jpg", "jpeg" -> "image/jpeg" - "png" -> "image/png" - "gif" -> "image/gif" - "webp" -> "image/webp" - "heic", "heif" -> "image/heic" - "mp4", "m4v" -> "video/mp4" - "mov" -> "video/quicktime" - "3gp" -> "video/3gpp" - else -> if (item.kind == uniffi.tugboat_ffi.MediaKind.VIDEO) "video/*" else "image/*" - } + private fun mimeOf(item: ItemInfo): String = FileRules.mime(item.ext, item.kind, PlatformMime.ofExt) } diff --git a/apps/android/app/src/main/java/app/localtugboat/Files.kt b/apps/android/app/src/main/java/app/localtugboat/Files.kt new file mode 100644 index 0000000..f765783 --- /dev/null +++ b/apps/android/app/src/main/java/app/localtugboat/Files.kt @@ -0,0 +1,158 @@ +package app.localtugboat + +import android.content.ContentResolver +import android.content.Intent +import android.database.Cursor +import android.database.MatrixCursor +import android.net.Uri +import android.provider.OpenableColumns +import android.webkit.MimeTypeMap +import androidx.core.content.FileProvider +import java.io.File +import java.io.IOException +import uniffi.tugboat_ffi.ItemInfo +import uniffi.tugboat_ffi.MediaKind + +/** Which icon a file tile wears. Four are enough: the extension is written next to it. */ +enum class FileGlyph { DOCUMENT, ARCHIVE, AUDIO, OTHER } + +/** + * Pure rules for files that are not photos or videos: icon, labels, names shown to other apps, MIME types. + * No Android classes (the platform MIME lookup is passed in), so every rule has a JVM test. + */ +object FileRules { + private val DOCUMENT = setOf("pdf", "doc", "docx", "odt", "rtf", "txt", "md", "csv", "xls", "xlsx", "ods", "ppt", "pptx", "odp", "json", "xml", "html", "log") + private val ARCHIVE = setOf("zip", "7z", "rar", "tar", "gz", "tgz", "bz2", "xz") + private val AUDIO = setOf("mp3", "m4a", "aac", "wav", "flac", "ogg", "opus", "amr") + + fun glyph(ext: String): FileGlyph = when (ext.lowercase()) { + in DOCUMENT -> FileGlyph.DOCUMENT + in ARCHIVE -> FileGlyph.ARCHIVE + in AUDIO -> FileGlyph.AUDIO + else -> FileGlyph.OTHER + } + + /** "512 B", "3 KB", "1.2 MB", "12 MB", "1.5 GB": one decimal under 10, none above, so a file tile shows a real size. */ + fun sizeText(n: Long): String { + fun unit(v: Double, u: String) = if (v < 10) "%.1f %s".format(java.util.Locale.ROOT, v, u) else "${Math.round(v)} $u" + return when { + n >= 1L shl 30 -> unit(n / (1L shl 30).toDouble(), "GB") + n >= 1L shl 20 -> unit(n / (1L shl 20).toDouble(), "MB") + n >= 1L shl 10 -> "${n shr 10} KB" + else -> "${n.coerceAtLeast(0)} B" + } + } + + /** "PDF, 1.2 MB". A file with no extension reads "File, 3 KB". */ + fun meta(ext: String, sizeBytes: Long): String = "${if (ext.isEmpty()) "File" else ext.uppercase()}, ${sizeText(sizeBytes)}" + + /** The name with its extension, once: core item names already carry it, but never trust that for a display. */ + fun displayName(name: String, ext: String): String = + if (ext.isEmpty() || name.endsWith(".$ext", ignoreCase = true)) name else "$name.$ext" + + /** + * The name another app sees for a shared or opened file. Path separators and control characters go (a name + * is shown, never used as a path), the length is capped. Null = nothing usable: the provider keeps its own name. + */ + fun providerName(raw: String?): String? { + // Direction controls (U+061C, U+200E/F, U+202A-E, U+2066-9) go too: "invoicefdp.exe" reads "invoiceexe.pdf". + val s = raw?.replace(Regex("""[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]"""), "")?.replace(Regex("""[\\/\p{Cntrl}]"""), "_")?.trim()?.take(120)?.trim() + return if (s.isNullOrEmpty() || s == "." || s == "..") null else s + } + + /** MIME for an opening or sharing intent. Photos and videos keep their fixed table; anything else asks the platform. */ + fun mime(ext: String, kind: MediaKind, platform: (String) -> String?): String { + val e = ext.lowercase() + MEDIA_MIME[e]?.let { return it } + if (kind == MediaKind.VIDEO) return "video/*" + if (kind == MediaKind.IMAGE) return "image/*" + return (if (e.isEmpty()) null else platform(e)) ?: "application/octet-stream" + } + + private val MEDIA_MIME = mapOf( + "jpg" to "image/jpeg", "jpeg" to "image/jpeg", "png" to "image/png", "gif" to "image/gif", "webp" to "image/webp", + "heic" to "image/heic", "heif" to "image/heic", "mp4" to "video/mp4", "m4v" to "video/mp4", "mov" to "video/quicktime", "3gp" to "video/3gpp", + ) + + /** An extension for a shared file that names none, from its MIME type. Null for the types that say nothing. */ + fun extFromMime(mime: String?, platform: (String) -> String?): String? { + val m = mime?.substringBefore(';')?.trim()?.lowercase() ?: return null + if (m.isEmpty() || m.endsWith("/*") || m == "application/octet-stream") return null + return platform(m)?.lowercase()?.takeIf { it.isNotEmpty() } + } + + /** The "no app" line. */ + fun noAppText(ext: String) = if (ext.isEmpty()) "NO APP OPENS THIS FILE - use Share" else "NO APP OPENS .${ext.uppercase()} FILES - use Share" +} + +/** Platform MIME lookups, passed to [FileRules]. */ +object PlatformMime { + val ofExt: (String) -> String? = { MimeTypeMap.getSingleton().getMimeTypeFromExtension(it) } + val extOf: (String) -> String? = { MimeTypeMap.getSingleton().getExtensionFromMimeType(it) } +} + +/** + * FileProvider that answers a content query with the item's real file name. Held files are stored as + * `.`, so without this the app that opens or receives a share would see the uuid. The name rides in + * the URI's query (`?n=`), which FileProvider ignores when it finds the file; it is display only. + */ +class ItemFileProvider : FileProvider() { + override fun query(uri: Uri, projection: Array?, selection: String?, selectionArgs: Array?, sortOrder: String?): Cursor { + val base = super.query(uri, projection, selection, selectionArgs, sortOrder) + val name = FileRules.providerName(uri.getQueryParameter(NAME_PARAM)) ?: return base + try { + val cols = base.columnNames + val out = MatrixCursor(cols, 1) + if (base.moveToFirst()) { + val row = out.newRow() + for (i in cols.indices) { + row.add( + when { + cols[i] == OpenableColumns.DISPLAY_NAME -> name + base.getType(i) == Cursor.FIELD_TYPE_INTEGER -> base.getLong(i) + base.getType(i) == Cursor.FIELD_TYPE_NULL -> null + else -> base.getString(i) + }, + ) + } + } + return out + } finally { + base.close() + } + } + + companion object { + const val NAME_PARAM = "n" + + fun authority(c: android.content.Context) = "${c.packageName}.fileprovider" + + /** content:// URI for a held item with its real name attached. Throws IOException for a file outside items/ (the Bin). */ + fun uriFor(c: android.content.Context, item: ItemInfo): Uri { + val path = item.path ?: throw IOException("File is not on this phone yet") + val plain = try { + FileProvider.getUriForFile(c, authority(c), File(path)) + } catch (e: IllegalArgumentException) { + throw IOException("This file cannot be opened or shared from the Bin. Restore it first") + } + return plain.buildUpon().appendQueryParameter(NAME_PARAM, FileRules.displayName(item.name, item.ext)).build() + } + + /** ACTION_VIEW for the file: a content URI with a read grant, never file://. The platform picks the default app. */ + fun openIntent(c: android.content.Context, item: ItemInfo): Intent { + val uri = uriFor(c, item) + return Intent(Intent.ACTION_VIEW) + .setDataAndType(uri, FileRules.mime(item.ext, item.kind, PlatformMime.ofExt)) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + } +} + +/** Content resolver helpers for Share > Tugboat. */ +object ShareQuery { + fun type(r: ContentResolver, uri: Uri): String? = try { + r.getType(uri) + } catch (e: Exception) { + null + } +} diff --git a/apps/android/app/src/main/java/app/localtugboat/Gallery.kt b/apps/android/app/src/main/java/app/localtugboat/Gallery.kt index 75094e3..dab5224 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Gallery.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Gallery.kt @@ -160,9 +160,9 @@ private fun Badge(icon: Int) { private fun ItemCell(item: ItemInfo, cell: UiLogic.CellUi, onClick: () -> Unit) { Box( Modifier.aspectRatio(1f).clip(RoundedCornerShape(8.dp)).clickable(role = Role.Button, onClick = onClick) - .described("${if (cell.video) "Video" else "Photo"}, ${cell.label}"), + .described("${UiLogic.kindWord(item.kind)}, ${if (cell.file) FileRules.displayName(item.name, item.ext) + ", " else ""}${cell.label}"), ) { - ThumbImage(item.thumbPath, null, Modifier.fillMaxSize()) + if (cell.file) FileFace(item, Modifier.fillMaxSize()) else ThumbImage(item.thumbPath, null, Modifier.fillMaxSize()) Row(Modifier.align(Alignment.TopStart).padding(4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) { if (cell.video) Badge(R.drawable.ic_videocam) if (cell.kept) Badge(R.drawable.ic_star_fill1) @@ -196,10 +196,16 @@ fun BinScreen(vm: SnapViewModel, ui: UiState) { Modifier.fillMaxWidth().defaultMinSize(minHeight = 72.dp).clickable(role = Role.Button) { vm.nav.go(Route.Viewer(null, true, item.id)) }.padding(horizontal = 16.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, ) { - ThumbImage(item.thumbPath, null, Modifier.size(56.dp).clip(RoundedCornerShape(8.dp))) + if (cell.file) { + Box(Modifier.size(56.dp).clip(RoundedCornerShape(8.dp)).background(MaterialTheme.colorScheme.surfaceVariant), contentAlignment = Alignment.Center) { + Ico(fileIcon(item.ext), null, tint = MaterialTheme.colorScheme.onSurfaceVariant, size = 28) + } + } else { + ThumbImage(item.thumbPath, null, Modifier.size(56.dp).clip(RoundedCornerShape(8.dp))) + } Spacer(Modifier.width(12.dp)) Column(Modifier.weight(1f)) { - Text(item.name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(if (cell.file) FileRules.displayName(item.name, item.ext) else item.name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) Text(cell.label, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } TextButton(onClick = { scope.launchRestore(vm, model, item.id) }, modifier = Modifier.defaultMinSize(minHeight = Touch)) { diff --git a/apps/android/app/src/main/java/app/localtugboat/Import.kt b/apps/android/app/src/main/java/app/localtugboat/Import.kt index cc2920c..4b4def4 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Import.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Import.kt @@ -124,11 +124,11 @@ object Capture { * SnapException / IOException. [src] is deleted only when the core took it: after a failure the file * stays, so a photo is never lost to a transient error (the screen says so, [recover] retries). */ - fun add(c: Context, src: File, name: String, folderId: String?, capturedAtMs: Long, geo: GeoFix?, imported: Boolean, video: Boolean): String { + fun add(c: Context, src: File, name: String, folderId: String?, capturedAtMs: Long, geo: GeoFix?, imported: Boolean, video: Boolean, thumbnail: Boolean = true): String { // One hand-off per file: [recover] must not take a file a slow hand-off is still working on. if (!inFlight.add(src.path)) throw IOException("${src.name} is already being added") try { - return addNow(c, src, name, folderId, capturedAtMs, geo, imported, video) + return addNow(c, src, name, folderId, capturedAtMs, geo, imported, video, thumbnail) } finally { inFlight.remove(src.path) } @@ -136,9 +136,10 @@ object Capture { private val inFlight: MutableSet = java.util.concurrent.ConcurrentHashMap.newKeySet() - private fun addNow(c: Context, src: File, name: String, folderId: String?, capturedAtMs: Long, geo: GeoFix?, imported: Boolean, video: Boolean): String { + private fun addNow(c: Context, src: File, name: String, folderId: String?, capturedAtMs: Long, geo: GeoFix?, imported: Boolean, video: Boolean, thumbnail: Boolean): String { + // Only photos and videos get a thumbnail: any other file is a tile with an icon. val thumbDir = File(c.cacheDir, "thumbs").apply { mkdirs() } - val thumb = Thumbs.make(c, src, video, File(thumbDir, "${UUID.randomUUID()}.jpg")) + val thumb = if (thumbnail) Thumbs.make(c, src, video, File(thumbDir, "${UUID.randomUUID()}.jpg")) else null try { val id = c.core.phone().addFile( NewFile( @@ -185,21 +186,43 @@ object Capture { /** What a Share > Tugboat run did, in the words the user reads. */ class ShareResult(val added: Int, val refused: List, val folderName: String) { - /** One line: "2 added to Inbox" or "1 added to Inbox. Not synced: x.zip (not a photo or video)". */ + /** One line that fits a toast: "2 added to Inbox" or "1 added to Inbox. NOT SYNCED: x.lnk (shortcut file)". The full reason is kept in the error list. */ fun summary(): String { val ok = if (added > 0) "$added added to $folderName" else "" - val bad = if (refused.isNotEmpty()) "Not synced: ${refused.joinToString("; ")}" else "" + val bad = if (refused.isNotEmpty()) "NOT SYNCED: ${refused.joinToString("; ")}" else "" return listOf(ok, bad).filter { it.isNotEmpty() }.joinToString(". ").ifEmpty { "Nothing to add" } } } -/** Share > Tugboat: streamed copy of each shared URI into app storage, type by magic bytes, then the core. */ +/** Thrown by [Streams.copyWithin] when the source is longer than the room left. */ +class OutOfRoom : IOException("phone storage low") + +object Streams { + /** + * Copy [input] to [output], at most [maxBytes]. A source that streams on past the room left (a provider that gave + * no size, or lied) stops at once with [OutOfRoom]: one shared file must never fill the phone. + * Returns the bytes copied. + */ + fun copyWithin(input: java.io.InputStream, output: java.io.OutputStream, maxBytes: Long): Long { + val buf = ByteArray(64 * 1024) + var total = 0L + while (true) { + val n = input.read(buf) + if (n < 0) return total + total += n + if (total > maxBytes) throw OutOfRoom() + output.write(buf, 0, n) + } + } +} + +/** Share > Tugboat: streamed copy of each shared URI into app storage, then the core. Any file type. */ object ShareImporter { /** Keep this much free after the copy: a full phone breaks more than Tugboat. */ private const val FREE_MARGIN = 64L * 1024 * 1024 - /** Blocking. One bad file never stops the others; each refusal is named in the result. */ - fun run(c: Context, uris: List): ShareResult { + /** Blocking. One bad file never stops the others; each refusal is named in the result. [intentType] = the share intent's MIME type. */ + fun run(c: Context, uris: List, intentType: String? = null): ShareResult { val target = Capture.importTarget(c) val importDir = File(c.cacheDir, "import").apply { mkdirs() } var added = 0 @@ -208,11 +231,15 @@ object ShareImporter { val label = displayName(c, uri) ?: "a file" try { if (!ShareNames.acceptableUri(uri.scheme, uri.authority, "${c.packageName}.fileprovider")) throw Refusal("not a shared file") - if (importOne(c, uri, label, importDir, target.folderId)) added++ + // Shortcut and folder-setting files never sync: say so before a single byte is copied. + if (ShareNames.refused(label)) throw Refusal(ShareNames.REFUSED_SHORT) + if (importOne(c, uri, label, intentType, importDir, target.folderId)) added++ } catch (e: Refusal) { + // The toast is gone in seconds: the refusal also goes to the error list, which stays until dismissed. + c.core.reportError("share $label: ${if (e.message == ShareNames.REFUSED_SHORT) ShareNames.REFUSED_WHY else e.message}") refused += "$label (${e.message})" } catch (e: Exception) { - // Core errors (NotMedia, Io, Invalid) carry a readable one-line message. + // Core errors (Refused, NotMedia, Io, Invalid) carry a readable one-line message. c.core.reportError("share $label: ${e.message}") refused += "$label (${e.message})" } @@ -222,13 +249,13 @@ object ShareImporter { private class Refusal(msg: String) : Exception(msg) - private fun importOne(c: Context, uri: Uri, label: String, dir: File, folderId: String): Boolean { + private fun importOne(c: Context, uri: Uri, label: String, intentType: String?, dir: File, folderId: String): Boolean { val resolver = c.contentResolver val declared = size(c, uri) val free = c.core.phone().freeSpaceBytes().toLong() if (declared != null && declared + FREE_MARGIN > free) throw Refusal("phone storage low") val tmp = File(dir, "${UUID.randomUUID()}.tmp") - val media: Media + var media: Media? = null try { val input = resolver.openInputStream(uri) ?: throw Refusal("cannot be opened") input.use { ins -> @@ -239,21 +266,26 @@ object ShareImporter { if (r < 0) break n += r } - media = MagicBytes.sniff(head, n) ?: throw Refusal("not a photo or video") + // A photo or video is known by its first bytes (and a name that does not say otherwise: an + // .m4a is audio); anything else is a plain file. + media = ShareNames.mediaFor(label, MagicBytes.sniff(head, n)) tmp.outputStream().use { out -> out.write(head, 0, n) - ins.copyTo(out) + Streams.copyWithin(ins, out, free - FREE_MARGIN - n) } } } catch (e: Exception) { tmp.delete() if (e is Refusal) throw e + if (e is OutOfRoom) throw Refusal(e.message ?: "phone storage low") throw IOException("could not be read: ${e.message}", e) } val fallback = "Shared_${System.currentTimeMillis()}" - val name = ShareNames.finalName(label, media, fallback) + val mime = ShareQuery.type(resolver, uri) ?: intentType + val name = ShareNames.finalName(label, media, if (media == null) FileRules.extFromMime(mime, PlatformMime.extOf) else null, fallback) try { - Capture.add(c, tmp, name, folderId, System.currentTimeMillis(), null, imported = true, video = media.video) + if (ShareNames.refused(name)) throw Refusal(ShareNames.REFUSED_SHORT) + Capture.add(c, tmp, name, folderId, System.currentTimeMillis(), null, imported = true, video = media?.video == true, thumbnail = media != null) } catch (e: Exception) { tmp.delete() // the sender still has the original; our temp copy is only clutter throw e diff --git a/apps/android/app/src/main/java/app/localtugboat/PairingText.kt b/apps/android/app/src/main/java/app/localtugboat/PairingText.kt index 88d5fdb..b6eb4b6 100644 --- a/apps/android/app/src/main/java/app/localtugboat/PairingText.kt +++ b/apps/android/app/src/main/java/app/localtugboat/PairingText.kt @@ -22,14 +22,38 @@ object PairingText { } } +/** + * The two naming rules the core owns, behind an interface so JVM tests can stand in for the native library. + * The app never keeps its own copy of the rules: [CoreNameRules] asks the core (the same code the PC runs). + */ +interface NameRules { + /** The extension core would give this name: lowercase, or "" for none. */ + fun extOf(name: String): String + /** True for names that never sync (shortcuts, desktop.ini, autorun.inf, ...). */ + fun isRefused(name: String): Boolean +} + +object CoreNameRules : NameRules { + override fun extOf(name: String) = uniffi.tugboat_ffi.namesExtOf(name) + override fun isRefused(name: String) = uniffi.tugboat_ffi.namesIsRefused(name) +} + /** Names for files that come from other apps (Share > Tugboat). */ object ShareNames { private const val MAX_STEM = 80 private val BAD = Regex("""[\\/:*?"<>|\p{Cntrl}]""") + /** Why a shared file is refused before any byte is copied. The core says the same on the PC. */ + const val REFUSED_WHY = "shortcut and folder-setting files never sync" + + /** The same, short enough for a toast. */ + const val REFUSED_SHORT = "shortcut file" + /** A stem the core will accept: no path separators, ':' or reserved characters, no "..", not empty. */ - fun safeStem(displayName: String?, fallback: String): String { - val base = displayName?.substringBeforeLast('.', displayName)?.trim().orEmpty() + fun safeStem(displayName: String?, fallback: String): String = + clean(displayName?.substringBeforeLast('.', displayName)?.trim().orEmpty(), fallback) + + private fun clean(base: String, fallback: String): String { val cleaned = BAD.replace(base, "_").replace("..", "_").trim(' ', '.').take(MAX_STEM).trim(' ', '.') return cleaned.ifEmpty { fallback } } @@ -39,9 +63,42 @@ object ShareNames { * private files (we run with our own rights), and our own provider is never a legitimate source. */ fun acceptableUri(scheme: String?, authority: String?, ownAuthority: String): Boolean = - scheme == "content" && authority != null && !authority.equals(ownAuthority, ignoreCase = true) + // ContentResolver drops a "@" prefix before it finds the provider, so "0@" IS ours. + scheme == "content" && authority != null && !authority.substringAfterLast('@').equals(ownAuthority, ignoreCase = true) - /** Final name: cleaned stem plus the extension of the SNIFFED type, so name and content always agree. */ - fun finalName(displayName: String?, media: Media, fallback: String): String = - "${safeStem(displayName, fallback)}.${media.ext}" + /** True when this name must never sync. The core's answer is final; this only refuses early, before a large copy. */ + fun refused(name: String?, rules: NameRules = CoreNameRules): Boolean = name != null && rules.isRefused(name) + + private val MEDIA_EXTS = setOf("jpg", "jpeg", "png", "gif", "webp", "heic", "heif", "mp4", "m4v", "mov", "3gp") + + /** + * The sniffed photo/video type to act on, or null for a plain file. The bytes alone do not make a photo or + * video: audio in an MP4/3GP container (.m4a, .3ga) looks like a video. The sniffed type counts only when the + * display name has no extension or already carries a photo/video one. + */ + fun mediaFor(displayName: String?, sniffed: Media?, rules: NameRules = CoreNameRules): Media? { + if (sniffed == null) return null + val shown = displayName?.trimEnd(' ', '.').orEmpty() + val ext = if (shown.isEmpty()) "" else rules.extOf(shown) + return if (ext.isEmpty() || ext in MEDIA_EXTS) sniffed else null + } + + /** + * Final name for a shared file. + * - A photo or video (known by its first bytes, [media], and not an audio file in a video container, see + * [mediaFor]): cleaned stem plus the SNIFFED extension, so name and content always agree. + * - Anything else: the cleaned stem plus the display name's own extension (as the core reads it), else the one + * the MIME type implies ([mimeExt]), else none ("Makefile" stays "Makefile"). + * The core re-checks every name; a photo extension on non-photo bytes is refused there. + */ + fun finalName(displayName: String?, media: Media?, mimeExt: String?, fallback: String, rules: NameRules = CoreNameRules): String { + val m = mediaFor(displayName, media, rules) + if (m != null) return "${safeStem(displayName, fallback)}.${m.ext}" + val shown = displayName?.trimEnd(' ', '.').orEmpty() + var ext = if (shown.isEmpty()) "" else rules.extOf(shown) + val base = if (ext.isNotEmpty() && shown.endsWith(".$ext", ignoreCase = true)) shown.dropLast(ext.length + 1) else { ext = ""; shown } + if (ext.isEmpty() && mimeExt != null && rules.extOf("x.$mimeExt") == mimeExt) ext = mimeExt + val stem = clean(base, fallback) + return if (ext.isEmpty()) stem else "$stem.$ext" + } } diff --git a/apps/android/app/src/main/java/app/localtugboat/ShareActivity.kt b/apps/android/app/src/main/java/app/localtugboat/ShareActivity.kt index 83db749..acf65d8 100644 --- a/apps/android/app/src/main/java/app/localtugboat/ShareActivity.kt +++ b/apps/android/app/src/main/java/app/localtugboat/ShareActivity.kt @@ -29,7 +29,7 @@ object ShareRuns { } /** - * Share > Tugboat (ACTION_SEND / ACTION_SEND_MULTIPLE for any image or video type). Stays open until the + * Share > Tugboat (ACTION_SEND / ACTION_SEND_MULTIPLE, any file type; a share with no stream, such as a link, saves nothing). Stays open until the * copy is done: the sender's temporary read grant lives only as long as this activity. * * The import runs on the process scope and ends the activity through [ShareRuns], not through `this`: if the @@ -51,16 +51,17 @@ class ShareActivity : ComponentActivity() { if (savedInstanceState == null) { val uris = sharedUris(intent) if (uris.isEmpty()) { - Toast.makeText(this, "Nothing to add", Toast.LENGTH_LONG).show() + Toast.makeText(this, "NOTHING TO SAVE - share a file", Toast.LENGTH_LONG).show() finish() return } val app = applicationContext + val type = intent.type ShareRuns.active.update { it + 1 } // Process scope, not the activity's: a rotation or a back press must not stop a half-copied video. app.core.scope.launch { val text = try { - ShareImporter.run(app, uris).summary() + ShareImporter.run(app, uris, type).summary() } catch (e: Exception) { app.core.reportError("share failed: ${e.message}") "Could not add: ${e.message}" diff --git a/apps/android/app/src/main/java/app/localtugboat/SnapService.kt b/apps/android/app/src/main/java/app/localtugboat/SnapService.kt index 7847484..29adbde 100644 --- a/apps/android/app/src/main/java/app/localtugboat/SnapService.kt +++ b/apps/android/app/src/main/java/app/localtugboat/SnapService.kt @@ -101,13 +101,22 @@ class SnapService : Service() { /** Set by [stop]: the next destroy is on purpose, so its quiet time is not a failure. */ @Volatile private var stopWanted = false - /** Returns an error text if the system refused to start the service, else null. */ - fun start(c: Context): String? = try { + /** + * Returns an error text if the system refused to start the service, else null. + * + * A refusal is always in the log. It becomes a banner only when no start has succeeded within + * [StartRefusal.GRACE_MS]: Android can refuse one start (a broadcast delivered after a force-stop, a worker with + * no foreground standing) while the next one, from the opened app, works. A banner for the first would stay on + * screen although the service is running (known bug, 0.1.0). + */ + fun start(c: Context, why: String = "?"): String? = try { c.applicationContext.startForegroundService(Intent(c.applicationContext, SnapService::class.java)) null } catch (e: Exception) { - val m = "service start refused: ${e.javaClass.simpleName}: ${e.message}" - c.core.reportError(m) + val m = "service start refused ($why): ${e.javaClass.simpleName}: ${e.message}" + KLog.log(c, m) + val core = c.core + StartRefusal.watch(core.scope, StartRefusal.GRACE_MS, { core.serviceRunning }, { core.reportError(it) }, m) m } @@ -119,3 +128,15 @@ class SnapService : Service() { } } } + +/** The rule for a refused service start: tell the user only if the service is still not running after a grace period. */ +object StartRefusal { + const val GRACE_MS = 10_000L + + /** After [graceMs], calls [report] with [text] unless [running] says a start has worked since. */ + fun watch(scope: kotlinx.coroutines.CoroutineScope, graceMs: Long, running: () -> Boolean, report: (String) -> Unit, text: String): Job = + scope.launch { + delay(graceMs) + if (!running()) report(text) + } +} diff --git a/apps/android/app/src/main/java/app/localtugboat/SnapViewModel.kt b/apps/android/app/src/main/java/app/localtugboat/SnapViewModel.kt index 27eef33..dabeebe 100644 --- a/apps/android/app/src/main/java/app/localtugboat/SnapViewModel.kt +++ b/apps/android/app/src/main/java/app/localtugboat/SnapViewModel.kt @@ -264,6 +264,13 @@ class SnapViewModel(app: Application) : AndroidViewModel(app) { _pairing.value = PairUi.Dialing viewModelScope.launch(Dispatchers.IO) { core.hold("pairing").join() // pairing needs the endpoint up + // The code's expiry (the PC's stamp, compared with this phone's clock) is read before dialing: a failure + // after it means "expired", whatever words the PC's newer window used to refuse the old secret. + val expiresAt = try { + inspectPairingPayload(payload).expiresAtMs + } catch (e: Exception) { + null + } try { val pc = core.phone().pairWith(payload) _pairing.value = PairUi.Done(pc.name) @@ -271,7 +278,7 @@ class SnapViewModel(app: Application) : AndroidViewModel(app) { ServiceGate.startIfWanted(ctx, "paired") refresh() } catch (e: Exception) { - val line = Texts.pairFailure(e, Perms.localNetworkAllowed(ctx)) + val line = Texts.pairFailure(e, Perms.localNetworkAllowed(ctx), codeExpired = expiresAt != null && System.currentTimeMillis() >= expiresAt) // The onboarding screen shows this failure; a banner after a later success would be stale, so log only. KLog.log(ctx, "pairing failed: $line") _pairing.value = PairUi.Failed(line) @@ -373,6 +380,16 @@ class SnapViewModel(app: Application) : AndroidViewModel(app) { } } + /** ACTION_VIEW intent for a held file (content URI, read grant), or null (with a message) when it cannot be opened. */ + suspend fun openIntent(item: ItemInfo): Intent? = withContext(Dispatchers.IO) { + try { + ItemFileProvider.openIntent(ctx, item) + } catch (e: Exception) { + fail("Open", e) + null + } + } + fun saveToGallery(item: ItemInfo) = act("Save to phone") { ItemExport.saveToGallery(ctx, item) _messages.tryEmit("Saved to phone gallery") diff --git a/apps/android/app/src/main/java/app/localtugboat/Texts.kt b/apps/android/app/src/main/java/app/localtugboat/Texts.kt index 9dabcc5..509ffb9 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Texts.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Texts.kt @@ -29,7 +29,6 @@ object Texts { /** Label under a thumbnail in the gallery. */ fun expiryLabel(state: ItemStateInfo, nowMs: Long, binDays: UInt): String = when (state) { is ItemStateInfo.Live -> "Expires in ${duration(state.expiresAtMs - nowMs)}" - ItemStateInfo.Waiting -> "Waiting for PC" ItemStateInfo.Kept -> "Kept" ItemStateInfo.FolderKeep -> "Kept (folder)" is ItemStateInfo.Deleted -> binLabel(state.binnedAtMs, nowMs, binDays) @@ -43,10 +42,10 @@ object Texts { return "In Bin, ${(leftMs + DAY - 1) / DAY}d left" } - /** Banner after a heartbeat gap: "Tugboat was stopped at 14:02." */ + /** Banner after a heartbeat gap: "STOPPED at 14:02 - Tugboat was not running". */ fun stoppedAt(fromMs: Long, zone: java.time.ZoneId): String { val hm = java.time.format.DateTimeFormatter.ofPattern("HH:mm", java.util.Locale.ROOT) - return "Tugboat was stopped at ${java.time.Instant.ofEpochMilli(fromMs).atZone(zone).format(hm)}." + return "STOPPED at ${java.time.Instant.ofEpochMilli(fromMs).atZone(zone).format(hm)} - Tugboat was not running" } /** The ongoing notification line: "Connected to NIGEL-PC, synced 10s ago" or "PC not found, 3 waiting". */ @@ -76,13 +75,31 @@ object Texts { } /** One line for a failed pairing. The core's own messages are already readable; only the network ones need context. */ - fun pairFailure(e: Exception, localNetworkAllowed: Boolean): String = when (e) { + fun pairFailure(e: Exception, localNetworkAllowed: Boolean, codeExpired: Boolean = false): String = when (e) { + // The PC opens a NEW pairing window when the old one runs out, so an old QR reaches it as a wrong secret or a closed + // window. When the code's own expiry time has passed by this phone's clock, that is what it means. + is SnapException.PairBadSecret, is SnapException.PairNotOpen -> + if (codeExpired) EXPIRED_QR else e.message ?: "WRONG PAIRING CODE - scan the QR again" + // The core already says "PAIRING CODE EXPIRED - show a new QR": show its words. + is SnapException.PairExpired -> e.message ?: EXPIRED_QR is SnapException.PairBadPayload -> "That is not a Tugboat code" is SnapException.NetTimeout, is SnapException.NetUnreachable -> if (localNetworkAllowed) "PC NOT FOUND - same Wi-Fi as the PC?" else "LOCAL NETWORK BLOCKED - allow it, then scan again" else -> e.message ?: e.javaClass.simpleName } + const val EXPIRED_QR = "PAIRING CODE EXPIRED - show a new QR" + + /** Red banner while the core holds downloads back because free space is under the storage guard. */ + fun storageLow(waitingOnPc: UInt): String = when (waitingOnPc) { + 0u -> "PHONE STORAGE LOW" + 1u -> "PHONE STORAGE LOW - 1 item waits on the PC" + else -> "PHONE STORAGE LOW - $waitingOnPc items wait on the PC" + } + + /** Bin note for an item that expired before the PC ever confirmed holding it. */ + const val NOT_ON_PC = "NOT ON PC" + private fun notFound(s: SyncStatus): String = if (s.waiting > 0u) "PC not found, ${s.waiting} waiting" else "PC not found" } diff --git a/apps/android/app/src/main/java/app/localtugboat/UiLogic.kt b/apps/android/app/src/main/java/app/localtugboat/UiLogic.kt index bb385d2..d2cd49a 100644 --- a/apps/android/app/src/main/java/app/localtugboat/UiLogic.kt +++ b/apps/android/app/src/main/java/app/localtugboat/UiLogic.kt @@ -144,7 +144,9 @@ object UiLogic { if (paired && perms != null && !perms.localNetwork) { out += BannerUi(BannerId.LOCAL_NETWORK, "LOCAL NETWORK BLOCKED - sync cannot work", "Allow", Level.BLOCKER) } - if (paired && ui.storageLow) out += BannerUi(BannerId.STORAGE, "PHONE STORAGE LOW - downloads from the PC wait", null, Level.BLOCKER) + // The core enforces the guard and says when it holds downloads back: the banner follows the core, not the free-bytes guess. + val st = ui.status + if (paired && st != null && st.storageLow) out += BannerUi(BannerId.STORAGE, Texts.storageLow(st.downloading), null, Level.BLOCKER) ui.stoppedGapFromMs?.let { out += BannerUi(BannerId.STOPPED, Texts.stoppedAt(it, zone), "Fix", Level.WARNING) } if (paired && perms != null && !perms.notifications) { out += BannerUi(BannerId.NOTIFICATIONS, "Notifications off: sync state shows only in Tugboat", "Allow", Level.WARNING) @@ -189,6 +191,13 @@ object UiLogic { return if (r == r.toInt().toFloat()) "${r.toInt()}x" else "${r}x" } + /** + * Screen orientation request while the camera screen runs: locked at the current orientation during a recording + * (a rotation would recreate the activity and end the video), free otherwise. + */ + fun recordingOrientation(recording: Boolean): Int = + if (recording) android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LOCKED else android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED + /** Recording clock: "0:07", "12:30", "1:02:03". */ fun clock(ms: Long): String { val s = (ms / 1000).coerceAtLeast(0) @@ -261,15 +270,26 @@ object UiLogic { /** Furthest the zoomed photo may be dragged from centre on one axis: its edge stops at the screen edge. */ fun panLimit(scale: Float, extent: Float) = if (scale <= 1f) 0f else extent * (scale - 1f) / 2f - class CellUi(val label: String, val kept: Boolean, val video: Boolean, val waiting: Boolean) + class CellUi(val label: String, val kept: Boolean, val video: Boolean, val file: Boolean) - /** Label and badges under one thumbnail. */ + /** Label and badges under one thumbnail or file tile. A Bin item that never reached the PC says so. */ fun cell(item: ItemInfo, nowMs: Long, binDays: UInt, bin: Boolean): CellUi { - val label = fileNote(item.local, bin) ?: Texts.expiryLabel(item.state, nowMs, binDays) + val base = fileNote(item.local, bin) ?: Texts.expiryLabel(item.state, nowMs, binDays) + val label = if (bin && item.neverReachedPeer) "$base - ${Texts.NOT_ON_PC}" else base val kept = item.pinned || item.state is uniffi.tugboat_ffi.ItemStateInfo.Kept || item.state is uniffi.tugboat_ffi.ItemStateInfo.FolderKeep - return CellUi(label, kept, item.kind == MediaKind.VIDEO, item.state is uniffi.tugboat_ffi.ItemStateInfo.Waiting) + return CellUi(label, kept, item.kind == MediaKind.VIDEO, item.kind == MediaKind.FILE) } + /** Spoken name of a tile or page: "Photo", "Video" or "File". */ + fun kindWord(k: MediaKind): String = when (k) { + MediaKind.IMAGE -> "Photo" + MediaKind.VIDEO -> "Video" + MediaKind.FILE -> "File" + } + + /** Share and Open need the file on this phone AND outside the Bin (the provider serves items/ only). */ + fun canOpen(item: ItemInfo, bin: Boolean) = !bin && fileHeld(item) + /** "17 Nov, 10:30" in the phone's own zone and language. */ fun capturedAt(ms: Long, zone: java.time.ZoneId, locale: java.util.Locale = java.util.Locale.getDefault()): String = java.time.format.DateTimeFormatter.ofPattern("d MMM, HH:mm", locale).format(java.time.Instant.ofEpochMilli(ms).atZone(zone)) diff --git a/apps/android/app/src/main/java/app/localtugboat/Viewer.kt b/apps/android/app/src/main/java/app/localtugboat/Viewer.kt index bc0f7cd..ed06078 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Viewer.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Viewer.kt @@ -112,6 +112,19 @@ fun ViewerScreen(vm: SnapViewModel, ui: UiState, route: Route.Viewer) { } val item = rows.getOrNull(pager.currentPage) ?: return + fun openFile(i: ItemInfo) { + scope.launch { + val intent = vm.openIntent(i) ?: return@launch + try { + ctx.startActivity(intent) + } catch (e: android.content.ActivityNotFoundException) { + vm.say(FileRules.noAppText(i.ext)) + } catch (e: Exception) { + vm.reportFailure("Open", e) + } + } + } + fun after(job: kotlinx.coroutines.Job) { scope.launch { job.join() @@ -129,13 +142,13 @@ fun ViewerScreen(vm: SnapViewModel, ui: UiState, route: Route.Viewer) { } HorizontalPager(pager, Modifier.weight(1f).fillMaxWidth(), userScrollEnabled = !zoomed, key = { model.rows.getOrNull(it)?.id ?: it }) { page -> val row = model.rows.getOrNull(page) - if (row != null) ViewerPage(row, active = page == pager.currentPage, bin = route.bin) { z -> if (page == pager.currentPage) zoomed = z } + if (row != null) ViewerPage(row, active = page == pager.currentPage, bin = route.bin, onOpen = { openFile(row) }) { z -> if (page == pager.currentPage) zoomed = z } } Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 4.dp)) { val cell = UiLogic.cell(item, nowMs, binDays, route.bin) val folder = folders.firstOrNull { it.id == item.folderId }?.name Text( - listOfNotNull(UiLogic.capturedAt(item.capturedAtMs, ZoneId.systemDefault()), folder, UiLogic.bytes(item.size.toLong()), cell.label).joinToString(" - "), + listOfNotNull(UiLogic.capturedAt(item.capturedAtMs, ZoneId.systemDefault()), folder, if (item.kind == MediaKind.FILE) null else FileRules.sizeText(item.size.toLong()), cell.label).joinToString(" - "), color = Color.White, style = MaterialTheme.typography.bodySmall, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp), ) val held = UiLogic.fileHeld(item) @@ -147,7 +160,8 @@ fun ViewerScreen(vm: SnapViewModel, ui: UiState, route: Route.Viewer) { ViewerAction(if (cell.kept) R.drawable.ic_star_fill1 else R.drawable.ic_star, if (cell.kept) "Kept" else "Keep", !folderKeep) { after(vm.keep(item.id, !item.pinned)) } ViewerAction(R.drawable.ic_drive_file_move, "Move", true) { moving = true } ViewerAction(R.drawable.ic_share, "Share", held) { scope.launch { vm.shareIntent(item)?.let { i -> ctx.startActivity(i) } } } - ViewerAction(R.drawable.ic_download, "Save", held) { vm.saveToGallery(item) } + // Only photos and videos go to the phone gallery. A file has no Save: its one Open is the big button on its page (its size is there too). + if (item.kind != MediaKind.FILE) ViewerAction(R.drawable.ic_download, "Save", held) { vm.saveToGallery(item) } ViewerAction(R.drawable.ic_delete, "Delete", true) { after(vm.delete(item.id)) } // Shell offers Undo once it succeeded } } @@ -182,16 +196,34 @@ private fun RowScope.ViewerAction(icon: Int, label: String, enabled: Boolean, on } @Composable -private fun ViewerPage(item: ItemInfo, active: Boolean, bin: Boolean, onZoomed: (Boolean) -> Unit) { +private fun ViewerPage(item: ItemInfo, active: Boolean, bin: Boolean, onOpen: () -> Unit, onZoomed: (Boolean) -> Unit) { val note = UiLogic.fileNote(item.local, bin) val path = item.path when { + item.kind == MediaKind.FILE -> FilePage(item, note ?: if (path == null) "FILE MISSING on this phone" else null, bin, onOpen) note != null || path == null -> NoFile(item, note ?: "FILE MISSING on this phone") item.kind == MediaKind.VIDEO -> if (active) VideoPlayer(path) else ThumbImage(item.thumbPath, "Video", Modifier.fillMaxSize(), ContentScale.Fit) else -> PhotoPage(path, item.name, onZoomed) } } +/** A file that is not a photo or video: type icon, real name, "PDF, 1.2 MB" and Open. In the Bin: Restore first. */ +@Composable +private fun FilePage(item: ItemInfo, note: String?, bin: Boolean, onOpen: () -> Unit) { + Column(Modifier.fillMaxSize().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { + Ico(fileIcon(item.ext), null, tint = Color.White, size = 72) + Spacer(Modifier.height(12.dp)) + Text(FileRules.displayName(item.name, item.ext), color = Color.White, style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center, maxLines = 4, overflow = TextOverflow.Ellipsis) + Text(FileRules.meta(item.ext, item.size.toLong()), color = Color.White, style = MaterialTheme.typography.bodyMedium, textAlign = TextAlign.Center) + Spacer(Modifier.height(20.dp)) + when { + note != null -> Text(note, color = Color.White, style = MaterialTheme.typography.titleMedium, textAlign = TextAlign.Center) + bin -> Text("Restore it to open it", color = Color.White, style = MaterialTheme.typography.titleMedium, textAlign = TextAlign.Center) + else -> ActionButton(onClick = onOpen, modifier = Modifier.defaultMinSize(minHeight = 56.dp)) { Text("Open") } + } + } +} + /** The file is not here: the thumbnail, dimmed, with the reason in words. */ @Composable private fun NoFile(item: ItemInfo, note: String) { @@ -259,12 +291,30 @@ private fun ZoomableImage(bitmap: ImageBitmap, desc: String, onZoomed: (Boolean) } } +/** + * Decoder fallback on: if a phone's first-choice decoder cannot be set up, the next one is tried (often the software decoder). + * Debug builds also skip the Android emulator's own "goldfish" decoders: on the emulator image used for QA they fail for any + * third-party app (SELinux denies the codec service the app's shared-memory queue, see notes/plans/0.2.0-android-notes.md), + * so without this no recorded video could be played there. Release builds never touch the decoder list. + */ +@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +private fun renderersFactory(ctx: android.content.Context): androidx.media3.exoplayer.DefaultRenderersFactory { + val f = androidx.media3.exoplayer.DefaultRenderersFactory(ctx).setEnableDecoderFallback(true) + if (BuildConfig.DEBUG) { + f.setMediaCodecSelector { mime, secure, tunneling -> + androidx.media3.exoplayer.mediacodec.MediaCodecSelector.DEFAULT.getDecoderInfos(mime, secure, tunneling).filterNot { it.name.contains("goldfish") } + } + } + return f +} + /** Media3 player for the current page only: created when the page settles, released when it leaves. */ +@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) @Composable private fun VideoPlayer(path: String) { val ctx = LocalContext.current val player = remember(path) { - ExoPlayer.Builder(ctx).build().apply { + ExoPlayer.Builder(ctx, renderersFactory(ctx)).build().apply { setMediaItem(MediaItem.fromUri(Uri.fromFile(File(path)))) prepare() } diff --git a/apps/android/app/src/main/res/drawable/ic_file.xml b/apps/android/app/src/main/res/drawable/ic_file.xml new file mode 100644 index 0000000..4208981 --- /dev/null +++ b/apps/android/app/src/main/res/drawable/ic_file.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/android/app/src/main/res/drawable/ic_file_archive.xml b/apps/android/app/src/main/res/drawable/ic_file_archive.xml new file mode 100644 index 0000000..4349dd0 --- /dev/null +++ b/apps/android/app/src/main/res/drawable/ic_file_archive.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/android/app/src/main/res/drawable/ic_file_audio.xml b/apps/android/app/src/main/res/drawable/ic_file_audio.xml new file mode 100644 index 0000000..3401690 --- /dev/null +++ b/apps/android/app/src/main/res/drawable/ic_file_audio.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/android/app/src/main/res/drawable/ic_file_doc.xml b/apps/android/app/src/main/res/drawable/ic_file_doc.xml new file mode 100644 index 0000000..5c2b1d3 --- /dev/null +++ b/apps/android/app/src/main/res/drawable/ic_file_doc.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/android/app/src/test/java/app/localtugboat/Adversarial020SecurityTest.kt b/apps/android/app/src/test/java/app/localtugboat/Adversarial020SecurityTest.kt new file mode 100644 index 0000000..930be81 --- /dev/null +++ b/apps/android/app/src/test/java/app/localtugboat/Adversarial020SecurityTest.kt @@ -0,0 +1,68 @@ +package app.localtugboat + +import java.io.File +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Adversarial security tests for 0.2.0 on the phone (verifier stage, security lens): the any-type share target + * against hostile content URIs, the FileProvider's reach, and the names other apps are shown. + * A FAILING test here is a finding, not a broken test. + */ +class Adversarial020SecurityTest { + private val main: File = listOf(File("src/main"), File("app/src/main")).first { it.isDirectory } + private val own = "app.snapferry.fileprovider" + + /** + * ContentResolver resolves "content://0@app.snapferry.fileprovider/items/x" to OUR provider for user 0 + * (ContentProvider.getAuthorityWithoutUserId strips the "@" prefix), and our own process may read it. + * A hostile app that shares such a URI makes Tugboat copy its own held files or its exported log as a new + * item: the "our own provider is never a source" rule must hold for the user-prefixed spelling too. + */ + @Test + fun adversarial_020_security_own_provider_with_a_user_id_prefix_is_refused() { + for (authority in listOf("0@$own", "10@$own", "0@APP.SNAPFERRY.FILEPROVIDER")) { + assertFalse("content://$authority/... reaches our own FileProvider", ShareNames.acceptableUri("content", authority, own)) + } + } + + /** Scheme spellings ContentResolver does not treat as content:// must not pass either. */ + @Test + fun adversarial_020_security_only_the_exact_content_scheme_passes() { + for (scheme in listOf("file", "FILE", "android.resource", "CONTENT", "", "http", "https")) { + assertFalse("scheme $scheme accepted", ShareNames.acceptableUri(scheme, "media", own)) + } + assertTrue(ShareNames.acceptableUri("content", "media", own)) + } + + /** + * The name another app sees (DISPLAY_NAME of an opened or shared file) comes from the item's record name. A + * bidi override makes "invoicefdp.exe" read "invoiceexe.pdf" in the receiving app. providerName strips + * \p{Cntrl} only (U+202E is a format character, Cf). + */ + @Test + fun adversarial_020_security_the_name_shown_to_other_apps_has_no_bidi_override() { + for (raw in listOf("invoice‮fdp.exe", "a⁦b.apk", "x‏.pdf")) { + val shown = FileRules.providerName(raw) ?: continue + assertFalse("other apps are shown ${shown.map { "%04X".format(it.code) }}", shown.any { it in '‪'..'‮' || it in '⁦'..'⁩' || it == '‎' || it == '‏' || it == '؜' }) + } + } + + /** The FileProvider stays private, read-only by grant, and limited to the export folder and held items. */ + @Test + fun adversarial_020_security_file_provider_is_not_exported_and_reaches_only_items_and_the_export() { + val manifest = File(main, "AndroidManifest.xml").readText() + val provider = Regex("""]*ItemFileProvider[\s\S]*?""").find(manifest)?.value ?: error("no provider") + assertTrue(provider.contains("""android:exported="false"""")) + assertTrue(provider.contains("""android:grantUriPermissions="true"""")) + val paths = File(main, "res/xml/file_paths.xml").readText() + val entries = Regex("""<([a-z-]+-path)\s+name="([^"]+)"\s+path="([^"]*)"""").findAll(paths).map { it.groupValues.drop(1) }.toList() + assertTrue("paths: $entries", entries == listOf(listOf("cache-path", "export", "export/"), listOf("files-path", "items", "storage/items/"))) + // No write grant, no persistable grant anywhere in the app. + val kt = File(main, "java/app/localtugboat").walk().filter { it.extension == "kt" }.joinToString("\n") { it.readText() } + assertFalse(kt.contains("FLAG_GRANT_WRITE_URI_PERMISSION")) + assertFalse(kt.contains("FLAG_GRANT_PERSISTABLE_URI_PERMISSION")) + assertFalse(kt.contains("FLAG_GRANT_PREFIX_URI_PERMISSION")) + } +} diff --git a/apps/android/app/src/test/java/app/localtugboat/Adversarial020Test.kt b/apps/android/app/src/test/java/app/localtugboat/Adversarial020Test.kt new file mode 100644 index 0000000..9b727fd --- /dev/null +++ b/apps/android/app/src/test/java/app/localtugboat/Adversarial020Test.kt @@ -0,0 +1,54 @@ +package app.localtugboat + +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * Adversarial tests, verifier stage 020 (correctness and data-safety lens). A failing test here is a finding. + * + * R1: "every other file shows as a file tile" and keeps its own type. The share importer sniffs EVERY shared file + * and, when the first bytes look like an ISO-BMFF video, renames it to the video extension. Audio in an MP4/3GP + * container (Android voice recorder .m4a / .3ga, AAC .m4a written with the common "mp42" / "isom" brands) is then + * saved and synced under a different name and type than the user shared. + */ +class Adversarial020Test { + private object Rules : NameRules { + private val ok = Regex("^[a-z0-9_-]{1,16}$") + override fun extOf(name: String): String { + val n = name.trimEnd(' ', '.') + val i = n.lastIndexOf('.') + if (i <= 0) return "" + val e = n.substring(i + 1).lowercase() + return if (ok.matches(e)) e else "" + } + override fun isRefused(name: String) = false + } + + private fun bmff(brand: String): ByteArray { + val b = ByteArray(32) + b[3] = 0x20 + "ftyp".forEachIndexed { i, c -> b[4 + i] = c.code.toByte() } + brand.forEachIndexed { i, c -> b[8 + i] = c.code.toByte() } + return b + } + + private fun shared(display: String, head: ByteArray): String = + ShareNames.finalName(display, MagicBytes.sniff(head), null, "Shared_1", Rules) + + @Test + fun adv020_an_m4a_audio_file_keeps_its_name() { + assertEquals("voice.m4a", shared("voice.m4a", bmff("mp42"))) + assertEquals("song.m4a", shared("song.m4a", bmff("isom"))) + } + + @Test + fun adv020_a_3ga_voice_recording_keeps_its_name() { + assertEquals("memo.3ga", shared("memo.3ga", bmff("3gp4"))) + } + + /** Control: a real video keeps working (sniffed extension). */ + @Test + fun adv020_control_a_video_with_a_wrong_extension_gets_the_sniffed_one() { + assertEquals("clip.mp4", shared("clip.mp4", bmff("isom"))) + } +} diff --git a/apps/android/app/src/test/java/app/localtugboat/AnyFileTest.kt b/apps/android/app/src/test/java/app/localtugboat/AnyFileTest.kt new file mode 100644 index 0000000..c04a067 --- /dev/null +++ b/apps/android/app/src/test/java/app/localtugboat/AnyFileTest.kt @@ -0,0 +1,313 @@ +package app.localtugboat + +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.InputStream +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import uniffi.tugboat_ffi.MediaKind + +/** + * 0.2.0 "any file type" on the phone: share names, refusals, file tiles' labels, MIME, the real name other apps see. + * The core's own name rules live in Rust; [FakeRules] stands in for the native library (a JVM test cannot load an + * Android .so), so the emulator run (notes/plans/0.2.0-android-notes.md) is what proves the real rules end to end. + */ +class AnyFileTest { + private val main: File = listOf(File("src/main"), File("app/src/main")).first { it.isDirectory } + private val kotlin = File(main, "java/app/localtugboat") + + /** Same rule as core `names::ext_of` / `is_refused_name`, only as far as these tests need. */ + internal object FakeRules : NameRules { + private val ok = Regex("^[a-z0-9_-]{1,16}$") + private val refusedSuffix = listOf(".lnk", ".url", ".scf", ".library-ms", ".searchconnector-ms") + override fun extOf(name: String): String { + val n = name.trimEnd(' ', '.') + val i = n.lastIndexOf('.') + if (i <= 0) return "" + val e = n.substring(i + 1).lowercase() + return if (ok.matches(e)) e else "" + } + override fun isRefused(name: String): Boolean { + val n = name.trimEnd(' ', '.').lowercase() + return refusedSuffix.any { n.endsWith(it) } || n == "desktop.ini" || n == "autorun.inf" + } + } + + private fun name(display: String?, media: Media? = null, mimeExt: String? = null) = ShareNames.finalName(display, media, mimeExt, "Shared_1", FakeRules) + + // ---- share names ---- + + @Test fun a_shared_file_keeps_its_own_extension_lowercased() { + assertEquals("report.pdf", name("report.PDF")) + assertEquals("archive.tar.gz", name("archive.tar.gz")) + assertEquals("notes.docx", name("notes.docx")) + } + + @Test fun a_file_with_no_extension_stays_without_one() { + assertEquals("Makefile", name("Makefile")) + assertEquals("gitignore", name(".gitignore")) // a leading dot is not an extension; the core refuses dot-names, so it is cleaned + assertEquals("a.b c", name("a.b c")) // "b c" is not an extension the core would read + } + + @Test fun trailing_dots_and_spaces_do_not_hide_the_extension() { + assertEquals("a.pdf", name("a.pdf. ")) + } + + @Test fun the_mime_type_gives_an_extension_only_when_the_name_has_none() { + assertEquals("data.csv", name("data", mimeExt = "csv")) + assertEquals("report.pdf", name("report.pdf", mimeExt = "doc")) + assertEquals("data", name("data", mimeExt = "a b")) // an extension the core would not read is never added + assertEquals("Shared_1.pdf", name(null, mimeExt = "pdf")) + assertEquals("Shared_1", name(null)) + } + + @Test fun unsafe_characters_never_reach_the_core() { + assertEquals("a_b.pdf", name("a:b.pdf")) + assertEquals("a_b.pdf", name("a/b.pdf")) + assertEquals("a_b.pdf", name("a\\b.pdf")) + assertEquals("a_b.pdf", name("a..b.pdf")) + } + + @Test fun a_photo_or_video_takes_the_extension_of_its_bytes() { + assertEquals("IMG.jpg", name("IMG", Media.JPEG)) + assertEquals("IMG.png", name("IMG.jpg", Media.PNG)) + assertEquals("photo.heic", name("photo.jpg", Media.HEIF)) + assertEquals("clip.mp4", name("clip", Media.MP4)) + assertEquals("Shared_1.png", name(null, Media.PNG)) + } + + @Test fun a_name_that_says_document_or_audio_keeps_its_type_whatever_the_bytes_look_like() { + // Audio in an MP4 container sniffs as a video; the user shared a voice memo, not a video. + assertEquals("voice.m4a", name("voice.m4a", Media.MP4)) + assertEquals("memo.3ga", name("memo.3ga", Media.THREE_GP)) + assertEquals("scan.pdf", name("scan.pdf", Media.JPEG)) + assertEquals(null, ShareNames.mediaFor("voice.m4a", Media.MP4, FakeRules)) + assertEquals(Media.MP4, ShareNames.mediaFor("clip", Media.MP4, FakeRules)) + assertEquals(Media.MP4, ShareNames.mediaFor("clip.MOV", Media.MP4, FakeRules)) + assertEquals(null, ShareNames.mediaFor("clip", null, FakeRules)) + } + + @Test fun a_photo_extension_on_other_bytes_is_left_for_the_core_to_refuse() { + // No sniffed media: the name keeps jpg, the core's magic-byte check refuses it (a program cannot pose as a photo). + assertEquals("virus.jpg", name("virus.jpg")) + } + + @Test fun shortcut_and_folder_setting_names_are_refused_before_any_copy() { + for (n in listOf("x.lnk", "X.LNK", "x.lnk. ", "link.url", "a.scf", "y.library-ms", "z.searchConnector-ms", "desktop.ini", "DESKTOP.INI", "autorun.inf")) { + assertTrue(n, ShareNames.refused(n, FakeRules)) + } + for (n in listOf("lnk.txt", "desktop.ini.txt", "mylnk", "report.pdf", "Makefile")) { + assertFalse(n, ShareNames.refused(n, FakeRules)) + } + assertFalse(ShareNames.refused(null, FakeRules)) + // The final name is checked again: a refused name cannot slip through by cleaning. + assertTrue(ShareNames.refused(name("x.lnk"), FakeRules)) + } + + @Test fun the_refusal_line_matches_what_the_pc_says() { + assertEquals("shortcut and folder-setting files never sync", ShareNames.REFUSED_WHY) + val r = ShareResult(1, listOf("x.lnk (${ShareNames.REFUSED_WHY})"), "Inbox") + assertEquals("1 added to Inbox. NOT SYNCED: x.lnk (shortcut and folder-setting files never sync)", r.summary()) + assertEquals("NOT SYNCED: x.lnk (shortcut and folder-setting files never sync)", ShareResult(0, listOf("x.lnk (${ShareNames.REFUSED_WHY})"), "Inbox").summary()) + } + + // ---- which sources are read (dirty stream) ---- + + @Test fun only_content_uris_from_other_apps_are_read() { + val own = "app.snapferry.fileprovider" + assertFalse(ShareNames.acceptableUri("file", null, own)) // file:///data/data/app.snapferry/files/tugboat.db + assertFalse(ShareNames.acceptableUri("file", "", own)) + assertFalse(ShareNames.acceptableUri("content", own, own)) // our own provider + assertFalse(ShareNames.acceptableUri("content", "APP.SNAPFERRY.FILEPROVIDER", own)) + assertFalse(ShareNames.acceptableUri("content", null, own)) + assertFalse(ShareNames.acceptableUri(null, "media", own)) + assertTrue(ShareNames.acceptableUri("content", "media", own)) // content://media/external/file/12 + } + + @Test fun the_share_target_takes_any_type_and_the_provider_is_the_naming_one() { + val m = File(main, "AndroidManifest.xml").readText() + val share = m.substring(m.indexOf("android:name=\".ShareActivity\""), m.indexOf(" String? = { mapOf("pdf" to "application/pdf", "docx" to "application/vnd.openxmlformats-officedocument.wordprocessingml.document")[it] } + assertEquals("application/pdf", FileRules.mime("pdf", MediaKind.FILE, platform)) + assertEquals("application/octet-stream", FileRules.mime("", MediaKind.FILE, platform)) // no extension + assertEquals("application/octet-stream", FileRules.mime("xyz", MediaKind.FILE, platform)) // the platform knows nothing + assertEquals("image/jpeg", FileRules.mime("JPG", MediaKind.IMAGE, platform)) + assertEquals("video/mp4", FileRules.mime("mp4", MediaKind.VIDEO, platform)) + assertEquals("video/*", FileRules.mime("weird", MediaKind.VIDEO, platform)) + assertEquals("image/*", FileRules.mime("weird", MediaKind.IMAGE, platform)) + } + + @Test fun mime_gives_an_extension_only_for_a_real_type() { + val platform: (String) -> String? = { mapOf("application/pdf" to "pdf", "text/csv" to "CSV")[it] } + assertEquals("pdf", FileRules.extFromMime("application/pdf", platform)) + assertEquals("pdf", FileRules.extFromMime("application/pdf; charset=binary", platform)) + assertEquals("csv", FileRules.extFromMime("TEXT/CSV", platform)) + assertNull(FileRules.extFromMime("*/*", platform)) + assertNull(FileRules.extFromMime("image/*", platform)) + assertNull(FileRules.extFromMime("application/octet-stream", platform)) + assertNull(FileRules.extFromMime(null, platform)) + assertNull(FileRules.extFromMime("", platform)) + assertNull(FileRules.extFromMime("application/x-unknown", platform)) + } + + @Test fun the_no_app_line_names_the_type() { + assertEquals("NO APP OPENS .XYZ FILES - use Share", FileRules.noAppText("xyz")) + assertEquals("NO APP OPENS THIS FILE - use Share", FileRules.noAppText("")) + } + + // ---- a refused service start ---- + + @Test fun a_refused_service_start_is_reported_only_when_no_start_worked_in_time() { + val said = mutableListOf() + var running = false + runBlocking { + StartRefusal.watch(CoroutineScope(Dispatchers.Default), 60, { running }, { said += it }, "refused").join() + } + assertEquals(listOf("refused"), said) + + said.clear() + running = false + val job = StartRefusal.watch(CoroutineScope(Dispatchers.Default), 200, { running }, { said += it }, "refused") + running = true // a later start (the opened app) worked within the grace time + runBlocking { job.join() } + assertTrue("a banner for a start that was followed by a good one: $said", said.isEmpty()) + } + + @Test fun the_service_start_goes_through_the_grace_rule() { + val svc = File(kotlin, "SnapService.kt").readText() + assertTrue(svc.contains("StartRefusal.watch(")) + assertFalse("a refused start must not raise a banner at once", svc.contains("c.core.reportError(m)")) + } + + // ---- recording ---- + + @Test fun orientation_is_locked_only_while_recording() { + assertEquals(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LOCKED, UiLogic.recordingOrientation(true)) + assertEquals(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED, UiLogic.recordingOrientation(false)) + val cam = File(kotlin, "CameraScreen.kt").readText() + assertTrue(cam.contains("UiLogic.recordingOrientation(true)")) + assertTrue("the lock must be released on dispose", cam.contains("onDispose { if (isRecording) activity?.requestedOrientation = UiLogic.recordingOrientation(false) }")) + } +} diff --git a/apps/android/app/src/test/java/app/localtugboat/PairingTextTest.kt b/apps/android/app/src/test/java/app/localtugboat/PairingTextTest.kt index 114e456..1e231e8 100644 --- a/apps/android/app/src/test/java/app/localtugboat/PairingTextTest.kt +++ b/apps/android/app/src/test/java/app/localtugboat/PairingTextTest.kt @@ -54,9 +54,9 @@ class PairingTextTest { } @Test fun share_extension_comes_from_the_content_not_the_name() { - assertEquals("photo.heic", ShareNames.finalName("photo.jpg", Media.HEIF, "fb")) - assertEquals("photo.mp4", ShareNames.finalName("photo", Media.MP4, "fb")) - assertEquals("fb.png", ShareNames.finalName(null, Media.PNG, "fb")) + assertEquals("photo.heic", ShareNames.finalName("photo.jpg", Media.HEIF, null, "fb", AnyFileTest.FakeRules)) + assertEquals("photo.mp4", ShareNames.finalName("photo", Media.MP4, null, "fb", AnyFileTest.FakeRules)) + assertEquals("fb.png", ShareNames.finalName(null, Media.PNG, null, "fb", AnyFileTest.FakeRules)) } @Test fun share_accepts_only_foreign_content_uris() { @@ -72,8 +72,8 @@ class PairingTextTest { @Test fun share_summary() { assertEquals("2 added to Inbox", ShareResult(2, emptyList(), "Inbox").summary()) - assertEquals("1 added to Work. Not synced: a.zip (not a photo or video)", ShareResult(1, listOf("a.zip (not a photo or video)"), "Work").summary()) - assertEquals("Not synced: a.zip (not a photo or video)", ShareResult(0, listOf("a.zip (not a photo or video)"), "Inbox").summary()) + assertEquals("1 added to Work. NOT SYNCED: a.zip (not a photo or video)", ShareResult(1, listOf("a.zip (not a photo or video)"), "Work").summary()) + assertEquals("NOT SYNCED: a.zip (not a photo or video)", ShareResult(0, listOf("a.zip (not a photo or video)"), "Inbox").summary()) assertEquals("Nothing to add", ShareResult(0, emptyList(), "Inbox").summary()) } } diff --git a/apps/android/app/src/test/java/app/localtugboat/TextsTest.kt b/apps/android/app/src/test/java/app/localtugboat/TextsTest.kt index 679a476..357fa33 100644 --- a/apps/android/app/src/test/java/app/localtugboat/TextsTest.kt +++ b/apps/android/app/src/test/java/app/localtugboat/TextsTest.kt @@ -14,7 +14,7 @@ class TextsTest { private val day = 24 * hour private fun status(state: SyncState, peer: String? = "NIGEL-PC", last: Long? = null, waiting: UInt = 0u, message: String? = null) = - SyncStatus(state, peer, last, waiting, 0u, message) + SyncStatus(state, peer, last, waiting, 0u, false, message) @Test fun duration_rounds_down_and_switches_unit() { assertEquals("<1m", Texts.duration(59_999)) @@ -37,7 +37,6 @@ class TextsTest { @Test fun expiry_labels() { val now = 1_000_000_000L assertEquals("Expires in 5h", Texts.expiryLabel(ItemStateInfo.Live(now + 5 * hour + 10 * min), now, 7u)) - assertEquals("Waiting for PC", Texts.expiryLabel(ItemStateInfo.Waiting, now, 7u)) assertEquals("Kept", Texts.expiryLabel(ItemStateInfo.Kept, now, 7u)) assertEquals("Kept (folder)", Texts.expiryLabel(ItemStateInfo.FolderKeep, now, 7u)) } @@ -71,8 +70,8 @@ class TextsTest { @Test fun stopped_banner_uses_local_time() { // 2026-11-17 14:02:30 UTC shown in UTC and in Sydney (UTC+11 in November). val ms = java.time.ZonedDateTime.of(2026, 11, 17, 14, 2, 30, 0, ZoneId.of("UTC")).toInstant().toEpochMilli() - assertEquals("Tugboat was stopped at 14:02.", Texts.stoppedAt(ms, ZoneId.of("UTC"))) - assertEquals("Tugboat was stopped at 01:02.", Texts.stoppedAt(ms, ZoneId.of("Australia/Sydney"))) + assertEquals("STOPPED at 14:02 - Tugboat was not running", Texts.stoppedAt(ms, ZoneId.of("UTC"))) + assertEquals("STOPPED at 01:02 - Tugboat was not running", Texts.stoppedAt(ms, ZoneId.of("Australia/Sydney"))) } @Test fun pair_failures_name_the_cause() { @@ -81,4 +80,35 @@ class TextsTest { assertEquals("LOCAL NETWORK BLOCKED - allow it, then scan again", Texts.pairFailure(SnapException.NetUnreachable("u"), false)) assertEquals("PAIRING CODE EXPIRED - show a new QR", Texts.pairFailure(SnapException.PairExpired("PAIRING CODE EXPIRED - show a new QR"), true)) } + + @Test fun an_old_qr_never_reads_as_not_a_tugboat_code() { + // Known bug 0.1.x: a QR older than 2 minutes said "That is not a Tugboat code". Only a payload the core cannot parse says that. + assertEquals("PAIRING CODE EXPIRED - show a new QR", Texts.pairFailure(SnapException.PairExpired("PAIRING CODE EXPIRED - show a new QR"), false)) + assertEquals("Pairing is not open on the PC", Texts.pairFailure(SnapException.PairNotOpen("Pairing is not open on the PC"), true)) + assertEquals("Update Tugboat on the PC", Texts.pairFailure(SnapException.PairVersionMismatch("Update Tugboat on the PC"), true)) + assertEquals("That is not a Tugboat code", Texts.pairFailure(SnapException.PairBadPayload("bad"), true)) + } + + @Test fun an_old_qr_refused_by_the_pcs_newer_window_reads_expired() { + // Measured on the emulator: after 2 minutes the PC opens a new window, so the old QR comes back as a wrong secret. + assertEquals("WRONG PAIRING CODE - scan the QR again", Texts.pairFailure(SnapException.PairBadSecret("WRONG PAIRING CODE - scan the QR again"), true)) + assertEquals("PAIRING CODE EXPIRED - show a new QR", Texts.pairFailure(SnapException.PairBadSecret("WRONG PAIRING CODE - scan the QR again"), true, codeExpired = true)) + assertEquals("PAIRING CODE EXPIRED - show a new QR", Texts.pairFailure(SnapException.PairNotOpen("Pairing is not open on the PC"), true, codeExpired = true)) + // A refusal that has nothing to do with the code's age keeps its words. + assertEquals("Update Tugboat on the PC", Texts.pairFailure(SnapException.PairVersionMismatch("Update Tugboat on the PC"), true, codeExpired = true)) + } + + @Test fun storage_low_text_counts_what_waits_on_the_pc() { + assertEquals("PHONE STORAGE LOW - 37 items wait on the PC", Texts.storageLow(37u)) + assertEquals("PHONE STORAGE LOW - 2 items wait on the PC", Texts.storageLow(2u)) + assertEquals("PHONE STORAGE LOW - 1 item waits on the PC", Texts.storageLow(1u)) + assertEquals("PHONE STORAGE LOW", Texts.storageLow(0u)) + } + + @Test fun expiry_labels_have_no_waiting_state() { + val now = 100 * day + for (st in listOf(ItemStateInfo.Kept, ItemStateInfo.FolderKeep, ItemStateInfo.Live(now + hour), ItemStateInfo.Deleted(now), ItemStateInfo.Expired(now))) { + assertEquals(false, Texts.expiryLabel(st, now, 7u).contains("aiting")) + } + } } diff --git a/apps/android/app/src/test/java/app/localtugboat/UiLogicTest.kt b/apps/android/app/src/test/java/app/localtugboat/UiLogicTest.kt index d9391c9..d0a717e 100644 --- a/apps/android/app/src/test/java/app/localtugboat/UiLogicTest.kt +++ b/apps/android/app/src/test/java/app/localtugboat/UiLogicTest.kt @@ -26,12 +26,13 @@ class UiLogicTest { private fun pc() = PairedPc("a".repeat(64), "NIGEL-PC", 1L, 2L, listOf("192.168.1.5:47300")) - private fun status(state: SyncState, waiting: UInt = 0u, message: String? = null) = SyncStatus(state, "NIGEL-PC", null, waiting, 0u, message) + private fun status(state: SyncState, waiting: UInt = 0u, message: String? = null, downloading: UInt = 0u, storageLow: Boolean = false) = + SyncStatus(state, "NIGEL-PC", null, waiting, downloading, storageLow, message) private fun item( state: ItemStateInfo = ItemStateInfo.Live(1_000_000L + 5 * hour), local: LocalFileState = LocalFileState.PRESENT, - pinned: Boolean = false, kind: MediaKind = MediaKind.IMAGE, path: String? = "/x/a.jpg", - ) = ItemInfo("i1", "a", "f1", kind, 10uL, "jpg", 0L, pinned, state, local, path, null) + pinned: Boolean = false, kind: MediaKind = MediaKind.IMAGE, path: String? = "/x/a.jpg", neverReached: Boolean = false, + ) = ItemInfo("i1", "a", "f1", kind, 10uL, "jpg", 0L, pinned, state, local, path, null, neverReached) // ---- which screen ---- @@ -129,7 +130,7 @@ class UiLogicTest { @Test fun banners_list_blockers_first_each_group_in_a_fixed_order() { val ui = UiState( loaded = true, paired = pc(), perms = perms(notif = false, net = false), stoppedGapFromMs = 1_000L, - storageLow = true, errors = listOf("old", "download failed"), + status = status(SyncState.SYNCING, downloading = 37u, storageLow = true), errors = listOf("old", "download failed"), ) val ids = UiLogic.banners(ui, ZoneId.of("UTC")).map { it.id } assertEquals( @@ -139,14 +140,30 @@ class UiLogicTest { val b = UiLogic.banners(ui, ZoneId.of("UTC")) assertEquals(listOf(UiLogic.Level.BLOCKER, UiLogic.Level.BLOCKER, UiLogic.Level.WARNING, UiLogic.Level.WARNING, UiLogic.Level.WARNING), b.map { it.level }) assertEquals("download failed", b.last().text) // newest error only + assertEquals("PHONE STORAGE LOW - 37 items wait on the PC", b.first { it.id == UiLogic.BannerId.STORAGE }.text) assertEquals("Fix", b.first { it.id == UiLogic.BannerId.STOPPED }.action) } @Test fun an_unpaired_phone_gets_no_permission_or_storage_banners() { - val ui = UiState(loaded = true, perms = perms(notif = false, net = false), storageLow = true) + val ui = UiState(loaded = true, perms = perms(notif = false, net = false), storageLow = true, status = status(SyncState.UNPAIRED, storageLow = true)) assertTrue(UiLogic.banners(ui, ZoneId.of("UTC")).isEmpty()) } + @Test fun the_storage_banner_follows_the_core_not_the_free_bytes_guess() { + val zone = ZoneId.of("UTC") + // Core holds downloads back: red banner with the count of items that wait on the PC. + val low = UiLogic.banners(UiState(loaded = true, paired = pc(), status = status(SyncState.SYNCED, downloading = 1u, storageLow = true)), zone) + assertEquals("PHONE STORAGE LOW - 1 item waits on the PC", low.single().text) + assertEquals(UiLogic.Level.BLOCKER, low.single().level) + assertEquals("PHONE STORAGE LOW", UiLogic.banners(UiState(loaded = true, paired = pc(), status = status(SyncState.SYNCED, storageLow = true)), zone).single().text) + // Free space under the setting but the core is not holding anything back (nothing waits): no banner. + assertTrue(UiLogic.banners(UiState(loaded = true, paired = pc(), storageLow = true, status = status(SyncState.SYNCED)), zone).isEmpty()) + // Space is back: the core says storageLow false, banner gone even with items still downloading. + assertTrue(UiLogic.banners(UiState(loaded = true, paired = pc(), status = status(SyncState.SYNCING, downloading = 5u)), zone).isEmpty()) + // No status yet (app just started): nothing to say. + assertTrue(UiLogic.banners(UiState(loaded = true, paired = pc()), zone).isEmpty()) + } + @Test fun a_core_that_will_not_open_is_a_blocker() { val b = UiLogic.banners(UiState(loaded = true, openError = "KEY UNREADABLE"), ZoneId.of("UTC")).single() assertEquals(UiLogic.Level.BLOCKER, b.level) @@ -264,10 +281,7 @@ class UiLogicTest { assertTrue(UiLogic.cell(item(pinned = true), now, 7u, false).kept) assertTrue(UiLogic.cell(item(state = ItemStateInfo.FolderKeep), now, 7u, false).kept) assertEquals("Kept (folder)", UiLogic.cell(item(state = ItemStateInfo.FolderKeep), now, 7u, false).label) - val waiting = UiLogic.cell(item(state = ItemStateInfo.Waiting, kind = MediaKind.VIDEO), now, 7u, false) - assertEquals("Waiting for PC", waiting.label) - assertTrue(waiting.waiting) - assertTrue(waiting.video) + assertTrue(UiLogic.cell(item(kind = MediaKind.VIDEO), now, 7u, false).video) // A file problem outranks the expiry text. assertEquals("FILE MISSING on this phone", UiLogic.cell(item(local = LocalFileState.LOST), now, 7u, false).label) // Bin rows count their days. @@ -275,6 +289,41 @@ class UiLogicTest { assertEquals("In Bin, 6d left", UiLogic.cell(binned, now, 7u, true).label) } + @Test fun a_file_that_is_not_a_photo_or_video_is_a_file_cell() { + val now = 1_000_000L + val f = UiLogic.cell(item(kind = MediaKind.FILE, path = "/x/a.pdf"), now, 7u, false) + assertTrue(f.file) + assertFalse(f.video) + assertFalse(UiLogic.cell(item(), now, 7u, false).file) + assertFalse(UiLogic.cell(item(kind = MediaKind.VIDEO), now, 7u, false).file) + assertEquals("File", UiLogic.kindWord(MediaKind.FILE)) + assertEquals("Photo", UiLogic.kindWord(MediaKind.IMAGE)) + assertEquals("Video", UiLogic.kindWord(MediaKind.VIDEO)) + } + + @Test fun nothing_says_waiting_for_pc_any_more() { + // 0.2.0: items expire on time. Every state has a plain label; none of them holds the item back. + val now = 100 * day + val states = listOf(ItemStateInfo.Live(now + hour), ItemStateInfo.Kept, ItemStateInfo.FolderKeep, ItemStateInfo.Deleted(now), ItemStateInfo.Expired(now)) + for (st in states) assertFalse(UiLogic.cell(item(state = st, local = LocalFileState.PRESENT), now, 7u, false).label.contains("aiting")) + } + + @Test fun a_bin_item_that_never_reached_the_pc_says_so() { + val now = 100 * day + val gone = item(state = ItemStateInfo.Expired(now - day), local = LocalFileState.BINNED, neverReached = true) + assertEquals("In Bin, 6d left - NOT ON PC", UiLogic.cell(gone, now, 7u, true).label) + // Only the Bin carries the note; a normal expired item is unchanged. + assertEquals("In Bin, 6d left", UiLogic.cell(item(state = ItemStateInfo.Expired(now - day), local = LocalFileState.BINNED), now, 7u, true).label) + assertEquals("Expires in 1h", UiLogic.cell(item(state = ItemStateInfo.Live(now + hour), neverReached = true), now, 7u, false).label) + } + + @Test fun open_needs_the_file_here_and_outside_the_bin() { + assertTrue(UiLogic.canOpen(item(kind = MediaKind.FILE), false)) + assertFalse(UiLogic.canOpen(item(kind = MediaKind.FILE), true)) // the provider serves items/ only: restore first + assertFalse(UiLogic.canOpen(item(kind = MediaKind.FILE, path = null), false)) + assertFalse(UiLogic.canOpen(item(kind = MediaKind.FILE, local = LocalFileState.PENDING), false)) + } + @Test fun share_and_save_need_the_file_on_this_phone() { assertTrue(UiLogic.fileHeld(item())) assertFalse(UiLogic.fileHeld(item(path = null))) diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 17e2779..86db494 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "tugboat-desktop", - "version": "0.1.0", + "version": "0.2.0", "private": true, "description": "Tugboat desktop app UI (Svelte 5). All logic is in Rust; this is the view.", "type": "module", diff --git a/apps/desktop/src-tauri/src/backend.rs b/apps/desktop/src-tauri/src/backend.rs index 5575851..16d0326 100644 --- a/apps/desktop/src-tauri/src/backend.rs +++ b/apps/desktop/src-tauri/src/backend.rs @@ -16,12 +16,14 @@ use serde::{Deserialize, Serialize}; use tugboat_core::{ events::{Event, PairingEvent, SyncStatus}, facade::{device_id_from_secret, NetworkConfig}, - names, ActivityEntry, Clock, Core, CoreConfig, DeviceId, FolderId, FolderView, ItemId, ItemQuery, ItemView, Page, Role, Settings, SystemClock, + names, ActivityEntry, Clock, Core, CoreConfig, DeviceId, FolderId, FolderKind, FolderView, ItemId, ItemQuery, ItemView, Page, Role, Settings, SystemClock, + INBOX_ID, }; use tokio::{sync::broadcast, task::JoinHandle}; use ts_rs::TS; use crate::{ + drop::{self, DropLine, DropProgress, DropReport, DropState, DropTarget, NativeDrop}, error::{CmdError, CmdResult}, firewall::{self, FirewallInfo}, keys::{self, KeyStore}, @@ -47,6 +49,12 @@ pub mod ev { pub const RESYNC: &str = "resync"; /// `TrayState`. pub const TRAY: &str = "tray-state"; + /// `DropState`: files dragged over the window (the overlay names the target). + pub const DROP_STATE: &str = "drop-state"; + /// `DropProgress`: how far the file being copied is. + pub const DROP_PROGRESS: &str = "drop-progress"; + /// `DropReport`: what the drop did. + pub const DROP_RESULT: &str = "drop-result"; } /// Where backend events go: the Tauri window, or a list in a test. @@ -161,6 +169,12 @@ pub struct Backend { bind: Mutex, network_error: Mutex>, tasks: Mutex>>, + /// The folder the gallery is showing (None = Inbox), set by the UI. Only a folder id: never a path. + drop_view: Mutex>, + /// The target named by the overlay at the moment files entered the window. + drop_locked: Mutex>, + /// One drop copies at a time; a second waits its turn. + drop_run: Mutex<()>, } impl Backend { @@ -213,8 +227,18 @@ impl Backend { bind: Mutex::new(SocketAddr::from(([0, 0, 0, 0], 0))), network_error: Mutex::new(None), tasks: Mutex::new(Vec::new()), + drop_view: Mutex::new(None), + drop_locked: Mutex::new(None), + drop_run: Mutex::new(()), }); + // A quit during a drop leaves its temp copy in `.tugboat`: remove it. + if let Some(root) = library.root() { + let n = drop::clean_stale(&root); + if n > 0 { + tracing::info!("removed {n} unfinished drop copies"); + } + } shared.set_tray(&core.status()); *lock(&backend.worker) = Some(library.start()); backend.restart_network().await; @@ -315,14 +339,17 @@ impl Backend { Ok(self.core.activity(before, limit.clamp(1, 500))?) } - /// The file of a held item, for "open" and "show in folder". Only a photo or video that - /// Core holds, inside the library or the Bin, is ever handed to the shell: the id comes - /// from the webview, the path never does. + /// The file of a held item, for "open" and "show in folder". Only a file that Core holds, + /// inside the library or the Bin, whose name is not an always-refused one, is ever handed to the + /// shell: the id comes from the webview, the path never does. Windows still applies its own + /// "downloaded from another computer" check to a received program (the shell is asked, never + /// told to skip the zone check). pub fn item_path(&self, id: ItemId) -> CmdResult { let view = self.core.item(id)?.ok_or_else(|| CmdError::new("not_found", "ITEM NOT FOUND"))?; let path = PathBuf::from(view.path.ok_or_else(|| CmdError::new("not_held", "FILE IS NOT ON THIS PC"))?); let in_library = self.library.root().is_some_and(|r| is_inside(&r, &path)); - if !(in_library || is_inside(&self.paths.bin_dir, &path)) || names::ext_family(path.extension().and_then(|e| e.to_str()).unwrap_or("")).is_none() { + let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + if !(in_library || is_inside(&self.paths.bin_dir, &path)) || names::is_refused_name(&file_name) { return Err(CmdError::new("forbidden", "THAT FILE CANNOT BE OPENED")); } if !path.is_file() { @@ -419,6 +446,65 @@ impl Backend { } } + // ---------- drag and drop ---------- + + /// The gallery tells which folder it shows (None = All = Inbox). Called on every change, and with + /// None when the gallery is not on screen, so a drop on another screen says "Copy to Inbox". + pub fn drop_target_set(&self, folder: Option) { + *lock(&self.drop_view) = folder; + } + + /// The folder a drop would land in right now: the viewed one when it is still a live folder, + /// else Inbox. + pub fn drop_target(&self) -> CmdResult { + let live = self.core.live_folders()?; + let want = *lock(&self.drop_view); + let pick = want.and_then(|w| live.iter().find(|(id, _, _)| *id == w)).or_else(|| live.iter().find(|(id, kind, _)| *id == INBOX_ID || *kind == FolderKind::Inbox)); + let (id, kind, name) = pick.cloned().ok_or_else(|| CmdError::new("not_found", "INBOX NOT FOUND"))?; + Ok(DropTarget { id, kind, name }) + } + + /// Files entered the window: fix the target now (the overlay names it) and tell the overlay. + pub fn drop_enter(&self, paths: &[PathBuf]) { + let (files, folders) = drop::count_kinds(paths); + match self.drop_target() { + Ok(t) => { + let state = DropState::Enter { files, folders, target_name: t.name.clone() }; + *lock(&self.drop_locked) = Some(t); + self.shared.emit(ev::DROP_STATE, &state); + } + Err(e) => self.shared.emit(ev::CORE, &Event::Error { kind: "drop".into(), message: e.message }), + } + } + + pub fn drop_leave(&self) { + *lock(&self.drop_locked) = None; + self.shared.emit(ev::DROP_STATE, &DropState::Leave); + } + + /// Files were dropped: copy them (blocking: call off the UI thread). Always ends with one `drop-result`. + pub fn drop_files(&self, files: NativeDrop) -> DropReport { + let _turn = lock(&self.drop_run); + let locked = lock(&self.drop_locked).take(); + self.shared.emit(ev::DROP_STATE, &DropState::Leave); + let report = match locked.map(Ok).unwrap_or_else(|| self.drop_target()) { + Ok(target) => { + let shared = self.shared.clone(); + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + drop::copy_dropped(&self.library, files, &target, &mut |p: DropProgress| shared.emit(ev::DROP_PROGRESS, &p)) + })); + run.unwrap_or_else(|_| DropReport { + folder_name: target.name.clone(), + failed: vec![DropLine { name: String::new(), reason: "COPY FAILED - internal error, see the log".into() }], + ..Default::default() + }) + } + Err(e) => DropReport { failed: vec![DropLine { name: String::new(), reason: format!("COPY FAILED - {}", e.message) }], ..Default::default() }, + }; + self.shared.emit(ev::DROP_RESULT, &report); + report + } + // ---------- firewall ---------- pub fn firewall(&self) -> FirewallInfo { diff --git a/apps/desktop/src-tauri/src/bindings.rs b/apps/desktop/src-tauri/src/bindings.rs index 962dd30..e690628 100644 --- a/apps/desktop/src-tauri/src/bindings.rs +++ b/apps/desktop/src-tauri/src/bindings.rs @@ -15,6 +15,7 @@ use ts_rs::{Config, TS}; use crate::{ backend::{AppInfo, PairedDevice, PairingStart}, + drop::{DropLine, DropProgress, DropReport, DropState}, error::CmdError, firewall::{FirewallInfo, FirewallStatus}, library::{LibraryHealth, LibraryStatus, NotSyncedFile}, @@ -44,6 +45,10 @@ fn export_all(dir: &Path) { FirewallStatus, TrayState, CmdError, + DropState, + DropProgress, + DropLine, + DropReport, ); } @@ -73,8 +78,11 @@ fn bindings_match_the_committed_files() { let dir = committed_dir(); if std::env::var_os("UPDATE_BINDINGS").is_some() { std::fs::create_dir_all(&dir).unwrap(); - for old in read_dir_texts(&dir).keys() { - std::fs::remove_file(dir.join(old)).unwrap(); + // Only stale ts-rs output goes: a file without the generator's header is not ours to delete. + for (old, text) in read_dir_texts(&dir) { + if !generated.contains_key(&old) && text.contains("generated by [ts-rs]") { + std::fs::remove_file(dir.join(&old)).unwrap(); + } } for (name, text) in &generated { std::fs::write(dir.join(name), text).unwrap(); diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index f4d6c4a..20bfdea 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -186,6 +186,15 @@ pub fn library_rescan(window: WebviewWindow, be: Be) -> CmdResult<()> { Ok(()) } +/// The gallery says which folder it is showing (null = All = Inbox): a folder id, never a path. What a +/// dropped file does is decided by the window's native drop event alone (see drop.rs). +#[tauri::command(async)] +pub fn drop_target_set(window: WebviewWindow, be: Be, folder: Option) -> CmdResult<()> { + allow(&window)?; + be.drop_target_set(folder); + Ok(()) +} + /// Open the library folder in Explorer. #[tauri::command(async)] pub fn library_open_folder(window: WebviewWindow, app: AppHandle, be: Be) -> CmdResult<()> { @@ -260,6 +269,32 @@ mod tests { } } + /// No command lets the page name a file to read, copy or open: a string, path or list argument + /// must be on this list, and the list is the two folder pickers (the OS dialog chooses the folder) + /// and the item rename (a display name, never a path). A dropped file's path comes from the + /// window's native drop event only (drop.rs). + #[test] + fn no_command_takes_a_path_or_a_string_except_the_listed_ones() { + let allowed: &[(&str, &str)] = &[("library_choose", "path"), ("library_locate", "path"), ("item_rename", "name")]; + let src = include_str!("commands.rs"); + let body = src.split("#[cfg(test)]").next().unwrap(); + for c in body.split("#[tauri::command").skip(1) { + let name = c.split("fn ").nth(1).and_then(|r| r.split('(').next()).unwrap_or("?"); + let params = c.split('(').nth(1).and_then(|r| r.split(") ->").next()).unwrap_or(""); + for p in params.split(',') { + let Some((pname, ty)) = p.split_once(':') else { continue }; + let (pname, ty) = (pname.trim(), ty.trim()); + let risky = ty.contains("String") || ty.contains("Path") || ty.contains("Vec<") || ty.contains("&str"); + if risky { + assert!( + allowed.contains(&(name, pname)), + "command {name} takes `{pname}: {ty}`: text or a path from the page. Add it to the list only if it cannot be a path" + ); + } + } + } + } + #[test] fn only_the_main_window_may_call_commands() { assert!(check_caller("main").is_ok()); diff --git a/apps/desktop/src-tauri/src/drop.rs b/apps/desktop/src-tauri/src/drop.rs new file mode 100644 index 0000000..77d1955 --- /dev/null +++ b/apps/desktop/src-tauri/src/drop.rs @@ -0,0 +1,237 @@ +//! Drag files onto the Tugboat window: copy them into the folder being viewed. +//! +//! Safety rules (the reason this module looks the way it does): +//! - The paths come ONLY from the native window event (`NativeDrop::from_native`, called by +//! `shell.rs`). No Tauri command takes a path to copy, so a script running in the page cannot make +//! the app copy an arbitrary file; a test reads the sources to keep it that way. +//! - The source is only ever read (CopyFileExW): a USB stick can be pulled right after "copied". +//! Its own Mark-of-the-Web, if it has one, comes along; none is added (the user's own file). +//! - The copy is made in the hidden `.tugboat` folder under a temp name and only then placed in the +//! library with a free name (hard link or checked rename), so the library never lists a half file. +//! - A failure is always a line in the report (refused or failed), never silent. + +use std::{ + path::{Path, PathBuf}, + time::{Duration, Instant}, +}; + +use serde::{Deserialize, Serialize}; +use tugboat_core::{names, CoreError, FolderId, FolderKind}; +use ts_rs::TS; + +use crate::{library::Library, winfs}; + +/// Room kept free on the library drive besides the files themselves. +const SPACE_MARGIN: u64 = 64 * 1024 * 1024; +/// Progress is reported at most this often. +const PROGRESS_EVERY: Duration = Duration::from_millis(200); + +pub const FOLDERS_TEXT: &str = "FOLDERS NOT COPIED - drop the files inside it"; +pub const NOTHING_TEXT: &str = "NOTHING TO COPY - drop files from Explorer"; + +/// The folder a drop lands in. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DropTarget { + pub id: FolderId, + pub kind: FolderKind, + pub name: String, +} + +/// Paths of a drop as the window's native event gave them. Only `shell.rs` (and the tests) build one. +#[derive(Debug, Clone)] +pub struct NativeDrop { + paths: Vec, +} + +impl NativeDrop { + /// Only `shell.rs` calls this in the app (a test reads the sources to keep it so); the tests call it + /// to play a drop. The webview can never reach it: no command takes a path. + pub fn from_native(paths: &[PathBuf]) -> NativeDrop { + NativeDrop { paths: paths.to_vec() } + } + + pub fn paths(&self) -> &[PathBuf] { + &self.paths + } +} + +/// Sent while files are dragged over the window: the overlay names the target. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[serde(tag = "t", rename_all = "snake_case")] +pub enum DropState { + Enter { files: u32, folders: u32, target_name: String }, + Leave, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +pub struct DropProgress { + pub file: String, + /// 1-based position among the files being copied. + pub index: u32, + pub count: u32, + #[ts(type = "number")] + pub done_bytes: u64, + #[ts(type = "number")] + pub total_bytes: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +pub struct DropLine { + /// Empty when the line is about the whole drop. + pub name: String, + pub reason: String, +} + +/// What a drop did. `refused` = Tugboat will not take it; `failed` = it tried and could not. +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, TS)] +pub struct DropReport { + pub folder_name: String, + /// Names the files have in the library now. + pub copied: Vec, + pub refused: Vec, + pub failed: Vec, +} + +fn file_name(p: &Path) -> String { + p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.display().to_string()) +} + +/// Drive text for the "not enough space" line: "D:" for `D:\...`. +fn drive_of(p: &Path) -> String { + match p.components().next() { + Some(std::path::Component::Prefix(pre)) => pre.as_os_str().to_string_lossy().into_owned(), + _ => "the library drive".to_string(), + } +} + +fn io_text(e: &std::io::Error) -> String { + let t = e.to_string(); + t.split(" (os error").next().unwrap_or(&t).to_string() +} + +/// Count files and folders in a drag (the overlay's sub-line). A link to a folder counts as a folder. +pub fn count_kinds(paths: &[PathBuf]) -> (u32, u32) { + let (mut files, mut folders) = (0, 0); + for p in paths { + if std::fs::metadata(p).map(|m| m.is_dir()).unwrap_or(false) { + folders += 1; + } else { + files += 1; + } + } + (files, folders) +} + +/// Copy the dropped files into `target`. Runs on the calling thread; `progress` is told how far the +/// current file is. Everything that was not copied is in the report with its reason. +pub fn copy_dropped(lib: &Library, drop: NativeDrop, target: &DropTarget, progress: &mut dyn FnMut(DropProgress)) -> DropReport { + let mut rep = DropReport { folder_name: target.name.clone(), ..Default::default() }; + let whole = |rep: &mut DropReport, reason: String| rep.refused.push(DropLine { name: String::new(), reason }); + + if drop.paths.is_empty() { + // A virtual drop (an Outlook attachment, a zip entry): there is no file on disk to copy. + whole(&mut rep, NOTHING_TEXT.into()); + return rep; + } + let root = match lib.inner.drop_gate() { + Ok(r) => r, + Err(why) => { + whole(&mut rep, why); + return rep; + } + }; + + // Judge every path first: folders, refused names and vanished files never reach the copy. + let mut todo: Vec<(PathBuf, String, u64, i64)> = Vec::new(); + for p in &drop.paths { + let name = file_name(p); + let meta = match std::fs::metadata(p) { + Ok(m) => m, + Err(e) => { + rep.refused.push(DropLine { name, reason: format!("NOT FOUND - {}", io_text(&e)) }); + continue; + } + }; + if meta.is_dir() { + rep.refused.push(DropLine { name, reason: FOLDERS_TEXT.into() }); + } else if names::is_refused_name(&name) { + rep.refused.push(DropLine { name, reason: names::REFUSED_TEXT.into() }); + } else { + let mtime = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_millis() as i64); + todo.push((p.clone(), name, meta.len(), mtime)); + } + } + if todo.is_empty() { + return rep; + } + + let total: u64 = todo.iter().map(|t| t.2).sum(); + match fs4::available_space(&root) { + Ok(free) if free < total.saturating_add(SPACE_MARGIN) => { + whole(&mut rep, format!("NOT ENOUGH SPACE on {} - nothing copied", drive_of(&root))); + return rep; + } + Ok(_) => {} + Err(e) => { + whole(&mut rep, format!("LIBRARY DRIVE NOT READABLE - nothing copied ({})", io_text(&e))); + return rep; + } + } + let staging = match lib.inner.place.staging_dir() { + Ok(d) => d, + Err(e) => { + whole(&mut rep, format!("COPY FAILED - {e}")); + return rep; + } + }; + + let count = todo.len() as u32; + for (i, (src, name, size, mtime)) in todo.into_iter().enumerate() { + let tmp = staging.join(format!("drop-{}.tmp", uuid::Uuid::now_v7())); + let mut last = Instant::now().checked_sub(PROGRESS_EVERY).unwrap_or_else(Instant::now); + let mut on_bytes = |done: u64, all: u64| { + if last.elapsed() >= PROGRESS_EVERY || (all > 0 && done >= all) { + last = Instant::now(); + progress(DropProgress { file: name.clone(), index: i as u32 + 1, count, done_bytes: done, total_bytes: all.max(size) }); + } + }; + if let Err(e) = winfs::copy_file(&src, &tmp, &mut on_bytes) { + let _ = std::fs::remove_file(&tmp); + rep.failed.push(DropLine { name, reason: format!("COPY FAILED - {}", io_text(&e)) }); + continue; + } + // A copy of a hidden or read-only file must be an ordinary file: the library scan skips hidden + // ones and would then call the item missing. + if let Err(e) = winfs::clear_attributes(&tmp) { + let _ = std::fs::remove_file(&tmp); + rep.failed.push(DropLine { name, reason: format!("COPY FAILED - {}", io_text(&e)) }); + continue; + } + match lib.inner.place_dropped(&tmp, &name, target, mtime) { + Ok(final_name) => rep.copied.push(final_name), + Err(CoreError::Refused(why)) => { + let _ = std::fs::remove_file(&tmp); + rep.refused.push(DropLine { name, reason: why }); + } + Err(e) => { + let _ = std::fs::remove_file(&tmp); + rep.failed.push(DropLine { name, reason: format!("COPY FAILED - {e}") }); + } + } + } + rep +} + +/// Remove copies left behind by a quit or crash during a drop (`.tugboat\drop-*.tmp`). Returns how many. +pub fn clean_stale(root: &Path) -> usize { + let dir = root.join(crate::library::config::HIDDEN_DIR); + let Ok(rd) = std::fs::read_dir(&dir) else { return 0 }; + let mut n = 0; + for e in rd.flatten() { + let name = e.file_name().to_string_lossy().to_ascii_lowercase(); + if name.starts_with("drop-") && name.ends_with(".tmp") && std::fs::remove_file(e.path()).is_ok() { + n += 1; + } + } + n +} diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 75a794f..9f11a0c 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -8,6 +8,7 @@ pub mod applog; pub mod backend; pub mod commands; +pub mod drop; pub mod error; pub mod firewall; pub mod keys; @@ -120,6 +121,7 @@ pub fn run() { commands::library_locate, commands::library_resolve_missing, commands::library_rescan, + commands::drop_target_set, commands::library_open_folder, commands::firewall_status, commands::firewall_recheck, diff --git a/apps/desktop/src-tauri/src/library/config.rs b/apps/desktop/src-tauri/src/library/config.rs index 8a9ed05..6a4dd7a 100644 --- a/apps/desktop/src-tauri/src/library/config.rs +++ b/apps/desktop/src-tauri/src/library/config.rs @@ -29,6 +29,19 @@ pub struct DirEntry { pub id: Option, } +/// A file that was already in the library when 0.2.0 started syncing every file type. It is listed +/// "FROM BEFORE 0.2.0 - not synced" instead of being imported: an import would start its expiry +/// clock and the file would leave the user's folder a day later. Matched by path or NTFS identity. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LegacyFile { + /// `placement::norm` of the path. + pub path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub volume: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id: Option, +} + #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct LibraryConfig { /// Library root. None = not chosen yet. @@ -40,6 +53,13 @@ pub struct LibraryConfig { /// Folder id (uuid text) -> directory. #[serde(default)] pub dirs: BTreeMap, + /// True once the first scan of this library under 0.2.0 has recorded `legacy`. A library made + /// by 0.2.0 (empty at the start) is born done; a 0.1.x `library.json` has no such key. + #[serde(default)] + pub legacy_done: bool, + /// Non-photo files that were in the library before 0.2.0 (see `LegacyFile`). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub legacy: Vec, } #[derive(Debug, thiserror::Error)] @@ -103,7 +123,7 @@ mod tests { #[test] fn save_then_load_roundtrips_and_leaves_no_temp_file() { let d = tempfile::tempdir().unwrap(); - let mut c = LibraryConfig { path: Some(PathBuf::from(r"D:\Local Tugboat")), id: Some("abc".into()), dirs: BTreeMap::new() }; + let mut c = LibraryConfig { path: Some(PathBuf::from(r"D:\Local Tugboat")), id: Some("abc".into()), dirs: BTreeMap::new(), ..Default::default() }; c.dirs.insert("f1".into(), DirEntry { name: "Work".into(), volume: Some(7), id: Some("00".repeat(16)) }); c.save(d.path()).unwrap(); assert_eq!(LibraryConfig::load(d.path()).unwrap(), c); diff --git a/apps/desktop/src-tauri/src/library/mod.rs b/apps/desktop/src-tauri/src/library/mod.rs index 433e395..d1cc4b0 100644 --- a/apps/desktop/src-tauri/src/library/mod.rs +++ b/apps/desktop/src-tauri/src/library/mod.rs @@ -7,6 +7,8 @@ //! subfolder). The watcher only says "look again"; the pass is the same code the start-up //! and 10-minute full rescans run, so a dropped watcher event can never lose a change. //! - `worker`: the thread that owns the watcher, the debounce and the timers. +//! - `Library::drop_in`: the copy a file dropped on the window gets into the library (drop.rs +//! does the copying; this does the placing and the Core call under the same lock as a scan). pub mod config; pub mod placement; @@ -66,7 +68,7 @@ impl Default for LibraryOptions { pub struct NotSyncedFile { pub path: String, pub name: String, - /// One short line, uppercase key word ("NOT A PHOTO OR VIDEO"). + /// One short line, uppercase key word ("REFUSED - ...", "IN PROGRESS - ..."). pub reason: String, } @@ -91,6 +93,9 @@ pub struct LibraryStatus { /// Set when the library folder looks cloud-synced. pub cloud_warning: Option, pub not_synced: Vec, + /// The library drive cannot keep the Mark-of-the-Web (FAT, exFAT): files from the phone wait + /// instead of being saved unmarked. + pub cannot_mark: bool, #[ts(type = "number | null")] pub last_scan_at: Option, /// The first error of the last scan (an unreadable folder, a locked file), if any. @@ -130,8 +135,11 @@ pub(crate) struct State { pub ids: HashMap, /// mtime last handled per path: a later mtime means the file was edited. pub mtimes: HashMap, - /// Media-extension files whose content failed the type check: (size, mtime) when judged. - pub rejected: HashMap, + /// Files judged not importable (content does not match a photo/video type, too large): + /// (size, mtime, reason line) when judged, so they are listed and not retried until they change. + pub rejected: HashMap, + /// The library drive cannot hold named streams (no Mark-of-the-Web possible). + pub cannot_mark: bool, pub last_scan_at: Option, pub last_error: Option, /// Old files choose() could not delete: kept in the status until they are gone. @@ -180,6 +188,7 @@ impl Library { std::fs::create_dir_all(default_root)?; cfg.id = Some(config::write_new_marker(default_root)?); cfg.path = Some(default_root.to_path_buf()); + cfg.legacy_done = true; // a library made now was empty: nothing pre-dates 0.2.0 cfg.save(&data_dir)?; place.set_root(cfg.path.clone()); } @@ -196,6 +205,7 @@ impl Library { ids: HashMap::new(), mtimes: HashMap::new(), rejected: HashMap::new(), + cannot_mark: false, last_scan_at: None, last_error: None, leftovers: Vec::new(), @@ -206,7 +216,7 @@ impl Library { } pub fn status(&self) -> LibraryStatus { - reconcile::build_status(&lock(&self.inner.st)) + self.inner.status_of(&lock(&self.inner.st)) } /// One scan pass now, on the calling thread (the worker and the tests both use this). diff --git a/apps/desktop/src-tauri/src/library/placement.rs b/apps/desktop/src-tauri/src/library/placement.rs index 1428094..3cc2729 100644 --- a/apps/desktop/src-tauri/src/library/placement.rs +++ b/apps/desktop/src-tauri/src/library/placement.rs @@ -14,6 +14,10 @@ //! in two small time-limited sets (files just put somewhere, files just taken away), which the //! rescan reads before it imports "new" files or bins "missing" ones. //! - C6 relocate, to_bin, from_bin, purge are idempotent. +//! - C7 (0.2.0) `commit` marks every file RECEIVED from the other device as downloaded +//! (Mark-of-the-Web, `winfs::write_zone_mark`) on the part BEFORE the hard link / rename, so +//! there is no moment the file is visible in the library unmarked, and fails closed when the +//! mark cannot be written. `adopt` (the user's own files) never adds a mark. use std::{ collections::{BTreeMap, HashMap}, @@ -130,7 +134,7 @@ pub fn move_across(from: &Path, to: &Path) -> io::Result<()> { /// Put `src` into `dir` under `name` without ever overwriting someone else's file. `own` is the /// item's own current file: it may be replaced. Returns the final path; `src` is consumed. -fn place_new(src: &Path, dir: &Path, name: &str, own: Option<&Path>) -> io::Result { +pub(crate) fn place_new(src: &Path, dir: &Path, name: &str, own: Option<&Path>) -> io::Result { for _ in 0..64 { let taken = |n: &str| { let p = dir.join(n); @@ -151,12 +155,13 @@ fn place_new(src: &Path, dir: &Path, name: &str, own: Option<&Path>) -> io::Resu Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, Err(_) => { // No hard links on this volume (FAT/exFAT), or src is on another drive. - // Checked rename: the exists() test above is the guard. - if candidate.exists() { - continue; + // A move that never replaces: a file created under `candidate` since the check + // (std::fs::rename would overwrite it on Windows) sends us to the next free name. + match winfs::move_no_replace(src, &candidate) { + Ok(()) => return Ok(candidate), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), } - move_across(src, &candidate)?; - return Ok(candidate); } } } @@ -175,6 +180,9 @@ pub struct PcLibrary { /// Files adopted in place (the user's own file): purge must not delete them (the add may /// have failed after adopt, and the file is the user's). adopted: Mutex>, + /// Test seam: make the Mark-of-the-Web write fail (a drive that cannot hold it). + #[cfg(test)] + pub(crate) fail_marks: AtomicBool, } impl PcLibrary { @@ -187,6 +195,8 @@ impl PcLibrary { arrived: Mutex::new(HashMap::new()), departed: Mutex::new(HashMap::new()), adopted: Mutex::new(HashMap::new()), + #[cfg(test)] + fail_marks: AtomicBool::new(false), } } @@ -202,6 +212,11 @@ impl PcLibrary { &self.bin } + /// The placement just put a file here, or Core is about to record one the placement put here. + pub(crate) fn mark_arrived(&self, p: &Path) { + Self::touch(&self.arrived, p); + } + pub fn dirs(&self) -> BTreeMap { lock(&self.dirs).clone() } @@ -259,6 +274,11 @@ impl PcLibrary { self.root().ok_or_else(|| CoreError::Invalid("LIBRARY NOT CHOSEN - choose a library folder first".into())) } + /// The hidden `.tugboat` folder (part files, drop copies), made when missing. + pub(crate) fn staging_dir(&self) -> Result { + self.part_dir() + } + fn part_dir(&self) -> Result { let dir = self.need_root()?.join(HIDDEN_DIR); if !dir.exists() { @@ -271,26 +291,31 @@ impl PcLibrary { } fn bin_path(&self, t: &FileTarget) -> Result { - // The extension came from a synced record: only allowlisted ones become part of a path. - if names::ext_family(&t.ext).is_none() { + // The extension came from a synced record: only safe ones (never a refused type) become part of a path. + if !names::is_safe_ext(&t.ext) || names::is_refused_ext(&t.ext) { return Err(CoreError::Invalid(format!("extension '{}' is not allowed", t.ext))); } - Ok(self.bin.join(format!("{}.{}", t.item.0.hyphenated(), t.ext.to_ascii_lowercase()))) + Ok(self.bin.join(names::join_ext(&t.item.0.hyphenated().to_string(), &t.ext.to_ascii_lowercase()))) } /// The directory for `t`'s folder (created when missing). Inbox = the root. A folder that /// has no directory yet gets the next free name and the entry is remembered. fn dir_for(&self, t: &FileTarget) -> Result { + self.dir_for_folder(t.folder, t.folder_kind, &t.folder_name) + } + + /// Same, from the folder alone (a drag-and-drop copy has no item yet). + pub(crate) fn dir_for_folder(&self, folder: tugboat_core::FolderId, kind: FolderKind, folder_name: &str) -> Result { let root = self.need_root()?; - if t.folder_kind == FolderKind::Inbox { + if kind == FolderKind::Inbox { return Ok(root); } - let key = t.folder.0.to_string(); + let key = folder.0.to_string(); let mut dirs = lock(&self.dirs); let name = match dirs.get(&key) { Some(e) => e.name.clone(), None => { - let base = names::clean_folder_name(&t.folder_name).unwrap_or_else(|_| "Folder".to_string()); + let base = names::clean_folder_name(folder_name).unwrap_or_else(|_| "Folder".to_string()); // Claimed by another folder = taken. A directory that exists on disk but nobody // claimed is the user's own of that name: this folder adopts it (the rescan // would match it by name too). @@ -318,7 +343,22 @@ impl PcLibrary { /// The on-disk name for `t` read from the bytes of `file` (extension and magic checked). fn disk_name(&self, t: &FileTarget, file: &Path) -> Result { let head = read_head(file)?; - names::disk_file_name(&t.name, &t.ext, &head, t.captured_at).map(|(n, _)| n).map_err(|e| CoreError::NotMedia(e.to_string())) + names::disk_file_name(&t.name, &t.ext, &head, t.captured_at).map(|(n, _)| n).map_err(|e| match e { + // Visible, never retried in a loop: the file stays where it is and the caller lists it. + names::NameError::Refused(_) => CoreError::Refused(names::REFUSED_TEXT.to_string()), + other => CoreError::NotMedia(other.to_string()), + }) + } + + /// Mark `part` as downloaded (C7). Fails closed: Err = nothing may appear in the library. + fn mark_downloaded(&self, part: &Path) -> Result<()> { + #[cfg(test)] + if self.fail_marks.load(Ordering::SeqCst) { + return Err(CoreError::io(part, io::Error::other("test: marks are failing"))); + } + winfs::write_zone_mark(part).map_err(|e| { + CoreError::io(part, io::Error::other(format!("NOT MARKED AS DOWNLOADED - this drive cannot hold the mark, so the file was not saved ({e})"))) + }) } } @@ -328,8 +368,12 @@ impl Placement for PcLibrary { } fn commit(&self, part: &Path, t: &FileTarget) -> Result { + // A record extension that is not safe fails here, before anything is placed (C4). + let bin = self.bin_path(t)?; let dir = self.dir_for(t)?; let name = self.disk_name(t, part)?; + // C7: the mark goes on the part first; the hard link / rename below carries the stream with the file. + self.mark_downloaded(part)?; let dest = place_new(part, &dir, &name, t.current.as_deref()).map_err(|e| CoreError::io(part, e))?; Self::touch(&self.arrived, &dest); // Same item, new content that landed under another name or folder: its old file goes. @@ -339,7 +383,7 @@ impl Placement for PcLibrary { Self::touch(&self.departed, old); } } - remove_if_exists(&self.bin_path(t)?)?; + remove_if_exists(&bin)?; Ok(dest) } @@ -461,7 +505,7 @@ impl Placement for PcLibrary { fn stem_name(t: &FileTarget) -> String { let ext = t.ext.to_ascii_lowercase(); match names::clean_stem(names::strip_ext(&t.name, &t.ext)) { - Ok(stem) => format!("{stem}.{ext}"), - Err(_) => format!("{}.{ext}", names::fallback_stem(t.captured_at)), + Ok(stem) => names::join_ext(&stem, &ext), + Err(_) => names::join_ext(&names::fallback_stem(t.captured_at), &ext), } } diff --git a/apps/desktop/src-tauri/src/library/reconcile.rs b/apps/desktop/src-tauri/src/library/reconcile.rs index 0a3adaf..a5604aa 100644 --- a/apps/desktop/src-tauri/src/library/reconcile.rs +++ b/apps/desktop/src-tauri/src/library/reconcile.rs @@ -28,12 +28,13 @@ use tugboat_core::{ }; use super::{ - config::{self, DirEntry, HIDDEN_DIR}, + config::{self, DirEntry, LegacyFile, HIDDEN_DIR}, lock, placement::{is_inside, norm, same_path}, unix_ms, Bulk, Inner, LibraryHealth, LibraryStatus, NotSyncedFile, PauseKind, Seen, State, }; use crate::{ + drop::DropTarget, error::CmdError, winfs::{self, FileIdentity}, }; @@ -57,6 +58,12 @@ pub struct PassReport { // ---------- disk walk ---------- +/// Listed in Not synced when the file's content fails the photo/video check. +const MISMATCH_REASON: &str = "REFUSED - content does not match its type"; +const IN_PROGRESS_REASON: &str = "IN PROGRESS - not synced yet"; +const LINK_REASON: &str = "LINK - shortcuts to other places never sync"; +const LEGACY_REASON: &str = "FROM BEFORE 0.2.0 - not synced"; + struct DiskFile { path: PathBuf, /// Directory name under the root; None = the root itself (Inbox). @@ -64,6 +71,10 @@ struct DiskFile { name: String, size: u64, mtime: i64, + /// Why this file is never imported (an always-refused name, a download still in progress, + /// a link). It is listed, never skipped silently, and a held item that was renamed to such a + /// name in Explorer is neither renamed back nor called missing. + skip: Option<&'static str>, } struct DiskDir { @@ -73,7 +84,7 @@ struct DiskDir { #[derive(Default)] struct Walk { - /// Files with a photo/video extension. + /// Every file the user can see, whatever its type (`DiskFile.skip` marks the ones never imported). files: Vec, dirs: Vec, /// Directories Tugboat does not sync (dot-named or hidden/system). Listed so a folder the @@ -92,8 +103,24 @@ fn not_synced(path: &Path, name: &str, reason: &str) -> NotSyncedFile { NotSyncedFile { path: path.display().to_string(), name: name.to_string(), reason: reason.to_string() } } -fn is_media_name(name: &str) -> bool { - Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| names::ext_family(e).is_some()) +/// A download or editor lock file that is not the real file yet: Chrome `.crdownload`, `.part`, +/// Office `~$x.docx`, LibreOffice `.~lock.x.odt#`. (Question 8 to the owner: built as "listed, not synced".) +fn is_in_progress(name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + lower.starts_with("~$") || lower.starts_with(".~lock.") || ["crdownload", "part", "partial", "download", "opdownload"].contains(&names::ext_of(name).as_str()) +} + +fn disk_file(path: PathBuf, dir: Option, name: String, meta: &std::fs::Metadata) -> DiskFile { + let skip = if names::is_refused_name(&name) { + Some(names::REFUSED_TEXT) + } else if meta.file_type().is_symlink() { + Some(LINK_REASON) + } else if is_in_progress(&name) { + Some(IN_PROGRESS_REASON) + } else { + None + }; + DiskFile { path, dir, name, size: meta.len(), mtime: mtime_ms(meta), skip } } /// List the root and its subfolders (one level: folders are flat). The root failing is an @@ -141,10 +168,8 @@ fn walk(root: &Path, with_files: bool) -> std::io::Result { } if smeta.is_dir() { w.not_synced.push(not_synced(&sub.path(), &sname, "NESTED FOLDER - folders are one level deep")); - } else if is_media_name(&sname) { - w.files.push(DiskFile { path: sub.path(), dir: Some(name.clone()), name: sname, size: smeta.len(), mtime: mtime_ms(&smeta) }); } else { - w.not_synced.push(not_synced(&sub.path(), &sname, "NOT A PHOTO OR VIDEO")); + w.files.push(disk_file(sub.path(), Some(name.clone()), sname, &smeta)); } } } @@ -152,11 +177,7 @@ fn walk(root: &Path, with_files: bool) -> std::io::Result { } else if hidden { continue; // desktop.ini, Thumbs.db: Windows' own files, not the user's } else if with_files { - if is_media_name(&name) { - w.files.push(DiskFile { path, dir: None, name, size: meta.len(), mtime: mtime_ms(&meta) }); - } else { - w.not_synced.push(not_synced(&path, &name, "NOT A PHOTO OR VIDEO")); - } + w.files.push(disk_file(path, None, name, &meta)); } } Ok(w) @@ -186,25 +207,56 @@ pub(super) fn check_new_library(path: &Path) -> Result<(), String> { Ok(()) } -pub(super) fn build_status(st: &State) -> LibraryStatus { - let path = st.cfg.path.as_ref().map(|p| p.display().to_string()); - let (health, message) = match (&st.cfg.path, &st.pause) { - (None, _) | (_, Some(PauseKind::NotConfigured)) => (LibraryHealth::NotConfigured, st.pause_reason.clone()), - (Some(p), Some(PauseKind::Missing)) => (LibraryHealth::Missing { path: p.display().to_string() }, st.pause_reason.clone()), - (_, Some(PauseKind::Bulk)) => { - let b = st.bulk.as_ref(); - (LibraryHealth::BulkMissing { missing: b.map_or(0, |b| b.missing), total: b.map_or(0, |b| b.total) }, st.pause_reason.clone()) +impl Inner { + /// The status the UI shows: the scan's own Not synced list, then what Core refused to take from + /// the other device (those have no file on this PC, so their path is empty). + pub(super) fn status_of(&self, st: &State) -> LibraryStatus { + let path = st.cfg.path.as_ref().map(|p| p.display().to_string()); + let (health, message) = match (&st.cfg.path, &st.pause) { + (None, _) | (_, Some(PauseKind::NotConfigured)) => (LibraryHealth::NotConfigured, st.pause_reason.clone()), + (Some(p), Some(PauseKind::Missing)) => (LibraryHealth::Missing { path: p.display().to_string() }, st.pause_reason.clone()), + (_, Some(PauseKind::Bulk)) => { + let b = st.bulk.as_ref(); + (LibraryHealth::BulkMissing { missing: b.map_or(0, |b| b.missing), total: b.map_or(0, |b| b.total) }, st.pause_reason.clone()) + } + _ => (LibraryHealth::Ready, None), + }; + let mut not_synced = st.not_synced.clone(); + not_synced.extend(self.refused_by_core()); + LibraryStatus { + cloud_warning: st.cfg.path.as_deref().and_then(winfs::cloud_warning), + path, + health, + message, + not_synced, + cannot_mark: st.cannot_mark, + last_scan_at: st.last_scan_at, + last_error: st.last_error.clone(), } - _ => (LibraryHealth::Ready, None), - }; - LibraryStatus { - cloud_warning: st.cfg.path.as_deref().and_then(winfs::cloud_warning), - path, - health, - message, - not_synced: st.not_synced.clone(), - last_scan_at: st.last_scan_at, - last_error: st.last_error.clone(), + } + + /// Items Core holds as Refused (a shortcut or folder-setting file the other device sent, a file + /// over the size limit): listed so a refusal is never silent. A query failure is logged and the + /// scan's own list still shows. + fn refused_by_core(&self) -> Vec { + let rows = match self.core.refused_items(200) { + Ok(r) => r, + Err(e) => { + tracing::warn!("refused items not listed: {e}"); + return Vec::new(); + } + }; + let peer = self.core.paired_device().ok().flatten().map(|d| d.name).unwrap_or_else(|| "the other device".to_string()); + rows.into_iter() + .map(|it| { + let reason = if names::is_refused_record(&it.name, &it.ext) { + format!("REFUSED - {peer} sent a shortcut or folder-setting file") + } else { + format!("REFUSED - {peer} sent a file this PC will not take") + }; + NotSyncedFile { path: String::new(), name: it.name, reason } + }) + .collect() } } @@ -219,7 +271,8 @@ fn leftover_message(st: &mut State) -> Option { /// means the record was renamed elsewhere. pub(super) fn name_matches(record_name: &str, ext: &str, disk_name: &str) -> bool { let want = names::clean_stem(names::strip_ext(record_name, ext)).unwrap_or_default().to_lowercase(); - let stem = Path::new(disk_name).file_stem().map(|s| s.to_string_lossy().to_lowercase()).unwrap_or_default(); + // The `ext_of` rule, so "Makefile", "archive.tar.gz" and "data.sqlite3" split like the core does. + let stem = names::strip_ext(disk_name, &names::ext_of(disk_name)).to_lowercase(); // IMG_1 (2) -> IMG_1 let base = match stem.rfind(" (") { Some(i) if stem.ends_with(')') && stem[i + 2..stem.len() - 1].chars().all(|c| c.is_ascii_digit()) && stem.len() > i + 3 => &stem[..i], @@ -229,6 +282,11 @@ pub(super) fn name_matches(record_name: &str, ext: &str, disk_name: &str) -> boo want.is_empty() || stem == want || base == want } +/// Is this file one of those recorded as already there before 0.2.0 (by path or NTFS identity)? +fn is_legacy(legacy: &[LegacyFile], key: &str, ident: Option) -> bool { + legacy.iter().any(|e| e.path == key || matches!((ident, e.volume, &e.id), (Some(i), Some(v), Some(id)) if i.volume_serial == v && i.id_hex() == *id)) +} + fn parse_folder(key: &str) -> Option { uuid::Uuid::parse_str(key).ok().map(FolderId) } @@ -288,7 +346,7 @@ impl Inner { /// Tell the UI when the status changed. pub(super) fn publish(&self, st: &mut State) { - let s = build_status(st); + let s = self.status_of(st); // The scan time moves on every pass: it is sent with the next real change, not alone. let same = st.published.as_ref().is_some_and(|p| LibraryStatus { last_scan_at: s.last_scan_at, ..p.clone() } == s); if !same { @@ -333,6 +391,8 @@ impl Inner { self.set_pause(st, None, None); st.rewatch = true; } + // Files from the phone are marked as downloaded; a drive that cannot hold the mark gets one banner. + st.cannot_mark = !winfs::supports_named_streams(&root).unwrap_or(true); // 2. Directories. The map is read BEFORE the walk: an entry the placement adds after // this point has its directory on disk before it could be read here, never the reverse @@ -404,10 +464,19 @@ impl Inner { } let ident = self.identity(st, f, &key, full); let idx = ident.and_then(|i| by_ident.get(&(i.volume_serial, i.file_id)).copied()).or_else(|| by_path.get(&key).copied()); + if let Some(why) = f.skip { + // Never imported, listed. A held item renamed to this name in Explorer is not missing and + // is left exactly as the user made it (never renamed back, never binned). + if let Some(i) = idx { + matched[i] = true; + } + ns.push(not_synced(&f.path, &f.name, why)); + continue; + } match idx { Some(i) if !matched[i] => { matched[i] = true; - self.known(st, &held[i], f, ident, &index, &live, now, rep, errors); + self.known(st, &held[i], f, ident, &index, &live, now, rep, errors, &mut ns); } // A second disk file claiming an already-matched item (a hard link): ignore. Some(_) => {} @@ -433,6 +502,7 @@ impl Inner { }) .collect(); + let mut legacy_changed = false; for (f, ident) in unmatched { if self.place.recently_arrived(&f.path) { continue; // the placement just put it there; Core is about to record the path @@ -450,13 +520,26 @@ impl Inner { } } let key = norm(&f.path); - if st.rejected.get(&key) == Some(&(f.size, f.mtime)) { - ns.push(not_synced(&f.path, &f.name, "NOT A PHOTO OR VIDEO - content does not match its type")); + if let Some((size, mtime, why)) = st.rejected.get(&key) { + if *size == f.size && *mtime == f.mtime { + ns.push(not_synced(&f.path, &f.name, why)); + continue; + } + } + // Files that were here before 0.2.0 synced every type stay out of sync (see LegacyFile). + if is_legacy(&st.cfg.legacy, &key, ident) { + ns.push(not_synced(&f.path, &f.name, LEGACY_REASON)); continue; } if st.pause.is_some() { continue; // paused: nothing new is imported until the user decides } + if !st.cfg.legacy_done && names::media_family_of_name(&f.name).is_none() { + st.cfg.legacy.push(LegacyFile { path: key.clone(), volume: ident.map(|i| i.volume_serial), id: ident.map(|i| i.id_hex()) }); + legacy_changed = true; + ns.push(not_synced(&f.path, &f.name, LEGACY_REASON)); + continue; + } let Some(folder) = (match &f.dir { None => Some(None), Some(d) => index.get(&d.to_lowercase()).map(|id| Some(*id)), @@ -477,11 +560,14 @@ impl Inner { st.mtimes.retain(|k, _| seen_paths.contains(k)); st.rejected.retain(|k, _| seen_paths.contains(k)); for f in &w.files { - if st.rejected.contains_key(&norm(&f.path)) && !ns.iter().any(|n| n.path == f.path.display().to_string()) { - ns.push(not_synced(&f.path, &f.name, "NOT A PHOTO OR VIDEO - content does not match its type")); + if let Some((_, _, why)) = st.rejected.get(&norm(&f.path)) { + if !ns.iter().any(|n| n.path == f.path.display().to_string()) { + ns.push(not_synced(&f.path, &f.name, why)); + } } } st.not_synced = ns; + self.settle_legacy(st, legacy_changed); if rep.deferred > 0 { rep.retry_after = Some(self.opts.stable_for); } @@ -530,6 +616,23 @@ impl Inner { } } + /// The first complete pass under 0.2.0 closes the pre-0.2.0 list; later passes only drop entries whose + /// file is gone (a deleted file's name is free again and a new file of that name syncs). + fn settle_legacy(&self, st: &mut State, mut changed: bool) { + if !st.cfg.legacy_done && st.pause.is_none() { + st.cfg.legacy_done = true; + changed = true; + } + let before = st.cfg.legacy.len(); + let live_ids: HashSet<(u64, String)> = st.ids.values().map(|(_, _, i)| (i.volume_serial, i.id_hex())).collect(); + st.cfg.legacy.retain(|e| Path::new(&e.path).exists() || matches!((e.volume, &e.id), (Some(v), Some(id)) if live_ids.contains(&(v, id.clone())))); + if changed || st.cfg.legacy.len() != before { + if let Err(e) = st.cfg.save(&self.data_dir) { + st.last_error = Some(format!("CANNOT SAVE LIBRARY CONFIG - {e}")); + } + } + } + // ----- directories ----- fn sync_dirs( @@ -706,6 +809,7 @@ impl Inner { now: Instant, rep: &mut PassReport, errors: &mut Vec, + ns: &mut Vec, ) { // Windows paths ignore case, so a case-only rename (IMG_1.jpg -> img_1.jpg) is the same // path to same_path: compare the file name exactly as well. @@ -722,12 +826,14 @@ impl Inner { } // The disk agrees with what Core recorded, so a folder or name that differs from the // record was changed on the OTHER device: the file follows. - self.realign(h, f, index, live, rep, errors); + self.realign(h, f, index, live, rep, errors, ns); } // An edit: size differs from the record, or mtime moved since the last pass. Waits for // the same "copy finished" check as a new file, so a half-saved edit is not synced. + // The last handled mtime is remembered in Core too (`file_ref.mtime_ms`), so an edit made while the + // app was closed (same size, later mtime) is still seen at the next start. let key = norm(&f.path); - let last = st.mtimes.get(&key).copied(); + let last = st.mtimes.get(&key).copied().or(h.mtime_ms); let changed = f.size != h.size || last.is_some_and(|m| m != f.mtime); if changed { if self.stable(st, f, now) { @@ -735,6 +841,7 @@ impl Inner { Ok(()) => { rep.edited += 1; st.mtimes.insert(key, f.mtime); + self.stamp_mtime(h.item, f.mtime); } Err(e) => errors.push(format!("EDIT NOT SYNCED - {}: {e}", f.name)), } @@ -743,11 +850,31 @@ impl Inner { } } else { st.mtimes.insert(key, f.mtime); + if h.mtime_ms != Some(f.mtime) { + self.stamp_mtime(h.item, f.mtime); + } + } + } + + /// Remember the mtime just handled. A failure is logged: the cost is one extra look at the file later. + fn stamp_mtime(&self, item: ItemId, mtime: i64) { + if let Err(e) = self.core.set_file_mtime(item, mtime) { + tracing::warn!("mtime of {item:?} not remembered: {e}"); } } /// The record's folder or name changed on the other device: move the file on disk to match. - fn realign(&self, h: &HeldFile, f: &DiskFile, index: &HashMap, live: &HashMap, rep: &mut PassReport, errors: &mut Vec) { + #[allow(clippy::too_many_arguments)] + fn realign( + &self, + h: &HeldFile, + f: &DiskFile, + index: &HashMap, + live: &HashMap, + rep: &mut PassReport, + errors: &mut Vec, + ns: &mut Vec, + ) { // A deleted or unknown folder shows its items under Unsorted (Core's effective folder). let want = if live.contains_key(&h.folder) { h.folder } else { UNSORTED_ID }; let Some((kind, folder_name)) = live.get(&want).cloned() else { return }; @@ -776,6 +903,9 @@ impl Inner { Err(e) => errors.push(format!("FILE PATH UPDATE FAILED - {}: {e}", h.name)), }, Ok(_) => {} + // The other device renamed it to a name this PC refuses: the file stays as it is, listed once per + // pass (never an error, so no retry storm). + Err(CoreError::Refused(why)) => ns.push(not_synced(&f.path, &f.name, &why)), Err(e) => errors.push(format!("FILE NOT MOVED - {}: {e}", h.name)), } } @@ -797,9 +927,16 @@ impl Inner { let old_name = Path::new(&h.path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let name = if old_name == f.name { h.name.clone() + } else if h.ext.is_empty() { + // No extension by the core's `ext_of` rule: the whole new name is the name ("Dr. Smith + // letter 2" must not be cut at its last dot). + f.name.clone() + } else if names::ext_of(&f.name) == h.ext { + names::join_ext(names::strip_ext(&f.name, &h.ext), &h.ext) } else { + // The user changed the extension: the record keeps its own type (open question for Nigel). let stem = Path::new(&f.name).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); - format!("{stem}.{}", h.ext) + names::join_ext(&stem, &h.ext) }; match self.core.local_file_moved(h.item, f.path.clone(), folder, &name) { Ok(()) => rep.moved += 1, @@ -815,34 +952,30 @@ impl Inner { } } - #[allow(clippy::too_many_arguments)] - fn import( - &self, - st: &mut State, - f: &DiskFile, - folder: Option, - ident: Option, - ns: &mut Vec, - rep: &mut PassReport, - errors: &mut Vec, - ) { + /// Take one file into Core: a Shell thumbnail for photos and videos only, the record, and the mtime + /// to remember. The ONE place both a scan and a drag-and-drop copy add a file, so they obey the same rules. + pub(super) fn add_file(&self, path: &Path, name: &str, folder: Option, mtime: i64, ident: Option) -> Result { let tmp_dir = self.data_dir.join("tmp"); - let thumb = std::fs::create_dir_all(&tmp_dir).ok().and_then(|()| { - let out = tmp_dir.join(format!("{}.jpg", uuid::Uuid::now_v7())); - match crate::thumbs::make_thumbnail(&f.path, &out) { - Ok(()) => Some(out), - Err(e) => { - // Best effort: no Shell thumbnail (e.g. a codec is missing) means no thumbnail. - tracing::debug!("no thumbnail for {}: {e}", f.path.display()); - None + let thumb = if names::media_family_of_name(name).is_some() { + std::fs::create_dir_all(&tmp_dir).ok().and_then(|()| { + let out = tmp_dir.join(format!("{}.jpg", uuid::Uuid::now_v7())); + match crate::thumbs::make_thumbnail(path, &out) { + Ok(()) => Some(out), + Err(e) => { + // Best effort: no Shell thumbnail (e.g. a codec is missing) means no thumbnail. + tracing::debug!("no thumbnail for {}: {e}", path.display()); + None + } } - } - }); + }) + } else { + None + }; let new = NewLocalFile { - src: f.path.clone(), - name: f.name.clone(), + src: path.to_path_buf(), + name: name.to_string(), folder, - captured_at: f.mtime.min(unix_ms()), + captured_at: mtime.min(unix_ms()), geo: None, thumb: thumb.clone(), how: AddKind::Added, @@ -852,15 +985,33 @@ impl Inner { if let Some(t) = thumb { let _ = std::fs::remove_file(t); } - match r { + if let Ok(id) = &r { + self.stamp_mtime(*id, mtime); + } + r + } + + #[allow(clippy::too_many_arguments)] + fn import( + &self, + st: &mut State, + f: &DiskFile, + folder: Option, + ident: Option, + ns: &mut Vec, + rep: &mut PassReport, + errors: &mut Vec, + ) { + match self.add_file(&f.path, &f.name, folder, f.mtime, ident) { Ok(_) => { rep.imported += 1; st.mtimes.insert(norm(&f.path), f.mtime); } - Err(CoreError::NotMedia(why)) => { + Err(e @ (CoreError::NotMedia(_) | CoreError::Refused(_))) => { // Judged once per (size, mtime): listed, never retried until the file changes. - st.rejected.insert(norm(&f.path), (f.size, f.mtime)); - ns.push(not_synced(&f.path, &f.name, &format!("NOT A PHOTO OR VIDEO - {why}"))); + let why = if let CoreError::Refused(m) = &e { m.clone() } else { MISMATCH_REASON.to_string() }; + st.rejected.insert(norm(&f.path), (f.size, f.mtime, why.clone())); + ns.push(not_synced(&f.path, &f.name, &why)); } Err(e) => errors.push(format!("NOT SYNCED YET - {}: {e}", f.name)), } @@ -943,6 +1094,49 @@ impl Inner { } } + // ----- drag and drop ----- + + /// May a drop copy anything now? Ok = the library folder; Err = the one-line refusal. A missing or + /// paused library takes nothing (the scan would not look at it anyway). + pub(crate) fn drop_gate(&self) -> Result { + let st = lock(&self.st); + let Some(root) = st.cfg.path.clone() else { return Err("LIBRARY NOT CHOSEN - nothing copied".into()) }; + let marker = config::read_marker(&root); + if !root.is_dir() || marker.is_none() || marker != st.cfg.id || st.pause == Some(PauseKind::Missing) { + return Err("LIBRARY NOT FOUND - nothing copied".into()); + } + match st.pause { + Some(PauseKind::NotConfigured) => Err("LIBRARY NOT CHOSEN - nothing copied".into()), + Some(_) => Err("PAUSED - nothing copied".into()), + None => Ok(root), + } + } + + /// Put a finished copy (`tmp`, in `.tugboat`) into the target folder's directory under a free name + /// and take it into Core. Holds the scan lock the whole time, so a scan can neither import the + /// placed file a second time nor see it before Core knows it. On any failure the placed copy is + /// removed again (never an orphan the next scan would adopt as the user's own). Returns the name + /// the file has in the library. + pub(crate) fn place_dropped(&self, tmp: &Path, name: &str, target: &DropTarget, mtime: i64) -> Result { + let mut st = lock(&self.st); + let dir = self.place.dir_for_folder(target.id, target.kind, &target.name)?; + let placed = super::placement::place_new(tmp, &dir, name, None).map_err(|e| CoreError::io(tmp, e))?; + self.place.mark_arrived(&placed); + let ident = winfs::identity_of(&placed).ok(); + let final_name = placed.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| name.to_string()); + let folder = (target.kind != FolderKind::Inbox).then_some(target.id); + match self.add_file(&placed, &final_name, folder, mtime, ident) { + Ok(_) => { + st.mtimes.insert(norm(&placed), mtime); + Ok(final_name) + } + Err(e) => { + let _ = std::fs::remove_file(&placed); + Err(e) + } + } + } + // ----- user actions ----- pub(super) fn resolve_missing(&self, bin: bool) -> Result<(), CmdError> { @@ -980,6 +1174,17 @@ impl Inner { self.core.local_file_moved(h.item, path.join(rel), h.folder, &h.name)?; } } + // The pre-0.2.0 list follows the library to its new place (identities belong to the old copy). + if let Some(old) = st.cfg.path.clone().filter(|o| !same_path(o, path)) { + let prefix = format!("{}\\", norm(&old).trim_end_matches('\\')); + for e in st.cfg.legacy.iter_mut() { + if let Some(rel) = e.path.strip_prefix(&prefix) { + e.path = norm(&path.join(rel)); + e.volume = None; + e.id = None; + } + } + } // Directory ids belong to the old copy: relearn them by name (as choose does). let mut dirs = self.place.dirs(); for e in dirs.values_mut() { @@ -1067,7 +1272,7 @@ impl Inner { e.id = None; } self.place.replace_dirs(dirs.clone()); - st.cfg = config::LibraryConfig { path: Some(path.to_path_buf()), id: Some(id), dirs }; + st.cfg = config::LibraryConfig { path: Some(path.to_path_buf()), id: Some(id), dirs, legacy_done: true, legacy: Vec::new() }; st.cfg.save(&self.data_dir)?; self.place.set_root(Some(path.to_path_buf())); st.ids.clear(); diff --git a/apps/desktop/src-tauri/src/library/tests.rs b/apps/desktop/src-tauri/src/library/tests.rs index f6d3e69..902bc8c 100644 --- a/apps/desktop/src-tauri/src/library/tests.rs +++ b/apps/desktop/src-tauri/src/library/tests.rs @@ -206,32 +206,214 @@ fn a_file_still_being_written_is_not_imported_until_it_stops_changing() { } #[test] -fn non_media_and_mismatched_files_are_listed_never_ignored() { +fn any_file_becomes_an_item_and_only_refused_and_mismatched_files_are_listed() { let mut r = Rig::new(); std::fs::write(r.root.join("notes.txt"), b"hello").unwrap(); + std::fs::write(r.root.join("Makefile"), b"all:").unwrap(); std::fs::create_dir(r.root.join("Work")).unwrap(); std::fs::write(r.root.join("Work").join("plan.docx"), b"x").unwrap(); std::fs::write(r.root.join("fake.jpg"), b"this is not a jpeg at all").unwrap(); - // Windows' own files are not the user's. - let hidden = r.root.join("desktop.ini"); + // Shortcut and folder-setting files are never synced, even when the user can see them. + std::fs::write(r.root.join("link.lnk"), b"x").unwrap(); + std::fs::write(r.root.join("desktop.ini"), b"[x]").unwrap(); + // Windows' own hidden files are not the user's and are not listed. + let hidden = r.root.join("Work").join("desktop.ini"); std::fs::write(&hidden, b"[x]").unwrap(); - let _ = crate::winfs::hide(&hidden); + crate::winfs::hide(&hidden).unwrap(); r.settle(); r.settle(); let s = r.lib.status(); let reasons: Vec<(String, String)> = s.not_synced.iter().map(|n| (n.name.clone(), n.reason.clone())).collect(); - assert!(reasons.iter().any(|(n, why)| n == "notes.txt" && why.starts_with("NOT A PHOTO OR VIDEO")), "{reasons:?}"); - assert!(reasons.iter().any(|(n, _)| n == "plan.docx"), "files in subfolders too: {reasons:?}"); - assert!(reasons.iter().any(|(n, why)| n == "fake.jpg" && why.contains("does not match")), "{reasons:?}"); - assert!(!reasons.iter().any(|(n, _)| n == "desktop.ini"), "hidden files are not listed"); - assert!(r.items().is_empty()); - assert!(s.last_error.is_none(), "a rejected file is a listing, not an error: {:?}", s.last_error); + let by_name = |n: &str| r.items().into_iter().find(|i| i.name == n); + let notes = by_name("notes.txt").expect("a text file syncs"); + assert_eq!((notes.kind, notes.ext.as_str()), (tugboat_core::MediaKind::File, "txt")); + let make = by_name("Makefile").expect("a file with no extension syncs"); + assert_eq!((make.kind, make.ext.as_str()), (tugboat_core::MediaKind::File, "")); + assert_eq!(by_name("plan.docx").expect("files in subfolders too").folder, r.folder_named("Work").id); + assert!(reasons.iter().any(|(n, why)| n == "fake.jpg" && why == "REFUSED - content does not match its type"), "{reasons:?}"); + assert!(reasons.iter().any(|(n, why)| n == "link.lnk" && why.starts_with("REFUSED")), "{reasons:?}"); + assert!(reasons.iter().any(|(n, why)| n == "desktop.ini" && why.starts_with("REFUSED")), "a visible desktop.ini is listed: {reasons:?}"); + assert_eq!(reasons.iter().filter(|(n, _)| n == "desktop.ini").count(), 1, "the hidden one is not listed"); + assert!(by_name("link.lnk").is_none() && by_name("desktop.ini").is_none() && by_name("fake.jpg").is_none()); + assert_eq!(r.items().len(), 3); + assert!(s.last_error.is_none(), "a refused file is a listing, not an error: {:?}", s.last_error); // Judged once: changing the file's content makes it get judged again. std::fs::write(r.root.join("fake.jpg"), jpeg(4, 64)).unwrap(); r.settle(); assert_eq!(r.item("fake.jpg").kind, tugboat_core::MediaKind::Image); } +#[test] +fn downloads_and_editor_lock_files_are_listed_not_synced_yet_and_sync_once_they_are_real_files() { + let mut r = Rig::new(); + let names = ["a.crdownload", "b.part", "c.partial", "d.download", "e.opdownload", "~$f.docx", ".~lock.g.odt#"]; + for n in names { + std::fs::write(r.root.join(n), b"x").unwrap(); + } + r.settle(); + r.settle(); + let s = r.lib.status(); + for n in names { + assert!(s.not_synced.iter().any(|f| f.name == n && f.reason.starts_with("IN PROGRESS")), "{n} is listed: {:?}", s.not_synced); + } + assert!(r.items().is_empty(), "nothing in progress is imported"); + // The download finishes: it is renamed to the real file and syncs. + std::fs::rename(r.root.join("a.crdownload"), r.root.join("a.zip")).unwrap(); + r.settle(); + assert_eq!(r.item("a.zip").ext, "zip"); +} + +/// A 0.1.x library: the config has a path but no `legacy_done`. Its non-photo files were listed +/// "not synced" and left alone; importing them now would start an expiry clock on files the user +/// never asked to sync. +#[test] +fn files_that_were_there_before_0_2_0_stay_listed_and_are_never_imported() { + let mut r = Rig::new(); + let reopen = |r: &Rig, done: bool| { + let mut cfg = LibraryConfig::load(&r.data).unwrap(); + cfg.legacy_done = done; + if !done { + cfg.legacy.clear(); + } + cfg.save(&r.data).unwrap(); + Library::open(r.core.clone(), r.place.clone(), r.data.clone(), cfg, &r.root, LibraryOptions::default(), Box::new(|_| {})).unwrap() + }; + std::fs::write(r.root.join("notes.txt"), b"old").unwrap(); + r.write("a.jpg", 1); + r.lib = reopen(&r, false); // as 0.1.x left it + r.settle(); + assert_eq!(r.items().iter().map(|i| i.name.as_str()).collect::>(), ["a.jpg"], "the photo syncs as before"); + let listed = |r: &Rig| r.lib.status().not_synced.iter().any(|n| n.name == "notes.txt" && n.reason.starts_with("FROM BEFORE 0.2.0")); + assert!(listed(&r)); + assert!(LibraryConfig::load(&r.data).unwrap().legacy_done, "the first full pass closed the list"); + // A file added AFTER the upgrade syncs like any other. + std::fs::write(r.root.join("b.txt"), b"new").unwrap(); + r.settle(); + assert_eq!(r.item("b.txt").kind, tugboat_core::MediaKind::File); + // The list survives a restart (a new Library reads library.json). + r.lib = reopen(&r, true); + r.settle(); + assert!(listed(&r)); + assert!(r.items().iter().all(|i| i.name != "notes.txt")); + // Renamed in Explorer it is the same file (NTFS identity): still listed, never imported. + std::fs::rename(r.root.join("notes.txt"), r.root.join("notes2.txt")).unwrap(); + r.settle(); + assert!(r.lib.status().not_synced.iter().any(|n| n.name == "notes2.txt" && n.reason.starts_with("FROM BEFORE 0.2.0"))); + // Deleted, its name is free again: a new file with that name syncs. + std::fs::remove_file(r.root.join("notes2.txt")).unwrap(); + r.settle(); + assert!(r.lib.status().not_synced.iter().all(|n| !n.reason.starts_with("FROM BEFORE")), "{:?}", r.lib.status().not_synced); + std::fs::write(r.root.join("notes2.txt"), b"fresh").unwrap(); + r.settle(); + assert_eq!(r.item("notes2.txt").kind, tugboat_core::MediaKind::File); +} + +/// Explorer rename to a refused name: the record does not change, the file is listed, Tugboat never +/// renames it back and never bins it. +#[test] +fn a_synced_file_renamed_to_a_refused_name_in_explorer_is_listed_not_binned_or_renamed_back() { + let mut r = Rig::new(); + std::fs::write(r.root.join("a.txt"), b"hello").unwrap(); + r.settle(); + let id = r.item("a.txt").id; + std::fs::rename(r.root.join("a.txt"), r.root.join("a.lnk")).unwrap(); + for _ in 0..4 { + r.scan(3); + } + assert!(r.root.join("a.lnk").exists() && !r.root.join("a.txt").exists(), "never renamed back"); + assert_eq!(r.deleted_count(), 0, "never binned"); + assert!(r.bin().is_empty()); + assert_eq!(r.core.item(id).unwrap().unwrap().local, LocalFileState::Present); + let s = r.lib.status(); + assert!(s.not_synced.iter().any(|n| n.name == "a.lnk" && n.reason.starts_with("REFUSED")), "{:?}", s.not_synced); + assert!(s.last_error.is_none(), "{:?}", s.last_error); +} + +/// The other device renames a File item to a name this PC refuses: the file stays, one REFUSED row, +/// no error and no retry storm. +#[test] +fn a_rename_to_a_refused_name_on_the_other_device_keeps_the_file_and_lists_one_row() { + let mut r = Rig::new(); + std::fs::write(r.root.join("notes.ini"), b"[x]").unwrap(); + r.settle(); + // Core refuses such a rename on THIS device, so the other device's record is written straight into + // the database, the way a sync merge would: name "desktop", extension ini stays, disk name desktop.ini. + let changed = r.core.debug_conn(|c| c.execute("UPDATE item SET name = 'desktop' WHERE name = 'notes.ini'", []).unwrap()); + assert_eq!(changed, 1); + for _ in 0..4 { + r.scan(3); + } + let s = r.lib.status(); + assert!(r.root.join("notes.ini").exists(), "the file stays where it is"); + assert!(!r.root.join("desktop.ini").exists()); + assert!(s.last_error.is_none(), "no repeated error: {:?}", s.last_error); + let rows = s.not_synced.iter().filter(|n| n.name == "notes.ini" && n.reason.starts_with("REFUSED")).count(); + assert_eq!(rows, 1, "one REFUSED row: {:?}", s.not_synced); + assert_eq!(r.deleted_count(), 0); +} + +/// Word and Excel save by writing a temp file and swapping it in with ReplaceFileW, which can give the +/// path a new NTFS identity. It must be an edit of the same item, never a delete plus an add. +#[test] +fn an_office_safe_save_with_replacefilew_is_an_edit_of_the_same_item() { + use windows::{ + core::PCWSTR, + Win32::Storage::FileSystem::{ReplaceFileW, REPLACE_FILE_FLAGS}, + }; + let wide = |p: &Path| -> Vec { p.as_os_str().to_string_lossy().encode_utf16().chain(std::iter::once(0)).collect() }; + let mut r = Rig::new(); + let p = r.root.join("plan.docx"); + std::fs::write(&p, b"version one").unwrap(); + r.settle(); + let first = r.item("plan.docx"); + let tmp = r.root.join("~WRL0001.tmp"); + std::fs::write(&tmp, b"version two, a little longer").unwrap(); + let (replaced, replacement) = (wide(&p), wide(&tmp)); + unsafe { ReplaceFileW(PCWSTR(replaced.as_ptr()), PCWSTR(replacement.as_ptr()), PCWSTR::null(), REPLACE_FILE_FLAGS(0), None, None) }.unwrap(); + r.settle(); + r.settle(); + assert_eq!(r.items().len(), 1, "{:?}", r.items().iter().map(|i| &i.name).collect::>()); + let now = r.item("plan.docx"); + assert_eq!(now.id, first.id, "the same item"); + assert_eq!(now.size, 28, "with the new content"); + assert!(r.actions().contains(&ActivityAction::Edited)); + assert_eq!(r.deleted_count(), 0); + assert!(r.bin().is_empty()); + assert!(r.lib.status().last_error.is_none()); +} + +/// Same-size edit while the app was closed: the mtime Core remembers is the only thing that shows it. +#[test] +fn an_edit_made_while_the_app_was_closed_is_seen_at_the_next_start_even_at_the_same_size() { + let mut r = Rig::new(); + let p = r.write("a.jpg", 1); + let t = r.root.join("n.txt"); + std::fs::write(&t, b"aaaa").unwrap(); + r.settle(); + let held = r.core.held_files().unwrap(); + assert!(held.iter().all(|h| h.mtime_ms.is_some()), "every held file remembers its mtime: {held:?}"); + // The app is closed; the files change without changing size. + let later = std::time::SystemTime::now() + Duration::from_secs(30); + let mut bytes = jpeg(2, 64); + bytes[10] = 0x77; + std::fs::write(&p, &bytes).unwrap(); + std::fs::write(&t, b"bbbb").unwrap(); + for f in [&p, &t] { + std::fs::OpenOptions::new().write(true).open(f).unwrap().set_modified(later).unwrap(); + } + // A fresh start: a new Library with an empty in-memory cache over the same Core. + let cfg = LibraryConfig::load(&r.data).unwrap(); + let lib2 = Library::open(r.core.clone(), r.place.clone(), r.data.clone(), cfg, &r.root, LibraryOptions::default(), Box::new(|_| {})).unwrap(); + let now = r.now; + lib2.scan_at(false, now); + let rep = lib2.scan_at(false, now + Duration::from_secs(3)); + assert_eq!(rep.edited, 2, "both same-size edits were seen: {rep:?}"); + assert!(r.actions().iter().filter(|a| **a == ActivityAction::Edited).count() >= 2); + // And it is quiet afterwards. + let again = lib2.scan_at(false, now + Duration::from_secs(8)); + assert_eq!((again.edited, again.imported, again.binned), (0, 0, 0)); +} + // ---------- Explorer actions ---------- #[test] @@ -753,7 +935,7 @@ fn the_ui_is_told_when_the_library_status_changes_and_only_then() { assert!(n >= 1, "the first scan published a status"); r.scan(1); assert_eq!(r.statuses.lock().unwrap().len(), n, "an unchanged status is not re-sent"); - std::fs::write(r.root.join("x.txt"), b"1").unwrap(); + std::fs::write(r.root.join("x.lnk"), b"1").unwrap(); r.scan(1); let all = r.statuses.lock().unwrap(); assert_eq!(all.len(), n + 1); @@ -792,10 +974,13 @@ fn the_watcher_thread_imports_a_drop_and_follows_an_explorer_move() { wait("the Explorer move is followed", &|| r.core.item(id).unwrap().is_some_and(|i| i.folder != INBOX_ID)); assert_eq!(r.items().len(), 1); assert_eq!(r.deleted_count(), 0); - // A manual rescan request works too. + // A manual rescan request works too: a text file is a file like any other now. std::fs::write(r.root.join("note.txt"), b"x").unwrap(); worker.request_scan(true); - wait("the rescan lists the text file", &|| lib.status().not_synced.iter().any(|n| n.name == "note.txt")); + wait("the rescan imports the text file", &|| r.items().iter().any(|i| i.name == "note.txt")); + std::fs::write(r.root.join("link.lnk"), b"x").unwrap(); + worker.request_scan(true); + wait("the rescan lists the shortcut as refused", &|| lib.status().not_synced.iter().any(|n| n.name == "link.lnk")); drop(worker); // stops the thread and the watcher } @@ -909,11 +1094,14 @@ mod placement { assert!(path.exists()); std::fs::remove_file(path).unwrap(); } - // The extension comes from a synced record: only the allowlist may become part of a path. - let mut t = inbox(8, "x.jpg"); - t.ext = "exe".into(); - assert!(p.to_bin(&t).is_err()); - assert!(p.commit(&part(&p, &inbox(8, "x.jpg"), &jpeg(1, 64)), &t).is_err()); + // The extension comes from a synced record: only a safe one may become part of a path. + for bad in ["lnk", "a/b", "..", "x y", "EXE"] { + let mut t = inbox(8, "x.jpg"); + t.ext = bad.into(); + assert!(p.to_bin(&t).is_err(), "{bad:?}"); + assert!(p.commit(&part(&p, &inbox(8, "x.jpg"), &jpeg(1, 64)), &t).is_err(), "{bad:?}"); + } + assert_eq!(std::fs::read_dir(&root).unwrap().filter(|e| e.as_ref().unwrap().file_name() != ".tugboat").count(), 0, "nothing was placed"); } #[test] @@ -1121,3 +1309,492 @@ fn path_compare_collapses_dot_and_dot_dot() { // Never above the drive root. assert_eq!(norm(Path::new(r"C:\..\..\a")), r"c:\a"); } + +// ---------- any file type and the Mark-of-the-Web (placement) ---------- + +mod any_file_placement { + use super::*; + use crate::winfs::{read_zone_mark, write_zone_mark, ZONE_TEXT}; + use tugboat_core::{placement::FileTarget, BlobHash, CoreError, Placement}; + + fn rig() -> (tempfile::TempDir, PcLibrary, PathBuf) { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("lib"); + std::fs::create_dir_all(&root).unwrap(); + let p = PcLibrary::new(Some(root.clone()), tmp.path().join("bin"), Default::default()); + (tmp, p, root) + } + + fn target(n: u128, name: &str, ext: &str) -> FileTarget { + FileTarget { + item: ItemId(uuid::Uuid::from_u128(n)), + hash: BlobHash([n as u8; 32]), + name: name.into(), + ext: ext.into(), + captured_at: 1_790_000_000_000, + folder: INBOX_ID, + folder_kind: FolderKind::Inbox, + folder_name: "Inbox".into(), + current: None, + } + } + + fn part(p: &PcLibrary, t: &FileTarget, bytes: &[u8]) -> PathBuf { + let path = p.part_path(&t.hash).unwrap(); + std::fs::write(&path, bytes).unwrap(); + path + } + + #[test] + fn a_received_file_of_any_type_is_placed_under_its_own_name_and_marked_as_downloaded() { + let (_t, p, root) = rig(); + for (n, name, ext) in [(1, "report.pdf", "pdf"), (2, "Makefile", ""), (3, "data.sqlite3", "sqlite3"), (4, "run.bat", "bat")] { + let t = target(n, name, ext); + let dest = p.commit(&part(&p, &t, b"some bytes"), &t).unwrap(); + assert_eq!(dest, root.join(name), "{name}"); + assert_eq!(read_zone_mark(&dest).as_deref(), Some(ZONE_TEXT), "{name} carries the mark"); + assert_eq!(std::fs::read(format!("{}:Zone.Identifier", dest.display())).unwrap(), b"[ZoneTransfer]\r\nZoneId=3\r\n", "byte exact"); + } + } + + #[test] + fn the_mark_goes_on_the_part_first_and_travels_with_the_file_however_it_is_put_down() { + let (tmp, _p, root) = rig(); + let dir = root.clone(); + // Hard link (the normal way), the same-item replace (a rename over the old file) and the + // copy that a cross-drive move falls back to: all keep the stream, so the file is never visible unmarked. + let a = tmp.path().join("a.part"); + std::fs::write(&a, b"1").unwrap(); + write_zone_mark(&a).unwrap(); + let linked = super::super::placement::place_new(&a, &dir, "a.txt", None).unwrap(); + assert!(read_zone_mark(&linked).is_some(), "hard link"); + let b = tmp.path().join("b.part"); + std::fs::write(&b, b"2").unwrap(); + write_zone_mark(&b).unwrap(); + let replaced = super::super::placement::place_new(&b, &dir, "a.txt", Some(&linked)).unwrap(); + assert_eq!(std::fs::read(&replaced).unwrap(), b"2"); + assert!(read_zone_mark(&replaced).is_some(), "rename over the old file"); + let copy = tmp.path().join("c.copy"); + std::fs::copy(&replaced, ©).unwrap(); + assert!(read_zone_mark(©).is_some(), "std::fs::copy (what move_across and the Bin restore use) carries the stream"); + } + + #[test] + fn replacing_an_items_file_keeps_it_marked_and_the_mark_stays_through_the_bin_and_back() { + let (_t, p, root) = rig(); + let mut t = target(1, "doc.docx", "docx"); + let first = p.commit(&part(&p, &t, b"v1"), &t).unwrap(); + t.current = Some(first.clone()); + t.hash = BlobHash([9; 32]); + let second = p.commit(&part(&p, &t, b"v2 longer"), &t).unwrap(); + assert_eq!(second, first); + assert_eq!(std::fs::read(&second).unwrap(), b"v2 longer"); + assert!(read_zone_mark(&second).is_some(), "the new content is marked too"); + let binned = p.to_bin(&t).unwrap(); + assert!(read_zone_mark(&binned).is_some(), "in the Bin"); + let mut tb = t.clone(); + tb.current = Some(binned); + let back = p.from_bin(&tb).unwrap(); + assert_eq!(back, root.join("doc.docx")); + assert!(read_zone_mark(&back).is_some(), "restored from the Bin"); + } + + #[test] + fn a_users_own_file_adopted_in_place_or_copied_in_gets_no_mark() { + let (tmp, p, root) = rig(); + let own = root.join("mine.txt"); + std::fs::write(&own, b"mine").unwrap(); + let t = target(1, "mine.txt", "txt"); + assert_eq!(p.adopt(&own, &t).unwrap(), own); + assert!(read_zone_mark(&own).is_none()); + let outside = tmp.path().join("outside.txt"); + std::fs::write(&outside, b"x").unwrap(); + let t2 = target(2, "outside.txt", "txt"); + let dest = p.adopt(&outside, &t2).unwrap(); + assert!(read_zone_mark(&dest).is_none(), "copied in by the user: no mark"); + // A source that already had one (downloaded from the internet) keeps it through the copy. + let marked = tmp.path().join("marked.txt"); + std::fs::write(&marked, b"x").unwrap(); + write_zone_mark(&marked).unwrap(); + let t3 = target(3, "marked.txt", "txt"); + assert!(read_zone_mark(&p.adopt(&marked, &t3).unwrap()).is_some()); + } + + #[test] + fn a_drive_that_cannot_hold_the_mark_gets_nothing_in_the_library_and_the_part_stays() { + let (_t, p, root) = rig(); + let t = target(1, "report.pdf", "pdf"); + let src = part(&p, &t, b"bytes"); + p.fail_marks.store(true, std::sync::atomic::Ordering::SeqCst); + let err = p.commit(&src, &t).unwrap_err(); + assert!(matches!(err, CoreError::Io { .. }), "{err:?}"); + assert!(src.exists(), "the part is kept for the next try"); + assert!(!root.join("report.pdf").exists(), "nothing appears unmarked"); + p.fail_marks.store(false, std::sync::atomic::Ordering::SeqCst); + assert!(p.commit(&src, &t).unwrap().exists(), "and the retry works once the drive can mark"); + } + + #[test] + fn a_rename_to_a_refused_name_is_refused_by_relocate_and_the_file_stays() { + let (_t, p, root) = rig(); + let mut t = target(1, "notes.ini", "ini"); + let placed = p.commit(&part(&p, &t, b"[x]"), &t).unwrap(); + t.current = Some(placed.clone()); + t.name = "desktop".into(); + assert!(matches!(p.relocate(&t), Err(CoreError::Refused(_)))); + assert!(placed.exists() && !root.join("desktop.ini").exists()); + } + + #[test] + fn this_drive_supports_named_streams_and_a_bad_path_is_an_error_not_a_yes() { + let (_t, _p, root) = rig(); + assert!(crate::winfs::supports_named_streams(&root).unwrap()); + assert!(crate::winfs::supports_named_streams(Path::new(r"Z:\definitely\not\a\drive")).is_err()); + } + + #[test] + fn a_name_the_pc_refuses_is_refused_visibly_and_left_alone() { + let (_t, p, root) = rig(); + // The record name is harmless, the final disk name is not: desktop + ini. + for (name, ext) in [("desktop", "ini"), ("x", "lnk"), ("a:b", "lnk"), ("x.url", "")] { + let t = target(5, name, ext); + let src = part(&p, &t, b"x"); + let err = p.commit(&src, &t).unwrap_err(); + assert!(matches!(err, CoreError::Refused(_)) || matches!(err, CoreError::Invalid(_)), "{name}.{ext}: {err:?}"); + assert!(src.exists(), "the part is left alone"); + std::fs::remove_file(&src).unwrap(); + } + assert_eq!(std::fs::read_dir(&root).unwrap().filter(|e| e.as_ref().unwrap().file_name() != ".tugboat").count(), 0); + } +} + +// ---------- drag and drop ---------- + +mod dropping { + use super::*; + use crate::{ + drop::{clean_stale, copy_dropped, DropReport, DropTarget, NativeDrop, FOLDERS_TEXT, NOTHING_TEXT}, + winfs::{read_zone_mark, write_zone_mark}, + }; + + fn target_of(r: &Rig, name: &str) -> DropTarget { + let (id, kind, name) = r.core.live_folders().unwrap().into_iter().find(|(_, _, n)| n == name).unwrap_or_else(|| panic!("no folder {name}")); + DropTarget { id, kind, name } + } + + fn inbox(r: &Rig) -> DropTarget { + target_of(r, "Inbox") + } + + fn src_dir(r: &Rig) -> PathBuf { + let d = r._tmp.path().join("usb"); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn src(r: &Rig, name: &str, bytes: &[u8]) -> PathBuf { + let p = src_dir(r).join(name); + std::fs::write(&p, bytes).unwrap(); + p + } + + fn copy(r: &Rig, paths: &[PathBuf], t: &DropTarget) -> DropReport { + copy_dropped(&r.lib, NativeDrop::from_native(paths), t, &mut |_| {}) + } + + fn mtime(p: &Path) -> std::time::SystemTime { + std::fs::metadata(p).unwrap().modified().unwrap() + } + + fn files_in(dir: &Path) -> Vec { + let mut v: Vec = std::fs::read_dir(dir).unwrap().flatten().filter(|e| e.path().is_file()).map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + v.sort(); + v + } + + #[test] + fn files_are_copied_into_the_inbox_and_into_a_viewed_folder_and_become_items() { + let r = Rig::new(); + r.core.create_folder("Work", Retention::Keep).unwrap(); + let paths = [src(&r, "photo.jpg", &jpeg(1, 200)), src(&r, "report.pdf", b"%PDF-1.4 hello"), src(&r, "Makefile", b"all:")]; + let rep = copy(&r, &paths, &inbox(&r)); + assert_eq!(rep.folder_name, "Inbox"); + assert_eq!(rep.copied, ["photo.jpg", "report.pdf", "Makefile"], "{rep:?}"); + assert!(rep.refused.is_empty() && rep.failed.is_empty()); + assert_eq!(files_in(&r.root), ["Makefile", "photo.jpg", "report.pdf"]); + let kinds: Vec<_> = r.items().into_iter().map(|i| (i.name, i.kind, i.folder)).collect(); + assert_eq!(kinds.len(), 3); + assert!(kinds.iter().all(|(_, _, f)| *f == INBOX_ID)); + assert!(kinds.iter().any(|(n, k, _)| n == "photo.jpg" && *k == tugboat_core::MediaKind::Image)); + assert!(kinds.iter().any(|(n, k, _)| n == "report.pdf" && *k == tugboat_core::MediaKind::File)); + // Into Work: its own directory, its own folder id. + let work = target_of(&r, "Work"); + let more = [src(&r, "two.pdf", b"%PDF-1.4 two")]; + let rep = copy(&r, &more, &work); + assert_eq!((rep.folder_name.as_str(), rep.copied.as_slice()), ("Work", ["two.pdf".to_string()].as_slice())); + assert!(r.root.join("Work").join("two.pdf").is_file()); + assert_eq!(r.item("two.pdf").folder, work.id); + // The watcher does not import any of it a second time, nor bin it. + r.lib.scan(true); + let mut r = r; + r.settle(); + assert_eq!(r.items().len(), 4); + assert_eq!(r.deleted_count(), 0); + assert!(r.lib.status().last_error.is_none()); + } + + #[test] + fn a_name_that_exists_gets_a_unique_name_and_the_original_is_not_touched() { + let r = Rig::new(); + let a = src(&r, "a.txt", b"first"); + assert_eq!(copy(&r, std::slice::from_ref(&a), &inbox(&r)).copied, ["a.txt"]); + std::fs::write(&a, b"second").unwrap(); + assert_eq!(copy(&r, std::slice::from_ref(&a), &inbox(&r)).copied, ["a (2).txt"]); + assert_eq!(copy(&r, &[a], &inbox(&r)).copied, ["a (3).txt"]); + assert_eq!(std::fs::read(r.root.join("a.txt")).unwrap(), b"first"); + assert_eq!(std::fs::read(r.root.join("a (2).txt")).unwrap(), b"second"); + assert_eq!(r.items().len(), 3); + } + + #[test] + fn a_dropped_folder_copies_nothing_and_says_so_and_a_junction_counts_as_a_folder() { + let r = Rig::new(); + let folder = src_dir(&r).join("Holiday"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(folder.join("inside.jpg"), jpeg(1, 100)).unwrap(); + let rep = copy(&r, std::slice::from_ref(&folder), &inbox(&r)); + assert!(rep.copied.is_empty()); + assert_eq!(rep.refused.len(), 1); + assert_eq!((rep.refused[0].name.as_str(), rep.refused[0].reason.as_str()), ("Holiday", FOLDERS_TEXT)); + assert!(files_in(&r.root).is_empty() && r.items().is_empty(), "nothing from inside it either"); + // A junction to a folder is a folder (mklink /J needs no privilege). + let link = src_dir(&r).join("Link"); + let made = std::process::Command::new("cmd").args(["/c", "mklink", "/J"]).arg(&link).arg(&folder).output().map(|o| o.status.success()).unwrap_or(false); + if made { + let rep = copy(&r, std::slice::from_ref(&link), &inbox(&r)); + assert_eq!(rep.refused[0].reason, FOLDERS_TEXT); + assert!(r.items().is_empty()); + let _ = std::fs::remove_dir(&link); // removes the junction, not its target + } + assert!(folder.join("inside.jpg").exists()); + } + + #[test] + fn refused_names_virtual_drops_and_vanished_files_are_refused_with_a_reason_each() { + let r = Rig::new(); + let ok = src(&r, "ok.txt", b"x"); + let lnk = src(&r, "shortcut.lnk", b"x"); + let ini = src(&r, "desktop.ini", b"x"); + let gone = src_dir(&r).join("gone.txt"); + let rep = copy(&r, &[lnk, ok, ini, gone], &inbox(&r)); + assert_eq!(rep.copied, ["ok.txt"]); + let names: Vec<_> = rep.refused.iter().map(|l| (l.name.as_str(), l.reason.as_str())).collect(); + assert!(names.iter().any(|(n, why)| *n == "shortcut.lnk" && why.starts_with("REFUSED")), "{names:?}"); + assert!(names.iter().any(|(n, why)| *n == "desktop.ini" && why.starts_with("REFUSED")), "{names:?}"); + assert!(names.iter().any(|(n, why)| *n == "gone.txt" && why.starts_with("NOT FOUND")), "{names:?}"); + assert_eq!(files_in(&r.root), ["ok.txt"]); + // An Outlook attachment or a zip entry has no path: nothing to copy, and it says so. + let rep = copy(&r, &[], &inbox(&r)); + assert_eq!(rep.refused[0].reason, NOTHING_TEXT); + } + + #[test] + fn the_source_is_untouched_a_marked_source_keeps_its_mark_and_an_unmarked_one_gets_none() { + let r = Rig::new(); + let plain = src(&r, "plain.txt", b"plain bytes"); + let marked = src(&r, "marked.txt", b"marked bytes"); + write_zone_mark(&marked).unwrap(); + let old = std::time::SystemTime::now() - Duration::from_secs(86_400 * 30); + for f in [&plain, &marked] { + std::fs::OpenOptions::new().write(true).open(f).unwrap().set_modified(old).unwrap(); + } + let before: Vec<_> = [&plain, &marked].iter().map(|p| (std::fs::read(p).unwrap(), mtime(p))).collect(); + let rep = copy(&r, &[plain.clone(), marked.clone()], &inbox(&r)); + assert_eq!(rep.copied.len(), 2, "{rep:?}"); + let after: Vec<_> = [&plain, &marked].iter().map(|p| (std::fs::read(p).unwrap(), mtime(p))).collect(); + assert_eq!(before, after, "the source bytes and mtime did not change"); + assert!(read_zone_mark(&marked).is_some() && read_zone_mark(&plain).is_none(), "the sources' own marks are as they were"); + assert!(read_zone_mark(&r.root.join("plain.txt")).is_none(), "a copy the user made gets no mark"); + assert!(read_zone_mark(&r.root.join("marked.txt")).is_some(), "an existing mark comes along"); + assert_eq!(mtime(&r.root.join("plain.txt")), old, "the copy keeps the source's modified time"); + } + + #[test] + #[allow(clippy::permissions_set_readonly_false)] // Windows only: this clears the read-only attribute for the temp-dir cleanup + fn a_hidden_read_only_source_gives_an_ordinary_copy_that_stays_an_item() { + let mut r = Rig::new(); + let s = src(&r, "secret.txt", b"hidden one"); + crate::winfs::hide(&s).unwrap(); + let mut perm = std::fs::metadata(&s).unwrap().permissions(); + perm.set_readonly(true); + std::fs::set_permissions(&s, perm).unwrap(); + let rep = copy(&r, std::slice::from_ref(&s), &inbox(&r)); + assert_eq!(rep.copied, ["secret.txt"], "{rep:?}"); + let meta = std::fs::metadata(r.root.join("secret.txt")).unwrap(); + assert!(!crate::winfs::is_hidden_or_system(&meta) && !meta.permissions().readonly(), "the copy is an ordinary file"); + // The scan must see it (a hidden file would be skipped and then counted as missing). + r.settle(); + r.settle(); + assert_eq!(r.deleted_count(), 0); + assert_eq!(r.item("secret.txt").local, LocalFileState::Present); + let mut perm = std::fs::metadata(&s).unwrap().permissions(); + perm.set_readonly(false); + std::fs::set_permissions(&s, perm).unwrap(); + } + + #[test] + fn a_big_copy_never_shows_a_partial_file_in_the_library_and_reports_progress() { + let r = Rig::new(); + const SIZE: usize = 96 * 1024 * 1024; + let big = src_dir(&r).join("big.mp4"); + { + let mut v = vec![0u8; SIZE]; + v[4..8].copy_from_slice(b"ftyp"); + v[8..12].copy_from_slice(b"isom"); + std::fs::write(&big, &v).unwrap(); + } + let lib = r.lib.clone(); + let t = inbox(&r); + let events = Arc::new(Mutex::new(Vec::new())); + let ev = events.clone(); + let paths = vec![big.clone()]; + let worker = std::thread::spawn(move || copy_dropped(&lib, NativeDrop::from_native(&paths), &t, &mut |p| ev.lock().unwrap().push(p))); + let mut saw_tmp = false; + while !worker.is_finished() { + for e in std::fs::read_dir(&r.root).unwrap().flatten() { + let p = e.path(); + if p.is_file() { + assert_eq!(std::fs::metadata(&p).map(|m| m.len()).unwrap_or(SIZE as u64), SIZE as u64, "a partial file is visible: {}", p.display()); + } + } + if let Ok(rd) = std::fs::read_dir(r.root.join(".tugboat")) { + saw_tmp |= rd.flatten().any(|e| e.file_name().to_string_lossy().starts_with("drop-")); + } + } + let rep = worker.join().unwrap(); + assert_eq!(rep.copied, ["big.mp4"], "{rep:?}"); + assert!(saw_tmp, "the copy was staged in the hidden folder"); + let ev = events.lock().unwrap(); + assert!(!ev.is_empty(), "progress was reported"); + assert!(ev.iter().all(|p| p.index == 1 && p.count == 1 && p.done_bytes <= p.total_bytes && p.total_bytes == SIZE as u64), "{:?}", ev.last()); + assert_eq!(ev.last().unwrap().done_bytes, SIZE as u64, "the last event is the whole file"); + assert!(std::fs::read_dir(r.root.join(".tugboat")).unwrap().flatten().all(|e| !e.file_name().to_string_lossy().starts_with("drop-")), "no temp copy left"); + } + + #[test] + fn a_missing_or_paused_library_takes_nothing() { + let mut r = Rig::new(); + let f = src(&r, "a.txt", b"x"); + // Paused: more than ten percent of the files gone. + let mut strict = Rig::strict(); + fill(&mut strict, 25); + for i in 0..25 { + std::fs::remove_file(strict.root.join(format!("p{i:02}.jpg"))).unwrap(); + } + strict.scan(1); + let f2 = src(&strict, "b.txt", b"x"); + let rep = copy(&strict, &[f2], &inbox(&strict)); + assert!(rep.copied.is_empty()); + assert_eq!(rep.refused[0].reason, "PAUSED - nothing copied"); + // Missing: the folder is gone. + let away = r.root.with_file_name("lib-away"); + std::fs::rename(&r.root, &away).unwrap(); + let rep = copy(&r, std::slice::from_ref(&f), &inbox(&r)); + assert!(rep.copied.is_empty()); + assert_eq!(rep.refused[0].reason, "LIBRARY NOT FOUND - nothing copied"); + assert!(f.exists()); + std::fs::rename(&away, &r.root).unwrap(); + r.settle(); + assert_eq!(copy(&r, &[f], &inbox(&r)).copied, ["a.txt"], "and it works again once the library is back"); + } + + #[test] + fn a_failed_add_removes_the_copy_and_lists_the_file_as_failed() { + let r = Rig::new(); + let fake = src(&r, "fake.jpg", b"MZ this is a program, not a photo"); + let rep = copy(&r, &[fake], &inbox(&r)); + assert!(rep.copied.is_empty(), "{rep:?}"); + assert_eq!(rep.failed.len(), 1, "{rep:?}"); + assert!(rep.failed[0].reason.starts_with("COPY FAILED"), "{:?}", rep.failed); + assert!(files_in(&r.root).is_empty(), "the copy was removed again: nothing the next scan could adopt"); + assert!(std::fs::read_dir(r.root.join(".tugboat")).unwrap().flatten().all(|e| !e.file_name().to_string_lossy().starts_with("drop-"))); + assert!(r.items().is_empty()); + } + + #[test] + fn unfinished_copies_left_by_a_quit_are_removed_at_start_and_nothing_else_is() { + let r = Rig::new(); + let hidden = r.root.join(".tugboat"); + std::fs::write(hidden.join("drop-0123.tmp"), b"half").unwrap(); + std::fs::write(hidden.join("DROP-ABCD.TMP"), b"half").unwrap(); + std::fs::write(hidden.join("0123.part"), b"a download").unwrap(); + assert_eq!(clean_stale(&r.root), 2); + assert!(hidden.join("0123.part").exists() && hidden.join("library-id").exists()); + assert_eq!(clean_stale(&r.root), 0); + } + + #[test] + fn a_drop_during_a_scan_makes_exactly_one_item() { + let r = Rig::new(); + let lib = r.lib.clone(); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let flag = stop.clone(); + let scanner = std::thread::spawn(move || { + let mut now = Instant::now(); + while !flag.load(std::sync::atomic::Ordering::SeqCst) { + now += Duration::from_secs(3); + lib.scan_at(false, now); + } + }); + for i in 0..8 { + let rep = copy(&r, &[src(&r, &format!("f{i}.txt"), format!("file {i}").as_bytes())], &inbox(&r)); + assert_eq!(rep.copied.len(), 1, "{rep:?}"); + } + std::thread::sleep(Duration::from_millis(300)); + stop.store(true, std::sync::atomic::Ordering::SeqCst); + scanner.join().unwrap(); + assert_eq!(r.items().len(), 8, "one item per file, none twice: {:?}", r.items().iter().map(|i| &i.name).collect::>()); + assert_eq!(r.deleted_count(), 0); + } + + #[test] + fn a_source_inside_the_library_is_copied_under_a_new_name_and_left_alone() { + let mut r = Rig::new(); + let own = r.root.join("a.txt"); + std::fs::write(&own, b"mine").unwrap(); + let rep = copy(&r, std::slice::from_ref(&own), &inbox(&r)); + assert_eq!(rep.copied, ["a (2).txt"], "{rep:?}"); + assert_eq!(std::fs::read(&own).unwrap(), b"mine"); + r.settle(); + r.settle(); + assert_eq!(r.items().len(), 2, "the original is imported by the scan, the copy by the drop"); + } + + #[test] + fn expiry_runs_from_the_copy_not_from_the_sources_age() { + let r = Rig::new(); + let old = src(&r, "old.txt", b"two years old"); + std::fs::OpenOptions::new().write(true).open(&old).unwrap().set_modified(std::time::SystemTime::now() - Duration::from_secs(86_400 * 730)).unwrap(); + assert_eq!(copy(&r, &[old], &inbox(&r)).copied, ["old.txt"]); + let it = r.item("old.txt"); + assert!(matches!(it.state, ItemState::Live { .. }), "a year-old source is not already expired: {:?}", it.state); + assert!(r.bin().is_empty()); + } + + /// The "no path from the page" guarantee: the window's own event is the only source of copy paths. + #[test] + fn only_the_shell_and_the_drop_module_build_a_native_drop() { + for (name, text) in [ + ("commands.rs", include_str!("../commands.rs")), + ("backend.rs", include_str!("../backend.rs")), + ("lib.rs", include_str!("../lib.rs")), + ("library/mod.rs", include_str!("mod.rs")), + ("library/reconcile.rs", include_str!("reconcile.rs")), + ("library/placement.rs", include_str!("placement.rs")), + ("library/worker.rs", include_str!("worker.rs")), + ] { + assert!(!text.contains("from_native("), "{name} builds a NativeDrop"); + } + assert!(include_str!("../shell.rs").contains("NativeDrop::from_native(paths)")); + } +} diff --git a/apps/desktop/src-tauri/src/shell.rs b/apps/desktop/src-tauri/src/shell.rs index 3f483f4..239b55b 100644 --- a/apps/desktop/src-tauri/src/shell.rs +++ b/apps/desktop/src-tauri/src/shell.rs @@ -7,12 +7,13 @@ use tauri::{ image::Image, menu::{Menu, MenuItem}, tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}, - AppHandle, Emitter as _, Manager, WindowEvent, + AppHandle, DragDropEvent, Emitter as _, Manager, WindowEvent, }; use crate::{ backend::{Backend, Emitter}, commands::MAIN, + drop::NativeDrop, tray::{self, TrayState}, }; @@ -54,13 +55,38 @@ pub fn show_main(app: &AppHandle) { } } -/// Closing the window hides it; Quit (tray menu or Settings) is the way out. +/// Closing the window hides it; Quit (tray menu or Settings) is the way out. Files dragged onto the +/// window are copied into the library: this native event is the ONLY place a copy's paths come from. pub fn on_window_event(window: &tauri::Window, event: &WindowEvent) { - if let WindowEvent::CloseRequested { api, .. } = event { - if window.label() == MAIN { + if window.label() != MAIN { + return; + } + match event { + WindowEvent::CloseRequested { api, .. } => { api.prevent_close(); let _ = window.hide(); } + WindowEvent::DragDrop(e) => on_drag_drop(window.app_handle(), e), + _ => {} + } +} + +fn on_drag_drop(app: &AppHandle, e: &DragDropEvent) { + let Some(state) = app.try_state::>() else { return }; + let backend: Arc = state.inner().clone(); + match e { + DragDropEvent::Enter { paths, .. } => backend.drop_enter(paths), + DragDropEvent::Leave => backend.drop_leave(), + DragDropEvent::Drop { paths, .. } => { + let files = NativeDrop::from_native(paths); + // A big copy must not freeze the window: its own thread. The result always arrives as an event. + if let Err(e) = std::thread::Builder::new().name("tugboat-drop".into()).spawn(move || { + backend.drop_files(files); + }) { + tracing::error!("drop thread did not start: {e}"); + } + } + _ => {} } } diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs index 1bdd69c..95024a7 100644 --- a/apps/desktop/src-tauri/src/tray.rs +++ b/apps/desktop/src-tauri/src/tray.rs @@ -114,7 +114,7 @@ mod tests { use super::*; fn status(state: SyncState, waiting: u32, downloading: u32) -> SyncStatus { - SyncStatus { state, peer_name: Some("Pixel".into()), last_synced_at: None, waiting, downloading, message: None } + SyncStatus { state, peer_name: Some("Pixel".into()), last_synced_at: None, waiting, downloading, storage_low: false, message: None } } #[test] diff --git a/apps/desktop/src-tauri/src/winfs.rs b/apps/desktop/src-tauri/src/winfs.rs index f94f4cc..6754d99 100644 --- a/apps/desktop/src-tauri/src/winfs.rs +++ b/apps/desktop/src-tauri/src/winfs.rs @@ -2,6 +2,7 @@ //! attribute, cloud-sync detection. Everything else in the crate stays platform-neutral std. use std::{ + ffi::c_void, fs::OpenOptions, io, os::windows::{ @@ -16,8 +17,9 @@ use windows::{ Win32::{ Foundation::HANDLE, Storage::FileSystem::{ - GetFileInformationByHandle, GetFileInformationByHandleEx, SetFileAttributesW, BY_HANDLE_FILE_INFORMATION, - FILE_ATTRIBUTE_HIDDEN, FILE_FLAG_BACKUP_SEMANTICS, FILE_ID_INFO, FileIdInfo, + CopyFileExW, GetFileInformationByHandle, MoveFileExW, MOVEFILE_COPY_ALLOWED, GetFileInformationByHandleEx, GetVolumeInformationW, GetVolumePathNameW, SetFileAttributesW, + BY_HANDLE_FILE_INFORMATION, COPYFILE_FLAGS, COPYPROGRESSROUTINE_PROGRESS, COPY_FILE_FAIL_IF_EXISTS, FILE_ATTRIBUTE_HIDDEN, + FILE_ATTRIBUTE_NORMAL, FILE_FLAG_BACKUP_SEMANTICS, FILE_ID_INFO, FileIdInfo, LPPROGRESS_ROUTINE_CALLBACK_REASON, PROGRESS_CONTINUE, }, }, }; @@ -80,6 +82,95 @@ pub fn hide(path: &Path) -> io::Result<()> { .map_err(|e| io::Error::other(format!("could not hide {}: {e}", path.display()))) } +fn wide(p: &Path) -> Vec { + p.as_os_str().to_string_lossy().encode_utf16().chain(std::iter::once(0)).collect() +} + +/// Windows' own text for "this file came from another computer" (Mark-of-the-Web, zone 3 = Internet). +pub const ZONE_TEXT: &str = "[ZoneTransfer]\r\nZoneId=3\r\n"; +const ZONE_STREAM: &str = ":Zone.Identifier"; + +fn zone_path(path: &Path) -> PathBuf { + let mut s = path.as_os_str().to_owned(); + s.push(ZONE_STREAM); + PathBuf::from(s) +} + +/// Mark `path` as downloaded: write the `Zone.Identifier` alternate data stream and read it back. +/// Err = the file is NOT reliably marked (a volume without named streams, a failed read-back). +pub fn write_zone_mark(path: &Path) -> io::Result<()> { + let stream = zone_path(path); + std::fs::write(&stream, ZONE_TEXT)?; + if std::fs::read(&stream)? != ZONE_TEXT.as_bytes() { + return Err(io::Error::other("the mark did not read back")); + } + Ok(()) +} + +/// The text of the file's `Zone.Identifier` stream, None when it has none. +pub fn read_zone_mark(path: &Path) -> Option { + std::fs::read_to_string(zone_path(path)).ok() +} + +/// Can the volume holding `path` keep NTFS named streams (the Mark-of-the-Web)? FAT and exFAT cannot. +pub fn supports_named_streams(path: &Path) -> io::Result { + const FILE_NAMED_STREAMS: u32 = 0x0004_0000; + let w = wide(path); + let mut root = [0u16; 261]; + unsafe { GetVolumePathNameW(PCWSTR(w.as_ptr()), &mut root) }.map_err(|e| io::Error::other(format!("volume of {}: {e}", path.display())))?; + let mut flags = 0u32; + unsafe { GetVolumeInformationW(PCWSTR(root.as_ptr()), None, None, None, Some(&mut flags), None) } + .map_err(|e| io::Error::other(format!("volume information of {}: {e}", path.display())))?; + Ok(flags & FILE_NAMED_STREAMS != 0) +} + +/// Clear hidden, system and read-only on `path` (a copy of a hidden file must not stay hidden: the +/// library scan skips hidden files, then calls them missing). +pub fn clear_attributes(path: &Path) -> io::Result<()> { + let w = wide(path); + unsafe { SetFileAttributesW(PCWSTR(w.as_ptr()), FILE_ATTRIBUTE_NORMAL) } + .map_err(|e| io::Error::other(format!("could not clear attributes of {}: {e}", path.display()))) +} + +unsafe extern "system" fn copy_progress( + total: i64, + done: i64, + _stream_size: i64, + _stream_done: i64, + _stream_no: u32, + _reason: LPPROGRESS_ROUTINE_CALLBACK_REASON, + _src: HANDLE, + _dst: HANDLE, + data: *const c_void, +) -> COPYPROGRESSROUTINE_PROGRESS { + // SAFETY: `data` is the `&mut &mut dyn FnMut` that `copy_file` keeps alive for the whole call. + let cb = unsafe { &mut *(data as *mut &mut dyn FnMut(u64, u64)) }; + cb(done.max(0) as u64, total.max(0) as u64); + PROGRESS_CONTINUE +} + +/// Copy `src` to a NEW file `dst` (fails when `dst` exists) with CopyFileExW: the source is only read, +/// its streams (an existing Mark-of-the-Web) and its modified time come along. `progress(done, total)` +/// is called as bytes move. +pub fn copy_file(src: &Path, dst: &Path, progress: &mut dyn FnMut(u64, u64)) -> io::Result<()> { + let (s, d) = (wide(src), wide(dst)); + let mut cb: &mut dyn FnMut(u64, u64) = progress; + let data = &mut cb as *mut &mut dyn FnMut(u64, u64) as *const c_void; + let flags: COPYFILE_FLAGS = COPY_FILE_FAIL_IF_EXISTS; + // SAFETY: both paths are NUL-terminated and outlive the call; `data` points at `cb`, which does too. + unsafe { CopyFileExW(PCWSTR(s.as_ptr()), PCWSTR(d.as_ptr()), Some(copy_progress), Some(data), None, flags) } + .map_err(|e| io::Error::from_raw_os_error((e.code().0 as u32 & 0xFFFF) as i32)) +} + +/// Move `from` to `to` WITHOUT replacing: when `to` exists the call fails with `AlreadyExists` +/// (`std::fs::rename` replaces on Windows). Across drives it copies and deletes (MOVEFILE_COPY_ALLOWED). +pub fn move_no_replace(from: &Path, to: &Path) -> io::Result<()> { + let (f, t) = (wide(from), wide(to)); + // SAFETY: both paths are NUL-terminated and outlive the call. + unsafe { MoveFileExW(PCWSTR(f.as_ptr()), PCWSTR(t.as_ptr()), MOVEFILE_COPY_ALLOWED) } + .map_err(|e| io::Error::from_raw_os_error((e.code().0 as u32 & 0xFFFF) as i32)) +} + /// Hidden or system file (desktop.ini, Thumbs.db, .tmp markers): never listed as "not synced". pub fn is_hidden_or_system(meta: &std::fs::Metadata) -> bool { meta.file_attributes() & (FILE_ATTRIBUTE_HIDDEN.0 | FILE_ATTRIBUTE_SYSTEM) != 0 @@ -176,6 +267,21 @@ mod tests { assert!(open_exclusive(&p).is_ok()); } + #[test] + fn move_no_replace_never_overwrites() { + let d = tempfile::tempdir().unwrap(); + let (a, b, c) = (d.path().join("a.txt"), d.path().join("b.txt"), d.path().join("c.txt")); + std::fs::write(&a, b"new").unwrap(); + std::fs::write(&b, b"someone else's").unwrap(); + let e = move_no_replace(&a, &b).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(&b).unwrap(), b"someone else's", "the existing file is untouched"); + assert!(a.exists(), "the source stays after a refused move"); + move_no_replace(&a, &c).unwrap(); + assert!(!a.exists()); + assert_eq!(std::fs::read(&c).unwrap(), b"new"); + } + #[test] fn hidden_attribute_is_set() { let d = tempfile::tempdir().unwrap(); diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 16c670a..a036ba5 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "Local Tugboat", "mainBinaryName": "tugboat", - "version": "0.1.0", + "version": "0.2.0", "identifier": "app.localtugboat.desktop", "build": { "beforeDevCommand": "bun run dev", diff --git a/apps/desktop/src-tauri/tests/adversarial_020_library.rs b/apps/desktop/src-tauri/tests/adversarial_020_library.rs new file mode 100644 index 0000000..3371eb6 --- /dev/null +++ b/apps/desktop/src-tauri/tests/adversarial_020_library.rs @@ -0,0 +1,211 @@ +//! Adversarial tests, verifier stage 020 (correctness and data-safety lens) for the 0.2.0 PC +//! library: any file type, Explorer renames, Mark-of-the-Web placement and drag-and-drop copies. +//! A failing test here is a finding, not a broken test. + +use std::{ + path::PathBuf, + sync::Arc, + time::{Duration, Instant}, +}; + +use tugboat_core::{ + facade::device_id_from_secret, names, BlobHash, Core, CoreConfig, FileTarget, FolderKind, ItemId, ItemQuery, ItemView, Placement, Role, Settings, + SystemClock, INBOX_ID, +}; +use tugboat_desktop_lib::{ + drop::{copy_dropped, DropReport, DropTarget, NativeDrop}, + library::{config::LibraryConfig, placement::PcLibrary, Library, LibraryOptions}, +}; + +struct Rig { + tmp: tempfile::TempDir, + core: Core, + lib: Library, + root: PathBuf, + now: Instant, +} + +impl Rig { + fn loose() -> Rig { + let tmp = tempfile::tempdir().unwrap(); + let data = tmp.path().join("data"); + let root = tmp.path().join("lib"); + let place = Arc::new(PcLibrary::new(None, data.join("Bin"), Default::default())); + let secret = [11u8; 32]; + let cfg = CoreConfig { data_dir: data.clone(), role: Role::Pc, self_id: device_id_from_secret(&secret), device_name: "PC".into(), app_version: "test".into() }; + let (core, _rx) = Core::open(cfg, Arc::new(SystemClock), place.clone()).unwrap(); + let lib = Library::open(core.clone(), place, data.clone(), LibraryConfig::default(), &root, LibraryOptions::default(), Box::new(|_| {})).unwrap(); + core.save_settings(&Settings { missing_pause_pct: 100, ..Default::default() }).unwrap(); + Rig { tmp, core, lib, root, now: Instant::now() } + } + + fn scan(&mut self, secs: u64) { + self.now += Duration::from_secs(secs); + self.lib.scan_at(false, self.now); + } + + fn settle(&mut self) { + self.scan(0); + self.scan(3); + self.scan(3); + } + + fn items(&self) -> Vec { + self.core.items(&ItemQuery { limit: 500, ..Default::default() }).unwrap().rows + } + + fn src(&self, name: &str, bytes: &[u8]) -> PathBuf { + let d = self.tmp.path().join("usb"); + std::fs::create_dir_all(&d).unwrap(); + let p = d.join(name); + std::fs::write(&p, bytes).unwrap(); + p + } + + fn drop_in_inbox(&self, paths: &[PathBuf]) -> DropReport { + let t = DropTarget { id: INBOX_ID, kind: FolderKind::Inbox, name: "Inbox".into() }; + copy_dropped(&self.lib, NativeDrop::from_native(paths), &t, &mut |_| {}) + } + + fn files_in_root(&self) -> Vec { + let mut v: Vec = + std::fs::read_dir(&self.root).unwrap().flatten().filter(|e| e.path().is_file()).map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + v.sort(); + v + } + + fn drop_temps(&self) -> usize { + std::fs::read_dir(self.root.join(".tugboat")) + .map(|d| d.flatten().filter(|e| e.file_name().to_string_lossy().starts_with("drop-")).count()) + .unwrap_or(0) + } +} + +/// PLAN "rename = rename". A plain file with no extension by the `ext_of` rule ("Dr. Smith letter": +/// the text after the last dot has a space) is renamed in Explorer to "Dr. Smith letter 2". The +/// record must take the new name and the file must stay where the user put it. `moved()` builds +/// the new name with Rust's `file_stem` ("Dr") instead of the `ext_of` rule, so the record becomes +/// "Dr" and the next pass renames the user's file on disk to "Dr". +#[test] +fn adv020_explorer_rename_of_a_dotted_name_with_no_extension_is_kept() { + let mut r = Rig::loose(); + std::fs::create_dir_all(&r.root).unwrap(); + std::fs::write(r.root.join("Dr. Smith letter"), b"Dear Dr. Smith").unwrap(); + r.settle(); + let it = r.items(); + assert_eq!(it.len(), 1, "imported: {:?}", it.iter().map(|i| &i.name).collect::>()); + assert_eq!(it[0].ext, "", "no extension by the ext_of rule"); + std::fs::rename(r.root.join("Dr. Smith letter"), r.root.join("Dr. Smith letter 2")).unwrap(); + r.settle(); + let names: Vec = r.items().into_iter().map(|i| i.name).collect(); + let disk = r.files_in_root(); + assert_eq!(names, ["Dr. Smith letter 2"], "record name after an Explorer rename (disk now {disk:?})"); + assert_eq!(disk, ["Dr. Smith letter 2"], "the user's file keeps the name the user gave it"); +} + +/// R1 "a renamed program cannot pose as a photo". A received File record with an EMPTY extension +/// whose name ends in ".jpg" (a phone share whose bytes are not a photo, or a hostile peer) is +/// placed on the PC under the record name, so an EXE lands in the library as "holiday.jpg" although +/// the core's own rule says a File never carries a photo extension (verify_received KindMismatch). +#[test] +fn adv020_a_received_file_with_no_extension_never_lands_under_a_photo_extension() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("lib"); + std::fs::create_dir_all(&root).unwrap(); + let p = PcLibrary::new(Some(root.clone()), tmp.path().join("bin"), Default::default()); + let mut mz = b"MZ\x90\x00\x03\x00\x00\x00".to_vec(); + mz.resize(64, 0); + let mut placed = Vec::new(); + for (n, name) in [(1u128, "holiday.jpg"), (2, "clip.mp4"), (3, "scan.png")] { + let t = FileTarget { + item: ItemId(uuid::Uuid::from_u128(n)), + hash: BlobHash([n as u8; 32]), + name: name.into(), + ext: String::new(), + captured_at: 1_790_000_000_000, + folder: INBOX_ID, + folder_kind: FolderKind::Inbox, + folder_name: "Inbox".into(), + current: None, + }; + let part = p.part_path(&t.hash).unwrap(); + std::fs::write(&part, &mz).unwrap(); + if let Ok(dest) = p.commit(&part, &t) { + placed.push(dest.file_name().unwrap().to_string_lossy().into_owned()); + } + } + let posing: Vec<&String> = placed.iter().filter(|n| names::media_family_of_name(n).is_some()).collect(); + assert!(posing.is_empty(), "program bytes placed under a photo/video name: {posing:?}"); +} + +/// R2: a zero-byte file dropped on the window is copied and becomes an item (any file type). +#[test] +fn adv020_a_dropped_zero_byte_file_is_copied() { + let mut r = Rig::loose(); + r.settle(); + let src = r.src("empty.txt", b""); + let rep = r.drop_in_inbox(std::slice::from_ref(&src)); + assert_eq!(rep.copied, ["empty.txt"], "{rep:?}"); + assert!(src.exists(), "source untouched"); + let it = r.items(); + assert_eq!(it.len(), 1); + assert_eq!(it[0].size, 0); + assert_eq!(r.drop_temps(), 0, "no temp copy left"); +} + +/// R1/R2: a refused name with a trailing dot (Windows treats "evil.lnk." as "evil.lnk"; it can be +/// made through a \\?\ path, e.g. on a USB stick) is refused by a drop and nothing is copied. +#[test] +fn adv020_a_dropped_shortcut_with_a_trailing_dot_is_refused() { + let mut r = Rig::loose(); + r.settle(); + let d = r.tmp.path().join("usb2"); + std::fs::create_dir_all(&d).unwrap(); + let verbatim = PathBuf::from(format!(r"\\?\{}\evil.lnk.", d.display())); + std::fs::write(&verbatim, b"L\x00\x00\x00").unwrap(); + let listed: Vec = std::fs::read_dir(&d).unwrap().flatten().map(|e| e.path()).collect(); + assert_eq!(listed.len(), 1); + let rep = r.drop_in_inbox(&listed); + assert!(rep.copied.is_empty(), "a shortcut must never be copied in: {rep:?}"); + assert_eq!(rep.refused.len(), 1, "{rep:?}"); + assert!(r.files_in_root().is_empty(), "nothing in the library: {:?}", r.files_in_root()); + let _ = std::fs::remove_file(&verbatim); +} + +/// R1/R2: a program named like a photo is dropped. Core refuses it (content does not match); the +/// drop must say so and leave neither the placed copy nor a temp copy behind. +#[test] +fn adv020_a_dropped_program_named_like_a_photo_leaves_nothing_behind() { + let mut r = Rig::loose(); + r.settle(); + let mut mz = b"MZ\x90\x00".to_vec(); + mz.resize(4096, 1); + let src = r.src("photo.jpg", &mz); + let rep = r.drop_in_inbox(&[src]); + assert!(rep.copied.is_empty(), "{rep:?}"); + assert_eq!(rep.refused.len() + rep.failed.len(), 1, "visible: {rep:?}"); + assert!(r.files_in_root().is_empty(), "no copy left in the library: {:?}", r.files_in_root()); + assert_eq!(r.drop_temps(), 0, "no temp copy left in .tugboat"); + r.scan(3); + assert!(r.items().is_empty(), "no item made by a later scan"); +} + +/// R2 unique names: two different files with the same name dropped in one go plus an existing +/// library file of that name: all three survive, nothing is overwritten. +#[test] +fn adv020_dropping_two_same_named_files_overwrites_nothing() { + let mut r = Rig::loose(); + std::fs::create_dir_all(&r.root).unwrap(); + std::fs::write(r.root.join("notes.txt"), b"library copy").unwrap(); + r.settle(); + let a = r.src("notes.txt", b"from usb A"); + let d = r.tmp.path().join("usbB"); + std::fs::create_dir_all(&d).unwrap(); + let b = d.join("notes.txt"); + std::fs::write(&b, b"from usb B").unwrap(); + let rep = r.drop_in_inbox(&[a, b]); + assert_eq!(rep.copied.len(), 2, "{rep:?}"); + let mut bodies: Vec> = r.files_in_root().iter().map(|n| std::fs::read(r.root.join(n)).unwrap()).collect(); + bodies.sort(); + assert_eq!(bodies, [b"from usb A".to_vec(), b"from usb B".to_vec(), b"library copy".to_vec()]); +} diff --git a/apps/desktop/src-tauri/tests/adversarial_020_security.rs b/apps/desktop/src-tauri/tests/adversarial_020_security.rs new file mode 100644 index 0000000..f6845e3 --- /dev/null +++ b/apps/desktop/src-tauri/tests/adversarial_020_security.rs @@ -0,0 +1,259 @@ +//! Adversarial security tests for 0.2.0 on the PC (verifier stage, security lens). They try to break: +//! the always-refused names against what NTFS and Win32 really do with a name (case, trailing dots and +//! spaces, stream syntax, Unicode lookalikes); the Mark-of-the-Web on received files when the other +//! device later renames or moves them; and the drag-drop copy against device paths and NTFS stream +//! paths that a hostile drag source could put in a drop. A FAILING test here is a finding. + +use std::{ + path::{Path, PathBuf}, + sync::Arc, + time::{Duration, Instant}, +}; + +use tugboat_core::{ + facade::device_id_from_secret, + names, + placement::{FileTarget, Placement}, + BlobHash, Core, CoreConfig, FolderId, FolderKind, ItemId, ItemQuery, ItemView, Role, SystemClock, INBOX_ID, +}; +use tugboat_desktop_lib::{ + drop::{copy_dropped, DropReport, DropTarget, NativeDrop}, + library::{config::LibraryConfig, placement::PcLibrary, Library, LibraryOptions}, + winfs::{read_zone_mark, ZONE_TEXT}, +}; + +// ---------- names against the real filesystem ---------- + +/// Every name in `variants` is written through plain Win32 (std::fs) into an empty folder. Whatever +/// file Windows really creates is read back from the directory listing; if that file is an +/// always-refused one, the name we were given must have been refused too (otherwise a watcher, a drop +/// or a received record could produce it without being stopped). +#[test] +fn adversarial_020_security_a_name_that_windows_turns_into_a_refused_file_is_refused() { + let variants = [ + "x.lnk", + "X.LNK", + "x.lnk.", + "x.lnk. .", + "x.lnk ", + "x.lnk::$DATA", + "x.lnk:payload", + "x.url..", + "x.scf ", + "x.Library-ms.", + "x.searchConnector-ms ", + "DESKTOP.INI", + "desktop.ini...", + "desktop.ini:zone", + "autorun.inf ", + "AutoRun.Inf::$DATA", + // Not refused by Windows itself (the extra character stays in the name): only checked for consistency. + "x.lnk\u{200B}", + "x.l\u{0131}nk", + ]; + for v in variants { + let dir = tempfile::tempdir().unwrap(); + if std::fs::write(dir.path().join(v), b"x").is_err() { + continue; // Windows refused the name outright: nothing could be made from it. + } + let made: Vec = std::fs::read_dir(dir.path()).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + for real in &made { + if names::is_refused_name(real) { + assert!(names::is_refused_name(v), "{v:?} creates the refused file {real:?} but is not refused itself"); + } + } + } +} + +/// Unicode lookalikes (dotless i, long s, Kelvin sign, Turkish capital I, fullwidth letters) are NOT +/// folded to ASCII by NTFS name lookup or by the registry's file-type lookup on this PC, so a name like +/// "de\u{17F}ktop.ini" is not desktop.ini to Explorer and need not be refused. This test pins that +/// assumption: if a Windows update ever starts folding them, it fails and the refused list needs a +/// Unicode case fold. +#[test] +fn adversarial_020_security_unicode_lookalikes_do_not_alias_a_refused_file_or_file_type() { + let dir = tempfile::tempdir().unwrap(); + for (look, real) in [ + ("de\u{017F}ktop.ini", "desktop.ini"), + ("desktop.\u{0131}ni", "desktop.ini"), + ("desktop.\u{0130}ni", "desktop.ini"), + ("autorun.\u{0131}nf", "autorun.inf"), + ("x.ln\u{212A}", "x.lnk"), + ("x.\u{FF4C}nk", "x.lnk"), + ] { + let p = dir.path().join(look); + std::fs::write(&p, b"x").unwrap(); + assert!(!dir.path().join(real).exists(), "NTFS opens {look:?} when {real:?} is asked for: the refused list must case-fold Unicode"); + std::fs::remove_file(&p).unwrap(); + } + // File types: HKCR lookups of the lookalike extensions must find no key (reg.exe exits 1 = not found). + for ext in [".\u{017F}cf", ".ln\u{212A}", ".\u{0131}ni"] { + let out = std::process::Command::new("reg").args(["query", &format!(r"HKCR\{ext}")]).output().unwrap(); + assert!(!out.status.success(), "the registry resolves the lookalike type {ext:?} to a real file type"); + } + // Control: the real types do exist, so the probe itself works. + let out = std::process::Command::new("reg").args(["query", r"HKCR\.lnk"]).output().unwrap(); + assert!(out.status.success(), "control probe failed: HKCR\\.lnk not found"); +} + +// ---------- Mark-of-the-Web when the other device renames or moves a received file ---------- + +fn target(n: u128, name: &str, ext: &str) -> FileTarget { + FileTarget { + item: ItemId(uuid::Uuid::from_u128(n)), + hash: BlobHash([n as u8; 32]), + name: name.into(), + ext: ext.into(), + captured_at: 1_790_000_000_000, + folder: INBOX_ID, + folder_kind: FolderKind::Inbox, + folder_name: "Inbox".into(), + current: None, + } +} + +/// A received file keeps its mark when the other device renames it, moves it to another folder, and +/// when it goes to the Bin and back: every one of those is the placement moving the same file, so the +/// "downloaded from elsewhere" warning must never quietly disappear. +#[test] +fn adversarial_020_security_a_received_file_stays_marked_through_rename_move_bin_and_restore() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("lib"); + std::fs::create_dir_all(&root).unwrap(); + let p = PcLibrary::new(Some(root.clone()), tmp.path().join("bin"), Default::default()); + let mut t = target(7, "setup.bat", "bat"); + let part = p.part_path(&t.hash).unwrap(); + std::fs::write(&part, b"@echo hi").unwrap(); + let placed = p.commit(&part, &t).unwrap(); + assert_eq!(read_zone_mark(&placed).as_deref(), Some(ZONE_TEXT)); + + // Renamed by the phone. + t.current = Some(placed); + t.name = "install.bat".into(); + let renamed = p.relocate(&t).unwrap(); + assert_eq!(renamed.file_name().unwrap(), "install.bat"); + assert_eq!(read_zone_mark(&renamed).as_deref(), Some(ZONE_TEXT), "mark lost on a rename by the other device"); + + // Moved to another folder by the phone. + t.current = Some(renamed); + t.folder = FolderId(uuid::Uuid::from_u128(99)); + t.folder_kind = FolderKind::User; + t.folder_name = "Work".into(); + let moved = p.relocate(&t).unwrap(); + assert!(moved.starts_with(root.join("Work")), "{}", moved.display()); + assert_eq!(read_zone_mark(&moved).as_deref(), Some(ZONE_TEXT), "mark lost on a move to another folder"); + + // Bin and back. + t.current = Some(moved); + let binned = p.to_bin(&t).unwrap(); + assert_eq!(read_zone_mark(&binned).as_deref(), Some(ZONE_TEXT), "mark lost in the Bin"); + t.current = Some(binned); + let back = p.from_bin(&t).unwrap(); + assert_eq!(read_zone_mark(&back).as_deref(), Some(ZONE_TEXT), "mark lost on restore"); +} + +// ---------- drag and drop: hostile drop paths ---------- + +struct Rig { + _tmp: tempfile::TempDir, + core: Core, + lib: Library, + root: PathBuf, + src: PathBuf, +} + +impl Rig { + fn new() -> Rig { + let tmp = tempfile::tempdir().unwrap(); + let data = tmp.path().join("data"); + let root = tmp.path().join("lib"); + let src = tmp.path().join("usb"); + std::fs::create_dir_all(&src).unwrap(); + let place = Arc::new(PcLibrary::new(None, data.join("Bin"), Default::default())); + let secret = [7u8; 32]; + let cfg = CoreConfig { data_dir: data.clone(), role: Role::Pc, self_id: device_id_from_secret(&secret), device_name: "PC".into(), app_version: "test".into() }; + let (core, _rx) = Core::open(cfg, Arc::new(SystemClock), place.clone()).unwrap(); + let lib = Library::open(core.clone(), place, data, LibraryConfig::default(), &root, LibraryOptions::default(), Box::new(|_| {})).unwrap(); + let now = Instant::now(); + lib.scan_at(false, now); + lib.scan_at(false, now + Duration::from_secs(3)); + Rig { _tmp: tmp, core, lib, root, src } + } + + fn inbox(&self) -> DropTarget { + let (id, kind, name) = self.core.live_folders().unwrap().into_iter().find(|(_, k, _)| *k == FolderKind::Inbox).unwrap(); + DropTarget { id, kind, name } + } + + fn items(&self) -> Vec { + self.core.items(&ItemQuery { limit: 500, ..Default::default() }).unwrap().rows + } + + /// Run a drop on its own thread; a drop that never returns (a device that blocks a read) is a finding. + fn drop_paths(&self, paths: Vec) -> DropReport { + let lib = self.lib.clone(); + let t = self.inbox(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let rep = copy_dropped(&lib, NativeDrop::from_native(&paths), &t, &mut |_| {}); + let _ = tx.send(rep); + }); + rx.recv_timeout(Duration::from_secs(30)).expect("the drop did not return within 30 s (a device path blocked the copy thread)") + } +} + +fn streams_of(p: &Path) -> Option { + std::fs::read_to_string(format!("{}:payload", p.display())).ok() +} + +/// A drag source is another program: it can put any path in a CF_HDROP drop, including NTFS stream +/// paths and device names. None of them may create a stream on a library file, put a name with ':' +/// into the library or a record, or vanish without a line in the report. +#[test] +fn adversarial_020_security_stream_and_device_paths_in_a_drop_never_touch_the_library() { + let r = Rig::new(); + // A user's own file already in the library, and a source file that has a hidden stream. + let own = r.root.join("a.txt"); + std::fs::write(&own, b"mine").unwrap(); + let src = r.src.join("a.txt"); + std::fs::write(&src, b"outer").unwrap(); + std::fs::write(format!("{}:payload", src.display()), b"hidden stream bytes").unwrap(); + let ini = r.src.join("desktop.ini"); + std::fs::write(&ini, b"[.ShellClassInfo]").unwrap(); + std::fs::write(format!("{}:x", ini.display()), b"y").unwrap(); + + let paths = vec![ + PathBuf::from(format!("{}:payload", src.display())), + PathBuf::from(format!("{}:payload:$DATA", src.display())), + PathBuf::from(format!("{}:x", ini.display())), + PathBuf::from(r"\\.\NUL"), + r.src.join("NUL"), + r.src.join("CON.txt"), + ]; + let n = paths.len(); + let rep = r.drop_paths(paths); + eprintln!("drop report: {rep:?}"); + // Silent-failure rule: every dropped path is accounted for. + assert_eq!(rep.copied.len() + rep.refused.len() + rep.failed.len(), n, "a dropped path vanished from the report: {rep:?}"); + // Nothing was hung onto the user's own file as a stream, and its bytes are unchanged. + assert_eq!(std::fs::read(&own).unwrap(), b"mine"); + assert!(streams_of(&own).is_none(), "the drop wrote a stream onto the library's a.txt"); + // No name with ':' anywhere: not on disk, not in a record, not in the report's copied list. + for e in std::fs::read_dir(&r.root).unwrap().flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + assert!(!name.contains(':') && !names::is_refused_name(&name), "the drop made {name:?} in the library"); + } + for it in r.items() { + assert!(!it.name.contains(':'), "a record got the name {:?}", it.name); + assert!(!names::is_refused_name(&it.name), "a record got the refused name {:?}", it.name); + } + for c in &rep.copied { + assert!(!c.contains(':'), "copied as {c:?}"); + } + // The desktop.ini stream path is refused by name, not copied. + assert!(!rep.copied.iter().any(|c| c.to_ascii_lowercase().starts_with("desktop")), "{rep:?}"); + // Device paths never become library files named after a device. + for dev in ["NUL", "CON.txt"] { + assert!(!rep.copied.iter().any(|c| c.eq_ignore_ascii_case(dev)), "a device was copied in as {dev}: {rep:?}"); + } +} diff --git a/apps/desktop/src-tauri/tests/backend_e2e.rs b/apps/desktop/src-tauri/tests/backend_e2e.rs index 7d882dc..ca046ff 100644 --- a/apps/desktop/src-tauri/tests/backend_e2e.rs +++ b/apps/desktop/src-tauri/tests/backend_e2e.rs @@ -270,3 +270,82 @@ async fn a_second_start_on_the_same_profile_keeps_the_identity_and_the_library() assert_eq!(second.items(ItemQuery { limit: 10, ..Default::default() }).unwrap().rows.len(), 1, "no re-import, no duplicate"); second.shutdown().await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn any_file_travels_both_ways_the_pc_marks_what_it_receives_and_a_dropped_file_syncs() { + use tugboat_desktop_lib::{drop::NativeDrop, winfs}; + + let pc = start_pc().await; + let be = &pc.be; + let tmp = tempfile::tempdir().unwrap(); + let (ph, secret) = phone(tmp.path()); + ph.start_network(NetworkConfig { bind: "127.0.0.1:0".parse().unwrap(), mdns: false, secret_key: secret }).await.unwrap(); + let payload = be.pairing_begin().unwrap().payload; + let phone_core = ph.clone(); + let pairing = tokio::spawn(async move { phone_core.pair_with(&payload).await }); + until("the PC shows a code", 10, || !code_events(&pc.out).is_empty()).await; + be.pairing_confirm(true).await.unwrap(); + pairing.await.unwrap().expect("phone paired"); + until("synced", 20, || be.status().state == SyncState::Synced && ph.status().state == SyncState::Synced).await; + + // ----- phone -> PC: a PDF and a file with no extension ----- + let pdf = b"%PDF-1.7 report body".to_vec(); + let make = b"all:\n\techo hi\n".to_vec(); + for (name, bytes) in [("report.pdf", &pdf), ("Makefile", &make)] { + let src = tmp.path().join(format!("src-{name}")); + std::fs::write(&src, bytes).unwrap(); + ph.add_local_file(NewLocalFile { src, name: name.into(), folder: None, captured_at: 1_790_000_000_000, geo: None, thumb: None, how: AddKind::Added, ntfs: None }).unwrap(); + } + until("both files in the library folder", 25, || pc.root.join("report.pdf").exists() && pc.root.join("Makefile").exists()).await; + assert_eq!(std::fs::read(pc.root.join("report.pdf")).unwrap(), pdf); + assert_eq!(std::fs::read(pc.root.join("Makefile")).unwrap(), make); + for n in ["report.pdf", "Makefile"] { + assert_eq!(winfs::read_zone_mark(&pc.root.join(n)).as_deref(), Some(winfs::ZONE_TEXT), "{n} was marked as downloaded when it arrived"); + } + let rows = be.items(ItemQuery { limit: 100, ..Default::default() }).unwrap().rows; + let r = rows.iter().find(|i| i.name == "report.pdf").unwrap(); + assert_eq!((r.kind, r.ext.as_str()), (tugboat_core::MediaKind::File, "pdf")); + assert_eq!(rows.iter().find(|i| i.name == "Makefile").unwrap().ext, ""); + // Open / Show in Explorer work for any held file inside the library, whatever its type. + for (name, item) in [("report.pdf", r), ("Makefile", rows.iter().find(|i| i.name == "Makefile").unwrap())] { + let p = be.item_path(item.id).unwrap_or_else(|e| panic!("{name}: {e:?}")); + assert!(tugboat_desktop_lib::library::placement::same_path(&p, &pc.root.join(name)), "{name}: {}", p.display()); + } + + // ----- PC -> phone: a Word file and a file with no extension put in the folder by the user ----- + let docx = b"PK docx bytes".to_vec(); + std::fs::write(pc.root.join("contract.docx"), &docx).unwrap(); + std::fs::write(pc.root.join("README"), b"read me").unwrap(); + let phone_rows = || ph.items(&ItemQuery { limit: 100, ..Default::default() }).unwrap().rows; + until("the phone has both", 30, || ["contract.docx", "README"].iter().all(|n| phone_rows().iter().any(|r| r.name == *n))).await; + let docx_item = phone_rows().into_iter().find(|r| r.name == "contract.docx").unwrap(); + assert_eq!(docx_item.kind, tugboat_core::MediaKind::File); + until("the phone holds the docx bytes", 20, || ph.item(docx_item.id).unwrap().is_some_and(|v| v.path.is_some())).await; + assert_eq!(std::fs::read(ph.item(docx_item.id).unwrap().unwrap().path.unwrap()).unwrap(), docx); + assert!(winfs::read_zone_mark(&pc.root.join("contract.docx")).is_none(), "the user's own file gets no mark"); + + // ----- a shortcut in the folder never leaves the PC and is listed ----- + std::fs::write(pc.root.join("evil.lnk"), b"x").unwrap(); + be.library_rescan(); + until("the shortcut is listed as refused", 15, || be.library_status().not_synced.iter().any(|n| n.name == "evil.lnk" && n.reason.starts_with("REFUSED"))).await; + + // ----- a file dropped on the window: copied in, synced to the phone, source untouched ----- + let usb = tmp.path().join("usb"); + std::fs::create_dir_all(&usb).unwrap(); + let dropped = usb.join("dropped.pdf"); + std::fs::write(&dropped, b"%PDF-1.4 dropped").unwrap(); + let rep = be.drop_files(NativeDrop::from_native(std::slice::from_ref(&dropped))); + assert_eq!(rep.copied, ["dropped.pdf"], "{rep:?}"); + assert!(dropped.exists(), "the source is never touched"); + assert!(pc.root.join("dropped.pdf").is_file()); + until("the phone has the dropped pdf", 30, || phone_rows().iter().any(|r| r.name == "dropped.pdf")).await; + assert!(!phone_rows().iter().any(|r| r.name == "evil.lnk"), "a refused shortcut never reached the phone"); + { + let evs = pc.out.events.lock().unwrap(); + assert!(evs.iter().any(|(n, v)| n == ev::DROP_RESULT && v["copied"][0] == "dropped.pdf"), "the UI got the result"); + assert!(evs.iter().any(|(n, v)| n == ev::DROP_STATE && v["t"] == "leave")); + } + + ph.stop_network().await; + be.shutdown().await; +} diff --git a/apps/desktop/src-tauri/tests/versions.rs b/apps/desktop/src-tauri/tests/versions.rs new file mode 100644 index 0000000..762c2d6 --- /dev/null +++ b/apps/desktop/src-tauri/tests/versions.rs @@ -0,0 +1,18 @@ +//! One version everywhere: the crate, `tauri.conf.json` and `package.json`. The GitHub release +//! workflow compares them with the tag and fails the build when they differ; this fails earlier. + +use std::path::Path; + +fn json(rel: &str) -> serde_json::Value { + let p = Path::new(env!("CARGO_MANIFEST_DIR")).join(rel); + serde_json::from_str(&std::fs::read_to_string(&p).unwrap_or_else(|e| panic!("{}: {e}", p.display()))).unwrap() +} + +#[test] +fn the_crate_tauri_config_and_package_json_all_say_the_same_version() { + let krate = env!("CARGO_PKG_VERSION"); + let tauri = json("tauri.conf.json")["version"].as_str().unwrap().to_string(); + let package = json("../package.json")["version"].as_str().unwrap().to_string(); + assert_eq!(tauri, krate, "tauri.conf.json vs the crate"); + assert_eq!(package, krate, "package.json vs the crate"); +} diff --git a/apps/desktop/src/App.svelte b/apps/desktop/src/App.svelte index 292f0fe..e2a6247 100644 --- a/apps/desktop/src/App.svelte +++ b/apps/desktop/src/App.svelte @@ -9,6 +9,7 @@ import Banners from "./lib/Banners.svelte"; import Bin from "./lib/Bin.svelte"; import Dialog from "./lib/Dialog.svelte"; + import DropOverlay from "./lib/DropOverlay.svelte"; import Gallery from "./lib/Gallery.svelte"; import Mark from "./lib/Mark.svelte"; import Pair from "./lib/Pair.svelte"; @@ -77,6 +78,8 @@ + +

{app.cloudPrompt?.message ?? ""}

Photos in a cloud folder are uploaded to the internet. Tugboat is meant to stay on your network.

@@ -94,10 +97,10 @@
-

These files are in the library folder but are not photos or videos, so they stay on this PC.

+

These files are not synced. The reason is on each line.

    - {#each app.library?.not_synced ?? [] as f (f.path)} -
  • {f.name} {f.reason}
    {f.path}
  • + {#each app.library?.not_synced ?? [] as f, i (i)} +
  • {f.name} {f.reason}{#if f.path}
    {f.path}{/if}
  • {:else}
  • Nothing left.
  • {/each} diff --git a/apps/desktop/src/lib/Banners.svelte b/apps/desktop/src/lib/Banners.svelte index dd86444..0f993e3 100644 --- a/apps/desktop/src/lib/Banners.svelte +++ b/apps/desktop/src/lib/Banners.svelte @@ -5,7 +5,7 @@ import { computeBanners, type BannerAction } from "./banners"; import { shortPath } from "./format"; - const banners = $derived(computeBanners({ info: app.info, sync: app.sync, library: app.library, firewall: app.firewall, error: app.error })); + const banners = $derived(computeBanners({ info: app.info, sync: app.sync, library: app.library, firewall: app.firewall, error: app.error, drop: app.dropReport })); const run: Record unknown> = { "fw-fix": () => @@ -21,6 +21,7 @@ "lib-choose": chooseLibrary, "not-synced": () => (app.notSyncedOpen = true), "dismiss-error": () => (app.error = null), + "dismiss-drop": () => (app.dropReport = null), }; @@ -30,10 +31,15 @@ {/each} @@ -53,6 +59,14 @@ padding: 6px 10px; border: 1px solid; border-radius: 8px; + flex-wrap: wrap; + } + .lines { + flex: 1 0 100%; + margin: 0; + padding: 0 0 0 24px; + max-height: 5.5em; + overflow-y: auto; } .banner.danger { background: var(--danger-bg); diff --git a/apps/desktop/src/lib/Bin.svelte b/apps/desktop/src/lib/Bin.svelte index d112a7a..3478b9a 100644 --- a/apps/desktop/src/lib/Bin.svelte +++ b/apps/desktop/src/lib/Bin.svelte @@ -4,7 +4,7 @@ import { api } from "./api"; import { act, app } from "./app.svelte"; import Chip from "./Chip.svelte"; - import { binLabel, fmtSize } from "./format"; + import { binLabel, fmtSize, peerNote } from "./format"; import ItemGrid from "./ItemGrid.svelte"; import { PagedItems } from "./paged.svelte"; @@ -63,6 +63,7 @@ {sel.name} {fmtSize(sel.size)} + {#if peerNote(sel)}{/if} diff --git a/apps/desktop/src/lib/DropOverlay.svelte b/apps/desktop/src/lib/DropOverlay.svelte new file mode 100644 index 0000000..54ccea7 --- /dev/null +++ b/apps/desktop/src/lib/DropOverlay.svelte @@ -0,0 +1,68 @@ + + + +
    {over ? [dropTitle(over), dropSub(over)].filter(Boolean).join(". ") : ""}
    + +{#if over} + +{/if} + + diff --git a/apps/desktop/src/lib/Gallery.svelte b/apps/desktop/src/lib/Gallery.svelte index cbac99e..1ea619d 100644 --- a/apps/desktop/src/lib/Gallery.svelte +++ b/apps/desktop/src/lib/Gallery.svelte @@ -2,7 +2,7 @@ import { untrack } from "svelte"; import { ExternalLink, FolderOpen, OctagonAlert, Pin, QrCode, Trash2, WifiOff } from "@lucide/svelte"; import { api } from "./api"; - import { act, app, beginPairing } from "./app.svelte"; + import { act, app, beginPairing, fail } from "./app.svelte"; import { fmtSize, itemLabel, retentionLabel } from "./format"; import Chip from "./Chip.svelte"; import ItemGrid from "./ItemGrid.svelte"; @@ -26,6 +26,13 @@ if (folder !== null && !app.folders.some((f) => f.id === folder)) folder = null; }); + // A file dropped on the window lands in the folder shown here. Only the folder id goes to Rust (never a path); when + // this screen goes away the target is None, so a drop elsewhere says "Copy to Inbox". + $effect(() => { + void api.dropTargetSet(folder).catch(fail); + }); + $effect(() => () => void api.dropTargetSet(null).catch(fail)); + const current = $derived(app.folders.find((f) => f.id === folder) ?? null); const total = $derived(app.folders.reduce((n, f) => n + f.count, 0)); const sel = $derived(list.rows.find((r) => r.id === selectedId) ?? null); @@ -78,20 +85,20 @@ {:else if app.paired === null}

    Pair your phone

    -

    Scan a code with the Tugboat app. Photos then show up here.

    +

    Scan a code with the Tugboat app. Photos and files then show up here.

    {:else if offline}

    Phone offline

    -

    Photos show up here when {app.paired.name} connects.

    +

    Photos and files show up here when {app.paired.name} connects.

    {:else}

    Nothing yet.

    -

    Photos you take on your phone show up here.

    +

    Photos and files from your phone show up here. Drop files here to copy them in.

    {/if} {:else} - itemLabel(it, app.now)} bind:selectedId ariaLabel="Photos and videos" onopen={(it) => act(() => api.openItem(it.id))} onend={() => list.loadMore()} /> + itemLabel(it, app.now)} bind:selectedId ariaLabel="Files" onopen={(it) => act(() => api.openItem(it.id))} onend={() => list.loadMore()} /> {/if} {#if sel} diff --git a/apps/desktop/src/lib/ItemTile.svelte b/apps/desktop/src/lib/ItemTile.svelte index 69f0b8d..a61cea0 100644 --- a/apps/desktop/src/lib/ItemTile.svelte +++ b/apps/desktop/src/lib/ItemTile.svelte @@ -3,7 +3,8 @@ import { thumbUrl } from "./api"; import type { ItemView } from "./api"; import Chip from "./Chip.svelte"; - import { fmtSize, type Label } from "./format"; + import { fileIcon, itemMeta, kindText, peerNote, type Label } from "./format"; + import { fileIcons } from "./icons"; let { item, @@ -25,7 +26,10 @@ // A missing thumbnail (404: nothing held yet, or a format the Shell cannot render) shows an icon. let failed = $state(false); - const Kind = $derived(item.kind === "video" ? Film : ImageIcon); + // Only photos and videos have thumbnails; any other file is a tile with an icon for its type (no thumbnail request at all). + const isFile = $derived(item.kind === "file"); + const Kind = $derived(item.kind === "video" ? Film : isFile ? fileIcons[fileIcon(item.ext)] : ImageIcon); + const note = $derived(peerNote(item)); @@ -105,9 +111,17 @@ font-weight: 600; } .meta { + max-width: calc(100% - 16px); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; color: var(--fg-muted); font-size: 12px; } + .peer { + color: var(--warn); + font-weight: 600; + } .tile.selected .meta { color: var(--fg-muted); } diff --git a/apps/desktop/src/lib/Pair.svelte b/apps/desktop/src/lib/Pair.svelte index ef80688..e058ab5 100644 --- a/apps/desktop/src/lib/Pair.svelte +++ b/apps/desktop/src/lib/Pair.svelte @@ -1,7 +1,7 @@
    @@ -14,6 +17,15 @@ {:else} Starting {/if} + + {#if progress} + + {dropProgressText(progress)} + + + {:else if note} + {note} + {/if} {#if app.info}v{app.info.version}{/if}
    @@ -48,6 +60,21 @@ .state.danger { color: var(--danger); } + .drop { + display: inline-flex; + align-items: center; + gap: 8px; + min-width: 0; + } + .dtext { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + progress { + width: 120px; + accent-color: var(--accent); + } .grow { flex: 1; } diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts index 88fb3e8..971ccff 100644 --- a/apps/desktop/src/lib/api.ts +++ b/apps/desktop/src/lib/api.ts @@ -12,6 +12,9 @@ import { open } from "@tauri-apps/plugin-dialog"; import type { ActivityEntry } from "./bindings/ActivityEntry"; import type { AppInfo } from "./bindings/AppInfo"; import type { CmdError } from "./bindings/CmdError"; +import type { DropProgress } from "./bindings/DropProgress"; +import type { DropReport } from "./bindings/DropReport"; +import type { DropState } from "./bindings/DropState"; import type { Event as CoreEvent } from "./bindings/Event"; import type { FirewallInfo } from "./bindings/FirewallInfo"; import type { FolderId } from "./bindings/FolderId"; @@ -28,7 +31,7 @@ import type { SyncStatus } from "./bindings/SyncStatus"; import type { TrayState } from "./bindings/TrayState"; export type { - ActivityEntry, AppInfo, CmdError, CoreEvent, FirewallInfo, FolderId, FolderView, ItemId, ItemQuery, + ActivityEntry, AppInfo, CmdError, CoreEvent, DropProgress, DropReport, DropState, FirewallInfo, FolderId, FolderView, ItemId, ItemQuery, ItemView, LibraryStatus, Page, PairedDevice, PairingStart, Settings, SyncStatus, TrayState, }; @@ -96,6 +99,9 @@ export const api = { libraryRescan: () => call("library_rescan"), libraryOpenFolder: () => call("library_open_folder"), + /** The gallery's current folder (null = All = Inbox): where a file dropped on the window lands. A folder id, never a path. */ + dropTargetSet: (folder: FolderId | null) => call("drop_target_set", { folder }), + // Windows Firewall firewallStatus: () => call("firewall_status"), firewallRecheck: () => call("firewall_recheck"), @@ -111,6 +117,9 @@ export const EVENTS = { firewall: "firewall-status", resync: "resync", tray: "tray-state", + dropState: "drop-state", + dropProgress: "drop-progress", + dropResult: "drop-result", } as const; /** Core events: sync status, items/folders changed, pairing steps, errors. */ @@ -118,6 +127,10 @@ export const onCoreEvent = (cb: (e: CoreEvent) => void): Promise => export const onLibraryStatus = (cb: (s: LibraryStatus) => void): Promise => listen(EVENTS.library, (m) => cb(m.payload)); export const onFirewallStatus = (cb: (s: FirewallInfo) => void): Promise => listen(EVENTS.firewall, (m) => cb(m.payload)); export const onTrayState = (cb: (s: TrayState) => void): Promise => listen(EVENTS.tray, (m) => cb(m.payload)); +/** Files dragged over the window (the overlay) and what a drop did. Rust sends them from the window's native drag-drop event. */ +export const onDropState = (cb: (s: DropState) => void): Promise => listen(EVENTS.dropState, (m) => cb(m.payload)); +export const onDropProgress = (cb: (p: DropProgress) => void): Promise => listen(EVENTS.dropProgress, (m) => cb(m.payload)); +export const onDropResult = (cb: (r: DropReport) => void): Promise => listen(EVENTS.dropResult, (m) => cb(m.payload)); /** The event stream lagged: re-read everything the screen shows. */ export const onResync = (cb: () => void): Promise => listen(EVENTS.resync, () => cb()); diff --git a/apps/desktop/src/lib/app.svelte.ts b/apps/desktop/src/lib/app.svelte.ts index b8d6490..ed98e72 100644 --- a/apps/desktop/src/lib/app.svelte.ts +++ b/apps/desktop/src/lib/app.svelte.ts @@ -5,8 +5,9 @@ // Events carry ids, not rows, so a screen that shows rows watches `app.itemsRev` / `activityRev` // and re-reads. If the event stream lags (`resync`) everything is re-read. -import { api, ApiError, onCoreEvent, onFirewallStatus, onLibraryStatus, onResync, pickFolder } from "./api"; -import type { AppInfo, FirewallInfo, FolderView, LibraryStatus, PairedDevice, Settings, SyncStatus } from "./api"; +import { api, ApiError, onCoreEvent, onDropProgress, onDropResult, onDropState, onFirewallStatus, onLibraryStatus, onResync, pickFolder } from "./api"; +import type { AppInfo, DropProgress, DropReport, FirewallInfo, FolderView, LibraryStatus, PairedDevice, Settings, SyncStatus } from "./api"; +import { dropBanner, dropSummary, type DropEnter } from "./drop"; import { nextPairPhase, type PairInput, type PairPhase } from "./pairing"; export type Screen = "gallery" | "bin" | "activity" | "pair" | "settings"; @@ -32,8 +33,34 @@ export const app = $state({ notSyncedOpen: false, itemsRev: 0, activityRev: 0, + /** Files dragged onto the window: the overlay (`over`), the copy in progress and the success line. */ + drop: { + over: null as DropEnter | null, + progress: null as DropProgress | null, + /** Progress shows only for a copy that runs longer than 300 ms. */ + showProgress: false, + note: null as { text: string; until: number } | null, + }, + /** What the last drop left behind (refused or failed files): a banner until dismissed. */ + dropReport: null as DropReport | null, }); +const PROGRESS_AFTER_MS = 300; +const NOTE_FOR_MS = 5000; +let progressTimer: ReturnType | undefined; + +function dropFinished(r: DropReport): void { + clearTimeout(progressTimer); + progressTimer = undefined; + app.drop.over = null; + app.drop.progress = null; + app.drop.showProgress = false; + const text = dropSummary(r); + app.drop.note = text === null ? null : { text, until: Date.now() + NOTE_FOR_MS }; + // A refused or failed file is never silent: the banner stays until the user dismisses it. + app.dropReport = dropBanner(r) === null ? app.dropReport : r; +} + /** Show a failure as the red banner. Errors are never swallowed. */ export function fail(e: unknown): void { app.error = e instanceof ApiError ? { kind: e.kind, message: e.message } : { kind: "unknown", message: e instanceof Error ? e.message : String(e) }; @@ -91,7 +118,10 @@ export async function start(): Promise<() => void> { switch (e.t) { case "sync": { const { t: _t, ...s } = e; + const changed = app.sync?.state !== s.state; app.sync = s; + // The core writes "last seen" at the first hello and when a session ends: re-read it on every state change. + if (changed) refreshPaired(); break; } case "items_changed": @@ -120,12 +150,19 @@ export async function start(): Promise<() => void> { } }), await onLibraryStatus((s) => (app.library = s)), + await onDropState((s) => (app.drop.over = s.t === "enter" ? s : null)), + await onDropProgress((p) => { + if (app.drop.progress === null) progressTimer = setTimeout(() => (app.drop.showProgress = true), PROGRESS_AFTER_MS); + app.drop.progress = p; + }), + await onDropResult(dropFinished), await onFirewallStatus((s) => (app.firewall = s)), await onResync(() => void reload()), ); await reload(); const timer = setInterval(() => { app.now = Date.now(); + if (app.drop.note !== null && app.now >= app.drop.note.until) app.drop.note = null; const p = app.pairing; // The QR stops working at expires_at (PC clock = this clock): close the window now rather // than leave a dead code on screen. diff --git a/apps/desktop/src/lib/banners.test.ts b/apps/desktop/src/lib/banners.test.ts index e8e6c15..0240028 100644 --- a/apps/desktop/src/lib/banners.test.ts +++ b/apps/desktop/src/lib/banners.test.ts @@ -3,14 +3,15 @@ import { computeBanners, type BannerInput } from "./banners"; import type { LibraryStatus } from "./bindings/LibraryStatus"; const lib = (over: Partial = {}): LibraryStatus => ({ - path: "C:\\Snap", health: { t: "ready" }, message: null, cloud_warning: null, not_synced: [], last_scan_at: null, last_error: null, ...over, + path: "C:\\Snap", health: { t: "ready" }, message: null, cloud_warning: null, not_synced: [], cannot_mark: false, last_scan_at: null, last_error: null, ...over, }); const base: BannerInput = { info: { version: "0.1.0", device_name: "PC", bind: "127.0.0.1:47300", network_error: null, data_dir: "C:\\d" }, - sync: { state: "synced", peer_name: "Pixel", last_synced_at: 1, waiting: 0, downloading: 0, message: null }, + sync: { state: "synced", peer_name: "Pixel", last_synced_at: 1, waiting: 0, downloading: 0, storage_low: false, message: null }, library: lib(), firewall: { status: { t: "ok" }, message: null, can_fix: false }, error: null, + drop: null, }; const ids = (i: BannerInput) => computeBanners(i).map((b) => b.id); @@ -19,7 +20,7 @@ describe("computeBanners", () => { expect(computeBanners(base)).toEqual([]); }); test("nothing loaded yet shows nothing", () => { - expect(computeBanners({ info: null, sync: null, library: null, firewall: null, error: null })).toEqual([]); + expect(computeBanners({ info: null, sync: null, library: null, firewall: null, error: null, drop: null })).toEqual([]); }); test("firewall problem: Fix only when it can help, always a recheck", () => { const fw = (can_fix: boolean) => ({ ...base, firewall: { status: { t: "rule_missing" as const }, message: "WINDOWS FIREWALL is blocking Tugboat", can_fix } }); @@ -44,7 +45,7 @@ describe("computeBanners", () => { test("cloud folder, scan error and not-synced are warnings", () => { const b = computeBanners({ ...base, - library: lib({ cloud_warning: "OneDrive", last_error: "locked", not_synced: [{ path: "a.txt", name: "a.txt", reason: "NOT A PHOTO OR VIDEO" }] }), + library: lib({ cloud_warning: "OneDrive", last_error: "locked", not_synced: [{ path: "a.txt", name: "a.txt", reason: "REFUSED - shortcut and folder-setting files never sync" }] }), }); expect(b.map((x) => [x.id, x.tone])).toEqual([["cloud", "warn"], ["scan-error", "warn"], ["not-synced", "warn"]]); expect(b[2]?.text).toBe("1 file NOT SYNCED"); @@ -56,11 +57,34 @@ describe("computeBanners", () => { const b = computeBanners({ ...base, sync: { ...base.sync!, state: "refused", message: "Update Tugboat on the PC" } }); expect(b[0]).toMatchObject({ id: "refused", tone: "danger", text: "SYNC REFUSED - Update Tugboat on the PC" }); }); + test("a refusal is said once: not again as an error banner", () => { + const sync = { ...base.sync!, state: "refused" as const, message: "Update Tugboat on the phone" }; + expect(ids({ ...base, sync, error: { kind: "refused", message: "Update Tugboat on the phone" } })).toEqual(["refused"]); + expect(ids({ ...base, sync, error: { kind: "x", message: "ERROR text: Update Tugboat on the phone" } })).toEqual(["refused"]); + expect(ids({ ...base, error: { kind: "refused", message: "REFUSED - shortcut files never sync" } })).toEqual([]); + expect(ids({ ...base, sync, error: { kind: "x", message: "disk full" } })).toEqual(["refused", "error"]); + }); test("network down and a core error", () => { const b = computeBanners({ ...base, info: { ...base.info!, network_error: "port 47300 in use" }, error: { kind: "x", message: "disk full" } }); expect(b.map((x) => x.id)).toEqual(["network", "error"]); expect(b[0]?.text).toBe("NETWORK DOWN - port 47300 in use"); }); + test("a drive that cannot hold the Mark-of-the-Web is a blocker with the count of waiting files", () => { + const b = computeBanners({ ...base, library: lib({ cannot_mark: true }), sync: { ...base.sync!, downloading: 4 } }); + expect(b[0]).toMatchObject({ id: "cannot-mark", tone: "danger", text: "LIBRARY DRIVE CANNOT MARK DOWNLOADS - files from the phone wait (4)" }); + expect(computeBanners({ ...base, library: lib({ cannot_mark: true }) })[0]?.text).toBe("LIBRARY DRIVE CANNOT MARK DOWNLOADS - files from the phone wait"); + expect(b[0]?.actions.map((a) => a.id)).toEqual(["lib-choose"]); + }); + test("a drop that left files behind stays as a banner until dismissed; a clean drop shows none", () => { + const clean = { folder_name: "Inbox", copied: ["a.pdf"], refused: [], failed: [] }; + expect(computeBanners({ ...base, drop: clean })).toEqual([]); + const b = computeBanners({ ...base, drop: { ...clean, refused: [{ name: "x.lnk", reason: "REFUSED - shortcut and folder-setting files never sync" }] } }); + expect(b).toHaveLength(1); + expect(b[0]).toMatchObject({ id: "drop", tone: "warn", text: "REFUSED - shortcut and folder-setting files never sync", detail: "x.lnk" }); + expect(b[0]?.actions.map((a) => a.id)).toEqual(["dismiss-drop"]); + const failed = computeBanners({ ...base, drop: { ...clean, failed: [{ name: "big.mp4", reason: "COPY FAILED - The device is not ready." }] } }); + expect(failed[0]?.tone).toBe("danger"); + }); test("blockers come before warnings", () => { const b = computeBanners({ ...base, library: lib({ cloud_warning: "OneDrive" }), firewall: { status: { t: "all_inbound_blocked" }, message: null, can_fix: false } }); expect(b.map((x) => x.id)).toEqual(["firewall", "cloud"]); diff --git a/apps/desktop/src/lib/banners.ts b/apps/desktop/src/lib/banners.ts index a6e16cf..52979b9 100644 --- a/apps/desktop/src/lib/banners.ts +++ b/apps/desktop/src/lib/banners.ts @@ -2,11 +2,13 @@ // maps each action id to a call. One short line each, uppercase key word for blockers. import type { AppInfo } from "./bindings/AppInfo"; +import type { DropReport } from "./bindings/DropReport"; import type { FirewallInfo } from "./bindings/FirewallInfo"; import type { LibraryStatus } from "./bindings/LibraryStatus"; import type { SyncStatus } from "./bindings/SyncStatus"; +import { dropBanner } from "./drop"; -export type BannerAction = "fw-fix" | "fw-recheck" | "lib-locate" | "lib-rescan" | "lib-bin" | "lib-wait" | "lib-choose" | "not-synced" | "dismiss-error"; +export type BannerAction = "fw-fix" | "fw-recheck" | "lib-locate" | "lib-rescan" | "lib-bin" | "lib-wait" | "lib-choose" | "not-synced" | "dismiss-error" | "dismiss-drop"; export interface Banner { id: string; @@ -15,6 +17,10 @@ export interface Banner { text: string; /** Long detail (a path) shown shortened on the same line, in full as a tooltip. */ detail?: string; + /** The detail is plain text (file names), not a path: normal font, no shortening. */ + plain?: boolean; + /** One short line per item under the banner text (a drop with different reasons per file). */ + lines?: string[]; actions: Array<{ id: BannerAction; label: string }>; } @@ -25,6 +31,8 @@ export interface BannerInput { firewall: FirewallInfo | null; /** The last core "error" event, until dismissed. */ error: { kind: string; message: string } | null; + /** The last drop that left files behind (refused or failed), until dismissed. */ + drop: DropReport | null; } export function computeBanners(i: BannerInput): Banner[] { @@ -60,6 +68,11 @@ export function computeBanners(i: BannerInput): Banner[] { actions: [{ id: "lib-bin", label: "Move them to the Bin" }, { id: "lib-wait", label: "Keep waiting" }], }); } + if (lib.cannot_mark) { + // Received files are marked as downloaded; this drive cannot hold the mark, so they wait here instead of being saved unmarked. + const n = i.sync?.downloading ?? 0; + out.push({ id: "cannot-mark", tone: "danger", text: `LIBRARY DRIVE CANNOT MARK DOWNLOADS - files from the phone wait${n > 0 ? ` (${n})` : ""}`, actions: [{ id: "lib-choose", label: "Choose another" }] }); + } if (lib.cloud_warning) { out.push({ id: "cloud", tone: "warn", text: `CLOUD FOLDER - ${lib.cloud_warning}`, actions: [{ id: "lib-choose", label: "Choose another" }] }); } @@ -74,7 +87,14 @@ export function computeBanners(i: BannerInput): Banner[] { if (i.sync?.state === "refused") { out.push({ id: "refused", tone: "danger", text: `SYNC REFUSED${i.sync.message ? ` - ${i.sync.message}` : ""}`, actions: [] }); } - if (i.error) { + const drop = i.drop ? dropBanner(i.drop) : null; + if (drop) { + out.push({ id: "drop", tone: drop.tone, text: drop.text, detail: drop.detail, plain: true, lines: drop.lines, actions: [{ id: "dismiss-drop", label: "Dismiss" }] }); + } + // The same words twice (the core's error event repeats what the SYNC REFUSED banner already says): show once. + const refusedText = i.sync?.state === "refused" ? i.sync.message : null; + // A refused file already has its own Not synced row and banner: its error event adds nothing. + if (i.error && i.error.kind !== "refused" && !(refusedText && i.error.message.includes(refusedText))) { out.push({ id: "error", tone: "danger", text: `ERROR - ${i.error.message}`, actions: [{ id: "dismiss-error", label: "Dismiss" }] }); } // Blockers first; the sort is stable, so each group keeps the order above. diff --git a/apps/desktop/src/lib/bindings/DropLine.ts b/apps/desktop/src/lib/bindings/DropLine.ts new file mode 100644 index 0000000..e7b3093 --- /dev/null +++ b/apps/desktop/src/lib/bindings/DropLine.ts @@ -0,0 +1,7 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type DropLine = { +/** + * Empty when the line is about the whole drop. + */ +name: string, reason: string, }; diff --git a/apps/desktop/src/lib/bindings/DropProgress.ts b/apps/desktop/src/lib/bindings/DropProgress.ts new file mode 100644 index 0000000..7b291a5 --- /dev/null +++ b/apps/desktop/src/lib/bindings/DropProgress.ts @@ -0,0 +1,7 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type DropProgress = { file: string, +/** + * 1-based position among the files being copied. + */ +index: number, count: number, done_bytes: number, total_bytes: number, }; diff --git a/apps/desktop/src/lib/bindings/DropReport.ts b/apps/desktop/src/lib/bindings/DropReport.ts new file mode 100644 index 0000000..113c751 --- /dev/null +++ b/apps/desktop/src/lib/bindings/DropReport.ts @@ -0,0 +1,11 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DropLine } from "./DropLine"; + +/** + * What a drop did. `refused` = Tugboat will not take it; `failed` = it tried and could not. + */ +export type DropReport = { folder_name: string, +/** + * Names the files have in the library now. + */ +copied: Array, refused: Array, failed: Array, }; diff --git a/apps/desktop/src/lib/bindings/DropState.ts b/apps/desktop/src/lib/bindings/DropState.ts new file mode 100644 index 0000000..0b200b0 --- /dev/null +++ b/apps/desktop/src/lib/bindings/DropState.ts @@ -0,0 +1,6 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Sent while files are dragged over the window: the overlay names the target. + */ +export type DropState = { "t": "enter", files: number, folders: number, target_name: string, } | { "t": "leave" }; diff --git a/apps/desktop/src/lib/bindings/ItemState.ts b/apps/desktop/src/lib/bindings/ItemState.ts index 1dcf163..b3a75ef 100644 --- a/apps/desktop/src/lib/bindings/ItemState.ts +++ b/apps/desktop/src/lib/bindings/ItemState.ts @@ -3,4 +3,4 @@ /** * Derived expiry/Bin state of an item (computed by `expiry::item_state`, never stored). */ -export type ItemState = { "t": "deleted", binned_at: number, } | { "t": "expired", binned_at: number, } | { "t": "kept" } | { "t": "folder_keep" } | { "t": "waiting" } | { "t": "live", expires_at: number, }; +export type ItemState = { "t": "deleted", binned_at: number, } | { "t": "expired", binned_at: number, } | { "t": "kept" } | { "t": "folder_keep" } | { "t": "live", expires_at: number, }; diff --git a/apps/desktop/src/lib/bindings/ItemView.ts b/apps/desktop/src/lib/bindings/ItemView.ts index 9c86b19..ac55b27 100644 --- a/apps/desktop/src/lib/bindings/ItemView.ts +++ b/apps/desktop/src/lib/bindings/ItemView.ts @@ -12,6 +12,11 @@ export type ItemView = { id: ItemId, name: string, folder: FolderId, kind: Media */ path: string | null, /** - * Local path of the thumbnail, when held. + * Local path of the thumbnail, when held. Always None for a File. */ -thumb_path: string | null, }; +thumb_path: string | null, +/** + * In the Bin because it EXPIRED, and the paired device never confirmed holding this file: + * the item may now exist on this device only (shown as "NOT ON PC" / "NOT ON PHONE"). + */ +never_reached_peer: boolean, }; diff --git a/apps/desktop/src/lib/bindings/LibraryStatus.ts b/apps/desktop/src/lib/bindings/LibraryStatus.ts index f9c773b..b0cfc97 100644 --- a/apps/desktop/src/lib/bindings/LibraryStatus.ts +++ b/apps/desktop/src/lib/bindings/LibraryStatus.ts @@ -10,7 +10,12 @@ message: string | null, /** * Set when the library folder looks cloud-synced. */ -cloud_warning: string | null, not_synced: Array, last_scan_at: number | null, +cloud_warning: string | null, not_synced: Array, +/** + * The library drive cannot keep the Mark-of-the-Web (FAT, exFAT): files from the phone wait + * instead of being saved unmarked. + */ +cannot_mark: boolean, last_scan_at: number | null, /** * The first error of the last scan (an unreadable folder, a locked file), if any. */ diff --git a/apps/desktop/src/lib/bindings/MediaKind.ts b/apps/desktop/src/lib/bindings/MediaKind.ts index 261f30b..ac58668 100644 --- a/apps/desktop/src/lib/bindings/MediaKind.ts +++ b/apps/desktop/src/lib/bindings/MediaKind.ts @@ -1,3 +1,3 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type MediaKind = "image" | "video"; +export type MediaKind = "image" | "video" | "file"; diff --git a/apps/desktop/src/lib/bindings/NotSyncedFile.ts b/apps/desktop/src/lib/bindings/NotSyncedFile.ts index e000aea..fc1125b 100644 --- a/apps/desktop/src/lib/bindings/NotSyncedFile.ts +++ b/apps/desktop/src/lib/bindings/NotSyncedFile.ts @@ -5,6 +5,6 @@ */ export type NotSyncedFile = { path: string, name: string, /** - * One short line, uppercase key word ("NOT A PHOTO OR VIDEO"). + * One short line, uppercase key word ("REFUSED - ...", "IN PROGRESS - ..."). */ reason: string, }; diff --git a/apps/desktop/src/lib/bindings/SyncStatus.ts b/apps/desktop/src/lib/bindings/SyncStatus.ts index 8a6557c..4739dea 100644 --- a/apps/desktop/src/lib/bindings/SyncStatus.ts +++ b/apps/desktop/src/lib/bindings/SyncStatus.ts @@ -7,13 +7,18 @@ export type SyncStatus = { state: SyncState, peer_name: string | null, */ last_synced_at: number | null, /** - * Items in state Waiting (not confirmed by the other device). + * Items held here (not in the Bin) that the paired device has not confirmed holding yet + * ("PC not found, 3 waiting"). 0 while unpaired. Expiry never waits for them (0.2.0). */ waiting: number, /** - * Downloads queued. + * Items that wait on the other device: Pending here (queued downloads). */ downloading: number, +/** + * Phone: the storage guard (`Settings.storage_guard_bytes`) is holding downloads back. + */ +storage_low: boolean, /** * One short line for Refused/Paused ("Update Tugboat on the PC"). */ diff --git a/apps/desktop/src/lib/drop.test.ts b/apps/desktop/src/lib/drop.test.ts new file mode 100644 index 0000000..5e60d86 --- /dev/null +++ b/apps/desktop/src/lib/drop.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, test } from "bun:test"; +import { dropBanner, dropPercent, dropProblems, dropProgressText, dropSub, dropSummary, dropTitle, type DropEnter } from "./drop"; +import type { DropReport } from "./bindings/DropReport"; + +const report = (over: Partial = {}): DropReport => ({ folder_name: "Inbox", copied: [], refused: [], failed: [], ...over }); +const enter = (over: Partial = {}): DropEnter => ({ t: "enter", files: 2, folders: 0, target_name: "Inbox", ...over }); + +describe("the drop overlay", () => { + test("names the target folder", () => { + expect(dropTitle(enter())).toBe("Copy to Inbox"); + expect(dropTitle(enter({ target_name: "Work" }))).toBe("Copy to Work"); + }); + test("a folder next to files gets one warning line, files alone get none", () => { + expect(dropSub(enter())).toBeNull(); + expect(dropSub(enter({ folders: 1 }))).toBe("FOLDERS NOT COPIED - drop the files inside it"); + }); + test("only folders: the blocker is the headline, no copy promised", () => { + expect(dropTitle(enter({ files: 0, folders: 2 }))).toBe("FOLDERS NOT COPIED - drop the files inside it"); + expect(dropSub(enter({ files: 0, folders: 2 }))).toBeNull(); + expect(dropTitle(enter({ files: 1, folders: 2 }))).toBe("Copy to Inbox"); + }); +}); + +describe("progress", () => { + const p = (done: number, total: number, index = 1, count = 1) => ({ file: "big.mp4", index, count, done_bytes: done, total_bytes: total }); + test("percent rounds down, never passes 100 and is null for an unknown size", () => { + expect(dropPercent(p(0, 100))).toBe(0); + expect(dropPercent(p(999, 1000))).toBe(99); + expect(dropPercent(p(1000, 1000))).toBe(100); + expect(dropPercent(p(2000, 1000))).toBe(100); + expect(dropPercent(p(5, 0))).toBeNull(); + }); + test("the line names the file, its place in the queue and the percent", () => { + expect(dropProgressText(p(500, 1000))).toBe("Copying big.mp4, 50%"); + expect(dropProgressText(p(500, 1000, 2, 3))).toBe("Copying big.mp4 (2 of 3), 50%"); + expect(dropProgressText(p(5, 0))).toBe("Copying big.mp4"); + }); +}); + +describe("the result", () => { + test("a success line only when something was copied", () => { + expect(dropSummary(report({ copied: ["a.pdf", "b.pdf", "c.pdf"] }))).toBe("3 copied to Inbox"); + expect(dropSummary(report({ copied: ["a.pdf"], folder_name: "Work" }))).toBe("1 copied to Work"); + expect(dropSummary(report())).toBeNull(); + }); + test("a clean drop has no banner", () => { + expect(dropBanner(report({ copied: ["a.pdf"] }))).toBeNull(); + }); + test("one refused file: its own reason as the text, the name as the detail, a warning", () => { + const b = dropBanner(report({ refused: [{ name: "x.lnk", reason: "REFUSED - shortcut and folder-setting files never sync" }] })); + expect(b).toEqual({ tone: "warn", text: "REFUSED - shortcut and folder-setting files never sync", detail: "x.lnk" }); + }); + test("the same reason for several files stays one line with all the names", () => { + const b = dropBanner(report({ refused: [{ name: "a", reason: "FOLDERS NOT COPIED - drop the files inside it" }, { name: "b", reason: "FOLDERS NOT COPIED - drop the files inside it" }] })); + expect(b).toMatchObject({ text: "FOLDERS NOT COPIED - drop the files inside it", detail: "a, b" }); + }); + test("different reasons are counted with one line per file and its own reason; any failure makes it red", () => { + const b = dropBanner(report({ refused: [{ name: "a.lnk", reason: "REFUSED" }], failed: [{ name: "big.mp4", reason: "COPY FAILED - The device is not ready." }] })); + expect(b).toEqual({ tone: "danger", text: "2 FILES NOT COPIED", lines: ["a.lnk: REFUSED", "big.mp4: COPY FAILED - The device is not ready."] }); + }); + test("a whole-drop line has no name and no detail", () => { + const b = dropBanner(report({ refused: [{ name: "", reason: "PAUSED - nothing copied" }] })); + expect(b).toEqual({ tone: "warn", text: "PAUSED - nothing copied", detail: undefined }); + expect(dropProblems(report({ refused: [{ name: "", reason: "x" }], failed: [{ name: "f", reason: "y" }] })).map((l) => l.reason)).toEqual(["x", "y"]); + }); +}); diff --git a/apps/desktop/src/lib/drop.ts b/apps/desktop/src/lib/drop.ts new file mode 100644 index 0000000..8f8f2c9 --- /dev/null +++ b/apps/desktop/src/lib/drop.ts @@ -0,0 +1,50 @@ +// Pure text for dragging files onto the window: the overlay, the progress line, the result. +// Rust decides what happened (src-tauri/src/drop.rs); this only words it, one short line each. + +import type { DropLine } from "./bindings/DropLine"; +import type { DropProgress } from "./bindings/DropProgress"; +import type { DropReport } from "./bindings/DropReport"; +import type { DropState } from "./bindings/DropState"; + +export type DropEnter = Extract; + +const FOLDERS_LINE = "FOLDERS NOT COPIED - drop the files inside it"; + +/** The overlay's headline: names the real target. A drag of only folders copies nothing, so it says that instead. */ +export const dropTitle = (s: DropEnter): string => (s.files === 0 && s.folders > 0 ? FOLDERS_LINE : `Copy to ${s.target_name}`); + +/** The overlay's second line: only when files AND a folder are in the drag (the folder is not copied). */ +export const dropSub = (s: DropEnter): string | null => (s.files > 0 && s.folders > 0 ? FOLDERS_LINE : null); + +/** Whole percent of the file being copied, null when its size is unknown. */ +export function dropPercent(p: DropProgress): number | null { + if (p.total_bytes <= 0) return null; + return Math.min(100, Math.floor((p.done_bytes / p.total_bytes) * 100)); +} + +export function dropProgressText(p: DropProgress): string { + const pct = dropPercent(p); + return `Copying ${p.file}${p.count > 1 ? ` (${p.index} of ${p.count})` : ""}${pct === null ? "" : `, ${pct}%`}`; +} + +/** The success line ("3 copied to Inbox"), null when nothing was copied. */ +export function dropSummary(r: DropReport): string | null { + return r.copied.length === 0 ? null : `${r.copied.length} copied to ${r.folder_name}`; +} + +/** Everything that was not copied: refused first, then failed. */ +export const dropProblems = (r: DropReport): DropLine[] => [...r.refused, ...r.failed]; + +/** The banner for a drop that left something behind: stays until dismissed. null = nothing to say. + * One reason for all: that reason, the names after it. Different reasons: a count, then one line per file with its own reason. */ +export function dropBanner(r: DropReport): { tone: "danger" | "warn"; text: string; detail?: string; lines?: string[] } | null { + const problems = dropProblems(r); + if (problems.length === 0) return null; + const tone = r.failed.length > 0 ? "danger" : "warn"; + const reasons = new Set(problems.map((l) => l.reason)); + if (reasons.size === 1) { + const names = problems.map((l) => l.name).filter((n) => n !== ""); + return { tone, text: problems[0]!.reason, detail: names.length > 0 ? names.join(", ") : undefined }; + } + return { tone, text: `${problems.length} FILES NOT COPIED`, lines: problems.map((l) => (l.name === "" ? l.reason : `${l.name}: ${l.reason}`)) }; +} diff --git a/apps/desktop/src/lib/format.test.ts b/apps/desktop/src/lib/format.test.ts index e8cae0d..3d5ddbd 100644 --- a/apps/desktop/src/lib/format.test.ts +++ b/apps/desktop/src/lib/format.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { actionLabel, ago, binLabel, duration, fmtSize, isProblem, itemLabel, parseBinDays, shortPath, syncLabel } from "./format"; +import { actionLabel, ago, binLabel, duration, fileIcon, fmtSize, isProblem, itemLabel, itemMeta, kindText, lastSeenText, parseBinDays, peerNote, shortPath, syncLabel } from "./format"; import type { ItemView } from "./bindings/ItemView"; import type { SyncStatus } from "./bindings/SyncStatus"; @@ -11,7 +11,7 @@ const DAY = 24 * HOUR; function item(over: Partial = {}): ItemView { return { id: "i1", name: "IMG_1.jpg", folder: "f1", kind: "image", size: 1000, ext: "jpg", captured_at: NOW, origin: "d1", - pinned: false, state: { t: "live", expires_at: NOW + 5 * HOUR + 10 * MIN }, local: "present", path: "C:\\x.jpg", thumb_path: null, + pinned: false, state: { t: "live", expires_at: NOW + 5 * HOUR + 10 * MIN }, local: "present", path: "C:\\x.jpg", thumb_path: null, never_reached_peer: false, ...over, }; } @@ -43,8 +43,7 @@ describe("itemLabel", () => { test("an item past its time but not yet swept says so, never a negative time", () => { expect(itemLabel(item({ state: { t: "live", expires_at: NOW - 1 } }), NOW).text).toBe("Expiring now"); }); - test("waiting, kept and folder keep labels", () => { - expect(itemLabel(item({ state: { t: "waiting" } }), NOW).text).toBe("Waiting for phone"); + test("kept and folder keep labels (an item no longer waits for the phone: it expires on time)", () => { expect(itemLabel(item({ state: { t: "kept" }, pinned: true }), NOW).text).toBe("Kept"); expect(itemLabel(item({ state: { t: "folder_keep" } }), NOW).text).toBe("Folder keeps"); }); @@ -70,7 +69,7 @@ describe("binLabel", () => { }); describe("syncLabel", () => { - const s = (over: Partial): SyncStatus => ({ state: "synced", peer_name: "Pixel", last_synced_at: NOW - 2 * MIN, waiting: 0, downloading: 0, message: null, ...over }); + const s = (over: Partial): SyncStatus => ({ state: "synced", peer_name: "Pixel", last_synced_at: NOW - 2 * MIN, waiting: 0, downloading: 0, storage_low: false, message: null, ...over }); test("synced shows the last synced time", () => { expect(syncLabel(s({}), NOW)).toEqual({ text: "Synced with Pixel, 2 min ago", tone: "ok", icon: "check" }); }); @@ -122,6 +121,48 @@ describe("small helpers", () => { }); }); +describe("file tiles", () => { + test("the icon follows the extension, in any case, and falls back to a plain file", () => { + expect(fileIcon("pdf")).toBe("text"); + expect(fileIcon("DOCX")).toBe("text"); + expect(fileIcon("xlsx")).toBe("sheet"); + expect(fileIcon("zip")).toBe("archive"); + expect(fileIcon("mp3")).toBe("audio"); + expect(fileIcon("json")).toBe("code"); + expect(fileIcon("svg")).toBe("image"); + expect(fileIcon("avi")).toBe("video"); + expect(fileIcon("")).toBe("file"); + expect(fileIcon("weird")).toBe("file"); + expect(fileIcon("constructor")).toBe("file"); // a name from a synced record is never looked up as an object member + }); + test("the meta line says Photo, Video, the extension, or File", () => { + expect(itemMeta(item({ size: 1024 * 1024 + 200 * 1024 }))).toBe("Photo, 1.2 MB"); + expect(itemMeta(item({ kind: "video", ext: "mp4", size: 5 * 1024 * 1024 }))).toBe("Video, 5.0 MB"); + expect(itemMeta(item({ kind: "file", ext: "pdf", size: 1024 * 1024 + 200 * 1024 }))).toBe("PDF, 1.2 MB"); + expect(itemMeta(item({ kind: "file", ext: "", size: 3 }))).toBe("File, 3 B"); + expect(kindText({ kind: "file", ext: "docx" })).toBe("DOCX"); + }); + test("an expired item the phone never confirmed says NOT ON PHONE", () => { + expect(peerNote(item())).toBeNull(); + expect(peerNote(item({ never_reached_peer: true }))).toBe("NOT ON PHONE"); + }); + test("a file item is labelled like any other item", () => { + expect(itemLabel(item({ kind: "file", ext: "pdf" }), NOW).text).toBe("Expires in 5h"); + }); +}); + +describe("last seen", () => { + test("connected while a session is open, else the time", () => { + const paired = { last_seen_at: NOW - 3 * HOUR }; + expect(lastSeenText(paired, { state: "synced" }, NOW)).toBe("Connected now"); + expect(lastSeenText(paired, { state: "syncing" }, NOW)).toBe("Connected now"); + expect(lastSeenText(paired, { state: "offline" }, NOW)).toBe("Last seen 3 h ago"); + expect(lastSeenText(paired, { state: "connecting" }, NOW)).toBe("Last seen 3 h ago"); + expect(lastSeenText(paired, null, NOW)).toBe("Last seen 3 h ago"); + expect(lastSeenText({ last_seen_at: null }, { state: "offline" }, NOW)).toBe("Last seen never"); + }); +}); + describe("parseBinDays", () => { test("accepts 1 to 365", () => { expect(parseBinDays("7")).toEqual({ ok: true, days: 7 }); diff --git a/apps/desktop/src/lib/format.ts b/apps/desktop/src/lib/format.ts index 8b9c25b..fd17146 100644 --- a/apps/desktop/src/lib/format.ts +++ b/apps/desktop/src/lib/format.ts @@ -1,5 +1,5 @@ // Pure text helpers: every label the screens show comes from here, so the rules (when an -// item says "Expires in 5h", when it says "Waiting for phone") are tested without a window. +// item says "Expires in 5h", what a file tile says about its type) are tested without a window. // Times are unix ms; `now` is always passed in so a test controls the clock. import type { ActivityAction } from "./bindings/ActivityAction"; @@ -43,8 +43,6 @@ export function itemLabel(it: ItemView, now: number): Label { return { text: "Kept", tone: "ok", icon: "pin" }; case "folder_keep": return { text: "Folder keeps", tone: "ok", icon: "infinity" }; - case "waiting": - return { text: "Waiting for phone", tone: "warn", icon: "hourglass" }; case "live": return s.expires_at <= now ? { text: "Expiring now", tone: "warn", icon: "clock" } @@ -56,6 +54,38 @@ export function itemLabel(it: ItemView, now: number): Label { } } +/** Which icon a file tile gets (lucide, monochrome); the tile maps the key to a component. */ +export type FileIconKey = "file" | "text" | "sheet" | "archive" | "audio" | "code" | "image" | "video"; + +const FILE_ICON_BY_EXT: Record = { + pdf: "text", doc: "text", docx: "text", odt: "text", rtf: "text", txt: "text", md: "text", log: "text", + xls: "sheet", xlsx: "sheet", ods: "sheet", csv: "sheet", tsv: "sheet", + zip: "archive", "7z": "archive", rar: "archive", tar: "archive", gz: "archive", tgz: "archive", bz2: "archive", xz: "archive", + mp3: "audio", wav: "audio", flac: "audio", ogg: "audio", m4a: "audio", aac: "audio", opus: "audio", + js: "code", ts: "code", json: "code", html: "code", css: "code", xml: "code", py: "code", rs: "code", sh: "code", bat: "code", ps1: "code", sql: "code", yml: "code", yaml: "code", + svg: "image", psd: "image", ai: "image", raw: "image", dng: "image", bmp: "image", tif: "image", tiff: "image", + avi: "video", mkv: "video", wmv: "video", flv: "video", +}; + +/** The icon for a file's extension (any case); anything unknown, and no extension, is a plain file. */ +export function fileIcon(ext: string): FileIconKey { + const e = ext.toLowerCase(); + return Object.hasOwn(FILE_ICON_BY_EXT, e) ? FILE_ICON_BY_EXT[e]! : "file"; +} + +/** What kind of thing an item is, in one word: "Photo", "Video", "PDF" (the extension), or "File" when it has none. */ +export function kindText(it: Pick): string { + if (it.kind === "image") return "Photo"; + if (it.kind === "video") return "Video"; + return it.ext === "" ? "File" : it.ext.toUpperCase(); +} + +/** The line under a tile's name: "PDF, 1.2 MB". */ +export const itemMeta = (it: Pick): string => `${kindText(it)}, ${fmtSize(it.size)}`; + +/** Said in the Bin when the item expired and the phone never confirmed holding it (it may exist on this PC only). */ +export const peerNote = (it: Pick): string | null => (it.never_reached_peer ? "NOT ON PHONE" : null); + /** Label of an item in the Bin: why it is there and when this PC removes its file. */ export function binLabel(it: ItemView, binDays: number, now: number): Label { const s = it.state; @@ -102,6 +132,11 @@ export function fmtSize(bytes: number): string { return `${v >= 100 ? v.toFixed(0) : v.toFixed(1)} ${units[i]}`; } +/** The paired phone's contact line: "Connected now" while a session is open, else when it was last seen. */ +export function lastSeenText(paired: { last_seen_at: number | null }, sync: Pick | null, now: number): string { + return sync && (sync.state === "syncing" || sync.state === "synced") ? "Connected now" : `Last seen ${ago(paired.last_seen_at, now)}`; +} + /** Local date and time for the Activity list. */ export function fmtTime(at: number): string { const d = new Date(at); diff --git a/apps/desktop/src/lib/icons.ts b/apps/desktop/src/lib/icons.ts index c23ee03..b887ae4 100644 --- a/apps/desktop/src/lib/icons.ts +++ b/apps/desktop/src/lib/icons.ts @@ -1,7 +1,39 @@ // IconKey (from format.ts) to lucide component. Monochrome only: icons take the text colour. -import { Check, CircleAlert, Clock, Download, Hourglass, Infinity as InfinityIcon, Pause, Pin, RefreshCw, Trash2, WifiOff } from "@lucide/svelte"; +import { + Check, + CircleAlert, + Clock, + Download, + File as FileIcon, + FileArchive, + FileCode, + FileImage, + FileMusic, + FilePlay, + FileSpreadsheet, + FileText, + Hourglass, + Infinity as InfinityIcon, + Pause, + Pin, + RefreshCw, + Trash2, + WifiOff, +} from "@lucide/svelte"; import type { Component } from "svelte"; -import type { IconKey } from "./format"; +import type { FileIconKey, IconKey } from "./format"; + +/** Icon for a file tile (see `fileIcon` in format.ts). */ +export const fileIcons: Record> = { + file: FileIcon, + text: FileText, + sheet: FileSpreadsheet, + archive: FileArchive, + audio: FileMusic, + code: FileCode, + image: FileImage, + video: FilePlay, +}; export const icons: Record> = { clock: Clock, diff --git a/crates/core/bindings/ItemState.ts b/crates/core/bindings/ItemState.ts index b6c4de5..833f1e0 100644 --- a/crates/core/bindings/ItemState.ts +++ b/crates/core/bindings/ItemState.ts @@ -3,4 +3,4 @@ /** * Derived expiry/Bin state of an item (computed by `expiry::item_state`, never stored). */ -export type ItemState = { "t": "deleted", binned_at: bigint, } | { "t": "expired", binned_at: bigint, } | { "t": "kept" } | { "t": "folder_keep" } | { "t": "waiting" } | { "t": "live", expires_at: bigint, }; +export type ItemState = { "t": "deleted", binned_at: bigint, } | { "t": "expired", binned_at: bigint, } | { "t": "kept" } | { "t": "folder_keep" } | { "t": "live", expires_at: bigint, }; diff --git a/crates/core/bindings/ItemView.ts b/crates/core/bindings/ItemView.ts index dbfd87a..a531dd5 100644 --- a/crates/core/bindings/ItemView.ts +++ b/crates/core/bindings/ItemView.ts @@ -12,6 +12,11 @@ export type ItemView = { id: ItemId, name: string, folder: FolderId, kind: Media */ path: string | null, /** - * Local path of the thumbnail, when held. + * Local path of the thumbnail, when held. Always None for a File. */ -thumb_path: string | null, }; +thumb_path: string | null, +/** + * In the Bin because it EXPIRED, and the paired device never confirmed holding this file: + * the item may now exist on this device only (shown as "NOT ON PC" / "NOT ON PHONE"). + */ +never_reached_peer: boolean, }; diff --git a/crates/core/bindings/MediaKind.ts b/crates/core/bindings/MediaKind.ts index 261f30b..ac58668 100644 --- a/crates/core/bindings/MediaKind.ts +++ b/crates/core/bindings/MediaKind.ts @@ -1,3 +1,3 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type MediaKind = "image" | "video"; +export type MediaKind = "image" | "video" | "file"; diff --git a/crates/core/bindings/SyncStatus.ts b/crates/core/bindings/SyncStatus.ts index 2d7b071..cbb5db1 100644 --- a/crates/core/bindings/SyncStatus.ts +++ b/crates/core/bindings/SyncStatus.ts @@ -7,13 +7,18 @@ export type SyncStatus = { state: SyncState, peer_name: string | null, */ last_synced_at: bigint | null, /** - * Items in state Waiting (not confirmed by the other device). + * Items held here (not in the Bin) that the paired device has not confirmed holding yet + * ("PC not found, 3 waiting"). 0 while unpaired. Expiry never waits for them (0.2.0). */ waiting: number, /** - * Downloads queued. + * Items that wait on the other device: Pending here (queued downloads). */ downloading: number, +/** + * Phone: the storage guard (`Settings.storage_guard_bytes`) is holding downloads back. + */ +storage_low: boolean, /** * One short line for Refused/Paused ("Update Tugboat on the PC"). */ diff --git a/crates/core/examples/fake_pc.rs b/crates/core/examples/fake_pc.rs index fc65431..ce47df4 100644 --- a/crates/core/examples/fake_pc.rs +++ b/crates/core/examples/fake_pc.rs @@ -10,14 +10,21 @@ //! The Android emulator reaches the host's loopback at 10.0.2.2, so //! use --advertise 10.0.2.2:47300 //! --auto-confirm accept the pairing code without asking (test only) -//! --push-dir every new photo/video file that appears in is pushed to the phone +//! --push-dir every new file that appears in is pushed to the phone: photos, videos +//! and ANY other type (docx, zip, a file with no extension). An always-refused +//! name (x.lnk, desktop.ini) is turned away and printed as push_error. +//! --send-refused once paired and connected, write a record with that always-refused name and +//! no file behind it (the way a hostile or newer peer would), so the phone +//! must show it as REFUSED and never ask for its bytes +//! --proto speak sync protocol n in the handshake (2 is current; 1 plays a 0.1.x PC: +//! both devices must then show "Update Tugboat on the PC") //! --new-pairing allow pairing a new phone although one is paired (replaces it) //! Without --auto-confirm, type `y` or `n` and Enter after a code is printed. //! //! Output: one JSON object per line on stdout, key "event": //! started, payload (the QR text), pairing_code, pairing_completed, pairing_cancelled, sync, //! received (a phone file arrived and verified: id, name, size, path, blake3, thumb_path), -//! pushed, push_error, error. +//! refused_item (a phone record this side will never hold: id, name), pushed, push_error, error. //! Run until killed (kill it by its PID). use std::{ @@ -45,6 +52,8 @@ struct Opts { auto_confirm: bool, push_dir: Option, new_pairing: bool, + proto: Option, + send_refused: Option, } fn main() { @@ -94,10 +103,12 @@ fn parse_opts() -> Result { let push_dir = take_flag(&mut args, "--push-dir")?.map(PathBuf::from); let auto_confirm = take_switch(&mut args, "--auto-confirm"); let new_pairing = take_switch(&mut args, "--new-pairing"); + let proto = take_flag(&mut args, "--proto")?.map(|p| p.parse().map_err(|_| format!("bad --proto {p:?}"))).transpose()?; + let send_refused = take_flag(&mut args, "--send-refused")?; if let Some(extra) = args.first() { return Err(format!("unknown argument {extra:?}; see the header of fake_pc.rs")); } - Ok(Opts { data, port, advertise, auto_confirm, push_dir, new_pairing }) + Ok(Opts { data, port, advertise, auto_confirm, push_dir, new_pairing, proto, send_refused }) } /// The test key: 32 raw bytes, created on first use. @@ -134,6 +145,9 @@ async fn run() -> Result<(), String> { let cfg = CoreConfig { data_dir: opts.data.clone(), role: Role::Pc, self_id: id, device_name: "Fake PC".into(), app_version: "fake-pc".into() }; let storage = AppStorage::new(opts.data.join("storage")).map_err(|e| e.to_string())?; let (core, mut rx) = Core::open(cfg, Arc::new(SystemClock), Arc::new(storage)).map_err(|e| e.to_string())?; + if let Some(n) = opts.proto { + core.debug_set_proto(n); + } let bind: SocketAddr = format!("127.0.0.1:{}", opts.port).parse().map_err(|e| format!("bad port: {e}"))?; core.start_network(NetworkConfig { bind, mdns: false, secret_key: key }).await.map_err(|e| e.to_string())?; emit(json!({"event": "started", "id": id.to_string(), "bind": bind.to_string(), "data": opts.data})); @@ -159,6 +173,7 @@ async fn run() -> Result<(), String> { } let mut reported: HashSet = HashSet::new(); + let mut refused_sent = opts.send_refused.is_none(); let mut seen_files: HashMap = HashMap::new(); let mut handled_files: HashSet = HashSet::new(); let mut ticker = tokio::time::interval(Duration::from_millis(500)); @@ -183,6 +198,14 @@ async fn run() -> Result<(), String> { report("tick", core.tick().map(|_| ())); } report_received(&core, id, &mut reported); + if !refused_sent && matches!(core.status().state, tugboat_core::events::SyncState::Synced) { + refused_sent = true; + let name = opts.send_refused.clone().unwrap_or_default(); + match core.debug_add_record(&name, &tugboat_core::names::ext_of(&name), tugboat_core::MediaKind::File, None, LocalFileState::Refused) { + Ok(rid) => emit(json!({"event": "refused_record_sent", "id": rid.0.to_string(), "name": name})), + Err(e) => emit(json!({"event": "error", "kind": e.kind(), "message": format!("send-refused: {e}")})), + } + } if let Some(dir) = &opts.push_dir { push_new_files(&core, dir, &mut seen_files, &mut handled_files); } @@ -234,6 +257,10 @@ fn report_received(core: &Core, me: tugboat_core::DeviceId, reported: &mut HashS } }; for v in page.rows { + if v.origin != me && v.local == LocalFileState::Refused && reported.insert(v.id) { + emit(json!({"event": "refused_item", "id": v.id.0.to_string(), "name": v.name})); + continue; + } if v.origin == me || v.local != LocalFileState::Present || reported.contains(&v.id) { continue; } diff --git a/crates/core/examples/fake_phone.rs b/crates/core/examples/fake_phone.rs index b4695ae..6f72d1f 100644 --- a/crates/core/examples/fake_phone.rs +++ b/crates/core/examples/fake_phone.rs @@ -7,10 +7,16 @@ //! cargo run -p tugboat-core --example fake_phone -- send [--data ] //! generates N test JPEGs (valid JPEG magic, unique bytes), adds them as captures, syncs, //! waits until the PC's receipts arrive, prints one JSON line per item +//! cargo run -p tugboat-core --example fake_phone -- send-file [--name ] [--data ] +//! adds ANY file (pdf, docx, zip, no extension ...) as it is, syncs, waits for the PC's receipt +//! cargo run -p tugboat-core --example fake_phone -- send-refused [--ext ] [--data ] +//! writes an item RECORD with an always-refused name (x.lnk, desktop.ini ...) the way a hostile +//! or newer peer would, so the PC's Not synced list can be checked. No file is behind it. //! cargo run -p tugboat-core --example fake_phone -- list [--data ] //! syncs once and prints every item it holds (name, folder, state, local) //! Any command takes `--hold-secs `: stay connected N seconds after it finishes (for screenshots of the -//! "phone connected" state). +//! "phone connected" state), and `--proto `: speak sync protocol N in the handshake (2 is current; +//! 1 plays a 0.1.x phone: both devices must then show "Update Tugboat on the phone"). //! Default --data: %TEMP%\tugboat-fake-phone. The key lives in \key (32 raw bytes) //! because this is a test tool; the real phone keeps it in the Android Keystore. //! @@ -27,7 +33,7 @@ use tugboat_core::{ events::{Event, PairingEvent, SyncState}, facade::{device_id_from_secret, NetworkConfig}, ops::{AddKind, NewLocalFile}, - AppStorage, Clock, Core, CoreConfig, ItemId, ItemQuery, ItemState, Role, SystemClock, + store, AppStorage, Clock, Core, CoreConfig, ItemId, ItemQuery, LocalFileState, MediaKind, Role, SystemClock, }; /// How long to wait for the first connection and for the PC's receipts. @@ -95,7 +101,10 @@ async fn run() -> Result<(), String> { let data = take_flag(&mut args, "--data").map(PathBuf::from).unwrap_or_else(|| std::env::temp_dir().join("tugboat-fake-phone")); let bind: SocketAddr = take_flag(&mut args, "--bind").unwrap_or_else(|| "127.0.0.1:0".into()).parse().map_err(|e| format!("bad --bind: {e}"))?; let hold: u64 = take_flag(&mut args, "--hold-secs").map(|s| s.parse().map_err(|_| "bad --hold-secs".to_string())).transpose()?.unwrap_or(0); - let cmd = args.first().cloned().ok_or("usage: fake_phone pair | send | list [--data ] [--bind ]")?; + let proto: Option = take_flag(&mut args, "--proto").map(|s| s.parse().map_err(|_| "bad --proto".to_string())).transpose()?; + let name_flag = take_flag(&mut args, "--name"); + let ext_flag = take_flag(&mut args, "--ext"); + let cmd = args.first().cloned().ok_or("usage: fake_phone pair | send | send-file | send-refused | list [--data ] [--bind ] [--proto ]")?; std::fs::create_dir_all(&data).map_err(|e| format!("cannot create {}: {e}", data.display()))?; let key = load_or_create_key(&data.join("key"))?; @@ -108,11 +117,16 @@ async fn run() -> Result<(), String> { }; let storage = AppStorage::new(data.join("storage")).map_err(|e| e.to_string())?; let (core, _rx) = Core::open(cfg, Arc::new(SystemClock), Arc::new(storage)).map_err(|e| e.to_string())?; + if let Some(n) = proto { + core.debug_set_proto(n); + } core.start_network(NetworkConfig { bind, mdns: false, secret_key: key }).await.map_err(|e| e.to_string())?; let result = match cmd.as_str() { "pair" => pair(&core, args.get(1).ok_or("pair needs the QR payload text")?).await, "send" => send(&core, &data, args.get(1).ok_or("send needs a number")?.parse().map_err(|_| "N must be a number")?).await, + "send-file" => send_file(&core, Path::new(args.get(1).ok_or("send-file needs a path")?), name_flag).await, + "send-refused" => send_refused(&core, args.get(1).ok_or("send-refused needs a name")?, ext_flag).await, "list" => list(&core).await, other => Err(format!("unknown command {other:?}")), }; @@ -155,21 +169,64 @@ async fn send(core: &Core, data: &Path, n: u32) -> Result<(), String> { .map_err(|e| e.to_string())?; ids.push(id); } - // An item shows Waiting until the PC has confirmed holding the file (its receipt). + wait_confirmed(core, &ids).await?; + println!("SENT {n} items, all confirmed by the PC"); + print_items(core, &ids); + Ok(()) +} + +/// Wait until the paired PC has confirmed holding every item (its receipt for the item's hash). +/// Items no longer wait for it to expire (0.2.0); the receipt is what proves the PC got the file. +async fn wait_confirmed(core: &Core, ids: &[ItemId]) -> Result<(), String> { + let pc = core.paired_device().map_err(|e| e.to_string())?.ok_or("not paired")?.id; let t0 = Instant::now(); loop { - let waiting = ids.iter().filter(|id| matches!(core.item(**id), Ok(Some(v)) if v.state == ItemState::Waiting)).count(); + let waiting = ids + .iter() + .filter(|id| { + core.debug_conn(|c| match store::get_item(c, **id) { + Ok(Some((rec, _))) => !store::peer_has_receipt(c, rec.content.val.hash, pc).unwrap_or(false), + _ => true, + }) + }) + .count(); if waiting == 0 { - break; + return Ok(()); } if t0.elapsed() > RECEIPT_WAIT { - print_items(core, &ids); - return Err(format!("{waiting} of {n} items are still waiting for the PC after {}s", RECEIPT_WAIT.as_secs())); + print_items(core, ids); + return Err(format!("{waiting} of {} items are not confirmed by the PC after {}s", ids.len(), RECEIPT_WAIT.as_secs())); } tokio::time::sleep(Duration::from_millis(250)).await; } - println!("SENT {n} items in {} ms, all confirmed by the PC", t0.elapsed().as_millis()); - print_items(core, &ids); +} + +/// Any file as it is: the name defaults to the file's own name; a file with no extension stays one. +async fn send_file(core: &Core, path: &Path, name: Option) -> Result<(), String> { + wait_synced(core).await?; + let name = match name { + Some(n) => n, + None => path.file_name().map(|n| n.to_string_lossy().into_owned()).ok_or("the path has no file name")?, + }; + let id = core + .add_local_file(NewLocalFile { src: path.to_path_buf(), name, folder: None, captured_at: SystemClock.now_ms(), geo: None, thumb: None, how: AddKind::Added, ntfs: None }) + .map_err(|e| format!("{}: {e}", e.kind()))?; + wait_confirmed(core, &[id]).await?; + println!("SENT 1 file, confirmed by the PC"); + print_items(core, &[id]); + Ok(()) +} + +/// A record with an always-refused name and no file behind it. The PC must list it as REFUSED and +/// never ask for its bytes. (A real phone cannot make one: `add_local_file` refuses the name.) +async fn send_refused(core: &Core, name: &str, ext: Option) -> Result<(), String> { + wait_synced(core).await?; + let ext = ext.unwrap_or_else(|| tugboat_core::names::ext_of(name)); + let id = core.debug_add_record(name, &ext, MediaKind::File, None, LocalFileState::Refused).map_err(|e| e.to_string())?; + // Give the live session a moment to send the change; the PC answers with a pull. + tokio::time::sleep(Duration::from_secs(2)).await; + println!("SENT refused record {name:?} (ext {ext:?})"); + print_items(core, &[id]); Ok(()) } diff --git a/crates/core/src/bin.rs b/crates/core/src/bin.rs index 768da79..008bc90 100644 --- a/crates/core/src/bin.rs +++ b/crates/core/src/bin.rs @@ -6,7 +6,7 @@ //! `sweep` rules, per item, with state = expiry::item_state(..) and local = LocalFileState: //! | state | local | action | activity | //! |------------|------------------|-----------------------------------------------------|----------| -//! | in Bin | Present | placement.to_bin, local = Binned, file_ref = Bin path | Expired (state Expired) / Binned (Deleted by a peer version) / none (Deleted by self: logged at delete time) | +//! | in Bin | Present | placement.to_bin, local = Binned, file_ref = Bin path | Expired (state Expired; the text adds "never reached the PC/phone" when the paired device never confirmed the file) / Binned (Deleted by a peer version) / none (Deleted by self: logged at delete time) | //! | in Bin, now >= purge_at | Binned (a Present file is binned first: bin_days >= 1) | placement.purge, local = Purged, file_ref deleted | Purged | //! | in Bin | Pending | local = Purged (never download Bin items) | none | //! | not in Bin | Binned | placement.from_bin, local = Present | Returned | @@ -63,19 +63,27 @@ pub fn local_purge_at(lfs: LocalFileState, state_at: i64, now: i64, bin_days: u3 } /// Derived state of an item given the folder table (preloaded by the caller for batches). -pub fn derive_state_in(c: &Connection, folders: &HashMap, rec: &ItemRecord, now: i64) -> Result { - let receipt = store::peer_receipt_seen_at(c, rec.content.val.hash)?; - Ok(expiry::item_state( - rec, - ExpiryCtx { folder: folders.get(&rec.location.val.folder), peer_receipt_seen_at: receipt, now_ms: now }, - )) +/// Pure in the record and the folder: no receipt lookup (items expire on time). +pub fn derive_state_in(_c: &Connection, folders: &HashMap, rec: &ItemRecord, now: i64) -> Result { + Ok(expiry::item_state(rec, ExpiryCtx { folder: folders.get(&rec.location.val.folder), now_ms: now })) } -/// Derived state of one item (loads its folder and receipt). +/// Derived state of one item (loads its folder). pub fn derive_state(c: &Connection, rec: &ItemRecord, now: i64) -> Result { let folder = store::get_folder(c, rec.location.val.folder)?; - let receipt = store::peer_receipt_seen_at(c, rec.content.val.hash)?; - Ok(expiry::item_state(rec, ExpiryCtx { folder: folder.as_ref(), peer_receipt_seen_at: receipt, now_ms: now })) + Ok(expiry::item_state(rec, ExpiryCtx { folder: folder.as_ref(), now_ms: now })) +} + +/// Silent-failure rule for the dropped expiry hold: the role ("PC" / "phone") of the paired +/// device when it has NOT confirmed holding the file with `hash`; None when there is no paired +/// device or it has the file. An item that expires with `Some(..)` may now exist on this +/// device only, so the Bin and the activity row say so. +pub fn missing_at_peer(c: &Connection, hash: BlobHash) -> Result> { + let Some(peer) = store::paired_peer(c)? else { return Ok(None) }; + if store::peer_has_receipt(c, hash, peer.id)? { + return Ok(None); + } + Ok(Some(if peer.role == Role::Pc { "PC" } else { "phone" })) } /// What a placement needs to know about an item: effective folder (E2) and current path. @@ -95,14 +103,16 @@ pub fn file_target(c: &Connection, rec: &ItemRecord) -> Result { }) } -/// Keep `file_ref` in step with a new path. Bin files carry no NTFS identity. +/// Keep `file_ref` in step with a new path. Bin files carry no NTFS identity. The modified time +/// travels with the file (a move or copy keeps it), so a same-size edit is still noticed later. fn set_path(c: &Connection, item: ItemId, path: &std::path::Path, keep_ntfs: bool) -> Result<()> { let old = store::get_file_ref(c, item)?; let (volume_serial, file_id) = match (&old, keep_ntfs) { (Some(o), true) => (o.volume_serial, o.file_id), _ => (None, None), }; - store::put_file_ref(c, &store::FileRef { item, path: path.to_string_lossy().into_owned(), volume_serial, file_id }) + let mtime_ms = old.as_ref().and_then(|o| o.mtime_ms); + store::put_file_ref(c, &store::FileRef { item, path: path.to_string_lossy().into_owned(), volume_serial, file_id, mtime_ms }) } struct Env<'a> { @@ -158,7 +168,13 @@ fn sweep_one(c: &mut Connection, env: &Env<'_>, id: ItemId, quiet: bool, rep: &m if !quiet { match state { ItemState::Expired { .. } => { - activity::log(&tx, env.now, Some(env.self_id), Some(id), ActivityAction::Expired, &target.folder_name)?; + // Never silent: an item that expires before the other device got it + // may now exist only here. + let detail = match missing_at_peer(&tx, rec.content.val.hash)? { + Some(who) => format!("{} - never reached the {who}", target.folder_name), + None => target.folder_name.clone(), + }; + activity::log(&tx, env.now, Some(env.self_id), Some(id), ActivityAction::Expired, &detail)?; } ItemState::Deleted { .. } if deleted_by_peer => { activity::log(&tx, env.now, Some(rec.deleted.v.device), Some(id), ActivityAction::Binned, "deleted on the other device")?; @@ -306,7 +322,8 @@ mod tests { use crate::ops; use crate::store::test_support::*; - // L14: expiry -> Bin -> purge at exactly 7 days (not 6.99), tombstone stays (L15). + // L14: expiry -> Bin -> purge at exactly 7 days (not 6.99), tombstone stays (L15). Expiry is on + // time: the other device never confirmed this file, and nothing waits for it (0.2.0). #[test] fn expire_bin_purge_timeline_and_tombstone() { let mut r = Rig::new(); @@ -314,27 +331,29 @@ mod tests { assert_eq!(r.lfs(id), LocalFileState::Present); let held = r.path(id).unwrap(); assert!(held.exists()); - // No receipt yet: Waiting, nothing happens however late. - r.clock.advance(10 * DAY_MS); + // One ms before due: still live, nothing happens. + r.clock.set(T0 + 24 * HOUR_MS - 1); let rep = r.sweep(); assert!(rep.to_bin.is_empty() && rep.purged.is_empty()); assert_eq!(r.lfs(id), LocalFileState::Present); - // Receipt arrives late: binned at the receipt time (seen_at), not at due. - let seen = r.clock.now_ms(); - r.confirm(id); + // At due, with NO receipt from the peer: binned at once. + let binned = T0 + 24 * HOUR_MS; + r.clock.set(binned); let rep = r.sweep(); assert_eq!(rep.to_bin, vec![id]); assert_eq!(r.lfs(id), LocalFileState::Binned); let bin_path = r.path(id).unwrap(); assert!(bin_path != held && bin_path.exists() && !held.exists(), "file moved to the Bin area"); assert!(r.actions().contains(&ActivityAction::Expired)); - // Not yet purged one ms before 7 days after seen_at (L13). - r.clock.set(seen + 7 * DAY_MS - 1); + let rec = store::get_item(&r.db.conn, id).unwrap().unwrap().0; + assert!(matches!(derive_state(&r.db.conn, &rec, binned).unwrap(), ItemState::Expired { binned_at } if binned_at == binned)); + // Not yet purged one ms before 7 days after binning (L13). + r.clock.set(binned + 7 * DAY_MS - 1); let rep = r.sweep(); assert!(rep.purged.is_empty(), "6.99 days: still in the Bin"); assert!(bin_path.exists()); - assert_eq!(rep.next_due, Some(seen + 7 * DAY_MS), "the purge is the next time-driven change"); - r.clock.set(seen + 7 * DAY_MS); + assert_eq!(rep.next_due, Some(binned + 7 * DAY_MS), "the purge is the next time-driven change"); + r.clock.set(binned + 7 * DAY_MS); let rep = r.sweep(); assert_eq!(rep.purged, vec![id]); assert_eq!(r.lfs(id), LocalFileState::Purged); @@ -350,6 +369,87 @@ mod tests { assert_eq!(rep, SweepReport::default()); } + // Silent-failure rule: an item that expires before the paired device confirmed it says so in the + // activity row, and missing_at_peer names the device. With a receipt the row stays plain. + #[test] + fn expiry_before_the_peer_got_the_file_is_never_silent() { + let mut r = Rig::new(); + let lost = r.add("lost"); + let safe = r.add("safe"); + r.confirm(safe); + let rec = r.rec(lost); + assert_eq!(missing_at_peer(&r.db.conn, rec.content.val.hash).unwrap(), Some("phone"), "the rig's peer is a phone"); + assert_eq!(missing_at_peer(&r.db.conn, r.rec(safe).content.val.hash).unwrap(), None); + r.clock.set(T0 + 24 * HOUR_MS); + r.sweep(); + let rows = activity::list(&r.db.conn, None, 50).unwrap(); + let expired: Vec<&ActivityEntry> = rows.iter().filter(|a| a.action == ActivityAction::Expired).collect(); + assert_eq!(expired.len(), 2); + let lost_row = expired.iter().find(|a| a.item == Some(lost)).unwrap(); + let safe_row = expired.iter().find(|a| a.item == Some(safe)).unwrap(); + assert!(lost_row.detail.contains("never reached the phone"), "{}", lost_row.detail); + assert_eq!(safe_row.detail, "Inbox", "confirmed items keep the plain row"); + // No paired device: nothing to say about a peer. + r.db.conn.execute("UPDATE device SET unpaired_at = 1 WHERE is_self = 0", []).unwrap(); + assert_eq!(missing_at_peer(&r.db.conn, rec.content.val.hash).unwrap(), None); + } + + // R3 upgrade flood (review amendment 15): a 0.1.x database holds items that were "Waiting" past + // their due time (never paired, or paired with no receipt). The first 0.2.0 sweep bins all of + // them at once, none is purged, each gets one Expired row, and the purge comes exactly + // bin_days after that sweep (the local Bin clock). Restore works. + #[test] + fn upgrade_flood_bins_every_overdue_waiting_item_once_and_purges_a_week_later() { + use crate::db::{backup_path, Db, MIGRATIONS}; + let dir = tempfile::tempdir().unwrap(); + let data = dir.path().join("data"); + let v1 = |paired: bool, items_dir: &std::path::Path| -> Vec { + // A real 0.1.x database: only the v1 schema, items inserted like 0.1.x did. + let db = Db::open_with(&data, &MIGRATIONS[..1]).unwrap(); + store::ensure_self(&db.conn, p(), "me", Role::Pc).unwrap(); + if paired { + let peer = DeviceRow { id: f(), name: "peer".into(), is_self: false, role: Role::Phone, paired_at: None, unpaired_at: None, last_seen_at: None, addresses: vec![] }; + store::set_paired(&db.conn, &peer, T0).unwrap(); + } + (1..=20u8) + .map(|n| { + let it = item(n, p(), v(1, p())); + store::insert_item(&db.conn, &it, LocalFileState::Present, T0).unwrap(); + let src = items_dir.join(format!("{}.jpg", it.id.0.hyphenated())); + std::fs::write(&src, [0xFF, 0xD8, 0xFF, n]).unwrap(); + // The v1 file_ref table has no mtime_ms column yet: write it the way 0.1.x did. + db.conn.execute("INSERT INTO file_ref (item_id, path) VALUES (?1, ?2)", rusqlite::params![it.id.0.as_bytes().as_slice(), src.to_string_lossy().into_owned()]).unwrap(); + it.id + }) + .collect() + }; + for paired in [false, true] { + let _ = std::fs::remove_dir_all(&data); + let pl = crate::placement::AppStorage::new(dir.path().join(format!("store-{paired}"))).unwrap(); + let ids = v1(paired, &pl.root.join("items")); + // Upgrade: opening migrates v1 -> v2 and writes the .bak-1 copy. + let db = Db::open(&data).unwrap(); + assert_eq!(db.user_version().unwrap(), 2); + assert!(backup_path(&data, 1).exists()); + let mut conn = db.conn; + let late = T0 + 30 * DAY_MS; + let rep = sweep(&mut conn, &pl, p(), late).unwrap(); + assert_eq!(rep.to_bin.len(), 20, "paired={paired}: every overdue item is binned at once"); + assert!(rep.purged.is_empty(), "paired={paired}: none purged in the same sweep"); + let expired_rows = activity::list(&conn, None, 100).unwrap().into_iter().filter(|a| a.action == ActivityAction::Expired).count(); + assert_eq!(expired_rows, 20, "paired={paired}: one Expired row each"); + assert_eq!(bin_page(&conn, None, 100, late).unwrap().len(), 20); + // Purge exactly bin_days after the upgrade sweep, not after the old due time. + assert!(sweep(&mut conn, &pl, p(), late + 7 * DAY_MS - 1).unwrap().purged.is_empty()); + // Restore works for a binned one. + let ctx = crate::ops::Ctx { self_id: p(), now: late + 1, placement: &pl }; + crate::ops::restore_item(&mut conn, &ctx, ids[0]).unwrap(); + assert_eq!(store::get_item(&conn, ids[0]).unwrap().unwrap().1, LocalFileState::Present); + let purged = sweep(&mut conn, &pl, p(), late + 7 * DAY_MS).unwrap().purged; + assert_eq!(purged.len(), 19, "paired={paired}: the other 19 are purged exactly Bin days after the sweep"); + } + } + #[test] fn next_due_points_at_the_earliest_future_change() { let mut r = Rig::new(); @@ -686,27 +786,20 @@ mod tests { assert_eq!(r.sweep().purged, vec![id]); } - // Verifier claim (needs Nigel's decision, so it is pinned here, not "fixed"): receipts are per - // file hash, forever. PLAN: "'Confirmed' means a receipt for that file's hash from a device - // this one is or was paired with." So a NEW item with the same bytes as a long-purged one (the - // user drops the same file in again) counts the old receipt and starts its expiry clock at once, - // even if the other device never got this new item. This test records that behaviour; if - // Nigel wants receipts to be per item generation, this test is the one to change. + // Receipts are per file hash, forever (PLAN: a receipt for that file's hash from a device this + // one is or was paired with). A NEW item with the same bytes as a long-purged one therefore + // counts as already delivered for the "waiting" count and the "never reached" note. Expiry + // itself no longer reads receipts (0.2.0), so this only affects those two. Whether receipts + // should be per item generation is Nigel's decision; this test records today's behaviour. #[test] - fn an_old_receipt_confirms_a_new_item_with_the_same_bytes() { + fn an_old_receipt_still_counts_for_a_new_item_with_the_same_bytes() { let mut r = Rig::new(); let old = r.add("a"); r.confirm(old); r.run(|c, x| ops::delete_item(c, x, old)).unwrap(); r.clock.advance(8 * DAY_MS); assert_eq!(r.sweep().purged, vec![old]); - // The same bytes come back as a new item, and the other device is away. - let mut again = r.rec(old); - again.id = ItemId(uuid::Uuid::from_u128(0xA11CE)); - again.deleted = Versioned { v: again.deleted.v, val: None }; - again.location.val.entered_at = r.clock.now_ms(); - store::insert_item(&r.db.conn, &again, LocalFileState::Present, r.clock.now_ms()).unwrap(); - let state = derive_state(&r.db.conn, &again, r.clock.now_ms()).unwrap(); - assert!(matches!(state, ItemState::Live { .. }), "not Waiting: the old receipt for these bytes still counts, got {state:?}"); + let again = r.rec(old); + assert_eq!(missing_at_peer(&r.db.conn, again.content.val.hash).unwrap(), None, "the old receipt for these bytes counts"); } } diff --git a/crates/core/src/db.rs b/crates/core/src/db.rs index fcf0a3d..cf88d9e 100644 --- a/crates/core/src/db.rs +++ b/crates/core/src/db.rs @@ -10,8 +10,11 @@ //! `VACUUM INTO '/tugboat.db.bak-'` (includes WAL content; fails if //! the backup file already exists -> keep the older backup, use `.bak--`), //! then apply each pending migration in its own transaction, setting user_version inside -//! the same transaction. Any failure -> `Migration{from,to,msg}`; the transaction rolls back -//! and the db stays at the last good version. +//! the same transaction. Before the commit every step runs `PRAGMA foreign_key_check` and +//! `PRAGMA integrity_check` and fails on any row/anything but "ok" (a table rebuild must never +//! commit damaged data). Any failure -> `Migration{from,to,msg}`; the transaction rolls back +//! and the db stays at the last good version. A backup that cannot be written (no space) +//! fails the migration before anything is touched: the db stays at the old version. //! 5. Connection pragmas after the version check: journal_mode=WAL, synchronous=NORMAL, //! foreign_keys=ON, busy_timeout=5000. //! 6. After migrating, ensure the default folders exist (`folders::ensure_defaults`) and the @@ -24,10 +27,10 @@ use rusqlite::{Connection, TransactionBehavior}; use crate::{clock::Clock, CoreError, Result}; /// Highest schema version this build knows. -pub const SCHEMA_VERSION: u32 = 1; +pub const SCHEMA_VERSION: u32 = 2; /// Migration SQL, index i = from version i to i + 1. -pub const MIGRATIONS: &[&str] = &[include_str!("schema/v1.sql")]; +pub const MIGRATIONS: &[&str] = &[include_str!("schema/v1.sql"), include_str!("schema/v2.sql")]; /// File name of the database inside the data dir (%LOCALAPPDATA%\Local Tugboat on the PC, /// filesDir on Android). @@ -61,6 +64,19 @@ fn set_pragmas(conn: &Connection) -> Result<()> { Ok(()) } +/// After a migration step, before its commit: foreign keys hold and SQLite finds the file sound. +fn check_integrity(conn: &Connection) -> rusqlite::Result<()> { + let fk_rows = conn.prepare("PRAGMA foreign_key_check")?.query_map([], |_| Ok(()))?.count(); + if fk_rows > 0 { + return Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CONSTRAINT_FOREIGNKEY), Some(format!("foreign_key_check found {fk_rows} broken row(s)")))); + } + let report: String = conn.query_row("PRAGMA integrity_check", [], |r| r.get(0))?; + if report != "ok" { + return Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CORRUPT), Some(format!("integrity_check: {report}")))); + } + Ok(()) +} + /// Apply `migrations[from..]` one transaction each. `from` is the current user_version. fn run_migrations(conn: &mut Connection, migrations: &[&str], from: u32) -> Result<()> { for (i, sql) in migrations.iter().enumerate().skip(from as usize) { @@ -68,6 +84,7 @@ fn run_migrations(conn: &mut Connection, migrations: &[&str], from: u32) -> Resu let step = |conn: &mut Connection| -> rusqlite::Result<()> { let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; tx.execute_batch(sql)?; + check_integrity(&tx)?; tx.pragma_update(None, "user_version", t)?; tx.commit() }; @@ -77,11 +94,10 @@ fn run_migrations(conn: &mut Connection, migrations: &[&str], from: u32) -> Resu } /// Rule 4: consistent copy of the db at the old version. Never overwrites an older backup. -fn backup(conn: &Connection, data_dir: &Path, version: u32) -> Result<()> { +fn backup(conn: &Connection, data_dir: &Path, version: u32, now: i64) -> Result<()> { let mut target = backup_path(data_dir, version); if target.exists() { // A backup of this version exists from an earlier attempt: keep it, it is older. - let now = crate::clock::SystemClock.now_ms(); target = data_dir.join(format!("{DB_FILE}.bak-{version}-{now}")); } let t = target.to_string_lossy().into_owned(); @@ -98,10 +114,10 @@ impl Db { /// `open` with an explicit migration list (the tests use a synthetic two-step list). pub(crate) fn open_with(data_dir: &Path, migrations: &[&str]) -> Result { - Db::open_inner(data_dir, migrations, true) + Db::open_inner(data_dir, migrations, true, crate::clock::SystemClock.now_ms()) } - fn open_inner(data_dir: &Path, migrations: &[&str], defaults: bool) -> Result { + fn open_inner(data_dir: &Path, migrations: &[&str], defaults: bool, now_ms: i64) -> Result { std::fs::create_dir_all(data_dir).map_err(|e| CoreError::io(data_dir, e))?; let path = data_dir.join(DB_FILE); let mut conn = Connection::open(&path)?; @@ -119,7 +135,7 @@ impl Db { }); } if found > 0 && found < supported { - backup(&conn, data_dir, found)?; + backup(&conn, data_dir, found, now_ms)?; } set_pragmas(&conn)?; run_migrations(&mut conn, migrations, found)?; @@ -197,7 +213,7 @@ mod tests { } let before = std::fs::read(&path).unwrap(); match Db::open(dir.path()) { - Err(CoreError::NewerDatabase { found: 99, supported: 1 }) => {} + Err(CoreError::NewerDatabase { found: 99, supported: 2 }) => {} other => panic!("expected NewerDatabase, got {:?}", other.map(|_| ())), } assert_eq!(std::fs::read(&path).unwrap(), before); @@ -271,10 +287,81 @@ mod tests { assert!(c.prepare("SELECT y FROM a").is_err()); } + // v1 -> v2 on a real 0.1.x file: rows identical, 'file' insertable, indexes and the file_ref + // column there, the backup is the v1 file, reopening is idempotent. + #[test] + fn v1_to_v2_keeps_every_row_and_accepts_files() { + let dir = tempfile::tempdir().unwrap(); + let cols = "id, captured_at, origin_device, lat, lon, accuracy_m, name, name_lamport, name_dev, blob_hash, size, media_kind, ext, thumb_hash, thumb_size, content_lamport, content_dev, folder_id, folder_entered_at, placement_lamport, placement_dev, pinned, pinned_lamport, pinned_dev, deleted_at, deleted_lamport, deleted_dev, local_file_state, local_state_at"; + let before: Vec; + { + let d = Db::open_with(dir.path(), &MIGRATIONS[..1]).unwrap(); + assert_eq!(d.user_version().unwrap(), 1); + for n in 1..=25u8 { + let kind = if n % 2 == 0 { "video" } else { "image" }; + d.conn + .execute( + "INSERT INTO item (id, captured_at, origin_device, name, name_lamport, name_dev, blob_hash, size, media_kind, ext, content_lamport, content_dev, folder_id, folder_entered_at, placement_lamport, placement_dev, pinned, pinned_lamport, pinned_dev, deleted_lamport, deleted_dev, local_file_state, local_state_at, thumb_hash, thumb_size, lat, lon) + VALUES (?1, ?2, zeroblob(32), ?3, 1, zeroblob(32), zeroblob(32), ?2, ?4, 'x', 1, zeroblob(32), zeroblob(16), 5, 1, zeroblob(32), 0, 1, zeroblob(32), 1, zeroblob(32), 'present', 9, NULL, NULL, 1.5, NULL)", + rusqlite::params![{ let mut id = vec![0u8; 15]; id.push(n); id }, 100 + n as i64, format!("name {n}"), kind], + ) + .unwrap(); + } + d.conn.execute("INSERT INTO file_ref (item_id, path) VALUES (x'00000000000000000000000000000001', 'C:/lib/a.jpg')", []).unwrap(); + before = dump(&d.conn, &format!("SELECT {cols} FROM item ORDER BY id")); + } + let d = Db::open(dir.path()).unwrap(); + assert_eq!(d.user_version().unwrap(), 2); + assert_eq!(dump(&d.conn, &format!("SELECT {cols} FROM item ORDER BY id")), before, "every item row is identical after the rebuild"); + // The backup is the v1 file: a 'file' row is refused there, accepted here. + let bak = Connection::open(backup_path(dir.path(), 1)).unwrap(); + assert_eq!(read_version(&bak).unwrap(), 1); + let insert = "INSERT INTO item (id, captured_at, origin_device, name, name_lamport, name_dev, blob_hash, size, media_kind, ext, content_lamport, content_dev, folder_id, folder_entered_at, placement_lamport, placement_dev, pinned, pinned_lamport, pinned_dev, deleted_lamport, deleted_dev, local_file_state, local_state_at) VALUES (zeroblob(16), 1, zeroblob(32), 'n', 1, zeroblob(32), zeroblob(32), 1, 'file', '', 1, zeroblob(32), zeroblob(16), 1, 1, zeroblob(32), 0, 1, zeroblob(32), 1, zeroblob(32), 'present', 1)"; + assert!(bak.execute(insert, []).is_err(), "v1 does not know 'file'"); + assert_eq!(d.conn.execute(insert, []).unwrap(), 1, "v2 accepts a file"); + assert!(d.conn.execute(&insert.replace("'file'", "'audio'"), []).is_err(), "still a closed list"); + // The five indexes by name, and the new file_ref column. + for ix in ["item_folder", "item_captured", "item_hash", "item_local", "item_entered"] { + let n: i64 = d.conn.query_row("SELECT count(*) FROM sqlite_master WHERE type = 'index' AND name = ?1", [ix], |r| r.get(0)).unwrap(); + assert_eq!(n, 1, "index {ix}"); + } + d.conn.execute("UPDATE file_ref SET mtime_ms = 5", []).unwrap(); + drop(d); + // Reopening is idempotent and keeps the rows. + let again = Db::open(dir.path()).unwrap(); + let n: i64 = again.conn.query_row("SELECT count(*) FROM item", [], |r| r.get(0)).unwrap(); + assert_eq!(n, 26); + } + + fn dump(c: &Connection, sql: &str) -> Vec { + let mut st = c.prepare(sql).unwrap(); + let n = st.column_count(); + st.query_map([], |r| Ok((0..n).map(|i| format!("{:?}", r.get_ref(i).unwrap())).collect::>().join("|"))).unwrap().map(|r| r.unwrap()).collect() + } + + // A backup that cannot be written (no space, no rights) fails the upgrade BEFORE anything changes: + // the file stays at v1, untouched, and the error is the visible Migration error. + #[test] + fn a_failed_backup_leaves_the_database_at_v1_untouched() { + let dir = tempfile::tempdir().unwrap(); + drop(Db::open_with(dir.path(), &MIGRATIONS[..1]).unwrap()); + // The first backup name is taken by a file, the timestamped one by a directory: VACUUM INTO cannot write either. + std::fs::write(backup_path(dir.path(), 1), b"older backup").unwrap(); + std::fs::create_dir(dir.path().join("tugboat.db.bak-1-777")).unwrap(); + match Db::open_inner(dir.path(), MIGRATIONS, true, 777) { + Err(CoreError::Migration { from: 1, to: 2, msg }) => assert!(msg.contains("backup failed"), "{msg}"), + other => panic!("expected a Migration error, got {:?}", other.map(|_| ())), + } + let c = Connection::open(dir.path().join(DB_FILE)).unwrap(); + assert_eq!(read_version(&c).unwrap(), 1, "still v1"); + assert!(c.prepare("SELECT mtime_ms FROM file_ref").is_err(), "no step ran"); + assert_eq!(std::fs::read(backup_path(dir.path(), 1)).unwrap(), b"older backup"); + } + impl Db { /// Test helper: `open_with` minus ensure_defaults (synthetic schemas have no folder table). fn open_with_no_defaults(data_dir: &Path, migrations: &[&str]) -> Result { - Db::open_inner(data_dir, migrations, false) + Db::open_inner(data_dir, migrations, false, crate::clock::SystemClock.now_ms()) } } } diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index 476ab4d..c507de2 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -25,9 +25,14 @@ pub enum CoreError { /// Input that violates a rule (empty folder name, retention 0, move into a deleted folder). #[error("invalid: {0}")] Invalid(String), - /// A file that is not an allowed photo/video (extension or magic bytes). + /// A photo/video extension whose content is not a photo or video (a renamed program). #[error("not a supported photo or video: {0}")] NotMedia(String), + /// Refused on purpose, never synced: an always-refused name ("REFUSED - shortcut and + /// folder-setting files never sync") or a file over the size limit ("TOO LARGE - over 16 GB"). + /// The text is the one-line message for the user. + #[error("{0}")] + Refused(String), /// Restore or fetch of a file neither device holds any more. #[error("file no longer on either device")] FileGone, @@ -70,6 +75,7 @@ impl CoreError { CoreError::Name(_) => "name", CoreError::Invalid(_) => "invalid", CoreError::NotMedia(_) => "not_media", + CoreError::Refused(_) => "refused", CoreError::FileGone => "file_gone", CoreError::NotPaired => "not_paired", CoreError::AlreadyPaired => "already_paired", @@ -97,6 +103,7 @@ mod tests { CoreError::Name(NameError::Empty), CoreError::Invalid("x".into()), CoreError::NotMedia("x".into()), + CoreError::Refused("x".into()), CoreError::FileGone, CoreError::NotPaired, CoreError::AlreadyPaired, diff --git a/crates/core/src/events.rs b/crates/core/src/events.rs index 95097d3..4eff16a 100644 --- a/crates/core/src/events.rs +++ b/crates/core/src/events.rs @@ -51,10 +51,13 @@ pub struct SyncStatus { pub peer_name: Option, /// PLAN silent-failure row "Sync stopped": shown as "last synced" on both apps. pub last_synced_at: Option, - /// Items in state Waiting (not confirmed by the other device). + /// Items held here (not in the Bin) that the paired device has not confirmed holding yet + /// ("PC not found, 3 waiting"). 0 while unpaired. Expiry never waits for them (0.2.0). pub waiting: u32, - /// Downloads queued. + /// Items that wait on the other device: Pending here (queued downloads). pub downloading: u32, + /// Phone: the storage guard (`Settings.storage_guard_bytes`) is holding downloads back. + pub storage_low: bool, /// One short line for Refused/Paused ("Update Tugboat on the PC"). pub message: Option, } diff --git a/crates/core/src/expiry.rs b/crates/core/src/expiry.rs index 5660f7e..d7682e7 100644 --- a/crates/core/src/expiry.rs +++ b/crates/core/src/expiry.rs @@ -1,29 +1,29 @@ //! Derived expiry. Owner: logic builder. Pure: no DB, no clock. //! -//! PLAN Folders and expiry: +//! PLAN Folders and expiry (Decisions log 2026-11-18, "drop the expiry hold"): //! - "An item expires at folder_entered_at + retention. Moving an item to another folder //! resets folder_entered_at to now. A kept (pinned) item never expires." -//! - "An item never expires until the other device has confirmed holding the same file." -//! ("Waiting for PC"). With no paired device ever, nothing expires. +//! - Items expire ON TIME, whether or not the other device has the file. Before 0.2.0 an item +//! waited ("Waiting for PC") until a receipt from the other device arrived; that hold is gone. +//! Receipts stay as sync bookkeeping only (the "waiting" count, "never reached the PC"). //! - "Expiry is worked out on each device from these synced fields; no device sends //! 'expired' to the other." //! //! Truth table (first matching row wins; full table with examples in core-design.md): -//! | # | effective deleted (E1) | pinned | retention (E2) | peer receipt | now >= due | state | -//! |---|---|---|---|---|---|---| -//! | 1 | yes | - | - | - | - | Deleted{binned_at = deleted_at} | -//! | 2 | no | yes | - | - | - | Kept | -//! | 3 | no | no | Keep | - | - | FolderKeep | -//! | 4 | no | no | secs | no | - | Waiting | -//! | 5 | no | no | secs | yes | no | Live{expires_at = due} | -//! | 6 | no | no | secs | yes | yes | Expired{binned_at = max(due, receipt_seen_at)} | +//! | # | effective deleted (E1) | pinned | retention (E2) | now >= due | state | +//! |---|---|---|---|---|---| +//! | 1 | yes | - | - | - | Deleted{binned_at = deleted_at} | +//! | 2 | no | yes | - | - | Kept | +//! | 3 | no | no | Keep | - | FolderKeep | +//! | 4 | no | no | secs | no | Live{expires_at = due} | +//! | 5 | no | no | secs | yes | Expired{binned_at = due} | //! due = location.entered_at + secs * 1000. //! E1 effective deleted = deleted.val.is_some() && !(pinned.val && pinned.v > deleted.v) //! (M5's rule, so the view is right even before the M5 rewrite has run). //! E2 retention = the item's folder's retention if that folder record exists and is not //! deleted; otherwise Keep (an unknown or deleted folder is treated as Unsorted/Keep, so //! an item never falls into a short retention by accident). -//! `binned_at` (rows 1 and 6) is when the item LOGICALLY entered the Bin, built from synced +//! `binned_at` (rows 1 and 5) is when the item LOGICALLY entered the Bin, built from synced //! times; it is for display and ordering only. When a file is purged is decided by this //! device's own Bin clock (bin.rs `local_purge_at`), never by `binned_at`: an old synced time //! must not purge a file with no Bin time. @@ -35,8 +35,6 @@ use crate::model::*; pub struct ExpiryCtx<'a> { /// The item's folder record, if known locally. pub folder: Option<&'a FolderRecord>, - /// `store::peer_receipt_seen_at` for the item's content hash. - pub peer_receipt_seen_at: Option, pub now_ms: i64, } @@ -51,18 +49,14 @@ pub fn item_state(item: &ItemRecord, ctx: ExpiryCtx<'_>) -> ItemState { } match effective_retention(ctx.folder) { Retention::Keep => ItemState::FolderKeep, - Retention::Secs { secs } => match ctx.peer_receipt_seen_at { - // PLAN: never expires until the other device has confirmed holding the file. - None => ItemState::Waiting, - Some(seen_at) => { - let due = item.location.val.entered_at.saturating_add(secs_to_ms(secs)); - if ctx.now_ms >= due { - ItemState::Expired { binned_at: due.max(seen_at) } - } else { - ItemState::Live { expires_at: due } - } + Retention::Secs { secs } => { + let due = item.location.val.entered_at.saturating_add(secs_to_ms(secs)); + if ctx.now_ms >= due { + ItemState::Expired { binned_at: due } + } else { + ItemState::Live { expires_at: due } } - }, + } } } @@ -91,7 +85,7 @@ pub fn in_bin(state: ItemState) -> bool { #[cfg(test)] mod tests { use super::*; - use crate::clock::{HOUR_MS, SECOND_MS}; + use crate::clock::HOUR_MS; use crate::store::test_support::*; fn folder(retention: Retention) -> FolderRecord { @@ -106,34 +100,33 @@ mod tests { const H24: Retention = Retention::Secs { secs: 24 * 3600 }; - fn st(item: &ItemRecord, f: Option<&FolderRecord>, receipt: Option, now: i64) -> ItemState { - item_state(item, ExpiryCtx { folder: f, peer_receipt_seen_at: receipt, now_ms: now }) + fn st(item: &ItemRecord, f: Option<&FolderRecord>, now: i64) -> ItemState { + item_state(item, ExpiryCtx { folder: f, now_ms: now }) } - // L11: truth table rows 1-6. + // L11: truth table rows 1-5. #[test] fn truth_table_rows() { let fo = folder(H24); let mut it = item(1, p(), v(1, p())); it.location.val.entered_at = T0; let due = T0 + 24 * HOUR_MS; - // Rows 5 and 6 share inputs, split by the boundary: due - 1 ms / due. - assert_eq!(st(&it, Some(&fo), Some(T0 + 2 * SECOND_MS), due - 1), ItemState::Live { expires_at: due }); - assert_eq!(st(&it, Some(&fo), Some(T0 + 2 * SECOND_MS), due), ItemState::Expired { binned_at: due }); - // Row 4: no receipt -> Waiting, however late. - assert_eq!(st(&it, Some(&fo), None, due + 1000 * HOUR_MS), ItemState::Waiting); + // Rows 4 and 5 are split by the boundary: due - 1 ms / due. + assert_eq!(st(&it, Some(&fo), due - 1), ItemState::Live { expires_at: due }); + assert_eq!(st(&it, Some(&fo), due), ItemState::Expired { binned_at: due }); + // Expiry never waits for the other device: a thousand hours late, still binned at due. + assert_eq!(st(&it, Some(&fo), due + 1000 * HOUR_MS), ItemState::Expired { binned_at: due }); // Row 3: Keep folder. - assert_eq!(st(&it, Some(&folder(Retention::Keep)), Some(T0), due + HOUR_MS), ItemState::FolderKeep); - // Row 2: pinned beats retention, receipt or not. + assert_eq!(st(&it, Some(&folder(Retention::Keep)), due + HOUR_MS), ItemState::FolderKeep); + // Row 2: pinned beats retention. let mut pinned = it.clone(); pinned.pinned.val = true; - assert_eq!(st(&pinned, Some(&fo), Some(T0), due + HOUR_MS), ItemState::Kept); - assert_eq!(st(&pinned, Some(&fo), None, due + HOUR_MS), ItemState::Kept); + assert_eq!(st(&pinned, Some(&fo), due + HOUR_MS), ItemState::Kept); // Row 1: deleted wins over everything (older pin). let mut del = pinned.clone(); del.deleted = Versioned { v: v(5, p()), val: Some(T0 + 77) }; del.pinned = Versioned { v: v(3, p()), val: true }; - assert_eq!(st(&del, Some(&fo), Some(T0), T0), ItemState::Deleted { binned_at: T0 + 77 }); + assert_eq!(st(&del, Some(&fo), T0), ItemState::Deleted { binned_at: T0 + 77 }); } // L11: E1 (pin newer than delete = not deleted before M5 runs). @@ -143,7 +136,7 @@ mod tests { it.deleted = Versioned { v: v(6, p()), val: Some(T0) }; it.pinned = Versioned { v: v(8, f()), val: true }; assert!(!effectively_deleted(&it)); - assert_eq!(st(&it, Some(&folder(H24)), None, T0), ItemState::Kept); + assert_eq!(st(&it, Some(&folder(H24)), T0), ItemState::Kept); // Pin older than delete: deleted. it.pinned.v = v(5, f()); assert!(effectively_deleted(&it)); @@ -163,31 +156,28 @@ mod tests { fn e2_unknown_and_deleted_folder_are_keep() { let it = item(1, p(), v(1, p())); assert_eq!(effective_retention(None), Retention::Keep); - assert_eq!(st(&it, None, Some(T0), T0 + 1000 * HOUR_MS), ItemState::FolderKeep); + assert_eq!(st(&it, None, T0 + 1000 * HOUR_MS), ItemState::FolderKeep); let mut gone = folder(H24); gone.deleted = Versioned { v: v(2, f()), val: Some(T0) }; assert_eq!(effective_retention(Some(&gone)), Retention::Keep); - assert_eq!(st(&it, Some(&gone), Some(T0), T0 + 1000 * HOUR_MS), ItemState::FolderKeep); + assert_eq!(st(&it, Some(&gone), T0 + 1000 * HOUR_MS), ItemState::FolderKeep); assert_eq!(effective_retention(Some(&folder(H24))), H24); } - // L13: late receipt: binned_at = seen_at (display value; the purge clock is local, see bin.rs). + // A device that was away binned_at = due (the display value; the purge clock is local, see bin.rs). #[test] - fn late_receipt_binned_at() { + fn late_device_binned_at_is_the_due_time() { let fo = folder(H24); let mut it = item(1, p(), v(1, p())); it.location.val.entered_at = T0; let due = T0 + 24 * HOUR_MS; - // Receipt seen 3 days after the due time (PC was away). - let seen = due + 3 * 24 * HOUR_MS; - assert_eq!(st(&it, Some(&fo), Some(seen), seen), ItemState::Expired { binned_at: seen }); - // On time: binned_at = due. - assert_eq!(st(&it, Some(&fo), Some(T0 + 2000), due), ItemState::Expired { binned_at: due }); + assert_eq!(st(&it, Some(&fo), due + 3 * 24 * HOUR_MS), ItemState::Expired { binned_at: due }); + assert_eq!(st(&it, Some(&fo), due), ItemState::Expired { binned_at: due }); } #[test] fn bin_helper() { - for s in [ItemState::Kept, ItemState::FolderKeep, ItemState::Waiting, ItemState::Live { expires_at: 5 }] { + for s in [ItemState::Kept, ItemState::FolderKeep, ItemState::Live { expires_at: 5 }] { assert!(!in_bin(s)); } assert!(in_bin(ItemState::Expired { binned_at: 0 }) && in_bin(ItemState::Deleted { binned_at: 0 })); @@ -197,19 +187,18 @@ mod tests { fn huge_retention_does_not_overflow() { let fo = folder(Retention::Secs { secs: u64::MAX }); let it = item(1, p(), v(1, p())); - assert!(matches!(st(&it, Some(&fo), Some(T0), T0), ItemState::Live { .. })); + assert!(matches!(st(&it, Some(&fo), T0), ItemState::Live { .. })); } - // Design doc dated example: entered 10:00, receipt 10:00:02, Inbox 24 h, Bin 7 days. + // Design doc dated example: entered 10:00, Inbox 24 h, Bin 7 days. #[test] fn design_doc_example() { let fo = folder(H24); let mut it = item(1, p(), v(1, p())); let entered = T0; it.location.val.entered_at = entered; - let seen = entered + 2000; - assert!(matches!(st(&it, Some(&fo), Some(seen), entered + 24 * HOUR_MS - 60_000), ItemState::Live { .. })); - let s = st(&it, Some(&fo), Some(seen), entered + 24 * HOUR_MS); + assert!(matches!(st(&it, Some(&fo), entered + 24 * HOUR_MS - 60_000), ItemState::Live { .. })); + let s = st(&it, Some(&fo), entered + 24 * HOUR_MS); assert_eq!(s, ItemState::Expired { binned_at: entered + 24 * HOUR_MS }); } } diff --git a/crates/core/src/facade.rs b/crates/core/src/facade.rs index 9d0c78c..b0c3571 100644 --- a/crates/core/src/facade.rs +++ b/crates/core/src/facade.rs @@ -28,6 +28,7 @@ use crate::{ events::{Event, SyncState, SyncStatus}, expiry, folders, model::*, + names, ops::{self, Ctx, NewLocalFile}, placement::Placement, places::{self, Fix, Route}, @@ -91,6 +92,8 @@ pub(crate) struct Inner { pub active: Mutex>, pub pairing: Mutex>, pub proto: AtomicU32, + /// Pairing protocol number the phone speaks (tests play an older phone). + pub pair_proto: AtomicU32, pub retry_base_ms: AtomicU64, pub generation: AtomicU64, /// Bytes of downloads that continued from an existing part file (tests assert on it). @@ -98,6 +101,13 @@ pub(crate) struct Inner { /// Phone: a task is delivering an unpair notice to a replaced PC while the connect loop /// serves the new one. pub notice_running: std::sync::atomic::AtomicBool, + /// Phone: the storage guard is holding at least one download back (SyncStatus.storage_low). + pub storage_low: std::sync::atomic::AtomicBool, + /// How long a blocked download queue waits before it looks at the free space again (ms). + pub guard_recheck_ms: AtomicU64, + /// Hash (hex) of every blob or thumbnail request this device answered or refused (tests + /// assert "zero", or that one hash was never asked for). + pub blob_requests: Mutex>, } #[derive(Clone)] @@ -138,10 +148,14 @@ impl Core { active: Mutex::new(None), pairing: Mutex::new(None), proto: AtomicU32::new(wire::PROTO), + pair_proto: AtomicU32::new(tugboat_net::pairing::PAIR_PROTO), retry_base_ms: AtomicU64::new(2000), generation: AtomicU64::new(0), resumed_bytes: AtomicU64::new(0), notice_running: std::sync::atomic::AtomicBool::new(false), + storage_low: std::sync::atomic::AtomicBool::new(false), + guard_recheck_ms: AtomicU64::new(30_000), + blob_requests: Mutex::new(Vec::new()), }), }; core.sweep_and_emit()?; @@ -212,12 +226,68 @@ impl Core { self.inner.proto.store(proto, Ordering::SeqCst); } + /// Test hook: speak another PAIRING protocol number when this device is the phone. + #[doc(hidden)] + pub fn debug_set_pair_proto(&self, proto: u32) { + self.inner.pair_proto.store(proto, Ordering::SeqCst); + } + /// Test hook: blob retry back-off base (default 2000 ms). #[doc(hidden)] pub fn debug_set_retry_base_ms(&self, ms: u64) { self.inner.retry_base_ms.store(ms.max(1), Ordering::SeqCst); } + /// Test and QA hook: write an item RECORD straight into the database (and the change log, so + /// it syncs) without any file behind it, with the name, extension, kind, thumbnail and local + /// state given: the way a hostile or newer peer's record would arrive. `fake_phone + /// send-refused` uses it to put a refused name on the PC's Not synced list. + #[doc(hidden)] + pub fn debug_add_record(&self, name: &str, ext: &str, kind: MediaKind, thumb: Option, local: LocalFileState) -> Result { + let id = self.with_ctx(|c, ctx| { + let tx = c.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; + let v = store::next_version(&tx, ctx.self_id)?; + let id = ItemId::new(ctx.now); + let rec = ItemRecord { + id, + captured_at: ctx.now, + origin: ctx.self_id, + geo: None, + name: Versioned { v, val: name.to_string() }, + content: Versioned { v, val: Content { hash: BlobHash(*blake3::hash(name.as_bytes()).as_bytes()), size: name.len() as u64, kind, ext: ext.to_string(), thumb } }, + location: Versioned { v, val: Location { folder: INBOX_ID, entered_at: ctx.now } }, + pinned: Versioned { v, val: false }, + deleted: Versioned { v, val: None }, + }; + store::insert_item(&tx, &rec, local, ctx.now)?; + store::log_change(&tx, &EntityKey::Item { id }, group::ALL, v.lamport)?; + tx.commit()?; + Ok(id) + })?; + self.wrote(&[id], false, false); + Ok(id) + } + + /// Test hook: how long a download queue blocked by the storage guard waits before it checks + /// the free space again (default 30 000 ms). + #[doc(hidden)] + pub fn debug_set_guard_recheck_ms(&self, ms: u64) { + self.inner.guard_recheck_ms.store(ms.max(1), Ordering::SeqCst); + } + + /// Test hook: how many blob or thumbnail requests the peer has made of this device (a refused + /// record must cost zero). + #[doc(hidden)] + pub fn debug_blob_requests(&self) -> usize { + lock(&self.inner.blob_requests).len() + } + + /// Test hook: has the peer asked this device for the blob or thumbnail with this hash? + #[doc(hidden)] + pub fn debug_blob_requested(&self, hash: BlobHash) -> bool { + lock(&self.inner.blob_requests).contains(&hex::encode(hash.0)) + } + /// Test hook: total bytes that downloads resumed from an existing part file. #[doc(hidden)] pub fn debug_resumed_bytes(&self) -> u64 { @@ -255,7 +325,8 @@ impl Core { } else { (st.state.unwrap_or(SyncState::Offline), st.message.clone()) }; - SyncStatus { state, peer_name: peer.map(|p| p.name), last_synced_at: st.last_synced_at, waiting, downloading, message } + let storage_low = self.inner.storage_low.load(Ordering::SeqCst); + SyncStatus { state, peer_name: peer.map(|p| p.name), last_synced_at: st.last_synced_at, waiting, downloading, storage_low, message } } /// Set the connection-derived state, then emit Event::Sync when the status changed. @@ -291,7 +362,7 @@ impl Core { pub fn folders(&self) -> Result> { let now = self.now(); let db = lock(&self.inner.db); - folders::folder_views(&db.conn, now) + folders::folder_views(&db.conn, now, self.inner.cfg.role == Role::Pc) } pub fn items(&self, q: &ItemQuery) -> Result> { @@ -334,7 +405,8 @@ impl Core { let got = page.len(); for (rec, lfs) in page { after = Some(rec.id); - if !wanted(&rec) { + // The PC lists a file it refused under Not synced, not as a tile; the phone keeps its tile. + if !wanted(&rec) || (lfs == LocalFileState::Refused && self.inner.cfg.role == Role::Pc) { continue; } let state = bin::derive_state_in(c, &fmap, &rec, now)?; @@ -374,10 +446,21 @@ impl Core { LocalFileState::Present | LocalFileState::Binned => store::get_file_ref(c, rec.id).ok().flatten().map(|r| r.path), _ => None, }; - let thumb_path = rec.content.val.thumb.as_ref().map(|t| self.thumb_path(t.hash)).filter(|p| p.exists()).map(|p| p.to_string_lossy().into_owned()); + // A File never shows a thumbnail, whatever its record carries. + let thumb_path = rec + .content + .val + .thumb + .as_ref() + .filter(|_| rec.content.val.kind != MediaKind::File) + .map(|t| self.thumb_path(t.hash)) + .filter(|p| p.exists()) + .map(|p| p.to_string_lossy().into_owned()); + // Expired before the paired device ever confirmed the file: the Bin says so (silent-failure rule). + let never_reached_peer = matches!(state, ItemState::Expired { .. }) && bin::missing_at_peer(c, rec.content.val.hash).ok().flatten().is_some(); ItemView { id: rec.id, - name: rec.name.val.clone(), + name: crate::names::display_name(&rec.name.val, &rec.content.val.ext), folder, kind: rec.content.val.kind, size: rec.content.val.size, @@ -389,9 +472,39 @@ impl Core { local: lfs, path, thumb_path, + never_reached_peer, } } + /// Items this device will not hold because the file is refused (an always-refused name from + /// the other device, a wrong type, too large): local state Refused, not in the Bin, newest + /// first. The PC lists them in its Not synced list, the phone as REFUSED tiles. + pub fn refused_items(&self, limit: u32) -> Result> { + let now = self.now(); + let db = lock(&self.inner.db); + let c = &db.conn; + let fmap: HashMap = store::all_folders(c)?.into_iter().map(|f| (f.id, f)).collect(); + let mut rows: Vec = Vec::new(); + let mut recs: Vec<(ItemRecord, LocalFileState)> = Vec::new(); + for id in store::item_ids_where(c, "local_file_state = 'refused'")? { + if let Some(x) = store::get_item(c, id)? { + recs.push(x); + } + } + recs.sort_by(|a, b| b.0.captured_at.cmp(&a.0.captured_at).then_with(|| b.0.id.cmp(&a.0.id))); + for (rec, lfs) in recs { + let state = bin::derive_state_in(c, &fmap, &rec, now)?; + if expiry::in_bin(state) { + continue; + } + rows.push(self.item_view(c, &fmap, &rec, lfs, state)); + if rows.len() >= limit.clamp(1, 500) as usize { + break; + } + } + Ok(rows) + } + /// Activity, newest first. `before` = last id of the previous page. pub fn activity(&self, before: Option, limit: u32) -> Result> { let db = lock(&self.inner.db); @@ -448,6 +561,10 @@ impl Core { } // The thumbnail is hashed and copied here; ops::add_local_file takes the finished Thumb. let mut made_thumb: Option = None; + // Only photos and videos get a thumbnail: a thumbnail offered for any other file is dropped. + if names::media_family_of_name(&f.name).is_none() { + f.thumb = None; + } let thumb = match f.thumb.take() { None => None, Some(src) => { @@ -589,6 +706,7 @@ impl Core { path: new_path.to_string_lossy().into_owned(), volume_serial: old.as_ref().and_then(|o| o.volume_serial), file_id: old.as_ref().and_then(|o| o.file_id), + mtime_ms: old.as_ref().and_then(|o| o.mtime_ms), }, )?; if rec.location.val.folder != folder { @@ -684,6 +802,13 @@ impl Core { store::held_files(&db.conn) } + /// Desktop: remember the modified time (unix ms) of the file an item holds, as the watcher + /// saw it at the item's current path. Errors when the item holds no file. + pub fn set_file_mtime(&self, id: ItemId, mtime_ms: i64) -> Result<()> { + let db = lock(&self.inner.db); + store::set_file_mtime(&db.conn, id, mtime_ms) + } + /// Desktop: remember the NTFS identity of an item's file (set after a scan recognised it). pub fn set_file_identity(&self, id: ItemId, volume_serial: u64, file_id: [u8; 16]) -> Result<()> { let db = lock(&self.inner.db); @@ -814,19 +939,25 @@ impl Core { } } -/// Items that would expire but wait for the other device's receipt ("Waiting for PC"). -/// The SQL only narrows to items with no qualifying peer receipt (the rare, small set); -/// `derive_state` still decides, so the expiry rules stay in one place. +/// Items held here (not in the Bin) that the paired device has not confirmed holding: no receipt +/// from the CURRENTLY paired device for the item's current hash ("PC not found, 3 waiting"). +/// 0 while unpaired. The SQL narrows to the rare set without a receipt; `derive_state` still +/// decides who is in the Bin, so the expiry rules stay in one place. Expiry itself never waits +/// for these items (0.2.0). fn waiting_count(c: &Connection, now: i64) -> Result { + let Some(peer) = store::paired_peer(c)? else { return Ok(0) }; let fmap: HashMap = store::all_folders(c)?.into_iter().map(|f| (f.id, f)).collect(); let candidates = store::item_ids_where( c, - "deleted_at IS NULL AND pinned = 0 AND NOT EXISTS (SELECT 1 FROM receipt r JOIN device d ON d.id = r.device_id WHERE r.blob_hash = item.blob_hash AND d.is_self = 0 AND d.paired_at IS NOT NULL)", + &format!( + "local_file_state = 'present' AND deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM receipt r WHERE r.blob_hash = item.blob_hash AND r.device_id = x'{}')", + hex::encode(peer.id.0) + ), )?; let mut n = 0; for id in candidates { let Some((rec, _)) = store::get_item(c, id)? else { continue }; - if matches!(bin::derive_state_in(c, &fmap, &rec, now)?, ItemState::Waiting) { + if !expiry::in_bin(bin::derive_state_in(c, &fmap, &rec, now)?) { n += 1; } } diff --git a/crates/core/src/folders.rs b/crates/core/src/folders.rs index bf6c239..c19dbc5 100644 --- a/crates/core/src/folders.rs +++ b/crates/core/src/folders.rs @@ -82,16 +82,20 @@ fn sort_key(f: &FolderRecord) -> (u8, String) { (rank, f.name.val.to_lowercase()) } -/// Live folders with item counts (not in the Bin), Inbox first, then Keep, Unsorted, then +/// Live folders with item counts (not in the Bin; `hide_refused` leaves out files this device refused: +/// the PC lists them under Not synced instead), Inbox first, then Keep, Unsorted, then /// user folders by name (case-insensitive). -pub fn folder_views(c: &Connection, now: i64) -> Result> { +pub fn folder_views(c: &Connection, now: i64, hide_refused: bool) -> Result> { let folders = store::all_folders(c)?; let map: HashMap = folders.iter().map(|f| (f.id, f.clone())).collect(); let mut counts: HashMap = HashMap::new(); // Items effectively deleted are in the Bin whatever the rest says: only items that are not // deleted, or that carry a pin (which may outrank an older delete), can be outside it. for id in store::item_ids_where(c, "deleted_at IS NULL OR pinned = 1")? { - let Some((rec, _)) = store::get_item(c, id)? else { continue }; + let Some((rec, lfs)) = store::get_item(c, id)? else { continue }; + if hide_refused && lfs == LocalFileState::Refused { + continue; + } let state = bin::derive_state_in(c, &map, &rec, now)?; if !expiry::in_bin(state) { // E2: an item in a deleted or unknown folder shows under Unsorted. @@ -106,7 +110,7 @@ pub fn folder_views(c: &Connection, now: i64) -> Result> { live.sort_by_key(|f| sort_key(f)); Ok(live .into_iter() - .map(|f| FolderView { id: f.id, kind: f.kind, name: f.name.val.clone(), retention: f.retention.val, count: counts.get(&f.id).copied().unwrap_or(0) }) + .map(|f| FolderView { id: f.id, kind: f.kind, name: crate::names::display_name(&f.name.val, ""), retention: f.retention.val, count: counts.get(&f.id).copied().unwrap_or(0) }) .collect()) } @@ -202,21 +206,21 @@ mod tests { let mut it2 = store::get_item(&db.conn, ItemId(uuid::Uuid::from_u128(0x1002))).unwrap().unwrap().0; it2.deleted = Versioned { v: v(5, p()), val: Some(T0) }; store::update_item(&db.conn, &it2).unwrap(); - let views = folder_views(&db.conn, T0).unwrap(); + let views = folder_views(&db.conn, T0, false).unwrap(); let names: Vec<&str> = views.iter().map(|v| v.name.as_str()).collect(); assert_eq!(names, vec!["Inbox", "Keep", "Unsorted", "Apple", "zebra"]); let count = |n: &str| views.iter().find(|v| v.name == n).unwrap().count; assert_eq!((count("Inbox"), count("Apple"), count("zebra"), count("Keep")), (1, 1, 1, 0)); // Deleting Apple deletes its item too; the folder disappears from the views. ops::delete_folder(&mut db.conn, &Ctx { now: T0 + 1, ..ctx }, a).unwrap(); - let views = folder_views(&db.conn, T0 + 1).unwrap(); + let views = folder_views(&db.conn, T0 + 1, false).unwrap(); assert!(views.iter().all(|v| v.name != "Apple")); assert_eq!(views.iter().map(|v| v.count).sum::(), 2, "Inbox 1 + zebra 1"); // An item that arrives pointing at a deleted folder is shown under Unsorted. let mut stray = item(9, f(), v(2, f())); stray.location.val.folder = a; store::insert_item(&db.conn, &stray, LocalFileState::Pending, T0).unwrap(); - let views = folder_views(&db.conn, T0 + 1).unwrap(); + let views = folder_views(&db.conn, T0 + 1, false).unwrap(); assert_eq!(views.iter().find(|v| v.id == UNSORTED_ID).unwrap().count, 1); } diff --git a/crates/core/src/merge.rs b/crates/core/src/merge.rs index e67c9ce..5c0aafc 100644 --- a/crates/core/src/merge.rs +++ b/crates/core/src/merge.rs @@ -202,12 +202,20 @@ fn validate_remote(record: &Record) -> Result<()> { match record { Record::Item(r) => { check_name("item", &r.name.val)?; - // The extension is used to build paths: only allowlisted extensions pass. - if names::ext_family(&r.content.val.ext).is_none() { - return Err(proto(format!("item {} has extension '{}' which is not allowed", r.id.0, r.content.val.ext))); + // The extension is used to build paths: only safe ones pass (empty, or 1-16 lowercase + // a-z 0-9 - _). A record may carry any file type now, but kind and extension must agree + // (a File with a photo extension would skip the content check, a photo with a document + // extension would get a thumbnail). A record whose NAME or extension is one of the + // always-refused ones is still ACCEPTED as a record (both devices' digests must stay + // equal) and never downloaded (sync::net::fetch_item). + let ext = &r.content.val.ext; + if !names::is_safe_ext(ext) { + return Err(proto(format!("item {} has extension '{}' which cannot be used", r.id.0, ext))); } - if r.content.val.ext != r.content.val.ext.to_ascii_lowercase() { - return Err(proto("item extension must be lowercase")); + match (r.content.val.kind, names::ext_family(ext)) { + (MediaKind::File, None) => {} + (MediaKind::Image | MediaKind::Video, Some(fam)) if fam.kind() == r.content.val.kind => {} + _ => return Err(proto(format!("item {} has kind {:?} and extension '{}' which do not belong together", r.id.0, r.content.val.kind, ext))), } if r.content.val.size > i64::MAX as u64 || r.content.val.thumb.as_ref().is_some_and(|t| t.size > i64::MAX as u64) { return Err(proto("item size out of range")); @@ -759,13 +767,56 @@ mod tests { let r = Record::Receipt(ReceiptRecord { hash: hash(1), device: f(), received_at: 77 }); let a = apply_remote(&d.conn, p(), f(), &r, T0).unwrap(); assert_eq!(a.changed, Some(EntityKey::Receipt { hash: hash(1), device: f() })); - assert_eq!(store::peer_receipt_seen_at(&d.conn, hash(1)).unwrap(), Some(T0)); + assert!(store::peer_has_receipt(&d.conn, hash(1), f()).unwrap()); let a = apply_remote(&d.conn, p(), f(), &r, T0 + 5).unwrap(); assert_eq!(a.changed, None, "duplicate"); - assert_eq!(store::peer_receipt_seen_at(&d.conn, hash(1)).unwrap(), Some(T0), "seen_at not moved by a duplicate"); + let seen: i64 = d.conn.query_row("SELECT seen_at FROM receipt", [], |r| r.get(0)).unwrap(); + assert_eq!(seen, T0, "seen_at not moved by a duplicate"); assert_eq!(store::head_seq(&d.conn).unwrap(), 0, "M9: remote-applied changes are not logged"); } + // 0.2.0: any file type. validate_remote accepts a File with a safe extension (or none), keeps + // kind and extension together, and still ACCEPTS a refused name (digests stay equal). + #[test] + fn validate_remote_for_any_file_type() { + let rec = |kind: MediaKind, ext: &str, name: &str| { + let mut it = item(3, f(), v(2, f())); + it.content.val.kind = kind; + it.content.val.ext = ext.into(); + it.name.val = name.into(); + Record::Item(it) + }; + for (kind, ext, name) in [ + (MediaKind::File, "pdf", "report.pdf"), + (MediaKind::File, "", "Makefile"), + (MediaKind::File, "tar-gz", "x.tar-gz"), + (MediaKind::File, "exe", "setup.exe"), + (MediaKind::Image, "jpg", "a.jpg"), + (MediaKind::Video, "mp4", "a.mp4"), + // Accepted as records, refused at download time. + (MediaKind::File, "lnk", "x.lnk"), + (MediaKind::File, "", "desktop.ini"), + (MediaKind::File, "", "AUTORUN.INF. "), + ] { + validate_remote(&rec(kind, ext, name)).unwrap_or_else(|e| panic!("{kind:?} {ext:?}: {e}")); + } + for (kind, ext) in [ + (MediaKind::File, "PDF"), + (MediaKind::File, "pd f"), + (MediaKind::File, "../x"), + (MediaKind::File, "a.b"), + (MediaKind::File, "jpg"), + (MediaKind::File, "mp4"), + (MediaKind::Image, "pdf"), + (MediaKind::Image, ""), + (MediaKind::Video, "jpg"), + (MediaKind::Image, "mp4"), + ] { + assert!(validate_remote(&rec(kind, ext, "x")).is_err(), "{kind:?} with ext {ext:?} must be rejected"); + } + assert!(validate_remote(&rec(MediaKind::File, &"x".repeat(17), "x")).is_err()); + } + // L9: a new remote item is Pending; applying logs nothing (M9). #[test] fn new_remote_item_is_pending_and_not_logged() { diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index 79c51c6..def1f96 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -170,6 +170,8 @@ pub enum Retention { pub enum MediaKind { Image, Video, + /// Any other file (0.2.0: any file type syncs). No thumbnail, no photo/video content check. + File, } /// Local-only: what this device physically holds for an item. Never synced. @@ -188,7 +190,8 @@ pub enum LocalFileState { /// Wanted, but the peer answered "not found". Soft: asked again on every connect and every few /// minutes, because the answer is often momentary (renamed in Explorer, drive briefly away). Lost, - /// The received file failed the type check (extension/magic); deleted, never stored. + /// The received file failed the type check (extension/magic) or is an always-refused name; + /// deleted or never downloaded, never stored. Refused, } @@ -213,7 +216,8 @@ pub struct Content { pub hash: BlobHash, pub size: u64, pub kind: MediaKind, - /// Lowercase extension without the dot, from the allowlist (`names`). + /// Lowercase extension without the dot (`names::is_safe_ext`); may be empty (a file with no + /// extension). Photos and videos carry one of the media extensions, every other kind never does. pub ext: String, pub thumb: Option, } @@ -387,9 +391,6 @@ pub enum ItemState { Kept, /// In a folder whose retention is Keep (or an unknown/deleted folder). Label "Keep". FolderKeep, - /// Would expire, but the other device has not confirmed holding the file. - /// Label "Waiting for PC" / "Waiting for phone". - Waiting, /// Label "Expires in 5h". Live { expires_at: i64 }, } @@ -411,8 +412,11 @@ pub struct ItemView { pub local: LocalFileState, /// Local path of the held file (library or Bin), when held. pub path: Option, - /// Local path of the thumbnail, when held. + /// Local path of the thumbnail, when held. Always None for a File. pub thumb_path: Option, + /// In the Bin because it EXPIRED, and the paired device never confirmed holding this file: + /// the item may now exist on this device only (shown as "NOT ON PC" / "NOT ON PHONE"). + pub never_reached_peer: bool, } #[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] diff --git a/crates/core/src/names.rs b/crates/core/src/names.rs index 0f4d446..68493a9 100644 --- a/crates/core/src/names.rs +++ b/crates/core/src/names.rs @@ -14,9 +14,10 @@ //! before the first '.' after N4 (so "con.jpg" and "CON .jpg" are reserved too). //! N6 Length cap: whole file name <= MAX_NAME_UTF16 UTF-16 code units; cut the stem at a //! char boundary, keep the extension. -//! N7 Extension must be on the allowlist AND agree with the magic bytes (`sniff`), so a -//! compromised phone cannot drop .exe, .lnk or desktop.ini into the library. -//! Families and extensions: +//! N7 Photos and videos: the extension must be on the media list AND agree with the magic +//! bytes (`sniff`), so a renamed program can never pose as a photo and get a thumbnail. +//! Every other file is a plain file (`MediaKind::File`) with its own safe extension (or none). +//! Media families and extensions: //! Jpeg: jpg jpeg magic FF D8 FF //! Png: png magic 89 50 4E 47 0D 0A 1A 0A //! Gif: gif magic "GIF87a" | "GIF89a" @@ -29,9 +30,14 @@ //! Agreement: the extension's family equals the sniffed family, except that the video //! containers Mp4/Mov/ThreeGp accept each other (phones mislabel them; all are ISO-BMFF //! video). Extension compare is case-insensitive; the stored ext is lowercase. +//! N7b Always refused, both directions (R1, 0.2.0): .lnk .url .scf .library-ms +//! .searchConnector-ms, desktop.ini, autorun.inf. Matched on the cleaned name (NFC, control +//! and bidi characters out, trailing dots and spaces out, case-insensitive, an NTFS stream +//! suffix ":..." ignored), on the record's extension and on the final disk name. //! N8 Empty after cleaning -> Empty. The caller then uses `fallback_name`. -//! N9 Collisions on disk: `disambiguate` adds " (2)", " (3)", ... before the extension, -//! lowest free number; the record keeps the original name (PLAN Storage). +//! N9 Collisions on disk: `disambiguate` adds " (2)", " (3)", ... before the extension (the +//! `ext_of` rule: up to 16 letters, digits, '-' or '_'), lowest free number; the record +//! keeps the original name (PLAN Storage). //! Folder names (`clean_folder_name`): N1-N6 without the extension rules, plus a leading '.' //! is rejected (protects the hidden `.tugboat` marker folder and avoids hidden folders). @@ -62,12 +68,25 @@ pub enum NameError { Reserved(String), #[error("folder name starts with '.'")] LeadingDot, - #[error("extension '{0}' is not an allowed photo or video type")] + /// A file extension that cannot be part of a path (not 1-16 of a-z 0-9 '-' '_'). + #[error("extension '{0}' cannot be used")] ExtensionNotAllowed(String), + /// A photo or video extension whose content is not a photo or video. #[error("file content is not a photo or video")] NotMedia, #[error("extension '{ext}' does not match the file content ({detected:?})")] MagicMismatch { ext: String, detected: Family }, + /// One of the always-refused names or extensions (the payload is what was refused). + #[error("REFUSED - shortcut and folder-setting files never sync")] + Refused(String), + /// A received record whose kind and extension disagree (a File with a photo extension, or a + /// photo/video with another extension). + #[error("the file kind does not match its extension '{0}'")] + KindMismatch(String), + /// A folder name ending in ".{GUID}": Explorer treats it as a shell junction (it shows the + /// text before the dot and opens a system folder), which would hide the files inside. + #[error("folder name ends in a shell class id")] + ShellJunction, } #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -172,6 +191,136 @@ pub fn check_media(ext: &str, head: &[u8]) -> Result<(String, Family), NameError Ok((ext_l, detected)) } +/// Longest extension `ext_of` / `is_safe_ext` accept. +pub const MAX_EXT_LEN: usize = 16; + +/// What a refusal says, everywhere (activity row, banner, Not synced list). +pub const REFUSED_TEXT: &str = "REFUSED - shortcut and folder-setting files never sync"; + +/// Extensions that are always refused (lowercase, no dot). +const REFUSED_EXTS: [&str; 5] = ["lnk", "url", "scf", "library-ms", "searchconnector-ms"]; +/// File names that are always refused (lowercase). +const REFUSED_NAMES: [&str; 2] = ["desktop.ini", "autorun.inf"]; + +/// Display-name preparation shared by `ext_of` and `is_refused_name`: NFC, control and bidi +/// characters out, trailing dots and spaces out (Windows drops them silently, so "x.lnk. " IS +/// "x.lnk" on disk). Order matters: `ext_of("a.pdf.")` must see "pdf". +pub fn prep(name: &str) -> String { + let s: String = name.nfc().filter(|c| !c.is_control() && !is_bidi(*c)).collect(); + s.trim_end_matches(['.', ' ']).to_string() +} + +fn ext_chars_ok(ext: &str) -> bool { + (1..=MAX_EXT_LEN).contains(&ext.len()) && ext.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +/// Extension of a file name: the text after the LAST '.' of the prepared name when that dot is +/// not its first character and the text is 1..=16 of `a-z 0-9 - _` (any case in, lowercase +/// out). Otherwise "" (no extension): "Makefile", ".gitignore", "x.weird ext". +pub fn ext_of(name: &str) -> String { + let s = prep(name); + match s.rfind('.') { + Some(i) if i > 0 && ext_chars_ok(&s[i + 1..]) => s[i + 1..].to_ascii_lowercase(), + _ => String::new(), + } +} + +/// An extension that may become part of a path: empty, or 1..=16 lowercase `a-z 0-9 - _`. +/// Used on every extension that comes from a record before it is used in a path. The one +/// exception to the length cap is an always-refused extension (`searchconnector-ms` has 18 +/// characters): such a record must still be accepted as a record so both devices' digests stay +/// equal, then refused at download time (`is_refused_record`); it never reaches a path. +pub fn is_safe_ext(ext: &str) -> bool { + ext.is_empty() || ((ext_chars_ok(ext) || REFUSED_EXTS.contains(&ext)) && ext == ext.to_ascii_lowercase()) +} + +/// The record's extension is one of the always-refused ones (a record can carry an extension +/// whose name is harmless: name "x", ext "lnk", which the disk name would join into "x.lnk"). +pub fn is_refused_ext(ext: &str) -> bool { + let e: String = ext.trim_start_matches('.').nfc().collect::().to_lowercase(); + REFUSED_EXTS.contains(&e.as_str()) +} + +/// The always-refused names (module doc N7b). Checks the whole prepared name, its last path +/// segment, and both without an NTFS stream suffix (`x.lnk::$DATA` is the file `x.lnk`). +pub fn is_refused_name(name: &str) -> bool { + let s = prep(name).to_lowercase(); + let segment = s.rsplit(['/', '\\']).next().unwrap_or("").to_string(); + let refused = |t: &str| { + let t = t.trim_end_matches(['.', ' ']); + REFUSED_NAMES.contains(&t) || REFUSED_EXTS.iter().any(|e| t.len() > e.len() && t.ends_with(&format!(".{e}"))) + }; + let mut found = false; + for cand in [s.as_str(), segment.as_str()] { + let main = cand.split(':').next().unwrap_or(""); + found |= refused(cand) || refused(main); + } + found +} + +/// "stem" or "stem.ext". +pub fn join_ext(stem: &str, ext: &str) -> String { + if ext.is_empty() { + stem.to_string() + } else { + format!("{stem}.{ext}") + } +} + +/// Media family of a file NAME (by extension only). Some = make a thumbnail and apply the +/// photo/video content check; None = a plain file. +pub fn media_family_of_name(name: &str) -> Option { + ext_family(&ext_of(name)) +} + +/// What a file with this extension and these first bytes is. +/// - refused extension -> `Refused`; +/// - photo/video extension -> the content must match (`check_media`), else `MagicMismatch` / +/// `NotMedia`: a renamed program never poses as a photo; +/// - any other safe extension, or none -> `(File, ext)`. No promotion: "" + JPEG bytes stays a +/// File named as it is (renaming the user's file is never ours to do). +pub fn classify(ext: &str, head: &[u8]) -> Result<(MediaKind, String), NameError> { + let ext = ext.trim_start_matches('.').to_ascii_lowercase(); + if is_refused_ext(&ext) { + return Err(NameError::Refused(ext)); + } + if ext_family(&ext).is_some() { + let (e, fam) = check_media(&ext, head)?; + return Ok((fam.kind(), e)); + } + if !is_safe_ext(&ext) { + return Err(NameError::ExtensionNotAllowed(ext)); + } + Ok((MediaKind::File, ext)) +} + +/// Check a RECEIVED record's kind and extension against the bytes (never re-derives them): +/// photo/video -> a media extension of that kind whose content matches; File -> a safe, +/// non-media extension. Refused extensions are always an error. +pub fn verify_received(kind: MediaKind, ext: &str, head: &[u8]) -> Result<(), NameError> { + if is_refused_ext(ext) { + return Err(NameError::Refused(ext.to_string())); + } + match kind { + MediaKind::File => { + if ext_family(ext).is_some() { + return Err(NameError::KindMismatch(ext.to_string())); + } + if !is_safe_ext(ext) { + return Err(NameError::ExtensionNotAllowed(ext.to_string())); + } + Ok(()) + } + MediaKind::Image | MediaKind::Video => { + let fam = ext_family(ext).ok_or_else(|| NameError::KindMismatch(ext.to_string()))?; + if fam.kind() != kind { + return Err(NameError::KindMismatch(ext.to_string())); + } + check_media(ext, head).map(|_| ()) + } + } +} + /// N1-N4, shared by file stems and folder names. fn clean_common(raw: &str) -> Result { let s: String = raw.nfc().filter(|c| !c.is_control() && !is_bidi(*c)).collect(); @@ -249,15 +398,31 @@ pub fn strip_ext<'a>(name: &'a str, ext: &str) -> &'a str { } } -/// The on-disk file name for a received item: clean_stem(record name without its extension) -/// + "." + the checked ext; on Err(Empty | Reserved | Colon | ...) uses -/// `fallback_name(captured_at, family)` instead (the file is still accepted; only N7 -/// failures refuse the file). Returns (name, family). -pub fn disk_file_name(record_name: &str, ext: &str, head: &[u8], captured_at_ms: i64) -> Result<(String, Family), NameError> { - // N7 first: a type failure refuses the file whatever the name looks like. - let (ext, family) = check_media(ext.trim_start_matches('.'), head)?; - let room = MAX_NAME_UTF16.saturating_sub(1 + ext.len()); - let stem = match clean_stem(strip_ext(record_name, &ext)) { +/// The on-disk file name for a received item: the cleaned record name without its extension, +/// plus "." and the checked extension (no dot when the extension is empty). A name that does not +/// clean (empty, reserved, a colon, ...) falls back to `fallback_stem(captured_at)`: the file is +/// still accepted, and only type and refusal failures refuse it (decision B: the made-up name keeps +/// today's `IMG_` look whatever the kind). Returns (name, kind). A final name that is one of the +/// always-refused ones (`desktop` + extension `ini`) is `Refused` too. +pub fn disk_file_name(record_name: &str, ext: &str, head: &[u8], captured_at_ms: i64) -> Result<(String, MediaKind), NameError> { + // Type first: a type failure refuses the file whatever the name looks like. + let (kind, ext) = classify(ext, head)?; + let mut name = build_disk_name(record_name, &ext, captured_at_ms); + // A plain file never lands under a photo/video name (Explorer would thumbnail and open it as a + // photo): a File record without an extension whose name ends in one gets the made-up name. + if kind == MediaKind::File && ext.is_empty() && media_family_of_name(&name).is_some() { + name = fallback_stem(captured_at_ms); + } + if is_refused_name(&name) { + return Err(NameError::Refused(name)); + } + Ok((name, kind)) +} + +/// The cleaned "stem.ext" `disk_file_name` builds (no type check, no refusal check). +fn build_disk_name(record_name: &str, ext: &str, captured_at_ms: i64) -> String { + let room = MAX_NAME_UTF16.saturating_sub(if ext.is_empty() { 0 } else { 1 + ext.len() }); + let stem = match clean_stem(strip_ext(record_name, ext)) { Ok(s) => { let capped = cap_utf16(&s, room); if capped.is_empty() { @@ -268,7 +433,15 @@ pub fn disk_file_name(record_name: &str, ext: &str, head: &[u8], captured_at_ms: } Err(_) => fallback_stem(captured_at_ms), }; - Ok((format!("{stem}.{ext}"), family)) + join_ext(&stem, ext) +} + +/// A synced record that must never be downloaded: its extension, its name, or the disk name this +/// device would build from them is one of the always-refused ones (amendment 1: name "a:b" with +/// ext "lnk" would otherwise become `IMG_