Compare commits
3
Commits
2e2714a50b
...
fd1d50662f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd1d50662f | ||
|
|
442cca4398 | ||
|
|
5f3cfe8bb7 |
@@ -29,12 +29,15 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.fabledsword.inkwell.R
|
||||
import com.fabledsword.inkwell.core.Member
|
||||
import com.fabledsword.inkwell.core.Note
|
||||
import com.fabledsword.inkwell.core.NoteShare
|
||||
import com.fabledsword.inkwell.core.ShareGroup
|
||||
import com.fabledsword.inkwell.core.ShareTarget
|
||||
|
||||
/** "Shared by Robin · view only" over someone else's note; nothing over our own. */
|
||||
@Composable
|
||||
@@ -59,16 +62,16 @@ private const val VIEW = "view"
|
||||
private const val EDIT = "edit"
|
||||
|
||||
/**
|
||||
* The Share sheet: who the note is shared with, and adding someone.
|
||||
* The Share sheet: who the note is shared with, and adding someone or a group.
|
||||
*
|
||||
* A peer of the web's `ShareDialog.vue`. Each person's permission is a pair of
|
||||
* chips rather than a menu, because there are exactly two and both fit.
|
||||
* A peer of the web's `ShareDialog.vue`. Each share's permission is a pair of chips
|
||||
* rather than a menu, because there are exactly two and both fit.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ShareSheet(
|
||||
state: ShareState,
|
||||
onShare: (userId: String, permission: String) -> Unit,
|
||||
onShare: (target: ShareTarget, permission: String) -> Unit,
|
||||
onUnshare: (shareId: String) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
@@ -96,7 +99,7 @@ fun ShareSheet(
|
||||
@Composable
|
||||
private fun ShareBody(
|
||||
state: ShareState,
|
||||
onShare: (userId: String, permission: String) -> Unit,
|
||||
onShare: (target: ShareTarget, permission: String) -> Unit,
|
||||
onUnshare: (shareId: String) -> Unit,
|
||||
) {
|
||||
if (state.shares.isEmpty()) {
|
||||
@@ -106,7 +109,7 @@ private fun ShareBody(
|
||||
ShareRow(
|
||||
share = share,
|
||||
busy = state.busy,
|
||||
onPermission = { onShare(share.member.id, it) },
|
||||
onPermission = { onShare(share.target, it) },
|
||||
onRemove = { onUnshare(share.id) },
|
||||
)
|
||||
}
|
||||
@@ -127,7 +130,7 @@ private fun ShareRow(
|
||||
) {
|
||||
Column {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
MemberName(share.member, Modifier.weight(1f))
|
||||
TargetName(share.member, share.group, Modifier.weight(1f))
|
||||
IconButton(onClick = onRemove, enabled = !busy) {
|
||||
Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.share_remove))
|
||||
}
|
||||
@@ -139,9 +142,9 @@ private fun ShareRow(
|
||||
@Composable
|
||||
private fun AddPerson(
|
||||
state: ShareState,
|
||||
onShare: (userId: String, permission: String) -> Unit,
|
||||
onShare: (target: ShareTarget, permission: String) -> Unit,
|
||||
) {
|
||||
var pick by remember(state.noteId) { mutableStateOf<String?>(null) }
|
||||
var pick by remember(state.noteId) { mutableStateOf<ShareCandidate?>(null) }
|
||||
var permission by remember(state.noteId) { mutableStateOf(VIEW) }
|
||||
|
||||
Text(
|
||||
@@ -152,13 +155,13 @@ private fun AddPerson(
|
||||
// Capped, like the tag picker: a sheet that grows past the screen makes its own
|
||||
// scroll fight the sheet's drag.
|
||||
LazyColumn(modifier = Modifier.heightIn(max = MEMBER_LIST_MAX_HEIGHT)) {
|
||||
items(items = state.available, key = { it.id }) { member ->
|
||||
items(items = state.available, key = { it.key }) { candidate ->
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().clickable { pick = member.id },
|
||||
modifier = Modifier.fillMaxWidth().clickable { pick = candidate },
|
||||
) {
|
||||
RadioButton(selected = pick == member.id, onClick = { pick = member.id })
|
||||
MemberName(member, Modifier.weight(1f))
|
||||
RadioButton(selected = pick?.key == candidate.key, onClick = { pick = candidate })
|
||||
TargetName(candidate.member, candidate.group, Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -168,7 +171,7 @@ private fun AddPerson(
|
||||
TextButton(
|
||||
enabled = pick != null && !state.busy,
|
||||
onClick = {
|
||||
pick?.let { onShare(it, permission) }
|
||||
pick?.let { onShare(it.target, permission) }
|
||||
pick = null
|
||||
},
|
||||
) { Text(stringResource(R.string.share_action)) }
|
||||
@@ -197,19 +200,30 @@ private fun PermissionChips(
|
||||
}
|
||||
}
|
||||
|
||||
/** A person (name over email) or a group (name over how many are in it). */
|
||||
@Composable
|
||||
private fun MemberName(
|
||||
member: Member,
|
||||
private fun TargetName(
|
||||
member: Member?,
|
||||
group: ShareGroup?,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val title = group?.name ?: member?.let { it.displayName.ifBlank { it.email } }.orEmpty()
|
||||
val detail =
|
||||
when {
|
||||
group != null ->
|
||||
pluralStringResource(
|
||||
R.plurals.share_group_members,
|
||||
group.memberCount.toInt(),
|
||||
group.memberCount.toInt(),
|
||||
)
|
||||
member != null && member.displayName.isNotBlank() -> member.email
|
||||
else -> null
|
||||
}
|
||||
Column(modifier = modifier) {
|
||||
Text(
|
||||
text = member.displayName.ifBlank { member.email },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
)
|
||||
if (member.displayName.isNotBlank()) {
|
||||
Text(text = title, style = MaterialTheme.typography.bodyLarge)
|
||||
detail?.let {
|
||||
Text(
|
||||
text = member.email,
|
||||
text = it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
@@ -10,6 +10,8 @@ import com.fabledsword.inkwell.core.CoreException
|
||||
import com.fabledsword.inkwell.core.Inkwell
|
||||
import com.fabledsword.inkwell.core.Member
|
||||
import com.fabledsword.inkwell.core.NoteShare
|
||||
import com.fabledsword.inkwell.core.ShareGroup
|
||||
import com.fabledsword.inkwell.core.ShareTarget
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -19,6 +21,8 @@ data class ShareState(
|
||||
val noteId: String? = null,
|
||||
val loading: Boolean = false,
|
||||
val members: List<Member> = emptyList(),
|
||||
/** The groups the admin made (#5177); a note shared with one reaches its members. */
|
||||
val groups: List<ShareGroup> = emptyList(),
|
||||
val shares: List<NoteShare> = emptyList(),
|
||||
/** This device has no server, and sharing is between people on one. */
|
||||
val needsServer: Boolean = false,
|
||||
@@ -28,14 +32,36 @@ data class ShareState(
|
||||
val busy: Boolean = false,
|
||||
val error: String? = null,
|
||||
) {
|
||||
/** The people it isn't shared with yet. */
|
||||
val available: List<Member>
|
||||
/** The people and groups it isn't shared with yet, people first. */
|
||||
val available: List<ShareCandidate>
|
||||
get() {
|
||||
val taken = shares.map { it.member.id }.toSet()
|
||||
return members.filterNot { it.id in taken }
|
||||
val people = shares.mapNotNull { it.member?.id }.toSet()
|
||||
val grouped = shares.mapNotNull { it.group?.id }.toSet()
|
||||
return members.filterNot { it.id in people }.map { ShareCandidate(member = it) } +
|
||||
groups.filterNot { it.id in grouped }.map { ShareCandidate(group = it) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Someone, or a group, the sheet offers to share with. Exactly one is set. */
|
||||
data class ShareCandidate(
|
||||
val member: Member? = null,
|
||||
val group: ShareGroup? = null,
|
||||
) {
|
||||
val key: String
|
||||
get() = group?.let { "g:${it.id}" } ?: "u:${member?.id}"
|
||||
val target: ShareTarget
|
||||
get() = targetOf(member, group)
|
||||
}
|
||||
|
||||
/** Who an existing share goes to, to change its permission. */
|
||||
val NoteShare.target: ShareTarget
|
||||
get() = targetOf(member, group)
|
||||
|
||||
private fun targetOf(
|
||||
member: Member?,
|
||||
group: ShareGroup?,
|
||||
): ShareTarget = group?.let { ShareTarget.Group(it.id) } ?: ShareTarget.Member(member?.id.orEmpty())
|
||||
|
||||
/**
|
||||
* Sharing a note with other people on the linked server (#5175).
|
||||
*
|
||||
@@ -63,9 +89,14 @@ class ShareViewModel(
|
||||
if (!withContext(Dispatchers.IO) { core.syncStatus().linked }) {
|
||||
state.copy(loading = false, needsServer = true)
|
||||
} else {
|
||||
val members = core.shareDirectory()
|
||||
val directory = core.shareDirectory()
|
||||
val shares = core.noteShares(noteId)
|
||||
state.copy(loading = false, members = members, shares = shares)
|
||||
state.copy(
|
||||
loading = false,
|
||||
members = directory.members,
|
||||
groups = directory.groups,
|
||||
shares = shares,
|
||||
)
|
||||
}
|
||||
} catch (e: CoreException) {
|
||||
state.copy(loading = false, loadError = e.describeShareFailure())
|
||||
@@ -77,11 +108,11 @@ class ShareViewModel(
|
||||
state = ShareState()
|
||||
}
|
||||
|
||||
/** Share with someone, or change what they may do. */
|
||||
/** Share with someone or a group, or change what they may do. */
|
||||
fun share(
|
||||
userId: String,
|
||||
target: ShareTarget,
|
||||
permission: String,
|
||||
) = write { noteId -> core.shareNote(noteId, userId, permission) }
|
||||
) = write { noteId -> core.shareNote(noteId, target, permission) }
|
||||
|
||||
fun unshare(shareId: String) = write { noteId -> core.unshareNote(noteId, shareId) }
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
<string name="share_needs_server">Sharing is between people on a server. Link this phone in Sync to share notes.</string>
|
||||
<string name="share_none">Not shared with anyone yet.</string>
|
||||
<string name="share_everyone">Shared with everyone on this server.</string>
|
||||
<string name="share_add">Add someone</string>
|
||||
<string name="share_add">Add someone or a group</string>
|
||||
<string name="share_action">Share</string>
|
||||
<string name="share_remove">Stop sharing</string>
|
||||
<string name="share_can_view">Can view</string>
|
||||
@@ -77,6 +77,10 @@
|
||||
<string name="share_by_can_edit">Shared by %1$s · you can edit the text</string>
|
||||
<string name="share_chip_shared">Shared</string>
|
||||
<string name="share_chip_by">From %1$s</string>
|
||||
<plurals name="share_group_members">
|
||||
<item quantity="one">Group · %d person</item>
|
||||
<item quantity="other">Group · %d people</item>
|
||||
</plurals>
|
||||
|
||||
<!-- Attachments. A file is stored on the phone at once and uploaded on a later
|
||||
sync, so nothing here talks about the network. -->
|
||||
|
||||
+10
-9
@@ -43,8 +43,9 @@ use inkwell_core::sync::blobs::BlobStore;
|
||||
use inkwell_core::sync::{client, compat, engine, push, sharing, state};
|
||||
|
||||
use models::{
|
||||
patch_from, BodyItem, BodyTag, ClientUpdate, Identity, Label, Member, Note, NoteDraft,
|
||||
NoteEdit, NoteQuery, NoteShare, ProbeResult, RevokeOutcome, SyncOutcome, SyncStatus,
|
||||
patch_from, BodyItem, BodyTag, ClientUpdate, Directory, Identity, Label, Note, NoteDraft,
|
||||
NoteEdit, NoteQuery, NoteShare, ProbeResult, RevokeOutcome, ShareTarget, SyncOutcome,
|
||||
SyncStatus,
|
||||
};
|
||||
|
||||
uniffi::setup_scaffolding!();
|
||||
@@ -612,13 +613,13 @@ impl Inkwell {
|
||||
// The Share dialog asks the server directly (#5175). Unlinked, each answers
|
||||
// `NotLinked`, which the dialog turns into "sharing needs a server".
|
||||
|
||||
/// Everyone on the instance a note can be shared with.
|
||||
pub async fn share_directory(&self) -> Result<Vec<Member>, CoreError> {
|
||||
/// Everyone on the instance a note can be shared with, and every group.
|
||||
pub async fn share_directory(&self) -> Result<Directory, CoreError> {
|
||||
self.credentials()?;
|
||||
let members = sharing::directory(&self.db)
|
||||
let directory = sharing::directory(&self.db)
|
||||
.await
|
||||
.map_err(CoreError::network)?;
|
||||
Ok(members.into_iter().map(Member::from).collect())
|
||||
Ok(directory.into())
|
||||
}
|
||||
|
||||
/// Who this note is shared with.
|
||||
@@ -630,15 +631,15 @@ impl Inkwell {
|
||||
Ok(shares.into_iter().map(NoteShare::from).collect())
|
||||
}
|
||||
|
||||
/// Share with one member at "view" or "edit", or change their permission.
|
||||
/// Share with a person or a group at "view" or "edit", or change their permission.
|
||||
pub async fn share_note(
|
||||
&self,
|
||||
note_id: String,
|
||||
user_id: String,
|
||||
target: ShareTarget,
|
||||
permission: String,
|
||||
) -> Result<Vec<NoteShare>, CoreError> {
|
||||
self.credentials()?;
|
||||
let shares = sharing::share(&self.db, ¬e_id, &user_id, &permission)
|
||||
let shares = sharing::share(&self.db, ¬e_id, &target.into(), &permission)
|
||||
.await
|
||||
.map_err(CoreError::network)?;
|
||||
Ok(shares.into_iter().map(NoteShare::from).collect())
|
||||
|
||||
@@ -636,11 +636,68 @@ impl From<core_client::Member> for Member {
|
||||
}
|
||||
}
|
||||
|
||||
/// One person a note is shared with, at "view" or "edit".
|
||||
/// A group the admin made, which a note can be shared with (#5177).
|
||||
#[derive(Debug, Clone, uniffi::Record)]
|
||||
pub struct ShareGroup {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub member_count: u32,
|
||||
}
|
||||
|
||||
impl From<core_client::ShareGroup> for ShareGroup {
|
||||
fn from(value: core_client::ShareGroup) -> Self {
|
||||
let core_client::ShareGroup {
|
||||
id,
|
||||
name,
|
||||
member_count,
|
||||
} = value;
|
||||
ShareGroup {
|
||||
id,
|
||||
name,
|
||||
member_count,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Everyone a note can be shared with: the other people, and every group.
|
||||
#[derive(Debug, Clone, uniffi::Record)]
|
||||
pub struct Directory {
|
||||
pub members: Vec<Member>,
|
||||
pub groups: Vec<ShareGroup>,
|
||||
}
|
||||
|
||||
impl From<core_client::Directory> for Directory {
|
||||
fn from(value: core_client::Directory) -> Self {
|
||||
let core_client::Directory { members, groups } = value;
|
||||
Directory {
|
||||
members: members.into_iter().map(Member::from).collect(),
|
||||
groups: groups.into_iter().map(ShareGroup::from).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Who a new share goes to: one person, or a group.
|
||||
#[derive(Debug, Clone, uniffi::Enum)]
|
||||
pub enum ShareTarget {
|
||||
Member { id: String },
|
||||
Group { id: String },
|
||||
}
|
||||
|
||||
impl From<ShareTarget> for core_client::ShareTarget {
|
||||
fn from(value: ShareTarget) -> Self {
|
||||
match value {
|
||||
ShareTarget::Member { id } => core_client::ShareTarget::Member(id),
|
||||
ShareTarget::Group { id } => core_client::ShareTarget::Group(id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One share of a note, at "view" or "edit": to a person or to a group, never both.
|
||||
#[derive(Debug, Clone, uniffi::Record)]
|
||||
pub struct NoteShare {
|
||||
pub id: String,
|
||||
pub member: Member,
|
||||
pub member: Option<Member>,
|
||||
pub group: Option<ShareGroup>,
|
||||
pub permission: String,
|
||||
}
|
||||
|
||||
@@ -650,12 +707,14 @@ impl From<core_client::NoteShare> for NoteShare {
|
||||
let core_client::NoteShare {
|
||||
id,
|
||||
member,
|
||||
group,
|
||||
permission,
|
||||
created_at: _,
|
||||
} = value;
|
||||
NoteShare {
|
||||
id,
|
||||
member: member.into(),
|
||||
member: member.map(Member::from),
|
||||
group: group.map(ShareGroup::from),
|
||||
permission,
|
||||
}
|
||||
}
|
||||
|
||||
+73
-12
@@ -439,19 +439,59 @@ pub struct Member {
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
/// One person a note is shared with, and at what level (`view` or `edit`).
|
||||
/// A group the admin made, which a note can be shared with (#5177). Sharing with it
|
||||
/// reaches whoever is in it at the time.
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct ShareGroup {
|
||||
pub id: String,
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub member_count: u32,
|
||||
}
|
||||
|
||||
/// Everyone a note can be shared with: the other people on the instance, and every
|
||||
/// group. `groups` defaults empty for a server from before groups.
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct Directory {
|
||||
#[serde(default)]
|
||||
pub members: Vec<Member>,
|
||||
#[serde(default)]
|
||||
pub groups: Vec<ShareGroup>,
|
||||
}
|
||||
|
||||
/// One share of a note, at `view` or `edit`: to a person (`member`) or to a group
|
||||
/// (`group`), never both.
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct NoteShare {
|
||||
pub id: String,
|
||||
pub member: Member,
|
||||
#[serde(default)]
|
||||
pub member: Option<Member>,
|
||||
#[serde(default)]
|
||||
pub group: Option<ShareGroup>,
|
||||
pub permission: String,
|
||||
#[serde(default)]
|
||||
pub created_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct MembersReply {
|
||||
members: Vec<Member>,
|
||||
/// Who a new share goes to.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ShareTarget {
|
||||
Member(String),
|
||||
Group(String),
|
||||
}
|
||||
|
||||
impl ShareTarget {
|
||||
fn body(&self, permission: &str) -> serde_json::Value {
|
||||
match self {
|
||||
ShareTarget::Member(id) => {
|
||||
serde_json::json!({ "user_id": id, "permission": permission })
|
||||
}
|
||||
ShareTarget::Group(id) => {
|
||||
serde_json::json!({ "group_id": id, "permission": permission })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -493,11 +533,10 @@ async fn read_reply<T: serde::de::DeserializeOwned>(
|
||||
.map_err(|e| format!("Couldn't read the reply from {base_url}: {e}"))
|
||||
}
|
||||
|
||||
/// Everyone on the instance but this account.
|
||||
pub async fn directory(base_url: &str, token: &str) -> Result<Vec<Member>, String> {
|
||||
/// Everyone on the instance but this account, and every group.
|
||||
pub async fn directory(base_url: &str, token: &str) -> Result<Directory, String> {
|
||||
let url = format!("{base_url}/api/users/directory");
|
||||
let reply: MembersReply = read_reply(base_url, prepare(http()?.get(url), Some(token))).await?;
|
||||
Ok(reply.members)
|
||||
read_reply(base_url, prepare(http()?.get(url), Some(token))).await
|
||||
}
|
||||
|
||||
pub async fn list_shares(
|
||||
@@ -510,16 +549,17 @@ pub async fn list_shares(
|
||||
Ok(reply.shares)
|
||||
}
|
||||
|
||||
/// Share with one member, or change their permission. Answers the note's shares.
|
||||
/// Share with a person or a group, or change their permission. Answers the note's
|
||||
/// shares.
|
||||
pub async fn share_note(
|
||||
base_url: &str,
|
||||
token: &str,
|
||||
note_id: &str,
|
||||
user_id: &str,
|
||||
target: &ShareTarget,
|
||||
permission: &str,
|
||||
) -> Result<Vec<NoteShare>, String> {
|
||||
let url = format!("{base_url}/api/notes/{note_id}/shares");
|
||||
let body = serde_json::json!({ "user_id": user_id, "permission": permission });
|
||||
let body = target.body(permission);
|
||||
let reply: SharesReply = read_reply(
|
||||
base_url,
|
||||
prepare(http()?.post(url), Some(token)).json(&body),
|
||||
@@ -583,6 +623,27 @@ fn describe_transport_error(base_url: &str, err: &reqwest::Error) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_share_names_a_person_or_a_group() {
|
||||
assert_eq!(
|
||||
ShareTarget::Member("u1".into()).body("view"),
|
||||
serde_json::json!({ "user_id": "u1", "permission": "view" })
|
||||
);
|
||||
assert_eq!(
|
||||
ShareTarget::Group("g1".into()).body("edit"),
|
||||
serde_json::json!({ "group_id": "g1", "permission": "edit" })
|
||||
);
|
||||
let raw = r#"{"id":"s2","member":null,
|
||||
"group":{"id":"g1","name":"Family","member_count":3},
|
||||
"permission":"edit"}"#;
|
||||
let share: NoteShare = serde_json::from_str(raw).expect("a group share reads");
|
||||
assert!(share.member.is_none());
|
||||
assert_eq!(share.group.expect("group").member_count, 3);
|
||||
// A server from before groups sends no `groups` at all.
|
||||
let older: Directory = serde_json::from_str(r#"{"members":[]}"#).expect("directory");
|
||||
assert!(older.groups.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn urls_join_without_doubling_slashes() {
|
||||
// normalize_base_url has already stripped any trailing slash, so plain
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
use rusqlite::params;
|
||||
|
||||
use super::client::{self, Member, NoteShare};
|
||||
use super::client::{self, Directory, NoteShare, ShareTarget};
|
||||
use super::state;
|
||||
use crate::local::Db;
|
||||
|
||||
@@ -38,7 +38,7 @@ fn mark_shared(db: &Db, note_id: &str, shares: &[NoteShare]) -> Result<(), Strin
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn directory(db: &Db) -> Result<Vec<Member>, String> {
|
||||
pub async fn directory(db: &Db) -> Result<Directory, String> {
|
||||
let (url, token) = link(db)?;
|
||||
client::directory(&url, &token).await
|
||||
}
|
||||
@@ -53,11 +53,11 @@ pub async fn list(db: &Db, note_id: &str) -> Result<Vec<NoteShare>, String> {
|
||||
pub async fn share(
|
||||
db: &Db,
|
||||
note_id: &str,
|
||||
user_id: &str,
|
||||
target: &ShareTarget,
|
||||
permission: &str,
|
||||
) -> Result<Vec<NoteShare>, String> {
|
||||
let (url, token) = link(db)?;
|
||||
let shares = client::share_note(&url, &token, note_id, user_id, permission).await?;
|
||||
let shares = client::share_note(&url, &token, note_id, target, permission).await?;
|
||||
mark_shared(db, note_id, &shares)?;
|
||||
Ok(shares)
|
||||
}
|
||||
@@ -73,6 +73,7 @@ pub async fn unshare(db: &Db, note_id: &str, share_id: &str) -> Result<Vec<NoteS
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::local::schema;
|
||||
use crate::sync::client::Member;
|
||||
use rusqlite::Connection;
|
||||
use std::sync::Mutex;
|
||||
|
||||
@@ -101,11 +102,12 @@ mod tests {
|
||||
}
|
||||
let one = NoteShare {
|
||||
id: "s1".into(),
|
||||
member: Member {
|
||||
member: Some(Member {
|
||||
id: "u2".into(),
|
||||
display_name: "Sam".into(),
|
||||
email: "sam@example.test".into(),
|
||||
},
|
||||
}),
|
||||
group: None,
|
||||
permission: "view".into(),
|
||||
created_at: None,
|
||||
};
|
||||
|
||||
@@ -8,7 +8,7 @@ use tauri::{AppHandle, State};
|
||||
|
||||
use inkwell_core::local::Db;
|
||||
use inkwell_core::sync::client::{self, Identity, ProbeResult};
|
||||
use inkwell_core::sync::client::{Member, NoteShare};
|
||||
use inkwell_core::sync::client::{Directory, NoteShare, ShareTarget};
|
||||
use inkwell_core::sync::compat::Compatibility;
|
||||
use inkwell_core::sync::engine;
|
||||
use inkwell_core::sync::push;
|
||||
@@ -193,7 +193,7 @@ pub fn sync_has_pending(db: State<'_, Db>) -> Result<bool, String> {
|
||||
// `sharing::NEEDS_SERVER`, which the dialog shows as it is.
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn shares_directory(db: State<'_, Db>) -> Result<Vec<Member>, String> {
|
||||
pub async fn shares_directory(db: State<'_, Db>) -> Result<Directory, String> {
|
||||
sharing::directory(&db).await
|
||||
}
|
||||
|
||||
@@ -202,14 +202,21 @@ pub async fn shares_list(note_id: String, db: State<'_, Db>) -> Result<Vec<NoteS
|
||||
sharing::list(&db, ¬e_id).await
|
||||
}
|
||||
|
||||
/// Share with a person (`user_id`) or a group (`group_id`, #5177): exactly one.
|
||||
#[tauri::command]
|
||||
pub async fn shares_share(
|
||||
note_id: String,
|
||||
user_id: String,
|
||||
user_id: Option<String>,
|
||||
group_id: Option<String>,
|
||||
permission: String,
|
||||
db: State<'_, Db>,
|
||||
) -> Result<Vec<NoteShare>, String> {
|
||||
sharing::share(&db, ¬e_id, &user_id, &permission).await
|
||||
let target = match (user_id, group_id) {
|
||||
(Some(id), None) => ShareTarget::Member(id),
|
||||
(None, Some(id)) => ShareTarget::Group(id),
|
||||
_ => return Err("Choose someone or a group to share with.".to_string()),
|
||||
};
|
||||
sharing::share(&db, ¬e_id, &target, &permission).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
+4
-2
@@ -221,8 +221,10 @@ labels are personal, and a recipient files nothing under the owner's tags.
|
||||
|
||||
Granting or changing a share moves the note to a new revision (without touching
|
||||
`updated_at`, so last-write-wins is unaffected), which is how it passes a
|
||||
recipient's cursor. Ending a share — or the owner purging the note — adds the note
|
||||
to the recipient's `revoked` list:
|
||||
recipient's cursor. Joining a group a note is shared with does the same for the
|
||||
new member (#5177). Ending a share — or the owner purging the note, the person
|
||||
leaving the group, or the admin deleting it — adds the note to the `revoked` list of
|
||||
each person who can no longer see it:
|
||||
|
||||
```json
|
||||
{ "notes": [ ... ], "labels": [ ... ], "revoked": ["<note id>", ...],
|
||||
|
||||
@@ -16,7 +16,7 @@ import type { Device } from "../stores/devices";
|
||||
import type { TitleEntry } from "../stores/titles";
|
||||
import type { User } from "../stores/session";
|
||||
import type { PublicConfig } from "../stores/config";
|
||||
import type { DeviceToken, ImportResult, Member, NoteShare, Repo } from "./repo";
|
||||
import type { DeviceToken, Directory, ImportResult, NoteShare, Repo } from "./repo";
|
||||
|
||||
const NEEDS_SERVER = "That's not available offline — connect a server to use it.";
|
||||
|
||||
@@ -95,9 +95,15 @@ export const local: Repo = {
|
||||
// Sharing is between accounts on a server, so these go to the linked one (#5175).
|
||||
// Unlinked, each rejects with the core's explanation, which the dialog shows.
|
||||
shares: {
|
||||
directory: () => invoke<Member[]>("shares_directory"),
|
||||
directory: () => invoke<Directory>("shares_directory"),
|
||||
list: (noteId) => invoke<NoteShare[]>("shares_list", { noteId }),
|
||||
share: (noteId, userId, permission) => invoke<NoteShare[]>("shares_share", { noteId, userId, permission }),
|
||||
share: (noteId, target, permission) =>
|
||||
invoke<NoteShare[]>("shares_share", {
|
||||
noteId,
|
||||
userId: "user_id" in target ? target.user_id : null,
|
||||
groupId: "group_id" in target ? target.group_id : null,
|
||||
permission,
|
||||
}),
|
||||
unshare: (noteId, shareId) => invoke<NoteShare[]>("shares_unshare", { noteId, shareId }),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -55,11 +55,29 @@ export interface Member {
|
||||
email: string;
|
||||
}
|
||||
|
||||
/** A group the admin made, as the directory shows it (#5177). */
|
||||
export interface ShareGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
member_count: number;
|
||||
}
|
||||
|
||||
/** Everyone a note can be shared with: the other people, and every group. */
|
||||
export interface Directory {
|
||||
members: Member[];
|
||||
groups: ShareGroup[];
|
||||
}
|
||||
|
||||
/** Who a share goes to: one person, or a group (whoever is in it at the time). */
|
||||
export type ShareTarget = { user_id: string } | { group_id: string };
|
||||
|
||||
export type SharePermission = "view" | "edit";
|
||||
|
||||
/** One share of a note: exactly one of `member` and `group` is set. */
|
||||
export interface NoteShare {
|
||||
id: string;
|
||||
member: Member;
|
||||
member: Member | null;
|
||||
group: ShareGroup | null;
|
||||
permission: SharePermission;
|
||||
created_at: string | null;
|
||||
}
|
||||
@@ -135,11 +153,11 @@ export interface NotesRepo {
|
||||
}
|
||||
|
||||
export interface SharesRepo {
|
||||
/** Everyone on the instance but you. */
|
||||
directory(): Promise<Member[]>;
|
||||
/** Everyone on the instance but you, and every group. */
|
||||
directory(): Promise<Directory>;
|
||||
list(noteId: string): Promise<NoteShare[]>;
|
||||
/** Share with one member, or change their permission. Answers the note's shares. */
|
||||
share(noteId: string, userId: string, permission: SharePermission): Promise<NoteShare[]>;
|
||||
/** Share with a person or a group, or change their permission. Answers the note's shares. */
|
||||
share(noteId: string, target: ShareTarget, permission: SharePermission): Promise<NoteShare[]>;
|
||||
unshare(noteId: string, shareId: string): Promise<NoteShare[]>;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,8 @@ import type { User } from "../stores/session";
|
||||
import type { PublicConfig } from "../stores/config";
|
||||
import type {
|
||||
DeviceToken,
|
||||
Directory,
|
||||
ImportResult,
|
||||
Member,
|
||||
NoteChanges,
|
||||
NoteShare,
|
||||
NoteCreateInput,
|
||||
@@ -120,10 +120,10 @@ export const rest: Repo = {
|
||||
},
|
||||
|
||||
shares: {
|
||||
directory: async () => (await api.get<{ members: Member[] }>("/api/users/directory")).members,
|
||||
directory: () => api.get<Directory>("/api/users/directory"),
|
||||
list: async (noteId) => (await api.get<{ shares: NoteShare[] }>(`/api/notes/${noteId}/shares`)).shares,
|
||||
share: async (noteId, userId, permission) =>
|
||||
(await api.post<{ shares: NoteShare[] }>(`/api/notes/${noteId}/shares`, { user_id: userId, permission })).shares,
|
||||
share: async (noteId, target, permission) =>
|
||||
(await api.post<{ shares: NoteShare[] }>(`/api/notes/${noteId}/shares`, { ...target, permission })).shares,
|
||||
unshare: async (noteId, shareId) =>
|
||||
(await api.del<{ shares: NoteShare[] }>(`/api/notes/${noteId}/shares/${shareId}`)).shares,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { api } from "../api/client";
|
||||
import { errorMessage } from "../api/errors";
|
||||
import { useUiStore } from "../stores/ui";
|
||||
import BaseButton from "./BaseButton.vue";
|
||||
import BaseInput from "./BaseInput.vue";
|
||||
import Icon from "./Icon.vue";
|
||||
|
||||
// Admin: groups of people a note can be shared with in one go (#5177). A group is
|
||||
// the instance's; anyone can share with it, and a note shared with it reaches whoever
|
||||
// is in it at the time, so adding or removing someone here changes what they see.
|
||||
|
||||
interface Person {
|
||||
id: string;
|
||||
display_name: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
interface Group {
|
||||
id: string;
|
||||
name: string;
|
||||
members: Person[];
|
||||
}
|
||||
|
||||
const ui = useUiStore();
|
||||
|
||||
const groups = ref<Group[]>([]);
|
||||
const accounts = ref<Person[]>([]);
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const name = ref("");
|
||||
const creating = ref(false);
|
||||
const busy = ref("");
|
||||
// Which group's "Add someone" picker holds which account id.
|
||||
const picks = ref<Record<string, string>>({});
|
||||
|
||||
const byName = (a: Group, b: Group) => a.name.localeCompare(b.name);
|
||||
|
||||
function outside(group: Group): Person[] {
|
||||
const inside = new Set(group.members.map((m) => m.id));
|
||||
return accounts.value.filter((a) => !inside.has(a.id));
|
||||
}
|
||||
|
||||
const empty = computed(() => !loading.value && !groups.value.length);
|
||||
|
||||
async function load() {
|
||||
error.value = "";
|
||||
try {
|
||||
const [g, a] = await Promise.all([
|
||||
api.get<{ groups: Group[] }>("/api/groups"),
|
||||
api.get<{ accounts: Person[] }>("/api/accounts"),
|
||||
]);
|
||||
groups.value = g.groups;
|
||||
accounts.value = a.accounts;
|
||||
} catch (e) {
|
||||
error.value = errorMessage(e, "Couldn't load groups.");
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function replace(updated: Group) {
|
||||
groups.value = groups.value.map((g) => (g.id === updated.id ? updated : g)).sort(byName);
|
||||
}
|
||||
|
||||
async function act(id: string, fn: () => Promise<void>, fallback: string) {
|
||||
busy.value = id;
|
||||
try {
|
||||
await fn();
|
||||
} catch (e) {
|
||||
ui.showToast(errorMessage(e, fallback));
|
||||
} finally {
|
||||
busy.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function create() {
|
||||
if (!name.value.trim()) return;
|
||||
creating.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
const made = await api.post<Group>("/api/groups", { name: name.value.trim() });
|
||||
groups.value = [...groups.value, made].sort(byName);
|
||||
name.value = "";
|
||||
} catch (e) {
|
||||
error.value = errorMessage(e, "Couldn't create the group.");
|
||||
} finally {
|
||||
creating.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function rename(group: Group) {
|
||||
const next = window.prompt("Rename the group", group.name)?.trim();
|
||||
if (!next || next === group.name) return;
|
||||
void act(
|
||||
group.id,
|
||||
async () => replace(await api.patch<Group>(`/api/groups/${group.id}`, { name: next })),
|
||||
"Couldn't rename it.",
|
||||
);
|
||||
}
|
||||
|
||||
function remove(group: Group) {
|
||||
if (!window.confirm(`Delete "${group.name}"? Notes shared with it stop being shared with its members.`)) return;
|
||||
void act(
|
||||
group.id,
|
||||
async () => {
|
||||
await api.del(`/api/groups/${group.id}`);
|
||||
groups.value = groups.value.filter((g) => g.id !== group.id);
|
||||
},
|
||||
"Couldn't delete it.",
|
||||
);
|
||||
}
|
||||
|
||||
function addMember(group: Group) {
|
||||
const userId = picks.value[group.id];
|
||||
if (!userId) return;
|
||||
void act(
|
||||
group.id,
|
||||
async () => {
|
||||
replace(await api.post<Group>(`/api/groups/${group.id}/members`, { user_id: userId }));
|
||||
picks.value[group.id] = "";
|
||||
},
|
||||
"Couldn't add them.",
|
||||
);
|
||||
}
|
||||
|
||||
function removeMember(group: Group, person: Person) {
|
||||
void act(
|
||||
group.id,
|
||||
async () => replace(await api.del<Group>(`/api/groups/${group.id}/members/${person.id}`)),
|
||||
"Couldn't remove them.",
|
||||
);
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="flex flex-col gap-5">
|
||||
<h2 class="text-xs font-semibold uppercase tracking-wide text-neutral-400">Groups</h2>
|
||||
|
||||
<form class="flex flex-wrap items-end gap-3" @submit.prevent="create">
|
||||
<BaseInput id="group-name" v-model="name" label="New group" placeholder="Family" class="min-w-48 flex-1" />
|
||||
<BaseButton type="submit" :loading="creating" :disabled="!name.trim()">Create group</BaseButton>
|
||||
</form>
|
||||
|
||||
<p v-if="error" class="text-sm text-red-600 dark:text-red-400">{{ error }}</p>
|
||||
|
||||
<div v-if="loading" class="py-6 text-center text-sm text-neutral-400">Loading…</div>
|
||||
<p v-else-if="empty" class="text-sm text-neutral-400">No groups yet.</p>
|
||||
<ul v-else class="flex flex-col gap-2">
|
||||
<li
|
||||
v-for="g in groups"
|
||||
:key="g.id"
|
||||
class="flex flex-col gap-3 rounded-xl border border-neutral-200 px-4 py-3 dark:border-neutral-800"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<p class="truncate text-sm font-medium text-neutral-800 dark:text-neutral-100">{{ g.name }}</p>
|
||||
<p class="text-xs text-neutral-400">
|
||||
{{ g.members.length }} {{ g.members.length === 1 ? "person" : "people" }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md border border-neutral-300 px-2.5 py-1 text-xs text-neutral-700 hover:bg-neutral-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand disabled:opacity-50 dark:border-neutral-700 dark:text-neutral-200 dark:hover:bg-neutral-800"
|
||||
:disabled="busy === g.id"
|
||||
@click="rename(g)"
|
||||
>
|
||||
Rename
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md border border-neutral-300 px-2.5 py-1 text-xs text-red-600 hover:bg-red-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand disabled:opacity-50 dark:border-neutral-700 dark:text-red-400 dark:hover:bg-red-950/40"
|
||||
:disabled="busy === g.id"
|
||||
@click="remove(g)"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul v-if="g.members.length" class="flex flex-wrap gap-1.5">
|
||||
<li
|
||||
v-for="m in g.members"
|
||||
:key="m.id"
|
||||
class="flex items-center gap-1 rounded-full bg-neutral-100 py-0.5 pl-2.5 pr-1 text-xs text-neutral-700 dark:bg-neutral-800 dark:text-neutral-200"
|
||||
:title="m.email"
|
||||
>
|
||||
{{ m.display_name || m.email }}
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full p-0.5 text-neutral-400 hover:text-red-500 disabled:opacity-50"
|
||||
:aria-label="`Remove ${m.display_name || m.email} from ${g.name}`"
|
||||
:disabled="busy === g.id"
|
||||
@click="removeMember(g, m)"
|
||||
>
|
||||
<Icon name="close" />
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<form v-if="outside(g).length" class="flex flex-wrap items-center gap-2" @submit.prevent="addMember(g)">
|
||||
<select
|
||||
v-model="picks[g.id]"
|
||||
class="min-w-0 flex-1 rounded-md border border-neutral-300 bg-white px-2 py-1.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-brand dark:border-neutral-700 dark:bg-neutral-800"
|
||||
:aria-label="`Add someone to ${g.name}`"
|
||||
:disabled="busy === g.id"
|
||||
>
|
||||
<option :value="undefined" disabled>Add someone…</option>
|
||||
<option v-for="a in outside(g)" :key="a.id" :value="a.id">{{ a.display_name }} ({{ a.email }})</option>
|
||||
</select>
|
||||
<button
|
||||
type="submit"
|
||||
class="rounded-md border border-neutral-300 px-2.5 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand disabled:opacity-50 dark:border-neutral-700 dark:text-neutral-200 dark:hover:bg-neutral-800"
|
||||
:disabled="busy === g.id || !picks[g.id]"
|
||||
>
|
||||
Add
|
||||
</button>
|
||||
</form>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,15 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { repo } from "../adapters";
|
||||
import type { Member, NoteShare, SharePermission } from "../adapters/repo";
|
||||
import type { Directory, NoteShare, SharePermission, ShareTarget } from "../adapters/repo";
|
||||
import { errorMessage } from "../api/errors";
|
||||
import { useNotesStore } from "../stores/notes";
|
||||
import BaseModal from "./BaseModal.vue";
|
||||
import Icon from "./Icon.vue";
|
||||
|
||||
// Share a note with other people on this instance (#5174). The owner picks a member
|
||||
// from the directory and says whether they may only read it or also change its text.
|
||||
// Only the owner opens this; the server refuses everyone else regardless.
|
||||
// Share a note with other people on this instance (#5174). The owner picks a member,
|
||||
// or a group the admin made (#5177), and says whether they may only read it or also
|
||||
// change its text. Only the owner opens this; the server refuses everyone else
|
||||
// regardless.
|
||||
|
||||
const props = defineProps<{ noteId: string }>();
|
||||
const emit = defineEmits<{ (e: "close"): void }>();
|
||||
@@ -20,26 +21,47 @@ const PERMISSIONS: { value: SharePermission; label: string }[] = [
|
||||
{ value: "edit", label: "Can edit" },
|
||||
];
|
||||
|
||||
const members = ref<Member[]>([]);
|
||||
const directory = ref<Directory>({ members: [], groups: [] });
|
||||
const shares = ref<NoteShare[]>([]);
|
||||
const loading = ref(true);
|
||||
const loadError = ref("");
|
||||
const error = ref("");
|
||||
const busy = ref(false);
|
||||
// "u:<id>" for a person, "g:<id>" for a group: one picker lists both.
|
||||
const pick = ref("");
|
||||
const permission = ref<SharePermission>("view");
|
||||
|
||||
/** The people it isn't shared with yet. */
|
||||
const available = computed(() => {
|
||||
const taken = new Set(shares.value.map((s) => s.member.id));
|
||||
return members.value.filter((m) => !taken.has(m.id));
|
||||
/** The people and groups it isn't shared with yet. */
|
||||
const availablePeople = computed(() => {
|
||||
const taken = new Set(shares.value.map((s) => s.member?.id));
|
||||
return directory.value.members.filter((m) => !taken.has(m.id));
|
||||
});
|
||||
const availableGroups = computed(() => {
|
||||
const taken = new Set(shares.value.map((s) => s.group?.id));
|
||||
return directory.value.groups.filter((g) => !taken.has(g.id));
|
||||
});
|
||||
const anyone = computed(() => directory.value.members.length + directory.value.groups.length > 0);
|
||||
const anyoneLeft = computed(() => availablePeople.value.length + availableGroups.value.length > 0);
|
||||
|
||||
function targetOf(share: NoteShare): ShareTarget {
|
||||
return share.group ? { group_id: share.group.id } : { user_id: share.member?.id ?? "" };
|
||||
}
|
||||
|
||||
function nameOf(share: NoteShare): string {
|
||||
return share.group?.name ?? share.member?.display_name ?? "";
|
||||
}
|
||||
|
||||
function detailOf(share: NoteShare): string {
|
||||
if (!share.group) return share.member?.email ?? "";
|
||||
const n = share.group.member_count;
|
||||
return `Group · ${n} ${n === 1 ? "person" : "people"}`;
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
loadError.value = "";
|
||||
try {
|
||||
[members.value, shares.value] = await Promise.all([repo.shares.directory(), repo.shares.list(props.noteId)]);
|
||||
[directory.value, shares.value] = await Promise.all([repo.shares.directory(), repo.shares.list(props.noteId)]);
|
||||
} catch (e) {
|
||||
loadError.value = errorMessage(e, "Couldn't load who this is shared with.");
|
||||
} finally {
|
||||
@@ -62,13 +84,14 @@ async function run(fn: () => Promise<NoteShare[]>, fallback: string) {
|
||||
|
||||
async function add() {
|
||||
if (!pick.value) return;
|
||||
const userId = pick.value;
|
||||
await run(() => repo.shares.share(props.noteId, userId, permission.value), "Couldn't share the note.");
|
||||
const id = pick.value.slice(2);
|
||||
const target: ShareTarget = pick.value.startsWith("g:") ? { group_id: id } : { user_id: id };
|
||||
await run(() => repo.shares.share(props.noteId, target, permission.value), "Couldn't share the note.");
|
||||
if (!error.value) pick.value = "";
|
||||
}
|
||||
|
||||
function change(share: NoteShare, next: SharePermission) {
|
||||
void run(() => repo.shares.share(props.noteId, share.member.id, next), "Couldn't change that.");
|
||||
void run(() => repo.shares.share(props.noteId, targetOf(share), next), "Couldn't change that.");
|
||||
}
|
||||
|
||||
function remove(share: NoteShare) {
|
||||
@@ -103,14 +126,23 @@ onMounted(load);
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<p v-if="!members.length" class="text-sm text-neutral-500 dark:text-neutral-400">
|
||||
<p v-if="!anyone" class="text-sm text-neutral-500 dark:text-neutral-400">
|
||||
No one else has an account here yet. An admin can invite people from Settings.
|
||||
</p>
|
||||
|
||||
<form v-else-if="available.length" class="flex flex-wrap items-center gap-2" @submit.prevent="add">
|
||||
<select v-model="pick" :class="[selectClass, 'min-w-0 flex-1']" aria-label="Person" :disabled="busy">
|
||||
<form v-else-if="anyoneLeft" class="flex flex-wrap items-center gap-2" @submit.prevent="add">
|
||||
<select v-model="pick" :class="[selectClass, 'min-w-0 flex-1']" aria-label="Person or group" :disabled="busy">
|
||||
<option value="" disabled>Choose someone…</option>
|
||||
<option v-for="m in available" :key="m.id" :value="m.id">{{ m.display_name }} ({{ m.email }})</option>
|
||||
<optgroup v-if="availablePeople.length" label="People">
|
||||
<option v-for="m in availablePeople" :key="m.id" :value="`u:${m.id}`">
|
||||
{{ m.display_name }} ({{ m.email }})
|
||||
</option>
|
||||
</optgroup>
|
||||
<optgroup v-if="availableGroups.length" label="Groups">
|
||||
<option v-for="g in availableGroups" :key="g.id" :value="`g:${g.id}`">
|
||||
{{ g.name }} ({{ g.member_count }})
|
||||
</option>
|
||||
</optgroup>
|
||||
</select>
|
||||
<select v-model="permission" :class="selectClass" aria-label="Permission" :disabled="busy">
|
||||
<option v-for="p in PERMISSIONS" :key="p.value" :value="p.value">{{ p.label }}</option>
|
||||
@@ -132,13 +164,13 @@ onMounted(load);
|
||||
<ul v-else class="flex flex-col gap-1">
|
||||
<li v-for="s in shares" :key="s.id" class="flex items-center gap-2 rounded-lg px-1 py-1">
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="truncate text-sm text-neutral-800 dark:text-neutral-100">{{ s.member.display_name }}</p>
|
||||
<p class="truncate text-xs text-neutral-400">{{ s.member.email }}</p>
|
||||
<p class="truncate text-sm text-neutral-800 dark:text-neutral-100">{{ nameOf(s) }}</p>
|
||||
<p class="truncate text-xs text-neutral-400">{{ detailOf(s) }}</p>
|
||||
</div>
|
||||
<select
|
||||
:value="s.permission"
|
||||
:class="selectClass"
|
||||
:aria-label="`Permission for ${s.member.display_name}`"
|
||||
:aria-label="`Permission for ${nameOf(s)}`"
|
||||
:disabled="busy"
|
||||
@change="change(s, ($event.target as HTMLSelectElement).value as SharePermission)"
|
||||
>
|
||||
@@ -147,8 +179,8 @@ onMounted(load);
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
:title="`Stop sharing with ${s.member.display_name}`"
|
||||
:aria-label="`Stop sharing with ${s.member.display_name}`"
|
||||
:title="`Stop sharing with ${nameOf(s)}`"
|
||||
:aria-label="`Stop sharing with ${nameOf(s)}`"
|
||||
:disabled="busy"
|
||||
@click="remove(s)"
|
||||
>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useConfigStore } from "../stores/config";
|
||||
import BaseButton from "../components/BaseButton.vue";
|
||||
import InviteList from "../components/InviteList.vue";
|
||||
import AccountList from "../components/AccountList.vue";
|
||||
import GroupList from "../components/GroupList.vue";
|
||||
import { errorMessage } from "../api/errors";
|
||||
import { useUiStore } from "../stores/ui";
|
||||
|
||||
@@ -227,9 +228,10 @@ onMounted(load);
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<!-- Outside the settings form: each invite and account action saves on its own,
|
||||
<!-- Outside the settings form: each invite, account and group action saves on its own,
|
||||
and the form's Save button has nothing to do with them. -->
|
||||
<InviteList v-if="items.length" class="mt-10" />
|
||||
<AccountList v-if="items.length" class="mt-10" />
|
||||
<GroupList v-if="items.length" class="mt-10" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -14,6 +14,7 @@ from quart.sessions import SecureCookieSessionInterface
|
||||
from .accounts_api import bp as accounts_bp
|
||||
from .auth import bp as auth_bp
|
||||
from .client_dist import advertisement as client_advertisement, bp as client_bp
|
||||
from .groups_api import bp as groups_bp
|
||||
from .config import Config
|
||||
from .db import session_scope
|
||||
from .invites_api import bp as invites_bp
|
||||
@@ -96,6 +97,7 @@ def create_app() -> Quart:
|
||||
app.register_blueprint(settings_bp)
|
||||
app.register_blueprint(invites_bp)
|
||||
app.register_blueprint(accounts_bp)
|
||||
app.register_blueprint(groups_bp)
|
||||
app.register_blueprint(shares_bp)
|
||||
app.register_blueprint(sync_bp)
|
||||
app.register_blueprint(saved_filters_bp)
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Admin routes over groups: named sets of people a note can be shared with (#5177).
|
||||
|
||||
A group is the instance's, not anyone's: the admin makes it and says who is in it,
|
||||
and every member of the instance can share a note with it. Sharing with a group
|
||||
reaches whoever is in it at the time, so adding or removing someone is what changes
|
||||
their access, and `share_sync` tells their devices.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from quart import Blueprint, jsonify, request
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
|
||||
from .auth import require_admin
|
||||
from .db import session_scope
|
||||
from .models.group import Group, GroupMember
|
||||
from .models.user import User
|
||||
from .responses import json_error, not_found, parse_uuid
|
||||
from .share_sync import bump_note, group_notes, joined_group, left_group, recipients, revoke
|
||||
|
||||
bp = Blueprint("groups", __name__, url_prefix="/api/groups")
|
||||
|
||||
NAME_CAP = 80
|
||||
|
||||
|
||||
def _name(data: dict) -> str | None:
|
||||
name = (data.get("name") or "").strip() if isinstance(data.get("name"), str) else ""
|
||||
return name[:NAME_CAP] or None
|
||||
|
||||
|
||||
async def _name_taken(db, name: str, but: uuid.UUID | None = None) -> bool:
|
||||
stmt = select(Group.id).where(func.lower(Group.name) == name.lower())
|
||||
if but is not None:
|
||||
stmt = stmt.where(Group.id != but)
|
||||
return await db.scalar(stmt) is not None
|
||||
|
||||
|
||||
async def _serialize_groups(db, groups: list[Group]) -> list[dict]:
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(GroupMember.group_id, User)
|
||||
.join(User, User.id == GroupMember.user_id)
|
||||
.where(GroupMember.group_id.in_([gr.id for gr in groups]))
|
||||
.order_by(User.display_name, User.email)
|
||||
)
|
||||
).all() if groups else []
|
||||
members: dict = {}
|
||||
for group_id, user in rows:
|
||||
members.setdefault(group_id, []).append(
|
||||
{"id": str(user.id), "display_name": user.display_name, "email": user.email}
|
||||
)
|
||||
return [{"id": str(gr.id), "name": gr.name, "members": members.get(gr.id, [])} for gr in groups]
|
||||
|
||||
|
||||
async def _answer(db, group: Group, status: int = 200):
|
||||
return jsonify((await _serialize_groups(db, [group]))[0]), status
|
||||
|
||||
|
||||
@bp.get("")
|
||||
@require_admin
|
||||
async def list_groups():
|
||||
async with session_scope() as db:
|
||||
groups = (await db.scalars(select(Group).order_by(func.lower(Group.name)))).all()
|
||||
return jsonify({"groups": await _serialize_groups(db, list(groups))})
|
||||
|
||||
|
||||
@bp.post("")
|
||||
@require_admin
|
||||
async def create_group():
|
||||
name = _name(await request.get_json(silent=True) or {})
|
||||
if name is None:
|
||||
return json_error("give the group a name", 400)
|
||||
async with session_scope() as db:
|
||||
if await _name_taken(db, name):
|
||||
return json_error("there is already a group with that name", 409)
|
||||
group = Group(name=name)
|
||||
db.add(group)
|
||||
await db.commit()
|
||||
return await _answer(db, group, 201)
|
||||
|
||||
|
||||
@bp.patch("/<group_id>")
|
||||
@require_admin
|
||||
async def rename_group(group_id: str):
|
||||
name = _name(await request.get_json(silent=True) or {})
|
||||
if name is None:
|
||||
return json_error("give the group a name", 400)
|
||||
gid = parse_uuid(group_id)
|
||||
async with session_scope() as db:
|
||||
group = await db.get(Group, gid) if gid else None
|
||||
if group is None:
|
||||
return not_found()
|
||||
if await _name_taken(db, name, but=group.id):
|
||||
return json_error("there is already a group with that name", 409)
|
||||
group.name = name
|
||||
await db.commit()
|
||||
return await _answer(db, group)
|
||||
|
||||
|
||||
@bp.delete("/<group_id>")
|
||||
@require_admin
|
||||
async def delete_group(group_id: str):
|
||||
"""Delete the group and every share made to it. Whoever could see a note only
|
||||
through it loses the note, and their devices are told."""
|
||||
gid = parse_uuid(group_id)
|
||||
async with session_scope() as db:
|
||||
group = await db.get(Group, gid) if gid else None
|
||||
if group is None:
|
||||
return not_found()
|
||||
note_ids = await group_notes(db, group.id)
|
||||
before = {nid: await recipients(db, nid) for nid in note_ids}
|
||||
await db.delete(group) # members and shares go with it (ON DELETE CASCADE)
|
||||
await db.flush()
|
||||
for nid in note_ids:
|
||||
await revoke(db, nid, before[nid] - await recipients(db, nid))
|
||||
# The owner's devices learn whether the note is still shared at all.
|
||||
await bump_note(db, nid)
|
||||
await db.commit()
|
||||
return jsonify({"ok": True})
|
||||
|
||||
|
||||
@bp.post("/<group_id>/members")
|
||||
@require_admin
|
||||
async def add_member(group_id: str):
|
||||
data = await request.get_json(silent=True) or {}
|
||||
gid = parse_uuid(group_id)
|
||||
uid = parse_uuid(str(data.get("user_id") or ""))
|
||||
async with session_scope() as db:
|
||||
group = await db.get(Group, gid) if gid else None
|
||||
if group is None:
|
||||
return not_found()
|
||||
if uid is None or await db.get(User, uid) is None:
|
||||
return json_error("that person isn't on this instance", 400)
|
||||
added = await db.execute(
|
||||
insert(GroupMember)
|
||||
.values(id=uuid.uuid4(), group_id=group.id, user_id=uid)
|
||||
.on_conflict_do_nothing(constraint="uq_group_members_group_user")
|
||||
)
|
||||
if added.rowcount:
|
||||
await joined_group(db, group.id, uid)
|
||||
await db.commit()
|
||||
return await _answer(db, group, 201)
|
||||
|
||||
|
||||
@bp.delete("/<group_id>/members/<user_id>")
|
||||
@require_admin
|
||||
async def remove_member(group_id: str, user_id: str):
|
||||
gid = parse_uuid(group_id)
|
||||
uid = parse_uuid(user_id)
|
||||
async with session_scope() as db:
|
||||
group = await db.get(Group, gid) if gid else None
|
||||
if group is None or uid is None:
|
||||
return not_found()
|
||||
membership = await db.scalar(
|
||||
select(GroupMember).where(GroupMember.group_id == group.id, GroupMember.user_id == uid)
|
||||
)
|
||||
if membership is None:
|
||||
return not_found()
|
||||
note_ids = await group_notes(db, group.id)
|
||||
await db.delete(membership)
|
||||
await db.flush()
|
||||
await left_group(db, group.id, uid, note_ids)
|
||||
await db.commit()
|
||||
return await _answer(db, group)
|
||||
@@ -16,6 +16,7 @@ from sqlalchemy import select, text
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
|
||||
from .models.group import GroupMember
|
||||
from .models.note import Note
|
||||
from .models.share import Share
|
||||
from .models.share_revocation import ShareRevocation
|
||||
|
||||
@@ -31,7 +32,8 @@ async def bump_note(db, note_id: uuid.UUID) -> None:
|
||||
|
||||
|
||||
async def recipients(db, note_id: uuid.UUID) -> set[uuid.UUID]:
|
||||
"""Everyone the note is shared with, directly or through a group."""
|
||||
"""Everyone the note is shared with, directly or through a group. Never its owner,
|
||||
who may be in a group it is shared with and holds it as their own regardless."""
|
||||
direct = await db.scalars(
|
||||
select(Share.shared_with_user_id).where(
|
||||
Share.resource_type == "note", Share.resource_id == note_id, Share.shared_with_user_id.is_not(None)
|
||||
@@ -42,7 +44,8 @@ async def recipients(db, note_id: uuid.UUID) -> set[uuid.UUID]:
|
||||
.join(Share, Share.shared_with_group_id == GroupMember.group_id)
|
||||
.where(Share.resource_type == "note", Share.resource_id == note_id)
|
||||
)
|
||||
return set(direct.all()) | set(grouped.all())
|
||||
owner = await db.scalar(select(Note.owner_id).where(Note.id == note_id))
|
||||
return (set(direct.all()) | set(grouped.all())) - {owner}
|
||||
|
||||
|
||||
async def revoke(db, note_id: uuid.UUID, user_ids) -> None:
|
||||
@@ -67,3 +70,34 @@ async def granted(db, note_id: uuid.UUID, user_id: uuid.UUID) -> None:
|
||||
sa_delete(ShareRevocation).where(ShareRevocation.note_id == note_id, ShareRevocation.user_id == user_id)
|
||||
)
|
||||
await bump_note(db, note_id)
|
||||
|
||||
|
||||
# --- Group membership (#5177) ------------------------------------------------
|
||||
#
|
||||
# A note shared with a group reaches whoever is in it NOW, so joining or leaving
|
||||
# changes what that one person can see without any share changing. Their devices
|
||||
# hear it the same way as for a direct share: a grant moves the note past their
|
||||
# cursor, and losing it leaves a revocation.
|
||||
|
||||
|
||||
async def group_notes(db, group_id: uuid.UUID) -> list[uuid.UUID]:
|
||||
"""The notes shared with this group."""
|
||||
rows = await db.scalars(
|
||||
select(Share.resource_id).where(Share.resource_type == "note", Share.shared_with_group_id == group_id)
|
||||
)
|
||||
return list(rows.all())
|
||||
|
||||
|
||||
async def joined_group(db, group_id: uuid.UUID, user_id: uuid.UUID) -> None:
|
||||
"""`user_id` was added to the group: each of its notes reaches their devices."""
|
||||
for note_id in await group_notes(db, group_id):
|
||||
await granted(db, note_id, user_id)
|
||||
|
||||
|
||||
async def left_group(db, group_id: uuid.UUID, user_id: uuid.UUID, note_ids: list[uuid.UUID]) -> None:
|
||||
"""`user_id` is no longer in the group (the membership row is gone and flushed):
|
||||
each of `note_ids`, the group's notes from before, leaves their devices unless a
|
||||
direct share or another group still reaches them."""
|
||||
for note_id in note_ids:
|
||||
if user_id not in await recipients(db, note_id):
|
||||
await revoke(db, note_id, [user_id])
|
||||
|
||||
+69
-29
@@ -2,7 +2,8 @@
|
||||
|
||||
`acl.visible_to_user` has gated every read since M0, but nothing wrote a share. This
|
||||
is the writing half: the note's owner lists, grants and revokes access, and anyone
|
||||
signed in can read the member directory the Share dialog picks people from.
|
||||
signed in can read the member directory the Share dialog picks people from. A share
|
||||
goes to one person or to a group the admin made (#5177).
|
||||
|
||||
What a share grants is in `acl` (view, or edit: the body and checklist) and is
|
||||
enforced by the note routes (`notes.helpers._get_owned` / `_get_editable`).
|
||||
@@ -12,13 +13,14 @@ from __future__ import annotations
|
||||
import uuid
|
||||
|
||||
from quart import Blueprint, g, jsonify, request
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
|
||||
from .acl import PERMISSIONS
|
||||
from .auth import login_required
|
||||
from .common import iso
|
||||
from .db import session_scope
|
||||
from .models.group import Group, GroupMember
|
||||
from .models.share import Share
|
||||
from .models.user import User
|
||||
from .notes.helpers import _get_owned
|
||||
@@ -32,32 +34,61 @@ def _member(user: User) -> dict:
|
||||
return {"id": str(user.id), "display_name": user.display_name, "email": user.email}
|
||||
|
||||
|
||||
def _group(group: Group, counts: dict) -> dict:
|
||||
return {"id": str(group.id), "name": group.name, "member_count": counts.get(group.id, 0)}
|
||||
|
||||
|
||||
async def _member_counts(db, group_ids: list) -> dict:
|
||||
if not group_ids:
|
||||
return {}
|
||||
rows = await db.execute(
|
||||
select(GroupMember.group_id, func.count())
|
||||
.where(GroupMember.group_id.in_(group_ids))
|
||||
.group_by(GroupMember.group_id)
|
||||
)
|
||||
return dict(rows.all())
|
||||
|
||||
|
||||
@bp.get("/users/directory")
|
||||
@login_required
|
||||
async def directory():
|
||||
"""The people on this instance a note can be shared with: everyone but you.
|
||||
"""Who on this instance a note can be shared with: everyone but you, and every
|
||||
group the admin has made (#5177).
|
||||
|
||||
Signed-in only. Each entry is a name and an email and nothing more, which is what
|
||||
choosing someone takes and all a fellow member needs to know."""
|
||||
Signed-in only. Each person is a name and an email and nothing more, which is
|
||||
what choosing someone takes and all a fellow member needs to know; a group is its
|
||||
name and how many people are in it."""
|
||||
async with session_scope() as db:
|
||||
users = (
|
||||
await db.scalars(select(User).where(User.id != g.user_id).order_by(User.display_name, User.email))
|
||||
).all()
|
||||
return jsonify({"members": [_member(u) for u in users]})
|
||||
groups = (await db.scalars(select(Group).order_by(func.lower(Group.name)))).all()
|
||||
counts = await _member_counts(db, [gr.id for gr in groups])
|
||||
return jsonify({"members": [_member(u) for u in users], "groups": [_group(gr, counts) for gr in groups]})
|
||||
|
||||
|
||||
async def _shares_of(db, note_id: uuid.UUID) -> list[dict]:
|
||||
"""Each share of the note, to a person (`member`) or to a group (`group`); the
|
||||
other of the two is null."""
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(Share, User)
|
||||
.join(User, User.id == Share.shared_with_user_id)
|
||||
select(Share, User, Group)
|
||||
.outerjoin(User, User.id == Share.shared_with_user_id)
|
||||
.outerjoin(Group, Group.id == Share.shared_with_group_id)
|
||||
.where(Share.resource_type == "note", Share.resource_id == note_id)
|
||||
.order_by(Share.created_at)
|
||||
)
|
||||
).all()
|
||||
counts = await _member_counts(db, [gr.id for _, _, gr in rows if gr is not None])
|
||||
return [
|
||||
{"id": str(share.id), "member": _member(user), "permission": share.permission, "created_at": iso(share.created_at)}
|
||||
for share, user in rows
|
||||
{
|
||||
"id": str(share.id),
|
||||
"member": _member(user) if user is not None else None,
|
||||
"group": _group(group, counts) if group is not None else None,
|
||||
"permission": share.permission,
|
||||
"created_at": iso(share.created_at),
|
||||
}
|
||||
for share, user, group in rows
|
||||
]
|
||||
|
||||
|
||||
@@ -74,39 +105,48 @@ async def list_shares(note_id: str):
|
||||
@bp.post("/notes/<note_id>/shares")
|
||||
@login_required
|
||||
async def share_note(note_id: str):
|
||||
"""Share the note with one member at `view` or `edit`. Sharing again with the same
|
||||
person changes their permission rather than adding a second grant."""
|
||||
"""Share the note at `view` or `edit` with one member (`user_id`) or with a group
|
||||
(`group_id`). Sharing again with the same person or group changes the permission
|
||||
rather than adding a second grant."""
|
||||
data = await request.get_json(silent=True) or {}
|
||||
permission = data.get("permission") or "view"
|
||||
if permission not in PERMISSIONS:
|
||||
return json_error("permission must be view or edit", 400)
|
||||
target = parse_uuid(str(data.get("user_id") or ""))
|
||||
if target is None:
|
||||
return json_error("choose someone to share with", 400)
|
||||
user_id = parse_uuid(str(data.get("user_id") or ""))
|
||||
group_id = parse_uuid(str(data.get("group_id") or ""))
|
||||
if (user_id is None) == (group_id is None):
|
||||
return json_error("choose someone or a group to share with", 400)
|
||||
async with session_scope() as db:
|
||||
note = await _get_owned(db, note_id)
|
||||
if note is None:
|
||||
return not_found()
|
||||
if target == g.user_id:
|
||||
return json_error("this note is already yours", 400)
|
||||
if await db.get(User, target) is None:
|
||||
return json_error("that person isn't on this instance", 400)
|
||||
if user_id is not None:
|
||||
if user_id == g.user_id:
|
||||
return json_error("this note is already yours", 400)
|
||||
if await db.get(User, user_id) is None:
|
||||
return json_error("that person isn't on this instance", 400)
|
||||
target_column, target = Share.shared_with_user_id, {"shared_with_user_id": user_id}
|
||||
reached = {user_id}
|
||||
else:
|
||||
if await db.get(Group, group_id) is None:
|
||||
return json_error("that group isn't on this instance", 400)
|
||||
target_column, target = Share.shared_with_group_id, {"shared_with_group_id": group_id}
|
||||
reached = set(
|
||||
(await db.scalars(select(GroupMember.user_id).where(GroupMember.group_id == group_id))).all()
|
||||
)
|
||||
await db.execute(
|
||||
insert(Share)
|
||||
.values(
|
||||
id=uuid.uuid4(),
|
||||
resource_type="note",
|
||||
resource_id=note.id,
|
||||
shared_with_user_id=target,
|
||||
permission=permission,
|
||||
)
|
||||
.values(id=uuid.uuid4(), resource_type="note", resource_id=note.id, permission=permission, **target)
|
||||
.on_conflict_do_update(
|
||||
index_elements=[Share.resource_type, Share.resource_id, Share.shared_with_user_id],
|
||||
index_where=Share.shared_with_user_id.is_not(None),
|
||||
index_elements=[Share.resource_type, Share.resource_id, target_column],
|
||||
index_where=target_column.is_not(None),
|
||||
set_={"permission": permission},
|
||||
)
|
||||
)
|
||||
await granted(db, note.id, target)
|
||||
for uid in reached - {g.user_id}:
|
||||
await granted(db, note.id, uid)
|
||||
# The owner's devices learn the note is shared, even with an empty group.
|
||||
await bump_note(db, note.id)
|
||||
await db.commit()
|
||||
return jsonify({"shares": await _shares_of(db, note.id)}), 201
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ pytestmark = pytest.mark.integration
|
||||
|
||||
# Every table the tests touch, child-first so FKs never block the truncate.
|
||||
# RESTART IDENTITY + CASCADE keeps this honest if a table gains children later.
|
||||
_TABLES = "notes, note_revisions, note_labels, note_link_previews, labels, shares, share_revocations, note_user_state, invites, password_resets, users"
|
||||
_TABLES = "notes, note_revisions, note_labels, note_link_previews, labels, shares, share_revocations, note_user_state, group_members, groups, invites, password_resets, users"
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
@@ -1511,6 +1511,86 @@ async def test_deleting_a_shared_note_reaches_the_recipients_devices(app_client,
|
||||
assert _feed_note(gone, nid) is None
|
||||
|
||||
|
||||
# --- Groups (#5177) ------------------------------------------------------------
|
||||
|
||||
|
||||
async def _group(app_client, name: str, *member_ids: str) -> str:
|
||||
made = await app_client.post("/api/groups", json={"name": name})
|
||||
assert made.status_code == 201, await made.get_data(as_text=True)
|
||||
gid = (await made.get_json())["id"]
|
||||
for uid in member_ids:
|
||||
added = await app_client.post(f"/api/groups/{gid}/members", json={"user_id": uid})
|
||||
assert added.status_code == 201, await added.get_data(as_text=True)
|
||||
return gid
|
||||
|
||||
|
||||
async def test_only_an_admin_manages_groups_and_everyone_can_share_with_one(app_client, db):
|
||||
recipient, _, people = await _three_people(app_client)
|
||||
assert (await recipient.get("/api/groups")).status_code == 403
|
||||
assert (await recipient.post("/api/groups", json={"name": "Mine"})).status_code == 403
|
||||
|
||||
gid = await _group(app_client, "Family", people["recipient"])
|
||||
assert (await app_client.post("/api/groups", json={"name": "family"})).status_code == 409
|
||||
assert (await app_client.post("/api/groups", json={"name": " "})).status_code == 400
|
||||
listed = (await (await app_client.get("/api/groups")).get_json())["groups"]
|
||||
assert [(gr["name"], [m["email"] for m in gr["members"]]) for gr in listed] == [
|
||||
("Family", ["recipient@example.test"])
|
||||
]
|
||||
renamed = await app_client.patch(f"/api/groups/{gid}", json={"name": "Household"})
|
||||
assert (await renamed.get_json())["name"] == "Household"
|
||||
|
||||
# Anyone signed in sees each group to share with, and how many are in it.
|
||||
directory = await (await recipient.get("/api/users/directory")).get_json()
|
||||
assert directory["groups"] == [{"id": gid, "name": "Household", "member_count": 1}]
|
||||
|
||||
|
||||
async def test_a_note_shared_with_a_group_follows_who_is_in_it(app_client, db):
|
||||
recipient, stranger, people = await _three_people(app_client)
|
||||
gid = await _group(app_client, "Family", people["recipient"])
|
||||
nid = await _owners_note(app_client)
|
||||
start = (await _feed(stranger))["cursor"]
|
||||
|
||||
shared = await app_client.post(f"/api/notes/{nid}/shares", json={"group_id": gid, "permission": "edit"})
|
||||
assert shared.status_code == 201, await shared.get_data(as_text=True)
|
||||
[entry] = (await shared.get_json())["shares"]
|
||||
assert (entry["member"], entry["group"]["name"], entry["group"]["member_count"]) == (None, "Family", 1)
|
||||
assert (await (await recipient.get(f"/api/notes/{nid}")).get_json())["permission"] == "edit"
|
||||
assert (await stranger.get(f"/api/notes/{nid}")).status_code == 404
|
||||
both = await app_client.post(f"/api/notes/{nid}/shares", json={"group_id": gid, "user_id": people["stranger"]})
|
||||
assert both.status_code == 400
|
||||
|
||||
# Joining reaches the new member's devices; leaving takes it back.
|
||||
await app_client.post(f"/api/groups/{gid}/members", json={"user_id": people["stranger"]})
|
||||
joined = await _feed(stranger, start)
|
||||
assert _feed_note(joined, nid)["permission"] == "edit"
|
||||
left = await app_client.delete(f"/api/groups/{gid}/members/{people['stranger']}")
|
||||
assert left.status_code == 200
|
||||
gone = await _feed(stranger, joined["cursor"])
|
||||
assert gone["revoked"] == [nid]
|
||||
assert (await stranger.get(f"/api/notes/{nid}")).status_code == 404
|
||||
|
||||
# Someone also shared with directly keeps the note when they leave the group.
|
||||
await _share(app_client, nid, people["recipient"], "view")
|
||||
before = (await _feed(recipient))["cursor"]
|
||||
await app_client.delete(f"/api/groups/{gid}/members/{people['recipient']}")
|
||||
assert (await _feed(recipient, before))["revoked"] == []
|
||||
assert (await (await recipient.get(f"/api/notes/{nid}")).get_json())["permission"] == "view"
|
||||
|
||||
|
||||
async def test_deleting_a_group_ends_every_share_made_to_it(app_client, db):
|
||||
recipient, _, people = await _three_people(app_client)
|
||||
gid = await _group(app_client, "Family", people["recipient"])
|
||||
nid = await _owners_note(app_client)
|
||||
await app_client.post(f"/api/notes/{nid}/shares", json={"group_id": gid})
|
||||
seen = await _feed(recipient)
|
||||
assert _feed_note(seen, nid) is not None
|
||||
|
||||
assert (await app_client.delete(f"/api/groups/{gid}")).status_code == 200
|
||||
assert (await _feed(recipient, seen["cursor"]))["revoked"] == [nid]
|
||||
assert (await recipient.get(f"/api/notes/{nid}")).status_code == 404
|
||||
assert (await (await app_client.get(f"/api/notes/{nid}")).get_json())["shared"] is False
|
||||
|
||||
|
||||
# --- Password reset by email (#5266) ------------------------------------------
|
||||
#
|
||||
# The SMTP hand-off is replaced by a list; everything up to it is real.
|
||||
|
||||
Reference in New Issue
Block a user