Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Heartbeat after a lapse, an account's reminder pictures, and smaller fixes

Yashwanth Kamireddi4b0afc6ec42e
diff --git a/.uiverify/settings-flatpak.mjs b/.uiverify/settings-flatpak.mjs
new file mode 100644
index 0000000..6cda494
--- /dev/null
+++ b/.uiverify/settings-flatpak.mjs
@@ -0,0 +1,32 @@
+// In the Flatpak: Open at Login is not a switch that says "on" over an entry the desktop never
+// reads — the row says how to add Skykeep to the desktop's startup apps instead. Outside it the
+// switch is there as before.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub } from "./stub.mjs";
+const BASE = process.env.BASE ?? process.env.URL ?? "http://localhost:4173";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+for (const flatpak of [true, false]) {
+ const ctx = await b.newContext({ viewport: { width: 1200, height: 900 } });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+ if (flatpak) await ctx.addInitScript(() => { window.__login = { available: false, command: "flatpak run io.github.yashwanthkamireddi.Skykeep" }; });
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); failures++; });
+ await page.goto(BASE, { waitUntil: "networkidle" });
+ await page.locator(".sidebar-account").click();
+ await page.waitForSelector(".settings");
+ await page.waitForTimeout(300);
+ const sw = page.getByRole("switch", { name: "Open at Login" });
+ const row = page.locator(".settings-row", { hasText: "Open at Login" });
+ if (flatpak) {
+ ok((await sw.count()) === 0, "Flatpak: no switch that cannot do what it says");
+ ok(/startup apps/.test(await row.innerText()), `and the row says how [${(await row.innerText()).replace(/\n/g, " · ")}]`);
+ } else {
+ ok((await sw.count()) === 1, "elsewhere: the switch is there");
+ }
+ await ctx.close();
+}
+await b.close();
+console.log(failures ? `\n${failures} FAILED` : "\nall passed");
+process.exit(failures ? 1 : 0);
diff --git a/crates/quince-core/src/contacts.rs b/crates/quince-core/src/contacts.rs
index 07ceb14..bf6b721 100644
--- a/crates/quince-core/src/contacts.rs
+++ b/crates/quince-core/src/contacts.rs
@@ -579,10 +579,9 @@ impl Library {
} else if keep.is_empty() {
tx.execute("DELETE FROM contacts", [])?;
} else {
- let placeholders = vec!["?"; keep.len()].join(",");
tx.execute(
- &format!("DELETE FROM contacts WHERE guid NOT IN ({placeholders})"),
- rusqlite::params_from_iter(keep),
+ "DELETE FROM contacts WHERE guid NOT IN (SELECT value FROM json_each(?1))",
+ params![crate::id_list(&keep)],
)?;
}
}
diff --git a/crates/quince-core/src/drive.rs b/crates/quince-core/src/drive.rs
index daf6e2b..a8598f5 100644
--- a/crates/quince-core/src/drive.rs
+++ b/crates/quince-core/src/drive.rs
@@ -95,14 +95,10 @@ impl Library {
params![parent_id],
)?;
} else {
- let placeholders = vec!["?"; keep.len()].join(",");
- let mut args: Vec<&str> = vec![parent_id];
- args.extend(keep);
tx.execute(
- &format!(
- "DELETE FROM drive_items WHERE parent_id = ? AND drivewsid NOT IN ({placeholders})"
- ),
- rusqlite::params_from_iter(args),
+ "DELETE FROM drive_items WHERE parent_id = ?1
+ AND drivewsid NOT IN (SELECT value FROM json_each(?2))",
+ params![parent_id, crate::id_list(&keep)],
)?;
}
}
@@ -373,3 +369,34 @@ mod tests {
assert!(lib.drive_item("nope").unwrap().is_none());
}
}
+
+#[cfg(test)]
+mod many_tests {
+ use super::*;
+
+ /// A folder past SQLite's 32,766 parameters (a camera's dump): stored, and pruned, in one
+ /// statement. One parameter per kept item failed its store on every pass.
+ #[test]
+ fn a_folder_of_forty_thousand_files_is_stored_and_pruned() {
+ let mut lib = Library::in_memory().unwrap();
+ let item = |i: usize| DriveItem {
+ drivewsid: format!("FILE::{i}"),
+ parent_id: Some("root".into()),
+ name: format!("IMG_{i}.jpg"),
+ extension: Some("jpg".into()),
+ kind: "FILE".into(),
+ size: Some(1),
+ child_count: None,
+ created_at: None,
+ modified_at: None,
+ etag: None,
+ };
+ let mut items: Vec<DriveItem> = (0..40_000).map(item).collect();
+ lib.put_drive_children("root", &items).unwrap();
+ items.truncate(39_999);
+ lib.put_drive_children("root", &items).unwrap();
+ let kept = lib.drive_children("root").unwrap();
+ assert_eq!(kept.len(), 39_999);
+ assert!(kept.iter().all(|i| i.drivewsid != "FILE::39999"));
+ }
+}
diff --git a/crates/quince-icloud/src/occasions.rs b/crates/quince-icloud/src/occasions.rs
index a624d32..cb5c026 100644
--- a/crates/quince-icloud/src/occasions.rs
+++ b/crates/quince-icloud/src/occasions.rs
@@ -287,7 +287,11 @@ pub fn parse_feed(ics: &str) -> (Option<String>, Vec<Holiday>) {
"DTSTART" => {
if let Some(c) = current.as_mut() {
c.2 = value(line).and_then(|v| {
- let d = v.get(..8)?;
+ // Digits only: sliced by byte, a feed's stray accented character there
+ // panicked rather than being skipped.
+ let d = v
+ .get(..8)
+ .filter(|d| d.bytes().all(|b| b.is_ascii_digit()))?;
format!("{}-{}-{}", &d[..4], &d[4..6], &d[6..8])
.parse()
.ok()
@@ -391,6 +395,15 @@ pub async fn fetch_feed(http: &reqwest::Client, region: &str, lang: &str) -> Res
#[cfg(test)]
mod tests {
+
+ /// A start date with an accented character where the digits go is skipped, not a panic.
+ #[test]
+ fn a_damaged_start_date_is_skipped_not_a_panic() {
+ let ics = "BEGIN:VCALENDAR\nBEGIN:VEVENT\nSUMMARY:Odd\nDTSTART;VALUE=DATE:202\u{e9}0101\nEND:VEVENT\nEND:VCALENDAR\n";
+ let (_, found) = parse_feed(ics);
+ assert!(found.is_empty() || found.iter().all(|h| h.title != "Odd"));
+ }
+
use super::*;
fn contact(guid: &str, first: &str, birthday: &str) -> Contact {
diff --git a/src-tauri/src/login.rs b/src-tauri/src/login.rs
index 774d443..f724e6f 100644
--- a/src-tauri/src/login.rs
+++ b/src-tauri/src/login.rs
@@ -96,6 +96,15 @@ pub struct LoginItem {
/// Whether this desktop runs autostart entries at login. `false`: the entry alone does
/// nothing here, and `command` has to go in the compositor's own startup.
pub honoured: bool,
+ /// Whether Skykeep can keep the entry itself. Not in a Flatpak: the entry was written in the
+ /// sandbox's own config folder, which the desktop never reads, and the switch said "on"
+ /// over nothing at all. There Settings says how to add it instead.
+ pub available: bool,
+}
+
+/// Running inside a Flatpak.
+fn in_flatpak() -> bool {
+ std::env::var_os("FLATPAK_ID").is_some()
}
#[cfg(not(windows))]
@@ -112,7 +121,7 @@ fn entry(app: &AppHandle) -> Option<PathBuf> {
fn command() -> String {
let program = std::env::var_os("APPIMAGE")
.map(PathBuf::from)
- .or_else(|| std::env::current_exe().ok())
+ .or_else(|| std::env::current_exe().ok().map(|p| still_installed(&p)))
.unwrap_or_else(|| PathBuf::from("quince-app"));
// Windows reads the Run value as a command line: the path in plain quotes.
if cfg!(windows) {
@@ -121,6 +130,14 @@ fn command() -> String {
format!("{} {FLAG}", quoted(&program.to_string_lossy()))
}
+/// The program as installed: replaced by a package upgrade while running, Linux names the
+/// running one `/usr/bin/skykeep (deleted)`, and an entry written then pointed at nothing.
+fn still_installed(path: &std::path::Path) -> PathBuf {
+ path.to_str()
+ .and_then(|p| p.strip_suffix(" (deleted)"))
+ .map_or_else(|| path.to_path_buf(), PathBuf::from)
+}
+
/// A program path as the Desktop Entry spec wants it in Exec: in double quotes, with `"`,
/// `` ` ``, `$` and `\` escaped, and `%` doubled — alone it starts a field code (`%f`, `%u`),
/// which the launcher would replace with something else.
@@ -214,6 +231,7 @@ pub async fn login_item_status(_app: AppHandle) -> Result<LoginItem, String> {
on,
command: command(),
honoured: true,
+ available: true,
})
}
@@ -243,6 +261,14 @@ pub async fn login_item_set(on: bool, app: AppHandle) -> Result<LoginItem, Strin
#[cfg(not(windows))]
#[tauri::command]
pub async fn login_item_status(app: AppHandle) -> Result<LoginItem, String> {
+ if in_flatpak() {
+ return Ok(LoginItem {
+ on: false,
+ command: format!("flatpak run {}", app.config().identifier),
+ honoured: true,
+ available: false,
+ });
+ }
let on = entry(&app).is_some_and(|p| p.exists());
let honoured = tauri::async_runtime::spawn_blocking(honoured)
.await
@@ -251,12 +277,16 @@ pub async fn login_item_status(app: AppHandle) -> Result<LoginItem, String> {
on,
command: command(),
honoured,
+ available: true,
})
}
#[cfg(not(windows))]
#[tauri::command]
pub async fn login_item_set(on: bool, app: AppHandle) -> Result<LoginItem, String> {
+ if in_flatpak() {
+ return Err("Add Skykeep to your desktop’s startup apps to open it at login.".into());
+ }
let path = entry(&app).ok_or("There is no configuration folder to keep it in.")?;
if on {
if let Some(dir) = path.parent() {
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index b082cdf..28e1203 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1159,7 +1159,7 @@ pub const ACCOUNT_KEY: &str = "account";
/// What of an account lives in the data folder beside the session: its library, and every
/// cache and queue made from it. Moved as one when another account signs in.
-const ACCOUNT_FILES: [&str; 12] = [
+const ACCOUNT_FILES: [&str; 13] = [
"library.db",
"library.db-wal",
"library.db-shm",
@@ -1172,6 +1172,8 @@ const ACCOUNT_FILES: [&str; 12] = [
"note-files",
"note-media",
"faces",
+ // A reminder's pictures: one account's, set aside and removed with the rest of it.
+ "reminder-media",
];
/// Where the accounts not signed in are kept, each under its own tag.
@@ -1730,23 +1732,36 @@ async fn account_services(auth: State<'_, Auth>) -> UiResult<Vec<String>> {
fn spawn_heartbeat(client: Arc<Mutex<Client>>) {
tauri::async_runtime::spawn(async move {
const INTERVAL: Duration = Duration::from_secs(45 * 60);
+ // The session that lapsed, by its token: not pinged again — but a new one, signed in
+ // since, is. Ended at the first lapse instead, a tray left running for weeks never kept
+ // the next sign-in warm.
+ let mut lapsed: Option<Option<String>> = None;
loop {
tokio::time::sleep(INTERVAL).await;
let mut guard = client.lock().await;
- // Only meaningful once signed in; before that there is nothing to keep warm.
- if guard.session().webservices.is_none() {
+ let session = guard.session();
+ let token = session.session_token.clone();
+ if !worth_a_ping(session.webservices.is_some(), &token, lapsed.as_ref()) {
continue;
}
// A lapsed session is expected roughly every two months. The UI discovers it on
// next use and asks for a code; nothing to do here but stop pinging a dead one.
- // A transient error is not proof of that, so only a clean `false` ends the loop.
- if matches!(guard.heartbeat().await, Ok(false)) {
- break;
+ // A transient error is not proof of that, so only a clean `false` counts. Each
+ // ping also writes the session again if a keyring would not take it before.
+ match guard.heartbeat().await {
+ Ok(false) => lapsed = Some(token),
+ Ok(true) => lapsed = None,
+ Err(_) => {}
}
}
});
}
+/// Whether the heartbeat pings the session now: signed in, and not the one that lapsed.
+fn worth_a_ping(signed_in: bool, token: &Option<String>, lapsed: Option<&Option<String>>) -> bool {
+ signed_in && lapsed != Some(token)
+}
+
/// Refresh the calendar window `[from, to]` (both `YYYY-MM-DD`) from Apple.
///
/// The interface does not wait on this to render: it reads the library, which still holds
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index fb006ba..655e071 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -928,7 +928,13 @@ export function turnStyle(turn: Turn | null | undefined, w: number, h: number, z
}
/** The iCloud Drive folder on this computer (see src-tauri/src/mount.rs). */
-export type LoginItem = { on: boolean; command: string; honoured: boolean };
+export type LoginItem = {
+ on: boolean;
+ command: string;
+ honoured: boolean;
+ /** Whether Skykeep keeps the login entry itself (not in the Flatpak). */
+ available?: boolean;
+};
export type DriveFolder = {
on: boolean;
diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsx
index 9a5ac62..3634aac 100644
--- a/src/screens/SettingsView.tsx
+++ b/src/screens/SettingsView.tsx
@@ -735,39 +735,50 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom
</div>
<WeekStartRow />
<MoveCheckedRow />
- <div className="settings-row">
- <span className="settings-label settings-stack">
- Open at Login
- <span className="settings-hint">
- {login?.on && !login.honoured
- ? "This desktop doesn't open apps at login by itself. Add this to its startup:"
- : "Starts in the background, so alerts ring and changes sync"}
+ {login?.available === false ? (
+ <div className="settings-row">
+ <span className="settings-label settings-stack">
+ Open at Login
+ <span className="settings-hint">
+ Add Skykeep to your desktop’s startup apps, so alerts ring and changes sync from the moment you log in
+ </span>
</span>
- {login?.on && !login.honoured && <code className="settings-command">{login.command}</code>}
- </span>
- <button
- className="switch"
- role="switch"
- aria-checked={login?.on ?? false}
- aria-label="Open at Login"
- disabled={!login || loginBusy}
- onClick={() => {
- if (!login) return;
- const was = login;
- setLogin({ ...login, on: !login.on });
- setLoginBusy(true);
- api
- .loginItemSet(!was.on)
- .then(setLogin, (e) => {
- setLogin(was);
- setError(messageOf(e));
- })
- .finally(() => setLoginBusy(false));
- }}
- >
- <span className="switch-knob" />
- </button>
- </div>
+ </div>
+ ) : (
+ <div className="settings-row">
+ <span className="settings-label settings-stack">
+ Open at Login
+ <span className="settings-hint">
+ {login?.on && !login.honoured
+ ? "This desktop doesn't open apps at login by itself. Add this to its startup:"
+ : "Starts in the background, so alerts ring and changes sync"}
+ </span>
+ {login?.on && !login.honoured && <code className="settings-command">{login.command}</code>}
+ </span>
+ <button
+ className="switch"
+ role="switch"
+ aria-checked={login?.on ?? false}
+ aria-label="Open at Login"
+ disabled={!login || loginBusy}
+ onClick={() => {
+ if (!login) return;
+ const was = login;
+ setLogin({ ...login, on: !login.on });
+ setLoginBusy(true);
+ api
+ .loginItemSet(!was.on)
+ .then(setLogin, (e) => {
+ setLogin(was);
+ setError(messageOf(e));
+ })
+ .finally(() => setLoginBusy(false));
+ }}
+ >
+ <span className="switch-knob" />
+ </button>
+ </div>
+ )}
</section>
<h2 className="settings-heading">Notifications</h2>