Compare commits
3
Commits
5e8c6dc7bf
...
4f5459cb94
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f5459cb94 | ||
|
|
89cd1c76bb | ||
|
|
63955bbe97 |
@@ -0,0 +1,55 @@
|
||||
"""note_user_state: a recipient's own pin, archive and place for a shared note
|
||||
|
||||
Revision ID: 0036
|
||||
Revises: 0035
|
||||
Create Date: 2026-10-07
|
||||
|
||||
Pin, archive and board order are personal organization, and until now they were
|
||||
columns on `notes`, so on a shared note they could only ever mean the owner's
|
||||
(#5176). This table holds them for everyone else: one row per (note, person it is
|
||||
shared with) who has pinned, archived or moved it. The owner keeps the note's own
|
||||
columns; a recipient with no row sees the note unpinned, unarchived, in the owner's
|
||||
order.
|
||||
|
||||
`sync_revision` is stamped by the same `ts_set_sync_revision()` trigger the notes
|
||||
and labels use (0015), so a recipient's change reaches their own devices on the one
|
||||
cursor they already page by, and never moves the note on anyone else's.
|
||||
|
||||
## Downgrade
|
||||
|
||||
Drops the table. Recipients lose their own pins and archives; the notes are
|
||||
untouched.
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
revision = "0036"
|
||||
down_revision = "0035"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"note_user_state",
|
||||
sa.Column("note_id", UUID(as_uuid=True), sa.ForeignKey("notes.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column("user_id", UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column("pinned", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("archived", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("position", sa.Integer(), nullable=True),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column("sync_revision", sa.BigInteger(), nullable=True),
|
||||
sa.PrimaryKeyConstraint("note_id", "user_id"),
|
||||
)
|
||||
op.create_index("ix_note_user_state_user_revision", "note_user_state", ["user_id", "sync_revision"])
|
||||
op.execute(
|
||||
"CREATE TRIGGER trg_note_user_state_sync_revision BEFORE INSERT OR UPDATE ON note_user_state "
|
||||
"FOR EACH ROW EXECUTE PROCEDURE ts_set_sync_revision()"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute("DROP TRIGGER IF EXISTS trg_note_user_state_sync_revision ON note_user_state")
|
||||
op.drop_index("ix_note_user_state_user_revision", table_name="note_user_state")
|
||||
op.drop_table("note_user_state")
|
||||
@@ -85,8 +85,9 @@ fun EditorTopBar(
|
||||
onConfirmDelete: () -> Unit,
|
||||
onAction: (EditorAction) -> Unit,
|
||||
) {
|
||||
// Someone else's note (#5175): its text is all that may change here, so the bar
|
||||
// keeps the checklist button and nothing that is the owner's to do.
|
||||
// Someone else's note (#5175): its text, at `edit`, and this account's own pin
|
||||
// and archive (#5176) are all that may change here, so the bar keeps the
|
||||
// checklist button and an overflow of those two, and nothing that is the owner's.
|
||||
val owner = access == NoteAccess.OWNER
|
||||
val dark = isSystemInDarkTheme()
|
||||
TopAppBar(
|
||||
@@ -133,10 +134,10 @@ fun EditorTopBar(
|
||||
)
|
||||
}
|
||||
}
|
||||
if (owner) {
|
||||
if (owner || !note.trashed) {
|
||||
OverflowMenu(
|
||||
note = note,
|
||||
readOnly = readOnly,
|
||||
owner = owner,
|
||||
onPicker = onPicker,
|
||||
onShare = onShare,
|
||||
onConfirmDelete = onConfirmDelete,
|
||||
@@ -278,7 +279,7 @@ private fun savedLabel(
|
||||
@Composable
|
||||
private fun OverflowMenu(
|
||||
note: Note,
|
||||
readOnly: Boolean,
|
||||
owner: Boolean,
|
||||
onPicker: (Picker) -> Unit,
|
||||
onShare: () -> Unit,
|
||||
onConfirmDelete: () -> Unit,
|
||||
@@ -291,7 +292,7 @@ private fun OverflowMenu(
|
||||
Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.editor_more))
|
||||
}
|
||||
DropdownMenu(expanded = open, onDismissRequest = close) {
|
||||
if (readOnly) {
|
||||
if (note.trashed) {
|
||||
MenuItem(R.string.editor_restore, close) { onAction(EditorAction.Restore) }
|
||||
MenuItem(R.string.editor_delete_forever, close, onConfirmDelete)
|
||||
} else {
|
||||
@@ -299,16 +300,20 @@ private fun OverflowMenu(
|
||||
if (note.pinned) R.string.editor_unpin else R.string.editor_pin,
|
||||
close,
|
||||
) { onAction(EditorAction.SetPinned(!note.pinned)) }
|
||||
MenuItem(R.string.editor_labels, close) { onPicker(Picker.LABELS) }
|
||||
if (owner) {
|
||||
MenuItem(R.string.editor_labels, close) { onPicker(Picker.LABELS) }
|
||||
}
|
||||
// Not on a draft: the server has nothing to share until it is saved.
|
||||
if (note.id != DRAFT_ID) {
|
||||
if (owner && note.id != DRAFT_ID) {
|
||||
MenuItem(R.string.editor_share, close, onShare)
|
||||
}
|
||||
MenuItem(
|
||||
if (note.archived) R.string.editor_unarchive else R.string.editor_archive,
|
||||
close,
|
||||
) { onAction(EditorAction.SetArchived(!note.archived)) }
|
||||
MenuItem(R.string.editor_trash, close) { onAction(EditorAction.Trash) }
|
||||
if (owner) {
|
||||
MenuItem(R.string.editor_trash, close) { onAction(EditorAction.Trash) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,10 @@ import com.fabledsword.inkwell.core.Note
|
||||
/**
|
||||
* How this account holds a note (#5175), read from the core's `permission`.
|
||||
*
|
||||
* Someone else's note at [EDIT] is theirs to have its TEXT changed here and nothing
|
||||
* else; at [VIEW] nothing changes here at all. The core refuses the rest anyway —
|
||||
* this only keeps the editor from offering what would be refused.
|
||||
* Someone else's note at [EDIT] may have its TEXT changed here; at [VIEW] it may
|
||||
* not. Either way its pin and archive are this account's own (#5176). The core
|
||||
* refuses the rest anyway — this only keeps the editor from offering what would be
|
||||
* refused.
|
||||
*/
|
||||
enum class NoteAccess { OWNER, EDIT, VIEW }
|
||||
|
||||
@@ -19,10 +20,10 @@ val Note.access: NoteAccess
|
||||
else -> NoteAccess.OWNER
|
||||
}
|
||||
|
||||
/** Nothing changes here: the note is in the trash, or shared with us to view. */
|
||||
/** Its content can't change here: it is in the trash, or shared with us to view. */
|
||||
val Note.readOnlyHere: Boolean
|
||||
get() = trashed || access == NoteAccess.VIEW
|
||||
|
||||
/** The owner's own controls apply: tags, reminder, files, previews, the menu. */
|
||||
/** The owner's own controls apply: tags, reminder, files, previews, share, trash. */
|
||||
val Note.ownerControlsHere: Boolean
|
||||
get() = !readOnlyHere && access == NoteAccess.OWNER
|
||||
|
||||
@@ -229,9 +229,11 @@ private fun NoteMenu(
|
||||
onAction: (EditorAction) -> Unit,
|
||||
onConfirmDelete: () -> Unit,
|
||||
) {
|
||||
// Every item here is the owner's to do, so someone else's note has no menu at all
|
||||
// rather than an empty one (#5175).
|
||||
DropdownMenu(expanded = expanded && note.access == NoteAccess.OWNER, onDismissRequest = onDismiss) {
|
||||
// Pin and archive are this account's own on someone else's note too (#5176);
|
||||
// trash is the owner's. A note shared with us never reaches our Trash, so the
|
||||
// trashed set is only ever the owner's.
|
||||
val owner = note.access == NoteAccess.OWNER
|
||||
DropdownMenu(expanded = expanded && (owner || !note.trashed), onDismissRequest = onDismiss) {
|
||||
if (note.trashed) {
|
||||
MenuItem(R.string.editor_restore, onDismiss) { onAction(EditorAction.Restore) }
|
||||
MenuItem(R.string.editor_delete_forever, onDismiss, onConfirmDelete)
|
||||
@@ -244,7 +246,9 @@ private fun NoteMenu(
|
||||
if (note.archived) R.string.editor_unarchive else R.string.editor_archive,
|
||||
onDismiss,
|
||||
) { onAction(EditorAction.SetArchived(!note.archived)) }
|
||||
MenuItem(R.string.editor_trash, onDismiss) { onAction(EditorAction.Trash) }
|
||||
if (owner) {
|
||||
MenuItem(R.string.editor_trash, onDismiss) { onAction(EditorAction.Trash) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -311,6 +311,20 @@ ALTER TABLE notes ADD COLUMN shared_by_name TEXT;
|
||||
ALTER TABLE sync_state ADD COLUMN shares_synced INTEGER NOT NULL DEFAULT 0;
|
||||
"#;
|
||||
|
||||
// v12 (#5176): a shared note's pin, archive and position are this account's own.
|
||||
//
|
||||
// `state_at` is when they last changed here, on a note someone else owns. It is kept
|
||||
// apart from `updated_at`, which stays the time of the note's TEXT: pinning a copy
|
||||
// whose text is behind the owner's must not make that text look like the newer
|
||||
// edit when it is pushed. Null on our own notes, where `updated_at` covers both.
|
||||
//
|
||||
// `sync_state.shares_synced` now holds a level rather than a flag (see
|
||||
// `state::SHARED_STATE`), and a device reaching this level pulls everything once
|
||||
// more: the shared notes it holds carry their owner's pins until it does.
|
||||
const SCHEMA_V12: &str = r#"
|
||||
ALTER TABLE notes ADD COLUMN state_at TEXT;
|
||||
"#;
|
||||
|
||||
pub fn migrate(conn: &Connection) -> rusqlite::Result<()> {
|
||||
conn.execute_batch("PRAGMA foreign_keys = ON;")?;
|
||||
let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;
|
||||
@@ -358,6 +372,10 @@ pub fn migrate(conn: &Connection) -> rusqlite::Result<()> {
|
||||
conn.execute_batch(SCHEMA_V11)?;
|
||||
conn.execute_batch("PRAGMA user_version = 11;")?;
|
||||
}
|
||||
if version < 12 {
|
||||
conn.execute_batch(SCHEMA_V12)?;
|
||||
conn.execute_batch("PRAGMA user_version = 12;")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -472,7 +490,7 @@ mod tests {
|
||||
let version: i64 = conn
|
||||
.query_row("PRAGMA user_version", [], |r| r.get(0))
|
||||
.expect("version");
|
||||
assert_eq!(version, 11);
|
||||
assert_eq!(version, 12);
|
||||
}
|
||||
|
||||
/// Every attachment that predates v10 came down the feed, so it is already on the
|
||||
|
||||
+100
-17
@@ -193,12 +193,14 @@ fn load_note(conn: &Connection, id: &str) -> rusqlite::Result<Note> {
|
||||
// ---- notes shared with this account (#5175) ---------------------------------
|
||||
//
|
||||
// A note someone else owns arrives with `permission` `edit` (its text may change
|
||||
// here) or `view` (nothing may). Everything else about it — pin, archive, trash,
|
||||
// reminders, labels, files — stays its owner's. The server enforces the same split;
|
||||
// here) or `view` (it may not). Its pin, archive and place on this board are this
|
||||
// account's own either way (#5176). Everything else about it — trash, reminders,
|
||||
// labels, files — stays its owner's. The server enforces the same split;
|
||||
// refusing here as well tells the person at once, instead of letting an edit be made,
|
||||
// queued, and then thrown away by the next sync.
|
||||
|
||||
pub const VIEW_ONLY: &str = "This note was shared with you to view, so it can't be changed here.";
|
||||
pub const VIEW_ONLY: &str =
|
||||
"This note was shared with you to view, so its text can't be changed here.";
|
||||
pub const OWNER_ONLY: &str = "Only the note's owner can change that.";
|
||||
|
||||
/// A refusal carrying words to show. Wrapped so it travels as a `rusqlite::Error`
|
||||
@@ -233,7 +235,8 @@ fn require_text(conn: &Connection, id: &str) -> rusqlite::Result<String> {
|
||||
Ok(permission)
|
||||
}
|
||||
|
||||
/// Anything but the text: only the owner.
|
||||
/// Anything but the text and this account's own pin, archive and place: only the
|
||||
/// owner.
|
||||
fn require_owner(conn: &Connection, id: &str) -> rusqlite::Result<()> {
|
||||
match permission_of(conn, id)?.as_str() {
|
||||
"owner" => Ok(()),
|
||||
@@ -242,6 +245,20 @@ fn require_owner(conn: &Connection, id: &str) -> rusqlite::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// This account's own pin, archive or place changed on a note someone else owns.
|
||||
/// Stamped apart from `updated_at`, which is the time of the note's text; see
|
||||
/// SCHEMA_V12 for why the two must not share a clock.
|
||||
fn touch_own_state(conn: &Connection, id: &str) -> rusqlite::Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE notes SET state_at = ?1, dirty = 1 WHERE id = ?2",
|
||||
params![now(), id],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The fields of a note anyone it is shared with may set: their own.
|
||||
const OWN_FIELDS: [&str; 2] = ["pinned", "archived"];
|
||||
|
||||
fn touch(conn: &Connection, id: &str) -> rusqlite::Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE notes SET updated_at = ?1, dirty = 1 WHERE id = ?2",
|
||||
@@ -596,9 +613,18 @@ pub fn update_note(conn: &Connection, id: &str, changes: &Value) -> rusqlite::Re
|
||||
let obj = changes
|
||||
.as_object()
|
||||
.ok_or_else(|| rusqlite::Error::InvalidParameterName("changes must be an object".into()))?;
|
||||
let permission = require_text(conn, id)?;
|
||||
let text = obj.contains_key("body");
|
||||
let permission = if text {
|
||||
require_text(conn, id)?
|
||||
} else {
|
||||
permission_of(conn, id)?
|
||||
};
|
||||
let owned = permission == "owner";
|
||||
if !owned && obj.keys().any(|k| k != "body") {
|
||||
if !owned
|
||||
&& obj
|
||||
.keys()
|
||||
.any(|k| k != "body" && !OWN_FIELDS.contains(&k.as_str()))
|
||||
{
|
||||
return Err(refuse(OWNER_ONLY));
|
||||
}
|
||||
|
||||
@@ -656,7 +682,12 @@ pub fn update_note(conn: &Connection, id: &str, changes: &Value) -> rusqlite::Re
|
||||
}
|
||||
}
|
||||
|
||||
touch(conn, id)?;
|
||||
if owned || text {
|
||||
touch(conn, id)?;
|
||||
}
|
||||
if !owned && OWN_FIELDS.iter().any(|k| obj.contains_key(*k)) {
|
||||
touch_own_state(conn, id)?;
|
||||
}
|
||||
load_note(conn, id)
|
||||
}
|
||||
|
||||
@@ -895,11 +926,16 @@ pub fn delete_preview(conn: &Connection, id: &str, preview_id: &str) -> rusqlite
|
||||
|
||||
pub fn reorder(conn: &Connection, ordered_ids: &[String]) -> rusqlite::Result<()> {
|
||||
let total = ordered_ids.len() as i64;
|
||||
let at = now();
|
||||
for (i, id) in ordered_ids.iter().enumerate() {
|
||||
// Order is the owner's; a shared note keeps its place on their board.
|
||||
// A note someone shared with us moves on this account's board only (#5176),
|
||||
// stamped as its own state rather than as an edit.
|
||||
conn.execute(
|
||||
"UPDATE notes SET position = ?1, dirty = 1 WHERE id = ?2 AND permission = 'owner'",
|
||||
params![total - i as i64, id],
|
||||
"UPDATE notes
|
||||
SET position = ?1, dirty = 1,
|
||||
state_at = CASE WHEN permission = 'owner' THEN state_at ELSE ?3 END
|
||||
WHERE id = ?2",
|
||||
params![total - i as i64, id, at],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -1340,17 +1376,21 @@ mod tests {
|
||||
assert!(dirty(&conn, "n"));
|
||||
add_item(&conn, "n", "eggs").expect("an item is text");
|
||||
|
||||
let pinned = update_note(&conn, "n", &json!({ "pinned": true }))
|
||||
.err()
|
||||
.expect("refused");
|
||||
assert_eq!(pinned.to_string(), OWNER_ONLY);
|
||||
assert!(update_note(&conn, "n", &json!({ "body": "x", "archived": true })).is_err());
|
||||
let reminded = update_note(
|
||||
&conn,
|
||||
"n",
|
||||
&json!({ "remind_at": "2026-02-01T00:00:00.000Z" }),
|
||||
)
|
||||
.err()
|
||||
.expect("refused");
|
||||
assert_eq!(reminded.to_string(), OWNER_ONLY);
|
||||
assert!(update_note(&conn, "n", &json!({ "body": "x", "recurrence": "daily" })).is_err());
|
||||
assert!(trash(&conn, "n").is_err());
|
||||
assert!(complete_reminder(&conn, "n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_notes_stay_out_of_trash_reminders_and_reordering() {
|
||||
fn shared_notes_stay_out_of_trash_and_reminders() {
|
||||
let conn = db();
|
||||
shared(&conn, "theirs", "edit");
|
||||
conn.execute(
|
||||
@@ -1367,9 +1407,52 @@ mod tests {
|
||||
.expect("restored");
|
||||
assert!(reminders(&conn).expect("reminders").is_empty());
|
||||
assert!(due_reminders(&conn, i64::MAX).expect("due").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recipient_pins_archives_and_orders_their_own_copy() {
|
||||
let conn = db();
|
||||
shared(&conn, "theirs", "view");
|
||||
let state_at = |conn: &Connection| -> Option<String> {
|
||||
conn.query_row("SELECT state_at FROM notes WHERE id = 'theirs'", [], |r| {
|
||||
r.get(0)
|
||||
})
|
||||
.expect("state_at")
|
||||
};
|
||||
|
||||
let pinned = update_note(
|
||||
&conn,
|
||||
"theirs",
|
||||
&json!({ "pinned": true, "archived": true }),
|
||||
)
|
||||
.expect("a view share may still be pinned");
|
||||
assert!(pinned.pinned && pinned.archived);
|
||||
assert!(dirty(&conn, "theirs"));
|
||||
// Stamped as this account's own state, never as an edit to the owner's text.
|
||||
assert_eq!(
|
||||
pinned.updated_at.as_deref(),
|
||||
Some("2026-01-01T00:00:00.000Z")
|
||||
);
|
||||
let first = state_at(&conn).expect("stamped");
|
||||
|
||||
conn.execute("UPDATE notes SET dirty = 0, state_at = NULL", [])
|
||||
.expect("synced");
|
||||
reorder(&conn, &["theirs".to_string()]).expect("reorder");
|
||||
assert!(!dirty(&conn, "theirs"), "order is the owner's");
|
||||
assert!(dirty(&conn, "theirs"));
|
||||
assert!(state_at(&conn).is_some_and(|at| at >= first));
|
||||
assert_eq!(get_note(&conn, "theirs").expect("get").position, 1);
|
||||
|
||||
// An own note's order is still its own edit, with no separate stamp.
|
||||
let mine = note(&conn, "mine");
|
||||
reorder(&conn, &[mine.id.clone()]).expect("reorder mine");
|
||||
let own: Option<String> = conn
|
||||
.query_row(
|
||||
"SELECT state_at FROM notes WHERE id = ?1",
|
||||
[&mine.id],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.expect("own state_at");
|
||||
assert!(own.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+12
-3
@@ -25,7 +25,10 @@ use std::sync::OnceLock;
|
||||
/// on [`MIN_SERVER_PROTOCOL_VERSION`].
|
||||
/// v5 (#5168): files attached here upload, and removed attachments and previews are
|
||||
/// pushed. Additive: both go only to a server advertising `attachment_sync`.
|
||||
pub const CLIENT_PROTOCOL_VERSION: u32 = 5;
|
||||
/// v6 (#5175): notes shared with this account, asked for with `shares`.
|
||||
/// v7 (#5176): this account's own pin, archive and position on a shared note, sent
|
||||
/// only to a server advertising `shared_state`.
|
||||
pub const CLIENT_PROTOCOL_VERSION: u32 = 7;
|
||||
|
||||
/// The oldest server protocol this client can drive — the symmetric half of the
|
||||
/// server's `min_client_protocol_version`.
|
||||
@@ -49,8 +52,14 @@ pub const REQUIRED_FEATURES: &[&str] = &["notes", "labels"];
|
||||
/// Capabilities whose absence costs a feature but not the link. Listing these
|
||||
/// explicitly (rather than diffing against whatever the server happens to send) is
|
||||
/// what lets the UI name exactly what the user will be missing.
|
||||
pub const OPTIONAL_FEATURES: &[&str] =
|
||||
&["attachments", "tombstones", "revisions", "attachment_sync"];
|
||||
pub const OPTIONAL_FEATURES: &[&str] = &[
|
||||
"attachments",
|
||||
"tombstones",
|
||||
"revisions",
|
||||
"attachment_sync",
|
||||
"shares",
|
||||
"shared_state",
|
||||
];
|
||||
|
||||
/// The handshake fields of `GET /api/config`.
|
||||
///
|
||||
|
||||
+16
-3
@@ -50,13 +50,26 @@ pub async fn run_cycle(
|
||||
// Notes shared with this account come only from a server offering `shares`, and
|
||||
// an unanswered probe reads as "not offered", like `attachment_sync` above.
|
||||
let shares = server.as_ref().is_some_and(|s| s.has_feature("shares"));
|
||||
// A recipient's own pin, archive and order on a shared note go only to a server
|
||||
// that keeps them per person; an older one would apply them to nobody.
|
||||
let accepts = push::Accepts {
|
||||
attachment_sync,
|
||||
shared_state: server
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.has_feature("shared_state")),
|
||||
};
|
||||
|
||||
let push = push::run(db, blobs, base_url, token, attachment_sync).await?;
|
||||
let push = push::run(db, blobs, base_url, token, accepts).await?;
|
||||
if shares {
|
||||
// After the push, so nothing unsent is waiting when the full pull lands.
|
||||
let level = if accepts.shared_state {
|
||||
state::SHARED_STATE
|
||||
} else {
|
||||
state::SHARES
|
||||
};
|
||||
let conn = db.0.lock().map_err(|e| e.to_string())?;
|
||||
if state::begin_shares(&conn).map_err(|e| e.to_string())? {
|
||||
log::info!("the server shares notes now; pulling everything once to find them");
|
||||
if state::begin_shares(&conn, level).map_err(|e| e.to_string())? {
|
||||
log::info!("the server shares more of notes now; pulling everything once");
|
||||
}
|
||||
}
|
||||
let pull = pull::run(db, blobs, base_url, token, shares).await?;
|
||||
|
||||
+112
-49
@@ -95,6 +95,12 @@ pub struct Change {
|
||||
pub created_at: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// When this account last pinned, archived or moved a note someone else owns
|
||||
/// (#5176): `pinned`, `archived` and `position` on such a note are its own, and
|
||||
/// the server weighs them against this rather than `edited_at`, which stays the
|
||||
/// time of the text.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub state_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Change {
|
||||
@@ -115,6 +121,7 @@ impl Change {
|
||||
label_ids: None,
|
||||
created_at: None,
|
||||
name: None,
|
||||
state_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,24 +150,38 @@ pub struct PushResult {
|
||||
|
||||
// --- collecting --------------------------------------------------------------
|
||||
|
||||
/// What the server takes beyond the base protocol, read from the features it
|
||||
/// advertises. What it doesn't take stays queued here, untouched, until a server
|
||||
/// that does: an older one would refuse it, or worse, accept it and keep nothing.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct Accepts {
|
||||
/// Attachment and preview removals, and file uploads (`attachment_sync`). An
|
||||
/// older server would answer "unknown entity" and the removal would read as a
|
||||
/// failure.
|
||||
pub attachment_sync: bool,
|
||||
/// This account's own pin, archive and position on a note someone else owns
|
||||
/// (`shared_state`, #5176).
|
||||
pub shared_state: bool,
|
||||
}
|
||||
|
||||
impl Accepts {
|
||||
/// Everything this client can send.
|
||||
pub const ALL: Accepts = Accepts {
|
||||
attachment_sync: true,
|
||||
shared_state: true,
|
||||
};
|
||||
}
|
||||
|
||||
/// Everything waiting to go up, oldest edit first so a truncated batch still makes
|
||||
/// forward progress in a sensible order.
|
||||
///
|
||||
/// `attachment_sync` is whether the server takes attachment and preview removals.
|
||||
/// Without it they stay queued here, untouched, until a server that does — an older
|
||||
/// one would answer "unknown entity" and the removal would read as a failure.
|
||||
pub fn collect(
|
||||
conn: &Connection,
|
||||
limit: usize,
|
||||
attachment_sync: bool,
|
||||
) -> rusqlite::Result<Vec<Change>> {
|
||||
pub fn collect(conn: &Connection, limit: usize, accepts: Accepts) -> rusqlite::Result<Vec<Change>> {
|
||||
let mut out = Vec::new();
|
||||
collect_deletes(conn, &mut out, limit, attachment_sync)?;
|
||||
collect_deletes(conn, &mut out, limit, accepts.attachment_sync)?;
|
||||
if out.len() < limit {
|
||||
collect_labels(conn, &mut out, limit)?;
|
||||
}
|
||||
if out.len() < limit {
|
||||
collect_notes(conn, &mut out, limit)?;
|
||||
collect_notes(conn, &mut out, limit, accepts.shared_state)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -225,6 +246,7 @@ fn collect_labels(conn: &Connection, out: &mut Vec<Change>, limit: usize) -> rus
|
||||
position: None,
|
||||
label_ids: None,
|
||||
created_at: None,
|
||||
state_at: None,
|
||||
})
|
||||
})?;
|
||||
for row in rows {
|
||||
@@ -233,21 +255,31 @@ fn collect_labels(conn: &Connection, out: &mut Vec<Change>, limit: usize) -> rus
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn collect_notes(conn: &Connection, out: &mut Vec<Change>, limit: usize) -> rusqlite::Result<()> {
|
||||
fn collect_notes(
|
||||
conn: &Connection,
|
||||
out: &mut Vec<Change>,
|
||||
limit: usize,
|
||||
shared_state: bool,
|
||||
) -> rusqlite::Result<()> {
|
||||
let remaining = limit.saturating_sub(out.len());
|
||||
let ids: Vec<String> = {
|
||||
// A note shared with us to view can't be changed here, so one that is dirty
|
||||
// anyway (its share was narrowed while an edit waited) has nothing the server
|
||||
// would take. The next pull puts the server's copy back over it.
|
||||
// A note shared with us to view has only this account's own pin, archive and
|
||||
// place to send, and only to a server that keeps them. Without one, a dirty
|
||||
// view note has nothing the server would take, and the next pull puts the
|
||||
// server's copy back over it.
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id FROM notes WHERE dirty = 1 AND permission <> 'view'
|
||||
"SELECT id FROM notes
|
||||
WHERE dirty = 1
|
||||
AND (permission <> 'view' OR (?2 AND state_at IS NOT NULL))
|
||||
ORDER BY updated_at LIMIT ?1",
|
||||
)?;
|
||||
let rows = stmt.query_map(params![remaining as i64], |r| r.get::<_, String>(0))?;
|
||||
let rows = stmt.query_map(params![remaining as i64, shared_state], |r| {
|
||||
r.get::<_, String>(0)
|
||||
})?;
|
||||
rows.collect::<rusqlite::Result<Vec<String>>>()?
|
||||
};
|
||||
for id in ids {
|
||||
out.push(note_change(conn, &id)?);
|
||||
out.push(note_change(conn, &id, shared_state)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -264,14 +296,16 @@ struct NoteRow {
|
||||
recurrence: Option<String>,
|
||||
created_at: String,
|
||||
updated_at: String,
|
||||
/// `owner`, or `edit` for a note someone shared with us (#5175).
|
||||
/// `owner`, or `edit` or `view` for a note someone shared with us (#5175).
|
||||
permission: String,
|
||||
/// When this account last pinned, archived or moved it, if it isn't ours (#5176).
|
||||
state_at: Option<String>,
|
||||
}
|
||||
|
||||
fn note_row(conn: &Connection, id: &str) -> rusqlite::Result<NoteRow> {
|
||||
conn.query_row(
|
||||
"SELECT body, position, pinned, archived, trashed,
|
||||
remind_at, recurrence, created_at, updated_at, permission
|
||||
remind_at, recurrence, created_at, updated_at, permission, state_at
|
||||
FROM notes WHERE id = ?1",
|
||||
params![id],
|
||||
|r| {
|
||||
@@ -286,34 +320,39 @@ fn note_row(conn: &Connection, id: &str) -> rusqlite::Result<NoteRow> {
|
||||
created_at: r.get(7)?,
|
||||
updated_at: r.get(8)?,
|
||||
permission: r.get(9)?,
|
||||
state_at: r.get(10)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn note_change(conn: &Connection, id: &str) -> rusqlite::Result<Change> {
|
||||
fn note_change(conn: &Connection, id: &str, shared_state: bool) -> rusqlite::Result<Change> {
|
||||
let row = note_row(conn, id)?;
|
||||
|
||||
// Someone else's note: only its text is ours to change, so only its text goes.
|
||||
// Pin, archive, trash, reminders, order and labels are the owner's, and this
|
||||
// account's labels were never on it.
|
||||
// Someone else's note: its text if it was shared to edit, and this account's own
|
||||
// pin, archive and place once they have been changed here, to a server that keeps
|
||||
// them. Trash, reminders and labels are the owner's, and this account's labels
|
||||
// were never on it.
|
||||
if row.permission != "owner" {
|
||||
let state_at = row.state_at.filter(|_| shared_state);
|
||||
let own = state_at.is_some();
|
||||
return Ok(Change {
|
||||
entity: "note",
|
||||
id: id.to_string(),
|
||||
op: "upsert",
|
||||
edited_at: row.updated_at,
|
||||
body: Some(row.body),
|
||||
body: (row.permission == "edit").then_some(row.body),
|
||||
color: None,
|
||||
pinned: None,
|
||||
archived: None,
|
||||
pinned: own.then_some(row.pinned),
|
||||
archived: own.then_some(row.archived),
|
||||
trashed: None,
|
||||
remind_at: None,
|
||||
recurrence: None,
|
||||
position: None,
|
||||
position: own.then_some(row.position),
|
||||
label_ids: None,
|
||||
created_at: None,
|
||||
name: None,
|
||||
state_at,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -346,6 +385,7 @@ fn note_change(conn: &Connection, id: &str) -> rusqlite::Result<Change> {
|
||||
label_ids: Some(label_ids),
|
||||
created_at: Some(row.created_at),
|
||||
name: None,
|
||||
state_at: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -616,21 +656,21 @@ async fn upload_pending(
|
||||
/// Send everything pending, in batches, applying each batch's results before the
|
||||
/// next is collected — then the files, once their notes are there to hold them.
|
||||
///
|
||||
/// `attachment_sync`: whether the server advertises it (see [`collect`]). Without
|
||||
/// it, uploads wait too.
|
||||
/// `accepts`: what the server advertises (see [`Accepts`]). Without
|
||||
/// `attachment_sync`, uploads wait too.
|
||||
pub async fn run(
|
||||
db: &Db,
|
||||
blobs: &BlobStore,
|
||||
base_url: &str,
|
||||
token: &str,
|
||||
attachment_sync: bool,
|
||||
accepts: Accepts,
|
||||
) -> Result<PushSummary, String> {
|
||||
let mut total = PushSummary::default();
|
||||
|
||||
loop {
|
||||
let batch = {
|
||||
let conn = db.0.lock().map_err(|e| e.to_string())?;
|
||||
collect(&conn, BATCH, attachment_sync).map_err(|e| e.to_string())?
|
||||
collect(&conn, BATCH, accepts).map_err(|e| e.to_string())?
|
||||
};
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
@@ -658,7 +698,7 @@ pub async fn run(
|
||||
}
|
||||
}
|
||||
|
||||
if attachment_sync {
|
||||
if accepts.attachment_sync {
|
||||
total.absorb(upload_pending(db, blobs, base_url, token).await?);
|
||||
}
|
||||
|
||||
@@ -736,7 +776,7 @@ mod tests {
|
||||
let conn = db();
|
||||
seed_note(&conn, "clean", 0);
|
||||
seed_note(&conn, "dirty", 1);
|
||||
let batch = collect(&conn, 100, true).expect("collect");
|
||||
let batch = collect(&conn, 100, Accepts::ALL).expect("collect");
|
||||
assert_eq!(batch.len(), 1);
|
||||
assert_eq!(batch[0].id, "dirty");
|
||||
assert_eq!(batch[0].op, "upsert");
|
||||
@@ -761,7 +801,7 @@ mod tests {
|
||||
)
|
||||
.expect("seed membership");
|
||||
}
|
||||
let batch = collect(&conn, 100, true).expect("collect");
|
||||
let batch = collect(&conn, 100, Accepts::ALL).expect("collect");
|
||||
let note = batch.iter().find(|c| c.entity == "note").expect("note");
|
||||
assert_eq!(note.label_ids.as_deref(), Some(&["manual".to_string()][..]));
|
||||
}
|
||||
@@ -771,7 +811,7 @@ mod tests {
|
||||
let conn = db();
|
||||
seed_note(&conn, "n1", 0);
|
||||
store::delete_forever(&conn, "n1").expect("delete");
|
||||
let batch = collect(&conn, 100, true).expect("collect");
|
||||
let batch = collect(&conn, 100, Accepts::ALL).expect("collect");
|
||||
assert_eq!(batch.len(), 1);
|
||||
assert_eq!(batch[0].op, "delete");
|
||||
assert_eq!(batch[0].entity, "note");
|
||||
@@ -782,7 +822,7 @@ mod tests {
|
||||
fn applied_clears_dirty_and_records_the_revision() {
|
||||
let conn = db();
|
||||
seed_note(&conn, "n1", 1);
|
||||
let batch = collect(&conn, 100, true).expect("collect");
|
||||
let batch = collect(&conn, 100, Accepts::ALL).expect("collect");
|
||||
apply_results(&conn, &batch, &[ok("applied", Some(42))]).expect("apply");
|
||||
assert_eq!(dirty_count(&conn), 0);
|
||||
let rev: i64 = conn
|
||||
@@ -799,7 +839,7 @@ mod tests {
|
||||
// every time; the following pull adopts the server's version instead.
|
||||
let conn = db();
|
||||
seed_note(&conn, "n1", 1);
|
||||
let batch = collect(&conn, 100, true).expect("collect");
|
||||
let batch = collect(&conn, 100, Accepts::ALL).expect("collect");
|
||||
let summary = apply_results(&conn, &batch, &[ok("kept", Some(99))]).expect("apply");
|
||||
assert_eq!(summary.kept, 1);
|
||||
assert_eq!(dirty_count(&conn), 0);
|
||||
@@ -813,7 +853,7 @@ mod tests {
|
||||
let conn = db();
|
||||
seed_note(&conn, "n1", 1);
|
||||
state::set_cursor(&conn, 100).expect("cursor");
|
||||
let batch = collect(&conn, 100, true).expect("collect");
|
||||
let batch = collect(&conn, 100, Accepts::ALL).expect("collect");
|
||||
apply_results(&conn, &batch, &[ok("kept", Some(40))]).expect("apply");
|
||||
assert_eq!(state::read(&conn).expect("state").last_cursor, 39);
|
||||
}
|
||||
@@ -823,7 +863,7 @@ mod tests {
|
||||
let conn = db();
|
||||
seed_note(&conn, "n1", 1);
|
||||
state::set_cursor(&conn, 10).expect("cursor");
|
||||
let batch = collect(&conn, 100, true).expect("collect");
|
||||
let batch = collect(&conn, 100, Accepts::ALL).expect("collect");
|
||||
apply_results(&conn, &batch, &[ok("kept", Some(40))]).expect("apply");
|
||||
assert_eq!(
|
||||
state::read(&conn).expect("state").last_cursor,
|
||||
@@ -836,7 +876,7 @@ mod tests {
|
||||
fn rejected_stays_dirty_and_is_reported() {
|
||||
let conn = db();
|
||||
seed_note(&conn, "n1", 1);
|
||||
let batch = collect(&conn, 100, true).expect("collect");
|
||||
let batch = collect(&conn, 100, Accepts::ALL).expect("collect");
|
||||
let mut bad = ok("rejected", None);
|
||||
bad.error = Some("name in use".into());
|
||||
let summary = apply_results(&conn, &batch, &[bad]).expect("apply");
|
||||
@@ -850,7 +890,7 @@ mod tests {
|
||||
let conn = db();
|
||||
seed_note(&conn, "n1", 0);
|
||||
store::delete_forever(&conn, "n1").expect("delete");
|
||||
let batch = collect(&conn, 100, true).expect("collect");
|
||||
let batch = collect(&conn, 100, Accepts::ALL).expect("collect");
|
||||
apply_results(&conn, &batch, &[ok("applied", Some(7))]).expect("apply");
|
||||
assert!(!has_pending(&conn).expect("pending"));
|
||||
}
|
||||
@@ -861,7 +901,7 @@ mod tests {
|
||||
let conn = db();
|
||||
seed_note(&conn, "n1", 1);
|
||||
store::delete_forever(&conn, "n1").expect("delete");
|
||||
let batch = collect(&conn, 100, true).expect("collect");
|
||||
let batch = collect(&conn, 100, Accepts::ALL).expect("collect");
|
||||
apply_results(&conn, &batch, &[ok("noop", None)]).expect("apply");
|
||||
assert!(!has_pending(&conn).expect("pending"));
|
||||
}
|
||||
@@ -895,7 +935,7 @@ mod tests {
|
||||
seed_note(&conn, "n1", 1);
|
||||
conn.execute("UPDATE notes SET permission = 'edit' WHERE id = 'n1'", [])
|
||||
.unwrap();
|
||||
let changes = collect(&conn, 10, true).unwrap();
|
||||
let changes = collect(&conn, 10, Accepts::ALL).unwrap();
|
||||
assert_eq!(changes.len(), 1);
|
||||
let wire = serde_json::to_value(&changes[0]).unwrap();
|
||||
let mut keys: Vec<&str> = wire
|
||||
@@ -909,12 +949,35 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_note_shared_to_view_is_never_pushed() {
|
||||
fn a_note_shared_to_view_sends_only_this_accounts_own_state() {
|
||||
let conn = db();
|
||||
seed_note(&conn, "n1", 1);
|
||||
conn.execute("UPDATE notes SET permission = 'view' WHERE id = 'n1'", [])
|
||||
.unwrap();
|
||||
assert!(collect(&conn, 10, true).unwrap().is_empty());
|
||||
// Dirty with nothing of ours changed on it: nothing to send.
|
||||
assert!(collect(&conn, 10, Accepts::ALL).unwrap().is_empty());
|
||||
|
||||
conn.execute(
|
||||
"UPDATE notes SET pinned = 1, position = 4,
|
||||
state_at = '2026-07-27T00:00:00.000Z' WHERE id = 'n1'",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
let changes = collect(&conn, 10, Accepts::ALL).unwrap();
|
||||
let wire = serde_json::to_value(&changes[0]).unwrap();
|
||||
assert!(wire.get("body").is_none(), "a view share sends no text");
|
||||
assert_eq!(wire["pinned"], true);
|
||||
assert_eq!(wire["archived"], false);
|
||||
assert_eq!(wire["position"], 4);
|
||||
assert_eq!(wire["state_at"], "2026-07-27T00:00:00.000Z");
|
||||
assert_eq!(wire["edited_at"], "2026-07-26T00:00:00.000Z");
|
||||
|
||||
// A server that doesn't keep them gets nothing, and it waits here.
|
||||
let older = Accepts {
|
||||
shared_state: false,
|
||||
..Accepts::ALL
|
||||
};
|
||||
assert!(collect(&conn, 10, older).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1003,14 +1066,14 @@ mod tests {
|
||||
store::record_pending_delete(&conn, "note", "n9").expect("tombstone");
|
||||
|
||||
// An older server would answer "unknown entity" to each of them.
|
||||
let older: Vec<_> = collect(&conn, 100, false)
|
||||
let older: Vec<_> = collect(&conn, 100, Accepts::default())
|
||||
.expect("collect")
|
||||
.iter()
|
||||
.map(|c| c.entity)
|
||||
.collect();
|
||||
assert_eq!(older, vec!["note"]);
|
||||
|
||||
let mut newer: Vec<_> = collect(&conn, 100, true)
|
||||
let mut newer: Vec<_> = collect(&conn, 100, Accepts::ALL)
|
||||
.expect("collect")
|
||||
.iter()
|
||||
.map(|c| (c.entity, c.op))
|
||||
@@ -1071,7 +1134,7 @@ mod tests {
|
||||
store::delete_attachment(&conn, "n1", "a1").expect("remove");
|
||||
|
||||
// Push: the removal and the touched note go up, and the server applies both.
|
||||
let batch = collect(&conn, 100, true).expect("collect");
|
||||
let batch = collect(&conn, 100, Accepts::ALL).expect("collect");
|
||||
let results: Vec<PushResult> = batch
|
||||
.iter()
|
||||
.map(|c| ok("applied", (c.entity == "note").then_some(5)))
|
||||
|
||||
+32
-12
@@ -115,17 +115,27 @@ fn forget_shared_notes(conn: &Connection) -> rusqlite::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start the change feed over the first time this device pulls with shares (#5175).
|
||||
/// How much of sharing this device's copy of the feed reflects, kept in
|
||||
/// `sync_state.shares_synced`. Each level changed what the feed says about notes a
|
||||
/// device may already hold, below the cursor it already has.
|
||||
///
|
||||
/// Notes shared before this build sit below the cursor the device already holds, so
|
||||
/// without a restart they would only arrive once something next changed them.
|
||||
/// Returns whether it restarted. Once per link: `set_link` to another server and
|
||||
/// `clear_link` both reset the flag.
|
||||
pub fn begin_shares(conn: &Connection) -> rusqlite::Result<bool> {
|
||||
/// Shared notes arrive at all (#5175).
|
||||
pub const SHARES: i64 = 1;
|
||||
/// A shared note's pin, archive and position are this account's own (#5176). Before,
|
||||
/// the feed sent the owner's, and a device holding those would keep showing them
|
||||
/// until something next changed the note.
|
||||
pub const SHARED_STATE: i64 = 2;
|
||||
|
||||
/// Start the change feed over the first time this device pulls at a sharing `level`
|
||||
/// the server offers, so what it already holds is re-read in that level's terms.
|
||||
///
|
||||
/// Returns whether it restarted. Once per level per link: `set_link` to another
|
||||
/// server and `clear_link` both go back to none.
|
||||
pub fn begin_shares(conn: &Connection, level: i64) -> rusqlite::Result<bool> {
|
||||
let restarted = conn.execute(
|
||||
"UPDATE sync_state SET last_cursor = NULL, shares_synced = 1
|
||||
WHERE id = 1 AND shares_synced = 0",
|
||||
[],
|
||||
"UPDATE sync_state SET last_cursor = NULL, shares_synced = ?1
|
||||
WHERE id = 1 AND shares_synced < ?1",
|
||||
params![level],
|
||||
)?;
|
||||
Ok(restarted > 0)
|
||||
}
|
||||
@@ -342,14 +352,24 @@ mod tests {
|
||||
let conn = db();
|
||||
set_link(&conn, "https://a.example.com", "tok-1").expect("link");
|
||||
set_cursor(&conn, 500).expect("cursor");
|
||||
assert!(begin_shares(&conn).expect("begin"));
|
||||
assert!(begin_shares(&conn, SHARES).expect("begin"));
|
||||
assert_eq!(read(&conn).expect("read").last_cursor, 0);
|
||||
set_cursor(&conn, 600).expect("cursor");
|
||||
assert!(!begin_shares(&conn).expect("again"), "only the first time");
|
||||
assert!(
|
||||
!begin_shares(&conn, SHARES).expect("again"),
|
||||
"only the first time"
|
||||
);
|
||||
assert_eq!(read(&conn).expect("read").last_cursor, 600);
|
||||
// A server offering more of sharing starts it over once more, and only once.
|
||||
assert!(begin_shares(&conn, SHARED_STATE).expect("a newer server"));
|
||||
assert_eq!(read(&conn).expect("read").last_cursor, 0);
|
||||
set_cursor(&conn, 700).expect("cursor");
|
||||
assert!(!begin_shares(&conn, SHARED_STATE).expect("again"));
|
||||
assert!(!begin_shares(&conn, SHARES).expect("an older level"));
|
||||
assert_eq!(read(&conn).expect("read").last_cursor, 700);
|
||||
// Another server is a fresh start, shares included.
|
||||
set_link(&conn, "https://b.example.com", "tok-2").expect("relink");
|
||||
assert!(begin_shares(&conn).expect("new server"));
|
||||
assert!(begin_shares(&conn, SHARES).expect("new server"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+26
-6
@@ -67,6 +67,10 @@ syncs everything else.
|
||||
- v6 (#5175): shared notes — see "Shared notes" below. Opt-in per request
|
||||
(`changes?shares=1`), so it is the `shares` feature and the floor stays: a v5
|
||||
client never asks and gets exactly its own notes.
|
||||
- v7 (#5176): a recipient's own pin, archive and position on a shared note —
|
||||
see "Shared notes". Additive, so it is the `shared_state` feature and the
|
||||
floor stays: a v6 client pushes only text, and reads its own state as if the
|
||||
note were simply unpinned.
|
||||
- **Additive change** (a new field, a new capability) → add a `sync_features`
|
||||
name. Do **not** raise a minimum. Old clients keep working.
|
||||
- **Breaking change only** → raise `MIN_CLIENT_PROTOCOL_VERSION` (or the client's
|
||||
@@ -230,6 +234,13 @@ sequence and page on the same cursor as notes and labels (three streams now; the
|
||||
smallest full boundary wins). Sharing with the person again deletes their
|
||||
revocation, so a device that never saw it is never told to drop a note it has.
|
||||
|
||||
**Pin, archive and position are personal** (`shared_state`, v7). On a note shared
|
||||
with the caller, the feed's `pinned`, `archived` and `position` are the caller's
|
||||
own: unpinned and unarchived until they change them, and the owner's `position`
|
||||
until they move it. They live in a per-person row with a revision of its own, so
|
||||
the note's `sync_revision` in the feed is the later of the note's and that row's —
|
||||
a recipient pinning a note reaches their devices and no one else's.
|
||||
|
||||
## Push — `POST /api/sync/push`
|
||||
|
||||
Body: `{ "changes": [ ... ] }` (max 1000 per batch). Each change:
|
||||
@@ -267,12 +278,21 @@ Body: `{ "changes": [ ... ] }` (max 1000 per batch). Each change:
|
||||
the same as one that never existed. Removals are explicit rather than "the
|
||||
note's current attachment set" on purpose: push runs before pull, so a set
|
||||
would delete an attachment another device added that this one has not seen.
|
||||
- **A note someone else owns** (`shares`): a recipient at `edit` may push an upsert
|
||||
and only its `body` is applied, under the same last-write-wins — every other
|
||||
field is ignored, since pinning, archiving, reminders, labels and deleting stay
|
||||
the owner's. A `view` recipient's change, or any delete, is `rejected` ("only its
|
||||
owner can change that"); a note the caller can't see at all answers the generic
|
||||
"cannot apply".
|
||||
- **A note someone else owns** (`shares`): an upsert may carry two things, each
|
||||
under its own last-write-wins.
|
||||
- Its `body`, from a recipient at `edit`, compared on `edited_at` against the
|
||||
note. From a `view` recipient a body is `rejected` ("only its owner can change
|
||||
that").
|
||||
- Their own `pinned`, `archived` and `position` (`shared_state`), from anyone it
|
||||
is shared with, compared on **`state_at`** against what they last set. A
|
||||
client stamps `state_at` apart from the text's `edited_at` so that pinning a
|
||||
copy whose text is out of date never makes that text look newer than the
|
||||
owner's edit. Without `state_at` the three are ignored.
|
||||
|
||||
Trashing, reminders, labels and deleting stay the owner's: those fields are
|
||||
ignored and a delete is `rejected`. The answer is `applied` if either part
|
||||
applied, else `kept`, with the revision as that caller's feed would show it. A
|
||||
note the caller can't see at all answers the generic "cannot apply".
|
||||
|
||||
### Conflict resolution — last-write-wins + history
|
||||
|
||||
|
||||
@@ -124,7 +124,8 @@ const root = ref<HTMLElement | null>(null);
|
||||
// touch — on a phone this did nothing at all. One code path now covers mouse, touch
|
||||
// and stylus. See composables/useCardDrag.ts for why the state is shared. ---
|
||||
// Board order is the owner's; a shared note's place is the recipient's from #5176.
|
||||
const canDrag = () => !!props.reorderable && !props.note.trashed && own.value;
|
||||
// A shared note moves on the recipient's board only (#5176), so anyone may drag it.
|
||||
const canDrag = () => !!props.reorderable && !props.note.trashed;
|
||||
const dragging = computed(() => draggingId.value === props.note.id);
|
||||
const dragOver = computed(() => overId.value === props.note.id);
|
||||
|
||||
@@ -458,9 +459,10 @@ const tagColors = computed<Record<string, string>>(() => {
|
||||
<Icon name="grip" />
|
||||
</button>
|
||||
|
||||
<!-- Every action here is the owner's, so a shared note has no action set. -->
|
||||
<!-- Pin and archive are everyone's own (#5176); share and trash are the owner's.
|
||||
A note shared with you is never in your Trash, so the trashed set is too. -->
|
||||
<div
|
||||
v-if="own"
|
||||
v-if="own || !note.trashed"
|
||||
class="note-actions-set hover-reveal pointer-events-none flex items-center gap-0.5 rounded-full bg-white/85 p-0.5 opacity-0 shadow-sm ring-1 ring-black/5 backdrop-blur-sm transition focus-within:pointer-events-auto focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100 dark:bg-neutral-900/85 dark:ring-white/10"
|
||||
>
|
||||
<template v-if="note.trashed">
|
||||
@@ -477,7 +479,7 @@ const tagColors = computed<Record<string, string>>(() => {
|
||||
<Icon name="trash" />
|
||||
</button>
|
||||
</template>
|
||||
<template v-else-if="own">
|
||||
<template v-else>
|
||||
<button
|
||||
v-if="canShare"
|
||||
type="button"
|
||||
@@ -509,6 +511,7 @@ const tagColors = computed<Record<string, string>>(() => {
|
||||
<Icon name="archive" />
|
||||
</button>
|
||||
<button
|
||||
v-if="own"
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
title="Move to trash"
|
||||
|
||||
@@ -865,7 +865,8 @@ function revPreview(rev: NoteRevision): string {
|
||||
>
|
||||
<Icon name="history" />
|
||||
</button>
|
||||
<template v-if="!isCreate && !liveNote.trashed && own">
|
||||
<!-- Pin and archive are everyone's own on a shared note (#5176); trash is the owner's. -->
|
||||
<template v-if="!isCreate && !liveNote.trashed">
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
@@ -884,6 +885,7 @@ function revPreview(rev: NoteRevision): string {
|
||||
<Icon name="archive" />
|
||||
</button>
|
||||
<button
|
||||
v-if="own"
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
title="Move to trash"
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useNotesStore, type Note, type NoteView } from "../stores/notes";
|
||||
import { useConfigStore } from "../stores/config";
|
||||
import { useUiStore } from "../stores/ui";
|
||||
import { facetCount, facetsFromQuery, facetsToQuery } from "../notes/facets";
|
||||
import { isOwnNote } from "../notes/sharing";
|
||||
import { useNoteEditor } from "../composables/useNoteEditor";
|
||||
import AsyncState from "../components/AsyncState.vue";
|
||||
import EmptyState from "../components/EmptyState.vue";
|
||||
@@ -127,7 +128,8 @@ function onBoardKey(e: KeyboardEvent) {
|
||||
if (key === "Enter") {
|
||||
e.preventDefault();
|
||||
openEditor(note);
|
||||
} else if (key === "x" && !inTrash.value) {
|
||||
} else if (key === "x" && !inTrash.value && isOwnNote(note)) {
|
||||
// Trash is the owner's; archive and pin below are everyone's own (#5176).
|
||||
e.preventDefault();
|
||||
void notes.trash(note.id);
|
||||
} else if (key === "e" && !inTrash.value) {
|
||||
|
||||
@@ -12,6 +12,7 @@ from . import ( # noqa: F401
|
||||
note_attachment,
|
||||
note_link_preview,
|
||||
note_revision,
|
||||
note_user_state,
|
||||
password_reset,
|
||||
saved_filter,
|
||||
settings,
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import BigInteger, Boolean, DateTime, ForeignKey, Integer, func
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from . import Base
|
||||
|
||||
|
||||
class NoteUserState(Base):
|
||||
"""A recipient's own pin, archive and place for a note shared with them (#5176).
|
||||
|
||||
The owner's live on the note itself. `position` null means "where the owner put
|
||||
it", so a recipient who only pins a note doesn't freeze its order. `updated_at`
|
||||
is when the recipient last changed any of it, which is what last-write-wins
|
||||
compares between their devices. See `note_state`.
|
||||
"""
|
||||
|
||||
__tablename__ = "note_user_state"
|
||||
|
||||
note_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("notes.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
pinned: Mapped[bool] = mapped_column(Boolean(), nullable=False, server_default=func.false())
|
||||
archived: Mapped[bool] = mapped_column(Boolean(), nullable=False, server_default=func.false())
|
||||
position: Mapped[int | None] = mapped_column(Integer(), nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
# Drawn by the row trigger (migration 0036), like notes and labels.
|
||||
sync_revision: Mapped[int | None] = mapped_column(BigInteger(), nullable=True)
|
||||
@@ -0,0 +1,100 @@
|
||||
"""How a note sits on one person's board: pinned, archived, and where (#5176).
|
||||
|
||||
For the owner that is the note's own columns. For someone it is shared with it is
|
||||
their `NoteUserState` row, so the owner pinning a shared shopping list doesn't
|
||||
reorder anyone else's board, and a recipient archiving it doesn't hide it from the
|
||||
owner. With no row, a recipient sees it unpinned, unarchived, in the owner's order.
|
||||
|
||||
The SQL expressions read through an outer join on the viewer's row, which
|
||||
`join_state` adds; every query that filters or orders by them needs it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import and_, case, false, func, select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
|
||||
from .models.note import Note
|
||||
from .models.note_user_state import NoteUserState
|
||||
|
||||
# The fields a recipient may set, which are exactly the ones this module holds.
|
||||
OWN_FIELDS = ("pinned", "archived", "position")
|
||||
|
||||
|
||||
def join_state(stmt, viewer: uuid.UUID):
|
||||
"""Outer-join the viewer's own row for each note, for the expressions below."""
|
||||
return stmt.outerjoin(
|
||||
NoteUserState, and_(NoteUserState.note_id == Note.id, NoteUserState.user_id == viewer)
|
||||
)
|
||||
|
||||
|
||||
def pinned_for(viewer: uuid.UUID):
|
||||
return case((Note.owner_id == viewer, Note.pinned), else_=func.coalesce(NoteUserState.pinned, false()))
|
||||
|
||||
|
||||
def archived_for(viewer: uuid.UUID):
|
||||
return case((Note.owner_id == viewer, Note.archived), else_=func.coalesce(NoteUserState.archived, false()))
|
||||
|
||||
|
||||
def position_for(viewer: uuid.UUID):
|
||||
return case((Note.owner_id == viewer, Note.position), else_=func.coalesce(NoteUserState.position, Note.position))
|
||||
|
||||
|
||||
def revision_for():
|
||||
"""The note's revision as the viewer's devices see it: an edit to the note, or a
|
||||
change to their own state, whichever came later. An owner has no row, so theirs
|
||||
is the note's own."""
|
||||
return func.greatest(Note.sync_revision, func.coalesce(NoteUserState.sync_revision, 0))
|
||||
|
||||
|
||||
async def states_for(db, note_ids: list, viewer: uuid.UUID) -> dict:
|
||||
"""note_id -> the viewer's own row, for the notes that have one."""
|
||||
if not note_ids:
|
||||
return {}
|
||||
rows = await db.scalars(
|
||||
select(NoteUserState).where(NoteUserState.note_id.in_(note_ids), NoteUserState.user_id == viewer)
|
||||
)
|
||||
return {s.note_id: s for s in rows.all()}
|
||||
|
||||
|
||||
def own_view(note: Note, state: NoteUserState | None) -> dict:
|
||||
"""The serialized fields this module decides, for someone who doesn't own the note."""
|
||||
return {
|
||||
"pinned": state.pinned if state is not None else False,
|
||||
"archived": state.archived if state is not None else False,
|
||||
"position": state.position if state is not None and state.position is not None else note.position,
|
||||
}
|
||||
|
||||
|
||||
async def set_own_state(db, note_id: uuid.UUID, user_id: uuid.UUID, changes: dict, at: datetime) -> bool:
|
||||
"""Apply a recipient's pin, archive or position, if `at` is no older than what
|
||||
they last set from another device (last-write-wins, as for every other change).
|
||||
Fields absent from `changes` keep their value. Returns whether it applied.
|
||||
|
||||
The caller has already found the note visible to `user_id`: this writes the row
|
||||
it is asked to, which is what lets one helper serve the web and sync alike."""
|
||||
values: dict = {}
|
||||
if "pinned" in changes:
|
||||
values["pinned"] = bool(changes["pinned"])
|
||||
if "archived" in changes:
|
||||
values["archived"] = bool(changes["archived"])
|
||||
if isinstance(changes.get("position"), int) and not isinstance(changes["position"], bool):
|
||||
values["position"] = changes["position"]
|
||||
existing = await db.scalar(
|
||||
select(NoteUserState.updated_at).where(NoteUserState.note_id == note_id, NoteUserState.user_id == user_id)
|
||||
)
|
||||
if existing is not None and at < existing:
|
||||
return False
|
||||
if not values:
|
||||
return True
|
||||
await db.execute(
|
||||
insert(NoteUserState)
|
||||
.values(note_id=note_id, user_id=user_id, updated_at=at, **values)
|
||||
.on_conflict_do_update(
|
||||
index_elements=[NoteUserState.note_id, NoteUserState.user_id],
|
||||
set_={**values, "updated_at": at},
|
||||
)
|
||||
)
|
||||
return True
|
||||
@@ -31,6 +31,7 @@ from ..models.note import Note
|
||||
from ..models.note_attachment import NoteAttachment
|
||||
from ..models.note_link_preview import NoteLinkPreview
|
||||
from ..models.note_revision import NoteRevision
|
||||
from ..note_state import OWN_FIELDS, archived_for, join_state, pinned_for, position_for, set_own_state
|
||||
from .checklist import (
|
||||
append_item,
|
||||
parse_items,
|
||||
@@ -51,6 +52,7 @@ from .helpers import (
|
||||
_attachment_ext,
|
||||
_get_editable,
|
||||
_get_owned,
|
||||
_get_visible,
|
||||
_header_filename,
|
||||
_safe_filename,
|
||||
_slugify,
|
||||
@@ -124,8 +126,12 @@ async def list_notes():
|
||||
if shared not in (None, "", "with_me"):
|
||||
return json_error("invalid shared", 400)
|
||||
async with session_scope() as db:
|
||||
stmt = select(Note).where(visible_to_user("note", Note.owner_id, Note.id, g.user_id))
|
||||
stmt = apply_filter(stmt, filter_name)
|
||||
# Through the viewer's own pin, archive and place: on a note shared with them
|
||||
# those are theirs, not the owner's (#5176).
|
||||
stmt = join_state(select(Note), g.user_id).where(
|
||||
visible_to_user("note", Note.owner_id, Note.id, g.user_id)
|
||||
)
|
||||
stmt = apply_filter(stmt, filter_name, archived_for(g.user_id))
|
||||
# Trash is the owner's: a note its owner trashed leaves a recipient's board
|
||||
# rather than turning up in their Trash, where they could do nothing with it.
|
||||
if filter_name == "trash":
|
||||
@@ -164,7 +170,9 @@ async def list_notes():
|
||||
elif sort == "created":
|
||||
stmt = stmt.order_by(Note.created_at.desc())
|
||||
else:
|
||||
stmt = stmt.order_by(Note.pinned.desc(), Note.position.desc(), Note.updated_at.desc())
|
||||
stmt = stmt.order_by(
|
||||
pinned_for(g.user_id).desc(), position_for(g.user_id).desc(), Note.updated_at.desc()
|
||||
)
|
||||
notes = (await db.scalars(stmt)).all()
|
||||
return jsonify({"notes": await _serialize_notes(db, notes, g.user_id)})
|
||||
|
||||
@@ -381,15 +389,27 @@ async def reorder_notes():
|
||||
return json_error("invalid id", 400)
|
||||
parsed.append(parsed_id)
|
||||
async with session_scope() as db:
|
||||
owned = {
|
||||
visible = {
|
||||
n.id: n
|
||||
for n in (await db.scalars(select(Note).where(Note.owner_id == g.user_id, Note.id.in_(parsed)))).all()
|
||||
for n in (
|
||||
await db.scalars(
|
||||
select(Note).where(
|
||||
Note.id.in_(parsed), visible_to_user("note", Note.owner_id, Note.id, g.user_id)
|
||||
)
|
||||
)
|
||||
).all()
|
||||
}
|
||||
now = datetime.now(timezone.utc)
|
||||
total = len(parsed)
|
||||
for index, nid in enumerate(parsed):
|
||||
note = owned.get(nid)
|
||||
if note is not None:
|
||||
note = visible.get(nid)
|
||||
if note is None:
|
||||
continue
|
||||
# A note shared with the caller moves on their board only (#5176).
|
||||
if note.owner_id == g.user_id:
|
||||
note.position = total - index
|
||||
else:
|
||||
await set_own_state(db, nid, g.user_id, {"position": total - index}, now)
|
||||
await db.commit()
|
||||
return jsonify({"ok": True})
|
||||
|
||||
@@ -441,19 +461,28 @@ async def get_note(note_id: str):
|
||||
async def update_note(note_id: str):
|
||||
data = await request.get_json(silent=True) or {}
|
||||
async with session_scope() as db:
|
||||
note = await _get_editable(db, note_id)
|
||||
note = await _get_visible(db, note_id)
|
||||
if note is None:
|
||||
return not_found()
|
||||
# Someone the note is shared with at `edit` may change its text and nothing
|
||||
# else. They can already read it, so saying so is no oracle.
|
||||
if note.owner_id != g.user_id and set(data) - {"body"}:
|
||||
return json_error("only the owner can change that", 403)
|
||||
owned = note.owner_id == g.user_id
|
||||
if not owned:
|
||||
# Someone the note is shared with may pin and archive it on their own
|
||||
# board (#5176), and change its text if it was shared at `edit`; nothing
|
||||
# else. They can already read it, so saying so is no oracle. Text from a
|
||||
# view share 404s, as it did before they could do anything at all.
|
||||
if set(data) - {"body", *OWN_FIELDS}:
|
||||
return json_error("only the owner can change that", 403)
|
||||
if "body" in data and await _get_editable(db, note_id) is None:
|
||||
return not_found()
|
||||
changed = False
|
||||
if isinstance(data.get("body"), str):
|
||||
# Version history: the first write of an editing session snapshots, not
|
||||
# every write — see revisions.should_snapshot. Writing often is what lets
|
||||
# a client autosave instead of hoarding text until it closes.
|
||||
changed = await write_body(db, note, data["body"])
|
||||
if not owned:
|
||||
await set_own_state(db, note.id, g.user_id, data, datetime.now(timezone.utc))
|
||||
return await _commit_note(db, note, changed)
|
||||
if "pinned" in data:
|
||||
note.pinned = bool(data["pinned"])
|
||||
if "archived" in data:
|
||||
|
||||
@@ -70,25 +70,28 @@ def parse_list_items(raw: object) -> list[str]:
|
||||
return [s.strip() for s in raw if isinstance(s, str) and s.strip()]
|
||||
|
||||
|
||||
def apply_filter(stmt, filter_name: str):
|
||||
def apply_filter(stmt, filter_name: str, archived):
|
||||
"""Narrow a notes query to one board view.
|
||||
|
||||
`archived` is the viewer's archive flag (`note_state.archived_for`): a note
|
||||
someone shared with you is archived on your board when YOU archived it (#5176).
|
||||
|
||||
Every branch excludes purge tombstones — content-less rows kept only so the sync
|
||||
feed can tell offline clients a note is gone (see `retention.purge_note`). The
|
||||
active/archived branches get that for free from `deleted_at IS NULL`, since a
|
||||
tombstone keeps the timestamp; Trash is the one view that has to say so.
|
||||
"""
|
||||
if filter_name == "archived":
|
||||
return stmt.where(Note.deleted_at.is_(None), Note.archived.is_(True))
|
||||
return stmt.where(Note.deleted_at.is_(None), archived.is_(True))
|
||||
if filter_name == "trash":
|
||||
return stmt.where(Note.deleted_at.is_not(None), Note.purged_at.is_(None))
|
||||
return stmt.where(Note.deleted_at.is_(None), Note.archived.is_(False))
|
||||
return stmt.where(Note.deleted_at.is_(None), archived.is_(False))
|
||||
|
||||
|
||||
async def _get_owned(db, note_id: str) -> Note | None:
|
||||
"""Fetch a note the current user OWNS, for every change only an owner may make:
|
||||
trash, delete, labels, reminders, pin, archive, attachments, previews, history and
|
||||
sharing (#5174).
|
||||
trash, delete, labels, reminders, attachments, previews, history and sharing
|
||||
(#5174). Pin and archive are everyone's own (#5176).
|
||||
|
||||
Someone the note is shared with gets None here, and so a 404, even when they can
|
||||
read the note: a 403 would confirm the note exists to a caller who only has its
|
||||
@@ -106,6 +109,22 @@ async def _get_owned(db, note_id: str) -> Note | None:
|
||||
)
|
||||
|
||||
|
||||
async def _get_visible(db, note_id: str) -> Note | None:
|
||||
"""Fetch a note the current user can see: theirs, or shared with them at any
|
||||
level. What a recipient may do to it from here is their own pin, archive and
|
||||
place (#5176); `_get_editable` and `_get_owned` gate the rest."""
|
||||
nid = parse_uuid(note_id)
|
||||
if nid is None:
|
||||
return None
|
||||
return await db.scalar(
|
||||
select(Note).where(
|
||||
Note.id == nid,
|
||||
visible_to_user("note", Note.owner_id, Note.id, g.user_id),
|
||||
Note.purged_at.is_(None),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def _get_editable(db, note_id: str) -> Note | None:
|
||||
"""Fetch a note the current user may change the TEXT of: its body and its
|
||||
checklist. The owner, or someone it is shared with at `edit`; a view share gets
|
||||
|
||||
@@ -11,6 +11,7 @@ from ..models.note import Note
|
||||
from ..models.note_attachment import NoteAttachment
|
||||
from ..models.note_link_preview import NoteLinkPreview
|
||||
from ..models.user import User
|
||||
from ..note_state import own_view, states_for
|
||||
from .checklist import parse_items
|
||||
|
||||
|
||||
@@ -141,12 +142,15 @@ async def _serialize_notes(db, notes: list, viewer=None) -> list:
|
||||
"""The API shape of each note. With `viewer`, each also says how the viewer holds
|
||||
it, and a note someone shared with them comes without the owner's labels: labels
|
||||
are personal, and a recipient's board files nothing under someone else's tags.
|
||||
Sync passes no viewer, since its feed is the caller's own notes."""
|
||||
For the same reason its pin, archive and position are the viewer's own (#5176).
|
||||
Sync passes no viewer to a client that asked only for its own notes."""
|
||||
ids = [n.id for n in notes]
|
||||
labels_map = await _labels_for_notes(db, ids)
|
||||
attach_map = await _attachments_for_notes(db, ids)
|
||||
preview_map = await _previews_for_notes(db, ids)
|
||||
sharing = await _sharing_for_notes(db, notes, viewer) if viewer is not None else {}
|
||||
foreign = [n.id for n in notes if viewer is not None and n.owner_id != viewer]
|
||||
own_states = await states_for(db, foreign, viewer)
|
||||
out = []
|
||||
for n in notes:
|
||||
data = n.serialize()
|
||||
@@ -157,5 +161,7 @@ async def _serialize_notes(db, notes: list, viewer=None) -> list:
|
||||
data["previews"] = preview_map.get(n.id, [])
|
||||
if viewer is not None:
|
||||
data.update(sharing[n.id])
|
||||
if not mine:
|
||||
data.update(own_view(n, own_states.get(n.id)))
|
||||
out.append(data)
|
||||
return out
|
||||
|
||||
+65
-32
@@ -31,13 +31,14 @@ from .models.note import Note
|
||||
from .models.note_attachment import NoteAttachment
|
||||
from .models.note_link_preview import NoteLinkPreview
|
||||
from .models.share_revocation import ShareRevocation
|
||||
from .note_state import OWN_FIELDS, join_state, revision_for, set_own_state
|
||||
from .notes import (
|
||||
_serialize_notes,
|
||||
normalize_color,
|
||||
normalize_recurrence,
|
||||
)
|
||||
from .notes.body import write_body
|
||||
from .notes.helpers import _get_editable, store_attachment, unlink_media
|
||||
from .notes.helpers import _get_editable, _get_visible, store_attachment, unlink_media
|
||||
from .responses import json_error, not_found, parse_uuid
|
||||
from .settings import get_setting
|
||||
from .retention import purge_note
|
||||
@@ -86,7 +87,10 @@ MAX_PUSH = 1000 # per-batch change cap
|
||||
# `revoked` list of notes that have left it; push takes body edits to notes shared at
|
||||
# `edit`. Additive and opt-in, so the floor stays: a v5 client never asks, and gets
|
||||
# its own notes exactly as before.
|
||||
SYNC_PROTOCOL_VERSION = 6
|
||||
# v7 (#5176): a recipient's own pin, archive and place. On a shared note the feed
|
||||
# carries the caller's own, and push takes them, stamped `state_at`, for a note shared
|
||||
# at any level. Additive, so the floor stays: a v6 client pushes only text, as before.
|
||||
SYNC_PROTOCOL_VERSION = 7
|
||||
MIN_CLIENT_PROTOCOL_VERSION = 3
|
||||
|
||||
# Named capabilities beyond the base protocol. An ADDITIVE change earns a name
|
||||
@@ -102,6 +106,7 @@ SYNC_FEATURES: tuple[str, ...] = (
|
||||
"revisions", # an overwritten version snapshots into note history
|
||||
"attachment_sync", # upload by client id + attachment/preview deletes in push (v5)
|
||||
"shares", # notes shared with the caller in the feed, `revoked`, edit-share pushes (v6)
|
||||
"shared_state", # a recipient's own pin, archive and position on a shared note (v7)
|
||||
)
|
||||
|
||||
|
||||
@@ -166,10 +171,16 @@ async def changes():
|
||||
visible = Note.owner_id == g.user_id
|
||||
async with session_scope() as db:
|
||||
# Every note the caller can see, in any state (active/archived/trash/purged),
|
||||
# since a client mirrors everything; ordered by the shared revision.
|
||||
# since a client mirrors everything; ordered by the shared revision. On a note
|
||||
# shared with the caller, pinning it moves their own state row and not the
|
||||
# note, so its revision here is whichever of the two moved last (#5176).
|
||||
revision = revision_for()
|
||||
note_rows = (
|
||||
await db.scalars(
|
||||
select(Note).where(visible, Note.sync_revision > since).order_by(Note.sync_revision).limit(limit)
|
||||
await db.execute(
|
||||
join_state(select(Note, revision), g.user_id)
|
||||
.where(visible, revision > since)
|
||||
.order_by(revision)
|
||||
.limit(limit)
|
||||
)
|
||||
).all()
|
||||
label_rows = (
|
||||
@@ -195,7 +206,7 @@ async def changes():
|
||||
|
||||
cursor, has_more = _page_cursor(
|
||||
[
|
||||
[n.sync_revision for n in note_rows],
|
||||
[rev for _, rev in note_rows],
|
||||
[lb.sync_revision for lb in label_rows],
|
||||
[rev for _, rev in revoked_rows],
|
||||
],
|
||||
@@ -203,16 +214,16 @@ async def changes():
|
||||
limit,
|
||||
)
|
||||
# Trim each stream to the shared watermark so the feeds stay aligned.
|
||||
note_rows = [n for n in note_rows if n.sync_revision <= cursor]
|
||||
note_rows = [(n, rev) for n, rev in note_rows if rev <= cursor]
|
||||
label_rows = [lb for lb in label_rows if lb.sync_revision <= cursor]
|
||||
revoked = [str(nid) for nid, rev in revoked_rows if rev <= cursor]
|
||||
|
||||
# Note bodies come from the shared note serializer; sync adds the two
|
||||
# delta-only fields on top. With shares, each note also says how the caller
|
||||
# holds it, and a note shared with them comes without the owner's labels.
|
||||
notes_out = await _serialize_notes(db, note_rows, g.user_id if with_shares else None)
|
||||
for data, n in zip(notes_out, note_rows):
|
||||
data["sync_revision"] = n.sync_revision
|
||||
notes_out = await _serialize_notes(db, [n for n, _ in note_rows], g.user_id if with_shares else None)
|
||||
for data, (n, rev) in zip(notes_out, note_rows):
|
||||
data["sync_revision"] = rev
|
||||
data["purged_at"] = iso(n.purged_at)
|
||||
|
||||
page = {
|
||||
@@ -346,32 +357,54 @@ async def _apply_note(db, ch: dict, previews: list[tuple[uuid.UUID, str]]) -> di
|
||||
|
||||
|
||||
async def _apply_shared_note(db, note: Note, ch: dict, edited_at, previews: list[tuple[uuid.UUID, str]]) -> dict:
|
||||
"""Apply a pushed change to a note someone else owns (#5175).
|
||||
"""Apply a pushed change to a note someone else owns (#5175, #5176).
|
||||
|
||||
Someone it is shared with at `edit` may change its text, exactly as in the web
|
||||
app: the body goes through `write_body` under the same last-write-wins, and every
|
||||
other field in the change is ignored, since pin, archive, reminders, labels and
|
||||
deletion are the owner's. Anything else is rejected. A note the caller cannot see
|
||||
at all gets the same generic answer as an id that doesn't exist, so the reply
|
||||
can't be used to learn that someone else's id is real.
|
||||
Two separate things can arrive, each under its own last-write-wins:
|
||||
|
||||
- Its text, from someone it is shared with at `edit`, exactly as in the web app:
|
||||
the body goes through `write_body`, compared on `edited_at` against the note.
|
||||
- Their own pin, archive and position, from anyone it is shared with, compared on
|
||||
`state_at` against what they last set. A client stamps that apart from the
|
||||
text's time so that pinning a note never makes a stale copy of its text look
|
||||
newer than the owner's edit.
|
||||
|
||||
Trash, reminders, labels and deletion are the owner's; anything asking for them
|
||||
is rejected. A note the caller cannot see at all gets the same generic answer as
|
||||
an id that doesn't exist, so the reply can't be used to learn that someone else's
|
||||
id is real.
|
||||
"""
|
||||
nid = str(note.id)
|
||||
if ch.get("op", "upsert") == "upsert" and await _get_editable(db, nid) is not None:
|
||||
if not client_wins(edited_at, note.updated_at):
|
||||
return {"id": nid, "entity": "note", "status": "kept", "sync_revision": note.sync_revision}
|
||||
body = ch["body"] if isinstance(ch.get("body"), str) else note.body
|
||||
if await write_body(db, note, body):
|
||||
previews.append((note.id, note.body))
|
||||
if edited_at is not None:
|
||||
note.updated_at = edited_at
|
||||
await db.flush()
|
||||
await db.refresh(note, ["sync_revision"])
|
||||
return {"id": nid, "entity": "note", "status": "applied", "sync_revision": note.sync_revision}
|
||||
visible = await db.scalar(
|
||||
select(Note.id).where(Note.id == note.id, visible_to_user("note", Note.owner_id, Note.id, g.user_id))
|
||||
if await _get_visible(db, nid) is None:
|
||||
return {"id": nid, "entity": "note", "status": "rejected", "error": "cannot apply"}
|
||||
owner_only = {"id": nid, "entity": "note", "status": "rejected", "error": "only its owner can change that"}
|
||||
if ch.get("op", "upsert") != "upsert":
|
||||
return owner_only
|
||||
applied = kept = False
|
||||
if isinstance(ch.get("body"), str):
|
||||
if await _get_editable(db, nid) is None:
|
||||
return owner_only
|
||||
if client_wins(edited_at, note.updated_at):
|
||||
applied = True
|
||||
if await write_body(db, note, ch["body"]):
|
||||
previews.append((note.id, note.body))
|
||||
# Only when the text changed: an unchanged body pushed beside a pin
|
||||
# is not an edit, and must not move the note on for its owner.
|
||||
if edited_at is not None:
|
||||
note.updated_at = edited_at
|
||||
else:
|
||||
kept = True
|
||||
state_at = parse_dt(ch.get("state_at"))
|
||||
if state_at is not None:
|
||||
if await set_own_state(db, note.id, g.user_id, {k: ch[k] for k in OWN_FIELDS if k in ch}, state_at):
|
||||
applied = True
|
||||
else:
|
||||
kept = True
|
||||
await db.flush()
|
||||
revision = await db.scalar(
|
||||
join_state(select(revision_for()).select_from(Note), g.user_id).where(Note.id == note.id)
|
||||
)
|
||||
error = "only its owner can change that" if visible is not None else "cannot apply"
|
||||
return {"id": nid, "entity": "note", "status": "rejected", "error": error}
|
||||
status = "kept" if kept and not applied else "applied"
|
||||
return {"id": nid, "entity": "note", "status": status, "sync_revision": revision}
|
||||
|
||||
|
||||
async def _apply_label(db, ch: dict) -> dict:
|
||||
|
||||
@@ -51,7 +51,7 @@ pytestmark = pytest.mark.integration
|
||||
|
||||
# Every table the tests touch, child-first so FKs never block the truncate.
|
||||
# RESTART IDENTITY + CASCADE keeps this honest if a table gains children later.
|
||||
_TABLES = "notes, note_revisions, note_labels, note_link_previews, labels, shares, share_revocations, invites, password_resets, users"
|
||||
_TABLES = "notes, note_revisions, note_labels, note_link_previews, labels, shares, share_revocations, note_user_state, invites, password_resets, users"
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
@@ -1292,9 +1292,9 @@ async def test_a_view_share_writes_nothing_and_an_edit_share_writes_only_text(ap
|
||||
assert "fromguest" in owner_tags
|
||||
assert (await (await recipient.get("/api/labels")).get_json())["labels"] == []
|
||||
|
||||
# Everything else stays the owner's.
|
||||
assert (await recipient.patch(f"/api/notes/{nid}", json={"pinned": True})).status_code == 403
|
||||
assert (await recipient.patch(f"/api/notes/{nid}", json={"body": "x", "archived": True})).status_code == 403
|
||||
# Everything else but their own pin and archive (#5176) stays the owner's.
|
||||
assert (await recipient.patch(f"/api/notes/{nid}", json={"remind_at": "2099-01-01T00:00:00Z"})).status_code == 403
|
||||
assert (await recipient.patch(f"/api/notes/{nid}", json={"body": "x", "recurrence": "daily"})).status_code == 403
|
||||
assert (await recipient.post(f"/api/notes/{nid}/trash")).status_code == 404
|
||||
assert (await recipient.get(f"/api/notes/{nid}/revisions")).status_code == 404
|
||||
|
||||
@@ -1303,6 +1303,41 @@ async def test_a_view_share_writes_nothing_and_an_edit_share_writes_only_text(ap
|
||||
assert "- [x] milk" in body and "eggs" in body
|
||||
|
||||
|
||||
async def test_owner_and_recipient_each_pin_archive_and_order_their_own(app_client, db):
|
||||
recipient, stranger, people = await _three_people(app_client)
|
||||
older = await _owners_note(app_client, "older")
|
||||
nid = await _owners_note(app_client, "newer")
|
||||
for note_id in (older, nid):
|
||||
await _share(app_client, note_id, people["recipient"], "view")
|
||||
|
||||
async def pinned(client) -> bool:
|
||||
return (await (await client.get(f"/api/notes/{nid}")).get_json())["pinned"]
|
||||
|
||||
# A view share is enough: pinning is organizing your own board, not changing the note.
|
||||
mine = await recipient.patch(f"/api/notes/{nid}", json={"pinned": True})
|
||||
assert mine.status_code == 200, await mine.get_data(as_text=True)
|
||||
assert (await mine.get_json())["pinned"] is True
|
||||
assert (await pinned(recipient), await pinned(app_client)) == (True, False)
|
||||
await app_client.patch(f"/api/notes/{nid}", json={"pinned": True})
|
||||
await recipient.patch(f"/api/notes/{nid}", json={"pinned": False})
|
||||
assert (await pinned(recipient), await pinned(app_client)) == (False, True)
|
||||
assert (await stranger.patch(f"/api/notes/{nid}", json={"pinned": True})).status_code == 404
|
||||
|
||||
# Archived by the recipient, it leaves their board and never the owner's.
|
||||
await recipient.patch(f"/api/notes/{nid}", json={"archived": True})
|
||||
assert await _board_ids(recipient) == [older]
|
||||
assert await _board_ids(recipient, "filter=archived") == [nid]
|
||||
assert nid in await _board_ids(app_client)
|
||||
await recipient.patch(f"/api/notes/{nid}", json={"archived": False})
|
||||
|
||||
# Until they move them, a recipient sees the owner's order; after, their own.
|
||||
await app_client.patch(f"/api/notes/{nid}", json={"pinned": False})
|
||||
assert await _board_ids(recipient) == [nid, older]
|
||||
assert (await recipient.post("/api/notes/reorder", json={"ids": [older, nid]})).status_code == 200
|
||||
assert await _board_ids(recipient) == [older, nid]
|
||||
assert await _board_ids(app_client) == [nid, older]
|
||||
|
||||
|
||||
async def test_unsharing_trashing_and_deleting_each_end_access(app_client, db):
|
||||
recipient, _, people = await _three_people(app_client)
|
||||
nid = await _owners_note(app_client)
|
||||
@@ -1420,6 +1455,45 @@ async def test_an_edit_share_pushes_text_and_nothing_else(app_client, db):
|
||||
assert (await app_client.get(f"/api/notes/{nid}")).status_code == 200
|
||||
|
||||
|
||||
async def test_a_recipients_own_state_syncs_to_their_devices_only(app_client, db):
|
||||
recipient, _, people = await _three_people(app_client)
|
||||
nid = await _owners_note(app_client, "first line")
|
||||
await _share(app_client, nid, people["recipient"], "edit")
|
||||
start = (await _feed(recipient))["cursor"]
|
||||
|
||||
async def push(change: dict) -> dict:
|
||||
payload = {"changes": [{"entity": "note", "id": nid, "op": "upsert", **change}]}
|
||||
return (await (await recipient.post("/api/sync/push", json=payload)).get_json())["results"][0]
|
||||
|
||||
# The owner edits; the recipient's phone, a version behind, pins its stale copy.
|
||||
await app_client.patch(f"/api/notes/{nid}", json={"body": "first line, the owner's edit"})
|
||||
owners = (await _feed(app_client))["cursor"]
|
||||
pinned = await push(
|
||||
{
|
||||
"edited_at": "2000-01-01T00:00:00Z",
|
||||
"body": "first line",
|
||||
"pinned": True,
|
||||
"archived": False,
|
||||
"position": 7,
|
||||
"state_at": "2099-01-01T00:00:00Z",
|
||||
}
|
||||
)
|
||||
assert pinned["status"] == "applied", pinned
|
||||
# The pin's newer time is the state's alone, so the stale text lost to the edit.
|
||||
assert (await (await app_client.get(f"/api/notes/{nid}")).get_json())["body"] == "first line, the owner's edit"
|
||||
|
||||
held = _feed_note(await _feed(recipient, start), nid)
|
||||
assert (held["pinned"], held["position"], held["sync_revision"]) == (True, 7, pinned["sync_revision"])
|
||||
# Nothing about the note changed for its owner, so their devices aren't sent it.
|
||||
assert _feed_note(await _feed(app_client, owners), nid) is None
|
||||
assert _feed_note(await _feed(app_client), nid)["pinned"] is False
|
||||
|
||||
# Another device's older unpin loses to the newer pin.
|
||||
stale = await push({"edited_at": "2000-01-01T00:00:00Z", "pinned": False, "state_at": "2098-01-01T00:00:00Z"})
|
||||
assert stale["status"] == "kept"
|
||||
assert (await (await recipient.get(f"/api/notes/{nid}")).get_json())["pinned"] is True
|
||||
|
||||
|
||||
async def test_deleting_a_shared_note_reaches_the_recipients_devices(app_client, db):
|
||||
recipient, _, people = await _three_people(app_client)
|
||||
nid = await _owners_note(app_client)
|
||||
|
||||
Reference in New Issue
Block a user