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,
|
onConfirmDelete: () -> Unit,
|
||||||
onAction: (EditorAction) -> Unit,
|
onAction: (EditorAction) -> Unit,
|
||||||
) {
|
) {
|
||||||
// Someone else's note (#5175): its text is all that may change here, so the bar
|
// Someone else's note (#5175): its text, at `edit`, and this account's own pin
|
||||||
// keeps the checklist button and nothing that is the owner's to do.
|
// 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 owner = access == NoteAccess.OWNER
|
||||||
val dark = isSystemInDarkTheme()
|
val dark = isSystemInDarkTheme()
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
@@ -133,10 +134,10 @@ fun EditorTopBar(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (owner) {
|
if (owner || !note.trashed) {
|
||||||
OverflowMenu(
|
OverflowMenu(
|
||||||
note = note,
|
note = note,
|
||||||
readOnly = readOnly,
|
owner = owner,
|
||||||
onPicker = onPicker,
|
onPicker = onPicker,
|
||||||
onShare = onShare,
|
onShare = onShare,
|
||||||
onConfirmDelete = onConfirmDelete,
|
onConfirmDelete = onConfirmDelete,
|
||||||
@@ -278,7 +279,7 @@ private fun savedLabel(
|
|||||||
@Composable
|
@Composable
|
||||||
private fun OverflowMenu(
|
private fun OverflowMenu(
|
||||||
note: Note,
|
note: Note,
|
||||||
readOnly: Boolean,
|
owner: Boolean,
|
||||||
onPicker: (Picker) -> Unit,
|
onPicker: (Picker) -> Unit,
|
||||||
onShare: () -> Unit,
|
onShare: () -> Unit,
|
||||||
onConfirmDelete: () -> Unit,
|
onConfirmDelete: () -> Unit,
|
||||||
@@ -291,7 +292,7 @@ private fun OverflowMenu(
|
|||||||
Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.editor_more))
|
Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.editor_more))
|
||||||
}
|
}
|
||||||
DropdownMenu(expanded = open, onDismissRequest = close) {
|
DropdownMenu(expanded = open, onDismissRequest = close) {
|
||||||
if (readOnly) {
|
if (note.trashed) {
|
||||||
MenuItem(R.string.editor_restore, close) { onAction(EditorAction.Restore) }
|
MenuItem(R.string.editor_restore, close) { onAction(EditorAction.Restore) }
|
||||||
MenuItem(R.string.editor_delete_forever, close, onConfirmDelete)
|
MenuItem(R.string.editor_delete_forever, close, onConfirmDelete)
|
||||||
} else {
|
} else {
|
||||||
@@ -299,16 +300,20 @@ private fun OverflowMenu(
|
|||||||
if (note.pinned) R.string.editor_unpin else R.string.editor_pin,
|
if (note.pinned) R.string.editor_unpin else R.string.editor_pin,
|
||||||
close,
|
close,
|
||||||
) { onAction(EditorAction.SetPinned(!note.pinned)) }
|
) { 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.
|
// 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(R.string.editor_share, close, onShare)
|
||||||
}
|
}
|
||||||
MenuItem(
|
MenuItem(
|
||||||
if (note.archived) R.string.editor_unarchive else R.string.editor_archive,
|
if (note.archived) R.string.editor_unarchive else R.string.editor_archive,
|
||||||
close,
|
close,
|
||||||
) { onAction(EditorAction.SetArchived(!note.archived)) }
|
) { 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`.
|
* 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
|
* Someone else's note at [EDIT] may have its TEXT changed here; at [VIEW] it may
|
||||||
* else; at [VIEW] nothing changes here at all. The core refuses the rest anyway —
|
* not. Either way its pin and archive are this account's own (#5176). The core
|
||||||
* this only keeps the editor from offering what would be refused.
|
* refuses the rest anyway — this only keeps the editor from offering what would be
|
||||||
|
* refused.
|
||||||
*/
|
*/
|
||||||
enum class NoteAccess { OWNER, EDIT, VIEW }
|
enum class NoteAccess { OWNER, EDIT, VIEW }
|
||||||
|
|
||||||
@@ -19,10 +20,10 @@ val Note.access: NoteAccess
|
|||||||
else -> NoteAccess.OWNER
|
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
|
val Note.readOnlyHere: Boolean
|
||||||
get() = trashed || access == NoteAccess.VIEW
|
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
|
val Note.ownerControlsHere: Boolean
|
||||||
get() = !readOnlyHere && access == NoteAccess.OWNER
|
get() = !readOnlyHere && access == NoteAccess.OWNER
|
||||||
|
|||||||
@@ -229,9 +229,11 @@ private fun NoteMenu(
|
|||||||
onAction: (EditorAction) -> Unit,
|
onAction: (EditorAction) -> Unit,
|
||||||
onConfirmDelete: () -> Unit,
|
onConfirmDelete: () -> Unit,
|
||||||
) {
|
) {
|
||||||
// Every item here is the owner's to do, so someone else's note has no menu at all
|
// Pin and archive are this account's own on someone else's note too (#5176);
|
||||||
// rather than an empty one (#5175).
|
// trash is the owner's. A note shared with us never reaches our Trash, so the
|
||||||
DropdownMenu(expanded = expanded && note.access == NoteAccess.OWNER, onDismissRequest = onDismiss) {
|
// 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) {
|
if (note.trashed) {
|
||||||
MenuItem(R.string.editor_restore, onDismiss) { onAction(EditorAction.Restore) }
|
MenuItem(R.string.editor_restore, onDismiss) { onAction(EditorAction.Restore) }
|
||||||
MenuItem(R.string.editor_delete_forever, onDismiss, onConfirmDelete)
|
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,
|
if (note.archived) R.string.editor_unarchive else R.string.editor_archive,
|
||||||
onDismiss,
|
onDismiss,
|
||||||
) { onAction(EditorAction.SetArchived(!note.archived)) }
|
) { 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;
|
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<()> {
|
pub fn migrate(conn: &Connection) -> rusqlite::Result<()> {
|
||||||
conn.execute_batch("PRAGMA foreign_keys = ON;")?;
|
conn.execute_batch("PRAGMA foreign_keys = ON;")?;
|
||||||
let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;
|
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(SCHEMA_V11)?;
|
||||||
conn.execute_batch("PRAGMA user_version = 11;")?;
|
conn.execute_batch("PRAGMA user_version = 11;")?;
|
||||||
}
|
}
|
||||||
|
if version < 12 {
|
||||||
|
conn.execute_batch(SCHEMA_V12)?;
|
||||||
|
conn.execute_batch("PRAGMA user_version = 12;")?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -472,7 +490,7 @@ mod tests {
|
|||||||
let version: i64 = conn
|
let version: i64 = conn
|
||||||
.query_row("PRAGMA user_version", [], |r| r.get(0))
|
.query_row("PRAGMA user_version", [], |r| r.get(0))
|
||||||
.expect("version");
|
.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
|
/// 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) ---------------------------------
|
// ---- notes shared with this account (#5175) ---------------------------------
|
||||||
//
|
//
|
||||||
// A note someone else owns arrives with `permission` `edit` (its text may change
|
// 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,
|
// here) or `view` (it may not). Its pin, archive and place on this board are this
|
||||||
// reminders, labels, files — stays its owner's. The server enforces the same split;
|
// 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,
|
// 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.
|
// 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.";
|
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`
|
/// 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)
|
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<()> {
|
fn require_owner(conn: &Connection, id: &str) -> rusqlite::Result<()> {
|
||||||
match permission_of(conn, id)?.as_str() {
|
match permission_of(conn, id)?.as_str() {
|
||||||
"owner" => Ok(()),
|
"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<()> {
|
fn touch(conn: &Connection, id: &str) -> rusqlite::Result<()> {
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"UPDATE notes SET updated_at = ?1, dirty = 1 WHERE id = ?2",
|
"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
|
let obj = changes
|
||||||
.as_object()
|
.as_object()
|
||||||
.ok_or_else(|| rusqlite::Error::InvalidParameterName("changes must be an object".into()))?;
|
.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";
|
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));
|
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)
|
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<()> {
|
pub fn reorder(conn: &Connection, ordered_ids: &[String]) -> rusqlite::Result<()> {
|
||||||
let total = ordered_ids.len() as i64;
|
let total = ordered_ids.len() as i64;
|
||||||
|
let at = now();
|
||||||
for (i, id) in ordered_ids.iter().enumerate() {
|
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(
|
conn.execute(
|
||||||
"UPDATE notes SET position = ?1, dirty = 1 WHERE id = ?2 AND permission = 'owner'",
|
"UPDATE notes
|
||||||
params![total - i as i64, id],
|
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(())
|
Ok(())
|
||||||
@@ -1340,17 +1376,21 @@ mod tests {
|
|||||||
assert!(dirty(&conn, "n"));
|
assert!(dirty(&conn, "n"));
|
||||||
add_item(&conn, "n", "eggs").expect("an item is text");
|
add_item(&conn, "n", "eggs").expect("an item is text");
|
||||||
|
|
||||||
let pinned = update_note(&conn, "n", &json!({ "pinned": true }))
|
let reminded = update_note(
|
||||||
.err()
|
&conn,
|
||||||
.expect("refused");
|
"n",
|
||||||
assert_eq!(pinned.to_string(), OWNER_ONLY);
|
&json!({ "remind_at": "2026-02-01T00:00:00.000Z" }),
|
||||||
assert!(update_note(&conn, "n", &json!({ "body": "x", "archived": true })).is_err());
|
)
|
||||||
|
.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!(trash(&conn, "n").is_err());
|
||||||
assert!(complete_reminder(&conn, "n").is_err());
|
assert!(complete_reminder(&conn, "n").is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn shared_notes_stay_out_of_trash_reminders_and_reordering() {
|
fn shared_notes_stay_out_of_trash_and_reminders() {
|
||||||
let conn = db();
|
let conn = db();
|
||||||
shared(&conn, "theirs", "edit");
|
shared(&conn, "theirs", "edit");
|
||||||
conn.execute(
|
conn.execute(
|
||||||
@@ -1367,9 +1407,52 @@ mod tests {
|
|||||||
.expect("restored");
|
.expect("restored");
|
||||||
assert!(reminders(&conn).expect("reminders").is_empty());
|
assert!(reminders(&conn).expect("reminders").is_empty());
|
||||||
assert!(due_reminders(&conn, i64::MAX).expect("due").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");
|
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]
|
#[test]
|
||||||
|
|||||||
+12
-3
@@ -25,7 +25,10 @@ use std::sync::OnceLock;
|
|||||||
/// on [`MIN_SERVER_PROTOCOL_VERSION`].
|
/// on [`MIN_SERVER_PROTOCOL_VERSION`].
|
||||||
/// v5 (#5168): files attached here upload, and removed attachments and previews are
|
/// v5 (#5168): files attached here upload, and removed attachments and previews are
|
||||||
/// pushed. Additive: both go only to a server advertising `attachment_sync`.
|
/// 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
|
/// The oldest server protocol this client can drive — the symmetric half of the
|
||||||
/// server's `min_client_protocol_version`.
|
/// 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
|
/// Capabilities whose absence costs a feature but not the link. Listing these
|
||||||
/// explicitly (rather than diffing against whatever the server happens to send) is
|
/// explicitly (rather than diffing against whatever the server happens to send) is
|
||||||
/// what lets the UI name exactly what the user will be missing.
|
/// what lets the UI name exactly what the user will be missing.
|
||||||
pub const OPTIONAL_FEATURES: &[&str] =
|
pub const OPTIONAL_FEATURES: &[&str] = &[
|
||||||
&["attachments", "tombstones", "revisions", "attachment_sync"];
|
"attachments",
|
||||||
|
"tombstones",
|
||||||
|
"revisions",
|
||||||
|
"attachment_sync",
|
||||||
|
"shares",
|
||||||
|
"shared_state",
|
||||||
|
];
|
||||||
|
|
||||||
/// The handshake fields of `GET /api/config`.
|
/// 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
|
// Notes shared with this account come only from a server offering `shares`, and
|
||||||
// an unanswered probe reads as "not offered", like `attachment_sync` above.
|
// an unanswered probe reads as "not offered", like `attachment_sync` above.
|
||||||
let shares = server.as_ref().is_some_and(|s| s.has_feature("shares"));
|
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 {
|
if shares {
|
||||||
// After the push, so nothing unsent is waiting when the full pull lands.
|
// 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())?;
|
let conn = db.0.lock().map_err(|e| e.to_string())?;
|
||||||
if state::begin_shares(&conn).map_err(|e| e.to_string())? {
|
if state::begin_shares(&conn, level).map_err(|e| e.to_string())? {
|
||||||
log::info!("the server shares notes now; pulling everything once to find them");
|
log::info!("the server shares more of notes now; pulling everything once");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let pull = pull::run(db, blobs, base_url, token, shares).await?;
|
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>,
|
pub created_at: Option<String>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub name: Option<String>,
|
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 {
|
impl Change {
|
||||||
@@ -115,6 +121,7 @@ impl Change {
|
|||||||
label_ids: None,
|
label_ids: None,
|
||||||
created_at: None,
|
created_at: None,
|
||||||
name: None,
|
name: None,
|
||||||
|
state_at: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -143,24 +150,38 @@ pub struct PushResult {
|
|||||||
|
|
||||||
// --- collecting --------------------------------------------------------------
|
// --- 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
|
/// Everything waiting to go up, oldest edit first so a truncated batch still makes
|
||||||
/// forward progress in a sensible order.
|
/// forward progress in a sensible order.
|
||||||
///
|
pub fn collect(conn: &Connection, limit: usize, accepts: Accepts) -> rusqlite::Result<Vec<Change>> {
|
||||||
/// `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>> {
|
|
||||||
let mut out = Vec::new();
|
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 {
|
if out.len() < limit {
|
||||||
collect_labels(conn, &mut out, limit)?;
|
collect_labels(conn, &mut out, limit)?;
|
||||||
}
|
}
|
||||||
if out.len() < limit {
|
if out.len() < limit {
|
||||||
collect_notes(conn, &mut out, limit)?;
|
collect_notes(conn, &mut out, limit, accepts.shared_state)?;
|
||||||
}
|
}
|
||||||
Ok(out)
|
Ok(out)
|
||||||
}
|
}
|
||||||
@@ -225,6 +246,7 @@ fn collect_labels(conn: &Connection, out: &mut Vec<Change>, limit: usize) -> rus
|
|||||||
position: None,
|
position: None,
|
||||||
label_ids: None,
|
label_ids: None,
|
||||||
created_at: None,
|
created_at: None,
|
||||||
|
state_at: None,
|
||||||
})
|
})
|
||||||
})?;
|
})?;
|
||||||
for row in rows {
|
for row in rows {
|
||||||
@@ -233,21 +255,31 @@ fn collect_labels(conn: &Connection, out: &mut Vec<Change>, limit: usize) -> rus
|
|||||||
Ok(())
|
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 remaining = limit.saturating_sub(out.len());
|
||||||
let ids: Vec<String> = {
|
let ids: Vec<String> = {
|
||||||
// A note shared with us to view can't be changed here, so one that is dirty
|
// A note shared with us to view has only this account's own pin, archive and
|
||||||
// anyway (its share was narrowed while an edit waited) has nothing the server
|
// place to send, and only to a server that keeps them. Without one, a dirty
|
||||||
// would take. The next pull puts the server's copy back over it.
|
// 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(
|
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",
|
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>>>()?
|
rows.collect::<rusqlite::Result<Vec<String>>>()?
|
||||||
};
|
};
|
||||||
for id in ids {
|
for id in ids {
|
||||||
out.push(note_change(conn, &id)?);
|
out.push(note_change(conn, &id, shared_state)?);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -264,14 +296,16 @@ struct NoteRow {
|
|||||||
recurrence: Option<String>,
|
recurrence: Option<String>,
|
||||||
created_at: String,
|
created_at: String,
|
||||||
updated_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,
|
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> {
|
fn note_row(conn: &Connection, id: &str) -> rusqlite::Result<NoteRow> {
|
||||||
conn.query_row(
|
conn.query_row(
|
||||||
"SELECT body, position, pinned, archived, trashed,
|
"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",
|
FROM notes WHERE id = ?1",
|
||||||
params![id],
|
params![id],
|
||||||
|r| {
|
|r| {
|
||||||
@@ -286,34 +320,39 @@ fn note_row(conn: &Connection, id: &str) -> rusqlite::Result<NoteRow> {
|
|||||||
created_at: r.get(7)?,
|
created_at: r.get(7)?,
|
||||||
updated_at: r.get(8)?,
|
updated_at: r.get(8)?,
|
||||||
permission: r.get(9)?,
|
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)?;
|
let row = note_row(conn, id)?;
|
||||||
|
|
||||||
// Someone else's note: only its text is ours to change, so only its text goes.
|
// Someone else's note: its text if it was shared to edit, and this account's own
|
||||||
// Pin, archive, trash, reminders, order and labels are the owner's, and this
|
// pin, archive and place once they have been changed here, to a server that keeps
|
||||||
// account's labels were never on it.
|
// them. Trash, reminders and labels are the owner's, and this account's labels
|
||||||
|
// were never on it.
|
||||||
if row.permission != "owner" {
|
if row.permission != "owner" {
|
||||||
|
let state_at = row.state_at.filter(|_| shared_state);
|
||||||
|
let own = state_at.is_some();
|
||||||
return Ok(Change {
|
return Ok(Change {
|
||||||
entity: "note",
|
entity: "note",
|
||||||
id: id.to_string(),
|
id: id.to_string(),
|
||||||
op: "upsert",
|
op: "upsert",
|
||||||
edited_at: row.updated_at,
|
edited_at: row.updated_at,
|
||||||
body: Some(row.body),
|
body: (row.permission == "edit").then_some(row.body),
|
||||||
color: None,
|
color: None,
|
||||||
pinned: None,
|
pinned: own.then_some(row.pinned),
|
||||||
archived: None,
|
archived: own.then_some(row.archived),
|
||||||
trashed: None,
|
trashed: None,
|
||||||
remind_at: None,
|
remind_at: None,
|
||||||
recurrence: None,
|
recurrence: None,
|
||||||
position: None,
|
position: own.then_some(row.position),
|
||||||
label_ids: None,
|
label_ids: None,
|
||||||
created_at: None,
|
created_at: None,
|
||||||
name: None,
|
name: None,
|
||||||
|
state_at,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -346,6 +385,7 @@ fn note_change(conn: &Connection, id: &str) -> rusqlite::Result<Change> {
|
|||||||
label_ids: Some(label_ids),
|
label_ids: Some(label_ids),
|
||||||
created_at: Some(row.created_at),
|
created_at: Some(row.created_at),
|
||||||
name: None,
|
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
|
/// 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.
|
/// next is collected — then the files, once their notes are there to hold them.
|
||||||
///
|
///
|
||||||
/// `attachment_sync`: whether the server advertises it (see [`collect`]). Without
|
/// `accepts`: what the server advertises (see [`Accepts`]). Without
|
||||||
/// it, uploads wait too.
|
/// `attachment_sync`, uploads wait too.
|
||||||
pub async fn run(
|
pub async fn run(
|
||||||
db: &Db,
|
db: &Db,
|
||||||
blobs: &BlobStore,
|
blobs: &BlobStore,
|
||||||
base_url: &str,
|
base_url: &str,
|
||||||
token: &str,
|
token: &str,
|
||||||
attachment_sync: bool,
|
accepts: Accepts,
|
||||||
) -> Result<PushSummary, String> {
|
) -> Result<PushSummary, String> {
|
||||||
let mut total = PushSummary::default();
|
let mut total = PushSummary::default();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let batch = {
|
let batch = {
|
||||||
let conn = db.0.lock().map_err(|e| e.to_string())?;
|
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() {
|
if batch.is_empty() {
|
||||||
break;
|
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?);
|
total.absorb(upload_pending(db, blobs, base_url, token).await?);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -736,7 +776,7 @@ mod tests {
|
|||||||
let conn = db();
|
let conn = db();
|
||||||
seed_note(&conn, "clean", 0);
|
seed_note(&conn, "clean", 0);
|
||||||
seed_note(&conn, "dirty", 1);
|
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.len(), 1);
|
||||||
assert_eq!(batch[0].id, "dirty");
|
assert_eq!(batch[0].id, "dirty");
|
||||||
assert_eq!(batch[0].op, "upsert");
|
assert_eq!(batch[0].op, "upsert");
|
||||||
@@ -761,7 +801,7 @@ mod tests {
|
|||||||
)
|
)
|
||||||
.expect("seed membership");
|
.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");
|
let note = batch.iter().find(|c| c.entity == "note").expect("note");
|
||||||
assert_eq!(note.label_ids.as_deref(), Some(&["manual".to_string()][..]));
|
assert_eq!(note.label_ids.as_deref(), Some(&["manual".to_string()][..]));
|
||||||
}
|
}
|
||||||
@@ -771,7 +811,7 @@ mod tests {
|
|||||||
let conn = db();
|
let conn = db();
|
||||||
seed_note(&conn, "n1", 0);
|
seed_note(&conn, "n1", 0);
|
||||||
store::delete_forever(&conn, "n1").expect("delete");
|
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.len(), 1);
|
||||||
assert_eq!(batch[0].op, "delete");
|
assert_eq!(batch[0].op, "delete");
|
||||||
assert_eq!(batch[0].entity, "note");
|
assert_eq!(batch[0].entity, "note");
|
||||||
@@ -782,7 +822,7 @@ mod tests {
|
|||||||
fn applied_clears_dirty_and_records_the_revision() {
|
fn applied_clears_dirty_and_records_the_revision() {
|
||||||
let conn = db();
|
let conn = db();
|
||||||
seed_note(&conn, "n1", 1);
|
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");
|
apply_results(&conn, &batch, &[ok("applied", Some(42))]).expect("apply");
|
||||||
assert_eq!(dirty_count(&conn), 0);
|
assert_eq!(dirty_count(&conn), 0);
|
||||||
let rev: i64 = conn
|
let rev: i64 = conn
|
||||||
@@ -799,7 +839,7 @@ mod tests {
|
|||||||
// every time; the following pull adopts the server's version instead.
|
// every time; the following pull adopts the server's version instead.
|
||||||
let conn = db();
|
let conn = db();
|
||||||
seed_note(&conn, "n1", 1);
|
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");
|
let summary = apply_results(&conn, &batch, &[ok("kept", Some(99))]).expect("apply");
|
||||||
assert_eq!(summary.kept, 1);
|
assert_eq!(summary.kept, 1);
|
||||||
assert_eq!(dirty_count(&conn), 0);
|
assert_eq!(dirty_count(&conn), 0);
|
||||||
@@ -813,7 +853,7 @@ mod tests {
|
|||||||
let conn = db();
|
let conn = db();
|
||||||
seed_note(&conn, "n1", 1);
|
seed_note(&conn, "n1", 1);
|
||||||
state::set_cursor(&conn, 100).expect("cursor");
|
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");
|
apply_results(&conn, &batch, &[ok("kept", Some(40))]).expect("apply");
|
||||||
assert_eq!(state::read(&conn).expect("state").last_cursor, 39);
|
assert_eq!(state::read(&conn).expect("state").last_cursor, 39);
|
||||||
}
|
}
|
||||||
@@ -823,7 +863,7 @@ mod tests {
|
|||||||
let conn = db();
|
let conn = db();
|
||||||
seed_note(&conn, "n1", 1);
|
seed_note(&conn, "n1", 1);
|
||||||
state::set_cursor(&conn, 10).expect("cursor");
|
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");
|
apply_results(&conn, &batch, &[ok("kept", Some(40))]).expect("apply");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
state::read(&conn).expect("state").last_cursor,
|
state::read(&conn).expect("state").last_cursor,
|
||||||
@@ -836,7 +876,7 @@ mod tests {
|
|||||||
fn rejected_stays_dirty_and_is_reported() {
|
fn rejected_stays_dirty_and_is_reported() {
|
||||||
let conn = db();
|
let conn = db();
|
||||||
seed_note(&conn, "n1", 1);
|
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);
|
let mut bad = ok("rejected", None);
|
||||||
bad.error = Some("name in use".into());
|
bad.error = Some("name in use".into());
|
||||||
let summary = apply_results(&conn, &batch, &[bad]).expect("apply");
|
let summary = apply_results(&conn, &batch, &[bad]).expect("apply");
|
||||||
@@ -850,7 +890,7 @@ mod tests {
|
|||||||
let conn = db();
|
let conn = db();
|
||||||
seed_note(&conn, "n1", 0);
|
seed_note(&conn, "n1", 0);
|
||||||
store::delete_forever(&conn, "n1").expect("delete");
|
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");
|
apply_results(&conn, &batch, &[ok("applied", Some(7))]).expect("apply");
|
||||||
assert!(!has_pending(&conn).expect("pending"));
|
assert!(!has_pending(&conn).expect("pending"));
|
||||||
}
|
}
|
||||||
@@ -861,7 +901,7 @@ mod tests {
|
|||||||
let conn = db();
|
let conn = db();
|
||||||
seed_note(&conn, "n1", 1);
|
seed_note(&conn, "n1", 1);
|
||||||
store::delete_forever(&conn, "n1").expect("delete");
|
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");
|
apply_results(&conn, &batch, &[ok("noop", None)]).expect("apply");
|
||||||
assert!(!has_pending(&conn).expect("pending"));
|
assert!(!has_pending(&conn).expect("pending"));
|
||||||
}
|
}
|
||||||
@@ -895,7 +935,7 @@ mod tests {
|
|||||||
seed_note(&conn, "n1", 1);
|
seed_note(&conn, "n1", 1);
|
||||||
conn.execute("UPDATE notes SET permission = 'edit' WHERE id = 'n1'", [])
|
conn.execute("UPDATE notes SET permission = 'edit' WHERE id = 'n1'", [])
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let changes = collect(&conn, 10, true).unwrap();
|
let changes = collect(&conn, 10, Accepts::ALL).unwrap();
|
||||||
assert_eq!(changes.len(), 1);
|
assert_eq!(changes.len(), 1);
|
||||||
let wire = serde_json::to_value(&changes[0]).unwrap();
|
let wire = serde_json::to_value(&changes[0]).unwrap();
|
||||||
let mut keys: Vec<&str> = wire
|
let mut keys: Vec<&str> = wire
|
||||||
@@ -909,12 +949,35 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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();
|
let conn = db();
|
||||||
seed_note(&conn, "n1", 1);
|
seed_note(&conn, "n1", 1);
|
||||||
conn.execute("UPDATE notes SET permission = 'view' WHERE id = 'n1'", [])
|
conn.execute("UPDATE notes SET permission = 'view' WHERE id = 'n1'", [])
|
||||||
.unwrap();
|
.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]
|
#[test]
|
||||||
@@ -1003,14 +1066,14 @@ mod tests {
|
|||||||
store::record_pending_delete(&conn, "note", "n9").expect("tombstone");
|
store::record_pending_delete(&conn, "note", "n9").expect("tombstone");
|
||||||
|
|
||||||
// An older server would answer "unknown entity" to each of them.
|
// 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")
|
.expect("collect")
|
||||||
.iter()
|
.iter()
|
||||||
.map(|c| c.entity)
|
.map(|c| c.entity)
|
||||||
.collect();
|
.collect();
|
||||||
assert_eq!(older, vec!["note"]);
|
assert_eq!(older, vec!["note"]);
|
||||||
|
|
||||||
let mut newer: Vec<_> = collect(&conn, 100, true)
|
let mut newer: Vec<_> = collect(&conn, 100, Accepts::ALL)
|
||||||
.expect("collect")
|
.expect("collect")
|
||||||
.iter()
|
.iter()
|
||||||
.map(|c| (c.entity, c.op))
|
.map(|c| (c.entity, c.op))
|
||||||
@@ -1071,7 +1134,7 @@ mod tests {
|
|||||||
store::delete_attachment(&conn, "n1", "a1").expect("remove");
|
store::delete_attachment(&conn, "n1", "a1").expect("remove");
|
||||||
|
|
||||||
// Push: the removal and the touched note go up, and the server applies both.
|
// 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
|
let results: Vec<PushResult> = batch
|
||||||
.iter()
|
.iter()
|
||||||
.map(|c| ok("applied", (c.entity == "note").then_some(5)))
|
.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(())
|
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
|
/// Shared notes arrive at all (#5175).
|
||||||
/// without a restart they would only arrive once something next changed them.
|
pub const SHARES: i64 = 1;
|
||||||
/// Returns whether it restarted. Once per link: `set_link` to another server and
|
/// A shared note's pin, archive and position are this account's own (#5176). Before,
|
||||||
/// `clear_link` both reset the flag.
|
/// the feed sent the owner's, and a device holding those would keep showing them
|
||||||
pub fn begin_shares(conn: &Connection) -> rusqlite::Result<bool> {
|
/// 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(
|
let restarted = conn.execute(
|
||||||
"UPDATE sync_state SET last_cursor = NULL, shares_synced = 1
|
"UPDATE sync_state SET last_cursor = NULL, shares_synced = ?1
|
||||||
WHERE id = 1 AND shares_synced = 0",
|
WHERE id = 1 AND shares_synced < ?1",
|
||||||
[],
|
params![level],
|
||||||
)?;
|
)?;
|
||||||
Ok(restarted > 0)
|
Ok(restarted > 0)
|
||||||
}
|
}
|
||||||
@@ -342,14 +352,24 @@ mod tests {
|
|||||||
let conn = db();
|
let conn = db();
|
||||||
set_link(&conn, "https://a.example.com", "tok-1").expect("link");
|
set_link(&conn, "https://a.example.com", "tok-1").expect("link");
|
||||||
set_cursor(&conn, 500).expect("cursor");
|
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);
|
assert_eq!(read(&conn).expect("read").last_cursor, 0);
|
||||||
set_cursor(&conn, 600).expect("cursor");
|
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);
|
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.
|
// Another server is a fresh start, shares included.
|
||||||
set_link(&conn, "https://b.example.com", "tok-2").expect("relink");
|
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]
|
#[test]
|
||||||
|
|||||||
+26
-6
@@ -67,6 +67,10 @@ syncs everything else.
|
|||||||
- v6 (#5175): shared notes — see "Shared notes" below. Opt-in per request
|
- 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
|
(`changes?shares=1`), so it is the `shares` feature and the floor stays: a v5
|
||||||
client never asks and gets exactly its own notes.
|
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`
|
- **Additive change** (a new field, a new capability) → add a `sync_features`
|
||||||
name. Do **not** raise a minimum. Old clients keep working.
|
name. Do **not** raise a minimum. Old clients keep working.
|
||||||
- **Breaking change only** → raise `MIN_CLIENT_PROTOCOL_VERSION` (or the client's
|
- **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
|
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.
|
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`
|
## Push — `POST /api/sync/push`
|
||||||
|
|
||||||
Body: `{ "changes": [ ... ] }` (max 1000 per batch). Each change:
|
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
|
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
|
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.
|
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
|
- **A note someone else owns** (`shares`): an upsert may carry two things, each
|
||||||
and only its `body` is applied, under the same last-write-wins — every other
|
under its own last-write-wins.
|
||||||
field is ignored, since pinning, archiving, reminders, labels and deleting stay
|
- Its `body`, from a recipient at `edit`, compared on `edited_at` against the
|
||||||
the owner's. A `view` recipient's change, or any delete, is `rejected` ("only its
|
note. From a `view` recipient a body is `rejected` ("only its owner can change
|
||||||
owner can change that"); a note the caller can't see at all answers the generic
|
that").
|
||||||
"cannot apply".
|
- 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
|
### 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
|
// 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. ---
|
// 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.
|
// 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 dragging = computed(() => draggingId.value === props.note.id);
|
||||||
const dragOver = computed(() => overId.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" />
|
<Icon name="grip" />
|
||||||
</button>
|
</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
|
<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"
|
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">
|
<template v-if="note.trashed">
|
||||||
@@ -477,7 +479,7 @@ const tagColors = computed<Record<string, string>>(() => {
|
|||||||
<Icon name="trash" />
|
<Icon name="trash" />
|
||||||
</button>
|
</button>
|
||||||
</template>
|
</template>
|
||||||
<template v-else-if="own">
|
<template v-else>
|
||||||
<button
|
<button
|
||||||
v-if="canShare"
|
v-if="canShare"
|
||||||
type="button"
|
type="button"
|
||||||
@@ -509,6 +511,7 @@ const tagColors = computed<Record<string, string>>(() => {
|
|||||||
<Icon name="archive" />
|
<Icon name="archive" />
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
|
v-if="own"
|
||||||
type="button"
|
type="button"
|
||||||
class="icon-btn"
|
class="icon-btn"
|
||||||
title="Move to trash"
|
title="Move to trash"
|
||||||
|
|||||||
@@ -865,7 +865,8 @@ function revPreview(rev: NoteRevision): string {
|
|||||||
>
|
>
|
||||||
<Icon name="history" />
|
<Icon name="history" />
|
||||||
</button>
|
</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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="icon-btn"
|
class="icon-btn"
|
||||||
@@ -884,6 +885,7 @@ function revPreview(rev: NoteRevision): string {
|
|||||||
<Icon name="archive" />
|
<Icon name="archive" />
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
|
v-if="own"
|
||||||
type="button"
|
type="button"
|
||||||
class="icon-btn"
|
class="icon-btn"
|
||||||
title="Move to trash"
|
title="Move to trash"
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useNotesStore, type Note, type NoteView } from "../stores/notes";
|
|||||||
import { useConfigStore } from "../stores/config";
|
import { useConfigStore } from "../stores/config";
|
||||||
import { useUiStore } from "../stores/ui";
|
import { useUiStore } from "../stores/ui";
|
||||||
import { facetCount, facetsFromQuery, facetsToQuery } from "../notes/facets";
|
import { facetCount, facetsFromQuery, facetsToQuery } from "../notes/facets";
|
||||||
|
import { isOwnNote } from "../notes/sharing";
|
||||||
import { useNoteEditor } from "../composables/useNoteEditor";
|
import { useNoteEditor } from "../composables/useNoteEditor";
|
||||||
import AsyncState from "../components/AsyncState.vue";
|
import AsyncState from "../components/AsyncState.vue";
|
||||||
import EmptyState from "../components/EmptyState.vue";
|
import EmptyState from "../components/EmptyState.vue";
|
||||||
@@ -127,7 +128,8 @@ function onBoardKey(e: KeyboardEvent) {
|
|||||||
if (key === "Enter") {
|
if (key === "Enter") {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
openEditor(note);
|
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();
|
e.preventDefault();
|
||||||
void notes.trash(note.id);
|
void notes.trash(note.id);
|
||||||
} else if (key === "e" && !inTrash.value) {
|
} else if (key === "e" && !inTrash.value) {
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from . import ( # noqa: F401
|
|||||||
note_attachment,
|
note_attachment,
|
||||||
note_link_preview,
|
note_link_preview,
|
||||||
note_revision,
|
note_revision,
|
||||||
|
note_user_state,
|
||||||
password_reset,
|
password_reset,
|
||||||
saved_filter,
|
saved_filter,
|
||||||
settings,
|
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_attachment import NoteAttachment
|
||||||
from ..models.note_link_preview import NoteLinkPreview
|
from ..models.note_link_preview import NoteLinkPreview
|
||||||
from ..models.note_revision import NoteRevision
|
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 (
|
from .checklist import (
|
||||||
append_item,
|
append_item,
|
||||||
parse_items,
|
parse_items,
|
||||||
@@ -51,6 +52,7 @@ from .helpers import (
|
|||||||
_attachment_ext,
|
_attachment_ext,
|
||||||
_get_editable,
|
_get_editable,
|
||||||
_get_owned,
|
_get_owned,
|
||||||
|
_get_visible,
|
||||||
_header_filename,
|
_header_filename,
|
||||||
_safe_filename,
|
_safe_filename,
|
||||||
_slugify,
|
_slugify,
|
||||||
@@ -124,8 +126,12 @@ async def list_notes():
|
|||||||
if shared not in (None, "", "with_me"):
|
if shared not in (None, "", "with_me"):
|
||||||
return json_error("invalid shared", 400)
|
return json_error("invalid shared", 400)
|
||||||
async with session_scope() as db:
|
async with session_scope() as db:
|
||||||
stmt = select(Note).where(visible_to_user("note", Note.owner_id, Note.id, g.user_id))
|
# Through the viewer's own pin, archive and place: on a note shared with them
|
||||||
stmt = apply_filter(stmt, filter_name)
|
# 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
|
# 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.
|
# rather than turning up in their Trash, where they could do nothing with it.
|
||||||
if filter_name == "trash":
|
if filter_name == "trash":
|
||||||
@@ -164,7 +170,9 @@ async def list_notes():
|
|||||||
elif sort == "created":
|
elif sort == "created":
|
||||||
stmt = stmt.order_by(Note.created_at.desc())
|
stmt = stmt.order_by(Note.created_at.desc())
|
||||||
else:
|
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()
|
notes = (await db.scalars(stmt)).all()
|
||||||
return jsonify({"notes": await _serialize_notes(db, notes, g.user_id)})
|
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)
|
return json_error("invalid id", 400)
|
||||||
parsed.append(parsed_id)
|
parsed.append(parsed_id)
|
||||||
async with session_scope() as db:
|
async with session_scope() as db:
|
||||||
owned = {
|
visible = {
|
||||||
n.id: n
|
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)
|
total = len(parsed)
|
||||||
for index, nid in enumerate(parsed):
|
for index, nid in enumerate(parsed):
|
||||||
note = owned.get(nid)
|
note = visible.get(nid)
|
||||||
if note is not None:
|
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
|
note.position = total - index
|
||||||
|
else:
|
||||||
|
await set_own_state(db, nid, g.user_id, {"position": total - index}, now)
|
||||||
await db.commit()
|
await db.commit()
|
||||||
return jsonify({"ok": True})
|
return jsonify({"ok": True})
|
||||||
|
|
||||||
@@ -441,19 +461,28 @@ async def get_note(note_id: str):
|
|||||||
async def update_note(note_id: str):
|
async def update_note(note_id: str):
|
||||||
data = await request.get_json(silent=True) or {}
|
data = await request.get_json(silent=True) or {}
|
||||||
async with session_scope() as db:
|
async with session_scope() as db:
|
||||||
note = await _get_editable(db, note_id)
|
note = await _get_visible(db, note_id)
|
||||||
if note is None:
|
if note is None:
|
||||||
return not_found()
|
return not_found()
|
||||||
# Someone the note is shared with at `edit` may change its text and nothing
|
owned = note.owner_id == g.user_id
|
||||||
# else. They can already read it, so saying so is no oracle.
|
if not owned:
|
||||||
if note.owner_id != g.user_id and set(data) - {"body"}:
|
# Someone the note is shared with may pin and archive it on their own
|
||||||
return json_error("only the owner can change that", 403)
|
# 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
|
changed = False
|
||||||
if isinstance(data.get("body"), str):
|
if isinstance(data.get("body"), str):
|
||||||
# Version history: the first write of an editing session snapshots, not
|
# Version history: the first write of an editing session snapshots, not
|
||||||
# every write — see revisions.should_snapshot. Writing often is what lets
|
# every write — see revisions.should_snapshot. Writing often is what lets
|
||||||
# a client autosave instead of hoarding text until it closes.
|
# a client autosave instead of hoarding text until it closes.
|
||||||
changed = await write_body(db, note, data["body"])
|
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:
|
if "pinned" in data:
|
||||||
note.pinned = bool(data["pinned"])
|
note.pinned = bool(data["pinned"])
|
||||||
if "archived" in data:
|
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()]
|
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.
|
"""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
|
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
|
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
|
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.
|
tombstone keeps the timestamp; Trash is the one view that has to say so.
|
||||||
"""
|
"""
|
||||||
if filter_name == "archived":
|
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":
|
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_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:
|
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:
|
"""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
|
trash, delete, labels, reminders, attachments, previews, history and sharing
|
||||||
sharing (#5174).
|
(#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
|
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
|
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:
|
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
|
"""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
|
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_attachment import NoteAttachment
|
||||||
from ..models.note_link_preview import NoteLinkPreview
|
from ..models.note_link_preview import NoteLinkPreview
|
||||||
from ..models.user import User
|
from ..models.user import User
|
||||||
|
from ..note_state import own_view, states_for
|
||||||
from .checklist import parse_items
|
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
|
"""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
|
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.
|
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]
|
ids = [n.id for n in notes]
|
||||||
labels_map = await _labels_for_notes(db, ids)
|
labels_map = await _labels_for_notes(db, ids)
|
||||||
attach_map = await _attachments_for_notes(db, ids)
|
attach_map = await _attachments_for_notes(db, ids)
|
||||||
preview_map = await _previews_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 {}
|
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 = []
|
out = []
|
||||||
for n in notes:
|
for n in notes:
|
||||||
data = n.serialize()
|
data = n.serialize()
|
||||||
@@ -157,5 +161,7 @@ async def _serialize_notes(db, notes: list, viewer=None) -> list:
|
|||||||
data["previews"] = preview_map.get(n.id, [])
|
data["previews"] = preview_map.get(n.id, [])
|
||||||
if viewer is not None:
|
if viewer is not None:
|
||||||
data.update(sharing[n.id])
|
data.update(sharing[n.id])
|
||||||
|
if not mine:
|
||||||
|
data.update(own_view(n, own_states.get(n.id)))
|
||||||
out.append(data)
|
out.append(data)
|
||||||
return out
|
return out
|
||||||
|
|||||||
+65
-32
@@ -31,13 +31,14 @@ from .models.note import Note
|
|||||||
from .models.note_attachment import NoteAttachment
|
from .models.note_attachment import NoteAttachment
|
||||||
from .models.note_link_preview import NoteLinkPreview
|
from .models.note_link_preview import NoteLinkPreview
|
||||||
from .models.share_revocation import ShareRevocation
|
from .models.share_revocation import ShareRevocation
|
||||||
|
from .note_state import OWN_FIELDS, join_state, revision_for, set_own_state
|
||||||
from .notes import (
|
from .notes import (
|
||||||
_serialize_notes,
|
_serialize_notes,
|
||||||
normalize_color,
|
normalize_color,
|
||||||
normalize_recurrence,
|
normalize_recurrence,
|
||||||
)
|
)
|
||||||
from .notes.body import write_body
|
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 .responses import json_error, not_found, parse_uuid
|
||||||
from .settings import get_setting
|
from .settings import get_setting
|
||||||
from .retention import purge_note
|
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
|
# `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
|
# `edit`. Additive and opt-in, so the floor stays: a v5 client never asks, and gets
|
||||||
# its own notes exactly as before.
|
# 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
|
MIN_CLIENT_PROTOCOL_VERSION = 3
|
||||||
|
|
||||||
# Named capabilities beyond the base protocol. An ADDITIVE change earns a name
|
# 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
|
"revisions", # an overwritten version snapshots into note history
|
||||||
"attachment_sync", # upload by client id + attachment/preview deletes in push (v5)
|
"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)
|
"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
|
visible = Note.owner_id == g.user_id
|
||||||
async with session_scope() as db:
|
async with session_scope() as db:
|
||||||
# Every note the caller can see, in any state (active/archived/trash/purged),
|
# 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 = (
|
note_rows = (
|
||||||
await db.scalars(
|
await db.execute(
|
||||||
select(Note).where(visible, Note.sync_revision > since).order_by(Note.sync_revision).limit(limit)
|
join_state(select(Note, revision), g.user_id)
|
||||||
|
.where(visible, revision > since)
|
||||||
|
.order_by(revision)
|
||||||
|
.limit(limit)
|
||||||
)
|
)
|
||||||
).all()
|
).all()
|
||||||
label_rows = (
|
label_rows = (
|
||||||
@@ -195,7 +206,7 @@ async def changes():
|
|||||||
|
|
||||||
cursor, has_more = _page_cursor(
|
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],
|
[lb.sync_revision for lb in label_rows],
|
||||||
[rev for _, rev in revoked_rows],
|
[rev for _, rev in revoked_rows],
|
||||||
],
|
],
|
||||||
@@ -203,16 +214,16 @@ async def changes():
|
|||||||
limit,
|
limit,
|
||||||
)
|
)
|
||||||
# Trim each stream to the shared watermark so the feeds stay aligned.
|
# 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]
|
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]
|
revoked = [str(nid) for nid, rev in revoked_rows if rev <= cursor]
|
||||||
|
|
||||||
# Note bodies come from the shared note serializer; sync adds the two
|
# 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
|
# 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.
|
# 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)
|
notes_out = await _serialize_notes(db, [n for n, _ in note_rows], g.user_id if with_shares else None)
|
||||||
for data, n in zip(notes_out, note_rows):
|
for data, (n, rev) in zip(notes_out, note_rows):
|
||||||
data["sync_revision"] = n.sync_revision
|
data["sync_revision"] = rev
|
||||||
data["purged_at"] = iso(n.purged_at)
|
data["purged_at"] = iso(n.purged_at)
|
||||||
|
|
||||||
page = {
|
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:
|
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
|
Two separate things can arrive, each under its own last-write-wins:
|
||||||
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
|
- Its text, from someone it is shared with at `edit`, exactly as in the web app:
|
||||||
deletion are the owner's. Anything else is rejected. A note the caller cannot see
|
the body goes through `write_body`, compared on `edited_at` against the note.
|
||||||
at all gets the same generic answer as an id that doesn't exist, so the reply
|
- Their own pin, archive and position, from anyone it is shared with, compared on
|
||||||
can't be used to learn that someone else's id is real.
|
`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)
|
nid = str(note.id)
|
||||||
if ch.get("op", "upsert") == "upsert" and await _get_editable(db, nid) is not None:
|
if await _get_visible(db, nid) is None:
|
||||||
if not client_wins(edited_at, note.updated_at):
|
return {"id": nid, "entity": "note", "status": "rejected", "error": "cannot apply"}
|
||||||
return {"id": nid, "entity": "note", "status": "kept", "sync_revision": note.sync_revision}
|
owner_only = {"id": nid, "entity": "note", "status": "rejected", "error": "only its owner can change that"}
|
||||||
body = ch["body"] if isinstance(ch.get("body"), str) else note.body
|
if ch.get("op", "upsert") != "upsert":
|
||||||
if await write_body(db, note, body):
|
return owner_only
|
||||||
previews.append((note.id, note.body))
|
applied = kept = False
|
||||||
if edited_at is not None:
|
if isinstance(ch.get("body"), str):
|
||||||
note.updated_at = edited_at
|
if await _get_editable(db, nid) is None:
|
||||||
await db.flush()
|
return owner_only
|
||||||
await db.refresh(note, ["sync_revision"])
|
if client_wins(edited_at, note.updated_at):
|
||||||
return {"id": nid, "entity": "note", "status": "applied", "sync_revision": note.sync_revision}
|
applied = True
|
||||||
visible = await db.scalar(
|
if await write_body(db, note, ch["body"]):
|
||||||
select(Note.id).where(Note.id == note.id, visible_to_user("note", Note.owner_id, Note.id, g.user_id))
|
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"
|
status = "kept" if kept and not applied else "applied"
|
||||||
return {"id": nid, "entity": "note", "status": "rejected", "error": error}
|
return {"id": nid, "entity": "note", "status": status, "sync_revision": revision}
|
||||||
|
|
||||||
|
|
||||||
async def _apply_label(db, ch: dict) -> dict:
|
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.
|
# 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.
|
# 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
|
@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 "fromguest" in owner_tags
|
||||||
assert (await (await recipient.get("/api/labels")).get_json())["labels"] == []
|
assert (await (await recipient.get("/api/labels")).get_json())["labels"] == []
|
||||||
|
|
||||||
# Everything else stays the owner's.
|
# Everything else but their own pin and archive (#5176) 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={"remind_at": "2099-01-01T00:00:00Z"})).status_code == 403
|
||||||
assert (await recipient.patch(f"/api/notes/{nid}", json={"body": "x", "archived": True})).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.post(f"/api/notes/{nid}/trash")).status_code == 404
|
||||||
assert (await recipient.get(f"/api/notes/{nid}/revisions")).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
|
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):
|
async def test_unsharing_trashing_and_deleting_each_end_access(app_client, db):
|
||||||
recipient, _, people = await _three_people(app_client)
|
recipient, _, people = await _three_people(app_client)
|
||||||
nid = await _owners_note(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
|
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):
|
async def test_deleting_a_shared_note_reaches_the_recipients_devices(app_client, db):
|
||||||
recipient, _, people = await _three_people(app_client)
|
recipient, _, people = await _three_people(app_client)
|
||||||
nid = await _owners_note(app_client)
|
nid = await _owners_note(app_client)
|
||||||
|
|||||||
Reference in New Issue
Block a user