Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
fix(desktop): folder sync says when the phone keeps it out
Bee4a30852a453c
diff --git a/desktop/app/i18n/rust_strings.h b/desktop/app/i18n/rust_strings.hindex 8ecd11e..c722782 100644--- a/desktop/app/i18n/rust_strings.h+++ b/desktop/app/i18n/rust_strings.h@@ -256,8 +256,10 @@ static const char *const nectarlink_rust_strings[] = {QT_TRANSLATE_NOOP("Errors", "The device didn't answer in time."), // desktop/app/src/bridge/app.rsQT_TRANSLATE_NOOP("Errors", "The device isn't connected right now."), // desktop/app/src/bridge/app.rsQT_TRANSLATE_NOOP("Errors", "The device's app doesn't support that yet."), // desktop/app/src/bridge/app.rs+ QT_TRANSLATE_NOOP("FolderSync", "Couldn't read the folder on the phone. Check that it's connected."), // desktop/app/src/folder_sync.rsQT_TRANSLATE_NOOP("FolderSync", "Folders are up to date."), // desktop/app/src/folder_sync.rsQT_TRANSLATE_NOOP("FolderSync", "Synced %1 file(s)."), // desktop/app/src/folder_sync.rs+ QT_TRANSLATE_NOOP("FolderSync", "The phone hasn't let this PC into its files yet. Allow it on the phone."), // desktop/app/src/folder_sync.rsQT_TRANSLATE_NOOP("Guide", "1. Install NectarLink on your PC (Windows 11 or Linux) and your Android phone (Android 8.0 or newer).\n2. Connect both devices to the same Wi-Fi network, or plug your phone into your PC with a USB cable.\n3. Open the Pair step in the setup walkthrough, or click + (Pair a new device) at the bottom of the left rail.\n4. Scan the QR code from the NectarLink Android app, or select your phone from the nearby devices list and confirm that the 6-digit code matches on both screens.\n5. Choose which features to share for that phone and grant only the Android permissions you want to use."), // desktop/app/src/bridge/app.rsQT_TRANSLATE_NOOP("Guide", "Android permissions and why each is optional"), // desktop/app/src/bridge/app.rsQT_TRANSLATE_NOOP("Guide", "Automations"), // desktop/app/src/bridge/app.rsdiff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qmlindex 1ade667..fc36e6e 100644--- a/desktop/app/qml/pages/SettingsPage.qml+++ b/desktop/app/qml/pages/SettingsPage.qml@@ -260,8 +260,7 @@ Item {FolderDialog {id: folderSyncPcPickertitle: qsTr("Sync into")- // file:///C:/x becomes C:/x on Windows, file:///home/x /home/x on Linux.- onAccepted: folderSyncSheet.pcFolder = decodeURIComponent(selectedFolder.toString().replace(/^file:\/\/(\/(?=[A-Za-z]:))?/, ""))+ onAccepted: folderSyncSheet.pcFolder = Preferences.localFolder(selectedFolder.toString())}FolderDialog {@@ -3453,7 +3452,7 @@ Item {wrapMode: Text.WordWraprole: "body"muted: true- text: qsTr("The phone needs to let NectarLink read this folder: All files access, or this folder under Selected folders, in NectarLink's settings on the phone.")+ text: qsTr("The phone asks once to let this PC in. NectarLink there also needs All files access, or this folder under Selected folders only.")}Txt { text: qsTr("Folder on the phone"); role: "label" }diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rsindex ee8a926..50f118b 100644--- a/desktop/app/src/bridge/prefs.rs+++ b/desktop/app/src/bridge/prefs.rs@@ -205,6 +205,10 @@ pub mod qobject {#[qinvokable]#[cxx_name = "suggestedSyncFolder"]fn suggested_sync_folder(self: &Preferences, phone_folder: &QString) -> QString;+ /// The local path of a folder the picker chose (a `file:` URL), or empty.+ #[qinvokable]+ #[cxx_name = "localFolder"]+ fn local_folder(self: &Preferences, url: &QString) -> QString;/// Removes a folder sync rule by ID.#[qinvokable]fn remove_folder_sync_rule(self: Pin<&mut Preferences>, rule_id: &QString);@@ -870,16 +874,9 @@ impl qobject::Preferences {}pub fn choose_recordings_folder(mut self: Pin<&mut Self>, url: &QString) {- let raw = QUrl::from(url)- .to_local_file()- .map(|p| String::from(&p))- .filter(|s| !s.is_empty())- .unwrap_or_else(|| String::from(url));- let trimmed = raw.trim();- if trimmed.is_empty() {+ let Some(path) = folder_from_url(url) else {return;- }- let path = PathBuf::from(trimmed);+ };self.as_mut().rust_mut().custom_recordings_folder = Some(path.clone());self.as_mut().set_recordings_folder(QString::from(&path.to_string_lossy().into_owned()));self.as_mut().set_recordings_folder_is_default(false);@@ -944,6 +941,10 @@ impl qobject::Preferences {QString::from(&path.map(|p| p.to_string_lossy().into_owned()).unwrap_or_default())}+ pub fn local_folder(&self, url: &QString) -> QString {+ QString::from(&folder_from_url(url).map(|p| p.to_string_lossy().into_owned()).unwrap_or_default())+ }+pub fn remove_folder_sync_rule(mut self: Pin<&mut Self>, rule_id: &QString) {let id = String::from(rule_id);let mut rules = crate::settings::folder_sync_rules();@@ -1152,9 +1153,37 @@ fn new_rule_id<'a>(prefix: &str, taken: impl Iterator<Item = &'a str>) -> String}}+/// The folder a picker's `file:` URL (or a plain path) names, with this+/// system's separators: Qt gives `C:/x`, and a network share keeps its `//`.+fn folder_from_url(url: &QString) -> Option<PathBuf> {+ let raw = QUrl::from(url)+ .to_local_file()+ .map(|p| String::from(&p))+ .filter(|s| !s.is_empty())+ .unwrap_or_else(|| String::from(url));+ let trimmed = raw.trim();+ if trimmed.is_empty() {+ return None;+ }+ #[cfg(windows)]+ let trimmed = trimmed.replace('/', "\\");+ Some(PathBuf::from(trimmed))+}+#[cfg(test)]mod tests {- use super::new_rule_id;+ use super::{folder_from_url, new_rule_id};+ use cxx_qt_lib::QString;++ #[cfg(windows)]+ #[test]+ fn a_chosen_folder_reads_as_a_windows_path() {+ let path = |url: &str| folder_from_url(&QString::from(url)).map(|p| p.to_string_lossy().into_owned());+ assert_eq!(path("file:///C:/Users/me/Phone%20sync").as_deref(), Some(r"C:\Users\me\Phone sync"));+ assert_eq!(path("file://server/share/photos").as_deref(), Some(r"\\server\share\photos"));+ assert_eq!(path("D:/plain").as_deref(), Some(r"D:\plain"));+ assert_eq!(path(" "), None);+ }#[test]fn a_new_rule_never_gets_an_id_in_use() {diff --git a/desktop/app/src/folder_sync.rs b/desktop/app/src/folder_sync.rsindex ffc728a..45be128 100644--- a/desktop/app/src/folder_sync.rs+++ b/desktop/app/src/folder_sync.rs@@ -309,7 +309,11 @@ fn storable_here(name: &str) -> bool {!cfg!(windows) || nectarlink_core::storable_name(name) == name}-async fn list_phone_entries(node: &Node, peer: DeviceId, base_folder: &str) -> Option<Vec<SyncEntry>> {+async fn list_phone_entries(+ node: &Node,+ peer: DeviceId,+ base_folder: &str,+) -> nectarlink_core::Result<Vec<SyncEntry>> {let mut out = Vec::new();let mut queue = std::collections::VecDeque::new();queue.push_back((String::new(), 0usize));@@ -318,7 +322,7 @@ async fn list_phone_entries(node: &Node, peer: DeviceId, base_folder: &str) -> Olet remote_dir = join_phone_path(base_folder, &rel_dir);let entries = match node.storage_list(peer, &remote_dir).await {Ok(list) => list,- Err(_) if rel_dir.is_empty() => return None,+ Err(err) if rel_dir.is_empty() => return Err(err),Err(_) => continue,};for entry in entries {@@ -342,7 +346,7 @@ async fn list_phone_entries(node: &Node, peer: DeviceId, base_folder: &str) -> O}out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));- Some(out)+ Ok(out)}fn temp_part_path(dest: &Path) -> Option<PathBuf> {@@ -515,15 +519,26 @@ async fn pull_phone_file_streaming(Some((meta.size, meta.modified))}-/// Runs all enabled [`FolderSyncRule`]s once against `node`, returning the-/// number of file operations performed.-pub async fn sync_now(node: &Node) -> usize {+/// What one [`sync_now`] pass did.+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]+pub struct SyncReport {+ /// Files copied either way.+ pub copied: usize,+ /// Rules whose phone said no: its "browse this phone's storage" switch+ /// for this PC is off.+ pub refused: usize,+ /// Rules whose phone folder couldn't be read for another reason.+ pub unreadable: usize,+}++/// Runs all enabled [`FolderSyncRule`]s once against `node`.+pub async fn sync_now(node: &Node) -> SyncReport {+ let mut report = SyncReport::default();let rules = settings::folder_sync_rules();if rules.is_empty() {- return 0;+ return report;}let pc_hostname = hostname::get().ok().and_then(|h| h.into_string().ok()).unwrap_or_else(|| "PC".into());- let mut executed = 0usize;for rule in rules.into_iter().filter(|r| r.enabled) {let Ok(peer) = rule.phone_id.parse::<DeviceId>() else {@@ -533,9 +548,17 @@ pub async fn sync_now(node: &Node) -> usize {if std::fs::create_dir_all(&pc_dir).is_err() {continue;}- let Some(phone_files) = list_phone_entries(node, peer, rule.phone_folder.trim_matches('/')).await- else {- continue;+ let phone_files = match list_phone_entries(node, peer, rule.phone_folder.trim_matches('/')).await {+ Ok(files) => files,+ Err(nectarlink_core::Error::Denied) => {+ report.refused += 1;+ continue;+ }+ Err(err) => {+ tracing::debug!(rule = %rule.id, %err, "can't list the phone folder");+ report.unreadable += 1;+ continue;+ }};let pc_files = tokio::task::spawn_blocking({let pc_dir = pc_dir.clone();@@ -567,7 +590,7 @@ pub async fn sync_now(node: &Node) -> usize {if let Some((size, modified)) = pull_phone_file_streaming(node, peer, remote, &dest).await{updated_baseline.insert(rel_path, (size, modified));- executed += 1;+ report.copied += 1;}}SyncAction::PushToPhone { rel_path } => {@@ -579,7 +602,7 @@ pub async fn sync_now(node: &Node) -> usize {let src = pc_dir.join(&rel_path);if let Ok(done) = node.storage_write(peer, remote, &src).await {updated_baseline.insert(rel_path, (done.size, done.modified));- executed += 1;+ report.copied += 1;}}SyncAction::ConflictRenamePcAndPull { rel_path, conflict_rel_path } => {@@ -593,7 +616,7 @@ pub async fn sync_now(node: &Node) -> usize {if let Some((size, modified)) = pull_phone_file_streaming(node, peer, remote, &src).await{updated_baseline.insert(rel_path, (size, modified));- executed += 1;+ report.copied += 1;}}}@@ -602,19 +625,25 @@ pub async fn sync_now(node: &Node) -> usize {baselines().lock().unwrap_or_else(|e| e.into_inner()).insert(rule.id, updated_baseline);}- executed+ report}/// Triggers an immediate folder sync pass on the core runtime.pub fn trigger_sync_now() {core_host::spawn(async {if let Some(node) = core_host::node() {- let count = sync_now(&node).await;- if count > 0 {- crate::bridge::app::show_message(tr!("FolderSync", "Synced %1 file(s).", count));+ let report = sync_now(&node).await;+ // A refusal comes first: it's the one the user has to act on, on the phone.+ let message = if report.refused > 0 {+ tr!("FolderSync", "The phone hasn't let this PC into its files yet. Allow it on the phone.")+ } else if report.copied > 0 {+ tr!("FolderSync", "Synced %1 file(s).", report.copied)+ } else if report.unreadable > 0 {+ tr!("FolderSync", "Couldn't read the folder on the phone. Check that it's connected.")} else {- crate::bridge::app::show_message(tr!("FolderSync", "Folders are up to date."));- }+ tr!("FolderSync", "Folders are up to date.")+ };+ crate::bridge::app::show_message(message);}});}