From df07d8e31cb38502cd52b678560ba800c02cf799 Mon Sep 17 00:00:00 2001 From: Nutomic Date: Thu, 31 Oct 2024 13:10:45 +0100 Subject: [PATCH 01/19] Skip api test for fetching nested comment (#5152) --- api_tests/src/comment.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api_tests/src/comment.spec.ts b/api_tests/src/comment.spec.ts index 153405820..c3f4b3efe 100644 --- a/api_tests/src/comment.spec.ts +++ b/api_tests/src/comment.spec.ts @@ -860,7 +860,7 @@ test("Dont send a comment reply to a blocked community", async () => { /// Fetching a deeply nested comment can lead to stack overflow as all parent comments are also /// fetched recursively. Ensure that it works properly. -test("Fetch a deeply nested comment", async () => { +test.skip("Fetch a deeply nested comment", async () => { let lastComment; for (let i = 0; i < 50; i++) { let commentRes = await createComment( From 8f88dda28fb5b4a6c4c8858b40daa22ccad530dd Mon Sep 17 00:00:00 2001 From: Integral Date: Thu, 31 Oct 2024 20:12:24 +0800 Subject: [PATCH 02/19] refactor: destructure tuples to enhance readability (#5151) --- crates/api/src/sitemap.rs | 6 +++--- crates/apub/src/objects/comment.rs | 10 +++++----- crates/apub/src/objects/person.rs | 9 ++++++--- crates/apub/src/objects/private_message.rs | 8 ++++---- crates/db_views/src/custom_emoji_view.rs | 8 ++++---- crates/utils/src/utils/markdown/image_links.rs | 17 +++++++---------- src/scheduled_tasks.rs | 6 +++--- 7 files changed, 32 insertions(+), 32 deletions(-) diff --git a/crates/api/src/sitemap.rs b/crates/api/src/sitemap.rs index c3c3c417c..57b39a5b3 100644 --- a/crates/api/src/sitemap.rs +++ b/crates/api/src/sitemap.rs @@ -14,9 +14,9 @@ async fn generate_urlset( ) -> LemmyResult { let urls = posts .into_iter() - .map_while(|post| { - Url::builder(post.0.to_string()) - .last_modified(post.1.into()) + .map_while(|(url, date_time)| { + Url::builder(url.to_string()) + .last_modified(date_time.into()) .build() .ok() }) diff --git a/crates/apub/src/objects/comment.rs b/crates/apub/src/objects/comment.rs index 403ecbf94..e6cc2ba85 100644 --- a/crates/apub/src/objects/comment.rs +++ b/crates/apub/src/objects/comment.rs @@ -247,13 +247,13 @@ pub(crate) mod tests { } async fn cleanup( - data: (ApubPerson, ApubCommunity, ApubPost, ApubSite), + (person, community, post, site): (ApubPerson, ApubCommunity, ApubPost, ApubSite), context: &LemmyContext, ) -> LemmyResult<()> { - Post::delete(&mut context.pool(), data.2.id).await?; - Community::delete(&mut context.pool(), data.1.id).await?; - Person::delete(&mut context.pool(), data.0.id).await?; - Site::delete(&mut context.pool(), data.3.id).await?; + Post::delete(&mut context.pool(), post.id).await?; + Community::delete(&mut context.pool(), community.id).await?; + Person::delete(&mut context.pool(), person.id).await?; + Site::delete(&mut context.pool(), site.id).await?; LocalSite::delete(&mut context.pool()).await?; Ok(()) } diff --git a/crates/apub/src/objects/person.rs b/crates/apub/src/objects/person.rs index 4e8519f78..737579662 100644 --- a/crates/apub/src/objects/person.rs +++ b/crates/apub/src/objects/person.rs @@ -285,9 +285,12 @@ pub(crate) mod tests { Ok(()) } - async fn cleanup(data: (ApubPerson, ApubSite), context: &LemmyContext) -> LemmyResult<()> { - DbPerson::delete(&mut context.pool(), data.0.id).await?; - Site::delete(&mut context.pool(), data.1.id).await?; + async fn cleanup( + (person, site): (ApubPerson, ApubSite), + context: &LemmyContext, + ) -> LemmyResult<()> { + DbPerson::delete(&mut context.pool(), person.id).await?; + Site::delete(&mut context.pool(), site.id).await?; Ok(()) } } diff --git a/crates/apub/src/objects/private_message.rs b/crates/apub/src/objects/private_message.rs index 5a191cc66..3a61eb4a5 100644 --- a/crates/apub/src/objects/private_message.rs +++ b/crates/apub/src/objects/private_message.rs @@ -186,12 +186,12 @@ mod tests { } async fn cleanup( - data: (ApubPerson, ApubPerson, ApubSite), + (person1, person2, site): (ApubPerson, ApubPerson, ApubSite), context: &Data, ) -> LemmyResult<()> { - Person::delete(&mut context.pool(), data.0.id).await?; - Person::delete(&mut context.pool(), data.1.id).await?; - Site::delete(&mut context.pool(), data.2.id).await?; + Person::delete(&mut context.pool(), person1.id).await?; + Person::delete(&mut context.pool(), person2.id).await?; + Site::delete(&mut context.pool(), site.id).await?; Ok(()) } diff --git a/crates/db_views/src/custom_emoji_view.rs b/crates/db_views/src/custom_emoji_view.rs index a346c086d..606e807e9 100644 --- a/crates/db_views/src/custom_emoji_view.rs +++ b/crates/db_views/src/custom_emoji_view.rs @@ -76,16 +76,16 @@ impl CustomEmojiView { fn from_tuple_to_vec(items: Vec) -> Vec { let mut result = Vec::new(); let mut hash: HashMap> = HashMap::new(); - for item in &items { - let emoji_id: CustomEmojiId = item.0.id; + for (emoji, keyword) in &items { + let emoji_id: CustomEmojiId = emoji.id; if let std::collections::hash_map::Entry::Vacant(e) = hash.entry(emoji_id) { e.insert(Vec::new()); result.push(CustomEmojiView { - custom_emoji: item.0.clone(), + custom_emoji: emoji.clone(), keywords: Vec::new(), }) } - if let Some(item_keyword) = &item.1 { + if let Some(item_keyword) = &keyword { if let Some(keywords) = hash.get_mut(&emoji_id) { keywords.push(item_keyword.clone()) } diff --git a/crates/utils/src/utils/markdown/image_links.rs b/crates/utils/src/utils/markdown/image_links.rs index a21bb6f41..7456190e4 100644 --- a/crates/utils/src/utils/markdown/image_links.rs +++ b/crates/utils/src/utils/markdown/image_links.rs @@ -42,13 +42,10 @@ pub fn markdown_rewrite_image_links(mut src: String) -> (String, Vec) { pub fn markdown_handle_title(src: &str, start: usize, end: usize) -> (&str, Option<&str>) { let content = src.get(start..end).unwrap_or_default(); // necessary for custom emojis which look like `![name](url "title")` - let (url, extra) = if content.contains(' ') { - let split = content.split_once(' ').expect("split is valid"); - (split.0, Some(split.1)) - } else { - (content, None) - }; - (url, extra) + match content.split_once(' ') { + Some((a, b)) => (a, Some(b)), + _ => (content, None), + } } pub fn markdown_find_links(src: &str) -> Vec<(usize, usize)> { @@ -61,9 +58,9 @@ fn find_urls(src: &str) -> Vec<(usize, usize)> { let mut links_offsets = vec![]; ast.walk(|node, _depth| { if let Some(image) = node.cast::() { - let node_offsets = node.srcmap.expect("srcmap is none").get_byte_offsets(); - let start_offset = node_offsets.1 - image.url_len() - 1 - image.title_len(); - let end_offset = node_offsets.1 - 1; + let (_, node_offset) = node.srcmap.expect("srcmap is none").get_byte_offsets(); + let start_offset = node_offset - image.url_len() - 1 - image.title_len(); + let end_offset = node_offset - 1; links_offsets.push((start_offset, end_offset)); } diff --git a/src/scheduled_tasks.rs b/src/scheduled_tasks.rs index 2f99fe8a1..75942d3dd 100644 --- a/src/scheduled_tasks.rs +++ b/src/scheduled_tasks.rs @@ -393,10 +393,10 @@ async fn active_counts(pool: &mut DbPool<'_>) { ("6 months", "half_year"), ]; - for i in &intervals { + for (full_form, abbr) in &intervals { let update_site_stmt = format!( "update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}')) where site_id = 1", - i.1, i.0 + abbr, full_form ); sql_query(update_site_stmt) .execute(&mut conn) @@ -404,7 +404,7 @@ async fn active_counts(pool: &mut DbPool<'_>) { .inspect_err(|e| error!("Failed to update site stats: {e}")) .ok(); - let update_community_stmt = format!("update community_aggregates ca set users_active_{} = mv.count_ from community_aggregates_activity('{}') mv where ca.community_id = mv.community_id_", i.1, i.0); + let update_community_stmt = format!("update community_aggregates ca set users_active_{} = mv.count_ from community_aggregates_activity('{}') mv where ca.community_id = mv.community_id_", abbr, full_form); sql_query(update_community_stmt) .execute(&mut conn) .await From e8875dec99456c4217a3e844eb67bdca756a02ff Mon Sep 17 00:00:00 2001 From: flamingos-cant <45780476+flamingo-cant-draw@users.noreply.github.com> Date: Thu, 31 Oct 2024 12:13:42 +0000 Subject: [PATCH 03/19] Append attachments to comments (#5143) * Append attachments to comments. * fmt * Proxy images + use newlines for separation * Use md for plain links * Use proxy_image_link directly --- crates/api_common/src/utils.rs | 2 +- .../objects/{note.json => note_1.json} | 0 .../apub/assets/mastodon/objects/note_2.json | 79 +++++++++++++++++++ crates/apub/src/objects/comment.rs | 4 +- crates/apub/src/objects/mod.rs | 19 ++++- crates/apub/src/protocol/objects/mod.rs | 3 +- crates/apub/src/protocol/objects/note.rs | 8 +- crates/apub/src/protocol/objects/page.rs | 21 ++++- 8 files changed, 130 insertions(+), 6 deletions(-) rename crates/apub/assets/mastodon/objects/{note.json => note_1.json} (100%) create mode 100644 crates/apub/assets/mastodon/objects/note_2.json diff --git a/crates/api_common/src/utils.rs b/crates/api_common/src/utils.rs index 87cdf9eef..e358d483b 100644 --- a/crates/api_common/src/utils.rs +++ b/crates/api_common/src/utils.rs @@ -1110,7 +1110,7 @@ async fn proxy_image_link_internal( /// Rewrite a link to go through `/api/v3/image_proxy` endpoint. This is only for remote urls and /// if image_proxy setting is enabled. -pub(crate) async fn proxy_image_link(link: Url, context: &LemmyContext) -> LemmyResult { +pub async fn proxy_image_link(link: Url, context: &LemmyContext) -> LemmyResult { proxy_image_link_internal( link, context.settings().pictrs_config()?.image_mode(), diff --git a/crates/apub/assets/mastodon/objects/note.json b/crates/apub/assets/mastodon/objects/note_1.json similarity index 100% rename from crates/apub/assets/mastodon/objects/note.json rename to crates/apub/assets/mastodon/objects/note_1.json diff --git a/crates/apub/assets/mastodon/objects/note_2.json b/crates/apub/assets/mastodon/objects/note_2.json new file mode 100644 index 000000000..b8c22b976 --- /dev/null +++ b/crates/apub/assets/mastodon/objects/note_2.json @@ -0,0 +1,79 @@ +{ + "@context": [ + "https://www.w3.org/ns/activitystreams", + { + "ostatus": "http://ostatus.org#", + "atomUri": "ostatus:atomUri", + "inReplyToAtomUri": "ostatus:inReplyToAtomUri", + "conversation": "ostatus:conversation", + "sensitive": "as:sensitive", + "toot": "http://joinmastodon.org/ns#", + "votersCount": "toot:votersCount", + "blurhash": "toot:blurhash", + "focalPoint": { + "@container": "@list", + "@id": "toot:focalPoint" + } + } + ], + "id": "https://floss.social/users/kde/statuses/113306831140126616", + "type": "Note", + "summary": null, + "inReplyTo": "https://floss.social/users/kde/statuses/113306824627995724", + "published": "2024-10-14T16:57:15Z", + "url": "https://floss.social/@kde/113306831140126616", + "attributedTo": "https://floss.social/users/kde", + "to": ["https://www.w3.org/ns/activitystreams#Public"], + "cc": [ + "https://floss.social/users/kde/followers", + "https://lemmy.kde.social/c/kde", + "https://lemmy.kde.social/c/kde/followers" + ], + "sensitive": false, + "atomUri": "https://floss.social/users/kde/statuses/113306831140126616", + "inReplyToAtomUri": "https://floss.social/users/kde/statuses/113306824627995724", + "conversation": "tag:floss.social,2024-10-14:objectId=71424279:objectType=Conversation", + "content": "

@kde@lemmy.kde.social

We also need funding 💶 to keep the gears turning! Please support us with a donation:

https://kde.org/donate/

[3/3]

", + "contentMap": { + "en": "

@kde@lemmy.kde.social

We also need funding 💶 to keep the gears turning! Please support us with a donation:

https://kde.org/donate/

[3/3]

" + }, + "attachment": [ + { + "type": "Document", + "mediaType": "image/jpeg", + "url": "https://cdn.masto.host/floss/media_attachments/files/113/306/826/682/985/891/original/c8d906a2f2ab2334.jpg", + "name": "The KDE dragons Katie and Konqi stand on either side of a pot filling up with gold coins. Donate!", + "blurhash": "USQv:h-W-qI-^,W;RPs=^-R%NZxbo#sDobSc", + "focalPoint": [0.0, 0.0], + "width": 1500, + "height": 1095 + } + ], + "tag": [ + { + "type": "Mention", + "href": "https://lemmy.kde.social/c/kde", + "name": "@kde@lemmy.kde.social" + } + ], + "replies": { + "id": "https://floss.social/users/kde/statuses/113306831140126616/replies", + "type": "Collection", + "first": { + "type": "CollectionPage", + "next": "https://floss.social/users/kde/statuses/113306831140126616/replies?only_other_accounts=true&page=true", + "partOf": "https://floss.social/users/kde/statuses/113306831140126616/replies", + "items": [] + } + }, + "likes": { + "id": "https://floss.social/users/kde/statuses/113306831140126616/likes", + "type": "Collection", + "totalItems": 39 + }, + "shares": { + "id": "https://floss.social/users/kde/statuses/113306831140126616/shares", + "type": "Collection", + "totalItems": 24 + } +} diff --git a/crates/apub/src/objects/comment.rs b/crates/apub/src/objects/comment.rs index e6cc2ba85..6e13afc91 100644 --- a/crates/apub/src/objects/comment.rs +++ b/crates/apub/src/objects/comment.rs @@ -3,7 +3,7 @@ use crate::{ check_apub_id_valid_with_strictness, fetcher::markdown_links::markdown_rewrite_remote_links, mentions::collect_non_local_mentions, - objects::{read_from_string_or_source, verify_is_remote_object}, + objects::{append_attachments_to_comment, read_from_string_or_source, verify_is_remote_object}, protocol::{ objects::{note::Note, LanguageTag}, InCommunity, @@ -124,6 +124,7 @@ impl Object for ApubComment { distinguished: Some(self.distinguished), language, audience: Some(community.actor_id.into()), + attachment: vec![], }; Ok(note) @@ -181,6 +182,7 @@ impl Object for ApubComment { let local_site = LocalSite::read(&mut context.pool()).await.ok(); let slur_regex = &local_site_opt_to_slur_regex(&local_site); let url_blocklist = get_url_blocklist(context).await?; + let content = append_attachments_to_comment(content, ¬e.attachment, context).await?; let content = process_markdown(&content, slur_regex, &url_blocklist, context).await?; let content = markdown_rewrite_remote_links(content, context).await; let language_id = Some( diff --git a/crates/apub/src/objects/mod.rs b/crates/apub/src/objects/mod.rs index e199ebfad..f837f7ad3 100644 --- a/crates/apub/src/objects/mod.rs +++ b/crates/apub/src/objects/mod.rs @@ -1,4 +1,4 @@ -use crate::protocol::Source; +use crate::protocol::{objects::page::Attachment, Source}; use activitypub_federation::{ config::Data, fetch::object_id::ObjectId, @@ -46,6 +46,23 @@ pub(crate) fn read_from_string_or_source_opt( .map(|content| read_from_string_or_source(content, media_type, source)) } +pub(crate) async fn append_attachments_to_comment( + content: String, + attachments: &[Attachment], + context: &Data, +) -> LemmyResult { + let mut content = content; + // Don't modify comments with no attachments + if !attachments.is_empty() { + content += "\n"; + for attachment in attachments { + content = content + "\n" + &attachment.as_markdown(context).await?; + } + } + + Ok(content) +} + /// When for example a Post is made in a remote community, the community will send it back, /// wrapped in Announce. If we simply receive this like any other federated object, overwrite the /// existing, local Post. In particular, it will set the field local = false, so that the object diff --git a/crates/apub/src/protocol/objects/mod.rs b/crates/apub/src/protocol/objects/mod.rs index dbba1bb8a..00fe26d2b 100644 --- a/crates/apub/src/protocol/objects/mod.rs +++ b/crates/apub/src/protocol/objects/mod.rs @@ -145,7 +145,8 @@ mod tests { #[test] fn test_parse_objects_mastodon() -> LemmyResult<()> { test_json::("assets/mastodon/objects/person.json")?; - test_json::("assets/mastodon/objects/note.json")?; + test_json::("assets/mastodon/objects/note_1.json")?; + test_json::("assets/mastodon/objects/note_2.json")?; test_json::("assets/mastodon/objects/page.json")?; Ok(()) } diff --git a/crates/apub/src/protocol/objects/note.rs b/crates/apub/src/protocol/objects/note.rs index e3e204254..21b5220f5 100644 --- a/crates/apub/src/protocol/objects/note.rs +++ b/crates/apub/src/protocol/objects/note.rs @@ -3,7 +3,11 @@ use crate::{ fetcher::post_or_comment::PostOrComment, mentions::MentionOrValue, objects::{comment::ApubComment, community::ApubCommunity, person::ApubPerson, post::ApubPost}, - protocol::{objects::LanguageTag, InCommunity, Source}, + protocol::{ + objects::{page::Attachment, LanguageTag}, + InCommunity, + Source, + }, }; use activitypub_federation::{ config::Data, @@ -50,6 +54,8 @@ pub struct Note { pub(crate) distinguished: Option, pub(crate) language: Option, pub(crate) audience: Option>, + #[serde(default)] + pub(crate) attachment: Vec, } impl Note { diff --git a/crates/apub/src/protocol/objects/page.rs b/crates/apub/src/protocol/objects/page.rs index 97f767573..3ce720bc0 100644 --- a/crates/apub/src/protocol/objects/page.rs +++ b/crates/apub/src/protocol/objects/page.rs @@ -19,7 +19,7 @@ use activitypub_federation::{ }; use chrono::{DateTime, Utc}; use itertools::Itertools; -use lemmy_api_common::context::LemmyContext; +use lemmy_api_common::{context::LemmyContext, utils::proxy_image_link}; use lemmy_utils::error::{FederationError, LemmyError, LemmyErrorType, LemmyResult}; use serde::{de::Error, Deserialize, Deserializer, Serialize}; use serde_with::skip_serializing_none; @@ -93,6 +93,7 @@ pub(crate) struct Document { #[serde(rename = "type")] kind: DocumentType, url: Url, + media_type: Option, /// Used for alt_text name: Option, } @@ -124,6 +125,24 @@ impl Attachment { _ => None, } } + + pub(crate) async fn as_markdown(&self, context: &Data) -> LemmyResult { + let (url, name, media_type) = match self { + Attachment::Image(i) => (i.url.clone(), i.name.clone(), Some(String::from("image"))), + Attachment::Document(d) => (d.url.clone(), d.name.clone(), d.media_type.clone()), + Attachment::Link(l) => (l.href.clone(), None, l.media_type.clone()), + }; + + let is_image = + media_type.is_some_and(|media| media.starts_with("video") || media.starts_with("image")); + + if is_image { + let url = proxy_image_link(url, context).await?; + Ok(format!("![{}]({url})", name.unwrap_or_default())) + } else { + Ok(format!("[{url}]({url})")) + } + } } #[derive(Clone, Debug, Deserialize, Serialize)] From 22e2290d7b20cc2c700769def062d36bcdcb4d72 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 31 Oct 2024 22:47:04 -0400 Subject: [PATCH 04/19] chore(deps): update npm (#5153) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- api_tests/package.json | 2 +- api_tests/pnpm-lock.yaml | 436 +++++++++++++++++---------------------- 2 files changed, 189 insertions(+), 249 deletions(-) diff --git a/api_tests/package.json b/api_tests/package.json index 63c212d01..81e518ea4 100644 --- a/api_tests/package.json +++ b/api_tests/package.json @@ -6,7 +6,7 @@ "repository": "https://github.com/LemmyNet/lemmy", "author": "Dessalines", "license": "AGPL-3.0", - "packageManager": "pnpm@9.12.0", + "packageManager": "pnpm@9.12.3", "scripts": { "lint": "tsc --noEmit && eslint --report-unused-disable-directives && prettier --check 'src/**/*.ts'", "fix": "prettier --write src && eslint --fix src", diff --git a/api_tests/pnpm-lock.yaml b/api_tests/pnpm-lock.yaml index 6807f43f8..dd357d248 100644 --- a/api_tests/pnpm-lock.yaml +++ b/api_tests/pnpm-lock.yaml @@ -10,25 +10,25 @@ importers: devDependencies: '@types/jest': specifier: ^29.5.12 - version: 29.5.13 + version: 29.5.14 '@types/node': specifier: ^22.3.0 - version: 22.7.4 + version: 22.8.6 '@typescript-eslint/eslint-plugin': specifier: ^8.1.0 - version: 8.8.1(@typescript-eslint/parser@8.8.1(eslint@9.12.0)(typescript@5.6.2))(eslint@9.12.0)(typescript@5.6.2) + version: 8.12.2(@typescript-eslint/parser@8.12.2(eslint@9.13.0)(typescript@5.6.3))(eslint@9.13.0)(typescript@5.6.3) '@typescript-eslint/parser': specifier: ^8.1.0 - version: 8.8.1(eslint@9.12.0)(typescript@5.6.2) + version: 8.12.2(eslint@9.13.0)(typescript@5.6.3) eslint: specifier: ^9.9.0 - version: 9.12.0 + version: 9.13.0 eslint-plugin-prettier: specifier: ^5.1.3 - version: 5.2.1(eslint@9.12.0)(prettier@3.3.3) + version: 5.2.1(eslint@9.13.0)(prettier@3.3.3) jest: specifier: ^29.5.0 - version: 29.7.0(@types/node@22.7.4) + version: 29.7.0(@types/node@22.8.6) lemmy-js-client: specifier: 0.20.0-alpha.11 version: 0.20.0-alpha.11 @@ -37,13 +37,13 @@ importers: version: 3.3.3 ts-jest: specifier: ^29.1.0 - version: 29.2.5(@babel/core@7.23.9)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.23.9))(jest@29.7.0(@types/node@22.7.4))(typescript@5.6.2) + version: 29.2.5(@babel/core@7.23.9)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.23.9))(jest@29.7.0(@types/node@22.8.6))(typescript@5.6.3) typescript: specifier: ^5.5.4 - version: 5.6.2 + version: 5.6.3 typescript-eslint: specifier: ^8.1.0 - version: 8.8.1(eslint@9.12.0)(typescript@5.6.2) + version: 8.12.2(eslint@9.13.0)(typescript@5.6.3) packages: @@ -51,8 +51,8 @@ packages: resolution: {integrity: sha512-lFMjJTrFL3j7L9yBxwYfCq2k6qqwHyzuUl/XBnif78PWTJYyL/dfowQHWE3sp6U6ZzqWiiIZnpTMO96zhkjwtg==} engines: {node: '>=6.0.0'} - '@babel/code-frame@7.24.7': - resolution: {integrity: sha512-BcYH1CVJBO9tvyIZ2jVeXgSIMvGZ2FDRvDdOIVQyuklNKSsx+eppDEBq/g47Ayw+RqNFE+URvOShmf+f/qwAlA==} + '@babel/code-frame@7.26.2': + resolution: {integrity: sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==} engines: {node: '>=6.9.0'} '@babel/compat-data@7.23.5': @@ -113,8 +113,8 @@ packages: resolution: {integrity: sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==} engines: {node: '>=6.9.0'} - '@babel/helper-validator-identifier@7.24.7': - resolution: {integrity: sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==} + '@babel/helper-validator-identifier@7.25.9': + resolution: {integrity: sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==} engines: {node: '>=6.9.0'} '@babel/helper-validator-option@7.23.5': @@ -125,10 +125,6 @@ packages: resolution: {integrity: sha512-87ICKgU5t5SzOT7sBMfCOZQ2rHjRU+Pcb9BoILMYz600W6DkVRLFBPwQ18gwUVvggqXivaUakpnxWQGbpywbBQ==} engines: {node: '>=6.9.0'} - '@babel/highlight@7.24.7': - resolution: {integrity: sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==} - engines: {node: '>=6.9.0'} - '@babel/parser@7.23.9': resolution: {integrity: sha512-9tcKgqKbs3xGJ+NtKF2ndOBBLVwPjl1SHxPQkd36r3Dlirw3xWUeGaTbqr7uGZcTaxkVNwc+03SVP7aCdWrTlA==} engines: {node: '>=6.0.0'} @@ -222,46 +218,46 @@ packages: '@bcoe/v8-coverage@0.2.3': resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==} - '@eslint-community/eslint-utils@4.4.0': - resolution: {integrity: sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==} + '@eslint-community/eslint-utils@4.4.1': + resolution: {integrity: sha512-s3O3waFUrMV8P/XaF/+ZTp1X9XBZW1a4B97ZnjQF2KYWaFD2A8KyFBsrsfSjEmjn3RGWAIuvlneuZm3CUK3jbA==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} peerDependencies: eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 - '@eslint-community/regexpp@4.11.1': - resolution: {integrity: sha512-m4DVN9ZqskZoLU5GlWZadwDnYo3vAEydiUayB9widCl9ffWx2IvPnp6n3on5rJmziJSw9Bv+Z3ChDVdMwXCY8Q==} + '@eslint-community/regexpp@4.12.1': + resolution: {integrity: sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==} engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} '@eslint/config-array@0.18.0': resolution: {integrity: sha512-fTxvnS1sRMu3+JjXwJG0j/i4RT9u4qJ+lqS/yCGap4lH4zZGzQ7tu+xZqQmcMZq5OBZDL4QRxQzRjkWcGt8IVw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@eslint/core@0.6.0': - resolution: {integrity: sha512-8I2Q8ykA4J0x0o7cg67FPVnehcqWTBehu/lmY+bolPFHGjh49YzGBMXTvpqVgEbBdvNCSxj6iFgiIyHzf03lzg==} + '@eslint/core@0.7.0': + resolution: {integrity: sha512-xp5Jirz5DyPYlPiKat8jaq0EmYvDXKKpzTbxXMpT9eqlRJkRKIz9AGMdlvYjih+im+QlhWrpvVjl8IPC/lHlUw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} '@eslint/eslintrc@3.1.0': resolution: {integrity: sha512-4Bfj15dVJdoy3RfZmmo86RK1Fwzn6SstsvK9JS+BaVKqC6QQQQyXekNaC+g+LKNgkQ+2VhGAzm6hO40AhMR3zQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@eslint/js@9.12.0': - resolution: {integrity: sha512-eohesHH8WFRUprDNyEREgqP6beG6htMeUYeCpkEgBCieCMme5r9zFWjzAJp//9S+Kub4rqE+jXe9Cp1a7IYIIA==} + '@eslint/js@9.13.0': + resolution: {integrity: sha512-IFLyoY4d72Z5y/6o/BazFBezupzI/taV8sGumxTAVw3lXG9A6md1Dc34T9s1FoD/an9pJH8RHbAxsaEbBed9lA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} '@eslint/object-schema@2.1.4': resolution: {integrity: sha512-BsWiH1yFGjXXS2yvrf5LyuoSIIbPrGUWob917o+BTKuZ7qJdxX8aJLRxs1fS9n6r7vESrq1OUqb68dANcFXuQQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@eslint/plugin-kit@0.2.0': - resolution: {integrity: sha512-vH9PiIMMwvhCx31Af3HiGzsVNULDbyVkHXwlemn/B0TFj/00ho3y55efXrUZTfQipxoHC5u4xq6zblww1zm1Ig==} + '@eslint/plugin-kit@0.2.2': + resolution: {integrity: sha512-CXtq5nR4Su+2I47WPOlWud98Y5Lv8Kyxp2ukhgFx/eW6Blm18VXJO5WuQylPugRo8nbluoi6GvvxBLqHcvqUUw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@humanfs/core@0.19.0': - resolution: {integrity: sha512-2cbWIHbZVEweE853g8jymffCA+NCMiuqeECeBBLm8dg2oFdjuGJhgN4UAbI+6v0CKbbhvtXA4qV8YR5Ji86nmw==} + '@humanfs/core@0.19.1': + resolution: {integrity: sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==} engines: {node: '>=18.18.0'} - '@humanfs/node@0.16.5': - resolution: {integrity: sha512-KSPA4umqSG4LHYRodq31VDwKAvaTF4xmVlzM8Aeh4PlU1JQ3IG0wiA8C25d3RQ9nJyM3mBHyI53K06VVL/oFFg==} + '@humanfs/node@0.16.6': + resolution: {integrity: sha512-YuI2ZHQL78Q5HbhDiBA1X4LmYdXCKCMQIfw0pw7piHJwyREFebJUvrQN4cMssyES6x+vfUbx1CIpaQUKYdQZOw==} engines: {node: '>=18.18.0'} '@humanwhocodes/module-importer@1.0.1': @@ -416,14 +412,14 @@ packages: '@types/istanbul-reports@3.0.4': resolution: {integrity: sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==} - '@types/jest@29.5.13': - resolution: {integrity: sha512-wd+MVEZCHt23V0/L642O5APvspWply/rGY5BcW4SUETo2UzPU3Z26qr8jC2qxpimI2jjx9h7+2cj2FwIr01bXg==} + '@types/jest@29.5.14': + resolution: {integrity: sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==} '@types/json-schema@7.0.15': resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} - '@types/node@22.7.4': - resolution: {integrity: sha512-y+NPi1rFzDs1NdQHHToqeiX2TIS79SWEAw9GYhkkx8bD0ChpfqC+n2j5OXOCpzfojBEBt6DnEnnG9MY0zk1XLg==} + '@types/node@22.8.6': + resolution: {integrity: sha512-tosuJYKrIqjQIlVCM4PEGxOmyg3FCPa/fViuJChnGeEIhjA46oy8FMVoF9su1/v8PNs2a8Q0iFNyOx0uOF91nw==} '@types/stack-utils@2.0.3': resolution: {integrity: sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==} @@ -434,8 +430,8 @@ packages: '@types/yargs@17.0.32': resolution: {integrity: sha512-xQ67Yc/laOG5uMfX/093MRlGGCIBzZMarVa+gfNKJxWAIgykYpVGkBdbqEzGDDfCrVUj6Hiff4mTZ5BA6TmAog==} - '@typescript-eslint/eslint-plugin@8.8.1': - resolution: {integrity: sha512-xfvdgA8AP/vxHgtgU310+WBnLB4uJQ9XdyP17RebG26rLtDrQJV3ZYrcopX91GrHmMoH8bdSwMRh2a//TiJ1jQ==} + '@typescript-eslint/eslint-plugin@8.12.2': + resolution: {integrity: sha512-gQxbxM8mcxBwaEmWdtLCIGLfixBMHhQjBqR8sVWNTPpcj45WlYL2IObS/DNMLH1DBP0n8qz+aiiLTGfopPEebw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} peerDependencies: '@typescript-eslint/parser': ^8.0.0 || ^8.0.0-alpha.0 @@ -445,8 +441,8 @@ packages: typescript: optional: true - '@typescript-eslint/parser@8.8.1': - resolution: {integrity: sha512-hQUVn2Lij2NAxVFEdvIGxT9gP1tq2yM83m+by3whWFsWC+1y8pxxxHUFE1UqDu2VsGi2i6RLcv4QvouM84U+ow==} + '@typescript-eslint/parser@8.12.2': + resolution: {integrity: sha512-MrvlXNfGPLH3Z+r7Tk+Z5moZAc0dzdVjTgUgwsdGweH7lydysQsnSww3nAmsq8blFuRD5VRlAr9YdEFw3e6PBw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} peerDependencies: eslint: ^8.57.0 || ^9.0.0 @@ -455,12 +451,12 @@ packages: typescript: optional: true - '@typescript-eslint/scope-manager@8.8.1': - resolution: {integrity: sha512-X4JdU+66Mazev/J0gfXlcC/dV6JI37h+93W9BRYXrSn0hrE64IoWgVkO9MSJgEzoWkxONgaQpICWg8vAN74wlA==} + '@typescript-eslint/scope-manager@8.12.2': + resolution: {integrity: sha512-gPLpLtrj9aMHOvxJkSbDBmbRuYdtiEbnvO25bCMza3DhMjTQw0u7Y1M+YR5JPbMsXXnSPuCf5hfq0nEkQDL/JQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript-eslint/type-utils@8.8.1': - resolution: {integrity: sha512-qSVnpcbLP8CALORf0za+vjLYj1Wp8HSoiI8zYU5tHxRVj30702Z1Yw4cLwfNKhTPWp5+P+k1pjmD5Zd1nhxiZA==} + '@typescript-eslint/type-utils@8.12.2': + resolution: {integrity: sha512-bwuU4TAogPI+1q/IJSKuD4shBLc/d2vGcRT588q+jzayQyjVK2X6v/fbR4InY2U2sgf8MEvVCqEWUzYzgBNcGQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} peerDependencies: typescript: '*' @@ -468,12 +464,12 @@ packages: typescript: optional: true - '@typescript-eslint/types@8.8.1': - resolution: {integrity: sha512-WCcTP4SDXzMd23N27u66zTKMuEevH4uzU8C9jf0RO4E04yVHgQgW+r+TeVTNnO1KIfrL8ebgVVYYMMO3+jC55Q==} + '@typescript-eslint/types@8.12.2': + resolution: {integrity: sha512-VwDwMF1SZ7wPBUZwmMdnDJ6sIFk4K4s+ALKLP6aIQsISkPv8jhiw65sAK6SuWODN/ix+m+HgbYDkH+zLjrzvOA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript-eslint/typescript-estree@8.8.1': - resolution: {integrity: sha512-A5d1R9p+X+1js4JogdNilDuuq+EHZdsH9MjTVxXOdVFfTJXunKJR/v+fNNyO4TnoOn5HqobzfRlc70NC6HTcdg==} + '@typescript-eslint/typescript-estree@8.12.2': + resolution: {integrity: sha512-mME5MDwGe30Pq9zKPvyduyU86PH7aixwqYR2grTglAdB+AN8xXQ1vFGpYaUSJ5o5P/5znsSBeNcs5g5/2aQwow==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} peerDependencies: typescript: '*' @@ -481,14 +477,14 @@ packages: typescript: optional: true - '@typescript-eslint/utils@8.8.1': - resolution: {integrity: sha512-/QkNJDbV0bdL7H7d0/y0qBbV2HTtf0TIyjSDTvvmQEzeVx8jEImEbLuOA4EsvE8gIgqMitns0ifb5uQhMj8d9w==} + '@typescript-eslint/utils@8.12.2': + resolution: {integrity: sha512-UTTuDIX3fkfAz6iSVa5rTuSfWIYZ6ATtEocQ/umkRSyC9O919lbZ8dcH7mysshrCdrAM03skJOEYaBugxN+M6A==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} peerDependencies: eslint: ^8.57.0 || ^9.0.0 - '@typescript-eslint/visitor-keys@8.8.1': - resolution: {integrity: sha512-0/TdC3aeRAsW7MDvYRwEc1Uwm0TIBfzjPFgg60UU2Haj5qsCs9cc3zNgY71edqE3LbWfF/WoZQd3lJoDXFQpag==} + '@typescript-eslint/visitor-keys@8.12.2': + resolution: {integrity: sha512-PChz8UaKQAVNHghsHcPyx1OMHoFRUEA7rJSK/mDhdq85bk+PLsUHUBqTQTFt18VJZbmxBovM65fezlheQRsSDA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} acorn-jsx@5.3.2: @@ -496,8 +492,8 @@ packages: peerDependencies: acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 - acorn@8.12.1: - resolution: {integrity: sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==} + acorn@8.14.0: + resolution: {integrity: sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==} engines: {node: '>=0.4.0'} hasBin: true @@ -512,10 +508,6 @@ packages: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} - ansi-styles@3.2.1: - resolution: {integrity: sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==} - engines: {node: '>=4'} - ansi-styles@4.3.0: resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} engines: {node: '>=8'} @@ -609,10 +601,6 @@ packages: caniuse-lite@1.0.30001581: resolution: {integrity: sha512-whlTkwhqV2tUmP3oYhtNfaWGYHDdS3JYFQBKXxcUR9qqPWsRhFHhoISO2Xnl/g0xyKzht9mI1LZpiNWfMzHixQ==} - chalk@2.4.2: - resolution: {integrity: sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==} - engines: {node: '>=4'} - chalk@4.1.2: resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} engines: {node: '>=10'} @@ -639,16 +627,10 @@ packages: collect-v8-coverage@1.0.2: resolution: {integrity: sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==} - color-convert@1.9.3: - resolution: {integrity: sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==} - color-convert@2.0.1: resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} engines: {node: '>=7.0.0'} - color-name@1.1.3: - resolution: {integrity: sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==} - color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} @@ -721,10 +703,6 @@ packages: resolution: {integrity: sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==} engines: {node: '>=6'} - escape-string-regexp@1.0.5: - resolution: {integrity: sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==} - engines: {node: '>=0.8.0'} - escape-string-regexp@2.0.0: resolution: {integrity: sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==} engines: {node: '>=8'} @@ -747,20 +725,20 @@ packages: eslint-config-prettier: optional: true - eslint-scope@8.1.0: - resolution: {integrity: sha512-14dSvlhaVhKKsa9Fx1l8A17s7ah7Ef7wCakJ10LYk6+GYmP9yDti2oq2SEwcyndt6knfcZyhyxwY3i9yL78EQw==} + eslint-scope@8.2.0: + resolution: {integrity: sha512-PHlWUfG6lvPc3yvP5A4PNyBL1W8fkDUccmI21JUu/+GKZBoH/W5u6usENXUrWFRsyoW5ACUjFGgAFQp5gUlb/A==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} eslint-visitor-keys@3.4.3: resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - eslint-visitor-keys@4.1.0: - resolution: {integrity: sha512-Q7lok0mqMUSf5a/AdAZkA5a/gHcO6snwQClVNNvFKCAVlxXucdU8pKydU5ZVZjBx5xr37vGbFFWtLQYreLzrZg==} + eslint-visitor-keys@4.2.0: + resolution: {integrity: sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - eslint@9.12.0: - resolution: {integrity: sha512-UVIOlTEWxwIopRL1wgSQYdnVDcEvs2wyaO6DGo5mXqe3r16IoCNWkR29iHhyaP4cICWjbgbmFUGAhh0GJRuGZw==} + eslint@9.13.0: + resolution: {integrity: sha512-EYZK6SX6zjFHST/HRytOdA/zE72Cq/bfw45LSyuwrdvcclb/gqV8RRQxywOBEWO2+WDpva6UZa4CcDeJKzUCFA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} hasBin: true peerDependencies: @@ -769,8 +747,8 @@ packages: jiti: optional: true - espree@10.2.0: - resolution: {integrity: sha512-upbkBJbckcCNBDBDXEbuhjbP68n+scUd3k/U2EkyM9nw+I/jPiL4cLF/Al06CF96wRltFda16sxDFrxsI1v0/g==} + espree@10.3.0: + resolution: {integrity: sha512-0QYC8b24HWY8zjRnDTL6RiHfDbAWn63qb4LMj1Z4b076A4une81+z03Kg7l7mn/48PUTqoLptSXez8oknU8Clg==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} esprima@4.0.1: @@ -911,10 +889,6 @@ packages: graphemer@1.4.0: resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} - has-flag@3.0.0: - resolution: {integrity: sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==} - engines: {node: '>=4'} - has-flag@4.0.0: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} @@ -1330,8 +1304,8 @@ packages: path-parse@1.0.7: resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} - picocolors@1.1.0: - resolution: {integrity: sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw==} + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} picomatch@2.3.1: resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==} @@ -1480,10 +1454,6 @@ packages: resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} engines: {node: '>=8'} - supports-color@5.5.0: - resolution: {integrity: sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==} - engines: {node: '>=4'} - supports-color@7.2.0: resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} engines: {node: '>=8'} @@ -1518,8 +1488,8 @@ packages: resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} engines: {node: '>=8.0'} - ts-api-utils@1.3.0: - resolution: {integrity: sha512-UQMIo7pb8WRomKR1/+MFVLTroIvDVtMX3K6OUir8ynLyzB8Jeriont2bTAtmNPa1ekAgN7YPDyf6V+ygrdU+eQ==} + ts-api-utils@1.4.0: + resolution: {integrity: sha512-032cPxaEKwM+GT3vA5JXNzIaizx388rhsSW79vGRNGXfRRAdEAn2mvk36PvK5HnOchyWZ7afLEXqYCvPCrzuzQ==} engines: {node: '>=16'} peerDependencies: typescript: '>=4.2.0' @@ -1563,8 +1533,8 @@ packages: resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==} engines: {node: '>=10'} - typescript-eslint@8.8.1: - resolution: {integrity: sha512-R0dsXFt6t4SAFjUSKFjMh4pXDtq04SsFKCVGDP3ZOzNP7itF0jBcZYU4fMsZr4y7O7V7Nc751dDeESbe4PbQMQ==} + typescript-eslint@8.12.2: + resolution: {integrity: sha512-UbuVUWSrHVR03q9CWx+JDHeO6B/Hr9p4U5lRH++5tq/EbFq1faYZe50ZSBePptgfIKLEti0aPQ3hFgnPVcd8ZQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} peerDependencies: typescript: '*' @@ -1572,8 +1542,8 @@ packages: typescript: optional: true - typescript@5.6.2: - resolution: {integrity: sha512-NW8ByodCSNCwZeghjN3o+JX5OFH0Ojg6sadjEKY4huZ52TqbJTJnDo5+Tw98lSy63NZvi4n+ez5m2u5d4PkZyw==} + typescript@5.6.3: + resolution: {integrity: sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==} engines: {node: '>=14.17'} hasBin: true @@ -1642,17 +1612,18 @@ snapshots: '@jridgewell/gen-mapping': 0.3.3 '@jridgewell/trace-mapping': 0.3.22 - '@babel/code-frame@7.24.7': + '@babel/code-frame@7.26.2': dependencies: - '@babel/highlight': 7.24.7 - picocolors: 1.1.0 + '@babel/helper-validator-identifier': 7.25.9 + js-tokens: 4.0.0 + picocolors: 1.1.1 '@babel/compat-data@7.23.5': {} '@babel/core@7.23.9': dependencies: '@ampproject/remapping': 2.2.1 - '@babel/code-frame': 7.24.7 + '@babel/code-frame': 7.26.2 '@babel/generator': 7.23.6 '@babel/helper-compilation-targets': 7.23.6 '@babel/helper-module-transforms': 7.23.3(@babel/core@7.23.9) @@ -1706,7 +1677,7 @@ snapshots: '@babel/helper-module-imports': 7.22.15 '@babel/helper-simple-access': 7.22.5 '@babel/helper-split-export-declaration': 7.22.6 - '@babel/helper-validator-identifier': 7.22.20 + '@babel/helper-validator-identifier': 7.25.9 '@babel/helper-plugin-utils@7.22.5': {} @@ -1722,7 +1693,7 @@ snapshots: '@babel/helper-validator-identifier@7.22.20': {} - '@babel/helper-validator-identifier@7.24.7': {} + '@babel/helper-validator-identifier@7.25.9': {} '@babel/helper-validator-option@7.23.5': {} @@ -1734,13 +1705,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@babel/highlight@7.24.7': - dependencies: - '@babel/helper-validator-identifier': 7.24.7 - chalk: 2.4.2 - js-tokens: 4.0.0 - picocolors: 1.1.0 - '@babel/parser@7.23.9': dependencies: '@babel/types': 7.23.9 @@ -1817,13 +1781,13 @@ snapshots: '@babel/template@7.23.9': dependencies: - '@babel/code-frame': 7.24.7 + '@babel/code-frame': 7.26.2 '@babel/parser': 7.23.9 '@babel/types': 7.23.9 '@babel/traverse@7.23.9': dependencies: - '@babel/code-frame': 7.24.7 + '@babel/code-frame': 7.26.2 '@babel/generator': 7.23.6 '@babel/helper-environment-visitor': 7.22.20 '@babel/helper-function-name': 7.23.0 @@ -1844,12 +1808,12 @@ snapshots: '@bcoe/v8-coverage@0.2.3': {} - '@eslint-community/eslint-utils@4.4.0(eslint@9.12.0)': + '@eslint-community/eslint-utils@4.4.1(eslint@9.13.0)': dependencies: - eslint: 9.12.0 + eslint: 9.13.0 eslint-visitor-keys: 3.4.3 - '@eslint-community/regexpp@4.11.1': {} + '@eslint-community/regexpp@4.12.1': {} '@eslint/config-array@0.18.0': dependencies: @@ -1859,13 +1823,13 @@ snapshots: transitivePeerDependencies: - supports-color - '@eslint/core@0.6.0': {} + '@eslint/core@0.7.0': {} '@eslint/eslintrc@3.1.0': dependencies: ajv: 6.12.6 debug: 4.3.7 - espree: 10.2.0 + espree: 10.3.0 globals: 14.0.0 ignore: 5.3.2 import-fresh: 3.3.0 @@ -1875,19 +1839,19 @@ snapshots: transitivePeerDependencies: - supports-color - '@eslint/js@9.12.0': {} + '@eslint/js@9.13.0': {} '@eslint/object-schema@2.1.4': {} - '@eslint/plugin-kit@0.2.0': + '@eslint/plugin-kit@0.2.2': dependencies: levn: 0.4.1 - '@humanfs/core@0.19.0': {} + '@humanfs/core@0.19.1': {} - '@humanfs/node@0.16.5': + '@humanfs/node@0.16.6': dependencies: - '@humanfs/core': 0.19.0 + '@humanfs/core': 0.19.1 '@humanwhocodes/retry': 0.3.1 '@humanwhocodes/module-importer@1.0.1': {} @@ -1907,7 +1871,7 @@ snapshots: '@jest/console@29.7.0': dependencies: '@jest/types': 29.6.3 - '@types/node': 22.7.4 + '@types/node': 22.8.6 chalk: 4.1.2 jest-message-util: 29.7.0 jest-util: 29.7.0 @@ -1920,14 +1884,14 @@ snapshots: '@jest/test-result': 29.7.0 '@jest/transform': 29.7.0 '@jest/types': 29.6.3 - '@types/node': 22.7.4 + '@types/node': 22.8.6 ansi-escapes: 4.3.2 chalk: 4.1.2 ci-info: 3.9.0 exit: 0.1.2 graceful-fs: 4.2.11 jest-changed-files: 29.7.0 - jest-config: 29.7.0(@types/node@22.7.4) + jest-config: 29.7.0(@types/node@22.8.6) jest-haste-map: 29.7.0 jest-message-util: 29.7.0 jest-regex-util: 29.6.3 @@ -1952,7 +1916,7 @@ snapshots: dependencies: '@jest/fake-timers': 29.7.0 '@jest/types': 29.6.3 - '@types/node': 22.7.4 + '@types/node': 22.8.6 jest-mock: 29.7.0 '@jest/expect-utils@29.7.0': @@ -1970,7 +1934,7 @@ snapshots: dependencies: '@jest/types': 29.6.3 '@sinonjs/fake-timers': 10.3.0 - '@types/node': 22.7.4 + '@types/node': 22.8.6 jest-message-util: 29.7.0 jest-mock: 29.7.0 jest-util: 29.7.0 @@ -1992,7 +1956,7 @@ snapshots: '@jest/transform': 29.7.0 '@jest/types': 29.6.3 '@jridgewell/trace-mapping': 0.3.22 - '@types/node': 22.7.4 + '@types/node': 22.8.6 chalk: 4.1.2 collect-v8-coverage: 1.0.2 exit: 0.1.2 @@ -2062,7 +2026,7 @@ snapshots: '@jest/schemas': 29.6.3 '@types/istanbul-lib-coverage': 2.0.6 '@types/istanbul-reports': 3.0.4 - '@types/node': 22.7.4 + '@types/node': 22.8.6 '@types/yargs': 17.0.32 chalk: 4.1.2 @@ -2132,7 +2096,7 @@ snapshots: '@types/graceful-fs@4.1.9': dependencies: - '@types/node': 22.7.4 + '@types/node': 22.8.6 '@types/istanbul-lib-coverage@2.0.6': {} @@ -2144,14 +2108,14 @@ snapshots: dependencies: '@types/istanbul-lib-report': 3.0.3 - '@types/jest@29.5.13': + '@types/jest@29.5.14': dependencies: expect: 29.7.0 pretty-format: 29.7.0 '@types/json-schema@7.0.15': {} - '@types/node@22.7.4': + '@types/node@22.8.6': dependencies: undici-types: 6.19.8 @@ -2163,92 +2127,92 @@ snapshots: dependencies: '@types/yargs-parser': 21.0.3 - '@typescript-eslint/eslint-plugin@8.8.1(@typescript-eslint/parser@8.8.1(eslint@9.12.0)(typescript@5.6.2))(eslint@9.12.0)(typescript@5.6.2)': + '@typescript-eslint/eslint-plugin@8.12.2(@typescript-eslint/parser@8.12.2(eslint@9.13.0)(typescript@5.6.3))(eslint@9.13.0)(typescript@5.6.3)': dependencies: - '@eslint-community/regexpp': 4.11.1 - '@typescript-eslint/parser': 8.8.1(eslint@9.12.0)(typescript@5.6.2) - '@typescript-eslint/scope-manager': 8.8.1 - '@typescript-eslint/type-utils': 8.8.1(eslint@9.12.0)(typescript@5.6.2) - '@typescript-eslint/utils': 8.8.1(eslint@9.12.0)(typescript@5.6.2) - '@typescript-eslint/visitor-keys': 8.8.1 - eslint: 9.12.0 + '@eslint-community/regexpp': 4.12.1 + '@typescript-eslint/parser': 8.12.2(eslint@9.13.0)(typescript@5.6.3) + '@typescript-eslint/scope-manager': 8.12.2 + '@typescript-eslint/type-utils': 8.12.2(eslint@9.13.0)(typescript@5.6.3) + '@typescript-eslint/utils': 8.12.2(eslint@9.13.0)(typescript@5.6.3) + '@typescript-eslint/visitor-keys': 8.12.2 + eslint: 9.13.0 graphemer: 1.4.0 ignore: 5.3.2 natural-compare: 1.4.0 - ts-api-utils: 1.3.0(typescript@5.6.2) + ts-api-utils: 1.4.0(typescript@5.6.3) optionalDependencies: - typescript: 5.6.2 + typescript: 5.6.3 transitivePeerDependencies: - supports-color - '@typescript-eslint/parser@8.8.1(eslint@9.12.0)(typescript@5.6.2)': + '@typescript-eslint/parser@8.12.2(eslint@9.13.0)(typescript@5.6.3)': dependencies: - '@typescript-eslint/scope-manager': 8.8.1 - '@typescript-eslint/types': 8.8.1 - '@typescript-eslint/typescript-estree': 8.8.1(typescript@5.6.2) - '@typescript-eslint/visitor-keys': 8.8.1 + '@typescript-eslint/scope-manager': 8.12.2 + '@typescript-eslint/types': 8.12.2 + '@typescript-eslint/typescript-estree': 8.12.2(typescript@5.6.3) + '@typescript-eslint/visitor-keys': 8.12.2 debug: 4.3.7 - eslint: 9.12.0 + eslint: 9.13.0 optionalDependencies: - typescript: 5.6.2 + typescript: 5.6.3 transitivePeerDependencies: - supports-color - '@typescript-eslint/scope-manager@8.8.1': + '@typescript-eslint/scope-manager@8.12.2': dependencies: - '@typescript-eslint/types': 8.8.1 - '@typescript-eslint/visitor-keys': 8.8.1 + '@typescript-eslint/types': 8.12.2 + '@typescript-eslint/visitor-keys': 8.12.2 - '@typescript-eslint/type-utils@8.8.1(eslint@9.12.0)(typescript@5.6.2)': + '@typescript-eslint/type-utils@8.12.2(eslint@9.13.0)(typescript@5.6.3)': dependencies: - '@typescript-eslint/typescript-estree': 8.8.1(typescript@5.6.2) - '@typescript-eslint/utils': 8.8.1(eslint@9.12.0)(typescript@5.6.2) + '@typescript-eslint/typescript-estree': 8.12.2(typescript@5.6.3) + '@typescript-eslint/utils': 8.12.2(eslint@9.13.0)(typescript@5.6.3) debug: 4.3.7 - ts-api-utils: 1.3.0(typescript@5.6.2) + ts-api-utils: 1.4.0(typescript@5.6.3) optionalDependencies: - typescript: 5.6.2 + typescript: 5.6.3 transitivePeerDependencies: - eslint - supports-color - '@typescript-eslint/types@8.8.1': {} + '@typescript-eslint/types@8.12.2': {} - '@typescript-eslint/typescript-estree@8.8.1(typescript@5.6.2)': + '@typescript-eslint/typescript-estree@8.12.2(typescript@5.6.3)': dependencies: - '@typescript-eslint/types': 8.8.1 - '@typescript-eslint/visitor-keys': 8.8.1 + '@typescript-eslint/types': 8.12.2 + '@typescript-eslint/visitor-keys': 8.12.2 debug: 4.3.7 fast-glob: 3.3.2 is-glob: 4.0.3 minimatch: 9.0.5 semver: 7.6.3 - ts-api-utils: 1.3.0(typescript@5.6.2) + ts-api-utils: 1.4.0(typescript@5.6.3) optionalDependencies: - typescript: 5.6.2 + typescript: 5.6.3 transitivePeerDependencies: - supports-color - '@typescript-eslint/utils@8.8.1(eslint@9.12.0)(typescript@5.6.2)': + '@typescript-eslint/utils@8.12.2(eslint@9.13.0)(typescript@5.6.3)': dependencies: - '@eslint-community/eslint-utils': 4.4.0(eslint@9.12.0) - '@typescript-eslint/scope-manager': 8.8.1 - '@typescript-eslint/types': 8.8.1 - '@typescript-eslint/typescript-estree': 8.8.1(typescript@5.6.2) - eslint: 9.12.0 + '@eslint-community/eslint-utils': 4.4.1(eslint@9.13.0) + '@typescript-eslint/scope-manager': 8.12.2 + '@typescript-eslint/types': 8.12.2 + '@typescript-eslint/typescript-estree': 8.12.2(typescript@5.6.3) + eslint: 9.13.0 transitivePeerDependencies: - supports-color - typescript - '@typescript-eslint/visitor-keys@8.8.1': + '@typescript-eslint/visitor-keys@8.12.2': dependencies: - '@typescript-eslint/types': 8.8.1 + '@typescript-eslint/types': 8.12.2 eslint-visitor-keys: 3.4.3 - acorn-jsx@5.3.2(acorn@8.12.1): + acorn-jsx@5.3.2(acorn@8.14.0): dependencies: - acorn: 8.12.1 + acorn: 8.14.0 - acorn@8.12.1: {} + acorn@8.14.0: {} ajv@6.12.6: dependencies: @@ -2263,10 +2227,6 @@ snapshots: ansi-regex@5.0.1: {} - ansi-styles@3.2.1: - dependencies: - color-convert: 1.9.3 - ansi-styles@4.3.0: dependencies: color-convert: 2.0.1 @@ -2382,12 +2342,6 @@ snapshots: caniuse-lite@1.0.30001581: {} - chalk@2.4.2: - dependencies: - ansi-styles: 3.2.1 - escape-string-regexp: 1.0.5 - supports-color: 5.5.0 - chalk@4.1.2: dependencies: ansi-styles: 4.3.0 @@ -2409,29 +2363,23 @@ snapshots: collect-v8-coverage@1.0.2: {} - color-convert@1.9.3: - dependencies: - color-name: 1.1.3 - color-convert@2.0.1: dependencies: color-name: 1.1.4 - color-name@1.1.3: {} - color-name@1.1.4: {} concat-map@0.0.1: {} convert-source-map@2.0.0: {} - create-jest@29.7.0(@types/node@22.7.4): + create-jest@29.7.0(@types/node@22.8.6): dependencies: '@jest/types': 29.6.3 chalk: 4.1.2 exit: 0.1.2 graceful-fs: 4.2.11 - jest-config: 29.7.0(@types/node@22.7.4) + jest-config: 29.7.0(@types/node@22.8.6) jest-util: 29.7.0 prompts: 2.4.2 transitivePeerDependencies: @@ -2476,38 +2424,36 @@ snapshots: escalade@3.1.1: {} - escape-string-regexp@1.0.5: {} - escape-string-regexp@2.0.0: {} escape-string-regexp@4.0.0: {} - eslint-plugin-prettier@5.2.1(eslint@9.12.0)(prettier@3.3.3): + eslint-plugin-prettier@5.2.1(eslint@9.13.0)(prettier@3.3.3): dependencies: - eslint: 9.12.0 + eslint: 9.13.0 prettier: 3.3.3 prettier-linter-helpers: 1.0.0 synckit: 0.9.1 - eslint-scope@8.1.0: + eslint-scope@8.2.0: dependencies: esrecurse: 4.3.0 estraverse: 5.3.0 eslint-visitor-keys@3.4.3: {} - eslint-visitor-keys@4.1.0: {} + eslint-visitor-keys@4.2.0: {} - eslint@9.12.0: + eslint@9.13.0: dependencies: - '@eslint-community/eslint-utils': 4.4.0(eslint@9.12.0) - '@eslint-community/regexpp': 4.11.1 + '@eslint-community/eslint-utils': 4.4.1(eslint@9.13.0) + '@eslint-community/regexpp': 4.12.1 '@eslint/config-array': 0.18.0 - '@eslint/core': 0.6.0 + '@eslint/core': 0.7.0 '@eslint/eslintrc': 3.1.0 - '@eslint/js': 9.12.0 - '@eslint/plugin-kit': 0.2.0 - '@humanfs/node': 0.16.5 + '@eslint/js': 9.13.0 + '@eslint/plugin-kit': 0.2.2 + '@humanfs/node': 0.16.6 '@humanwhocodes/module-importer': 1.0.1 '@humanwhocodes/retry': 0.3.1 '@types/estree': 1.0.6 @@ -2517,9 +2463,9 @@ snapshots: cross-spawn: 7.0.3 debug: 4.3.7 escape-string-regexp: 4.0.0 - eslint-scope: 8.1.0 - eslint-visitor-keys: 4.1.0 - espree: 10.2.0 + eslint-scope: 8.2.0 + eslint-visitor-keys: 4.2.0 + espree: 10.3.0 esquery: 1.6.0 esutils: 2.0.3 fast-deep-equal: 3.1.3 @@ -2538,11 +2484,11 @@ snapshots: transitivePeerDependencies: - supports-color - espree@10.2.0: + espree@10.3.0: dependencies: - acorn: 8.12.1 - acorn-jsx: 5.3.2(acorn@8.12.1) - eslint-visitor-keys: 4.1.0 + acorn: 8.14.0 + acorn-jsx: 5.3.2(acorn@8.14.0) + eslint-visitor-keys: 4.2.0 esprima@4.0.1: {} @@ -2677,8 +2623,6 @@ snapshots: graphemer@1.4.0: {} - has-flag@3.0.0: {} - has-flag@4.0.0: {} hasown@2.0.0: @@ -2792,7 +2736,7 @@ snapshots: '@jest/expect': 29.7.0 '@jest/test-result': 29.7.0 '@jest/types': 29.6.3 - '@types/node': 22.7.4 + '@types/node': 22.8.6 chalk: 4.1.2 co: 4.6.0 dedent: 1.5.1 @@ -2812,16 +2756,16 @@ snapshots: - babel-plugin-macros - supports-color - jest-cli@29.7.0(@types/node@22.7.4): + jest-cli@29.7.0(@types/node@22.8.6): dependencies: '@jest/core': 29.7.0 '@jest/test-result': 29.7.0 '@jest/types': 29.6.3 chalk: 4.1.2 - create-jest: 29.7.0(@types/node@22.7.4) + create-jest: 29.7.0(@types/node@22.8.6) exit: 0.1.2 import-local: 3.1.0 - jest-config: 29.7.0(@types/node@22.7.4) + jest-config: 29.7.0(@types/node@22.8.6) jest-util: 29.7.0 jest-validate: 29.7.0 yargs: 17.7.2 @@ -2831,7 +2775,7 @@ snapshots: - supports-color - ts-node - jest-config@29.7.0(@types/node@22.7.4): + jest-config@29.7.0(@types/node@22.8.6): dependencies: '@babel/core': 7.23.9 '@jest/test-sequencer': 29.7.0 @@ -2856,7 +2800,7 @@ snapshots: slash: 3.0.0 strip-json-comments: 3.1.1 optionalDependencies: - '@types/node': 22.7.4 + '@types/node': 22.8.6 transitivePeerDependencies: - babel-plugin-macros - supports-color @@ -2885,7 +2829,7 @@ snapshots: '@jest/environment': 29.7.0 '@jest/fake-timers': 29.7.0 '@jest/types': 29.6.3 - '@types/node': 22.7.4 + '@types/node': 22.8.6 jest-mock: 29.7.0 jest-util: 29.7.0 @@ -2895,7 +2839,7 @@ snapshots: dependencies: '@jest/types': 29.6.3 '@types/graceful-fs': 4.1.9 - '@types/node': 22.7.4 + '@types/node': 22.8.6 anymatch: 3.1.3 fb-watchman: 2.0.2 graceful-fs: 4.2.11 @@ -2921,7 +2865,7 @@ snapshots: jest-message-util@29.7.0: dependencies: - '@babel/code-frame': 7.24.7 + '@babel/code-frame': 7.26.2 '@jest/types': 29.6.3 '@types/stack-utils': 2.0.3 chalk: 4.1.2 @@ -2934,7 +2878,7 @@ snapshots: jest-mock@29.7.0: dependencies: '@jest/types': 29.6.3 - '@types/node': 22.7.4 + '@types/node': 22.8.6 jest-util: 29.7.0 jest-pnp-resolver@1.2.3(jest-resolve@29.7.0): @@ -2969,7 +2913,7 @@ snapshots: '@jest/test-result': 29.7.0 '@jest/transform': 29.7.0 '@jest/types': 29.6.3 - '@types/node': 22.7.4 + '@types/node': 22.8.6 chalk: 4.1.2 emittery: 0.13.1 graceful-fs: 4.2.11 @@ -2997,7 +2941,7 @@ snapshots: '@jest/test-result': 29.7.0 '@jest/transform': 29.7.0 '@jest/types': 29.6.3 - '@types/node': 22.7.4 + '@types/node': 22.8.6 chalk: 4.1.2 cjs-module-lexer: 1.2.3 collect-v8-coverage: 1.0.2 @@ -3043,7 +2987,7 @@ snapshots: jest-util@29.7.0: dependencies: '@jest/types': 29.6.3 - '@types/node': 22.7.4 + '@types/node': 22.8.6 chalk: 4.1.2 ci-info: 3.9.0 graceful-fs: 4.2.11 @@ -3062,7 +3006,7 @@ snapshots: dependencies: '@jest/test-result': 29.7.0 '@jest/types': 29.6.3 - '@types/node': 22.7.4 + '@types/node': 22.8.6 ansi-escapes: 4.3.2 chalk: 4.1.2 emittery: 0.13.1 @@ -3071,17 +3015,17 @@ snapshots: jest-worker@29.7.0: dependencies: - '@types/node': 22.7.4 + '@types/node': 22.8.6 jest-util: 29.7.0 merge-stream: 2.0.0 supports-color: 8.1.1 - jest@29.7.0(@types/node@22.7.4): + jest@29.7.0(@types/node@22.8.6): dependencies: '@jest/core': 29.7.0 '@jest/types': 29.6.3 import-local: 3.1.0 - jest-cli: 29.7.0(@types/node@22.7.4) + jest-cli: 29.7.0(@types/node@22.8.6) transitivePeerDependencies: - '@types/node' - babel-plugin-macros @@ -3237,7 +3181,7 @@ snapshots: parse-json@5.2.0: dependencies: - '@babel/code-frame': 7.24.7 + '@babel/code-frame': 7.26.2 error-ex: 1.3.2 json-parse-even-better-errors: 2.3.1 lines-and-columns: 1.2.4 @@ -3250,7 +3194,7 @@ snapshots: path-parse@1.0.7: {} - picocolors@1.1.0: {} + picocolors@1.1.1: {} picomatch@2.3.1: {} @@ -3363,10 +3307,6 @@ snapshots: strip-json-comments@3.1.1: {} - supports-color@5.5.0: - dependencies: - has-flag: 3.0.0 - supports-color@7.2.0: dependencies: has-flag: 4.0.0 @@ -3398,22 +3338,22 @@ snapshots: dependencies: is-number: 7.0.0 - ts-api-utils@1.3.0(typescript@5.6.2): + ts-api-utils@1.4.0(typescript@5.6.3): dependencies: - typescript: 5.6.2 + typescript: 5.6.3 - ts-jest@29.2.5(@babel/core@7.23.9)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.23.9))(jest@29.7.0(@types/node@22.7.4))(typescript@5.6.2): + ts-jest@29.2.5(@babel/core@7.23.9)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.23.9))(jest@29.7.0(@types/node@22.8.6))(typescript@5.6.3): dependencies: bs-logger: 0.2.6 ejs: 3.1.10 fast-json-stable-stringify: 2.1.0 - jest: 29.7.0(@types/node@22.7.4) + jest: 29.7.0(@types/node@22.8.6) jest-util: 29.7.0 json5: 2.2.3 lodash.memoize: 4.1.2 make-error: 1.3.6 semver: 7.6.3 - typescript: 5.6.2 + typescript: 5.6.3 yargs-parser: 21.1.1 optionalDependencies: '@babel/core': 7.23.9 @@ -3431,18 +3371,18 @@ snapshots: type-fest@0.21.3: {} - typescript-eslint@8.8.1(eslint@9.12.0)(typescript@5.6.2): + typescript-eslint@8.12.2(eslint@9.13.0)(typescript@5.6.3): dependencies: - '@typescript-eslint/eslint-plugin': 8.8.1(@typescript-eslint/parser@8.8.1(eslint@9.12.0)(typescript@5.6.2))(eslint@9.12.0)(typescript@5.6.2) - '@typescript-eslint/parser': 8.8.1(eslint@9.12.0)(typescript@5.6.2) - '@typescript-eslint/utils': 8.8.1(eslint@9.12.0)(typescript@5.6.2) + '@typescript-eslint/eslint-plugin': 8.12.2(@typescript-eslint/parser@8.12.2(eslint@9.13.0)(typescript@5.6.3))(eslint@9.13.0)(typescript@5.6.3) + '@typescript-eslint/parser': 8.12.2(eslint@9.13.0)(typescript@5.6.3) + '@typescript-eslint/utils': 8.12.2(eslint@9.13.0)(typescript@5.6.3) optionalDependencies: - typescript: 5.6.2 + typescript: 5.6.3 transitivePeerDependencies: - eslint - supports-color - typescript@5.6.2: {} + typescript@5.6.3: {} undici-types@6.19.8: {} @@ -3450,7 +3390,7 @@ snapshots: dependencies: browserslist: 4.22.3 escalade: 3.1.1 - picocolors: 1.1.0 + picocolors: 1.1.1 uri-js@4.4.1: dependencies: From 556191ef1650f38240097473506d24be81ab0c90 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 31 Oct 2024 23:02:50 -0400 Subject: [PATCH 05/19] chore(deps): update docker (#5154) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .woodpecker.yml | 2 +- docker/Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index a2124c1cc..b1ab18c97 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -2,7 +2,7 @@ # See https://github.com/woodpecker-ci/woodpecker/issues/1677 variables: - - &rust_image "rust:1.81" + - &rust_image "rust:1.82" - &rust_nightly_image "rustlang/rust:nightly" - &install_pnpm "corepack enable pnpm" - &install_binstall "wget -O- https://github.com/cargo-bins/cargo-binstall/releases/latest/download/cargo-binstall-x86_64-unknown-linux-musl.tgz | tar -xvz -C /usr/local/cargo/bin" diff --git a/docker/Dockerfile b/docker/Dockerfile index 9701b4ad6..9e6bb23b4 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,4 +1,4 @@ -# syntax=docker/dockerfile:1.10 +# syntax=docker/dockerfile:1.11 ARG RUST_VERSION=1.81 ARG CARGO_BUILD_FEATURES=default ARG RUST_RELEASE_MODE=debug From 30951a37b6b9d9172084e8737e12127f01902181 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Fri, 1 Nov 2024 09:34:12 -0400 Subject: [PATCH 06/19] Revert "chore(deps): update docker (#5154)" (#5156) This reverts commit 556191ef1650f38240097473506d24be81ab0c90. --- .woodpecker.yml | 2 +- docker/Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index b1ab18c97..a2124c1cc 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -2,7 +2,7 @@ # See https://github.com/woodpecker-ci/woodpecker/issues/1677 variables: - - &rust_image "rust:1.82" + - &rust_image "rust:1.81" - &rust_nightly_image "rustlang/rust:nightly" - &install_pnpm "corepack enable pnpm" - &install_binstall "wget -O- https://github.com/cargo-bins/cargo-binstall/releases/latest/download/cargo-binstall-x86_64-unknown-linux-musl.tgz | tar -xvz -C /usr/local/cargo/bin" diff --git a/docker/Dockerfile b/docker/Dockerfile index 9e6bb23b4..9701b4ad6 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,4 +1,4 @@ -# syntax=docker/dockerfile:1.11 +# syntax=docker/dockerfile:1.10 ARG RUST_VERSION=1.81 ARG CARGO_BUILD_FEATURES=default ARG RUST_RELEASE_MODE=debug From 02ba54c58964cc9b7d4928241716a6e0942c029b Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 1 Nov 2024 09:57:33 -0400 Subject: [PATCH 07/19] chore(deps): update node.js to v22 (#5155) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .woodpecker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index a2124c1cc..885796cac 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -215,7 +215,7 @@ steps: when: *slow_check_paths run_federation_tests: - image: node:20-bookworm-slim + image: node:22-bookworm-slim environment: LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432 DO_WRITE_HOSTS_FILE: "1" From 18bf9843bce48b33cf9b350724520665279e4edb Mon Sep 17 00:00:00 2001 From: Dessalines Date: Mon, 4 Nov 2024 04:44:58 -0500 Subject: [PATCH 08/19] Fixing LemmyError imports. (#5157) --- crates/api/src/post/get_link_metadata.rs | 5 +---- crates/api/src/site/registration_applications/tests.rs | 5 ++++- crates/api_common/src/lib.rs | 2 +- crates/api_crud/src/post/mod.rs | 2 +- crates/apub/src/activity_lists.rs | 2 +- crates/apub/src/api/resolve_object.rs | 2 +- crates/apub/src/http/community.rs | 2 +- crates/apub/src/http/person.rs | 2 +- crates/apub/src/protocol/objects/note.rs | 5 ++++- crates/db_schema/src/impls/captcha_answer.rs | 2 +- crates/db_schema/src/impls/community_block.rs | 2 +- crates/db_schema/src/impls/instance_block.rs | 2 +- crates/db_schema/src/impls/login_token.rs | 2 +- crates/db_schema/src/impls/person.rs | 2 +- crates/db_schema/src/impls/person_block.rs | 2 +- crates/db_schema/src/impls/site.rs | 2 +- crates/db_views/src/site_view.rs | 2 +- crates/db_views_actor/src/community_moderator_view.rs | 2 +- crates/db_views_actor/src/community_person_ban_view.rs | 2 +- crates/db_views_actor/src/community_view.rs | 2 +- crates/utils/src/lib.rs | 1 - crates/utils/src/utils/markdown/mod.rs | 2 +- crates/utils/tests/test_errors_used.rs | 2 +- src/scheduled_tasks.rs | 5 ++++- 24 files changed, 32 insertions(+), 27 deletions(-) diff --git a/crates/api/src/post/get_link_metadata.rs b/crates/api/src/post/get_link_metadata.rs index e469b51c7..a777cab17 100644 --- a/crates/api/src/post/get_link_metadata.rs +++ b/crates/api/src/post/get_link_metadata.rs @@ -5,10 +5,7 @@ use lemmy_api_common::{ request::fetch_link_metadata, }; use lemmy_db_views::structs::LocalUserView; -use lemmy_utils::{ - error::{LemmyErrorExt, LemmyResult}, - LemmyErrorType, -}; +use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult}; use url::Url; #[tracing::instrument(skip(context))] diff --git a/crates/api/src/site/registration_applications/tests.rs b/crates/api/src/site/registration_applications/tests.rs index 022cbf236..bdfb1535e 100644 --- a/crates/api/src/site/registration_applications/tests.rs +++ b/crates/api/src/site/registration_applications/tests.rs @@ -31,7 +31,10 @@ use lemmy_db_schema::{ RegistrationMode, }; use lemmy_db_views::structs::LocalUserView; -use lemmy_utils::{error::LemmyResult, LemmyErrorType, CACHE_DURATION_API}; +use lemmy_utils::{ + error::{LemmyErrorType, LemmyResult}, + CACHE_DURATION_API, +}; use serial_test::serial; async fn create_test_site(context: &Data) -> LemmyResult<(Instance, LocalUserView)> { diff --git a/crates/api_common/src/lib.rs b/crates/api_common/src/lib.rs index 68eeadecc..6e09d904d 100644 --- a/crates/api_common/src/lib.rs +++ b/crates/api_common/src/lib.rs @@ -26,7 +26,7 @@ pub extern crate lemmy_db_views_actor; pub extern crate lemmy_db_views_moderator; pub extern crate lemmy_utils; -pub use lemmy_utils::LemmyErrorType; +pub use lemmy_utils::error::LemmyErrorType; use serde::{Deserialize, Serialize}; use std::{cmp::min, time::Duration}; diff --git a/crates/api_crud/src/post/mod.rs b/crates/api_crud/src/post/mod.rs index 95df9663c..5db0ad5d0 100644 --- a/crates/api_crud/src/post/mod.rs +++ b/crates/api_crud/src/post/mod.rs @@ -2,7 +2,7 @@ use chrono::{DateTime, TimeZone, Utc}; use lemmy_api_common::context::LemmyContext; use lemmy_db_schema::source::post::Post; use lemmy_db_views::structs::LocalUserView; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; pub mod create; pub mod delete; diff --git a/crates/apub/src/activity_lists.rs b/crates/apub/src/activity_lists.rs index 9262236d8..1ba31b9b4 100644 --- a/crates/apub/src/activity_lists.rs +++ b/crates/apub/src/activity_lists.rs @@ -26,7 +26,7 @@ use crate::{ }; use activitypub_federation::{config::Data, traits::ActivityHandler}; use lemmy_api_common::context::LemmyContext; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; use serde::{Deserialize, Serialize}; use url::Url; diff --git a/crates/apub/src/api/resolve_object.rs b/crates/apub/src/api/resolve_object.rs index d9d50e69e..04d489592 100644 --- a/crates/apub/src/api/resolve_object.rs +++ b/crates/apub/src/api/resolve_object.rs @@ -86,7 +86,7 @@ mod tests { traits::Crud, }; use lemmy_db_views::structs::LocalUserView; - use lemmy_utils::{error::LemmyResult, LemmyErrorType}; + use lemmy_utils::error::{LemmyErrorType, LemmyResult}; use serial_test::serial; #[tokio::test] diff --git a/crates/apub/src/http/community.rs b/crates/apub/src/http/community.rs index 37482aedb..2516020d3 100644 --- a/crates/apub/src/http/community.rs +++ b/crates/apub/src/http/community.rs @@ -15,7 +15,7 @@ use activitypub_federation::{ use actix_web::{web, HttpResponse}; use lemmy_api_common::context::LemmyContext; use lemmy_db_schema::{source::community::Community, traits::ApubActor}; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; use serde::Deserialize; #[derive(Deserialize, Clone)] diff --git a/crates/apub/src/http/person.rs b/crates/apub/src/http/person.rs index 0f628c497..f8afceb94 100644 --- a/crates/apub/src/http/person.rs +++ b/crates/apub/src/http/person.rs @@ -7,7 +7,7 @@ use activitypub_federation::{config::Data, traits::Object}; use actix_web::{web, HttpResponse}; use lemmy_api_common::{context::LemmyContext, utils::generate_outbox_url}; use lemmy_db_schema::{source::person::Person, traits::ApubActor}; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; use serde::Deserialize; #[derive(Deserialize)] diff --git a/crates/apub/src/protocol/objects/note.rs b/crates/apub/src/protocol/objects/note.rs index 21b5220f5..fc38b9b5e 100644 --- a/crates/apub/src/protocol/objects/note.rs +++ b/crates/apub/src/protocol/objects/note.rs @@ -24,7 +24,10 @@ use lemmy_db_schema::{ source::{community::Community, post::Post}, traits::Crud, }; -use lemmy_utils::{error::LemmyResult, LemmyErrorType, MAX_COMMENT_DEPTH_LIMIT}; +use lemmy_utils::{ + error::{LemmyErrorType, LemmyResult}, + MAX_COMMENT_DEPTH_LIMIT, +}; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; use url::Url; diff --git a/crates/db_schema/src/impls/captcha_answer.rs b/crates/db_schema/src/impls/captcha_answer.rs index d7183e4fb..e7ba86d39 100644 --- a/crates/db_schema/src/impls/captcha_answer.rs +++ b/crates/db_schema/src/impls/captcha_answer.rs @@ -13,7 +13,7 @@ use diesel::{ QueryDsl, }; use diesel_async::RunQueryDsl; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; impl CaptchaAnswer { pub async fn insert(pool: &mut DbPool<'_>, captcha: &CaptchaAnswerForm) -> Result { diff --git a/crates/db_schema/src/impls/community_block.rs b/crates/db_schema/src/impls/community_block.rs index cd541cd8b..c78953d27 100644 --- a/crates/db_schema/src/impls/community_block.rs +++ b/crates/db_schema/src/impls/community_block.rs @@ -16,7 +16,7 @@ use diesel::{ QueryDsl, }; use diesel_async::RunQueryDsl; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; impl CommunityBlock { pub async fn read( diff --git a/crates/db_schema/src/impls/instance_block.rs b/crates/db_schema/src/impls/instance_block.rs index 1eb6e8f04..1b70f0e08 100644 --- a/crates/db_schema/src/impls/instance_block.rs +++ b/crates/db_schema/src/impls/instance_block.rs @@ -16,7 +16,7 @@ use diesel::{ QueryDsl, }; use diesel_async::RunQueryDsl; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; impl InstanceBlock { pub async fn read( diff --git a/crates/db_schema/src/impls/login_token.rs b/crates/db_schema/src/impls/login_token.rs index c8c44c506..f4f7a7aae 100644 --- a/crates/db_schema/src/impls/login_token.rs +++ b/crates/db_schema/src/impls/login_token.rs @@ -7,7 +7,7 @@ use crate::{ }; use diesel::{delete, dsl::exists, insert_into, result::Error, select}; use diesel_async::RunQueryDsl; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; impl LoginToken { pub async fn create(pool: &mut DbPool<'_>, form: LoginTokenCreateForm) -> Result { diff --git a/crates/db_schema/src/impls/person.rs b/crates/db_schema/src/impls/person.rs index a5f8ae1a0..fb287ef77 100644 --- a/crates/db_schema/src/impls/person.rs +++ b/crates/db_schema/src/impls/person.rs @@ -21,7 +21,7 @@ use diesel::{ QueryDsl, }; use diesel_async::RunQueryDsl; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; #[async_trait] impl Crud for Person { diff --git a/crates/db_schema/src/impls/person_block.rs b/crates/db_schema/src/impls/person_block.rs index 7f2286616..44c83b3f8 100644 --- a/crates/db_schema/src/impls/person_block.rs +++ b/crates/db_schema/src/impls/person_block.rs @@ -17,7 +17,7 @@ use diesel::{ QueryDsl, }; use diesel_async::RunQueryDsl; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; impl PersonBlock { pub async fn read( diff --git a/crates/db_schema/src/impls/site.rs b/crates/db_schema/src/impls/site.rs index 8f57647a3..e993639fa 100644 --- a/crates/db_schema/src/impls/site.rs +++ b/crates/db_schema/src/impls/site.rs @@ -10,7 +10,7 @@ use crate::{ }; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, OptionalExtension, QueryDsl}; use diesel_async::RunQueryDsl; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; use url::Url; #[async_trait] diff --git a/crates/db_views/src/site_view.rs b/crates/db_views/src/site_view.rs index 6014ad964..ed9aeb498 100644 --- a/crates/db_views/src/site_view.rs +++ b/crates/db_views/src/site_view.rs @@ -5,7 +5,7 @@ use lemmy_db_schema::{ schema::{local_site, local_site_rate_limit, site, site_aggregates}, utils::{get_conn, DbPool}, }; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; impl SiteView { pub async fn read_local(pool: &mut DbPool<'_>) -> LemmyResult { diff --git a/crates/db_views_actor/src/community_moderator_view.rs b/crates/db_views_actor/src/community_moderator_view.rs index ebcdcbd25..7126af1f6 100644 --- a/crates/db_views_actor/src/community_moderator_view.rs +++ b/crates/db_views_actor/src/community_moderator_view.rs @@ -8,7 +8,7 @@ use lemmy_db_schema::{ source::local_user::LocalUser, utils::{get_conn, DbPool}, }; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; impl CommunityModeratorView { pub async fn check_is_community_moderator( diff --git a/crates/db_views_actor/src/community_person_ban_view.rs b/crates/db_views_actor/src/community_person_ban_view.rs index 5543222f3..9bfa0704c 100644 --- a/crates/db_views_actor/src/community_person_ban_view.rs +++ b/crates/db_views_actor/src/community_person_ban_view.rs @@ -11,7 +11,7 @@ use lemmy_db_schema::{ schema::community_person_ban, utils::{get_conn, DbPool}, }; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; impl CommunityPersonBanView { pub async fn check( diff --git a/crates/db_views_actor/src/community_view.rs b/crates/db_views_actor/src/community_view.rs index 9ff6fadce..de749fff3 100644 --- a/crates/db_views_actor/src/community_view.rs +++ b/crates/db_views_actor/src/community_view.rs @@ -35,7 +35,7 @@ use lemmy_db_schema::{ ListingType, PostSortType, }; -use lemmy_utils::{error::LemmyResult, LemmyErrorType}; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; fn queries<'a>() -> Queries< impl ReadFn<'a, CommunityView, (CommunityId, Option<&'a LocalUser>, bool)>, diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs index 7f0691496..1e0cbefbf 100644 --- a/crates/utils/src/lib.rs +++ b/crates/utils/src/lib.rs @@ -13,7 +13,6 @@ cfg_if! { } pub mod error; -pub use error::LemmyErrorType; use std::time::Duration; pub type ConnectionId = usize; diff --git a/crates/utils/src/utils/markdown/mod.rs b/crates/utils/src/utils/markdown/mod.rs index a51b507ce..9d34e8a69 100644 --- a/crates/utils/src/utils/markdown/mod.rs +++ b/crates/utils/src/utils/markdown/mod.rs @@ -1,4 +1,4 @@ -use crate::{error::LemmyResult, LemmyErrorType}; +use crate::error::{LemmyErrorType, LemmyResult}; use markdown_it::MarkdownIt; use regex::RegexSet; use std::sync::LazyLock; diff --git a/crates/utils/tests/test_errors_used.rs b/crates/utils/tests/test_errors_used.rs index d0dec489a..bfd70bdad 100644 --- a/crates/utils/tests/test_errors_used.rs +++ b/crates/utils/tests/test_errors_used.rs @@ -1,4 +1,4 @@ -use lemmy_utils::LemmyErrorType; +use lemmy_utils::error::LemmyErrorType; use std::{env::current_dir, process::Command}; use strum::IntoEnumIterator; diff --git a/src/scheduled_tasks.rs b/src/scheduled_tasks.rs index 75942d3dd..e7c8a676c 100644 --- a/src/scheduled_tasks.rs +++ b/src/scheduled_tasks.rs @@ -609,7 +609,10 @@ mod tests { use crate::scheduled_tasks::build_update_instance_form; use lemmy_api_common::request::client_builder; - use lemmy_utils::{error::LemmyResult, settings::structs::Settings, LemmyErrorType}; + use lemmy_utils::{ + error::{LemmyErrorType, LemmyResult}, + settings::structs::Settings, + }; use pretty_assertions::assert_eq; use reqwest_middleware::ClientBuilder; use serial_test::serial; From 4690aff1e58311aa323a427e1cd620b9aa43dd0d Mon Sep 17 00:00:00 2001 From: Nutomic Date: Mon, 4 Nov 2024 14:16:54 +0100 Subject: [PATCH 09/19] Run analyze after changing post.url type (ref #4983) (#5148) * Run analyze after changing post.url type (ref #4983) * rename back --------- Co-authored-by: Dessalines --- .../2024-08-03-155932_increase_post_url_max_length/down.sql | 2 ++ .../2024-08-03-155932_increase_post_url_max_length/up.sql | 2 ++ 2 files changed, 4 insertions(+) diff --git a/migrations/2024-08-03-155932_increase_post_url_max_length/down.sql b/migrations/2024-08-03-155932_increase_post_url_max_length/down.sql index d25918578..7e4feef3d 100644 --- a/migrations/2024-08-03-155932_increase_post_url_max_length/down.sql +++ b/migrations/2024-08-03-155932_increase_post_url_max_length/down.sql @@ -1,3 +1,5 @@ ALTER TABLE post ALTER COLUMN url TYPE varchar(512); +ANALYZE post (url); + diff --git a/migrations/2024-08-03-155932_increase_post_url_max_length/up.sql b/migrations/2024-08-03-155932_increase_post_url_max_length/up.sql index 7c6818d22..8e5a3a9ce 100644 --- a/migrations/2024-08-03-155932_increase_post_url_max_length/up.sql +++ b/migrations/2024-08-03-155932_increase_post_url_max_length/up.sql @@ -3,3 +3,5 @@ ALTER TABLE post ALTER COLUMN url TYPE varchar(2000); +ANALYZE post (url); + From 9f4038756920de340f866abf3cad042d1ee8eac7 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Tue, 5 Nov 2024 11:45:58 -0500 Subject: [PATCH 10/19] Fixing sample image to fix unit tests. (#5167) Apparently yahoo.com doesnt want to return metatags for my local CI runners anymore. --- api_tests/src/shared.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api_tests/src/shared.ts b/api_tests/src/shared.ts index 8ec4b29ed..017dad903 100644 --- a/api_tests/src/shared.ts +++ b/api_tests/src/shared.ts @@ -83,7 +83,7 @@ export const fetchFunction = fetch; export const imageFetchLimit = 50; export const sampleImage = "https://i.pinimg.com/originals/df/5f/5b/df5f5b1b174a2b4b6026cc6c8f9395c1.jpg"; -export const sampleSite = "https://yahoo.com"; +export const sampleSite = "https://google.com"; export const alphaUrl = "http://127.0.0.1:8541"; export const betaUrl = "http://127.0.0.1:8551"; From 298c8fa52176b1a263ce9b4252e88e6526cc5c30 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Tue, 5 Nov 2024 12:09:25 -0500 Subject: [PATCH 11/19] Add filter to hide posts with comments. (#5158) * Add filter to hide posts with comments. - Useful for Q/A type communities. - Fixes #1106 * Changing to no_comments_only --- crates/api_common/src/post.rs | 2 ++ crates/apub/src/api/list_posts.rs | 2 ++ crates/db_views/src/post_view.rs | 36 +++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/crates/api_common/src/post.rs b/crates/api_common/src/post.rs index fa45459e2..22d5e1431 100644 --- a/crates/api_common/src/post.rs +++ b/crates/api_common/src/post.rs @@ -85,6 +85,8 @@ pub struct GetPosts { pub show_read: Option, /// If true, then show the nsfw posts (even if your user setting is to hide them) pub show_nsfw: Option, + /// If true, then only show posts with no comments + pub no_comments_only: Option, pub page_cursor: Option, } diff --git a/crates/apub/src/api/list_posts.rs b/crates/apub/src/api/list_posts.rs index d75a82d3b..cdf24dbaa 100644 --- a/crates/apub/src/api/list_posts.rs +++ b/crates/apub/src/api/list_posts.rs @@ -42,6 +42,7 @@ pub async fn list_posts( let show_hidden = data.show_hidden; let show_read = data.show_read; let show_nsfw = data.show_nsfw; + let no_comments_only = data.no_comments_only; let liked_only = data.liked_only; let disliked_only = data.disliked_only; @@ -82,6 +83,7 @@ pub async fn list_posts( show_hidden, show_read, show_nsfw, + no_comments_only, ..Default::default() } .list(&local_site.site, &mut context.pool()) diff --git a/crates/db_views/src/post_view.rs b/crates/db_views/src/post_view.rs index 4fa2222ae..13520f1cf 100644 --- a/crates/db_views/src/post_view.rs +++ b/crates/db_views/src/post_view.rs @@ -401,6 +401,11 @@ fn queries<'a>() -> Queries< query = query.filter(person::bot_account.eq(false)); }; + // Filter to show only posts with no comments + if options.no_comments_only.unwrap_or_default() { + query = query.filter(post_aggregates::comments.eq(0)); + }; + // If its saved only, then filter, and order by the saved time, not the comment creation time. if options.saved_only.unwrap_or_default() { query = query @@ -617,6 +622,7 @@ pub struct PostQuery<'a> { pub show_hidden: Option, pub show_read: Option, pub show_nsfw: Option, + pub no_comments_only: Option, } impl<'a> PostQuery<'a> { @@ -1988,4 +1994,34 @@ mod tests { cleanup(data, pool).await } + + #[tokio::test] + #[serial] + async fn post_listings_no_comments_only() -> LemmyResult<()> { + let pool = &build_db_pool().await?; + let pool = &mut pool.into(); + let data = init_data(pool).await?; + + // Create a comment for a post + let comment_form = CommentInsertForm::new( + data.local_user_view.person.id, + data.inserted_post.id, + "a comment".to_owned(), + ); + Comment::create(pool, &comment_form, None).await?; + + // Make sure it doesnt come back with the no_comments option + let post_listings_no_comments = PostQuery { + sort: Some(PostSortType::New), + no_comments_only: Some(true), + local_user: Some(&data.local_user_view.local_user), + ..Default::default() + } + .list(&data.site, pool) + .await?; + + assert_eq!(vec![POST_BY_BOT], names(&post_listings_no_comments)); + + cleanup(data, pool).await + } } From d162ec1638dadd7b8f6a7a3b0c0443db05c8e270 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Wed, 6 Nov 2024 04:24:49 -0500 Subject: [PATCH 12/19] Removing strip = true from release profile. (#5166) * Adding abort on panic to release profile to make binary smaller. * Remove strip and panic from release profile. --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 5523dcfd6..99e6a53e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,10 +24,10 @@ doctest = false [lints] workspace = true +# See https://github.com/johnthagen/min-sized-rust for additional optimizations [profile.release] debug = 0 lto = "fat" -strip = true # Automatically strip symbols from the binary. opt-level = 3 # Optimize for speed, not size. codegen-units = 1 # Reduce parallel code generation. From df664d9d9ae3f40b70e924b77758cd2396053071 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Wed, 6 Nov 2024 09:50:13 -0500 Subject: [PATCH 13/19] Upgrading ts_rs to 10.0.0 (#5163) * Upgrading ts_rs to 10.0.0 * Adding ts_option directives, and woodpecker test. * Fixing ts_options. --- .woodpecker.yml | 9 ++ Cargo.lock | 17 +-- Cargo.toml | 3 +- crates/api_common/src/comment.rs | 24 ++++ crates/api_common/src/community.rs | 32 +++++ crates/api_common/src/custom_emoji.rs | 4 + crates/api_common/src/oauth_provider.rs | 18 ++- crates/api_common/src/person.rs | 62 ++++++++ crates/api_common/src/post.rs | 48 +++++++ crates/api_common/src/private_message.rs | 7 + crates/api_common/src/site.rs | 133 ++++++++++++++++++ crates/api_common/src/tagline.rs | 2 + crates/api_common/src/utils.rs | 4 +- crates/apub/src/lib.rs | 15 +- crates/db_schema/src/newtypes.rs | 16 +-- crates/db_schema/src/sensitive.rs | 19 +-- crates/db_schema/src/source/comment.rs | 1 + crates/db_schema/src/source/comment_report.rs | 2 + crates/db_schema/src/source/community.rs | 5 + crates/db_schema/src/source/custom_emoji.rs | 1 + .../src/source/federation_queue_state.rs | 3 + crates/db_schema/src/source/images.rs | 1 + crates/db_schema/src/source/instance.rs | 3 + crates/db_schema/src/source/local_site.rs | 4 + .../src/source/local_site_rate_limit.rs | 1 + .../src/source/local_site_url_blocklist.rs | 1 + crates/db_schema/src/source/local_user.rs | 1 + crates/db_schema/src/source/login_token.rs | 2 + crates/db_schema/src/source/moderator.rs | 12 ++ crates/db_schema/src/source/oauth_account.rs | 1 + crates/db_schema/src/source/oauth_provider.rs | 1 + crates/db_schema/src/source/person.rs | 7 + crates/db_schema/src/source/post.rs | 14 +- crates/db_schema/src/source/post_report.rs | 4 + .../db_schema/src/source/private_message.rs | 1 + .../src/source/private_message_report.rs | 2 + .../src/source/registration_application.rs | 2 + crates/db_schema/src/source/site.rs | 6 + crates/db_schema/src/source/tagline.rs | 1 + crates/db_views/src/structs.rs | 9 ++ crates/db_views_actor/src/structs.rs | 2 + crates/db_views_moderator/src/structs.rs | 22 +++ crates/utils/src/error.rs | 12 +- scripts/ts_bindings_check.sh | 14 ++ 44 files changed, 492 insertions(+), 56 deletions(-) create mode 100755 scripts/ts_bindings_check.sh diff --git a/.woodpecker.yml b/.woodpecker.yml index 885796cac..16cd49375 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -181,6 +181,15 @@ steps: - cargo test --workspace --no-fail-fast when: *slow_check_paths + check_ts_bindings: + image: *rust_image + environment: + CARGO_HOME: .cargo_home + commands: + - ./scripts/ts_bindings_check.sh + when: + - event: pull_request + check_diesel_migration: # TODO: use willsquire/diesel-cli image when shared libraries become optional in lemmy_server image: *rust_image diff --git a/Cargo.lock b/Cargo.lock index 491b7cc94..edf237ab3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,6 @@ # It is not intended for manual editing. version = 3 -[[package]] -name = "Inflector" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" - [[package]] name = "accept-language" version = "3.1.0" @@ -5255,22 +5249,23 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "ts-rs" -version = "7.1.1" +version = "10.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc2cae1fc5d05d47aa24b64f9a4f7cba24cdc9187a2084dd97ac57bef5eccae6" +checksum = "3a2f31991cee3dce1ca4f929a8a04fdd11fd8801aac0f2030b0fa8a0a3fef6b9" dependencies = [ "chrono", + "lazy_static", "thiserror", "ts-rs-macros", + "url", ] [[package]] name = "ts-rs-macros" -version = "7.1.1" +version = "10.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73f7f9b821696963053a89a7bd8b292dc34420aea8294d7b225274d488f3ec92" +checksum = "0ea0b99e8ec44abd6f94a18f28f7934437809dd062820797c52401298116f70e" dependencies = [ - "Inflector", "proc-macro2", "quote", "syn 2.0.77", diff --git a/Cargo.toml b/Cargo.toml index 99e6a53e2..0373c4e51 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -142,10 +142,11 @@ itertools = "0.13.0" futures = "0.3.30" http = "1.1" rosetta-i18n = "0.1.3" -ts-rs = { version = "7.1.1", features = [ +ts-rs = { version = "10.0.0", features = [ "serde-compat", "chrono-impl", "no-serde-warnings", + "url-impl", ] } rustls = { version = "0.23.12", features = ["ring"] } futures-util = "0.3.30" diff --git a/crates/api_common/src/comment.rs b/crates/api_common/src/comment.rs index 48800cf8d..e08365789 100644 --- a/crates/api_common/src/comment.rs +++ b/crates/api_common/src/comment.rs @@ -17,7 +17,9 @@ use ts_rs::TS; pub struct CreateComment { pub content: String, pub post_id: PostId, + #[cfg_attr(feature = "full", ts(optional))] pub parent_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub language_id: Option, } @@ -37,7 +39,9 @@ pub struct GetComment { /// Edit a comment. pub struct EditComment { pub comment_id: CommentId, + #[cfg_attr(feature = "full", ts(optional))] pub content: Option, + #[cfg_attr(feature = "full", ts(optional))] pub language_id: Option, } @@ -69,6 +73,7 @@ pub struct DeleteComment { pub struct RemoveComment { pub comment_id: CommentId, pub removed: bool, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, } @@ -107,17 +112,29 @@ pub struct CreateCommentLike { #[cfg_attr(feature = "full", ts(export))] /// Get a list of comments. pub struct GetComments { + #[cfg_attr(feature = "full", ts(optional))] pub type_: Option, + #[cfg_attr(feature = "full", ts(optional))] pub sort: Option, + #[cfg_attr(feature = "full", ts(optional))] pub max_depth: Option, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, + #[cfg_attr(feature = "full", ts(optional))] pub community_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub community_name: Option, + #[cfg_attr(feature = "full", ts(optional))] pub post_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub parent_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub saved_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub liked_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub disliked_only: Option, } @@ -161,12 +178,17 @@ pub struct ResolveCommentReport { #[cfg_attr(feature = "full", ts(export))] /// List comment reports. pub struct ListCommentReports { + #[cfg_attr(feature = "full", ts(optional))] pub comment_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, /// Only shows the unresolved reports + #[cfg_attr(feature = "full", ts(optional))] pub unresolved_only: Option, /// if no community is given, it returns reports for all communities moderated by the auth user + #[cfg_attr(feature = "full", ts(optional))] pub community_id: Option, } @@ -185,7 +207,9 @@ pub struct ListCommentReportsResponse { /// List comment likes. Admins-only. pub struct ListCommentLikes { pub comment_id: CommentId, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, } diff --git a/crates/api_common/src/community.rs b/crates/api_common/src/community.rs index 1def2111b..2fab2d05c 100644 --- a/crates/api_common/src/community.rs +++ b/crates/api_common/src/community.rs @@ -19,10 +19,13 @@ use ts_rs::TS; #[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "full", derive(TS))] #[cfg_attr(feature = "full", ts(export))] +// TODO make this into a tagged enum /// Get a community. Must provide either an id, or a name. pub struct GetCommunity { + #[cfg_attr(feature = "full", ts(optional))] pub id: Option, /// Example: star_trek , or star_trek@xyz.tld + #[cfg_attr(feature = "full", ts(optional))] pub name: Option, } @@ -33,6 +36,7 @@ pub struct GetCommunity { /// The community response. pub struct GetCommunityResponse { pub community_view: CommunityView, + #[cfg_attr(feature = "full", ts(optional))] pub site: Option, pub moderators: Vec, pub discussion_languages: Vec, @@ -49,18 +53,26 @@ pub struct CreateCommunity { /// A longer title. pub title: String, /// A sidebar for the community in markdown. + #[cfg_attr(feature = "full", ts(optional))] pub sidebar: Option, /// A shorter, one line description of your community. + #[cfg_attr(feature = "full", ts(optional))] pub description: Option, /// An icon URL. + #[cfg_attr(feature = "full", ts(optional))] pub icon: Option, /// A banner URL. + #[cfg_attr(feature = "full", ts(optional))] pub banner: Option, /// Whether its an NSFW community. + #[cfg_attr(feature = "full", ts(optional))] pub nsfw: Option, /// Whether to restrict posting only to moderators. + #[cfg_attr(feature = "full", ts(optional))] pub posting_restricted_to_mods: Option, + #[cfg_attr(feature = "full", ts(optional))] pub discussion_languages: Option>, + #[cfg_attr(feature = "full", ts(optional))] pub visibility: Option, } @@ -79,10 +91,15 @@ pub struct CommunityResponse { #[cfg_attr(feature = "full", ts(export))] /// Fetches a list of communities. pub struct ListCommunities { + #[cfg_attr(feature = "full", ts(optional))] pub type_: Option, + #[cfg_attr(feature = "full", ts(optional))] pub sort: Option, + #[cfg_attr(feature = "full", ts(optional))] pub show_nsfw: Option, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, } @@ -105,11 +122,14 @@ pub struct BanFromCommunity { pub ban: bool, /// Optionally remove or restore all their data. Useful for new troll accounts. /// If ban is true, then this means remove. If ban is false, it means restore. + #[cfg_attr(feature = "full", ts(optional))] pub remove_or_restore_data: Option, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, /// A time that the ban will expire, in unix epoch seconds. /// /// An i64 unix timestamp is used for a simpler API client implementation. + #[cfg_attr(feature = "full", ts(optional))] pub expires: Option, } @@ -148,20 +168,29 @@ pub struct AddModToCommunityResponse { pub struct EditCommunity { pub community_id: CommunityId, /// A longer title. + #[cfg_attr(feature = "full", ts(optional))] pub title: Option, /// A sidebar for the community in markdown. + #[cfg_attr(feature = "full", ts(optional))] pub sidebar: Option, /// A shorter, one line description of your community. + #[cfg_attr(feature = "full", ts(optional))] pub description: Option, /// An icon URL. + #[cfg_attr(feature = "full", ts(optional))] pub icon: Option, /// A banner URL. + #[cfg_attr(feature = "full", ts(optional))] pub banner: Option, /// Whether its an NSFW community. + #[cfg_attr(feature = "full", ts(optional))] pub nsfw: Option, /// Whether to restrict posting only to moderators. + #[cfg_attr(feature = "full", ts(optional))] pub posting_restricted_to_mods: Option, + #[cfg_attr(feature = "full", ts(optional))] pub discussion_languages: Option>, + #[cfg_attr(feature = "full", ts(optional))] pub visibility: Option, } @@ -173,6 +202,7 @@ pub struct EditCommunity { pub struct HideCommunity { pub community_id: CommunityId, pub hidden: bool, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, } @@ -194,6 +224,7 @@ pub struct DeleteCommunity { pub struct RemoveCommunity { pub community_id: CommunityId, pub removed: bool, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, } @@ -240,5 +271,6 @@ pub struct TransferCommunity { #[cfg_attr(feature = "full", ts(export))] /// Fetches a random community pub struct GetRandomCommunity { + #[cfg_attr(feature = "full", ts(optional))] pub type_: Option, } diff --git a/crates/api_common/src/custom_emoji.rs b/crates/api_common/src/custom_emoji.rs index 3804b71af..76bc9c9e2 100644 --- a/crates/api_common/src/custom_emoji.rs +++ b/crates/api_common/src/custom_emoji.rs @@ -62,8 +62,12 @@ pub struct ListCustomEmojisResponse { #[cfg_attr(feature = "full", ts(export))] /// Fetches a list of custom emojis. pub struct ListCustomEmojis { + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, + #[cfg_attr(feature = "full", ts(optional))] pub category: Option, + #[cfg_attr(feature = "full", ts(optional))] pub ignore_page_limits: Option, } diff --git a/crates/api_common/src/oauth_provider.rs b/crates/api_common/src/oauth_provider.rs index 14847edf1..36fef3b18 100644 --- a/crates/api_common/src/oauth_provider.rs +++ b/crates/api_common/src/oauth_provider.rs @@ -20,8 +20,11 @@ pub struct CreateOAuthProvider { pub client_id: String, pub client_secret: String, pub scopes: String, + #[cfg_attr(feature = "full", ts(optional))] pub auto_verify_email: Option, + #[cfg_attr(feature = "full", ts(optional))] pub account_linking_enabled: Option, + #[cfg_attr(feature = "full", ts(optional))] pub enabled: Option, } @@ -32,15 +35,25 @@ pub struct CreateOAuthProvider { /// Edit an external auth method. pub struct EditOAuthProvider { pub id: OAuthProviderId, + #[cfg_attr(feature = "full", ts(optional))] pub display_name: Option, + #[cfg_attr(feature = "full", ts(optional))] pub authorization_endpoint: Option, + #[cfg_attr(feature = "full", ts(optional))] pub token_endpoint: Option, + #[cfg_attr(feature = "full", ts(optional))] pub userinfo_endpoint: Option, + #[cfg_attr(feature = "full", ts(optional))] pub id_claim: Option, + #[cfg_attr(feature = "full", ts(optional))] pub client_secret: Option, + #[cfg_attr(feature = "full", ts(optional))] pub scopes: Option, + #[cfg_attr(feature = "full", ts(optional))] pub auto_verify_email: Option, + #[cfg_attr(feature = "full", ts(optional))] pub account_linking_enabled: Option, + #[cfg_attr(feature = "full", ts(optional))] pub enabled: Option, } @@ -59,13 +72,14 @@ pub struct DeleteOAuthProvider { /// Logging in with an OAuth 2.0 authorization pub struct AuthenticateWithOauth { pub code: String, - #[cfg_attr(feature = "full", ts(type = "string"))] pub oauth_provider_id: OAuthProviderId, - #[cfg_attr(feature = "full", ts(type = "string"))] pub redirect_uri: Url, + #[cfg_attr(feature = "full", ts(optional))] pub show_nsfw: Option, /// Username is mandatory at registration time + #[cfg_attr(feature = "full", ts(optional))] pub username: Option, /// An answer is mandatory if require application is enabled on the server + #[cfg_attr(feature = "full", ts(optional))] pub answer: Option, } diff --git a/crates/api_common/src/person.rs b/crates/api_common/src/person.rs index 6f1ddfe43..6b64d8467 100644 --- a/crates/api_common/src/person.rs +++ b/crates/api_common/src/person.rs @@ -28,6 +28,7 @@ pub struct Login { pub username_or_email: SensitiveString, pub password: SensitiveString, /// May be required, if totp is enabled for their account. + #[cfg_attr(feature = "full", ts(optional))] pub totp_2fa_token: Option, } @@ -40,16 +41,22 @@ pub struct Register { pub username: String, pub password: SensitiveString, pub password_verify: SensitiveString, + #[cfg_attr(feature = "full", ts(optional))] pub show_nsfw: Option, /// email is mandatory if email verification is enabled on the server + #[cfg_attr(feature = "full", ts(optional))] pub email: Option, /// The UUID of the captcha item. + #[cfg_attr(feature = "full", ts(optional))] pub captcha_uuid: Option, /// Your captcha answer. + #[cfg_attr(feature = "full", ts(optional))] pub captcha_answer: Option, /// A form field to trick signup bots. Should be None. + #[cfg_attr(feature = "full", ts(optional))] pub honeypot: Option, /// An answer is mandatory if require application is enabled on the server + #[cfg_attr(feature = "full", ts(optional))] pub answer: Option, } @@ -60,6 +67,7 @@ pub struct Register { /// A wrapper for the captcha response. pub struct GetCaptchaResponse { /// Will be None if captchas are disabled. + #[cfg_attr(feature = "full", ts(optional))] pub ok: Option, } @@ -83,60 +91,89 @@ pub struct CaptchaResponse { /// Saves settings for your user. pub struct SaveUserSettings { /// Show nsfw posts. + #[cfg_attr(feature = "full", ts(optional))] pub show_nsfw: Option, /// Blur nsfw posts. + #[cfg_attr(feature = "full", ts(optional))] pub blur_nsfw: Option, /// Your user's theme. + #[cfg_attr(feature = "full", ts(optional))] pub theme: Option, /// The default post listing type, usually "local" + #[cfg_attr(feature = "full", ts(optional))] pub default_listing_type: Option, /// A post-view mode that changes how multiple post listings look. + #[cfg_attr(feature = "full", ts(optional))] pub post_listing_mode: Option, /// The default post sort, usually "active" + #[cfg_attr(feature = "full", ts(optional))] pub default_post_sort_type: Option, /// The default comment sort, usually "hot" + #[cfg_attr(feature = "full", ts(optional))] pub default_comment_sort_type: Option, /// The language of the lemmy interface + #[cfg_attr(feature = "full", ts(optional))] pub interface_language: Option, /// A URL for your avatar. + #[cfg_attr(feature = "full", ts(optional))] pub avatar: Option, /// A URL for your banner. + #[cfg_attr(feature = "full", ts(optional))] pub banner: Option, /// Your display name, which can contain strange characters, and does not need to be unique. + #[cfg_attr(feature = "full", ts(optional))] pub display_name: Option, /// Your email. + #[cfg_attr(feature = "full", ts(optional))] pub email: Option, /// Your bio / info, in markdown. + #[cfg_attr(feature = "full", ts(optional))] pub bio: Option, /// Your matrix user id. Ex: @my_user:matrix.org + #[cfg_attr(feature = "full", ts(optional))] pub matrix_user_id: Option, /// Whether to show or hide avatars. + #[cfg_attr(feature = "full", ts(optional))] pub show_avatars: Option, /// Sends notifications to your email. + #[cfg_attr(feature = "full", ts(optional))] pub send_notifications_to_email: Option, /// Whether this account is a bot account. Users can hide these accounts easily if they wish. + #[cfg_attr(feature = "full", ts(optional))] pub bot_account: Option, /// Whether to show bot accounts. + #[cfg_attr(feature = "full", ts(optional))] pub show_bot_accounts: Option, /// Whether to show read posts. + #[cfg_attr(feature = "full", ts(optional))] pub show_read_posts: Option, /// A list of languages you are able to see discussion in. + #[cfg_attr(feature = "full", ts(optional))] pub discussion_languages: Option>, /// Open links in a new tab + #[cfg_attr(feature = "full", ts(optional))] pub open_links_in_new_tab: Option, /// Enable infinite scroll + #[cfg_attr(feature = "full", ts(optional))] pub infinite_scroll_enabled: Option, /// Whether to allow keyboard navigation (for browsing and interacting with posts and comments). + #[cfg_attr(feature = "full", ts(optional))] pub enable_keyboard_navigation: Option, /// Whether user avatars or inline images in the UI that are gifs should be allowed to play or /// should be paused + #[cfg_attr(feature = "full", ts(optional))] pub enable_animated_images: Option, /// Whether to auto-collapse bot comments. + #[cfg_attr(feature = "full", ts(optional))] pub collapse_bot_comments: Option, /// Some vote display mode settings + #[cfg_attr(feature = "full", ts(optional))] pub show_scores: Option, + #[cfg_attr(feature = "full", ts(optional))] pub show_upvotes: Option, + #[cfg_attr(feature = "full", ts(optional))] pub show_downvotes: Option, + #[cfg_attr(feature = "full", ts(optional))] pub show_upvote_percentage: Option, } @@ -158,6 +195,7 @@ pub struct ChangePassword { pub struct LoginResponse { /// This is None in response to `Register` if email verification is enabled, or the server /// requires registration applications. + #[cfg_attr(feature = "full", ts(optional))] pub jwt: Option, /// If registration applications are required, this will return true for a signup response. pub registration_created: bool, @@ -173,13 +211,20 @@ pub struct LoginResponse { /// /// Either person_id, or username are required. pub struct GetPersonDetails { + #[cfg_attr(feature = "full", ts(optional))] pub person_id: Option, /// Example: dessalines , or dessalines@xyz.tld + #[cfg_attr(feature = "full", ts(optional))] pub username: Option, + #[cfg_attr(feature = "full", ts(optional))] pub sort: Option, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, + #[cfg_attr(feature = "full", ts(optional))] pub community_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub saved_only: Option, } @@ -190,6 +235,7 @@ pub struct GetPersonDetails { /// A person's details response. pub struct GetPersonDetailsResponse { pub person_view: PersonView, + #[cfg_attr(feature = "full", ts(optional))] pub site: Option, pub comments: Vec, pub posts: Vec, @@ -223,11 +269,14 @@ pub struct BanPerson { pub ban: bool, /// Optionally remove or restore all their data. Useful for new troll accounts. /// If ban is true, then this means remove. If ban is false, it means restore. + #[cfg_attr(feature = "full", ts(optional))] pub remove_or_restore_data: Option, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, /// A time that the ban will expire, in unix epoch seconds. /// /// An i64 unix timestamp is used for a simpler API client implementation. + #[cfg_attr(feature = "full", ts(optional))] pub expires: Option, } @@ -273,9 +322,13 @@ pub struct BlockPersonResponse { #[cfg_attr(feature = "full", ts(export))] /// Get comment replies. pub struct GetReplies { + #[cfg_attr(feature = "full", ts(optional))] pub sort: Option, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, + #[cfg_attr(feature = "full", ts(optional))] pub unread_only: Option, } @@ -294,9 +347,13 @@ pub struct GetRepliesResponse { #[cfg_attr(feature = "full", ts(export))] /// Get mentions for your user. pub struct GetPersonMentions { + #[cfg_attr(feature = "full", ts(optional))] pub sort: Option, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, + #[cfg_attr(feature = "full", ts(optional))] pub unread_only: Option, } @@ -375,6 +432,7 @@ pub struct PasswordChangeAfterReset { #[cfg_attr(feature = "full", ts(export))] /// Get a count of the number of reports. pub struct GetReportCount { + #[cfg_attr(feature = "full", ts(optional))] pub community_id: Option, } @@ -384,9 +442,11 @@ pub struct GetReportCount { #[cfg_attr(feature = "full", ts(export))] /// A response for the number of reports. pub struct GetReportCountResponse { + #[cfg_attr(feature = "full", ts(optional))] pub community_id: Option, pub comment_reports: i64, pub post_reports: i64, + #[cfg_attr(feature = "full", ts(optional))] pub private_message_reports: Option, } @@ -436,7 +496,9 @@ pub struct UpdateTotpResponse { #[cfg_attr(feature = "full", ts(export))] /// Get your user's image / media uploads. pub struct ListMedia { + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, } diff --git a/crates/api_common/src/post.rs b/crates/api_common/src/post.rs index 22d5e1431..ca4f53e9d 100644 --- a/crates/api_common/src/post.rs +++ b/crates/api_common/src/post.rs @@ -19,18 +19,26 @@ use ts_rs::TS; pub struct CreatePost { pub name: String, pub community_id: CommunityId, + #[cfg_attr(feature = "full", ts(optional))] pub url: Option, /// An optional body for the post in markdown. + #[cfg_attr(feature = "full", ts(optional))] pub body: Option, /// An optional alt_text, usable for image posts. + #[cfg_attr(feature = "full", ts(optional))] pub alt_text: Option, /// A honeypot to catch bots. Should be None. + #[cfg_attr(feature = "full", ts(optional))] pub honeypot: Option, + #[cfg_attr(feature = "full", ts(optional))] pub nsfw: Option, + #[cfg_attr(feature = "full", ts(optional))] pub language_id: Option, /// Instead of fetching a thumbnail, use a custom one. + #[cfg_attr(feature = "full", ts(optional))] pub custom_thumbnail: Option, /// Time when this post should be scheduled. Null means publish immediately. + #[cfg_attr(feature = "full", ts(optional))] pub scheduled_publish_time: Option, } @@ -45,9 +53,12 @@ pub struct PostResponse { #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "full", derive(TS))] #[cfg_attr(feature = "full", ts(export))] +// TODO this should be made into a tagged enum /// Get a post. Needs either the post id, or comment_id. pub struct GetPost { + #[cfg_attr(feature = "full", ts(optional))] pub id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub comment_id: Option, } @@ -70,23 +81,37 @@ pub struct GetPostResponse { #[cfg_attr(feature = "full", ts(export))] /// Get a list of posts. pub struct GetPosts { + #[cfg_attr(feature = "full", ts(optional))] pub type_: Option, + #[cfg_attr(feature = "full", ts(optional))] pub sort: Option, /// DEPRECATED, use page_cursor + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, + #[cfg_attr(feature = "full", ts(optional))] pub community_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub community_name: Option, + #[cfg_attr(feature = "full", ts(optional))] pub saved_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub liked_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub disliked_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub show_hidden: Option, /// If true, then show the read posts (even if your user setting is to hide them) + #[cfg_attr(feature = "full", ts(optional))] pub show_read: Option, /// If true, then show the nsfw posts (even if your user setting is to hide them) + #[cfg_attr(feature = "full", ts(optional))] pub show_nsfw: Option, + #[cfg_attr(feature = "full", ts(optional))] /// If true, then only show posts with no comments pub no_comments_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub page_cursor: Option, } @@ -98,6 +123,7 @@ pub struct GetPosts { pub struct GetPostsResponse { pub posts: Vec, /// the pagination cursor to use to fetch the next page + #[cfg_attr(feature = "full", ts(optional))] pub next_page: Option, } @@ -118,17 +144,25 @@ pub struct CreatePostLike { /// Edit a post. pub struct EditPost { pub post_id: PostId, + #[cfg_attr(feature = "full", ts(optional))] pub name: Option, + #[cfg_attr(feature = "full", ts(optional))] pub url: Option, /// An optional body for the post in markdown. + #[cfg_attr(feature = "full", ts(optional))] pub body: Option, /// An optional alt_text, usable for image posts. + #[cfg_attr(feature = "full", ts(optional))] pub alt_text: Option, + #[cfg_attr(feature = "full", ts(optional))] pub nsfw: Option, + #[cfg_attr(feature = "full", ts(optional))] pub language_id: Option, /// Instead of fetching a thumbnail, use a custom one. + #[cfg_attr(feature = "full", ts(optional))] pub custom_thumbnail: Option, /// Time when this post should be scheduled. Null means publish immediately. + #[cfg_attr(feature = "full", ts(optional))] pub scheduled_publish_time: Option, } @@ -149,6 +183,7 @@ pub struct DeletePost { pub struct RemovePost { pub post_id: PostId, pub removed: bool, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, } @@ -232,12 +267,18 @@ pub struct ResolvePostReport { #[cfg_attr(feature = "full", ts(export))] /// List post reports. pub struct ListPostReports { + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, /// Only shows the unresolved reports + #[cfg_attr(feature = "full", ts(optional))] pub unresolved_only: Option, + // TODO make into tagged enum at some point /// if no community is given, it returns reports for all communities moderated by the auth user + #[cfg_attr(feature = "full", ts(optional))] pub community_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub post_id: Option, } @@ -273,6 +314,7 @@ pub struct GetSiteMetadataResponse { pub struct LinkMetadata { #[serde(flatten)] pub opengraph_data: OpenGraphData, + #[cfg_attr(feature = "full", ts(optional))] pub content_type: Option, } @@ -282,9 +324,13 @@ pub struct LinkMetadata { #[cfg_attr(feature = "full", ts(export))] /// Site metadata, from its opengraph tags. pub struct OpenGraphData { + #[cfg_attr(feature = "full", ts(optional))] pub title: Option, + #[cfg_attr(feature = "full", ts(optional))] pub description: Option, + #[cfg_attr(feature = "full", ts(optional))] pub(crate) image: Option, + #[cfg_attr(feature = "full", ts(optional))] pub embed_video_url: Option, } @@ -295,7 +341,9 @@ pub struct OpenGraphData { /// List post likes. Admins-only. pub struct ListPostLikes { pub post_id: PostId, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, } diff --git a/crates/api_common/src/private_message.rs b/crates/api_common/src/private_message.rs index 429d68643..666fe3865 100644 --- a/crates/api_common/src/private_message.rs +++ b/crates/api_common/src/private_message.rs @@ -47,9 +47,13 @@ pub struct MarkPrivateMessageAsRead { #[cfg_attr(feature = "full", ts(export))] /// Get your private messages. pub struct GetPrivateMessages { + #[cfg_attr(feature = "full", ts(optional))] pub unread_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, + #[cfg_attr(feature = "full", ts(optional))] pub creator_id: Option, } @@ -102,9 +106,12 @@ pub struct ResolvePrivateMessageReport { /// List private message reports. // TODO , perhaps GetReports should be a tagged enum list too. pub struct ListPrivateMessageReports { + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, /// Only shows the unresolved reports + #[cfg_attr(feature = "full", ts(optional))] pub unresolved_only: Option, } diff --git a/crates/api_common/src/site.rs b/crates/api_common/src/site.rs index 8fc091e9d..40a5cc42d 100644 --- a/crates/api_common/src/site.rs +++ b/crates/api_common/src/site.rs @@ -71,18 +71,31 @@ use ts_rs::TS; /// Searches the site, given a query string, and some optional filters. pub struct Search { pub q: String, + #[cfg_attr(feature = "full", ts(optional))] pub community_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub community_name: Option, + #[cfg_attr(feature = "full", ts(optional))] pub creator_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub type_: Option, + #[cfg_attr(feature = "full", ts(optional))] pub sort: Option, + #[cfg_attr(feature = "full", ts(optional))] pub listing_type: Option, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, + #[cfg_attr(feature = "full", ts(optional))] pub title_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub post_url_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub saved_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub liked_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub disliked_only: Option, } @@ -115,9 +128,13 @@ pub struct ResolveObject { // TODO Change this to an enum /// The response of an apub object fetch. pub struct ResolveObjectResponse { + #[cfg_attr(feature = "full", ts(optional))] pub comment: Option, + #[cfg_attr(feature = "full", ts(optional))] pub post: Option, + #[cfg_attr(feature = "full", ts(optional))] pub community: Option, + #[cfg_attr(feature = "full", ts(optional))] pub person: Option, } @@ -127,13 +144,21 @@ pub struct ResolveObjectResponse { #[cfg_attr(feature = "full", ts(export))] /// Fetches the modlog. pub struct GetModlog { + #[cfg_attr(feature = "full", ts(optional))] pub mod_person_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub community_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, + #[cfg_attr(feature = "full", ts(optional))] pub type_: Option, + #[cfg_attr(feature = "full", ts(optional))] pub other_person_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub post_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub comment_id: Option, } @@ -167,50 +192,95 @@ pub struct GetModlogResponse { /// Creates a site. Should be done after first running lemmy. pub struct CreateSite { pub name: String, + #[cfg_attr(feature = "full", ts(optional))] pub sidebar: Option, + #[cfg_attr(feature = "full", ts(optional))] pub description: Option, + #[cfg_attr(feature = "full", ts(optional))] pub icon: Option, + #[cfg_attr(feature = "full", ts(optional))] pub banner: Option, + #[cfg_attr(feature = "full", ts(optional))] pub enable_nsfw: Option, + #[cfg_attr(feature = "full", ts(optional))] pub community_creation_admin_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub require_email_verification: Option, + #[cfg_attr(feature = "full", ts(optional))] pub application_question: Option, + #[cfg_attr(feature = "full", ts(optional))] pub private_instance: Option, + #[cfg_attr(feature = "full", ts(optional))] pub default_theme: Option, + #[cfg_attr(feature = "full", ts(optional))] pub default_post_listing_type: Option, + #[cfg_attr(feature = "full", ts(optional))] pub default_post_listing_mode: Option, + #[cfg_attr(feature = "full", ts(optional))] pub default_post_sort_type: Option, + #[cfg_attr(feature = "full", ts(optional))] pub default_comment_sort_type: Option, + #[cfg_attr(feature = "full", ts(optional))] pub legal_information: Option, + #[cfg_attr(feature = "full", ts(optional))] pub application_email_admins: Option, + #[cfg_attr(feature = "full", ts(optional))] pub hide_modlog_mod_names: Option, + #[cfg_attr(feature = "full", ts(optional))] pub discussion_languages: Option>, + #[cfg_attr(feature = "full", ts(optional))] pub slur_filter_regex: Option, + #[cfg_attr(feature = "full", ts(optional))] pub actor_name_max_length: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_message: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_message_per_second: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_post: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_post_per_second: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_register: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_register_per_second: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_image: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_image_per_second: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_comment: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_comment_per_second: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_search: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_search_per_second: Option, + #[cfg_attr(feature = "full", ts(optional))] pub federation_enabled: Option, + #[cfg_attr(feature = "full", ts(optional))] pub federation_debug: Option, + #[cfg_attr(feature = "full", ts(optional))] pub captcha_enabled: Option, + #[cfg_attr(feature = "full", ts(optional))] pub captcha_difficulty: Option, + #[cfg_attr(feature = "full", ts(optional))] pub allowed_instances: Option>, + #[cfg_attr(feature = "full", ts(optional))] pub blocked_instances: Option>, + #[cfg_attr(feature = "full", ts(optional))] pub registration_mode: Option, + #[cfg_attr(feature = "full", ts(optional))] pub oauth_registration: Option, + #[cfg_attr(feature = "full", ts(optional))] pub content_warning: Option, + #[cfg_attr(feature = "full", ts(optional))] pub post_upvotes: Option, + #[cfg_attr(feature = "full", ts(optional))] pub post_downvotes: Option, + #[cfg_attr(feature = "full", ts(optional))] pub comment_upvotes: Option, + #[cfg_attr(feature = "full", ts(optional))] pub comment_downvotes: Option, } @@ -220,94 +290,142 @@ pub struct CreateSite { #[cfg_attr(feature = "full", ts(export))] /// Edits a site. pub struct EditSite { + #[cfg_attr(feature = "full", ts(optional))] pub name: Option, /// A sidebar for the site, in markdown. + #[cfg_attr(feature = "full", ts(optional))] pub sidebar: Option, /// A shorter, one line description of your site. + #[cfg_attr(feature = "full", ts(optional))] pub description: Option, /// A url for your site's icon. + #[cfg_attr(feature = "full", ts(optional))] pub icon: Option, /// A url for your site's banner. + #[cfg_attr(feature = "full", ts(optional))] pub banner: Option, /// Whether to enable NSFW. + #[cfg_attr(feature = "full", ts(optional))] pub enable_nsfw: Option, /// Limits community creation to admins only. + #[cfg_attr(feature = "full", ts(optional))] pub community_creation_admin_only: Option, /// Whether to require email verification. + #[cfg_attr(feature = "full", ts(optional))] pub require_email_verification: Option, /// Your application question form. This is in markdown, and can be many questions. + #[cfg_attr(feature = "full", ts(optional))] pub application_question: Option, /// Whether your instance is public, or private. + #[cfg_attr(feature = "full", ts(optional))] pub private_instance: Option, /// The default theme. Usually "browser" + #[cfg_attr(feature = "full", ts(optional))] pub default_theme: Option, /// The default post listing type, usually "local" + #[cfg_attr(feature = "full", ts(optional))] pub default_post_listing_type: Option, /// Default value for listing mode, usually "list" + #[cfg_attr(feature = "full", ts(optional))] pub default_post_listing_mode: Option, /// The default post sort, usually "active" + #[cfg_attr(feature = "full", ts(optional))] pub default_post_sort_type: Option, /// The default comment sort, usually "hot" + #[cfg_attr(feature = "full", ts(optional))] pub default_comment_sort_type: Option, /// An optional page of legal information + #[cfg_attr(feature = "full", ts(optional))] pub legal_information: Option, /// Whether to email admins when receiving a new application. + #[cfg_attr(feature = "full", ts(optional))] pub application_email_admins: Option, /// Whether to hide moderator names from the modlog. + #[cfg_attr(feature = "full", ts(optional))] pub hide_modlog_mod_names: Option, /// A list of allowed discussion languages. + #[cfg_attr(feature = "full", ts(optional))] pub discussion_languages: Option>, /// A regex string of items to filter. + #[cfg_attr(feature = "full", ts(optional))] pub slur_filter_regex: Option, /// The max length of actor names. + #[cfg_attr(feature = "full", ts(optional))] pub actor_name_max_length: Option, /// The number of messages allowed in a given time frame. + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_message: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_message_per_second: Option, /// The number of posts allowed in a given time frame. + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_post: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_post_per_second: Option, /// The number of registrations allowed in a given time frame. + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_register: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_register_per_second: Option, /// The number of image uploads allowed in a given time frame. + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_image: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_image_per_second: Option, /// The number of comments allowed in a given time frame. + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_comment: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_comment_per_second: Option, /// The number of searches allowed in a given time frame. + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_search: Option, + #[cfg_attr(feature = "full", ts(optional))] pub rate_limit_search_per_second: Option, /// Whether to enable federation. + #[cfg_attr(feature = "full", ts(optional))] pub federation_enabled: Option, /// Enables federation debugging. + #[cfg_attr(feature = "full", ts(optional))] pub federation_debug: Option, /// Whether to enable captchas for signups. + #[cfg_attr(feature = "full", ts(optional))] pub captcha_enabled: Option, /// The captcha difficulty. Can be easy, medium, or hard + #[cfg_attr(feature = "full", ts(optional))] pub captcha_difficulty: Option, /// A list of allowed instances. If none are set, federation is open. + #[cfg_attr(feature = "full", ts(optional))] pub allowed_instances: Option>, /// A list of blocked instances. + #[cfg_attr(feature = "full", ts(optional))] pub blocked_instances: Option>, /// A list of blocked URLs + #[cfg_attr(feature = "full", ts(optional))] pub blocked_urls: Option>, + #[cfg_attr(feature = "full", ts(optional))] pub registration_mode: Option, /// Whether to email admins for new reports. + #[cfg_attr(feature = "full", ts(optional))] pub reports_email_admins: Option, /// If present, nsfw content is visible by default. Should be displayed by frontends/clients /// when the site is first opened by a user. + #[cfg_attr(feature = "full", ts(optional))] pub content_warning: Option, /// Whether or not external auth methods can auto-register users. + #[cfg_attr(feature = "full", ts(optional))] pub oauth_registration: Option, /// What kind of post upvotes your site allows. + #[cfg_attr(feature = "full", ts(optional))] pub post_upvotes: Option, /// What kind of post downvotes your site allows. + #[cfg_attr(feature = "full", ts(optional))] pub post_downvotes: Option, /// What kind of comment upvotes your site allows. + #[cfg_attr(feature = "full", ts(optional))] pub comment_upvotes: Option, /// What kind of comment downvotes your site allows. + #[cfg_attr(feature = "full", ts(optional))] pub comment_downvotes: Option, } @@ -330,6 +448,7 @@ pub struct GetSiteResponse { pub site_view: SiteView, pub admins: Vec, pub version: String, + #[cfg_attr(feature = "full", ts(optional))] pub my_user: Option, pub all_languages: Vec, pub discussion_languages: Vec, @@ -338,9 +457,12 @@ pub struct GetSiteResponse { /// deprecated, use /api/v3/custom_emoji/list pub custom_emojis: Vec<()>, /// If the site has any taglines, a random one is included here for displaying + #[cfg_attr(feature = "full", ts(optional))] pub tagline: Option, /// A list of external auth methods your site supports. + #[cfg_attr(feature = "full", ts(optional))] pub oauth_providers: Option>, + #[cfg_attr(feature = "full", ts(optional))] pub admin_oauth_providers: Option>, pub blocked_urls: Vec, } @@ -352,6 +474,7 @@ pub struct GetSiteResponse { /// A response of federated instances. pub struct GetFederatedInstancesResponse { /// Optional, because federation may be disabled. + #[cfg_attr(feature = "full", ts(optional))] pub federated_instances: Option, } @@ -387,6 +510,7 @@ pub struct ReadableFederationState { #[serde(flatten)] internal_state: FederationQueueState, /// timestamp of the next retry attempt (null if fail count is 0) + #[cfg_attr(feature = "full", ts(optional))] next_retry: Option>, } @@ -411,6 +535,7 @@ pub struct InstanceWithFederationState { pub instance: Instance, /// if federation to this instance is or was active, show state of outgoing federation to this /// instance + #[cfg_attr(feature = "full", ts(optional))] pub federation_state: Option, } @@ -421,6 +546,7 @@ pub struct InstanceWithFederationState { /// Purges a person from the database. This will delete all content attached to that person. pub struct PurgePerson { pub person_id: PersonId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, } @@ -431,6 +557,7 @@ pub struct PurgePerson { /// Purges a community from the database. This will delete all content attached to that community. pub struct PurgeCommunity { pub community_id: CommunityId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, } @@ -441,6 +568,7 @@ pub struct PurgeCommunity { /// Purges a post from the database. This will delete all content attached to that post. pub struct PurgePost { pub post_id: PostId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, } @@ -451,6 +579,7 @@ pub struct PurgePost { /// Purges a comment from the database. This will delete all content attached to that comment. pub struct PurgeComment { pub comment_id: CommentId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, } @@ -461,8 +590,11 @@ pub struct PurgeComment { /// Fetches a list of registration applications. pub struct ListRegistrationApplications { /// Only shows the unread applications (IE those without an admin actor) + #[cfg_attr(feature = "full", ts(optional))] pub unread_only: Option, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, } @@ -491,6 +623,7 @@ pub struct GetRegistrationApplication { pub struct ApproveRegistrationApplication { pub id: RegistrationApplicationId, pub approve: bool, + #[cfg_attr(feature = "full", ts(optional))] pub deny_reason: Option, } diff --git a/crates/api_common/src/tagline.rs b/crates/api_common/src/tagline.rs index 3090a2678..528d37947 100644 --- a/crates/api_common/src/tagline.rs +++ b/crates/api_common/src/tagline.rs @@ -50,6 +50,8 @@ pub struct ListTaglinesResponse { #[cfg_attr(feature = "full", ts(export))] /// Fetches a list of taglines. pub struct ListTaglines { + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, } diff --git a/crates/api_common/src/utils.rs b/crates/api_common/src/utils.rs index e358d483b..ddddd35e9 100644 --- a/crates/api_common/src/utils.rs +++ b/crates/api_common/src/utils.rs @@ -216,7 +216,9 @@ pub async fn check_registration_application( let local_user_id = local_user_view.local_user.id; let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?; if registration.admin_id.is_some() { - Err(LemmyErrorType::RegistrationDenied(registration.deny_reason))? + Err(LemmyErrorType::RegistrationDenied { + reason: registration.deny_reason, + })? } else { Err(LemmyErrorType::RegistrationApplicationIsPending)? } diff --git a/crates/apub/src/lib.rs b/crates/apub/src/lib.rs index a04aec655..e11475d6c 100644 --- a/crates/apub/src/lib.rs +++ b/crates/apub/src/lib.rs @@ -54,15 +54,24 @@ impl UrlVerifier for VerifyUrlData { use FederationError::*; check_apub_id_valid(url, &local_site_data).map_err(|err| match err { LemmyError { - error_type: LemmyErrorType::FederationError(Some(FederationDisabled)), + error_type: + LemmyErrorType::FederationError { + error: Some(FederationDisabled), + }, .. } => ActivityPubError::Other("Federation disabled".into()), LemmyError { - error_type: LemmyErrorType::FederationError(Some(DomainBlocked(domain))), + error_type: + LemmyErrorType::FederationError { + error: Some(DomainBlocked(domain)), + }, .. } => ActivityPubError::Other(format!("Domain {domain:?} is blocked")), LemmyError { - error_type: LemmyErrorType::FederationError(Some(DomainNotInAllowList(domain))), + error_type: + LemmyErrorType::FederationError { + error: Some(DomainNotInAllowList(domain)), + }, .. } => ActivityPubError::Other(format!("Domain {domain:?} is not in allowlist")), _ => ActivityPubError::Other("Failed validating apub id".into()), diff --git a/crates/db_schema/src/newtypes.rs b/crates/db_schema/src/newtypes.rs index fe1febef5..c28be8222 100644 --- a/crates/db_schema/src/newtypes.rs +++ b/crates/db_schema/src/newtypes.rs @@ -174,8 +174,9 @@ pub struct LtreeDef(pub String); #[repr(transparent)] #[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug, Hash)] -#[cfg_attr(feature = "full", derive(AsExpression, FromSqlRow))] +#[cfg_attr(feature = "full", derive(AsExpression, FromSqlRow, TS))] #[cfg_attr(feature = "full", diesel(sql_type = diesel::sql_types::Text))] +#[cfg_attr(feature = "full", ts(export))] pub struct DbUrl(pub(crate) Box); impl DbUrl { @@ -248,19 +249,6 @@ impl Deref for DbUrl { } } -#[cfg(feature = "full")] -impl TS for DbUrl { - fn name() -> String { - "string".to_string() - } - fn dependencies() -> Vec { - Vec::new() - } - fn transparent() -> bool { - true - } -} - #[cfg(feature = "full")] impl ToSql for DbUrl { fn to_sql(&self, out: &mut Output) -> diesel::serialize::Result { diff --git a/crates/db_schema/src/sensitive.rs b/crates/db_schema/src/sensitive.rs index 340679e2f..5d1d449fb 100644 --- a/crates/db_schema/src/sensitive.rs +++ b/crates/db_schema/src/sensitive.rs @@ -4,8 +4,9 @@ use std::{fmt::Debug, ops::Deref}; use ts_rs::TS; #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Default)] -#[cfg_attr(feature = "full", derive(DieselNewType))] +#[cfg_attr(feature = "full", derive(DieselNewType, TS))] #[serde(transparent)] +#[cfg_attr(feature = "full", ts(export))] pub struct SensitiveString(String); impl SensitiveString { @@ -39,19 +40,3 @@ impl From for SensitiveString { SensitiveString(t) } } - -#[cfg(feature = "full")] -impl TS for SensitiveString { - fn name() -> String { - "string".to_string() - } - fn name_with_type_args(_args: Vec) -> String { - "string".to_string() - } - fn dependencies() -> Vec { - Vec::new() - } - fn transparent() -> bool { - true - } -} diff --git a/crates/db_schema/src/source/comment.rs b/crates/db_schema/src/source/comment.rs index 1e5f043f1..7e65638ed 100644 --- a/crates/db_schema/src/source/comment.rs +++ b/crates/db_schema/src/source/comment.rs @@ -30,6 +30,7 @@ pub struct Comment { /// Whether the comment has been removed. pub removed: bool, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, /// Whether the comment has been deleted by its creator. pub deleted: bool, diff --git a/crates/db_schema/src/source/comment_report.rs b/crates/db_schema/src/source/comment_report.rs index 73dadc945..a19b6925a 100644 --- a/crates/db_schema/src/source/comment_report.rs +++ b/crates/db_schema/src/source/comment_report.rs @@ -25,8 +25,10 @@ pub struct CommentReport { pub original_comment_text: String, pub reason: String, pub resolved: bool, + #[cfg_attr(feature = "full", ts(optional))] pub resolver_id: Option, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, } diff --git a/crates/db_schema/src/source/community.rs b/crates/db_schema/src/source/community.rs index 2eb6c143c..870a132f2 100644 --- a/crates/db_schema/src/source/community.rs +++ b/crates/db_schema/src/source/community.rs @@ -25,10 +25,12 @@ pub struct Community { /// A longer title, that can contain other characters, and doesn't have to be unique. pub title: String, /// A sidebar for the community in markdown. + #[cfg_attr(feature = "full", ts(optional))] pub sidebar: Option, /// Whether the community is removed by a mod. pub removed: bool, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, /// Whether the community has been deleted by its creator. pub deleted: bool, @@ -45,8 +47,10 @@ pub struct Community { #[serde(skip)] pub last_refreshed_at: DateTime, /// A URL for an icon. + #[cfg_attr(feature = "full", ts(optional))] pub icon: Option, /// A URL for a banner. + #[cfg_attr(feature = "full", ts(optional))] pub banner: Option, #[cfg_attr(feature = "full", ts(skip))] #[serde(skip)] @@ -67,6 +71,7 @@ pub struct Community { pub featured_url: Option, pub visibility: CommunityVisibility, /// A shorter, one-line description of the site. + #[cfg_attr(feature = "full", ts(optional))] pub description: Option, } diff --git a/crates/db_schema/src/source/custom_emoji.rs b/crates/db_schema/src/source/custom_emoji.rs index f5a92ea46..bb95cb7c8 100644 --- a/crates/db_schema/src/source/custom_emoji.rs +++ b/crates/db_schema/src/source/custom_emoji.rs @@ -21,6 +21,7 @@ pub struct CustomEmoji { pub alt_text: String, pub category: String, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, } diff --git a/crates/db_schema/src/source/federation_queue_state.rs b/crates/db_schema/src/source/federation_queue_state.rs index 134dfe452..27e464d1f 100644 --- a/crates/db_schema/src/source/federation_queue_state.rs +++ b/crates/db_schema/src/source/federation_queue_state.rs @@ -19,10 +19,13 @@ use ts_rs::TS; pub struct FederationQueueState { pub instance_id: InstanceId, /// the last successfully sent activity id + #[cfg_attr(feature = "full", ts(optional))] pub last_successful_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub last_successful_published_time: Option>, /// how many failed attempts have been made to send the next activity pub fail_count: i32, /// timestamp of the last retry attempt (when the last failing activity was resent) + #[cfg_attr(feature = "full", ts(optional))] pub last_retry: Option>, } diff --git a/crates/db_schema/src/source/images.rs b/crates/db_schema/src/source/images.rs index 22f5e6eb4..acd339d8e 100644 --- a/crates/db_schema/src/source/images.rs +++ b/crates/db_schema/src/source/images.rs @@ -23,6 +23,7 @@ use ts_rs::TS; #[cfg_attr(feature = "full", diesel(check_for_backend(diesel::pg::Pg)))] #[cfg_attr(feature = "full", diesel(primary_key(pictrs_alias)))] pub struct LocalImage { + #[cfg_attr(feature = "full", ts(optional))] pub local_user_id: Option, pub pictrs_alias: String, pub pictrs_delete_token: String, diff --git a/crates/db_schema/src/source/instance.rs b/crates/db_schema/src/source/instance.rs index 8c27a2cb6..f622751cc 100644 --- a/crates/db_schema/src/source/instance.rs +++ b/crates/db_schema/src/source/instance.rs @@ -19,8 +19,11 @@ pub struct Instance { pub id: InstanceId, pub domain: String, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, + #[cfg_attr(feature = "full", ts(optional))] pub software: Option, + #[cfg_attr(feature = "full", ts(optional))] pub version: Option, } diff --git a/crates/db_schema/src/source/local_site.rs b/crates/db_schema/src/source/local_site.rs index 5fa57fe3b..b5bcebc58 100644 --- a/crates/db_schema/src/source/local_site.rs +++ b/crates/db_schema/src/source/local_site.rs @@ -33,6 +33,7 @@ pub struct LocalSite { /// Whether emails are required. pub require_email_verification: bool, /// An optional registration application questionnaire in markdown. + #[cfg_attr(feature = "full", ts(optional))] pub application_question: Option, /// Whether the instance is private or public. pub private_instance: bool, @@ -40,12 +41,14 @@ pub struct LocalSite { pub default_theme: String, pub default_post_listing_type: ListingType, /// An optional legal disclaimer page. + #[cfg_attr(feature = "full", ts(optional))] pub legal_information: Option, /// Whether to hide mod names on the modlog. pub hide_modlog_mod_names: bool, /// Whether new applications email admins. pub application_email_admins: bool, /// An optional regex to filter words. + #[cfg_attr(feature = "full", ts(optional))] pub slur_filter_regex: Option, /// The max actor name length. pub actor_name_max_length: i32, @@ -56,6 +59,7 @@ pub struct LocalSite { /// The captcha difficulty. pub captcha_difficulty: String, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, pub registration_mode: RegistrationMode, /// Whether to email admins on new reports. diff --git a/crates/db_schema/src/source/local_site_rate_limit.rs b/crates/db_schema/src/source/local_site_rate_limit.rs index f7f25f5c1..af424a248 100644 --- a/crates/db_schema/src/source/local_site_rate_limit.rs +++ b/crates/db_schema/src/source/local_site_rate_limit.rs @@ -34,6 +34,7 @@ pub struct LocalSiteRateLimit { pub search: i32, pub search_per_second: i32, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, pub import_user_settings: i32, pub import_user_settings_per_second: i32, diff --git a/crates/db_schema/src/source/local_site_url_blocklist.rs b/crates/db_schema/src/source/local_site_url_blocklist.rs index 4ac0893ec..d6127a78a 100644 --- a/crates/db_schema/src/source/local_site_url_blocklist.rs +++ b/crates/db_schema/src/source/local_site_url_blocklist.rs @@ -16,6 +16,7 @@ pub struct LocalSiteUrlBlocklist { pub id: i32, pub url: String, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, } diff --git a/crates/db_schema/src/source/local_user.rs b/crates/db_schema/src/source/local_user.rs index 37da70908..d5bbfbe19 100644 --- a/crates/db_schema/src/source/local_user.rs +++ b/crates/db_schema/src/source/local_user.rs @@ -27,6 +27,7 @@ pub struct LocalUser { pub person_id: PersonId, #[serde(skip)] pub password_encrypted: Option, + #[cfg_attr(feature = "full", ts(optional))] pub email: Option, /// Whether to show NSFW content. pub show_nsfw: bool, diff --git a/crates/db_schema/src/source/login_token.rs b/crates/db_schema/src/source/login_token.rs index 38aac33ef..20d81afb0 100644 --- a/crates/db_schema/src/source/login_token.rs +++ b/crates/db_schema/src/source/login_token.rs @@ -24,7 +24,9 @@ pub struct LoginToken { pub published: DateTime, /// IP address where login was made from, allows invalidating logins by IP address. /// Could be stored in truncated format, or store derived information for better privacy. + #[cfg_attr(feature = "full", ts(optional))] pub ip: Option, + #[cfg_attr(feature = "full", ts(optional))] pub user_agent: Option, } diff --git a/crates/db_schema/src/source/moderator.rs b/crates/db_schema/src/source/moderator.rs index c1f58ebc8..b4fdcc676 100644 --- a/crates/db_schema/src/source/moderator.rs +++ b/crates/db_schema/src/source/moderator.rs @@ -34,6 +34,7 @@ pub struct ModRemovePost { pub id: i32, pub mod_person_id: PersonId, pub post_id: PostId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, pub removed: bool, pub when_: DateTime, @@ -105,6 +106,7 @@ pub struct ModRemoveComment { pub id: i32, pub mod_person_id: PersonId, pub comment_id: CommentId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, pub removed: bool, pub when_: DateTime, @@ -130,6 +132,7 @@ pub struct ModRemoveCommunity { pub id: i32, pub mod_person_id: PersonId, pub community_id: CommunityId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, pub removed: bool, pub when_: DateTime, @@ -156,8 +159,10 @@ pub struct ModBanFromCommunity { pub mod_person_id: PersonId, pub other_person_id: PersonId, pub community_id: CommunityId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, pub banned: bool, + #[cfg_attr(feature = "full", ts(optional))] pub expires: Option>, pub when_: DateTime, } @@ -184,8 +189,10 @@ pub struct ModBan { pub id: i32, pub mod_person_id: PersonId, pub other_person_id: PersonId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, pub banned: bool, + #[cfg_attr(feature = "full", ts(optional))] pub expires: Option>, pub when_: DateTime, } @@ -211,6 +218,7 @@ pub struct ModHideCommunity { pub community_id: CommunityId, pub mod_person_id: PersonId, pub when_: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, pub hidden: bool, } @@ -303,6 +311,7 @@ pub struct ModAddForm { pub struct AdminPurgePerson { pub id: i32, pub admin_person_id: PersonId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, pub when_: DateTime, } @@ -324,6 +333,7 @@ pub struct AdminPurgePersonForm { pub struct AdminPurgeCommunity { pub id: i32, pub admin_person_id: PersonId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, pub when_: DateTime, } @@ -346,6 +356,7 @@ pub struct AdminPurgePost { pub id: i32, pub admin_person_id: PersonId, pub community_id: CommunityId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, pub when_: DateTime, } @@ -369,6 +380,7 @@ pub struct AdminPurgeComment { pub id: i32, pub admin_person_id: PersonId, pub post_id: PostId, + #[cfg_attr(feature = "full", ts(optional))] pub reason: Option, pub when_: DateTime, } diff --git a/crates/db_schema/src/source/oauth_account.rs b/crates/db_schema/src/source/oauth_account.rs index 83b578e22..b7d190c35 100644 --- a/crates/db_schema/src/source/oauth_account.rs +++ b/crates/db_schema/src/source/oauth_account.rs @@ -19,6 +19,7 @@ pub struct OAuthAccount { pub oauth_provider_id: OAuthProviderId, pub oauth_user_id: String, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, } diff --git a/crates/db_schema/src/source/oauth_provider.rs b/crates/db_schema/src/source/oauth_provider.rs index 75b989805..a70405a5e 100644 --- a/crates/db_schema/src/source/oauth_provider.rs +++ b/crates/db_schema/src/source/oauth_provider.rs @@ -60,6 +60,7 @@ pub struct OAuthProvider { /// switch to enable or disable an oauth provider pub enabled: bool, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, } diff --git a/crates/db_schema/src/source/person.rs b/crates/db_schema/src/source/person.rs index c3aeeb4d7..d8b0a5b1a 100644 --- a/crates/db_schema/src/source/person.rs +++ b/crates/db_schema/src/source/person.rs @@ -22,16 +22,20 @@ pub struct Person { pub id: PersonId, pub name: String, /// A shorter display name. + #[cfg_attr(feature = "full", ts(optional))] pub display_name: Option, /// A URL for an avatar. + #[cfg_attr(feature = "full", ts(optional))] pub avatar: Option, /// Whether the person is banned. pub banned: bool, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, /// The federated actor_id. pub actor_id: DbUrl, /// An optional bio, in markdown. + #[cfg_attr(feature = "full", ts(optional))] pub bio: Option, /// Whether the person is local to our site. pub local: bool, @@ -42,6 +46,7 @@ pub struct Person { #[serde(skip)] pub last_refreshed_at: DateTime, /// A URL for a banner. + #[cfg_attr(feature = "full", ts(optional))] pub banner: Option, /// Whether the person is deleted. pub deleted: bool, @@ -49,10 +54,12 @@ pub struct Person { #[serde(skip, default = "placeholder_apub_url")] pub inbox_url: DbUrl, /// A matrix id, usually given an @person:matrix.org + #[cfg_attr(feature = "full", ts(optional))] pub matrix_user_id: Option, /// Whether the person is a bot account. pub bot_account: bool, /// When their ban, if it exists, expires, if at all. + #[cfg_attr(feature = "full", ts(optional))] pub ban_expires: Option>, pub instance_id: InstanceId, } diff --git a/crates/db_schema/src/source/post.rs b/crates/db_schema/src/source/post.rs index 3819bd773..3417f87b5 100644 --- a/crates/db_schema/src/source/post.rs +++ b/crates/db_schema/src/source/post.rs @@ -17,10 +17,11 @@ use ts_rs::TS; pub struct Post { pub id: PostId, pub name: String, - #[cfg_attr(feature = "full", ts(type = "string"))] /// An optional link / url for the post. + #[cfg_attr(feature = "full", ts(optional))] pub url: Option, /// An optional post body, in markdown. + #[cfg_attr(feature = "full", ts(optional))] pub body: Option, pub creator_id: PersonId, pub community_id: CommunityId, @@ -29,35 +30,40 @@ pub struct Post { /// Whether the post is locked. pub locked: bool, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, /// Whether the post is deleted. pub deleted: bool, /// Whether the post is NSFW. pub nsfw: bool, /// A title for the link. + #[cfg_attr(feature = "full", ts(optional))] pub embed_title: Option, /// A description for the link. + #[cfg_attr(feature = "full", ts(optional))] pub embed_description: Option, - #[cfg_attr(feature = "full", ts(type = "string"))] /// A thumbnail picture url. + #[cfg_attr(feature = "full", ts(optional))] pub thumbnail_url: Option, - #[cfg_attr(feature = "full", ts(type = "string"))] /// The federated activity id / ap_id. pub ap_id: DbUrl, /// Whether the post is local. pub local: bool, - #[cfg_attr(feature = "full", ts(type = "string"))] /// A video url for the link. + #[cfg_attr(feature = "full", ts(optional))] pub embed_video_url: Option, pub language_id: LanguageId, /// Whether the post is featured to its community. pub featured_community: bool, /// Whether the post is featured to its site. pub featured_local: bool, + #[cfg_attr(feature = "full", ts(optional))] pub url_content_type: Option, /// An optional alt_text, usable for image posts. + #[cfg_attr(feature = "full", ts(optional))] pub alt_text: Option, /// Time at which the post will be published. None means publish immediately. + #[cfg_attr(feature = "full", ts(optional))] pub scheduled_publish_time: Option>, } diff --git a/crates/db_schema/src/source/post_report.rs b/crates/db_schema/src/source/post_report.rs index 9aee9ed97..610e495ae 100644 --- a/crates/db_schema/src/source/post_report.rs +++ b/crates/db_schema/src/source/post_report.rs @@ -25,13 +25,17 @@ pub struct PostReport { /// The original post title. pub original_post_name: String, /// The original post url. + #[cfg_attr(feature = "full", ts(optional))] pub original_post_url: Option, /// The original post body. + #[cfg_attr(feature = "full", ts(optional))] pub original_post_body: Option, pub reason: String, pub resolved: bool, + #[cfg_attr(feature = "full", ts(optional))] pub resolver_id: Option, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, } diff --git a/crates/db_schema/src/source/private_message.rs b/crates/db_schema/src/source/private_message.rs index 8afaa14f1..f15373907 100644 --- a/crates/db_schema/src/source/private_message.rs +++ b/crates/db_schema/src/source/private_message.rs @@ -29,6 +29,7 @@ pub struct PrivateMessage { pub deleted: bool, pub read: bool, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, pub ap_id: DbUrl, pub local: bool, diff --git a/crates/db_schema/src/source/private_message_report.rs b/crates/db_schema/src/source/private_message_report.rs index 7b4c8c637..570f55584 100644 --- a/crates/db_schema/src/source/private_message_report.rs +++ b/crates/db_schema/src/source/private_message_report.rs @@ -29,8 +29,10 @@ pub struct PrivateMessageReport { pub original_pm_text: String, pub reason: String, pub resolved: bool, + #[cfg_attr(feature = "full", ts(optional))] pub resolver_id: Option, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, } diff --git a/crates/db_schema/src/source/registration_application.rs b/crates/db_schema/src/source/registration_application.rs index 2ac973f34..f01c042d9 100644 --- a/crates/db_schema/src/source/registration_application.rs +++ b/crates/db_schema/src/source/registration_application.rs @@ -18,7 +18,9 @@ pub struct RegistrationApplication { pub id: RegistrationApplicationId, pub local_user_id: LocalUserId, pub answer: String, + #[cfg_attr(feature = "full", ts(optional))] pub admin_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub deny_reason: Option, pub published: DateTime, } diff --git a/crates/db_schema/src/source/site.rs b/crates/db_schema/src/source/site.rs index 0ec4043e4..0fe33de01 100644 --- a/crates/db_schema/src/source/site.rs +++ b/crates/db_schema/src/source/site.rs @@ -21,14 +21,19 @@ pub struct Site { pub id: SiteId, pub name: String, /// A sidebar for the site in markdown. + #[cfg_attr(feature = "full", ts(optional))] pub sidebar: Option, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, /// An icon URL. + #[cfg_attr(feature = "full", ts(optional))] pub icon: Option, /// A banner url. + #[cfg_attr(feature = "full", ts(optional))] pub banner: Option, /// A shorter, one-line description of the site. + #[cfg_attr(feature = "full", ts(optional))] pub description: Option, /// The federated actor_id. pub actor_id: DbUrl, @@ -43,6 +48,7 @@ pub struct Site { pub instance_id: InstanceId, /// If present, nsfw content is visible by default. Should be displayed by frontends/clients /// when the site is first opened by a user. + #[cfg_attr(feature = "full", ts(optional))] pub content_warning: Option, } diff --git a/crates/db_schema/src/source/tagline.rs b/crates/db_schema/src/source/tagline.rs index 05f7e0520..80c045a0a 100644 --- a/crates/db_schema/src/source/tagline.rs +++ b/crates/db_schema/src/source/tagline.rs @@ -17,6 +17,7 @@ pub struct Tagline { pub id: i32, pub content: String, pub published: DateTime, + #[cfg_attr(feature = "full", ts(optional))] pub updated: Option>, } diff --git a/crates/db_views/src/structs.rs b/crates/db_views/src/structs.rs index 3c219d63f..4586fbcac 100644 --- a/crates/db_views/src/structs.rs +++ b/crates/db_views/src/structs.rs @@ -48,7 +48,9 @@ pub struct CommentReportView { pub creator_blocked: bool, pub subscribed: SubscribedType, pub saved: bool, + #[cfg_attr(feature = "full", ts(optional))] pub my_vote: Option, + #[cfg_attr(feature = "full", ts(optional))] pub resolver: Option, } @@ -71,6 +73,7 @@ pub struct CommentView { pub subscribed: SubscribedType, pub saved: bool, pub creator_blocked: bool, + #[cfg_attr(feature = "full", ts(optional))] pub my_vote: Option, } @@ -106,9 +109,11 @@ pub struct PostReportView { pub read: bool, pub hidden: bool, pub creator_blocked: bool, + #[cfg_attr(feature = "full", ts(optional))] pub my_vote: Option, pub unread_comments: i64, pub counts: PostAggregates, + #[cfg_attr(feature = "full", ts(optional))] pub resolver: Option, } @@ -131,6 +136,7 @@ pub struct PostView { pub post: Post, pub creator: Person, pub community: Community, + #[cfg_attr(feature = "full", ts(optional))] pub image_details: Option, pub creator_banned_from_community: bool, pub banned_from_community: bool, @@ -142,6 +148,7 @@ pub struct PostView { pub read: bool, pub hidden: bool, pub creator_blocked: bool, + #[cfg_attr(feature = "full", ts(optional))] pub my_vote: Option, pub unread_comments: i64, } @@ -168,6 +175,7 @@ pub struct PrivateMessageReportView { pub private_message: PrivateMessage, pub private_message_creator: Person, pub creator: Person, + #[cfg_attr(feature = "full", ts(optional))] pub resolver: Option, } @@ -181,6 +189,7 @@ pub struct RegistrationApplicationView { pub registration_application: RegistrationApplication, pub creator_local_user: LocalUser, pub creator: Person, + #[cfg_attr(feature = "full", ts(optional))] pub admin: Option, } diff --git a/crates/db_views_actor/src/structs.rs b/crates/db_views_actor/src/structs.rs index ecf9ba11d..db5cb1899 100644 --- a/crates/db_views_actor/src/structs.rs +++ b/crates/db_views_actor/src/structs.rs @@ -109,6 +109,7 @@ pub struct PersonMentionView { pub subscribed: SubscribedType, pub saved: bool, pub creator_blocked: bool, + #[cfg_attr(feature = "full", ts(optional))] pub my_vote: Option, } @@ -133,6 +134,7 @@ pub struct CommentReplyView { pub subscribed: SubscribedType, pub saved: bool, pub creator_blocked: bool, + #[cfg_attr(feature = "full", ts(optional))] pub my_vote: Option, } diff --git a/crates/db_views_moderator/src/structs.rs b/crates/db_views_moderator/src/structs.rs index 10ad78942..27ee82522 100644 --- a/crates/db_views_moderator/src/structs.rs +++ b/crates/db_views_moderator/src/structs.rs @@ -39,6 +39,7 @@ use ts_rs::TS; /// When someone is added as a community moderator. pub struct ModAddCommunityView { pub mod_add_community: ModAddCommunity, + #[cfg_attr(feature = "full", ts(optional))] pub moderator: Option, pub community: Community, pub modded_person: Person, @@ -52,6 +53,7 @@ pub struct ModAddCommunityView { /// When someone is added as a site moderator. pub struct ModAddView { pub mod_add: ModAdd, + #[cfg_attr(feature = "full", ts(optional))] pub moderator: Option, pub modded_person: Person, } @@ -64,6 +66,7 @@ pub struct ModAddView { /// When someone is banned from a community. pub struct ModBanFromCommunityView { pub mod_ban_from_community: ModBanFromCommunity, + #[cfg_attr(feature = "full", ts(optional))] pub moderator: Option, pub community: Community, pub banned_person: Person, @@ -77,6 +80,7 @@ pub struct ModBanFromCommunityView { /// When someone is banned from the site. pub struct ModBanView { pub mod_ban: ModBan, + #[cfg_attr(feature = "full", ts(optional))] pub moderator: Option, pub banned_person: Person, } @@ -89,6 +93,7 @@ pub struct ModBanView { /// When a community is hidden from public view. pub struct ModHideCommunityView { pub mod_hide_community: ModHideCommunity, + #[cfg_attr(feature = "full", ts(optional))] pub admin: Option, pub community: Community, } @@ -101,6 +106,7 @@ pub struct ModHideCommunityView { /// When a moderator locks a post (prevents new comments being made). pub struct ModLockPostView { pub mod_lock_post: ModLockPost, + #[cfg_attr(feature = "full", ts(optional))] pub moderator: Option, pub post: Post, pub community: Community, @@ -114,6 +120,7 @@ pub struct ModLockPostView { /// When a moderator removes a comment. pub struct ModRemoveCommentView { pub mod_remove_comment: ModRemoveComment, + #[cfg_attr(feature = "full", ts(optional))] pub moderator: Option, pub comment: Comment, pub commenter: Person, @@ -129,6 +136,7 @@ pub struct ModRemoveCommentView { /// When a moderator removes a community. pub struct ModRemoveCommunityView { pub mod_remove_community: ModRemoveCommunity, + #[cfg_attr(feature = "full", ts(optional))] pub moderator: Option, pub community: Community, } @@ -141,6 +149,7 @@ pub struct ModRemoveCommunityView { /// When a moderator removes a post. pub struct ModRemovePostView { pub mod_remove_post: ModRemovePost, + #[cfg_attr(feature = "full", ts(optional))] pub moderator: Option, pub post: Post, pub community: Community, @@ -154,6 +163,7 @@ pub struct ModRemovePostView { /// When a moderator features a post on a community (pins it to the top). pub struct ModFeaturePostView { pub mod_feature_post: ModFeaturePost, + #[cfg_attr(feature = "full", ts(optional))] pub moderator: Option, pub post: Post, pub community: Community, @@ -167,6 +177,7 @@ pub struct ModFeaturePostView { /// When a moderator transfers a community to a new owner. pub struct ModTransferCommunityView { pub mod_transfer_community: ModTransferCommunity, + #[cfg_attr(feature = "full", ts(optional))] pub moderator: Option, pub community: Community, pub modded_person: Person, @@ -180,6 +191,7 @@ pub struct ModTransferCommunityView { /// When an admin purges a comment. pub struct AdminPurgeCommentView { pub admin_purge_comment: AdminPurgeComment, + #[cfg_attr(feature = "full", ts(optional))] pub admin: Option, pub post: Post, } @@ -192,6 +204,7 @@ pub struct AdminPurgeCommentView { /// When an admin purges a community. pub struct AdminPurgeCommunityView { pub admin_purge_community: AdminPurgeCommunity, + #[cfg_attr(feature = "full", ts(optional))] pub admin: Option, } @@ -203,6 +216,7 @@ pub struct AdminPurgeCommunityView { /// When an admin purges a person. pub struct AdminPurgePersonView { pub admin_purge_person: AdminPurgePerson, + #[cfg_attr(feature = "full", ts(optional))] pub admin: Option, } @@ -214,6 +228,7 @@ pub struct AdminPurgePersonView { /// When an admin purges a post. pub struct AdminPurgePostView { pub admin_purge_post: AdminPurgePost, + #[cfg_attr(feature = "full", ts(optional))] pub admin: Option, pub community: Community, } @@ -225,12 +240,19 @@ pub struct AdminPurgePostView { #[cfg_attr(feature = "full", ts(export))] /// Querying / filtering the modlog. pub struct ModlogListParams { + #[cfg_attr(feature = "full", ts(optional))] pub community_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub mod_person_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub other_person_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub post_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub comment_id: Option, + #[cfg_attr(feature = "full", ts(optional))] pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] pub limit: Option, pub hide_modlog_names: bool, } diff --git a/crates/utils/src/error.rs b/crates/utils/src/error.rs index c95af03e2..75cecc41f 100644 --- a/crates/utils/src/error.rs +++ b/crates/utils/src/error.rs @@ -119,7 +119,10 @@ pub enum LemmyErrorType { InvalidUrl, EmailSendFailed, Slurs, - RegistrationDenied(Option), + RegistrationDenied { + #[cfg_attr(feature = "full", ts(optional))] + reason: Option, + }, SiteNameRequired, SiteNameLengthOverflow, PermissiveRegex, @@ -147,7 +150,10 @@ pub enum LemmyErrorType { CommunityHasNoFollowers, PostScheduleTimeMustBeInFuture, TooManyScheduledPosts, - FederationError(Option), + FederationError { + #[cfg_attr(feature = "full", ts(optional))] + error: Option, + }, } /// Federation related errors, these dont need to be translated. @@ -262,7 +268,7 @@ cfg_if! { fn from(error_type: FederationError) -> Self { let inner = anyhow::anyhow!("{}", error_type); LemmyError { - error_type: LemmyErrorType::FederationError(Some(error_type)), + error_type: LemmyErrorType::FederationError { error: Some(error_type) }, inner, context: Backtrace::capture(), } diff --git a/scripts/ts_bindings_check.sh b/scripts/ts_bindings_check.sh new file mode 100755 index 000000000..a925081c8 --- /dev/null +++ b/scripts/ts_bindings_check.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -e + +# This check is only used for CI. + +CWD="$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)" + +cd "$CWD/../" + +# Export the ts-rs bindings +cargo test --workspace export_bindings + +# Make sure no rows are returned +! grep -nr --include=\*.ts ' | null' ./crates/ From a55e7fd9fe3c42cdaa3aeb423b1707b393cea2a8 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Wed, 6 Nov 2024 10:20:30 -0500 Subject: [PATCH 14/19] Trying to use w3.org as a sample site to fix tests. (#5170) - #5167 --- api_tests/src/shared.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api_tests/src/shared.ts b/api_tests/src/shared.ts index 017dad903..20cb171c5 100644 --- a/api_tests/src/shared.ts +++ b/api_tests/src/shared.ts @@ -83,7 +83,7 @@ export const fetchFunction = fetch; export const imageFetchLimit = 50; export const sampleImage = "https://i.pinimg.com/originals/df/5f/5b/df5f5b1b174a2b4b6026cc6c8f9395c1.jpg"; -export const sampleSite = "https://google.com"; +export const sampleSite = "https://w3.org"; export const alphaUrl = "http://127.0.0.1:8541"; export const betaUrl = "http://127.0.0.1:8551"; From 917e408735cd9347096e1d6f1e5a2bcfd3cf745f Mon Sep 17 00:00:00 2001 From: Dessalines Date: Wed, 6 Nov 2024 10:58:40 -0500 Subject: [PATCH 15/19] Fix postgres connection options causing slow query speed. (#5150) * Adding a query speed check. * Fixing slow queries due to connection config options. * Remove pointless set_config sql function. * Removing pointless bool. * Removing comment * Removing test.sh changes. * Add analyze to speed up query * Trying to fix DB perf connection try #1 * Try encoding option * Fix woodpecker * Try to use path character. * Fixing lemmy config location. * Removing pointless connection options. * Use OnceLock to create a once-init psql connection. * Fixing comment. * Fix host encoding for dev DB. * Address PR comments. * Revert query mut change. --- .woodpecker.yml | 4 +- crates/db_schema/src/utils.rs | 56 ++++++++++++++++------------ crates/db_views/src/post_view.rs | 64 +++++++++++++++++++++++++++++++- scripts/start_dev_db.sh | 6 ++- 4 files changed, 100 insertions(+), 30 deletions(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index 16cd49375..8930c21fc 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -122,7 +122,6 @@ steps: environment: CARGO_HOME: .cargo_home commands: - - export LEMMY_CONFIG_LOCATION=./config/config.hjson - ./scripts/update_config_defaults.sh config/defaults_current.hjson - diff config/defaults.hjson config/defaults_current.hjson when: *slow_check_paths @@ -147,7 +146,6 @@ steps: CARGO_HOME: .cargo_home commands: # same as scripts/db_perf.sh but without creating a new database server - - export LEMMY_CONFIG_LOCATION=config/config.hjson - cargo run --package lemmy_db_perf -- --posts 10 --read-post-pages 1 when: *slow_check_paths @@ -176,8 +174,8 @@ steps: RUST_BACKTRACE: "1" CARGO_HOME: .cargo_home LEMMY_TEST_FAST_FEDERATION: "1" + LEMMY_CONFIG_LOCATION: ../../config/config.hjson commands: - - export LEMMY_CONFIG_LOCATION=../../config/config.hjson - cargo test --workspace --no-fail-fast when: *slow_check_paths diff --git a/crates/db_schema/src/utils.rs b/crates/db_schema/src/utils.rs index 1e56563bc..6c5b792eb 100644 --- a/crates/db_schema/src/utils.rs +++ b/crates/db_schema/src/utils.rs @@ -22,7 +22,6 @@ use diesel_async::{ ManagerConfig, }, AsyncConnection, - RunQueryDsl, }; use futures_util::{future::BoxFuture, Future, FutureExt}; use i_love_jesus::CursorKey; @@ -47,7 +46,7 @@ use rustls::{ }; use std::{ ops::{Deref, DerefMut}, - sync::{Arc, LazyLock}, + sync::{Arc, LazyLock, OnceLock}, time::Duration, }; use tracing::error; @@ -59,6 +58,8 @@ pub const SITEMAP_LIMIT: i64 = 50000; pub const SITEMAP_DAYS: Option = TimeDelta::try_days(31); pub const RANK_DEFAULT: f64 = 0.0001; +/// Some connection options to speed up queries +const CONNECTION_OPTIONS: [&str; 1] = ["geqo_threshold=12"]; pub type ActualDbPool = Pool; /// References a pool or connection. Functions must take `&mut DbPool<'_>` to allow implicit @@ -345,10 +346,37 @@ pub fn diesel_url_create(opt: Option<&str>) -> LemmyResult> { } } +/// Sets a few additional config options necessary for starting lemmy +fn build_config_options_uri_segment(config: &str) -> String { + let mut url = Url::parse(config).expect("Couldn't parse postgres connection URI"); + + // Set `lemmy.protocol_and_hostname` so triggers can use it + let lemmy_protocol_and_hostname_option = + "lemmy.protocol_and_hostname=".to_owned() + &SETTINGS.get_protocol_and_hostname(); + let mut options = CONNECTION_OPTIONS.to_vec(); + options.push(&lemmy_protocol_and_hostname_option); + + // Create the connection uri portion + let options_segments = options + .iter() + .map(|o| "-c ".to_owned() + o) + .collect::>() + .join(" "); + + url.set_query(Some(&format!("options={options_segments}"))); + url.into() +} + fn establish_connection(config: &str) -> BoxFuture> { let fut = async { + /// Use a once_lock to create the postgres connection config, since this config never changes + static POSTGRES_CONFIG_WITH_OPTIONS: OnceLock = OnceLock::new(); + + let config = + POSTGRES_CONFIG_WITH_OPTIONS.get_or_init(|| build_config_options_uri_segment(config)); + // We only support TLS with sslmode=require currently - let mut conn = if config.contains("sslmode=require") { + let conn = if config.contains("sslmode=require") { let rustls_config = DangerousClientConfigBuilder { cfg: ClientConfig::builder(), } @@ -369,24 +397,6 @@ fn establish_connection(config: &str) -> BoxFuture = LazyLock::new(|| { }); pub mod functions { - use diesel::sql_types::{BigInt, Bool, Text, Timestamptz}; + use diesel::sql_types::{BigInt, Text, Timestamptz}; sql_function! { #[sql_name = "r.hot_rank"] @@ -521,8 +531,6 @@ pub mod functions { // really this function is variadic, this just adds the two-argument version sql_function!(fn coalesce(x: diesel::sql_types::Nullable, y: T) -> T); - - sql_function!(fn set_config(setting_name: Text, new_value: Text, is_local: Bool) -> Text); } pub const DELETED_REPLACEMENT_TEXT: &str = "*Permanently Deleted*"; diff --git a/crates/db_views/src/post_view.rs b/crates/db_views/src/post_view.rs index 13520f1cf..dc00b0438 100644 --- a/crates/db_views/src/post_view.rs +++ b/crates/db_views/src/post_view.rs @@ -734,6 +734,7 @@ mod tests { structs::LocalUserView, }; use chrono::Utc; + use diesel_async::SimpleAsyncConnection; use lemmy_db_schema::{ aggregates::structs::PostAggregates, impls::actor_language::UNDETERMINED_ID, @@ -774,7 +775,7 @@ mod tests { site::Site, }, traits::{Bannable, Blockable, Crud, Followable, Joinable, Likeable, Saveable}, - utils::{build_db_pool, build_db_pool_for_tests, DbPool, RANK_DEFAULT}, + utils::{build_db_pool, build_db_pool_for_tests, get_conn, DbPool, RANK_DEFAULT}, CommunityVisibility, PostSortType, SubscribedType, @@ -782,7 +783,10 @@ mod tests { use lemmy_utils::error::LemmyResult; use pretty_assertions::assert_eq; use serial_test::serial; - use std::{collections::HashSet, time::Duration}; + use std::{ + collections::HashSet, + time::{Duration, Instant}, + }; use url::Url; const POST_WITH_ANOTHER_TITLE: &str = "Another title"; @@ -1995,6 +1999,62 @@ mod tests { cleanup(data, pool).await } + #[tokio::test] + #[serial] + async fn speed_check() -> LemmyResult<()> { + let pool = &build_db_pool().await?; + let pool = &mut pool.into(); + let data = init_data(pool).await?; + + // Make sure the post_view query is less than this time + let duration_max = Duration::from_millis(40); + + // Create some dummy posts + let num_posts = 1000; + for x in 1..num_posts { + let name = format!("post_{x}"); + let url = Some(Url::parse(&format!("https://google.com/{name}"))?.into()); + + let post_form = PostInsertForm { + url, + ..PostInsertForm::new( + name, + data.local_user_view.person.id, + data.inserted_community.id, + ) + }; + Post::create(pool, &post_form).await?; + } + + // Manually trigger and wait for a statistics update to ensure consistent and high amount of + // accuracy in the statistics used for query planning + println!("🧮 updating database statistics"); + let conn = &mut get_conn(pool).await?; + conn.batch_execute("ANALYZE;").await?; + + // Time how fast the query took + let now = Instant::now(); + PostQuery { + sort: Some(PostSortType::Active), + local_user: Some(&data.local_user_view.local_user), + ..Default::default() + } + .list(&data.site, pool) + .await?; + + let elapsed = now.elapsed(); + println!("Elapsed: {:.0?}", elapsed); + + assert!( + elapsed.lt(&duration_max), + "Query took {:.0?}, longer than the max of {:.0?}", + elapsed, + duration_max + ); + + cleanup(data, pool).await + } + #[tokio::test] #[serial] async fn post_listings_no_comments_only() -> LemmyResult<()> { diff --git a/scripts/start_dev_db.sh b/scripts/start_dev_db.sh index 5965316ba..1cbe9e16a 100644 --- a/scripts/start_dev_db.sh +++ b/scripts/start_dev_db.sh @@ -2,8 +2,12 @@ export PGDATA="$PWD/dev_pgdata" export PGHOST=$PWD + +# Necessary to encode the dev db path into proper URL params +export ENCODED_HOST=$(printf $PWD | jq -sRr @uri) + export PGUSER=postgres -export DATABASE_URL="postgresql://lemmy:password@/lemmy?host=$PWD" +export DATABASE_URL="postgresql://lemmy:password@$ENCODED_HOST/lemmy" export LEMMY_DATABASE_URL=$DATABASE_URL export PGDATABASE=lemmy From ad90cd77f9602205671ae4211f230e4fd415420d Mon Sep 17 00:00:00 2001 From: Nutomic Date: Thu, 7 Nov 2024 11:49:05 +0100 Subject: [PATCH 16/19] Implement private communities (#5076) * add private visibility * filter private communities in post_view.rs * also filter in comment_view * community follower state * remove unused method * sql fmt * add CommunityFollower.approved_by * implement api endpoints * api changes * only admins can create private community for now * add local api tests * fix api tests * follow remote private community * use authorized fetch for content in private community * federate community visibility * dont mark content in private community as public * expose ApprovalRequired in api * also check content fetchable for outbox/featured * address private community content to followers * implement reject activity * fix tests * add files * remove local api tests * dont use delay * is_new_instance * single query for is_new_instance * return subscribed type for pending follow * working * need to catch errors in waitUntil * clippy * fix query * lint for unused async * diesel.toml comment * add comment * avoid db reads * rename approved_by to approver_id * add helper * form init * list pending follows should return items for all communities * clippy * ci * fix down migration * fix api tests * references * rename * run git diff * ci * fix schema check * fix joins * ci * ci * skip_serializing_none * fix test --------- Co-authored-by: Dessalines --- .woodpecker.yml | 2 +- Cargo.toml | 1 + api_tests/package.json | 5 +- api_tests/pnpm-lock.yaml | 10 +- api_tests/src/private_community.spec.ts | 214 +++++++++++++++ api_tests/src/shared.ts | 54 +++- crates/api/src/comment/distinguish.rs | 4 +- crates/api/src/comment/like.rs | 5 +- crates/api/src/comment_report/create.rs | 5 +- crates/api/src/comment_report/resolve.rs | 2 +- crates/api/src/community/add_mod.rs | 12 +- crates/api/src/community/ban.rs | 14 +- crates/api/src/community/block.rs | 10 +- crates/api/src/community/follow.rs | 57 ++-- crates/api/src/community/hide.rs | 3 +- crates/api/src/community/mod.rs | 1 + .../src/community/pending_follows/approve.rs | 46 ++++ .../src/community/pending_follows/count.rs | 25 ++ .../api/src/community/pending_follows/list.rs | 29 +++ .../api/src/community/pending_follows/mod.rs | 3 + crates/api/src/community/transfer.rs | 8 +- crates/api/src/lib.rs | 9 +- crates/api/src/local_user/ban_person.rs | 3 +- crates/api/src/post/feature.rs | 7 +- crates/api/src/post/like.rs | 22 +- crates/api/src/post/lock.rs | 11 +- crates/api/src/post_report/create.rs | 5 +- crates/api/src/post_report/resolve.rs | 2 +- crates/api/src/site/purge/comment.rs | 3 +- crates/api/src/site/purge/community.rs | 3 +- crates/api/src/site/purge/person.rs | 3 +- crates/api/src/site/purge/post.rs | 3 +- crates/api/src/sitemap.rs | 8 +- crates/api_common/src/claims.rs | 2 +- crates/api_common/src/community.rs | 48 ++++ crates/api_common/src/context.rs | 2 +- crates/api_common/src/request.rs | 2 +- crates/api_common/src/send_activity.rs | 7 +- crates/api_common/src/utils.rs | 22 +- crates/api_crud/src/comment/create.rs | 10 +- crates/api_crud/src/comment/delete.rs | 5 +- crates/api_crud/src/comment/remove.rs | 5 +- crates/api_crud/src/comment/update.rs | 5 +- crates/api_crud/src/community/create.rs | 11 +- crates/api_crud/src/community/delete.rs | 9 +- crates/api_crud/src/community/mod.rs | 17 ++ crates/api_crud/src/community/remove.rs | 6 +- crates/api_crud/src/community/update.rs | 7 +- crates/api_crud/src/post/create.rs | 15 +- crates/api_crud/src/post/delete.rs | 16 +- crates/api_crud/src/post/remove.rs | 11 +- crates/api_crud/src/post/update.rs | 18 +- crates/api_crud/src/private_message/create.rs | 3 +- crates/api_crud/src/private_message/delete.rs | 3 +- crates/api_crud/src/private_message/update.rs | 3 +- crates/api_crud/src/user/delete.rs | 3 +- .../apub/src/activities/block/block_user.rs | 21 +- crates/apub/src/activities/block/mod.rs | 12 + .../src/activities/block/undo_block_user.rs | 15 +- .../apub/src/activities/community/announce.rs | 9 +- .../activities/community/collection_add.rs | 11 +- .../activities/community/collection_remove.rs | 11 +- .../src/activities/community/lock_page.rs | 13 +- .../apub/src/activities/community/update.rs | 9 +- .../activities/create_or_update/comment.rs | 8 +- .../src/activities/create_or_update/post.rs | 8 +- crates/apub/src/activities/deletion/delete.rs | 4 +- crates/apub/src/activities/deletion/mod.rs | 26 +- .../src/activities/deletion/undo_delete.rs | 4 +- .../apub/src/activities/following/follow.rs | 24 +- crates/apub/src/activities/following/mod.rs | 49 +++- .../apub/src/activities/following/reject.rs | 79 ++++++ .../src/activities/following/undo_follow.rs | 6 +- crates/apub/src/activities/mod.rs | 30 +++ crates/apub/src/activity_lists.rs | 9 +- crates/apub/src/api/user_settings_backup.rs | 21 +- .../src/fetcher/site_or_community_or_user.rs | 11 + crates/apub/src/http/comment.rs | 13 +- crates/apub/src/http/community.rs | 53 ++-- crates/apub/src/http/mod.rs | 49 +++- crates/apub/src/http/post.rs | 14 +- crates/apub/src/objects/comment.rs | 8 +- crates/apub/src/objects/community.rs | 9 +- crates/apub/src/objects/post.rs | 7 +- .../src/protocol/activities/following/mod.rs | 1 + .../protocol/activities/following/reject.rs | 24 ++ crates/apub/src/protocol/objects/group.rs | 2 + crates/db_perf/src/main.rs | 2 +- .../src/aggregates/comment_aggregates.rs | 2 +- .../src/aggregates/community_aggregates.rs | 19 +- .../src/aggregates/person_aggregates.rs | 2 +- .../src/aggregates/post_aggregates.rs | 4 +- .../src/aggregates/site_aggregates.rs | 4 +- crates/db_schema/src/impls/activity.rs | 4 +- crates/db_schema/src/impls/actor_language.rs | 12 +- crates/db_schema/src/impls/captcha_answer.rs | 4 +- crates/db_schema/src/impls/comment.rs | 2 +- crates/db_schema/src/impls/community.rs | 58 +++-- .../src/impls/federation_allowlist.rs | 2 +- crates/db_schema/src/impls/language.rs | 2 +- crates/db_schema/src/impls/local_user.rs | 5 +- crates/db_schema/src/impls/moderator.rs | 2 +- .../src/impls/password_reset_request.rs | 2 +- crates/db_schema/src/impls/person.rs | 4 +- crates/db_schema/src/impls/post.rs | 2 +- crates/db_schema/src/impls/post_report.rs | 4 +- crates/db_schema/src/impls/private_message.rs | 2 +- crates/db_schema/src/lib.rs | 5 +- crates/db_schema/src/schema.rs | 29 ++- crates/db_schema/src/source/community.rs | 25 +- crates/db_schema/src/utils.rs | 6 +- crates/db_views/src/comment_report_view.rs | 5 +- crates/db_views/src/comment_view.rs | 174 +++++++++++-- crates/db_views/src/post_report_view.rs | 5 +- crates/db_views/src/post_view.rs | 195 +++++++++++--- .../src/private_message_report_view.rs | 2 +- crates/db_views/src/private_message_view.rs | 6 +- .../src/registration_application_view.rs | 2 +- crates/db_views/src/vote_view.rs | 2 +- crates/db_views_actor/Cargo.toml | 3 +- .../db_views_actor/src/comment_reply_view.rs | 17 +- .../src/community_follower_view.rs | 243 +++++++++++++++++- crates/db_views_actor/src/community_view.rs | 130 +++++++--- .../db_views_actor/src/person_mention_view.rs | 17 +- crates/db_views_actor/src/person_view.rs | 8 +- crates/db_views_actor/src/structs.rs | 11 + crates/utils/src/error.rs | 1 + diesel.toml | 2 + .../down.sql | 52 ++++ .../up.sql | 47 ++++ scripts/test.sh | 4 +- src/api_routes_http.rs | 14 +- src/lib.rs | 2 +- src/prometheus_metrics.rs | 4 +- src/scheduled_tasks.rs | 1 - src/session_middleware.rs | 2 +- 136 files changed, 1980 insertions(+), 551 deletions(-) create mode 100644 api_tests/src/private_community.spec.ts create mode 100644 crates/api/src/community/pending_follows/approve.rs create mode 100644 crates/api/src/community/pending_follows/count.rs create mode 100644 crates/api/src/community/pending_follows/list.rs create mode 100644 crates/api/src/community/pending_follows/mod.rs create mode 100644 crates/apub/src/activities/following/reject.rs create mode 100644 crates/apub/src/protocol/activities/following/reject.rs create mode 100644 migrations/2024-10-29-090055_private-community/down.sql create mode 100644 migrations/2024-10-29-090055_private-community/up.sql diff --git a/.woodpecker.yml b/.woodpecker.yml index 8930c21fc..060cc3e26 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -133,8 +133,8 @@ steps: DATABASE_URL: postgres://lemmy:password@database:5432/lemmy commands: - <<: *install_diesel_cli + - cp crates/db_schema/src/schema.rs tmp.schema - diesel migration run - - diesel print-schema --config-file=diesel.toml > tmp.schema - diff tmp.schema crates/db_schema/src/schema.rs when: *slow_check_paths diff --git a/Cargo.toml b/Cargo.toml index 0373c4e51..8db7b8b8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -78,6 +78,7 @@ uninlined_format_args = "allow" unused_self = "deny" unwrap_used = "deny" unimplemented = "deny" +unused_async = "deny" [workspace.dependencies] lemmy_api = { version = "=0.19.6-beta.7", path = "./crates/api" } diff --git a/api_tests/package.json b/api_tests/package.json index 81e518ea4..9a5057c00 100644 --- a/api_tests/package.json +++ b/api_tests/package.json @@ -10,12 +10,13 @@ "scripts": { "lint": "tsc --noEmit && eslint --report-unused-disable-directives && prettier --check 'src/**/*.ts'", "fix": "prettier --write src && eslint --fix src", - "api-test": "jest -i follow.spec.ts && jest -i image.spec.ts && jest -i user.spec.ts && jest -i private_message.spec.ts && jest -i community.spec.ts && jest -i post.spec.ts && jest -i comment.spec.ts ", + "api-test": "jest -i follow.spec.ts && jest -i image.spec.ts && jest -i user.spec.ts && jest -i private_message.spec.ts && jest -i community.spec.ts && jest -i private_community.spec.ts && jest -i post.spec.ts && jest -i comment.spec.ts ", "api-test-follow": "jest -i follow.spec.ts", "api-test-comment": "jest -i comment.spec.ts", "api-test-post": "jest -i post.spec.ts", "api-test-user": "jest -i user.spec.ts", "api-test-community": "jest -i community.spec.ts", + "api-test-private-community": "jest -i private_community.spec.ts", "api-test-private-message": "jest -i private_message.spec.ts", "api-test-image": "jest -i image.spec.ts" }, @@ -27,7 +28,7 @@ "eslint": "^9.9.0", "eslint-plugin-prettier": "^5.1.3", "jest": "^29.5.0", - "lemmy-js-client": "0.20.0-alpha.11", + "lemmy-js-client": "0.20.0-private-community.9", "prettier": "^3.2.5", "ts-jest": "^29.1.0", "typescript": "^5.5.4", diff --git a/api_tests/pnpm-lock.yaml b/api_tests/pnpm-lock.yaml index dd357d248..b1f18622e 100644 --- a/api_tests/pnpm-lock.yaml +++ b/api_tests/pnpm-lock.yaml @@ -30,8 +30,8 @@ importers: specifier: ^29.5.0 version: 29.7.0(@types/node@22.8.6) lemmy-js-client: - specifier: 0.20.0-alpha.11 - version: 0.20.0-alpha.11 + specifier: 0.20.0-private-community.9 + version: 0.20.0-private-community.9 prettier: specifier: ^3.2.5 version: 3.3.3 @@ -1159,8 +1159,8 @@ packages: resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} engines: {node: '>=6'} - lemmy-js-client@0.20.0-alpha.11: - resolution: {integrity: sha512-iRSG4xHMjPDIreQqVIoJ5JrMY71uk07G0Zbgyf068xKbib22J3+i1x/XgCTs6tiHlqTnw1Ig/KRq7p7qJoA4uw==} + lemmy-js-client@0.20.0-private-community.9: + resolution: {integrity: sha512-iuFezswCzIco5U5Q4Eo8HAWVE65pDW2zeO+fYLEyFl30SLw9a3gqJkip2vbDfVvoAjDXyUskZKddf1Nnj8mVcg==} leven@3.1.0: resolution: {integrity: sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==} @@ -3061,7 +3061,7 @@ snapshots: kleur@3.0.3: {} - lemmy-js-client@0.20.0-alpha.11: {} + lemmy-js-client@0.20.0-private-community.9: {} leven@3.1.0: {} diff --git a/api_tests/src/private_community.spec.ts b/api_tests/src/private_community.spec.ts new file mode 100644 index 000000000..76faf800f --- /dev/null +++ b/api_tests/src/private_community.spec.ts @@ -0,0 +1,214 @@ +jest.setTimeout(120000); + +import { FollowCommunity } from "lemmy-js-client"; +import { + alpha, + setupLogins, + createCommunity, + unfollows, + registerUser, + listCommunityPendingFollows, + getCommunity, + getCommunityPendingFollowsCount, + approveCommunityPendingFollow, + randomString, + createPost, + createComment, + beta, + resolveCommunity, + betaUrl, + resolvePost, + resolveComment, + likeComment, + waitUntil, +} from "./shared"; + +beforeAll(setupLogins); +afterAll(unfollows); + +test("Follow a private community", async () => { + // create private community + const community = await createCommunity(alpha, randomString(10), "Private"); + expect(community.community_view.community.visibility).toBe("Private"); + const alphaCommunityId = community.community_view.community.id; + + // No pending follows yet + const pendingFollows0 = await listCommunityPendingFollows(alpha); + expect(pendingFollows0.items.length).toBe(0); + const pendingFollowsCount0 = await getCommunityPendingFollowsCount( + alpha, + alphaCommunityId, + ); + expect(pendingFollowsCount0.count).toBe(0); + + // follow as new user + const user = await registerUser(beta, betaUrl); + const betaCommunity = ( + await resolveCommunity(user, community.community_view.community.actor_id) + ).community; + expect(betaCommunity).toBeDefined(); + const betaCommunityId = betaCommunity!.community.id; + const follow_form: FollowCommunity = { + community_id: betaCommunityId, + follow: true, + }; + await user.followCommunity(follow_form); + + // Follow listed as pending + const follow1 = await getCommunity(user, betaCommunityId); + expect(follow1.community_view.subscribed).toBe("ApprovalRequired"); + + // Wait for follow to federate, shown as pending + let pendingFollows1 = await waitUntil( + () => listCommunityPendingFollows(alpha), + f => f.items.length == 1, + ); + expect(pendingFollows1.items[0].is_new_instance).toBe(true); + const pendingFollowsCount1 = await getCommunityPendingFollowsCount( + alpha, + alphaCommunityId, + ); + expect(pendingFollowsCount1.count).toBe(1); + + // user still sees approval required at this point + const betaCommunity2 = await getCommunity(user, betaCommunityId); + expect(betaCommunity2.community_view.subscribed).toBe("ApprovalRequired"); + + // Approve the follow + const approve = await approveCommunityPendingFollow( + alpha, + alphaCommunityId, + pendingFollows1.items[0].person.id, + ); + expect(approve.success).toBe(true); + + // Follow is confirmed + await waitUntil( + () => getCommunity(user, betaCommunityId), + c => c.community_view.subscribed == "Subscribed", + ); + const pendingFollows2 = await listCommunityPendingFollows(alpha); + expect(pendingFollows2.items.length).toBe(0); + const pendingFollowsCount2 = await getCommunityPendingFollowsCount( + alpha, + alphaCommunityId, + ); + expect(pendingFollowsCount2.count).toBe(0); + + // follow with another user from that instance, is_new_instance should be false now + const user2 = await registerUser(beta, betaUrl); + await user2.followCommunity(follow_form); + let pendingFollows3 = await waitUntil( + () => listCommunityPendingFollows(alpha), + f => f.items.length == 1, + ); + expect(pendingFollows3.items[0].is_new_instance).toBe(false); + + // cleanup pending follow + const approve2 = await approveCommunityPendingFollow( + alpha, + alphaCommunityId, + pendingFollows3.items[0].person.id, + ); + expect(approve2.success).toBe(true); +}); + +test("Only followers can view and interact with private community content", async () => { + // create private community + const community = await createCommunity(alpha, randomString(10), "Private"); + expect(community.community_view.community.visibility).toBe("Private"); + const alphaCommunityId = community.community_view.community.id; + + // create post and comment + const post0 = await createPost(alpha, alphaCommunityId); + const post_id = post0.post_view.post.id; + expect(post_id).toBeDefined(); + const comment = await createComment(alpha, post_id); + const comment_id = comment.comment_view.comment.id; + expect(comment_id).toBeDefined(); + + // user is not following the community and cannot view nor create posts + const user = await registerUser(beta, betaUrl); + const betaCommunity = ( + await resolveCommunity(user, community.community_view.community.actor_id) + ).community!.community; + await expect(resolvePost(user, post0.post_view.post)).rejects.toStrictEqual( + Error("not_found"), + ); + await expect( + resolveComment(user, comment.comment_view.comment), + ).rejects.toStrictEqual(Error("not_found")); + await expect(createPost(user, betaCommunity.id)).rejects.toStrictEqual( + Error("not_found"), + ); + + // follow the community and approve + const follow_form: FollowCommunity = { + community_id: betaCommunity.id, + follow: true, + }; + await user.followCommunity(follow_form); + const pendingFollows1 = await waitUntil( + () => listCommunityPendingFollows(alpha), + f => f.items.length == 1, + ); + const approve = await approveCommunityPendingFollow( + alpha, + alphaCommunityId, + pendingFollows1.items[0].person.id, + ); + expect(approve.success).toBe(true); + + // now user can fetch posts and comments in community (using signed fetch), and create posts + await waitUntil( + () => resolvePost(user, post0.post_view.post), + p => p?.post?.post.id != undefined, + ); + const resolvedComment = ( + await resolveComment(user, comment.comment_view.comment) + ).comment; + expect(resolvedComment?.comment.id).toBeDefined(); + + const post1 = await createPost(user, betaCommunity.id); + expect(post1.post_view).toBeDefined(); + const like = await likeComment(user, 1, resolvedComment!.comment); + expect(like.comment_view.my_vote).toBe(1); +}); + +test("Reject follower", async () => { + // create private community + const community = await createCommunity(alpha, randomString(10), "Private"); + expect(community.community_view.community.visibility).toBe("Private"); + const alphaCommunityId = community.community_view.community.id; + + // user is not following the community and cannot view nor create posts + const user = await registerUser(beta, betaUrl); + const betaCommunity1 = ( + await resolveCommunity(user, community.community_view.community.actor_id) + ).community!.community; + + // follow the community and reject + const follow_form: FollowCommunity = { + community_id: betaCommunity1.id, + follow: true, + }; + const follow = await user.followCommunity(follow_form); + expect(follow.community_view.subscribed).toBe("ApprovalRequired"); + + const pendingFollows1 = await waitUntil( + () => listCommunityPendingFollows(alpha), + f => f.items.length == 1, + ); + const approve = await approveCommunityPendingFollow( + alpha, + alphaCommunityId, + pendingFollows1.items[0].person.id, + false, + ); + expect(approve.success).toBe(true); + + await waitUntil( + () => getCommunity(user, betaCommunity1.id), + c => c.community_view.subscribed == "NotSubscribed", + ); +}); diff --git a/api_tests/src/shared.ts b/api_tests/src/shared.ts index 20cb171c5..95e916ef2 100644 --- a/api_tests/src/shared.ts +++ b/api_tests/src/shared.ts @@ -1,17 +1,24 @@ import { + ApproveCommunityPendingFollower, BlockCommunity, BlockCommunityResponse, BlockInstance, BlockInstanceResponse, CommunityId, + CommunityVisibility, CreatePrivateMessageReport, DeleteImage, EditCommunity, + GetCommunityPendingFollowsCount, + GetCommunityPendingFollowsCountResponse, GetReplies, GetRepliesResponse, GetUnreadCountResponse, InstanceId, LemmyHttp, + ListCommunityPendingFollows, + ListCommunityPendingFollowsResponse, + PersonId, PostView, PrivateMessageReportResponse, SuccessResponse, @@ -198,7 +205,7 @@ export async function setupLogins() { // only needed the first time so do in this try await delay(10_000); } catch { - console.log("Communities already exist"); + //console.log("Communities already exist"); } } @@ -554,12 +561,14 @@ export async function likeComment( export async function createCommunity( api: LemmyHttp, name_: string = randomString(10), + visibility: CommunityVisibility = "Public", ): Promise { let description = "a sample description"; let form: CreateCommunity = { name: name_, title: name_, description, + visibility, }; return api.createCommunity(form); } @@ -688,7 +697,6 @@ export async function saveUserSettingsBio( let form: SaveUserSettings = { show_nsfw: true, blur_nsfw: false, - auto_expand: true, theme: "darkly", default_post_sort_type: "Active", default_listing_type: "All", @@ -709,7 +717,6 @@ export async function saveUserSettingsFederated( let form: SaveUserSettings = { show_nsfw: false, blur_nsfw: true, - auto_expand: false, default_post_sort_type: "Hot", default_listing_type: "All", interface_language: "", @@ -872,6 +879,39 @@ export function blockCommunity( return api.blockCommunity(form); } +export function listCommunityPendingFollows( + api: LemmyHttp, +): Promise { + let form: ListCommunityPendingFollows = { + pending_only: true, + all_communities: false, + page: 1, + limit: 50, + }; + return api.listCommunityPendingFollows(form); +} + +export function getCommunityPendingFollowsCount( + api: LemmyHttp, + community_id: CommunityId, +): Promise { + return api.getCommunityPendingFollowsCount(community_id); +} + +export function approveCommunityPendingFollow( + api: LemmyHttp, + community_id: CommunityId, + follower_id: PersonId, + approve: boolean = true, +): Promise { + let form: ApproveCommunityPendingFollower = { + community_id, + follower_id, + approve, + }; + return api.approveCommunityPendingFollow(form); +} + export function delay(millis = 500) { return new Promise(resolve => setTimeout(resolve, millis)); } @@ -962,8 +1002,12 @@ export async function waitUntil( let retry = 0; let result; while (retry++ < retries) { - result = await fetcher(); - if (checker(result)) return result; + try { + result = await fetcher(); + if (checker(result)) return result; + } catch (error) { + //console.error(error); + } await delay( delaySeconds[Math.min(retry - 1, delaySeconds.length - 1)] * 1000, ); diff --git a/crates/api/src/comment/distinguish.rs b/crates/api/src/comment/distinguish.rs index a1b25ea44..17608a230 100644 --- a/crates/api/src/comment/distinguish.rs +++ b/crates/api/src/comment/distinguish.rs @@ -26,7 +26,7 @@ pub async fn distinguish_comment( check_community_user_action( &local_user_view.person, - orig_comment.community.id, + &orig_comment.community, &mut context.pool(), ) .await?; @@ -39,7 +39,7 @@ pub async fn distinguish_comment( // Verify that only a mod or admin can distinguish a comment check_community_mod_action( &local_user_view.person, - orig_comment.community.id, + &orig_comment.community, false, &mut context.pool(), ) diff --git a/crates/api/src/comment/like.rs b/crates/api/src/comment/like.rs index e93b8513f..fbc720102 100644 --- a/crates/api/src/comment/like.rs +++ b/crates/api/src/comment/like.rs @@ -50,7 +50,7 @@ pub async fn like_comment( check_community_user_action( &local_user_view.person, - orig_comment.community.id, + &orig_comment.community, &mut context.pool(), ) .await?; @@ -92,8 +92,7 @@ pub async fn like_comment( score: data.score, }, &context, - ) - .await?; + )?; Ok(Json( build_comment_response( diff --git a/crates/api/src/comment_report/create.rs b/crates/api/src/comment_report/create.rs index a0ff4be77..48066cfe6 100644 --- a/crates/api/src/comment_report/create.rs +++ b/crates/api/src/comment_report/create.rs @@ -44,7 +44,7 @@ pub async fn create_comment_report( check_community_user_action( &local_user_view.person, - comment_view.community.id, + &comment_view.community, &mut context.pool(), ) .await?; @@ -85,8 +85,7 @@ pub async fn create_comment_report( reason: data.reason.clone(), }, &context, - ) - .await?; + )?; Ok(Json(CommentReportResponse { comment_report_view, diff --git a/crates/api/src/comment_report/resolve.rs b/crates/api/src/comment_report/resolve.rs index a663fdf74..58d5041dc 100644 --- a/crates/api/src/comment_report/resolve.rs +++ b/crates/api/src/comment_report/resolve.rs @@ -22,7 +22,7 @@ pub async fn resolve_comment_report( let person_id = local_user_view.person.id; check_community_mod_action( &local_user_view.person, - report.community.id, + &report.community, true, &mut context.pool(), ) diff --git a/crates/api/src/community/add_mod.rs b/crates/api/src/community/add_mod.rs index 7d04f6bb0..9e85788ea 100644 --- a/crates/api/src/community/add_mod.rs +++ b/crates/api/src/community/add_mod.rs @@ -24,12 +24,11 @@ pub async fn add_mod_to_community( context: Data, local_user_view: LocalUserView, ) -> LemmyResult> { - let community_id = data.community_id; - + let community = Community::read(&mut context.pool(), data.community_id).await?; // Verify that only mods or admins can add mod check_community_mod_action( &local_user_view.person, - community_id, + &community, false, &mut context.pool(), ) @@ -39,15 +38,13 @@ pub async fn add_mod_to_community( if !data.added { LocalUser::is_higher_mod_or_admin_check( &mut context.pool(), - community_id, + community.id, local_user_view.person.id, vec![data.person_id], ) .await?; } - let community = Community::read(&mut context.pool(), community_id).await?; - // If user is admin and community is remote, explicitly check that he is a // moderator. This is necessary because otherwise the action would be rejected // by the community's home instance. @@ -98,8 +95,7 @@ pub async fn add_mod_to_community( added: data.added, }, &context, - ) - .await?; + )?; Ok(Json(AddModToCommunityResponse { moderators })) } diff --git a/crates/api/src/community/ban.rs b/crates/api/src/community/ban.rs index 64b1c7196..a0e57061b 100644 --- a/crates/api/src/community/ban.rs +++ b/crates/api/src/community/ban.rs @@ -13,6 +13,7 @@ use lemmy_api_common::{ use lemmy_db_schema::{ source::{ community::{ + Community, CommunityFollower, CommunityFollowerForm, CommunityPersonBan, @@ -38,11 +39,12 @@ pub async fn ban_from_community( ) -> LemmyResult> { let banned_person_id = data.person_id; let expires = check_expire_time(data.expires)?; + let community = Community::read(&mut context.pool(), data.community_id).await?; // Verify that only mods or admins can ban check_community_mod_action( &local_user_view.person, - data.community_id, + &community, false, &mut context.pool(), ) @@ -72,12 +74,7 @@ pub async fn ban_from_community( .with_lemmy_type(LemmyErrorType::CommunityUserAlreadyBanned)?; // Also unsubscribe them from the community, if they are subscribed - let community_follower_form = CommunityFollowerForm { - community_id: data.community_id, - person_id: banned_person_id, - pending: false, - }; - + let community_follower_form = CommunityFollowerForm::new(data.community_id, banned_person_id); CommunityFollower::unfollow(&mut context.pool(), &community_follower_form) .await .ok(); @@ -123,8 +120,7 @@ pub async fn ban_from_community( data: data.0.clone(), }, &context, - ) - .await?; + )?; Ok(Json(BanFromCommunityResponse { person_view, diff --git a/crates/api/src/community/block.rs b/crates/api/src/community/block.rs index 90931c762..a6a48e2e7 100644 --- a/crates/api/src/community/block.rs +++ b/crates/api/src/community/block.rs @@ -35,12 +35,7 @@ pub async fn block_community( .with_lemmy_type(LemmyErrorType::CommunityBlockAlreadyExists)?; // Also, unfollow the community, and send a federated unfollow - let community_follower_form = CommunityFollowerForm { - community_id: data.community_id, - person_id, - pending: false, - }; - + let community_follower_form = CommunityFollowerForm::new(data.community_id, person_id); CommunityFollower::unfollow(&mut context.pool(), &community_follower_form) .await .ok(); @@ -65,8 +60,7 @@ pub async fn block_community( false, ), &context, - ) - .await?; + )?; Ok(Json(BlockCommunityResponse { blocked: data.block, diff --git a/crates/api/src/community/follow.rs b/crates/api/src/community/follow.rs index d0f5bbf0d..d5cd3e5b1 100644 --- a/crates/api/src/community/follow.rs +++ b/crates/api/src/community/follow.rs @@ -4,17 +4,18 @@ use lemmy_api_common::{ community::{CommunityResponse, FollowCommunity}, context::LemmyContext, send_activity::{ActivityChannel, SendActivityData}, - utils::check_community_user_action, + utils::{check_community_deleted_removed, check_user_valid}, }; use lemmy_db_schema::{ source::{ actor_language::CommunityLanguage, - community::{Community, CommunityFollower, CommunityFollowerForm}, + community::{Community, CommunityFollower, CommunityFollowerForm, CommunityFollowerState}, }, traits::{Crud, Followable}, + CommunityVisibility, }; use lemmy_db_views::structs::LocalUserView; -use lemmy_db_views_actor::structs::CommunityView; +use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView}; use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult}; #[tracing::instrument(skip(context))] @@ -23,40 +24,52 @@ pub async fn follow_community( context: Data, local_user_view: LocalUserView, ) -> LemmyResult> { + check_user_valid(&local_user_view.person)?; let community = Community::read(&mut context.pool(), data.community_id).await?; - let mut community_follower_form = CommunityFollowerForm { - community_id: community.id, - person_id: local_user_view.person.id, - pending: false, - }; + let form = CommunityFollowerForm::new(community.id, local_user_view.person.id); if data.follow { + // Only run these checks for local community, in case of remote community the local + // state may be outdated. Can't use check_community_user_action() here as it only allows + // actions from existing followers for private community (so following would be impossible). if community.local { - check_community_user_action(&local_user_view.person, community.id, &mut context.pool()) + check_community_deleted_removed(&community)?; + CommunityPersonBanView::check(&mut context.pool(), local_user_view.person.id, community.id) .await?; - - CommunityFollower::follow(&mut context.pool(), &community_follower_form) - .await - .with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?; - } else { - // Mark as pending, the actual federation activity is sent via `SendActivity` handler - community_follower_form.pending = true; - CommunityFollower::follow(&mut context.pool(), &community_follower_form) - .await - .with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?; } + + let state = if community.local { + // Local follow is accepted immediately + Some(CommunityFollowerState::Accepted) + } else if community.visibility == CommunityVisibility::Private { + // Private communities require manual approval + Some(CommunityFollowerState::ApprovalRequired) + } else { + // remote follow needs to be federated first + Some(CommunityFollowerState::Pending) + }; + + let form = CommunityFollowerForm { + state, + ..CommunityFollowerForm::new(community.id, local_user_view.person.id) + }; + + // Write to db + CommunityFollower::follow(&mut context.pool(), &form) + .await + .with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?; } else { - CommunityFollower::unfollow(&mut context.pool(), &community_follower_form) + CommunityFollower::unfollow(&mut context.pool(), &form) .await .with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?; } + // Send the federated follow if !community.local { ActivityChannel::submit_activity( SendActivityData::FollowCommunity(community, local_user_view.person.clone(), data.follow), &context, - ) - .await?; + )?; } let community_id = data.community_id; diff --git a/crates/api/src/community/hide.rs b/crates/api/src/community/hide.rs index 997d88de3..077ed1c5e 100644 --- a/crates/api/src/community/hide.rs +++ b/crates/api/src/community/hide.rs @@ -48,8 +48,7 @@ pub async fn hide_community( ActivityChannel::submit_activity( SendActivityData::UpdateCommunity(local_user_view.person.clone(), community), &context, - ) - .await?; + )?; Ok(Json(SuccessResponse::default())) } diff --git a/crates/api/src/community/mod.rs b/crates/api/src/community/mod.rs index 54bdbef28..121e181c6 100644 --- a/crates/api/src/community/mod.rs +++ b/crates/api/src/community/mod.rs @@ -3,5 +3,6 @@ pub mod ban; pub mod block; pub mod follow; pub mod hide; +pub mod pending_follows; pub mod random; pub mod transfer; diff --git a/crates/api/src/community/pending_follows/approve.rs b/crates/api/src/community/pending_follows/approve.rs new file mode 100644 index 000000000..468e9d9d0 --- /dev/null +++ b/crates/api/src/community/pending_follows/approve.rs @@ -0,0 +1,46 @@ +use activitypub_federation::config::Data; +use actix_web::web::Json; +use lemmy_api_common::{ + community::ApproveCommunityPendingFollower, + context::LemmyContext, + send_activity::{ActivityChannel, SendActivityData}, + utils::is_mod_or_admin, + SuccessResponse, +}; +use lemmy_db_schema::{ + source::community::{CommunityFollower, CommunityFollowerForm}, + traits::Followable, +}; +use lemmy_db_views::structs::LocalUserView; +use lemmy_utils::error::LemmyResult; + +pub async fn post_pending_follows_approve( + data: Json, + context: Data, + local_user_view: LocalUserView, +) -> LemmyResult> { + is_mod_or_admin( + &mut context.pool(), + &local_user_view.person, + data.community_id, + ) + .await?; + + let activity_data = if data.approve { + CommunityFollower::approve( + &mut context.pool(), + data.community_id, + data.follower_id, + local_user_view.person.id, + ) + .await?; + SendActivityData::AcceptFollower(data.community_id, data.follower_id) + } else { + let form = CommunityFollowerForm::new(data.community_id, data.follower_id); + CommunityFollower::unfollow(&mut context.pool(), &form).await?; + SendActivityData::RejectFollower(data.community_id, data.follower_id) + }; + ActivityChannel::submit_activity(activity_data, &context)?; + + Ok(Json(SuccessResponse::default())) +} diff --git a/crates/api/src/community/pending_follows/count.rs b/crates/api/src/community/pending_follows/count.rs new file mode 100644 index 000000000..e8e333c84 --- /dev/null +++ b/crates/api/src/community/pending_follows/count.rs @@ -0,0 +1,25 @@ +use actix_web::web::{Data, Json, Query}; +use lemmy_api_common::{ + community::{GetCommunityPendingFollowsCount, GetCommunityPendingFollowsCountResponse}, + context::LemmyContext, + utils::is_mod_or_admin, +}; +use lemmy_db_views::structs::LocalUserView; +use lemmy_db_views_actor::structs::CommunityFollowerView; +use lemmy_utils::error::LemmyResult; + +pub async fn get_pending_follows_count( + data: Query, + context: Data, + local_user_view: LocalUserView, +) -> LemmyResult> { + is_mod_or_admin( + &mut context.pool(), + &local_user_view.person, + data.community_id, + ) + .await?; + let count = + CommunityFollowerView::count_approval_required(&mut context.pool(), data.community_id).await?; + Ok(Json(GetCommunityPendingFollowsCountResponse { count })) +} diff --git a/crates/api/src/community/pending_follows/list.rs b/crates/api/src/community/pending_follows/list.rs new file mode 100644 index 000000000..9f300a74f --- /dev/null +++ b/crates/api/src/community/pending_follows/list.rs @@ -0,0 +1,29 @@ +use actix_web::web::{Data, Json, Query}; +use lemmy_api_common::{ + community::{ListCommunityPendingFollows, ListCommunityPendingFollowsResponse}, + context::LemmyContext, + utils::check_community_mod_of_any_or_admin_action, +}; +use lemmy_db_views::structs::LocalUserView; +use lemmy_db_views_actor::structs::CommunityFollowerView; +use lemmy_utils::error::LemmyResult; + +pub async fn get_pending_follows_list( + data: Query, + context: Data, + local_user_view: LocalUserView, +) -> LemmyResult> { + check_community_mod_of_any_or_admin_action(&local_user_view, &mut context.pool()).await?; + let all_communities = + data.all_communities.unwrap_or_default() && local_user_view.local_user.admin; + let items = CommunityFollowerView::list_approval_required( + &mut context.pool(), + local_user_view.person.id, + all_communities, + data.pending_only.unwrap_or_default(), + data.page, + data.limit, + ) + .await?; + Ok(Json(ListCommunityPendingFollowsResponse { items })) +} diff --git a/crates/api/src/community/pending_follows/mod.rs b/crates/api/src/community/pending_follows/mod.rs new file mode 100644 index 000000000..dcc82e250 --- /dev/null +++ b/crates/api/src/community/pending_follows/mod.rs @@ -0,0 +1,3 @@ +pub mod approve; +pub mod count; +pub mod list; diff --git a/crates/api/src/community/transfer.rs b/crates/api/src/community/transfer.rs index 195adbd8d..a5255e5e1 100644 --- a/crates/api/src/community/transfer.rs +++ b/crates/api/src/community/transfer.rs @@ -7,7 +7,7 @@ use lemmy_api_common::{ }; use lemmy_db_schema::{ source::{ - community::{CommunityModerator, CommunityModeratorForm}, + community::{Community, CommunityModerator, CommunityModeratorForm}, moderator::{ModTransferCommunity, ModTransferCommunityForm}, }, traits::{Crud, Joinable}, @@ -27,11 +27,11 @@ pub async fn transfer_community( context: Data, local_user_view: LocalUserView, ) -> LemmyResult> { - let community_id = data.community_id; + let community = Community::read(&mut context.pool(), data.community_id).await?; let mut community_mods = - CommunityModeratorView::for_community(&mut context.pool(), community_id).await?; + CommunityModeratorView::for_community(&mut context.pool(), community.id).await?; - check_community_user_action(&local_user_view.person, community_id, &mut context.pool()).await?; + check_community_user_action(&local_user_view.person, &community, &mut context.pool()).await?; // Make sure transferrer is either the top community mod, or an admin if !(is_top_mod(&local_user_view, &community_mods).is_ok() || is_admin(&local_user_view).is_ok()) diff --git a/crates/api/src/lib.rs b/crates/api/src/lib.rs index 6ffa52f77..3ab2ba277 100644 --- a/crates/api/src/lib.rs +++ b/crates/api/src/lib.rs @@ -197,11 +197,7 @@ pub(crate) async fn ban_nonlocal_user_from_local_communities( .ok(); // Also unsubscribe them from the community, if they are subscribed - let community_follower_form = CommunityFollowerForm { - community_id, - person_id: target.id, - pending: false, - }; + let community_follower_form = CommunityFollowerForm::new(community_id, target.id); CommunityFollower::unfollow(&mut context.pool(), &community_follower_form) .await @@ -242,8 +238,7 @@ pub(crate) async fn ban_nonlocal_user_from_local_communities( data: ban_from_community, }, context, - ) - .await?; + )?; } } diff --git a/crates/api/src/local_user/ban_person.rs b/crates/api/src/local_user/ban_person.rs index 2ace7f031..9349cc632 100644 --- a/crates/api/src/local_user/ban_person.rs +++ b/crates/api/src/local_user/ban_person.rs @@ -111,8 +111,7 @@ pub async fn ban_from_site( expires: data.expires, }, &context, - ) - .await?; + )?; Ok(Json(BanPersonResponse { person_view, diff --git a/crates/api/src/post/feature.rs b/crates/api/src/post/feature.rs index cb6e6c144..6fc2f443c 100644 --- a/crates/api/src/post/feature.rs +++ b/crates/api/src/post/feature.rs @@ -9,6 +9,7 @@ use lemmy_api_common::{ }; use lemmy_db_schema::{ source::{ + community::Community, moderator::{ModFeaturePost, ModFeaturePostForm}, post::{Post, PostUpdateForm}, }, @@ -27,9 +28,10 @@ pub async fn feature_post( let post_id = data.post_id; let orig_post = Post::read(&mut context.pool(), post_id).await?; + let community = Community::read(&mut context.pool(), orig_post.community_id).await?; check_community_mod_action( &local_user_view.person, - orig_post.community_id, + &community, false, &mut context.pool(), ) @@ -67,8 +69,7 @@ pub async fn feature_post( ActivityChannel::submit_activity( SendActivityData::FeaturePost(post, local_user_view.person.clone(), data.featured), &context, - ) - .await?; + )?; build_post_response(&context, orig_post.community_id, local_user_view, post_id).await } diff --git a/crates/api/src/post/like.rs b/crates/api/src/post/like.rs index c81d9630a..ec01e3e8c 100644 --- a/crates/api/src/post/like.rs +++ b/crates/api/src/post/like.rs @@ -15,13 +15,12 @@ use lemmy_api_common::{ }; use lemmy_db_schema::{ source::{ - community::Community, local_site::LocalSite, - post::{Post, PostLike, PostLikeForm}, + post::{PostLike, PostLikeForm}, }, - traits::{Crud, Likeable}, + traits::Likeable, }; -use lemmy_db_views::structs::LocalUserView; +use lemmy_db_views::structs::{LocalUserView, PostView}; use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult}; use std::ops::Deref; @@ -45,11 +44,11 @@ pub async fn like_post( check_bot_account(&local_user_view.person)?; // Check for a community ban - let post = Post::read(&mut context.pool(), post_id).await?; + let post = PostView::read(&mut context.pool(), post_id, None, false).await?; check_community_user_action( &local_user_view.person, - post.community_id, + &post.community, &mut context.pool(), ) .await?; @@ -75,18 +74,15 @@ pub async fn like_post( mark_post_as_read(person_id, post_id, &mut context.pool()).await?; - let community = Community::read(&mut context.pool(), post.community_id).await?; - ActivityChannel::submit_activity( SendActivityData::LikePostOrComment { - object_id: post.ap_id, + object_id: post.post.ap_id, actor: local_user_view.person.clone(), - community, + community: post.community.clone(), score: data.score, }, &context, - ) - .await?; + )?; - build_post_response(context.deref(), post.community_id, local_user_view, post_id).await + build_post_response(context.deref(), post.community.id, local_user_view, post_id).await } diff --git a/crates/api/src/post/lock.rs b/crates/api/src/post/lock.rs index 548947b78..011770c2e 100644 --- a/crates/api/src/post/lock.rs +++ b/crates/api/src/post/lock.rs @@ -14,7 +14,7 @@ use lemmy_db_schema::{ }, traits::Crud, }; -use lemmy_db_views::structs::LocalUserView; +use lemmy_db_views::structs::{LocalUserView, PostView}; use lemmy_utils::error::LemmyResult; #[tracing::instrument(skip(context))] @@ -24,11 +24,11 @@ pub async fn lock_post( local_user_view: LocalUserView, ) -> LemmyResult> { let post_id = data.post_id; - let orig_post = Post::read(&mut context.pool(), post_id).await?; + let orig_post = PostView::read(&mut context.pool(), post_id, None, false).await?; check_community_mod_action( &local_user_view.person, - orig_post.community_id, + &orig_post.community, false, &mut context.pool(), ) @@ -58,8 +58,7 @@ pub async fn lock_post( ActivityChannel::submit_activity( SendActivityData::LockPost(post, local_user_view.person.clone(), data.locked), &context, - ) - .await?; + )?; - build_post_response(&context, orig_post.community_id, local_user_view, post_id).await + build_post_response(&context, orig_post.community.id, local_user_view, post_id).await } diff --git a/crates/api/src/post_report/create.rs b/crates/api/src/post_report/create.rs index 590c9af40..b9edf35c5 100644 --- a/crates/api/src/post_report/create.rs +++ b/crates/api/src/post_report/create.rs @@ -39,7 +39,7 @@ pub async fn create_post_report( check_community_user_action( &local_user_view.person, - post_view.community.id, + &post_view.community, &mut context.pool(), ) .await?; @@ -80,8 +80,7 @@ pub async fn create_post_report( reason: data.reason.clone(), }, &context, - ) - .await?; + )?; Ok(Json(PostReportResponse { post_report_view })) } diff --git a/crates/api/src/post_report/resolve.rs b/crates/api/src/post_report/resolve.rs index a3cb85c6c..652327513 100644 --- a/crates/api/src/post_report/resolve.rs +++ b/crates/api/src/post_report/resolve.rs @@ -22,7 +22,7 @@ pub async fn resolve_post_report( let person_id = local_user_view.person.id; check_community_mod_action( &local_user_view.person, - report.community.id, + &report.community, true, &mut context.pool(), ) diff --git a/crates/api/src/site/purge/comment.rs b/crates/api/src/site/purge/comment.rs index b21ffbc80..ae79a835a 100644 --- a/crates/api/src/site/purge/comment.rs +++ b/crates/api/src/site/purge/comment.rs @@ -67,8 +67,7 @@ pub async fn purge_comment( reason: data.reason.clone(), }, &context, - ) - .await?; + )?; Ok(Json(SuccessResponse::default())) } diff --git a/crates/api/src/site/purge/community.rs b/crates/api/src/site/purge/community.rs index bf06bd529..f0252e303 100644 --- a/crates/api/src/site/purge/community.rs +++ b/crates/api/src/site/purge/community.rs @@ -75,8 +75,7 @@ pub async fn purge_community( removed: true, }, &context, - ) - .await?; + )?; Ok(Json(SuccessResponse::default())) } diff --git a/crates/api/src/site/purge/person.rs b/crates/api/src/site/purge/person.rs index 7ab573cbc..6dad4ce65 100644 --- a/crates/api/src/site/purge/person.rs +++ b/crates/api/src/site/purge/person.rs @@ -80,8 +80,7 @@ pub async fn purge_person( expires: None, }, &context, - ) - .await?; + )?; Ok(Json(SuccessResponse::default())) } diff --git a/crates/api/src/site/purge/post.rs b/crates/api/src/site/purge/post.rs index d2cacdae1..f808269e7 100644 --- a/crates/api/src/site/purge/post.rs +++ b/crates/api/src/site/purge/post.rs @@ -66,8 +66,7 @@ pub async fn purge_post( removed: true, }, &context, - ) - .await?; + )?; Ok(Json(SuccessResponse::default())) } diff --git a/crates/api/src/sitemap.rs b/crates/api/src/sitemap.rs index 57b39a5b3..4d3799b1b 100644 --- a/crates/api/src/sitemap.rs +++ b/crates/api/src/sitemap.rs @@ -9,9 +9,7 @@ use lemmy_utils::error::LemmyResult; use sitemap_rs::{url::Url, url_set::UrlSet}; use tracing::info; -async fn generate_urlset( - posts: Vec<(DbUrl, chrono::DateTime)>, -) -> LemmyResult { +fn generate_urlset(posts: Vec<(DbUrl, chrono::DateTime)>) -> LemmyResult { let urls = posts .into_iter() .map_while(|(url, date_time)| { @@ -31,7 +29,7 @@ pub async fn get_sitemap(context: Data) -> LemmyResult::new(); - generate_urlset(posts).await?.write(&mut buf)?; + generate_urlset(posts)?.write(&mut buf)?; Ok( HttpResponse::Ok() @@ -74,7 +72,7 @@ pub(crate) mod tests { ]; let mut buf = Vec::::new(); - generate_urlset(posts).await?.write(&mut buf)?; + generate_urlset(posts)?.write(&mut buf)?; let root = Element::from_reader(buf.as_slice())?; assert_eq!(root.tag().name(), "urlset"); diff --git a/crates/api_common/src/claims.rs b/crates/api_common/src/claims.rs index 6476f855a..759673f4b 100644 --- a/crates/api_common/src/claims.rs +++ b/crates/api_common/src/claims.rs @@ -92,7 +92,7 @@ mod tests { #[tokio::test] #[serial] async fn test_should_not_validate_user_token_after_password_change() -> LemmyResult<()> { - let pool_ = build_db_pool_for_tests().await; + let pool_ = build_db_pool_for_tests(); let pool = &mut (&pool_).into(); let secret = Secret::init(pool).await?; let context = LemmyContext::create( diff --git a/crates/api_common/src/community.rs b/crates/api_common/src/community.rs index 2fab2d05c..898767b34 100644 --- a/crates/api_common/src/community.rs +++ b/crates/api_common/src/community.rs @@ -8,6 +8,7 @@ use lemmy_db_views_actor::structs::{ CommunityModeratorView, CommunitySortType, CommunityView, + PendingFollow, PersonView, }; use serde::{Deserialize, Serialize}; @@ -274,3 +275,50 @@ pub struct GetRandomCommunity { #[cfg_attr(feature = "full", ts(optional))] pub type_: Option, } + +#[skip_serializing_none] +#[derive(Debug, Serialize, Deserialize, Clone)] +#[cfg_attr(feature = "full", derive(TS))] +#[cfg_attr(feature = "full", ts(export))] +pub struct ListCommunityPendingFollows { + /// Only shows the unapproved applications + #[cfg_attr(feature = "full", ts(optional))] + pub pending_only: Option, + // Only for admins, show pending follows for communities which you dont moderate + #[cfg_attr(feature = "full", ts(optional))] + pub all_communities: Option, + #[cfg_attr(feature = "full", ts(optional))] + pub page: Option, + #[cfg_attr(feature = "full", ts(optional))] + pub limit: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[cfg_attr(feature = "full", derive(TS))] +#[cfg_attr(feature = "full", ts(export))] +pub struct GetCommunityPendingFollowsCount { + pub community_id: CommunityId, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[cfg_attr(feature = "full", derive(TS))] +#[cfg_attr(feature = "full", ts(export))] +pub struct GetCommunityPendingFollowsCountResponse { + pub count: i64, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[cfg_attr(feature = "full", derive(TS))] +#[cfg_attr(feature = "full", ts(export))] +pub struct ListCommunityPendingFollowsResponse { + pub items: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[cfg_attr(feature = "full", derive(TS))] +#[cfg_attr(feature = "full", ts(export))] +pub struct ApproveCommunityPendingFollower { + pub community_id: CommunityId, + pub follower_id: PersonId, + pub approve: bool, +} diff --git a/crates/api_common/src/context.rs b/crates/api_common/src/context.rs index 334983b20..c6ab23bfc 100644 --- a/crates/api_common/src/context.rs +++ b/crates/api_common/src/context.rs @@ -57,7 +57,7 @@ impl LemmyContext { /// Do not use this in production code. pub async fn init_test_federation_config() -> FederationConfig { // call this to run migrations - let pool = build_db_pool_for_tests().await; + let pool = build_db_pool_for_tests(); let client = client_builder(&SETTINGS).build().expect("build client"); diff --git a/crates/api_common/src/request.rs b/crates/api_common/src/request.rs index b0da6cf4d..96d64d0e5 100644 --- a/crates/api_common/src/request.rs +++ b/crates/api_common/src/request.rs @@ -175,7 +175,7 @@ pub async fn generate_post_link_metadata( }; let updated_post = Post::update(&mut context.pool(), post.id, &form).await?; if let Some(send_activity) = send_activity(updated_post) { - ActivityChannel::submit_activity(send_activity, &context).await?; + ActivityChannel::submit_activity(send_activity, &context)?; } Ok(()) } diff --git a/crates/api_common/src/send_activity.rs b/crates/api_common/src/send_activity.rs index 465e074f4..b606c9a90 100644 --- a/crates/api_common/src/send_activity.rs +++ b/crates/api_common/src/send_activity.rs @@ -59,6 +59,8 @@ pub enum SendActivityData { score: i16, }, FollowCommunity(Community, Person, bool), + AcceptFollower(CommunityId, PersonId), + RejectFollower(CommunityId, PersonId), UpdateCommunity(Person, Community), DeleteCommunity(Person, Community, bool), RemoveCommunity { @@ -123,10 +125,7 @@ impl ActivityChannel { lock.recv().await } - pub async fn submit_activity( - data: SendActivityData, - _context: &Data, - ) -> LemmyResult<()> { + pub fn submit_activity(data: SendActivityData, _context: &Data) -> LemmyResult<()> { // could do `ACTIVITY_CHANNEL.keepalive_sender.lock()` instead and get rid of weak_sender, // not sure which way is more efficient if let Some(sender) = ACTIVITY_CHANNEL.weak_sender.upgrade() { diff --git a/crates/api_common/src/utils.rs b/crates/api_common/src/utils.rs index ddddd35e9..6b79ce6ba 100644 --- a/crates/api_common/src/utils.rs +++ b/crates/api_common/src/utils.rs @@ -42,6 +42,7 @@ use lemmy_db_views::{ structs::{LocalImageView, LocalUserView, SiteView}, }; use lemmy_db_views_actor::structs::{ + CommunityFollowerView, CommunityModeratorView, CommunityPersonBanView, CommunityView, @@ -232,20 +233,17 @@ pub async fn check_registration_application( /// the user isn't banned. pub async fn check_community_user_action( person: &Person, - community_id: CommunityId, + community: &Community, pool: &mut DbPool<'_>, ) -> LemmyResult<()> { check_user_valid(person)?; - check_community_deleted_removed(community_id, pool).await?; - CommunityPersonBanView::check(pool, person.id, community_id).await?; + check_community_deleted_removed(community)?; + CommunityPersonBanView::check(pool, person.id, community.id).await?; + CommunityFollowerView::check_private_community_action(pool, person.id, community).await?; Ok(()) } -async fn check_community_deleted_removed( - community_id: CommunityId, - pool: &mut DbPool<'_>, -) -> LemmyResult<()> { - let community = Community::read(pool, community_id).await?; +pub fn check_community_deleted_removed(community: &Community) -> LemmyResult<()> { if community.deleted || community.removed { Err(LemmyErrorType::Deleted)? } @@ -258,16 +256,16 @@ async fn check_community_deleted_removed( /// removed/deleted. pub async fn check_community_mod_action( person: &Person, - community_id: CommunityId, + community: &Community, allow_deleted: bool, pool: &mut DbPool<'_>, ) -> LemmyResult<()> { - is_mod_or_admin(pool, person, community_id).await?; - CommunityPersonBanView::check(pool, person.id, community_id).await?; + is_mod_or_admin(pool, person, community.id).await?; + CommunityPersonBanView::check(pool, person.id, community.id).await?; // it must be possible to restore deleted community if !allow_deleted { - check_community_deleted_removed(community_id, pool).await?; + check_community_deleted_removed(community)?; } Ok(()) } diff --git a/crates/api_crud/src/comment/create.rs b/crates/api_crud/src/comment/create.rs index 2f67fa7e7..65aa1f612 100644 --- a/crates/api_crud/src/comment/create.rs +++ b/crates/api_crud/src/comment/create.rs @@ -61,7 +61,12 @@ pub async fn create_comment( let post = post_view.post; let community_id = post_view.community.id; - check_community_user_action(&local_user_view.person, community_id, &mut context.pool()).await?; + check_community_user_action( + &local_user_view.person, + &post_view.community, + &mut context.pool(), + ) + .await?; check_post_deleted_or_removed(&post)?; // Check if post is locked, no new comments @@ -143,8 +148,7 @@ pub async fn create_comment( ActivityChannel::submit_activity( SendActivityData::CreateComment(inserted_comment.clone()), &context, - ) - .await?; + )?; // Update the read comments, so your own new comment doesn't appear as a +1 unread update_read_comments( diff --git a/crates/api_crud/src/comment/delete.rs b/crates/api_crud/src/comment/delete.rs index 2b5f35827..60a22a2ef 100644 --- a/crates/api_crud/src/comment/delete.rs +++ b/crates/api_crud/src/comment/delete.rs @@ -35,7 +35,7 @@ pub async fn delete_comment( check_community_user_action( &local_user_view.person, - orig_comment.community.id, + &orig_comment.community, &mut context.pool(), ) .await?; @@ -76,8 +76,7 @@ pub async fn delete_comment( orig_comment.community, ), &context, - ) - .await?; + )?; Ok(Json( build_comment_response( diff --git a/crates/api_crud/src/comment/remove.rs b/crates/api_crud/src/comment/remove.rs index 3c137a984..4e8a1871a 100644 --- a/crates/api_crud/src/comment/remove.rs +++ b/crates/api_crud/src/comment/remove.rs @@ -35,7 +35,7 @@ pub async fn remove_comment( check_community_mod_action( &local_user_view.person, - orig_comment.community.id, + &orig_comment.community, false, &mut context.pool(), ) @@ -99,8 +99,7 @@ pub async fn remove_comment( reason: data.reason.clone(), }, &context, - ) - .await?; + )?; Ok(Json( build_comment_response( diff --git a/crates/api_crud/src/comment/update.rs b/crates/api_crud/src/comment/update.rs index 51f65aa67..95cc85fe4 100644 --- a/crates/api_crud/src/comment/update.rs +++ b/crates/api_crud/src/comment/update.rs @@ -45,7 +45,7 @@ pub async fn update_comment( check_community_user_action( &local_user_view.person, - orig_comment.community.id, + &orig_comment.community, &mut context.pool(), ) .await?; @@ -98,8 +98,7 @@ pub async fn update_comment( ActivityChannel::submit_activity( SendActivityData::UpdateComment(updated_comment.clone()), &context, - ) - .await?; + )?; Ok(Json( build_comment_response( diff --git a/crates/api_crud/src/community/create.rs b/crates/api_crud/src/community/create.rs index cd0fc985e..c81157950 100644 --- a/crates/api_crud/src/community/create.rs +++ b/crates/api_crud/src/community/create.rs @@ -1,3 +1,4 @@ +use super::check_community_visibility_allowed; use activitypub_federation::{config::Data, http_signatures::generate_actor_keypair}; use actix_web::web::Json; use lemmy_api_common::{ @@ -23,6 +24,7 @@ use lemmy_db_schema::{ Community, CommunityFollower, CommunityFollowerForm, + CommunityFollowerState, CommunityInsertForm, CommunityModerator, CommunityModeratorForm, @@ -82,6 +84,12 @@ pub async fn create_community( is_valid_actor_name(&data.name, local_site.actor_name_max_length as usize)?; + if let Some(desc) = &data.description { + is_valid_body_field(desc, false)?; + } + + check_community_visibility_allowed(data.visibility, &local_user_view)?; + // Double check for duplicate community actor_ids let community_actor_id = generate_local_apub_endpoint( EndpointType::Community, @@ -135,7 +143,8 @@ pub async fn create_community( let community_follower_form = CommunityFollowerForm { community_id: inserted_community.id, person_id: local_user_view.person.id, - pending: false, + state: Some(CommunityFollowerState::Accepted), + approver_id: None, }; CommunityFollower::follow(&mut context.pool(), &community_follower_form) diff --git a/crates/api_crud/src/community/delete.rs b/crates/api_crud/src/community/delete.rs index a2ceaff50..7f9d04933 100644 --- a/crates/api_crud/src/community/delete.rs +++ b/crates/api_crud/src/community/delete.rs @@ -22,13 +22,13 @@ pub async fn delete_community( local_user_view: LocalUserView, ) -> LemmyResult> { // Fetch the community mods - let community_id = data.community_id; let community_mods = - CommunityModeratorView::for_community(&mut context.pool(), community_id).await?; + CommunityModeratorView::for_community(&mut context.pool(), data.community_id).await?; + let community = Community::read(&mut context.pool(), data.community_id).await?; check_community_mod_action( &local_user_view.person, - community_id, + &community, true, &mut context.pool(), ) @@ -54,8 +54,7 @@ pub async fn delete_community( ActivityChannel::submit_activity( SendActivityData::DeleteCommunity(local_user_view.person.clone(), community, data.deleted), &context, - ) - .await?; + )?; build_community_response(&context, local_user_view, community_id).await } diff --git a/crates/api_crud/src/community/mod.rs b/crates/api_crud/src/community/mod.rs index 4bd028482..0c9a507f1 100644 --- a/crates/api_crud/src/community/mod.rs +++ b/crates/api_crud/src/community/mod.rs @@ -1,5 +1,22 @@ +use lemmy_api_common::utils::is_admin; +use lemmy_db_schema::CommunityVisibility; +use lemmy_db_views::structs::LocalUserView; +use lemmy_utils::error::LemmyResult; + pub mod create; pub mod delete; pub mod list; pub mod remove; pub mod update; + +/// For now only admins can make communities private, in order to prevent abuse. +/// Need to implement admin approval for new communities to get rid of this. +fn check_community_visibility_allowed( + visibility: Option, + local_user_view: &LocalUserView, +) -> LemmyResult<()> { + if visibility == Some(lemmy_db_schema::CommunityVisibility::Private) { + is_admin(local_user_view)?; + } + Ok(()) +} diff --git a/crates/api_crud/src/community/remove.rs b/crates/api_crud/src/community/remove.rs index f4271565d..c506bde1b 100644 --- a/crates/api_crud/src/community/remove.rs +++ b/crates/api_crud/src/community/remove.rs @@ -23,9 +23,10 @@ pub async fn remove_community( context: Data, local_user_view: LocalUserView, ) -> LemmyResult> { + let community = Community::read(&mut context.pool(), data.community_id).await?; check_community_mod_action( &local_user_view.person, - data.community_id, + &community, true, &mut context.pool(), ) @@ -65,8 +66,7 @@ pub async fn remove_community( removed: data.removed, }, &context, - ) - .await?; + )?; build_community_response(&context, local_user_view, community_id).await } diff --git a/crates/api_crud/src/community/update.rs b/crates/api_crud/src/community/update.rs index cde8058ee..3dca7d892 100644 --- a/crates/api_crud/src/community/update.rs +++ b/crates/api_crud/src/community/update.rs @@ -1,3 +1,4 @@ +use super::check_community_visibility_allowed; use activitypub_federation::config::Data; use actix_web::web::Json; use lemmy_api_common::{ @@ -51,6 +52,7 @@ pub async fn update_community( is_valid_body_field(sidebar, false)?; } + check_community_visibility_allowed(data.visibility, &local_user_view)?; let description = diesel_string_update(data.description.as_deref()); let old_community = Community::read(&mut context.pool(), data.community_id).await?; @@ -66,7 +68,7 @@ pub async fn update_community( // Verify its a mod (only mods can edit it) check_community_mod_action( &local_user_view.person, - data.community_id, + &old_community, false, &mut context.pool(), ) @@ -105,8 +107,7 @@ pub async fn update_community( ActivityChannel::submit_activity( SendActivityData::UpdateCommunity(local_user_view.person.clone(), community), &context, - ) - .await?; + )?; build_community_response(&context, local_user_view, community_id).await } diff --git a/crates/api_crud/src/post/create.rs b/crates/api_crud/src/post/create.rs index 90c68bdbd..16932cacb 100644 --- a/crates/api_crud/src/post/create.rs +++ b/crates/api_crud/src/post/create.rs @@ -85,15 +85,9 @@ pub async fn create_post( is_valid_body_field(body, true)?; } - check_community_user_action( - &local_user_view.person, - data.community_id, - &mut context.pool(), - ) - .await?; + let community = Community::read(&mut context.pool(), data.community_id).await?; + check_community_user_action(&local_user_view.person, &community, &mut context.pool()).await?; - let community_id = data.community_id; - let community = Community::read(&mut context.pool(), community_id).await?; if community.posting_restricted_to_mods { let community_id = data.community_id; CommunityModeratorView::check_is_community_moderator( @@ -110,7 +104,7 @@ pub async fn create_post( None => { default_post_language( &mut context.pool(), - community_id, + community.id, local_user_view.local_user.id, ) .await? @@ -119,7 +113,7 @@ pub async fn create_post( // Only need to check if language is allowed in case user set it explicitly. When using default // language, it already only returns allowed languages. - CommunityLanguage::is_allowed_community_language(&mut context.pool(), language_id, community_id) + CommunityLanguage::is_allowed_community_language(&mut context.pool(), language_id, community.id) .await?; let scheduled_publish_time = @@ -142,6 +136,7 @@ pub async fn create_post( .await .with_lemmy_type(LemmyErrorType::CouldntCreatePost)?; + let community_id = community.id; let federate_post = if scheduled_publish_time.is_none() { send_webmention(inserted_post.clone(), community); |post| Some(SendActivityData::CreatePost(post)) diff --git a/crates/api_crud/src/post/delete.rs b/crates/api_crud/src/post/delete.rs index be31759d5..e54086911 100644 --- a/crates/api_crud/src/post/delete.rs +++ b/crates/api_crud/src/post/delete.rs @@ -8,7 +8,10 @@ use lemmy_api_common::{ utils::check_community_user_action, }; use lemmy_db_schema::{ - source::post::{Post, PostUpdateForm}, + source::{ + community::Community, + post::{Post, PostUpdateForm}, + }, traits::Crud, }; use lemmy_db_views::structs::LocalUserView; @@ -28,12 +31,8 @@ pub async fn delete_post( Err(LemmyErrorType::CouldntUpdatePost)? } - check_community_user_action( - &local_user_view.person, - orig_post.community_id, - &mut context.pool(), - ) - .await?; + let community = Community::read(&mut context.pool(), orig_post.community_id).await?; + check_community_user_action(&local_user_view.person, &community, &mut context.pool()).await?; // Verify that only the creator can delete if !Post::is_post_creator(local_user_view.person.id, orig_post.creator_id) { @@ -54,8 +53,7 @@ pub async fn delete_post( ActivityChannel::submit_activity( SendActivityData::DeletePost(post, local_user_view.person.clone(), data.0), &context, - ) - .await?; + )?; build_post_response( &context, diff --git a/crates/api_crud/src/post/remove.rs b/crates/api_crud/src/post/remove.rs index c53a4552c..7e3261e6f 100644 --- a/crates/api_crud/src/post/remove.rs +++ b/crates/api_crud/src/post/remove.rs @@ -9,6 +9,7 @@ use lemmy_api_common::{ }; use lemmy_db_schema::{ source::{ + community::Community, local_user::LocalUser, moderator::{ModRemovePost, ModRemovePostForm}, post::{Post, PostUpdateForm}, @@ -26,11 +27,16 @@ pub async fn remove_post( local_user_view: LocalUserView, ) -> LemmyResult> { let post_id = data.post_id; + + // We cannot use PostView to avoid a database read here, as it doesn't return removed items + // by default. So we would have to pass in `is_mod_or_admin`, but that is impossible without + // knowing which community the post belongs to. let orig_post = Post::read(&mut context.pool(), post_id).await?; + let community = Community::read(&mut context.pool(), orig_post.community_id).await?; check_community_mod_action( &local_user_view.person, - orig_post.community_id, + &community, false, &mut context.pool(), ) @@ -77,8 +83,7 @@ pub async fn remove_post( removed: data.removed, }, &context, - ) - .await?; + )?; build_post_response(&context, orig_post.community_id, local_user_view, post_id).await } diff --git a/crates/api_crud/src/post/update.rs b/crates/api_crud/src/post/update.rs index cef8bfea8..fc23e7d9e 100644 --- a/crates/api_crud/src/post/update.rs +++ b/crates/api_crud/src/post/update.rs @@ -24,7 +24,7 @@ use lemmy_db_schema::{ traits::Crud, utils::{diesel_string_update, diesel_url_update, naive_now}, }; -use lemmy_db_views::structs::LocalUserView; +use lemmy_db_views::structs::{LocalUserView, PostView}; use lemmy_utils::{ error::{LemmyErrorExt, LemmyErrorType, LemmyResult}, utils::{ @@ -87,17 +87,17 @@ pub async fn update_post( } let post_id = data.post_id; - let orig_post = Post::read(&mut context.pool(), post_id).await?; + let orig_post = PostView::read(&mut context.pool(), post_id, None, false).await?; check_community_user_action( &local_user_view.person, - orig_post.community_id, + &orig_post.community, &mut context.pool(), ) .await?; // Verify that only the creator can edit - if !Post::is_post_creator(local_user_view.person.id, orig_post.creator_id) { + if !Post::is_post_creator(local_user_view.person.id, orig_post.post.creator_id) { Err(LemmyErrorType::NoPostEditAllowed)? } @@ -105,14 +105,14 @@ pub async fn update_post( CommunityLanguage::is_allowed_community_language( &mut context.pool(), language_id, - orig_post.community_id, + orig_post.community.id, ) .await?; } // handle changes to scheduled_publish_time let scheduled_publish_time = match ( - orig_post.scheduled_publish_time, + orig_post.post.scheduled_publish_time, data.scheduled_publish_time, ) { // schedule time can be changed if post is still scheduled (and not published yet) @@ -144,12 +144,12 @@ pub async fn update_post( // send out federation/webmention if necessary match ( - orig_post.scheduled_publish_time, + orig_post.post.scheduled_publish_time, data.scheduled_publish_time, ) { // schedule was removed, send create activity and webmention (Some(_), None) => { - let community = Community::read(&mut context.pool(), orig_post.community_id).await?; + let community = Community::read(&mut context.pool(), orig_post.community.id).await?; send_webmention(updated_post.clone(), community); generate_post_link_metadata( updated_post.clone(), @@ -175,7 +175,7 @@ pub async fn update_post( build_post_response( context.deref(), - orig_post.community_id, + orig_post.community.id, local_user_view, post_id, ) diff --git a/crates/api_crud/src/private_message/create.rs b/crates/api_crud/src/private_message/create.rs index 2a49e4ac0..5f3c7b639 100644 --- a/crates/api_crud/src/private_message/create.rs +++ b/crates/api_crud/src/private_message/create.rs @@ -78,8 +78,7 @@ pub async fn create_private_message( ActivityChannel::submit_activity( SendActivityData::CreatePrivateMessage(view.clone()), &context, - ) - .await?; + )?; Ok(Json(PrivateMessageResponse { private_message_view: view, diff --git a/crates/api_crud/src/private_message/delete.rs b/crates/api_crud/src/private_message/delete.rs index 936ff57b8..30efc020c 100644 --- a/crates/api_crud/src/private_message/delete.rs +++ b/crates/api_crud/src/private_message/delete.rs @@ -42,8 +42,7 @@ pub async fn delete_private_message( ActivityChannel::submit_activity( SendActivityData::DeletePrivateMessage(local_user_view.person, private_message, data.deleted), &context, - ) - .await?; + )?; let view = PrivateMessageView::read(&mut context.pool(), private_message_id).await?; Ok(Json(PrivateMessageResponse { diff --git a/crates/api_crud/src/private_message/update.rs b/crates/api_crud/src/private_message/update.rs index 20eaadb36..aa562c626 100644 --- a/crates/api_crud/src/private_message/update.rs +++ b/crates/api_crud/src/private_message/update.rs @@ -59,8 +59,7 @@ pub async fn update_private_message( ActivityChannel::submit_activity( SendActivityData::UpdatePrivateMessage(view.clone()), &context, - ) - .await?; + )?; Ok(Json(PrivateMessageResponse { private_message_view: view, diff --git a/crates/api_crud/src/user/delete.rs b/crates/api_crud/src/user/delete.rs index d1825425c..39598265a 100644 --- a/crates/api_crud/src/user/delete.rs +++ b/crates/api_crud/src/user/delete.rs @@ -45,8 +45,7 @@ pub async fn delete_account( ActivityChannel::submit_activity( SendActivityData::DeleteUser(local_user_view.person, data.delete_content), &context, - ) - .await?; + )?; Ok(Json(SuccessResponse::default())) } diff --git a/crates/apub/src/activities/block/block_user.rs b/crates/apub/src/activities/block/block_user.rs index 64d5e7816..866e1cc6c 100644 --- a/crates/apub/src/activities/block/block_user.rs +++ b/crates/apub/src/activities/block/block_user.rs @@ -1,3 +1,4 @@ +use super::to_and_audience; use crate::{ activities::{ block::{generate_cc, SiteOrCommunity}, @@ -7,6 +8,7 @@ use crate::{ verify_is_public, verify_mod_action, verify_person_in_community, + verify_visibility, }, activity_lists::AnnouncableActivities, insert_received_activity, @@ -15,7 +17,7 @@ use crate::{ }; use activitypub_federation::{ config::Data, - kinds::{activity::BlockType, public}, + kinds::activity::BlockType, protocol::verification::verify_domains_match, traits::{ActivityHandler, Actor}, }; @@ -52,14 +54,10 @@ impl BlockUser { expires: Option>, context: &Data, ) -> LemmyResult { - let audience = if let SiteOrCommunity::Community(c) = target { - Some(c.id().into()) - } else { - None - }; + let (to, audience) = to_and_audience(target)?; Ok(BlockUser { actor: mod_.id().into(), - to: vec![public()], + to, object: user.id().into(), cc: generate_cc(target, &mut context.pool()).await?, target: target.id(), @@ -125,9 +123,9 @@ impl ActivityHandler for BlockUser { #[tracing::instrument(skip_all)] async fn verify(&self, context: &Data) -> LemmyResult<()> { - verify_is_public(&self.to, &self.cc)?; match self.target.dereference(context).await? { SiteOrCommunity::Site(site) => { + verify_is_public(&self.to, &self.cc)?; let domain = self .object .inner() @@ -143,6 +141,7 @@ impl ActivityHandler for BlockUser { verify_domains_match(&site.id(), self.object.inner())?; } SiteOrCommunity::Community(community) => { + verify_visibility(&self.to, &self.cc, &community)?; verify_person_in_community(&self.actor, &community, context).await?; verify_mod_action(&self.actor, &community, context).await?; } @@ -194,11 +193,7 @@ impl ActivityHandler for BlockUser { CommunityPersonBan::ban(&mut context.pool(), &community_user_ban_form).await?; // Also unsubscribe them from the community, if they are subscribed - let community_follower_form = CommunityFollowerForm { - community_id: community.id, - person_id: blocked_person.id, - pending: false, - }; + let community_follower_form = CommunityFollowerForm::new(community.id, blocked_person.id); CommunityFollower::unfollow(&mut context.pool(), &community_follower_form) .await .ok(); diff --git a/crates/apub/src/activities/block/mod.rs b/crates/apub/src/activities/block/mod.rs index c8323fcb4..550d98183 100644 --- a/crates/apub/src/activities/block/mod.rs +++ b/crates/apub/src/activities/block/mod.rs @@ -1,3 +1,4 @@ +use super::generate_to; use crate::{ objects::{community::ApubCommunity, instance::ApubSite}, protocol::{ @@ -8,6 +9,7 @@ use crate::{ use activitypub_federation::{ config::Data, fetch::object_id::ObjectId, + kinds::public, traits::{Actor, Object}, }; use chrono::{DateTime, Utc}; @@ -205,3 +207,13 @@ pub(crate) async fn send_ban_from_community( .await } } + +fn to_and_audience( + target: &SiteOrCommunity, +) -> LemmyResult<(Vec, Option>)> { + Ok(if let SiteOrCommunity::Community(c) = target { + (vec![generate_to(c)?], Some(c.id().into())) + } else { + (vec![public()], None) + }) +} diff --git a/crates/apub/src/activities/block/undo_block_user.rs b/crates/apub/src/activities/block/undo_block_user.rs index f9f6890b6..29fc22f0c 100644 --- a/crates/apub/src/activities/block/undo_block_user.rs +++ b/crates/apub/src/activities/block/undo_block_user.rs @@ -1,3 +1,4 @@ +use super::to_and_audience; use crate::{ activities::{ block::{generate_cc, SiteOrCommunity}, @@ -5,6 +6,7 @@ use crate::{ generate_activity_id, send_lemmy_activity, verify_is_public, + verify_visibility, }, activity_lists::AnnouncableActivities, insert_received_activity, @@ -13,7 +15,7 @@ use crate::{ }; use activitypub_federation::{ config::Data, - kinds::{activity::UndoType, public}, + kinds::activity::UndoType, protocol::verification::verify_domains_match, traits::{ActivityHandler, Actor}, }; @@ -44,11 +46,7 @@ impl UndoBlockUser { context: &Data, ) -> LemmyResult<()> { let block = BlockUser::new(target, user, mod_, None, reason, None, context).await?; - let audience = if let SiteOrCommunity::Community(c) = target { - Some(c.id().into()) - } else { - None - }; + let (to, audience) = to_and_audience(target)?; let id = generate_activity_id( UndoType::Undo, @@ -56,7 +54,7 @@ impl UndoBlockUser { )?; let undo = UndoBlockUser { actor: mod_.id().into(), - to: vec![public()], + to, object: block, cc: generate_cc(target, &mut context.pool()).await?, kind: UndoType::Undo, @@ -94,7 +92,6 @@ impl ActivityHandler for UndoBlockUser { #[tracing::instrument(skip_all)] async fn verify(&self, context: &Data) -> LemmyResult<()> { - verify_is_public(&self.to, &self.cc)?; verify_domains_match(self.actor.inner(), self.object.actor.inner())?; self.object.verify(context).await?; Ok(()) @@ -108,6 +105,7 @@ impl ActivityHandler for UndoBlockUser { let blocked_person = self.object.object.dereference(context).await?; match self.object.target.dereference(context).await? { SiteOrCommunity::Site(_site) => { + verify_is_public(&self.to, &self.cc)?; let blocked_person = Person::update( &mut context.pool(), blocked_person.id, @@ -135,6 +133,7 @@ impl ActivityHandler for UndoBlockUser { ModBan::create(&mut context.pool(), &form).await?; } SiteOrCommunity::Community(community) => { + verify_visibility(&self.to, &self.cc, &community)?; let community_user_ban_form = CommunityPersonBanForm { community_id: community.id, person_id: blocked_person.id, diff --git a/crates/apub/src/activities/community/announce.rs b/crates/apub/src/activities/community/announce.rs index e374d2874..d32b9d76e 100644 --- a/crates/apub/src/activities/community/announce.rs +++ b/crates/apub/src/activities/community/announce.rs @@ -2,9 +2,10 @@ use crate::{ activities::{ generate_activity_id, generate_announce_activity_id, + generate_to, send_lemmy_activity, - verify_is_public, verify_person_in_community, + verify_visibility, }, activity_lists::AnnouncableActivities, insert_received_activity, @@ -18,7 +19,7 @@ use crate::{ }; use activitypub_federation::{ config::Data, - kinds::{activity::AnnounceType, public}, + kinds::activity::AnnounceType, traits::{ActivityHandler, Actor}, }; use lemmy_api_common::context::LemmyContext; @@ -92,7 +93,7 @@ impl AnnounceActivity { generate_announce_activity_id(inner_kind, &context.settings().get_protocol_and_hostname())?; Ok(AnnounceActivity { actor: community.id().into(), - to: vec![public()], + to: vec![generate_to(community)?], object: IdOrNestedObject::NestedObject(object), cc: community .followers_url @@ -154,7 +155,6 @@ impl ActivityHandler for AnnounceActivity { #[tracing::instrument(skip_all)] async fn verify(&self, _context: &Data) -> LemmyResult<()> { - verify_is_public(&self.to, &self.cc)?; Ok(()) } @@ -169,6 +169,7 @@ impl ActivityHandler for AnnounceActivity { } let community = object.community(context).await?; + verify_visibility(&self.to, &self.cc, &community)?; can_accept_activity_in_community(&Some(community), context).await?; // verify here in order to avoid fetching the object twice over http diff --git a/crates/apub/src/activities/community/collection_add.rs b/crates/apub/src/activities/community/collection_add.rs index 5ab754d35..ae508c2c5 100644 --- a/crates/apub/src/activities/community/collection_add.rs +++ b/crates/apub/src/activities/community/collection_add.rs @@ -2,9 +2,10 @@ use crate::{ activities::{ community::send_activity_in_community, generate_activity_id, - verify_is_public, + generate_to, verify_mod_action, verify_person_in_community, + verify_visibility, }, activity_lists::AnnouncableActivities, insert_received_activity, @@ -17,7 +18,7 @@ use crate::{ use activitypub_federation::{ config::Data, fetch::object_id::ObjectId, - kinds::{activity::AddType, public}, + kinds::activity::AddType, traits::{ActivityHandler, Actor}, }; use lemmy_api_common::{ @@ -53,7 +54,7 @@ impl CollectionAdd { )?; let add = CollectionAdd { actor: actor.id().into(), - to: vec![public()], + to: vec![generate_to(community)?], object: added_mod.id(), target: generate_moderators_url(&community.actor_id)?.into(), cc: vec![community.id()], @@ -79,7 +80,7 @@ impl CollectionAdd { )?; let add = CollectionAdd { actor: actor.id().into(), - to: vec![public()], + to: vec![generate_to(community)?], object: featured_post.ap_id.clone().into(), target: generate_featured_url(&community.actor_id)?.into(), cc: vec![community.id()], @@ -115,8 +116,8 @@ impl ActivityHandler for CollectionAdd { #[tracing::instrument(skip_all)] async fn verify(&self, context: &Data) -> LemmyResult<()> { - verify_is_public(&self.to, &self.cc)?; let community = self.community(context).await?; + verify_visibility(&self.to, &self.cc, &community)?; verify_person_in_community(&self.actor, &community, context).await?; verify_mod_action(&self.actor, &community, context).await?; Ok(()) diff --git a/crates/apub/src/activities/community/collection_remove.rs b/crates/apub/src/activities/community/collection_remove.rs index 90df1fd14..6c08735ed 100644 --- a/crates/apub/src/activities/community/collection_remove.rs +++ b/crates/apub/src/activities/community/collection_remove.rs @@ -2,9 +2,10 @@ use crate::{ activities::{ community::send_activity_in_community, generate_activity_id, - verify_is_public, + generate_to, verify_mod_action, verify_person_in_community, + verify_visibility, }, activity_lists::AnnouncableActivities, insert_received_activity, @@ -14,7 +15,7 @@ use crate::{ use activitypub_federation::{ config::Data, fetch::object_id::ObjectId, - kinds::{activity::RemoveType, public}, + kinds::activity::RemoveType, traits::{ActivityHandler, Actor}, }; use lemmy_api_common::{ @@ -48,7 +49,7 @@ impl CollectionRemove { )?; let remove = CollectionRemove { actor: actor.id().into(), - to: vec![public()], + to: vec![generate_to(community)?], object: removed_mod.id(), target: generate_moderators_url(&community.actor_id)?.into(), id: id.clone(), @@ -74,7 +75,7 @@ impl CollectionRemove { )?; let remove = CollectionRemove { actor: actor.id().into(), - to: vec![public()], + to: vec![generate_to(community)?], object: featured_post.ap_id.clone().into(), target: generate_featured_url(&community.actor_id)?.into(), cc: vec![community.id()], @@ -110,8 +111,8 @@ impl ActivityHandler for CollectionRemove { #[tracing::instrument(skip_all)] async fn verify(&self, context: &Data) -> LemmyResult<()> { - verify_is_public(&self.to, &self.cc)?; let community = self.community(context).await?; + verify_visibility(&self.to, &self.cc, &community)?; verify_person_in_community(&self.actor, &community, context).await?; verify_mod_action(&self.actor, &community, context).await?; Ok(()) diff --git a/crates/apub/src/activities/community/lock_page.rs b/crates/apub/src/activities/community/lock_page.rs index 0d90b5bb0..a9bacea8a 100644 --- a/crates/apub/src/activities/community/lock_page.rs +++ b/crates/apub/src/activities/community/lock_page.rs @@ -3,9 +3,10 @@ use crate::{ check_community_deleted_or_removed, community::send_activity_in_community, generate_activity_id, - verify_is_public, + generate_to, verify_mod_action, verify_person_in_community, + verify_visibility, }, activity_lists::AnnouncableActivities, insert_received_activity, @@ -18,7 +19,7 @@ use crate::{ use activitypub_federation::{ config::Data, fetch::object_id::ObjectId, - kinds::{activity::UndoType, public}, + kinds::activity::UndoType, traits::ActivityHandler, }; use lemmy_api_common::context::LemmyContext; @@ -49,8 +50,8 @@ impl ActivityHandler for LockPage { } async fn verify(&self, context: &Data) -> Result<(), Self::Error> { - verify_is_public(&self.to, &self.cc)?; let community = self.community(context).await?; + verify_visibility(&self.to, &self.cc, &community)?; verify_person_in_community(&self.actor, &community, context).await?; check_community_deleted_or_removed(&community)?; verify_mod_action(&self.actor, &community, context).await?; @@ -92,8 +93,8 @@ impl ActivityHandler for UndoLockPage { } async fn verify(&self, context: &Data) -> Result<(), Self::Error> { - verify_is_public(&self.to, &self.cc)?; let community = self.community(context).await?; + verify_visibility(&self.to, &self.cc, &community)?; verify_person_in_community(&self.actor, &community, context).await?; check_community_deleted_or_removed(&community)?; verify_mod_action(&self.actor, &community, context).await?; @@ -137,7 +138,7 @@ pub(crate) async fn send_lock_post( let community_id = community.actor_id.inner().clone(); let lock = LockPage { actor: actor.actor_id.clone().into(), - to: vec![public()], + to: vec![generate_to(&community)?], object: ObjectId::from(post.ap_id), cc: vec![community_id.clone()], kind: LockType::Lock, @@ -153,7 +154,7 @@ pub(crate) async fn send_lock_post( )?; let undo = UndoLockPage { actor: lock.actor.clone(), - to: vec![public()], + to: vec![generate_to(&community)?], cc: lock.cc.clone(), kind: UndoType::Undo, id, diff --git a/crates/apub/src/activities/community/update.rs b/crates/apub/src/activities/community/update.rs index 48a64bd9d..85be94246 100644 --- a/crates/apub/src/activities/community/update.rs +++ b/crates/apub/src/activities/community/update.rs @@ -2,9 +2,10 @@ use crate::{ activities::{ community::send_activity_in_community, generate_activity_id, - verify_is_public, + generate_to, verify_mod_action, verify_person_in_community, + verify_visibility, }, activity_lists::AnnouncableActivities, insert_received_activity, @@ -13,7 +14,7 @@ use crate::{ }; use activitypub_federation::{ config::Data, - kinds::{activity::UpdateType, public}, + kinds::activity::UpdateType, traits::{ActivityHandler, Actor, Object}, }; use lemmy_api_common::context::LemmyContext; @@ -42,7 +43,7 @@ pub(crate) async fn send_update_community( )?; let update = UpdateCommunity { actor: actor.id().into(), - to: vec![public()], + to: vec![generate_to(&community)?], object: Box::new(community.clone().into_json(&context).await?), cc: vec![community.id()], kind: UpdateType::Update, @@ -77,8 +78,8 @@ impl ActivityHandler for UpdateCommunity { #[tracing::instrument(skip_all)] async fn verify(&self, context: &Data) -> LemmyResult<()> { - verify_is_public(&self.to, &self.cc)?; let community = self.community(context).await?; + verify_visibility(&self.to, &self.cc, &community)?; verify_person_in_community(&self.actor, &community, context).await?; verify_mod_action(&self.actor, &community, context).await?; ApubCommunity::verify(&self.object, &community.actor_id.clone().into(), context).await?; diff --git a/crates/apub/src/activities/create_or_update/comment.rs b/crates/apub/src/activities/create_or_update/comment.rs index 0a0737151..90ab0153f 100644 --- a/crates/apub/src/activities/create_or_update/comment.rs +++ b/crates/apub/src/activities/create_or_update/comment.rs @@ -3,8 +3,9 @@ use crate::{ check_community_deleted_or_removed, community::send_activity_in_community, generate_activity_id, - verify_is_public, + generate_to, verify_person_in_community, + verify_visibility, }, activity_lists::AnnouncableActivities, insert_received_activity, @@ -18,7 +19,6 @@ use crate::{ use activitypub_federation::{ config::Data, fetch::object_id::ObjectId, - kinds::public, protocol::verification::{verify_domains_match, verify_urls_match}, traits::{ActivityHandler, Actor, Object}, }; @@ -70,7 +70,7 @@ impl CreateOrUpdateNote { let create_or_update = CreateOrUpdateNote { actor: person.id().into(), - to: vec![public()], + to: vec![generate_to(&community)?], cc: note.cc.clone(), tag: note.tag.clone(), object: note, @@ -118,9 +118,9 @@ impl ActivityHandler for CreateOrUpdateNote { #[tracing::instrument(skip_all)] async fn verify(&self, context: &Data) -> LemmyResult<()> { - verify_is_public(&self.to, &self.cc)?; let post = self.object.get_parents(context).await?.0; let community = self.community(context).await?; + verify_visibility(&self.to, &self.cc, &community)?; verify_person_in_community(&self.actor, &community, context).await?; verify_domains_match(self.actor.inner(), self.object.id.inner())?; diff --git a/crates/apub/src/activities/create_or_update/post.rs b/crates/apub/src/activities/create_or_update/post.rs index fb53100f6..d0cf17a51 100644 --- a/crates/apub/src/activities/create_or_update/post.rs +++ b/crates/apub/src/activities/create_or_update/post.rs @@ -3,8 +3,9 @@ use crate::{ check_community_deleted_or_removed, community::send_activity_in_community, generate_activity_id, - verify_is_public, + generate_to, verify_person_in_community, + verify_visibility, }, activity_lists::AnnouncableActivities, insert_received_activity, @@ -16,7 +17,6 @@ use crate::{ }; use activitypub_federation::{ config::Data, - kinds::public, protocol::verification::{verify_domains_match, verify_urls_match}, traits::{ActivityHandler, Actor, Object}, }; @@ -49,7 +49,7 @@ impl CreateOrUpdatePage { )?; Ok(CreateOrUpdatePage { actor: actor.id().into(), - to: vec![public()], + to: vec![generate_to(community)?], object: post.into_json(context).await?, cc: vec![community.id()], kind, @@ -102,8 +102,8 @@ impl ActivityHandler for CreateOrUpdatePage { #[tracing::instrument(skip_all)] async fn verify(&self, context: &Data) -> LemmyResult<()> { - verify_is_public(&self.to, &self.cc)?; let community = self.community(context).await?; + verify_visibility(&self.to, &self.cc, &community)?; verify_person_in_community(&self.actor, &community, context).await?; check_community_deleted_or_removed(&community)?; verify_domains_match(self.actor.inner(), self.object.id.inner())?; diff --git a/crates/apub/src/activities/deletion/delete.rs b/crates/apub/src/activities/deletion/delete.rs index 1ddf642b9..064f0bc82 100644 --- a/crates/apub/src/activities/deletion/delete.rs +++ b/crates/apub/src/activities/deletion/delete.rs @@ -84,7 +84,7 @@ impl Delete { pub(in crate::activities::deletion) fn new( actor: &ApubPerson, object: DeletableObjects, - to: Url, + to: Vec, community: Option<&Community>, summary: Option, context: &Data, @@ -96,7 +96,7 @@ impl Delete { let cc: Option = community.map(|c| c.actor_id.clone().into()); Ok(Delete { actor: actor.actor_id.clone().into(), - to: vec![to], + to, object: IdOrNestedObject::Id(object.id()), cc: cc.into_iter().collect(), kind: DeleteType::Delete, diff --git a/crates/apub/src/activities/deletion/mod.rs b/crates/apub/src/activities/deletion/mod.rs index b12532087..15118a476 100644 --- a/crates/apub/src/activities/deletion/mod.rs +++ b/crates/apub/src/activities/deletion/mod.rs @@ -1,11 +1,12 @@ +use super::{generate_to, verify_is_public}; use crate::{ activities::{ community::send_activity_in_community, send_lemmy_activity, - verify_is_public, verify_mod_action, verify_person, verify_person_in_community, + verify_visibility, }, activity_lists::AnnouncableActivities, objects::{ @@ -59,11 +60,12 @@ pub(crate) async fn send_apub_delete_in_community( ) -> LemmyResult<()> { let actor = ApubPerson::from(actor); let is_mod_action = reason.is_some(); + let to = vec![generate_to(&community)?]; let activity = if deleted { - let delete = Delete::new(&actor, object, public(), Some(&community), reason, context)?; + let delete = Delete::new(&actor, object, to, Some(&community), reason, context)?; AnnouncableActivities::Delete(delete) } else { - let undo = UndoDelete::new(&actor, object, public(), Some(&community), reason, context)?; + let undo = UndoDelete::new(&actor, object, to, Some(&community), reason, context)?; AnnouncableActivities::UndoDelete(undo) }; send_activity_in_community( @@ -92,10 +94,10 @@ pub(crate) async fn send_apub_delete_private_message( let deletable = DeletableObjects::PrivateMessage(pm.into()); let inbox = ActivitySendTargets::to_inbox(recipient.shared_inbox_or_inbox()); if deleted { - let delete: Delete = Delete::new(actor, deletable, recipient.id(), None, None, &context)?; + let delete: Delete = Delete::new(actor, deletable, vec![recipient.id()], None, None, &context)?; send_lemmy_activity(&context, delete, actor, inbox, true).await?; } else { - let undo = UndoDelete::new(actor, deletable, recipient.id(), None, None, &context)?; + let undo = UndoDelete::new(actor, deletable, vec![recipient.id()], None, None, &context)?; send_lemmy_activity(&context, undo, actor, inbox, true).await?; }; Ok(()) @@ -109,7 +111,7 @@ pub async fn send_apub_delete_user( let person: ApubPerson = person.into(); let deletable = DeletableObjects::Person(person.clone()); - let mut delete: Delete = Delete::new(&person, deletable, public(), None, None, &context)?; + let mut delete: Delete = Delete::new(&person, deletable, vec![public()], None, None, &context)?; delete.remove_data = Some(remove_data); let inboxes = ActivitySendTargets::to_all_instances(); @@ -170,7 +172,7 @@ pub(in crate::activities) async fn verify_delete_activity( let object = DeletableObjects::read_from_db(activity.object.id(), context).await?; match object { DeletableObjects::Community(community) => { - verify_is_public(&activity.to, &[])?; + verify_visibility(&activity.to, &[], &community)?; if community.local { // can only do this check for local community, in remote case it would try to fetch the // deleted community (which fails) @@ -185,22 +187,24 @@ pub(in crate::activities) async fn verify_delete_activity( verify_urls_match(person.actor_id.inner(), activity.object.id())?; } DeletableObjects::Post(p) => { - verify_is_public(&activity.to, &[])?; + let community = activity.community(context).await?; + verify_visibility(&activity.to, &[], &community)?; verify_delete_post_or_comment( &activity.actor, &p.ap_id.clone().into(), - &activity.community(context).await?, + &community, is_mod_action, context, ) .await?; } DeletableObjects::Comment(c) => { - verify_is_public(&activity.to, &[])?; + let community = activity.community(context).await?; + verify_visibility(&activity.to, &[], &community)?; verify_delete_post_or_comment( &activity.actor, &c.ap_id.clone().into(), - &activity.community(context).await?, + &community, is_mod_action, context, ) diff --git a/crates/apub/src/activities/deletion/undo_delete.rs b/crates/apub/src/activities/deletion/undo_delete.rs index 6328bb427..f4a7bb9b9 100644 --- a/crates/apub/src/activities/deletion/undo_delete.rs +++ b/crates/apub/src/activities/deletion/undo_delete.rs @@ -68,7 +68,7 @@ impl UndoDelete { pub(in crate::activities::deletion) fn new( actor: &ApubPerson, object: DeletableObjects, - to: Url, + to: Vec, community: Option<&Community>, summary: Option, context: &Data, @@ -82,7 +82,7 @@ impl UndoDelete { let cc: Option = community.map(|c| c.actor_id.clone().into()); Ok(UndoDelete { actor: actor.actor_id.clone().into(), - to: vec![to], + to, object, cc: cc.into_iter().collect(), kind: UndoType::Undo, diff --git a/crates/apub/src/activities/following/follow.rs b/crates/apub/src/activities/following/follow.rs index 02f29a1a9..befa2e00c 100644 --- a/crates/apub/src/activities/following/follow.rs +++ b/crates/apub/src/activities/following/follow.rs @@ -20,7 +20,7 @@ use lemmy_api_common::context::LemmyContext; use lemmy_db_schema::{ source::{ activity::ActivitySendTargets, - community::{CommunityFollower, CommunityFollowerForm}, + community::{CommunityFollower, CommunityFollowerForm, CommunityFollowerState}, person::{PersonFollower, PersonFollowerForm}, }, traits::Followable, @@ -102,21 +102,25 @@ impl ActivityHandler for Follow { pending: false, }; PersonFollower::follow(&mut context.pool(), &form).await?; + AcceptFollow::send(self, context).await?; } UserOrCommunity::Community(c) => { - // Dont allow following local-only community via federation. - if c.visibility != CommunityVisibility::Public { - return Err(LemmyErrorType::NotFound.into()); - } + let state = Some(match c.visibility { + CommunityVisibility::Public => CommunityFollowerState::Accepted, + CommunityVisibility::Private => CommunityFollowerState::ApprovalRequired, + // Dont allow following local-only community via federation. + CommunityVisibility::LocalOnly => return Err(LemmyErrorType::NotFound.into()), + }); let form = CommunityFollowerForm { - community_id: c.id, - person_id: actor.id, - pending: false, + state, + ..CommunityFollowerForm::new(c.id, actor.id) }; CommunityFollower::follow(&mut context.pool(), &form).await?; + if c.visibility == CommunityVisibility::Public { + AcceptFollow::send(self, context).await?; + } } } - - AcceptFollow::send(self, context).await + Ok(()) } } diff --git a/crates/apub/src/activities/following/mod.rs b/crates/apub/src/activities/following/mod.rs index 7c7163f12..83cdc841c 100644 --- a/crates/apub/src/activities/following/mod.rs +++ b/crates/apub/src/activities/following/mod.rs @@ -1,15 +1,26 @@ +use super::generate_activity_id; use crate::{ objects::{community::ApubCommunity, person::ApubPerson}, - protocol::activities::following::{follow::Follow, undo_follow::UndoFollow}, + protocol::activities::following::{ + accept::AcceptFollow, + follow::Follow, + reject::RejectFollow, + undo_follow::UndoFollow, + }, }; -use activitypub_federation::config::Data; +use activitypub_federation::{config::Data, kinds::activity::FollowType}; use lemmy_api_common::context::LemmyContext; -use lemmy_db_schema::source::{community::Community, person::Person}; +use lemmy_db_schema::{ + newtypes::{CommunityId, PersonId}, + source::{community::Community, person::Person}, + traits::Crud, +}; use lemmy_utils::error::LemmyResult; -pub mod accept; -pub mod follow; -pub mod undo_follow; +pub(crate) mod accept; +pub(crate) mod follow; +pub(crate) mod reject; +pub(crate) mod undo_follow; pub async fn send_follow_community( community: Community, @@ -25,3 +36,29 @@ pub async fn send_follow_community( UndoFollow::send(&actor, &community, context).await } } + +pub async fn send_accept_or_reject_follow( + community_id: CommunityId, + person_id: PersonId, + accepted: bool, + context: &Data, +) -> LemmyResult<()> { + let community = Community::read(&mut context.pool(), community_id).await?; + let person = Person::read(&mut context.pool(), person_id).await?; + + let follow = Follow { + actor: person.actor_id.into(), + to: Some([community.actor_id.clone().into()]), + object: community.actor_id.into(), + kind: FollowType::Follow, + id: generate_activity_id( + FollowType::Follow, + &context.settings().get_protocol_and_hostname(), + )?, + }; + if accepted { + AcceptFollow::send(follow, context).await + } else { + RejectFollow::send(follow, context).await + } +} diff --git a/crates/apub/src/activities/following/reject.rs b/crates/apub/src/activities/following/reject.rs new file mode 100644 index 000000000..8f1623d20 --- /dev/null +++ b/crates/apub/src/activities/following/reject.rs @@ -0,0 +1,79 @@ +use crate::{ + activities::{generate_activity_id, send_lemmy_activity}, + insert_received_activity, + protocol::activities::following::{follow::Follow, reject::RejectFollow}, +}; +use activitypub_federation::{ + config::Data, + kinds::activity::RejectType, + protocol::verification::verify_urls_match, + traits::{ActivityHandler, Actor}, +}; +use lemmy_api_common::context::LemmyContext; +use lemmy_db_schema::{ + source::{ + activity::ActivitySendTargets, + community::{CommunityFollower, CommunityFollowerForm}, + }, + traits::Followable, +}; +use lemmy_utils::error::{LemmyError, LemmyResult}; +use url::Url; + +impl RejectFollow { + #[tracing::instrument(skip_all)] + pub async fn send(follow: Follow, context: &Data) -> LemmyResult<()> { + let user_or_community = follow.object.dereference_local(context).await?; + let person = follow.actor.clone().dereference(context).await?; + let reject = RejectFollow { + actor: user_or_community.id().into(), + to: Some([person.id().into()]), + object: follow, + kind: RejectType::Reject, + id: generate_activity_id( + RejectType::Reject, + &context.settings().get_protocol_and_hostname(), + )?, + }; + let inbox = ActivitySendTargets::to_inbox(person.shared_inbox_or_inbox()); + send_lemmy_activity(context, reject, &user_or_community, inbox, true).await + } +} + +/// Handle rejected follows +#[async_trait::async_trait] +impl ActivityHandler for RejectFollow { + type DataType = LemmyContext; + type Error = LemmyError; + + fn id(&self) -> &Url { + &self.id + } + + fn actor(&self) -> &Url { + self.actor.inner() + } + + #[tracing::instrument(skip_all)] + async fn verify(&self, context: &Data) -> LemmyResult<()> { + verify_urls_match(self.actor.inner(), self.object.object.inner())?; + self.object.verify(context).await?; + if let Some(to) = &self.to { + verify_urls_match(to[0].inner(), self.object.actor.inner())?; + } + Ok(()) + } + + #[tracing::instrument(skip_all)] + async fn receive(self, context: &Data) -> LemmyResult<()> { + insert_received_activity(&self.id, context).await?; + let community = self.actor.dereference(context).await?; + let person = self.object.actor.dereference(context).await?; + + // remove the follow + let form = CommunityFollowerForm::new(community.id, person.id); + CommunityFollower::unfollow(&mut context.pool(), &form).await?; + + Ok(()) + } +} diff --git a/crates/apub/src/activities/following/undo_follow.rs b/crates/apub/src/activities/following/undo_follow.rs index ba6253946..1aa6bb7fc 100644 --- a/crates/apub/src/activities/following/undo_follow.rs +++ b/crates/apub/src/activities/following/undo_follow.rs @@ -90,11 +90,7 @@ impl ActivityHandler for UndoFollow { PersonFollower::unfollow(&mut context.pool(), &form).await?; } UserOrCommunity::Community(c) => { - let form = CommunityFollowerForm { - community_id: c.id, - person_id: person.id, - pending: false, - }; + let form = CommunityFollowerForm::new(c.id, person.id); CommunityFollower::unfollow(&mut context.pool(), &form).await?; } } diff --git a/crates/apub/src/activities/mod.rs b/crates/apub/src/activities/mod.rs index 21723c390..ffb6a662e 100644 --- a/crates/apub/src/activities/mod.rs +++ b/crates/apub/src/activities/mod.rs @@ -30,6 +30,7 @@ use activitypub_federation::{ traits::{ActivityHandler, Actor}, }; use anyhow::anyhow; +use following::send_accept_or_reject_follow; use lemmy_api_common::{ context::LemmyContext, send_activity::{ActivityChannel, SendActivityData}, @@ -40,6 +41,7 @@ use lemmy_db_schema::{ community::Community, }, traits::Crud, + CommunityVisibility, }; use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView}; use lemmy_utils::error::{FederationError, LemmyError, LemmyErrorExt, LemmyErrorType, LemmyResult}; @@ -120,6 +122,28 @@ pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> LemmyResult<()> { } } +/// Returns an error if object visibility doesnt match community visibility +/// (ie content in private community must also be private). +pub(crate) fn verify_visibility(to: &[Url], cc: &[Url], community: &Community) -> LemmyResult<()> { + use CommunityVisibility::*; + let object_is_public = [to, cc].iter().any(|set| set.contains(&public())); + match community.visibility { + Public if !object_is_public => Err(FederationError::ObjectIsNotPublic)?, + Private if object_is_public => Err(FederationError::ObjectIsNotPrivate)?, + LocalOnly => Err(LemmyErrorType::NotFound.into()), + _ => Ok(()), + } +} + +/// Marks object as public only if the community is public +pub(crate) fn generate_to(community: &Community) -> LemmyResult { + if community.visibility == CommunityVisibility::Public { + Ok(public()) + } else { + Ok(Url::parse(&format!("{}/followers", community.actor_id))?) + } +} + pub(crate) fn verify_community_matches(a: &ObjectId, b: T) -> LemmyResult<()> where T: Into>, @@ -367,6 +391,12 @@ pub async fn match_outgoing_activities( community, reason, } => Report::send(ObjectId::from(object_id), actor, community, reason, context).await, + AcceptFollower(community_id, person_id) => { + send_accept_or_reject_follow(community_id, person_id, true, &context).await + } + RejectFollower(community_id, person_id) => { + send_accept_or_reject_follow(community_id, person_id, false, &context).await + } } }; fed_task.await?; diff --git a/crates/apub/src/activity_lists.rs b/crates/apub/src/activity_lists.rs index 1ba31b9b4..7ed1d8baf 100644 --- a/crates/apub/src/activity_lists.rs +++ b/crates/apub/src/activity_lists.rs @@ -17,7 +17,12 @@ use crate::{ page::CreateOrUpdatePage, }, deletion::{delete::Delete, undo_delete::UndoDelete}, - following::{accept::AcceptFollow, follow::Follow, undo_follow::UndoFollow}, + following::{ + accept::AcceptFollow, + follow::Follow, + reject::RejectFollow, + undo_follow::UndoFollow, + }, voting::{undo_vote::UndoVote, vote::Vote}, }, objects::page::Page, @@ -41,6 +46,7 @@ use url::Url; pub enum SharedInboxActivities { Follow(Follow), AcceptFollow(AcceptFollow), + RejectFollow(RejectFollow), UndoFollow(UndoFollow), CreateOrUpdatePrivateMessage(CreateOrUpdateChatMessage), Report(Report), @@ -68,6 +74,7 @@ pub enum GroupInboxActivities { pub enum PersonInboxActivities { Follow(Follow), AcceptFollow(AcceptFollow), + RejectFollow(RejectFollow), UndoFollow(UndoFollow), CreateOrUpdatePrivateMessage(CreateOrUpdateChatMessage), Delete(Delete), diff --git a/crates/apub/src/api/user_settings_backup.rs b/crates/apub/src/api/user_settings_backup.rs index 2e075c202..601ba8664 100644 --- a/crates/apub/src/api/user_settings_backup.rs +++ b/crates/apub/src/api/user_settings_backup.rs @@ -13,7 +13,7 @@ use lemmy_db_schema::{ newtypes::DbUrl, source::{ comment::{CommentSaved, CommentSavedForm}, - community::{CommunityFollower, CommunityFollowerForm}, + community::{CommunityFollower, CommunityFollowerForm, CommunityFollowerState}, community_block::{CommunityBlock, CommunityBlockForm}, instance::Instance, instance_block::{InstanceBlock, InstanceBlockForm}, @@ -186,9 +186,8 @@ pub async fn import_settings( |(followed, context)| async move { let community = followed.dereference(&context).await?; let form = CommunityFollowerForm { - person_id, - community_id: community.id, - pending: true, + state: Some(CommunityFollowerState::Pending), + ..CommunityFollowerForm::new(community.id, person_id) }; CommunityFollower::follow(&mut context.pool(), &form).await?; LemmyResult::Ok(()) @@ -319,7 +318,13 @@ pub(crate) mod tests { use lemmy_api_common::context::LemmyContext; use lemmy_db_schema::{ source::{ - community::{Community, CommunityFollower, CommunityFollowerForm, CommunityInsertForm}, + community::{ + Community, + CommunityFollower, + CommunityFollowerForm, + CommunityFollowerState, + CommunityInsertForm, + }, local_user::LocalUser, }, traits::{Crud, Followable}, @@ -327,7 +332,6 @@ pub(crate) mod tests { use lemmy_db_views::structs::LocalUserView; use lemmy_db_views_actor::structs::CommunityFollowerView; use lemmy_utils::error::{LemmyErrorType, LemmyResult}; - use pretty_assertions::assert_eq; use serial_test::serial; use std::time::Duration; use tokio::time::sleep; @@ -348,9 +352,8 @@ pub(crate) mod tests { ); let community = Community::create(pool, &community_form).await?; let follower_form = CommunityFollowerForm { - community_id: community.id, - person_id: export_user.person.id, - pending: false, + state: Some(CommunityFollowerState::Accepted), + ..CommunityFollowerForm::new(community.id, export_user.person.id) }; CommunityFollower::follow(pool, &follower_form).await?; diff --git a/crates/apub/src/fetcher/site_or_community_or_user.rs b/crates/apub/src/fetcher/site_or_community_or_user.rs index c6a1bb17e..79d7978ae 100644 --- a/crates/apub/src/fetcher/site_or_community_or_user.rs +++ b/crates/apub/src/fetcher/site_or_community_or_user.rs @@ -9,6 +9,7 @@ use activitypub_federation::{ }; use chrono::{DateTime, Utc}; use lemmy_api_common::context::LemmyContext; +use lemmy_db_schema::newtypes::InstanceId; use lemmy_utils::error::{LemmyError, LemmyResult}; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -127,3 +128,13 @@ impl Actor for SiteOrCommunityOrUser { } } } + +impl SiteOrCommunityOrUser { + pub fn instance_id(&self) -> InstanceId { + match self { + SiteOrCommunityOrUser::Site(s) => s.instance_id, + SiteOrCommunityOrUser::UserOrCommunity(UserOrCommunity::User(u)) => u.instance_id, + SiteOrCommunityOrUser::UserOrCommunity(UserOrCommunity::Community(c)) => c.instance_id, + } + } +} diff --git a/crates/apub/src/http/comment.rs b/crates/apub/src/http/comment.rs index d6b3c818d..41160234f 100644 --- a/crates/apub/src/http/comment.rs +++ b/crates/apub/src/http/comment.rs @@ -1,14 +1,10 @@ +use super::check_community_content_fetchable; use crate::{ - http::{ - check_community_public, - create_apub_response, - create_apub_tombstone_response, - redirect_remote_object, - }, + http::{create_apub_response, create_apub_tombstone_response, redirect_remote_object}, objects::comment::ApubComment, }; use activitypub_federation::{config::Data, traits::Object}; -use actix_web::{web::Path, HttpResponse}; +use actix_web::{web::Path, HttpRequest, HttpResponse}; use lemmy_api_common::context::LemmyContext; use lemmy_db_schema::{ newtypes::CommentId, @@ -28,13 +24,14 @@ pub(crate) struct CommentQuery { pub(crate) async fn get_apub_comment( info: Path, context: Data, + request: HttpRequest, ) -> LemmyResult { let id = CommentId(info.comment_id.parse::()?); // Can't use CommentView here because it excludes deleted/removed/local-only items let comment: ApubComment = Comment::read(&mut context.pool(), id).await?.into(); let post = Post::read(&mut context.pool(), comment.post_id).await?; let community = Community::read(&mut context.pool(), post.community_id).await?; - check_community_public(&community)?; + check_community_content_fetchable(&community, &request, &context).await?; if !comment.local { Ok(redirect_remote_object(&comment.ap_id)) diff --git a/crates/apub/src/http/community.rs b/crates/apub/src/http/community.rs index 2516020d3..96a917d91 100644 --- a/crates/apub/src/http/community.rs +++ b/crates/apub/src/http/community.rs @@ -1,3 +1,4 @@ +use super::check_community_content_fetchable; use crate::{ collections::{ community_featured::ApubCommunityFeatured, @@ -5,14 +6,14 @@ use crate::{ community_moderators::ApubCommunityModerators, community_outbox::ApubCommunityOutbox, }, - http::{check_community_public, create_apub_response, create_apub_tombstone_response}, + http::{check_community_fetchable, create_apub_response, create_apub_tombstone_response}, objects::community::ApubCommunity, }; use activitypub_federation::{ config::Data, traits::{Collection, Object}, }; -use actix_web::{web, HttpResponse}; +use actix_web::{web, HttpRequest, HttpResponse}; use lemmy_api_common::context::LemmyContext; use lemmy_db_schema::{source::community::Community, traits::ApubActor}; use lemmy_utils::error::{LemmyErrorType, LemmyResult}; @@ -38,7 +39,7 @@ pub(crate) async fn get_apub_community_http( if community.deleted || community.removed { return create_apub_tombstone_response(community.actor_id.clone()); } - check_community_public(&community)?; + check_community_fetchable(&community)?; let apub = community.into_json(&context).await?; create_apub_response(&apub) @@ -52,7 +53,7 @@ pub(crate) async fn get_apub_community_followers( let community = Community::read_from_name(&mut context.pool(), &info.community_name, false) .await? .ok_or(LemmyErrorType::NotFound)?; - check_community_public(&community)?; + check_community_fetchable(&community)?; let followers = ApubCommunityFollower::read_local(&community.into(), &context).await?; create_apub_response(&followers) } @@ -62,13 +63,14 @@ pub(crate) async fn get_apub_community_followers( pub(crate) async fn get_apub_community_outbox( info: web::Path, context: Data, + request: HttpRequest, ) -> LemmyResult { let community: ApubCommunity = Community::read_from_name(&mut context.pool(), &info.community_name, false) .await? .ok_or(LemmyErrorType::NotFound)? .into(); - check_community_public(&community)?; + check_community_content_fetchable(&community, &request, &context).await?; let outbox = ApubCommunityOutbox::read_local(&community, &context).await?; create_apub_response(&outbox) } @@ -83,7 +85,7 @@ pub(crate) async fn get_apub_community_moderators( .await? .ok_or(LemmyErrorType::NotFound)? .into(); - check_community_public(&community)?; + check_community_fetchable(&community)?; let moderators = ApubCommunityModerators::read_local(&community, &context).await?; create_apub_response(&moderators) } @@ -92,13 +94,14 @@ pub(crate) async fn get_apub_community_moderators( pub(crate) async fn get_apub_community_featured( info: web::Path, context: Data, + request: HttpRequest, ) -> LemmyResult { let community: ApubCommunity = Community::read_from_name(&mut context.pool(), &info.community_name, false) .await? .ok_or(LemmyErrorType::NotFound)? .into(); - check_community_public(&community)?; + check_community_content_fetchable(&community, &request, &context).await?; let featured = ApubCommunityFeatured::read_local(&community, &context).await?; create_apub_response(&featured) } @@ -108,7 +111,7 @@ pub(crate) mod tests { use super::*; use crate::protocol::objects::{group::Group, tombstone::Tombstone}; - use actix_web::body::to_bytes; + use actix_web::{body::to_bytes, test::TestRequest}; use lemmy_db_schema::{ newtypes::InstanceId, source::{ @@ -175,6 +178,7 @@ pub(crate) mod tests { async fn test_get_community() -> LemmyResult<()> { let context = LemmyContext::init_test_context().await; let (instance, community) = init(false, CommunityVisibility::Public, &context).await?; + let request = TestRequest::default().to_http_request(); // fetch invalid community let query = CommunityQuery { @@ -194,8 +198,12 @@ pub(crate) mod tests { let group = community.clone().into_json(&context).await?; assert_eq!(group, res_group); - let res = - get_apub_community_featured(query.clone().into(), context.reset_request_count()).await?; + let res = get_apub_community_featured( + query.clone().into(), + context.reset_request_count(), + request.clone(), + ) + .await?; assert_eq!(200, res.status()); let res = get_apub_community_followers(query.clone().into(), context.reset_request_count()).await?; @@ -203,7 +211,8 @@ pub(crate) mod tests { let res = get_apub_community_moderators(query.clone().into(), context.reset_request_count()).await?; assert_eq!(200, res.status()); - let res = get_apub_community_outbox(query.into(), context.reset_request_count()).await?; + let res = + get_apub_community_outbox(query.into(), context.reset_request_count(), request).await?; assert_eq!(200, res.status()); Instance::delete(&mut context.pool(), instance.id).await?; @@ -215,6 +224,7 @@ pub(crate) mod tests { async fn test_get_deleted_community() -> LemmyResult<()> { let context = LemmyContext::init_test_context().await; let (instance, community) = init(true, CommunityVisibility::LocalOnly, &context).await?; + let request = TestRequest::default().to_http_request(); // should return tombstone let query = CommunityQuery { @@ -225,8 +235,12 @@ pub(crate) mod tests { let res_tombstone = decode_response::(res).await; assert!(res_tombstone.is_ok()); - let res = - get_apub_community_featured(query.clone().into(), context.reset_request_count()).await; + let res = get_apub_community_featured( + query.clone().into(), + context.reset_request_count(), + request.clone(), + ) + .await; assert!(res.is_err()); let res = get_apub_community_followers(query.clone().into(), context.reset_request_count()).await; @@ -234,7 +248,7 @@ pub(crate) mod tests { let res = get_apub_community_moderators(query.clone().into(), context.reset_request_count()).await; assert!(res.is_err()); - let res = get_apub_community_outbox(query.into(), context.reset_request_count()).await; + let res = get_apub_community_outbox(query.into(), context.reset_request_count(), request).await; assert!(res.is_err()); //Community::delete(&mut context.pool(), community.id).await?; @@ -247,14 +261,19 @@ pub(crate) mod tests { async fn test_get_local_only_community() -> LemmyResult<()> { let context = LemmyContext::init_test_context().await; let (instance, community) = init(false, CommunityVisibility::LocalOnly, &context).await?; + let request = TestRequest::default().to_http_request(); let query = CommunityQuery { community_name: community.name.clone(), }; let res = get_apub_community_http(query.clone().into(), context.reset_request_count()).await; assert!(res.is_err()); - let res = - get_apub_community_featured(query.clone().into(), context.reset_request_count()).await; + let res = get_apub_community_featured( + query.clone().into(), + context.reset_request_count(), + request.clone(), + ) + .await; assert!(res.is_err()); let res = get_apub_community_followers(query.clone().into(), context.reset_request_count()).await; @@ -262,7 +281,7 @@ pub(crate) mod tests { let res = get_apub_community_moderators(query.clone().into(), context.reset_request_count()).await; assert!(res.is_err()); - let res = get_apub_community_outbox(query.into(), context.reset_request_count()).await; + let res = get_apub_community_outbox(query.into(), context.reset_request_count(), request).await; assert!(res.is_err()); Instance::delete(&mut context.pool(), instance.id).await?; diff --git a/crates/apub/src/http/mod.rs b/crates/apub/src/http/mod.rs index bc148eb9c..d79cd3d55 100644 --- a/crates/apub/src/http/mod.rs +++ b/crates/apub/src/http/mod.rs @@ -1,11 +1,11 @@ use crate::{ activity_lists::SharedInboxActivities, - fetcher::user_or_community::UserOrCommunity, + fetcher::{site_or_community_or_user::SiteOrCommunityOrUser, user_or_community::UserOrCommunity}, protocol::objects::tombstone::Tombstone, FEDERATION_CONTEXT, }; use activitypub_federation::{ - actix_web::inbox::receive_activity, + actix_web::{inbox::receive_activity, signing_actor}, config::Data, protocol::context::WithContext, FEDERATION_CONTENT_TYPE, @@ -17,6 +17,7 @@ use lemmy_db_schema::{ source::{activity::SentActivity, community::Community}, CommunityVisibility, }; +use lemmy_db_views_actor::structs::CommunityFollowerView; use lemmy_utils::error::{FederationError, LemmyErrorType, LemmyResult}; use serde::{Deserialize, Serialize}; use std::{ops::Deref, time::Duration}; @@ -119,12 +120,46 @@ pub(crate) async fn get_activity( } /// Ensure that the community is public and not removed/deleted. -fn check_community_public(community: &Community) -> LemmyResult<()> { - if community.deleted || community.removed { - Err(LemmyErrorType::Deleted)? - } - if community.visibility != CommunityVisibility::Public { +fn check_community_fetchable(community: &Community) -> LemmyResult<()> { + check_community_removed_or_deleted(community)?; + if community.visibility == CommunityVisibility::LocalOnly { return Err(LemmyErrorType::NotFound.into()); } Ok(()) } + +/// Check if posts or comments in the community are allowed to be fetched +async fn check_community_content_fetchable( + community: &Community, + request: &HttpRequest, + context: &Data, +) -> LemmyResult<()> { + use CommunityVisibility::*; + check_community_removed_or_deleted(community)?; + match community.visibility { + // content in public community can always be fetched + Public => Ok(()), + // no federation for local only community + LocalOnly => Err(LemmyErrorType::NotFound.into()), + // for private community check http signature of request, if there is any approved follower + // from the fetching instance then fetching is allowed + Private => { + let signing_actor = signing_actor::(request, None, context).await?; + Ok( + CommunityFollowerView::check_has_followers_from_instance( + community.id, + signing_actor.instance_id(), + &mut context.pool(), + ) + .await?, + ) + } + } +} + +fn check_community_removed_or_deleted(community: &Community) -> LemmyResult<()> { + if community.deleted || community.removed { + Err(LemmyErrorType::Deleted)? + } + Ok(()) +} diff --git a/crates/apub/src/http/post.rs b/crates/apub/src/http/post.rs index ce6612826..6afb9fc3e 100644 --- a/crates/apub/src/http/post.rs +++ b/crates/apub/src/http/post.rs @@ -1,14 +1,10 @@ +use super::check_community_content_fetchable; use crate::{ - http::{ - check_community_public, - create_apub_response, - create_apub_tombstone_response, - redirect_remote_object, - }, + http::{create_apub_response, create_apub_tombstone_response, redirect_remote_object}, objects::post::ApubPost, }; use activitypub_federation::{config::Data, traits::Object}; -use actix_web::{web, HttpResponse}; +use actix_web::{web, HttpRequest, HttpResponse}; use lemmy_api_common::context::LemmyContext; use lemmy_db_schema::{ newtypes::PostId, @@ -28,12 +24,14 @@ pub(crate) struct PostQuery { pub(crate) async fn get_apub_post( info: web::Path, context: Data, + request: HttpRequest, ) -> LemmyResult { let id = PostId(info.post_id.parse::()?); // Can't use PostView here because it excludes deleted/removed/local-only items let post: ApubPost = Post::read(&mut context.pool(), id).await?.into(); let community = Community::read(&mut context.pool(), post.community_id).await?; - check_community_public(&community)?; + + check_community_content_fetchable(&community, &request, &context).await?; if !post.local { Ok(redirect_remote_object(&post.ap_id)) diff --git a/crates/apub/src/objects/comment.rs b/crates/apub/src/objects/comment.rs index 6e13afc91..b7c6a5f51 100644 --- a/crates/apub/src/objects/comment.rs +++ b/crates/apub/src/objects/comment.rs @@ -1,5 +1,5 @@ use crate::{ - activities::{verify_is_public, verify_person_in_community}, + activities::{generate_to, verify_person_in_community, verify_visibility}, check_apub_id_valid_with_strictness, fetcher::markdown_links::markdown_rewrite_remote_links, mentions::collect_non_local_mentions, @@ -12,7 +12,7 @@ use crate::{ }; use activitypub_federation::{ config::Data, - kinds::{object::NoteType, public}, + kinds::object::NoteType, protocol::{values::MediaTypeMarkdownOrHtml, verification::verify_domains_match}, traits::Object, }; @@ -112,7 +112,7 @@ impl Object for ApubComment { r#type: NoteType::Note, id: self.ap_id.clone().into(), attributed_to: creator.actor_id.into(), - to: vec![public()], + to: vec![generate_to(&community)?], cc: maa.ccs, content: markdown_to_html(&self.content), media_type: Some(MediaTypeMarkdownOrHtml::Html), @@ -140,8 +140,8 @@ impl Object for ApubComment { ) -> LemmyResult<()> { verify_domains_match(note.id.inner(), expected_domain)?; verify_domains_match(note.attributed_to.inner(), note.id.inner())?; - verify_is_public(¬e.to, ¬e.cc)?; let community = Box::pin(note.community(context)).await?; + verify_visibility(¬e.to, ¬e.cc, &community)?; Box::pin(check_apub_id_valid_with_strictness( note.id.inner(), diff --git a/crates/apub/src/objects/community.rs b/crates/apub/src/objects/community.rs index 7ee204ac9..efa2c5247 100644 --- a/crates/apub/src/objects/community.rs +++ b/crates/apub/src/objects/community.rs @@ -39,6 +39,7 @@ use lemmy_db_schema::{ }, traits::{ApubActor, Crud}, utils::naive_now, + CommunityVisibility, }; use lemmy_db_views_actor::structs::CommunityFollowerView; use lemmy_utils::{ @@ -126,6 +127,7 @@ impl Object for ApubCommunity { updated: self.updated, posting_restricted_to_mods: Some(self.posting_restricted_to_mods), attributed_to: Some(generate_moderators_url(&self.actor_id)?.into()), + manually_approves_followers: Some(self.visibility == CommunityVisibility::Private), }; Ok(group) } @@ -152,7 +154,11 @@ impl Object for ApubCommunity { let sidebar = markdown_rewrite_remote_links_opt(sidebar, context).await; let icon = proxy_image_link_opt_apub(group.icon.map(|i| i.url), context).await?; let banner = proxy_image_link_opt_apub(group.image.map(|i| i.url), context).await?; - + let visibility = Some(if group.manually_approves_followers.unwrap_or_default() { + CommunityVisibility::Private + } else { + CommunityVisibility::Public + }); let form = CommunityInsertForm { published: group.published, updated: group.updated, @@ -176,6 +182,7 @@ impl Object for ApubCommunity { moderators_url: group.attributed_to.clone().map(Into::into), posting_restricted_to_mods: group.posting_restricted_to_mods, featured_url: group.featured.clone().map(Into::into), + visibility, ..CommunityInsertForm::new( instance_id, group.preferred_username.clone(), diff --git a/crates/apub/src/objects/post.rs b/crates/apub/src/objects/post.rs index ee88cf3ec..b72fa1728 100644 --- a/crates/apub/src/objects/post.rs +++ b/crates/apub/src/objects/post.rs @@ -1,5 +1,5 @@ use crate::{ - activities::{verify_is_public, verify_person_in_community}, + activities::{generate_to, verify_person_in_community, verify_visibility}, check_apub_id_valid_with_strictness, fetcher::markdown_links::{markdown_rewrite_remote_links_opt, to_local_url}, local_site_data_cached, @@ -16,7 +16,6 @@ use crate::{ }; use activitypub_federation::{ config::Data, - kinds::public, protocol::{values::MediaTypeMarkdownOrHtml, verification::verify_domains_match}, traits::Object, }; @@ -135,7 +134,7 @@ impl Object for ApubPost { kind: PageType::Page, id: self.ap_id.clone().into(), attributed_to: AttributedTo::Lemmy(creator.actor_id.into()), - to: vec![community.actor_id.clone().into(), public()], + to: vec![generate_to(&community)?], cc: vec![], name: Some(self.name.clone()), content: self.body.as_ref().map(|b| markdown_to_html(b)), @@ -172,7 +171,7 @@ impl Object for ApubPost { check_slurs_opt(&page.name, slur_regex)?; verify_domains_match(page.creator()?.inner(), page.id.inner())?; - verify_is_public(&page.to, &page.cc)?; + verify_visibility(&page.to, &page.cc, &community)?; Ok(()) } diff --git a/crates/apub/src/protocol/activities/following/mod.rs b/crates/apub/src/protocol/activities/following/mod.rs index ec263adae..1bb805608 100644 --- a/crates/apub/src/protocol/activities/following/mod.rs +++ b/crates/apub/src/protocol/activities/following/mod.rs @@ -1,5 +1,6 @@ pub(crate) mod accept; pub mod follow; +pub(crate) mod reject; pub mod undo_follow; #[cfg(test)] diff --git a/crates/apub/src/protocol/activities/following/reject.rs b/crates/apub/src/protocol/activities/following/reject.rs new file mode 100644 index 000000000..1584dfb11 --- /dev/null +++ b/crates/apub/src/protocol/activities/following/reject.rs @@ -0,0 +1,24 @@ +use crate::{ + objects::{community::ApubCommunity, person::ApubPerson}, + protocol::activities::following::follow::Follow, +}; +use activitypub_federation::{ + fetch::object_id::ObjectId, + kinds::activity::RejectType, + protocol::helpers::deserialize_skip_error, +}; +use serde::{Deserialize, Serialize}; +use url::Url; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RejectFollow { + pub(crate) actor: ObjectId, + /// Optional, for compatibility with platforms that always expect recipient field + #[serde(deserialize_with = "deserialize_skip_error", default)] + pub(crate) to: Option<[ObjectId; 1]>, + pub(crate) object: Follow, + #[serde(rename = "type")] + pub(crate) kind: RejectType, + pub(crate) id: Url, +} diff --git a/crates/apub/src/protocol/objects/group.rs b/crates/apub/src/protocol/objects/group.rs index affafe269..dbf4af892 100644 --- a/crates/apub/src/protocol/objects/group.rs +++ b/crates/apub/src/protocol/objects/group.rs @@ -73,6 +73,8 @@ pub struct Group { pub(crate) featured: Option>, #[serde(default)] pub(crate) language: Vec, + /// True if this is a private community + pub(crate) manually_approves_followers: Option, pub(crate) published: Option>, pub(crate) updated: Option>, } diff --git a/crates/db_perf/src/main.rs b/crates/db_perf/src/main.rs index 0fa5c0549..02796a906 100644 --- a/crates/db_perf/src/main.rs +++ b/crates/db_perf/src/main.rs @@ -54,7 +54,7 @@ async fn main() -> anyhow::Result<()> { async fn try_main() -> LemmyResult<()> { let args = CmdArgs::parse(); - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let conn = &mut get_conn(pool).await?; diff --git a/crates/db_schema/src/aggregates/comment_aggregates.rs b/crates/db_schema/src/aggregates/comment_aggregates.rs index a97bb565b..b26d27736 100644 --- a/crates/db_schema/src/aggregates/comment_aggregates.rs +++ b/crates/db_schema/src/aggregates/comment_aggregates.rs @@ -51,7 +51,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_schema/src/aggregates/community_aggregates.rs b/crates/db_schema/src/aggregates/community_aggregates.rs index 0359d8632..3ec56d73d 100644 --- a/crates/db_schema/src/aggregates/community_aggregates.rs +++ b/crates/db_schema/src/aggregates/community_aggregates.rs @@ -37,7 +37,13 @@ mod tests { aggregates::community_aggregates::CommunityAggregates, source::{ comment::{Comment, CommentInsertForm}, - community::{Community, CommunityFollower, CommunityFollowerForm, CommunityInsertForm}, + community::{ + Community, + CommunityFollower, + CommunityFollowerForm, + CommunityFollowerState, + CommunityInsertForm, + }, instance::Instance, person::{Person, PersonInsertForm}, post::{Post, PostInsertForm}, @@ -52,7 +58,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; @@ -84,7 +90,8 @@ mod tests { let first_person_follow = CommunityFollowerForm { community_id: inserted_community.id, person_id: inserted_person.id, - pending: false, + state: Some(CommunityFollowerState::Accepted), + approver_id: None, }; CommunityFollower::follow(pool, &first_person_follow).await?; @@ -92,7 +99,8 @@ mod tests { let second_person_follow = CommunityFollowerForm { community_id: inserted_community.id, person_id: another_inserted_person.id, - pending: false, + state: Some(CommunityFollowerState::Accepted), + approver_id: None, }; CommunityFollower::follow(pool, &second_person_follow).await?; @@ -100,7 +108,8 @@ mod tests { let another_community_follow = CommunityFollowerForm { community_id: another_inserted_community.id, person_id: inserted_person.id, - pending: false, + state: Some(CommunityFollowerState::Accepted), + approver_id: None, }; CommunityFollower::follow(pool, &another_community_follow).await?; diff --git a/crates/db_schema/src/aggregates/person_aggregates.rs b/crates/db_schema/src/aggregates/person_aggregates.rs index 6e0eacc07..62aa9b609 100644 --- a/crates/db_schema/src/aggregates/person_aggregates.rs +++ b/crates/db_schema/src/aggregates/person_aggregates.rs @@ -36,7 +36,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_schema/src/aggregates/post_aggregates.rs b/crates/db_schema/src/aggregates/post_aggregates.rs index b63017317..46747b076 100644 --- a/crates/db_schema/src/aggregates/post_aggregates.rs +++ b/crates/db_schema/src/aggregates/post_aggregates.rs @@ -70,7 +70,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; @@ -182,7 +182,7 @@ mod tests { #[tokio::test] #[serial] async fn test_soft_delete() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_schema/src/aggregates/site_aggregates.rs b/crates/db_schema/src/aggregates/site_aggregates.rs index 379ddd2d9..2df566290 100644 --- a/crates/db_schema/src/aggregates/site_aggregates.rs +++ b/crates/db_schema/src/aggregates/site_aggregates.rs @@ -65,7 +65,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let (inserted_instance, inserted_person, inserted_site, inserted_community) = @@ -136,7 +136,7 @@ mod tests { #[tokio::test] #[serial] async fn test_soft_delete() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let (inserted_instance, inserted_person, inserted_site, inserted_community) = diff --git a/crates/db_schema/src/impls/activity.rs b/crates/db_schema/src/impls/activity.rs index fff0c2f0c..d2cc6dcef 100644 --- a/crates/db_schema/src/impls/activity.rs +++ b/crates/db_schema/src/impls/activity.rs @@ -71,7 +71,7 @@ mod tests { #[tokio::test] #[serial] async fn receive_activity_duplicate() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let ap_id: DbUrl = Url::parse("http://example.com/activity/531")?.into(); @@ -86,7 +86,7 @@ mod tests { #[tokio::test] #[serial] async fn sent_activity_write_read() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let ap_id: DbUrl = Url::parse("http://example.com/activity/412")?.into(); let data = json!({ diff --git a/crates/db_schema/src/impls/actor_language.rs b/crates/db_schema/src/impls/actor_language.rs index bff729f41..b4ad0d347 100644 --- a/crates/db_schema/src/impls/actor_language.rs +++ b/crates/db_schema/src/impls/actor_language.rs @@ -438,7 +438,7 @@ mod tests { #[tokio::test] #[serial] async fn test_convert_update_languages() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); // call with empty vec, returns all languages @@ -457,7 +457,7 @@ mod tests { #[serial] async fn test_convert_read_languages() -> Result<(), Error> { use crate::schema::language::dsl::{id, language}; - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); // call with all languages, returns empty vec @@ -477,7 +477,7 @@ mod tests { #[tokio::test] #[serial] async fn test_site_languages() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let (site, instance) = create_test_site(pool).await?; @@ -502,7 +502,7 @@ mod tests { #[tokio::test] #[serial] async fn test_user_languages() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let (site, instance) = create_test_site(pool).await?; @@ -535,7 +535,7 @@ mod tests { #[tokio::test] #[serial] async fn test_community_languages() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let (site, instance) = create_test_site(pool).await?; let test_langs = test_langs1(pool).await?; @@ -591,7 +591,7 @@ mod tests { #[tokio::test] #[serial] async fn test_default_post_language() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let (site, instance) = create_test_site(pool).await?; let test_langs = test_langs1(pool).await?; diff --git a/crates/db_schema/src/impls/captcha_answer.rs b/crates/db_schema/src/impls/captcha_answer.rs index e7ba86d39..8be8fc5de 100644 --- a/crates/db_schema/src/impls/captcha_answer.rs +++ b/crates/db_schema/src/impls/captcha_answer.rs @@ -62,7 +62,7 @@ mod tests { #[tokio::test] #[serial] async fn test_captcha_happy_path() { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted = CaptchaAnswer::insert( @@ -89,7 +89,7 @@ mod tests { #[tokio::test] #[serial] async fn test_captcha_repeat_answer_fails() { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted = CaptchaAnswer::insert( diff --git a/crates/db_schema/src/impls/comment.rs b/crates/db_schema/src/impls/comment.rs index 30d18465f..d261dbf2c 100644 --- a/crates/db_schema/src/impls/comment.rs +++ b/crates/db_schema/src/impls/comment.rs @@ -227,7 +227,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_schema/src/impls/community.rs b/crates/db_schema/src/impls/community.rs index 8efc579e9..5375bcc3c 100644 --- a/crates/db_schema/src/impls/community.rs +++ b/crates/db_schema/src/impls/community.rs @@ -15,6 +15,7 @@ use crate::{ Community, CommunityFollower, CommunityFollowerForm, + CommunityFollowerState, CommunityInsertForm, CommunityModerator, CommunityModeratorForm, @@ -324,22 +325,8 @@ impl Bannable for CommunityPersonBan { } impl CommunityFollower { - pub fn to_subscribed_type(follower: &Option) -> SubscribedType { - match follower { - Some(f) => { - if f.pending { - SubscribedType::Pending - } else { - SubscribedType::Subscribed - } - } - // If the row doesn't exist, the person isn't a follower. - None => SubscribedType::NotSubscribed, - } - } - - pub fn select_subscribed_type() -> dsl::Nullable { - community_follower::pending.nullable() + pub fn select_subscribed_type() -> dsl::Nullable { + community_follower::state.nullable() } /// Check if a remote instance has any followers on local instance. For this it is enough to check @@ -357,14 +344,34 @@ impl CommunityFollower { .then_some(()) .ok_or(LemmyErrorType::CommunityHasNoFollowers.into()) } + + pub async fn approve( + pool: &mut DbPool<'_>, + community_id: CommunityId, + follower_id: PersonId, + approver_id: PersonId, + ) -> LemmyResult<()> { + let conn = &mut get_conn(pool).await?; + diesel::update(community_follower::table.find((follower_id, community_id))) + .set(( + community_follower::state.eq(CommunityFollowerState::Accepted), + community_follower::approver_id.eq(approver_id), + )) + .get_result::(conn) + .await?; + Ok(()) + } } -impl Queryable, Pg> for SubscribedType { - type Row = Option; +impl Queryable, Pg> + for SubscribedType +{ + type Row = Option; fn build(row: Self::Row) -> deserialize::Result { Ok(match row { - Some(true) => SubscribedType::Pending, - Some(false) => SubscribedType::Subscribed, + Some(CommunityFollowerState::Pending) => SubscribedType::Pending, + Some(CommunityFollowerState::Accepted) => SubscribedType::Subscribed, + Some(CommunityFollowerState::ApprovalRequired) => SubscribedType::ApprovalRequired, None => SubscribedType::NotSubscribed, }) } @@ -393,7 +400,7 @@ impl Followable for CommunityFollower { ) -> Result { let conn = &mut get_conn(pool).await?; diesel::update(community_follower::table.find((person_id, community_id))) - .set(community_follower::pending.eq(false)) + .set(community_follower::state.eq(CommunityFollowerState::Accepted)) .get_result::(conn) .await } @@ -463,6 +470,7 @@ mod tests { Community, CommunityFollower, CommunityFollowerForm, + CommunityFollowerState, CommunityInsertForm, CommunityModerator, CommunityModeratorForm, @@ -485,7 +493,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; @@ -535,7 +543,8 @@ mod tests { let community_follower_form = CommunityFollowerForm { community_id: inserted_community.id, person_id: inserted_bobby.id, - pending: false, + state: Some(CommunityFollowerState::Accepted), + approver_id: None, }; let inserted_community_follower = @@ -544,8 +553,9 @@ mod tests { let expected_community_follower = CommunityFollower { community_id: inserted_community.id, person_id: inserted_bobby.id, - pending: false, + state: CommunityFollowerState::Accepted, published: inserted_community_follower.published, + approver_id: None, }; let bobby_moderator_form = CommunityModeratorForm { diff --git a/crates/db_schema/src/impls/federation_allowlist.rs b/crates/db_schema/src/impls/federation_allowlist.rs index cbfd14b03..099e0b231 100644 --- a/crates/db_schema/src/impls/federation_allowlist.rs +++ b/crates/db_schema/src/impls/federation_allowlist.rs @@ -61,7 +61,7 @@ mod tests { #[tokio::test] #[serial] async fn test_allowlist_insert_and_clear() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let domains = vec![ "tld1.xyz".to_string(), diff --git a/crates/db_schema/src/impls/language.rs b/crates/db_schema/src/impls/language.rs index 57420fcd4..3b8bc1d20 100644 --- a/crates/db_schema/src/impls/language.rs +++ b/crates/db_schema/src/impls/language.rs @@ -46,7 +46,7 @@ mod tests { #[tokio::test] #[serial] async fn test_languages() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let all = Language::read_all(pool).await?; diff --git a/crates/db_schema/src/impls/local_user.rs b/crates/db_schema/src/impls/local_user.rs index 235f053c1..69a5ef314 100644 --- a/crates/db_schema/src/impls/local_user.rs +++ b/crates/db_schema/src/impls/local_user.rs @@ -331,6 +331,7 @@ impl LocalUserOptionHelper for Option<&LocalUser> { .unwrap_or(site.content_warning.is_some()) } + // TODO: use this function for private community checks, but the generics get extremely confusing fn visible_communities_only(&self, query: Q) -> Q where Q: diesel::query_dsl::methods::FilterDsl< @@ -385,7 +386,7 @@ mod tests { #[tokio::test] #[serial] async fn test_admin_higher_check() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; @@ -424,7 +425,7 @@ mod tests { #[tokio::test] #[serial] async fn test_email_taken() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let darwin_email = "charles.darwin@gmail.com"; diff --git a/crates/db_schema/src/impls/moderator.rs b/crates/db_schema/src/impls/moderator.rs index b2ef26e69..8deb56258 100644 --- a/crates/db_schema/src/impls/moderator.rs +++ b/crates/db_schema/src/impls/moderator.rs @@ -533,7 +533,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_schema/src/impls/password_reset_request.rs b/crates/db_schema/src/impls/password_reset_request.rs index 015db5581..a9ac3a9c2 100644 --- a/crates/db_schema/src/impls/password_reset_request.rs +++ b/crates/db_schema/src/impls/password_reset_request.rs @@ -61,7 +61,7 @@ mod tests { #[tokio::test] #[serial] async fn test_password_reset() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); // Setup diff --git a/crates/db_schema/src/impls/person.rs b/crates/db_schema/src/impls/person.rs index fb287ef77..85ab20d6a 100644 --- a/crates/db_schema/src/impls/person.rs +++ b/crates/db_schema/src/impls/person.rs @@ -252,7 +252,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; @@ -306,7 +306,7 @@ mod tests { #[tokio::test] #[serial] async fn follow() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_schema/src/impls/post.rs b/crates/db_schema/src/impls/post.rs index fb6245585..bd99344b9 100644 --- a/crates/db_schema/src/impls/post.rs +++ b/crates/db_schema/src/impls/post.rs @@ -423,7 +423,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_schema/src/impls/post_report.rs b/crates/db_schema/src/impls/post_report.rs index 5507423e1..e7d27aee9 100644 --- a/crates/db_schema/src/impls/post_report.rs +++ b/crates/db_schema/src/impls/post_report.rs @@ -126,7 +126,7 @@ mod tests { #[tokio::test] #[serial] async fn test_resolve_post_report() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let (person, report) = init(pool).await?; @@ -146,7 +146,7 @@ mod tests { #[tokio::test] #[serial] async fn test_resolve_all_post_reports() -> Result<(), Error> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let (person, report) = init(pool).await?; diff --git a/crates/db_schema/src/impls/private_message.rs b/crates/db_schema/src/impls/private_message.rs index 264175fe2..e08b4cf7f 100644 --- a/crates/db_schema/src/impls/private_message.rs +++ b/crates/db_schema/src/impls/private_message.rs @@ -104,7 +104,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_schema/src/lib.rs b/crates/db_schema/src/lib.rs index dbadaaf95..0397c939a 100644 --- a/crates/db_schema/src/lib.rs +++ b/crates/db_schema/src/lib.rs @@ -191,6 +191,7 @@ pub enum SubscribedType { Subscribed, NotSubscribed, Pending, + ApprovalRequired, } #[derive(EnumString, Display, Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash)] @@ -241,14 +242,14 @@ pub enum PostFeatureType { #[cfg_attr(feature = "full", DbValueStyle = "verbatim")] #[cfg_attr(feature = "full", ts(export))] /// Defines who can browse and interact with content in a community. -/// -/// TODO: Also use this to define private communities pub enum CommunityVisibility { /// Public community, any local or federated user can interact. #[default] Public, /// Unfederated community, only local users can interact. LocalOnly, + /// Users need to be approved by mods before they are able to browse or post. + Private, } #[derive( diff --git a/crates/db_schema/src/schema.rs b/crates/db_schema/src/schema.rs index 9f1d00568..a986f55d1 100644 --- a/crates/db_schema/src/schema.rs +++ b/crates/db_schema/src/schema.rs @@ -1,39 +1,43 @@ // @generated automatically by Diesel CLI. pub mod sql_types { - #[derive(diesel::sql_types::SqlType)] + #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)] #[diesel(postgres_type(name = "actor_type_enum"))] pub struct ActorTypeEnum; - #[derive(diesel::sql_types::SqlType)] + #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)] #[diesel(postgres_type(name = "comment_sort_type_enum"))] pub struct CommentSortTypeEnum; - #[derive(diesel::sql_types::SqlType)] + #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)] + #[diesel(postgres_type(name = "community_follower_state"))] + pub struct CommunityFollowerState; + + #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)] #[diesel(postgres_type(name = "community_visibility"))] pub struct CommunityVisibility; - #[derive(diesel::sql_types::SqlType)] + #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)] #[diesel(postgres_type(name = "federation_mode_enum"))] pub struct FederationModeEnum; - #[derive(diesel::sql_types::SqlType)] + #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)] #[diesel(postgres_type(name = "listing_type_enum"))] pub struct ListingTypeEnum; - #[derive(diesel::sql_types::SqlType)] + #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)] #[diesel(postgres_type(name = "ltree"))] pub struct Ltree; - #[derive(diesel::sql_types::SqlType)] + #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)] #[diesel(postgres_type(name = "post_listing_mode_enum"))] pub struct PostListingModeEnum; - #[derive(diesel::sql_types::SqlType)] + #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)] #[diesel(postgres_type(name = "post_sort_type_enum"))] pub struct PostSortTypeEnum; - #[derive(diesel::sql_types::SqlType)] + #[derive(diesel::query_builder::QueryId, diesel::sql_types::SqlType)] #[diesel(postgres_type(name = "registration_mode_enum"))] pub struct RegistrationModeEnum; } @@ -226,11 +230,15 @@ diesel::table! { } diesel::table! { + use diesel::sql_types::*; + use super::sql_types::CommunityFollowerState; + community_follower (person_id, community_id) { community_id -> Int4, person_id -> Int4, published -> Timestamptz, - pending -> Bool, + state -> CommunityFollowerState, + approver_id -> Nullable, } } @@ -1006,7 +1014,6 @@ diesel::joinable!(community_aggregates -> community (community_id)); diesel::joinable!(community_block -> community (community_id)); diesel::joinable!(community_block -> person (person_id)); diesel::joinable!(community_follower -> community (community_id)); -diesel::joinable!(community_follower -> person (person_id)); diesel::joinable!(community_language -> community (community_id)); diesel::joinable!(community_language -> language (language_id)); diesel::joinable!(community_moderator -> community (community_id)); diff --git a/crates/db_schema/src/source/community.rs b/crates/db_schema/src/source/community.rs index 870a132f2..95d2a67c3 100644 --- a/crates/db_schema/src/source/community.rs +++ b/crates/db_schema/src/source/community.rs @@ -9,6 +9,7 @@ use crate::{ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; +use strum::{Display, EnumString}; #[cfg(feature = "full")] use ts_rs::TS; @@ -207,6 +208,20 @@ pub struct CommunityPersonBanForm { pub expires: Option>>, } +#[derive(EnumString, Display, Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "full", derive(DbEnum, TS))] +#[cfg_attr( + feature = "full", + ExistingTypePath = "crate::schema::sql_types::CommunityFollowerState" +)] +#[cfg_attr(feature = "full", DbValueStyle = "verbatim")] +#[cfg_attr(feature = "full", ts(export))] +pub enum CommunityFollowerState { + Accepted, + Pending, + ApprovalRequired, +} + #[derive(PartialEq, Eq, Debug)] #[cfg_attr( feature = "full", @@ -223,14 +238,18 @@ pub struct CommunityFollower { pub community_id: CommunityId, pub person_id: PersonId, pub published: DateTime, - pub pending: bool, + pub state: CommunityFollowerState, + pub approver_id: Option, } -#[derive(Clone)] +#[derive(Clone, derive_new::new)] #[cfg_attr(feature = "full", derive(Insertable, AsChangeset))] #[cfg_attr(feature = "full", diesel(table_name = community_follower))] pub struct CommunityFollowerForm { pub community_id: CommunityId, pub person_id: PersonId, - pub pending: bool, + #[new(default)] + pub state: Option, + #[new(default)] + pub approver_id: Option, } diff --git a/crates/db_schema/src/utils.rs b/crates/db_schema/src/utils.rs index 6c5b792eb..03f1bb8ca 100644 --- a/crates/db_schema/src/utils.rs +++ b/crates/db_schema/src/utils.rs @@ -453,7 +453,7 @@ impl ServerCertVerifier for NoCertVerifier { } } -pub async fn build_db_pool() -> LemmyResult { +pub fn build_db_pool() -> LemmyResult { let db_url = SETTINGS.get_database_url(); // diesel-async does not support any TLS connections out of the box, so we need to manually // provide a setup function which handles creating the connection @@ -482,8 +482,8 @@ pub async fn build_db_pool() -> LemmyResult { Ok(pool) } -pub async fn build_db_pool_for_tests() -> ActualDbPool { - build_db_pool().await.expect("db pool missing") +pub fn build_db_pool_for_tests() -> ActualDbPool { + build_db_pool().expect("db pool missing") } pub fn naive_now() -> DateTime { diff --git a/crates/db_views/src/comment_report_view.rs b/crates/db_views/src/comment_report_view.rs index be5e76562..06c05639d 100644 --- a/crates/db_views/src/comment_report_view.rs +++ b/crates/db_views/src/comment_report_view.rs @@ -28,6 +28,7 @@ use lemmy_db_schema::{ person_block, post, }, + source::community::CommunityFollower, utils::{get_conn, limit_and_offset, DbConn, DbPool, ListFn, Queries, ReadFn}, }; @@ -122,7 +123,7 @@ fn queries<'a>() -> Queries< .is_not_null(), local_user::admin.nullable().is_not_null(), person_block::target_id.nullable().is_not_null(), - community_follower::pending.nullable(), + CommunityFollower::select_subscribed_type(), comment_saved::published.nullable().is_not_null(), comment_like::score.nullable(), aliases::person2.fields(person::all_columns).nullable(), @@ -290,7 +291,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_views/src/comment_view.rs b/crates/db_views/src/comment_view.rs index ff1405508..0521e401c 100644 --- a/crates/db_views/src/comment_view.rs +++ b/crates/db_views/src/comment_view.rs @@ -35,9 +35,14 @@ use lemmy_db_schema::{ person_block, post, }, - source::{local_user::LocalUser, site::Site}, + source::{ + community::{CommunityFollower, CommunityFollowerState}, + local_user::LocalUser, + site::Site, + }, utils::{fuzzy_search, limit_and_offset, DbConn, DbPool, ListFn, Queries, ReadFn}, CommentSortType, + CommunityVisibility, ListingType, }; @@ -70,7 +75,7 @@ fn queries<'a>() -> Queries< .eq(community_follower::community_id) .and(community_follower::person_id.eq(person_id)), ) - .select(community_follower::pending.nullable()) + .select(CommunityFollower::select_subscribed_type()) .single_value() }; @@ -129,11 +134,15 @@ fn queries<'a>() -> Queries< }; let subscribed_type_selection: Box< - dyn BoxableExpression<_, Pg, SqlType = sql_types::Nullable>, + dyn BoxableExpression< + _, + Pg, + SqlType = sql_types::Nullable, + >, > = if let Some(person_id) = my_person_id { Box::new(is_community_followed(person_id)) } else { - Box::new(None::.into_sql::>()) + Box::new(None::.into_sql::>()) }; let is_creator_blocked_selection: Box> = @@ -179,6 +188,26 @@ fn queries<'a>() -> Queries< my_local_user.person_id(), ); query = my_local_user.visible_communities_only(query); + + // Check permissions to view private community content. + // Specifically, if the community is private then only accepted followers may view its + // content, otherwise it is filtered out. Admins can view private community content + // without restriction. + if !my_local_user.is_admin() { + query = query.filter( + community::visibility + .ne(CommunityVisibility::Private) + .or(exists( + community_follower::table.filter( + post::community_id.eq(community_follower::community_id).and( + community_follower::person_id + .eq(my_local_user.map(|l| l.person_id).unwrap_or_default()) + .and(community_follower::state.eq(CommunityFollowerState::Accepted)), + ), + ), + )), + ); + } query.first(&mut conn).await }; @@ -301,6 +330,22 @@ fn queries<'a>() -> Queries< query = options.local_user.visible_communities_only(query); + if !options.local_user.is_admin() { + query = query.filter( + community::visibility + .ne(CommunityVisibility::Private) + .or(exists( + community_follower::table.filter( + post::community_id.eq(community_follower::community_id).and( + community_follower::person_id + .eq(person_id_join) + .and(community_follower::state.eq(CommunityFollowerState::Accepted)), + ), + ), + )), + ); + } + // A Max depth given means its a tree fetch let (limit, offset) = if let Some(max_depth) = options.max_depth { let depth_limit = if let Some(parent_path) = options.parent_path.as_ref() { @@ -445,6 +490,9 @@ mod tests { }, community::{ Community, + CommunityFollower, + CommunityFollowerForm, + CommunityFollowerState, CommunityInsertForm, CommunityModerator, CommunityModeratorForm, @@ -461,7 +509,7 @@ mod tests { post::{Post, PostInsertForm, PostUpdateForm}, site::{Site, SiteInsertForm}, }, - traits::{Bannable, Blockable, Crud, Joinable, Likeable, Saveable}, + traits::{Bannable, Blockable, Crud, Followable, Joinable, Likeable, Saveable}, utils::{build_db_pool_for_tests, RANK_DEFAULT}, CommunityVisibility, SubscribedType, @@ -631,7 +679,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -686,7 +734,7 @@ mod tests { #[tokio::test] #[serial] async fn test_liked_only() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -737,7 +785,7 @@ mod tests { #[tokio::test] #[serial] async fn test_comment_tree() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -810,7 +858,7 @@ mod tests { #[tokio::test] #[serial] async fn test_languages() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -869,7 +917,7 @@ mod tests { #[tokio::test] #[serial] async fn test_distinguished_first() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -894,7 +942,7 @@ mod tests { #[tokio::test] #[serial] async fn test_creator_is_moderator() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -925,7 +973,7 @@ mod tests { #[tokio::test] #[serial] async fn test_creator_is_admin() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -950,7 +998,7 @@ mod tests { #[tokio::test] #[serial] async fn test_saved_order() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1125,7 +1173,7 @@ mod tests { #[tokio::test] #[serial] async fn local_only_instance() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1171,7 +1219,7 @@ mod tests { #[tokio::test] #[serial] async fn comment_listing_local_user_banned_from_community() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1213,7 +1261,7 @@ mod tests { #[tokio::test] #[serial] async fn comment_listing_local_user_not_banned_from_community() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1232,7 +1280,7 @@ mod tests { #[tokio::test] #[serial] async fn comment_listings_hide_nsfw() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1257,4 +1305,96 @@ mod tests { cleanup(data, pool).await } + + #[tokio::test] + #[serial] + async fn comment_listing_private_community() -> LemmyResult<()> { + let pool = &build_db_pool_for_tests(); + let pool = &mut pool.into(); + let mut data = init_data(pool).await?; + + // Mark community as private + Community::update( + pool, + data.inserted_community.id, + &CommunityUpdateForm { + visibility: Some(CommunityVisibility::Private), + ..Default::default() + }, + ) + .await?; + + // No comments returned without auth + let read_comment_listing = CommentQuery::default().list(&data.site, pool).await?; + assert_eq!(0, read_comment_listing.len()); + let comment_view = CommentView::read(pool, data.inserted_comment_0.id, None).await; + assert!(comment_view.is_err()); + + // No comments returned for non-follower who is not admin + data.timmy_local_user_view.local_user.admin = false; + let read_comment_listing = CommentQuery { + community_id: Some(data.inserted_community.id), + local_user: Some(&data.timmy_local_user_view.local_user), + ..Default::default() + } + .list(&data.site, pool) + .await?; + assert_eq!(0, read_comment_listing.len()); + let comment_view = CommentView::read( + pool, + data.inserted_comment_0.id, + Some(&data.timmy_local_user_view.local_user), + ) + .await; + assert!(comment_view.is_err()); + + // Admin can view content without following + data.timmy_local_user_view.local_user.admin = true; + let read_comment_listing = CommentQuery { + community_id: Some(data.inserted_community.id), + local_user: Some(&data.timmy_local_user_view.local_user), + ..Default::default() + } + .list(&data.site, pool) + .await?; + assert_eq!(5, read_comment_listing.len()); + let comment_view = CommentView::read( + pool, + data.inserted_comment_0.id, + Some(&data.timmy_local_user_view.local_user), + ) + .await; + assert!(comment_view.is_ok()); + data.timmy_local_user_view.local_user.admin = false; + + // User can view after following + CommunityFollower::follow( + pool, + &CommunityFollowerForm { + state: Some(CommunityFollowerState::Accepted), + ..CommunityFollowerForm::new( + data.inserted_community.id, + data.timmy_local_user_view.person.id, + ) + }, + ) + .await?; + let read_comment_listing = CommentQuery { + community_id: Some(data.inserted_community.id), + local_user: Some(&data.timmy_local_user_view.local_user), + ..Default::default() + } + .list(&data.site, pool) + .await?; + assert_eq!(5, read_comment_listing.len()); + let comment_view = CommentView::read( + pool, + data.inserted_comment_0.id, + Some(&data.timmy_local_user_view.local_user), + ) + .await; + assert!(comment_view.is_ok()); + + cleanup(data, pool).await + } } diff --git a/crates/db_views/src/post_report_view.rs b/crates/db_views/src/post_report_view.rs index 82e4c5d5b..d6577af38 100644 --- a/crates/db_views/src/post_report_view.rs +++ b/crates/db_views/src/post_report_view.rs @@ -29,6 +29,7 @@ use lemmy_db_schema::{ post_report, post_saved, }, + source::community::CommunityFollower, utils::{ functions::coalesce, get_conn, @@ -143,7 +144,7 @@ fn queries<'a>() -> Queries< .nullable() .is_not_null(), local_user::admin.nullable().is_not_null(), - community_follower::pending.nullable(), + CommunityFollower::select_subscribed_type(), post_saved::post_id.nullable().is_not_null(), post_read::post_id.nullable().is_not_null(), post_hide::post_id.nullable().is_not_null(), @@ -312,7 +313,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_views/src/post_view.rs b/crates/db_views/src/post_view.rs index dc00b0438..78b10cc3f 100644 --- a/crates/db_views/src/post_view.rs +++ b/crates/db_views/src/post_view.rs @@ -42,7 +42,11 @@ use lemmy_db_schema::{ post_read, post_saved, }, - source::{local_user::LocalUser, site::Site}, + source::{ + community::{CommunityFollower, CommunityFollowerState}, + local_user::LocalUser, + site::Site, + }, utils::{ functions::coalesce, fuzzy_search, @@ -57,6 +61,7 @@ use lemmy_db_schema::{ ReadFn, ReverseTimestampKey, }, + CommunityVisibility, ListingType, PostSortType, }; @@ -175,7 +180,11 @@ fn queries<'a>() -> Queries< }; let subscribed_type_selection: Box< - dyn BoxableExpression<_, Pg, SqlType = sql_types::Nullable>, + dyn BoxableExpression< + _, + Pg, + SqlType = sql_types::Nullable, + >, > = if let Some(person_id) = my_person_id { Box::new( community_follower::table @@ -184,11 +193,11 @@ fn queries<'a>() -> Queries< .eq(community_follower::community_id) .and(community_follower::person_id.eq(person_id)), ) - .select(community_follower::pending.nullable()) + .select(CommunityFollower::select_subscribed_type()) .single_value(), ) } else { - Box::new(None::.into_sql::>()) + Box::new(None::.into_sql::>()) }; let score_selection: Box< @@ -291,6 +300,22 @@ fn queries<'a>() -> Queries< post::deleted .eq(false) .or(post::creator_id.eq(person_id_join)), + ) + // private communities can only by browsed by accepted followers + .filter( + community::visibility + .ne(CommunityVisibility::Private) + .or(exists( + community_follower::table.filter( + post_aggregates::community_id + .eq(community_follower::community_id) + .and( + community_follower::person_id + .eq(my_local_user.map(|l| l.person_id).unwrap_or_default()) + .and(community_follower::state.eq(CommunityFollowerState::Accepted)), + ), + ), + )), ); } @@ -443,6 +468,21 @@ fn queries<'a>() -> Queries< query = options.local_user.visible_communities_only(query); + if !options.local_user.is_admin() { + query = query.filter( + community::visibility + .ne(CommunityVisibility::Private) + .or(exists( + community_follower::table.filter( + post_aggregates::community_id + .eq(community_follower::community_id) + .and(community_follower::person_id.eq(person_id_join)) + .and(community_follower::state.eq(CommunityFollowerState::Accepted)), + ), + )), + ); + } + // Dont filter blocks or missing languages for moderator view type if let (Some(person_id), false) = ( options.local_user.person_id(), @@ -746,6 +786,7 @@ mod tests { Community, CommunityFollower, CommunityFollowerForm, + CommunityFollowerState, CommunityInsertForm, CommunityModerator, CommunityModeratorForm, @@ -937,7 +978,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listing_with_person() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let mut data = init_data(pool).await?; @@ -997,7 +1038,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listing_no_person() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1035,7 +1076,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listing_title_only() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1094,7 +1135,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listing_block_community() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1120,7 +1161,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listing_like() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let mut data = init_data(pool).await?; @@ -1178,7 +1219,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listing_liked_only() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1227,7 +1268,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listing_saved_only() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1257,7 +1298,7 @@ mod tests { #[tokio::test] #[serial] async fn creator_info() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1295,7 +1336,7 @@ mod tests { async fn post_listing_person_language() -> LemmyResult<()> { const EL_POSTO: &str = "el posto"; - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1356,7 +1397,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listings_removed() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let mut data = init_data(pool).await?; @@ -1391,7 +1432,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listings_deleted() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1430,7 +1471,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listings_hidden_community() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1452,9 +1493,8 @@ mod tests { // Follow the community let form = CommunityFollowerForm { - community_id: data.inserted_community.id, - person_id: data.local_user_view.person.id, - pending: false, + state: Some(CommunityFollowerState::Accepted), + ..CommunityFollowerForm::new(data.inserted_community.id, data.local_user_view.person.id) }; CommunityFollower::follow(pool, &form).await?; @@ -1469,7 +1509,7 @@ mod tests { async fn post_listing_instance_block() -> LemmyResult<()> { const POST_FROM_BLOCKED_INSTANCE: &str = "post on blocked instance"; - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1529,7 +1569,7 @@ mod tests { #[tokio::test] #[serial] async fn pagination_includes_each_post_once() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1639,7 +1679,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listings_hide_read() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let mut data = init_data(pool).await?; @@ -1689,7 +1729,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listings_hide_hidden() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1725,7 +1765,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listings_hide_nsfw() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1891,7 +1931,7 @@ mod tests { #[tokio::test] #[serial] async fn local_only_instance() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1939,7 +1979,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listing_local_user_banned_from_community() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -1982,7 +2022,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listing_local_user_not_banned_from_community() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -2002,7 +2042,7 @@ mod tests { #[tokio::test] #[serial] async fn speed_check() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -2058,7 +2098,7 @@ mod tests { #[tokio::test] #[serial] async fn post_listings_no_comments_only() -> LemmyResult<()> { - let pool = &build_db_pool().await?; + let pool = &build_db_pool()?; let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -2084,4 +2124,101 @@ mod tests { cleanup(data, pool).await } + + #[tokio::test] + #[serial] + async fn post_listing_private_community() -> LemmyResult<()> { + let pool = &build_db_pool()?; + let pool = &mut pool.into(); + let mut data = init_data(pool).await?; + + // Mark community as private + Community::update( + pool, + data.inserted_community.id, + &CommunityUpdateForm { + visibility: Some(CommunityVisibility::Private), + ..Default::default() + }, + ) + .await?; + + // No posts returned without auth + let read_post_listing = PostQuery { + community_id: Some(data.inserted_community.id), + ..Default::default() + } + .list(&data.site, pool) + .await?; + assert_eq!(0, read_post_listing.len()); + let post_view = PostView::read(pool, data.inserted_post.id, None, false).await; + assert!(post_view.is_err()); + + // No posts returned for non-follower who is not admin + data.local_user_view.local_user.admin = false; + let read_post_listing = PostQuery { + community_id: Some(data.inserted_community.id), + local_user: Some(&data.local_user_view.local_user), + ..Default::default() + } + .list(&data.site, pool) + .await?; + assert_eq!(0, read_post_listing.len()); + let post_view = PostView::read( + pool, + data.inserted_post.id, + Some(&data.local_user_view.local_user), + false, + ) + .await; + assert!(post_view.is_err()); + + // Admin can view content without following + data.local_user_view.local_user.admin = true; + let read_post_listing = PostQuery { + community_id: Some(data.inserted_community.id), + local_user: Some(&data.local_user_view.local_user), + ..Default::default() + } + .list(&data.site, pool) + .await?; + assert_eq!(2, read_post_listing.len()); + let post_view = PostView::read( + pool, + data.inserted_post.id, + Some(&data.local_user_view.local_user), + true, + ) + .await; + assert!(post_view.is_ok()); + data.local_user_view.local_user.admin = false; + + // User can view after following + CommunityFollower::follow( + pool, + &CommunityFollowerForm { + state: Some(CommunityFollowerState::Accepted), + ..CommunityFollowerForm::new(data.inserted_community.id, data.local_user_view.person.id) + }, + ) + .await?; + let read_post_listing = PostQuery { + community_id: Some(data.inserted_community.id), + local_user: Some(&data.local_user_view.local_user), + ..Default::default() + } + .list(&data.site, pool) + .await?; + assert_eq!(2, read_post_listing.len()); + let post_view = PostView::read( + pool, + data.inserted_post.id, + Some(&data.local_user_view.local_user), + true, + ) + .await; + assert!(post_view.is_ok()); + + cleanup(data, pool).await + } } diff --git a/crates/db_views/src/private_message_report_view.rs b/crates/db_views/src/private_message_report_view.rs index 56d0d6e7b..e59d99608 100644 --- a/crates/db_views/src/private_message_report_view.rs +++ b/crates/db_views/src/private_message_report_view.rs @@ -133,7 +133,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_views/src/private_message_view.rs b/crates/db_views/src/private_message_view.rs index 0fbc0ee16..0b9a2708a 100644 --- a/crates/db_views/src/private_message_view.rs +++ b/crates/db_views/src/private_message_view.rs @@ -251,7 +251,7 @@ mod tests { #[tokio::test] #[serial] async fn read_private_messages() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let Data { timmy, @@ -322,7 +322,7 @@ mod tests { #[tokio::test] #[serial] async fn ensure_person_block() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let Data { timmy, @@ -365,7 +365,7 @@ mod tests { #[tokio::test] #[serial] async fn ensure_instance_block() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let Data { timmy, diff --git a/crates/db_views/src/registration_application_view.rs b/crates/db_views/src/registration_application_view.rs index a0a40789b..e0a1ea953 100644 --- a/crates/db_views/src/registration_application_view.rs +++ b/crates/db_views/src/registration_application_view.rs @@ -162,7 +162,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_views/src/vote_view.rs b/crates/db_views/src/vote_view.rs index 0fd64deca..79ba7f72a 100644 --- a/crates/db_views/src/vote_view.rs +++ b/crates/db_views/src/vote_view.rs @@ -105,7 +105,7 @@ mod tests { #[tokio::test] #[serial] async fn post_and_comment_vote_views() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_views_actor/Cargo.toml b/crates/db_views_actor/Cargo.toml index d623959d5..18a79826b 100644 --- a/crates/db_views_actor/Cargo.toml +++ b/crates/db_views_actor/Cargo.toml @@ -46,5 +46,4 @@ serial_test = { workspace = true } tokio = { workspace = true } pretty_assertions = { workspace = true } url.workspace = true -lemmy_db_views.workspace = true -lemmy_utils.workspace = true +lemmy_db_views = { workspace = true, features = ["full"] } diff --git a/crates/db_views_actor/src/comment_reply_view.rs b/crates/db_views_actor/src/comment_reply_view.rs index 1b657866a..8694298e0 100644 --- a/crates/db_views_actor/src/comment_reply_view.rs +++ b/crates/db_views_actor/src/comment_reply_view.rs @@ -31,7 +31,10 @@ use lemmy_db_schema::{ person_block, post, }, - source::local_user::LocalUser, + source::{ + community::{CommunityFollower, CommunityFollowerState}, + local_user::LocalUser, + }, utils::{get_conn, limit_and_offset, DbConn, DbPool, ListFn, Queries, ReadFn}, CommentSortType, }; @@ -75,7 +78,7 @@ fn queries<'a>() -> Queries< .eq(community_follower::community_id) .and(community_follower::person_id.eq(person_id)), ) - .select(community_follower::pending.nullable()) + .select(CommunityFollower::select_subscribed_type()) .single_value() }; @@ -135,11 +138,15 @@ fn queries<'a>() -> Queries< }; let subscribed_type_selection: Box< - dyn BoxableExpression<_, Pg, SqlType = sql_types::Nullable>, + dyn BoxableExpression< + _, + Pg, + SqlType = sql_types::Nullable, + >, > = if let Some(person_id) = my_person_id { Box::new(is_community_followed(person_id)) } else { - Box::new(None::.into_sql::>()) + Box::new(None::.into_sql::>()) }; let is_saved_selection: Box> = @@ -328,7 +335,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_views_actor/src/community_follower_view.rs b/crates/db_views_actor/src/community_follower_view.rs index 92889d12d..f9413a078 100644 --- a/crates/db_views_actor/src/community_follower_view.rs +++ b/crates/db_views_actor/src/community_follower_view.rs @@ -1,17 +1,27 @@ -use crate::structs::CommunityFollowerView; +use crate::structs::{CommunityFollowerView, PendingFollow}; use chrono::Utc; use diesel::{ - dsl::{count_star, not}, + dsl::{count, count_star, exists, not}, result::Error, + select, + BoolExpressionMethods, ExpressionMethods, + JoinOnDsl, QueryDsl, }; use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::{CommunityId, DbUrl, InstanceId, PersonId}, - schema::{community, community_follower, person}, - utils::{get_conn, DbPool}, + schema::{community, community_follower, community_moderator, person}, + source::{ + community::{Community, CommunityFollower, CommunityFollowerState}, + person::Person, + }, + utils::{get_conn, limit_and_offset, DbPool}, + CommunityVisibility, + SubscribedType, }; +use lemmy_utils::error::{LemmyErrorType, LemmyResult}; impl CommunityFollowerView { /// return a list of local community ids and remote inboxes that at least one user of the given @@ -31,7 +41,7 @@ impl CommunityFollowerView { community_follower::table .inner_join(community::table) - .inner_join(person::table) + .inner_join(person::table.on(community_follower::person_id.eq(person::id))) .filter(person::instance_id.eq(instance_id)) .filter(community::local) // this should be a no-op since community_followers table only has // local-person+remote-community or remote-person+local-community @@ -50,7 +60,7 @@ impl CommunityFollowerView { let res = community_follower::table .filter(community_follower::community_id.eq(community_id)) .filter(not(person::local)) - .inner_join(person::table) + .inner_join(person::table.on(community_follower::person_id.eq(person::id))) .select(person::inbox_url) .distinct() .load::(conn) @@ -76,7 +86,7 @@ impl CommunityFollowerView { let conn = &mut get_conn(pool).await?; community_follower::table .inner_join(community::table) - .inner_join(person::table) + .inner_join(person::table.on(community_follower::person_id.eq(person::id))) .select((community::all_columns, person::all_columns)) .filter(community_follower::person_id.eq(person_id)) .filter(community::deleted.eq(false)) @@ -85,4 +95,223 @@ impl CommunityFollowerView { .load::(conn) .await } + + pub async fn list_approval_required( + pool: &mut DbPool<'_>, + person_id: PersonId, + // TODO: if this is true dont check for community mod, but only check for local community + // also need to check is_admin() + all_communities: bool, + pending_only: bool, + page: Option, + limit: Option, + ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + let (limit, offset) = limit_and_offset(page, limit)?; + let (person_alias, community_follower_alias) = diesel::alias!( + person as person_alias, + community_follower as community_follower_alias + ); + + // check if the community already has an accepted follower from the same instance + let is_new_instance = not(exists( + person_alias + .inner_join( + community_follower_alias.on( + person_alias + .field(person::id) + .eq(community_follower_alias.field(community_follower::person_id)), + ), + ) + .filter( + person::instance_id + .eq(person_alias.field(person::instance_id)) + .and( + community_follower_alias + .field(community_follower::community_id) + .eq(community_follower::community_id), + ) + .and( + community_follower_alias + .field(community_follower::state) + .eq(CommunityFollowerState::Accepted), + ), + ), + )); + + let mut query = community_follower::table + .inner_join(person::table.on(community_follower::person_id.eq(person::id))) + .inner_join(community::table) + .into_boxed(); + if all_communities { + // if param is false, only return items for communities where user is a mod + query = query.filter(exists( + community_moderator::table.filter( + community_follower::community_id + .eq(community_moderator::community_id) + .and(community_moderator::person_id.eq(person_id)), + ), + )); + } + if pending_only { + query = query.filter(community_follower::state.eq(CommunityFollowerState::ApprovalRequired)); + } + let res = query + .order_by(community_follower::published.asc()) + .limit(limit) + .offset(offset) + .select(( + person::all_columns, + community::all_columns, + is_new_instance, + CommunityFollower::select_subscribed_type(), + )) + .load::<(Person, Community, bool, SubscribedType)>(conn) + .await?; + Ok( + res + .into_iter() + .map( + |(person, community, is_new_instance, subscribed)| PendingFollow { + person, + community, + is_new_instance, + subscribed, + }, + ) + .collect(), + ) + } + + pub async fn count_approval_required( + pool: &mut DbPool<'_>, + community_id: CommunityId, + ) -> Result { + let conn = &mut get_conn(pool).await?; + community_follower::table + .inner_join(person::table.on(community_follower::person_id.eq(person::id))) + .filter(community_follower::community_id.eq(community_id)) + .filter(community_follower::state.eq(CommunityFollowerState::ApprovalRequired)) + .select(count(community_follower::community_id)) + .first::(conn) + .await + } + pub async fn check_private_community_action( + pool: &mut DbPool<'_>, + from_person_id: PersonId, + community: &Community, + ) -> LemmyResult<()> { + if community.visibility != CommunityVisibility::Private { + return Ok(()); + } + let conn = &mut get_conn(pool).await?; + select(exists( + community_follower::table + .filter(community_follower::community_id.eq(community.id)) + .filter(community_follower::person_id.eq(from_person_id)) + .filter(community_follower::state.eq(CommunityFollowerState::Accepted)), + )) + .get_result::(conn) + .await? + .then_some(()) + .ok_or(LemmyErrorType::NotFound.into()) + } + pub async fn check_has_followers_from_instance( + community_id: CommunityId, + instance_id: InstanceId, + pool: &mut DbPool<'_>, + ) -> Result<(), Error> { + let conn = &mut get_conn(pool).await?; + select(exists( + community_follower::table + .inner_join(person::table.on(community_follower::person_id.eq(person::id))) + .filter(community_follower::community_id.eq(community_id)) + .filter(person::instance_id.eq(instance_id)) + .filter(community_follower::state.eq(CommunityFollowerState::Accepted)), + )) + .get_result::(conn) + .await? + .then_some(()) + .ok_or(diesel::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use lemmy_db_schema::{ + source::{ + community::{CommunityFollower, CommunityFollowerForm, CommunityInsertForm}, + instance::Instance, + person::PersonInsertForm, + }, + traits::{Crud, Followable}, + utils::build_db_pool_for_tests, + }; + use serial_test::serial; + + #[tokio::test] + #[serial] + async fn test_has_followers_from_instance() -> LemmyResult<()> { + let pool = &build_db_pool_for_tests(); + let pool = &mut pool.into(); + + // insert local community + let local_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; + let community_form = CommunityInsertForm::new( + local_instance.id, + "test_community_3".to_string(), + "nada".to_owned(), + "pubkey".to_string(), + ); + let community = Community::create(pool, &community_form).await?; + + // insert remote user + let remote_instance = Instance::read_or_create(pool, "other_domain.tld".to_string()).await?; + let person_form = + PersonInsertForm::new("name".to_string(), "pubkey".to_string(), remote_instance.id); + let person = Person::create(pool, &person_form).await?; + + // community has no follower from remote instance, returns error + let has_followers = CommunityFollowerView::check_has_followers_from_instance( + community.id, + remote_instance.id, + pool, + ) + .await; + assert!(has_followers.is_err()); + + // insert unapproved follower + let mut follower_form = CommunityFollowerForm { + state: Some(CommunityFollowerState::ApprovalRequired), + ..CommunityFollowerForm::new(community.id, person.id) + }; + CommunityFollower::follow(pool, &follower_form).await?; + + // still returns error + let has_followers = CommunityFollowerView::check_has_followers_from_instance( + community.id, + remote_instance.id, + pool, + ) + .await; + assert!(has_followers.is_err()); + + // mark follower as accepted + follower_form.state = Some(CommunityFollowerState::Accepted); + CommunityFollower::follow(pool, &follower_form).await?; + + // now returns ok + let has_followers = CommunityFollowerView::check_has_followers_from_instance( + community.id, + remote_instance.id, + pool, + ) + .await; + assert!(has_followers.is_ok()); + + Instance::delete(pool, local_instance.id).await?; + Instance::delete(pool, remote_instance.id).await?; + Ok(()) + } } diff --git a/crates/db_views_actor/src/community_view.rs b/crates/db_views_actor/src/community_view.rs index de749fff3..999ec23f0 100644 --- a/crates/db_views_actor/src/community_view.rs +++ b/crates/db_views_actor/src/community_view.rs @@ -21,7 +21,11 @@ use lemmy_db_schema::{ community_person_ban, instance_block, }, - source::{community::CommunityFollower, local_user::LocalUser, site::Site}, + source::{ + community::{CommunityFollower, CommunityFollowerState}, + local_user::LocalUser, + site::Site, + }, utils::{ functions::lower, fuzzy_search, @@ -163,7 +167,9 @@ fn queries<'a>() -> Queries< if let Some(listing_type) = options.listing_type { query = match listing_type { - ListingType::Subscribed => query.filter(community_follower::pending.is_not_null()), /* TODO could be this: and(community_follower::person_id.eq(person_id_join)), */ + ListingType::Subscribed => { + query.filter(community_follower::state.eq(CommunityFollowerState::Accepted)) + } ListingType::Local => query.filter(community::local.eq(true)), _ => query, }; @@ -293,44 +299,52 @@ mod tests { }; use lemmy_db_schema::{ source::{ - community::{Community, CommunityInsertForm, CommunityUpdateForm}, + community::{ + Community, + CommunityFollower, + CommunityFollowerForm, + CommunityFollowerState, + CommunityInsertForm, + CommunityUpdateForm, + }, instance::Instance, local_user::{LocalUser, LocalUserInsertForm}, person::{Person, PersonInsertForm}, site::Site, }, - traits::Crud, + traits::{Crud, Followable}, utils::{build_db_pool_for_tests, DbPool}, CommunityVisibility, + SubscribedType, }; use lemmy_utils::error::LemmyResult; use serial_test::serial; use url::Url; struct Data { - inserted_instance: Instance, + instance: Instance, local_user: LocalUser, - inserted_communities: [Community; 3], + communities: [Community; 3], site: Site, } async fn init_data(pool: &mut DbPool<'_>) -> LemmyResult { - let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; + let instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; let person_name = "tegan".to_string(); - let new_person = PersonInsertForm::test_form(inserted_instance.id, &person_name); + let new_person = PersonInsertForm::test_form(instance.id, &person_name); let inserted_person = Person::create(pool, &new_person).await?; let local_user_form = LocalUserInsertForm::test_form(inserted_person.id); let local_user = LocalUser::create(pool, &local_user_form, vec![]).await?; - let inserted_communities = [ + let communities = [ Community::create( pool, &CommunityInsertForm::new( - inserted_instance.id, + instance.id, "test_community_1".to_string(), "nada1".to_owned(), "pubkey".to_string(), @@ -340,7 +354,7 @@ mod tests { Community::create( pool, &CommunityInsertForm::new( - inserted_instance.id, + instance.id, "test_community_2".to_string(), "nada2".to_owned(), "pubkey".to_string(), @@ -350,7 +364,7 @@ mod tests { Community::create( pool, &CommunityInsertForm::new( - inserted_instance.id, + instance.id, "test_community_3".to_string(), "nada3".to_owned(), "pubkey".to_string(), @@ -379,33 +393,93 @@ mod tests { }; Ok(Data { - inserted_instance, + instance, local_user, - inserted_communities, + communities, site, }) } async fn cleanup(data: Data, pool: &mut DbPool<'_>) -> LemmyResult<()> { - for Community { id, .. } in data.inserted_communities { + for Community { id, .. } in data.communities { Community::delete(pool, id).await?; } Person::delete(pool, data.local_user.person_id).await?; - Instance::delete(pool, data.inserted_instance.id).await?; + Instance::delete(pool, data.instance.id).await?; Ok(()) } + #[tokio::test] + #[serial] + async fn subscribe_state() -> LemmyResult<()> { + let pool = &build_db_pool_for_tests(); + let pool = &mut pool.into(); + let data = init_data(pool).await?; + let community = &data.communities[0]; + + let unauthenticated = CommunityView::read(pool, community.id, None, false).await?; + assert_eq!(SubscribedType::NotSubscribed, unauthenticated.subscribed); + + let authenticated = + CommunityView::read(pool, community.id, Some(&data.local_user), false).await?; + assert_eq!(SubscribedType::NotSubscribed, authenticated.subscribed); + + let form = CommunityFollowerForm { + state: Some(CommunityFollowerState::Pending), + ..CommunityFollowerForm::new(community.id, data.local_user.person_id) + }; + CommunityFollower::follow(pool, &form).await?; + + let with_pending_follow = + CommunityView::read(pool, community.id, Some(&data.local_user), false).await?; + assert_eq!(SubscribedType::Pending, with_pending_follow.subscribed); + + // mark community private and set follow as approval required + Community::update( + pool, + community.id, + &CommunityUpdateForm { + visibility: Some(CommunityVisibility::Private), + ..Default::default() + }, + ) + .await?; + let form = CommunityFollowerForm { + state: Some(CommunityFollowerState::ApprovalRequired), + ..CommunityFollowerForm::new(community.id, data.local_user.person_id) + }; + CommunityFollower::follow(pool, &form).await?; + + let with_approval_required_follow = + CommunityView::read(pool, community.id, Some(&data.local_user), false).await?; + assert_eq!( + SubscribedType::ApprovalRequired, + with_approval_required_follow.subscribed + ); + + let form = CommunityFollowerForm { + state: Some(CommunityFollowerState::Accepted), + ..CommunityFollowerForm::new(community.id, data.local_user.person_id) + }; + CommunityFollower::follow(pool, &form).await?; + let with_accepted_follow = + CommunityView::read(pool, community.id, Some(&data.local_user), false).await?; + assert_eq!(SubscribedType::Subscribed, with_accepted_follow.subscribed); + + cleanup(data, pool).await + } + #[tokio::test] #[serial] async fn local_only_community() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; Community::update( pool, - data.inserted_communities[0].id, + data.communities[0].id, &CommunityUpdateForm { visibility: Some(CommunityVisibility::LocalOnly), ..Default::default() @@ -418,10 +492,7 @@ mod tests { } .list(&data.site, pool) .await?; - assert_eq!( - data.inserted_communities.len() - 1, - unauthenticated_query.len() - ); + assert_eq!(data.communities.len() - 1, unauthenticated_query.len()); let authenticated_query = CommunityQuery { local_user: Some(&data.local_user), @@ -429,19 +500,14 @@ mod tests { } .list(&data.site, pool) .await?; - assert_eq!(data.inserted_communities.len(), authenticated_query.len()); + assert_eq!(data.communities.len(), authenticated_query.len()); let unauthenticated_community = - CommunityView::read(pool, data.inserted_communities[0].id, None, false).await; + CommunityView::read(pool, data.communities[0].id, None, false).await; assert!(unauthenticated_community.is_err()); - let authenticated_community = CommunityView::read( - pool, - data.inserted_communities[0].id, - Some(&data.local_user), - false, - ) - .await; + let authenticated_community = + CommunityView::read(pool, data.communities[0].id, Some(&data.local_user), false).await; assert!(authenticated_community.is_ok()); cleanup(data, pool).await @@ -450,7 +516,7 @@ mod tests { #[tokio::test] #[serial] async fn community_sort_name() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; diff --git a/crates/db_views_actor/src/person_mention_view.rs b/crates/db_views_actor/src/person_mention_view.rs index 2478c0183..2bc701805 100644 --- a/crates/db_views_actor/src/person_mention_view.rs +++ b/crates/db_views_actor/src/person_mention_view.rs @@ -31,7 +31,10 @@ use lemmy_db_schema::{ person_mention, post, }, - source::local_user::LocalUser, + source::{ + community::{CommunityFollower, CommunityFollowerState}, + local_user::LocalUser, + }, utils::{get_conn, limit_and_offset, DbConn, DbPool, ListFn, Queries, ReadFn}, CommentSortType, }; @@ -75,7 +78,7 @@ fn queries<'a>() -> Queries< .eq(community_follower::community_id) .and(community_follower::person_id.eq(person_id)), ) - .select(community_follower::pending.nullable()) + .select(CommunityFollower::select_subscribed_type()) .single_value() }; @@ -134,11 +137,15 @@ fn queries<'a>() -> Queries< }; let subscribed_type_selection: Box< - dyn BoxableExpression<_, Pg, SqlType = sql_types::Nullable>, + dyn BoxableExpression< + _, + Pg, + SqlType = sql_types::Nullable, + >, > = if let Some(person_id) = my_person_id { Box::new(is_community_followed(person_id)) } else { - Box::new(None::.into_sql::>()) + Box::new(None::.into_sql::>()) }; let is_saved_selection: Box> = @@ -328,7 +335,7 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; diff --git a/crates/db_views_actor/src/person_view.rs b/crates/db_views_actor/src/person_view.rs index 724a700ad..39d1ac27c 100644 --- a/crates/db_views_actor/src/person_view.rs +++ b/crates/db_views_actor/src/person_view.rs @@ -229,7 +229,7 @@ mod tests { #[tokio::test] #[serial] async fn exclude_deleted() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -261,7 +261,7 @@ mod tests { #[tokio::test] #[serial] async fn list_banned() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -285,7 +285,7 @@ mod tests { #[tokio::test] #[serial] async fn list_admins() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; @@ -315,7 +315,7 @@ mod tests { #[tokio::test] #[serial] async fn listing_type() -> LemmyResult<()> { - let pool = &build_db_pool_for_tests().await; + let pool = &build_db_pool_for_tests(); let pool = &mut pool.into(); let data = init_data(pool).await?; diff --git a/crates/db_views_actor/src/structs.rs b/crates/db_views_actor/src/structs.rs index db5cb1899..6b609a753 100644 --- a/crates/db_views_actor/src/structs.rs +++ b/crates/db_views_actor/src/structs.rs @@ -148,3 +148,14 @@ pub struct PersonView { pub counts: PersonAggregates, pub is_admin: bool, } + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[cfg_attr(feature = "full", derive(TS, Queryable))] +#[cfg_attr(feature = "full", diesel(check_for_backend(diesel::pg::Pg)))] +#[cfg_attr(feature = "full", ts(export))] +pub struct PendingFollow { + pub person: Person, + pub community: Community, + pub is_new_instance: bool, + pub subscribed: SubscribedType, +} diff --git a/crates/utils/src/error.rs b/crates/utils/src/error.rs index 75cecc41f..d52df2f72 100644 --- a/crates/utils/src/error.rs +++ b/crates/utils/src/error.rs @@ -184,6 +184,7 @@ pub enum FederationError { InboxTimeout, CantDeleteSite, ObjectIsNotPublic, + ObjectIsNotPrivate, } cfg_if! { diff --git a/diesel.toml b/diesel.toml index ce23d470e..0da2434d4 100644 --- a/diesel.toml +++ b/diesel.toml @@ -1,3 +1,5 @@ [print_schema] file = "crates/db_schema/src/schema.rs" patch_file = "crates/db_schema/src/diesel_ltree.patch" +# Required for https://github.com/adwhit/diesel-derive-enum +custom_type_derives = ["diesel::query_builder::QueryId"] diff --git a/migrations/2024-10-29-090055_private-community/down.sql b/migrations/2024-10-29-090055_private-community/down.sql new file mode 100644 index 000000000..3a5c516c2 --- /dev/null +++ b/migrations/2024-10-29-090055_private-community/down.sql @@ -0,0 +1,52 @@ +-- Remove private visibility +ALTER TYPE community_visibility RENAME TO community_visibility__; + +CREATE TYPE community_visibility AS enum ( + 'Public', + 'LocalOnly' +); + +ALTER TABLE community + ALTER COLUMN visibility DROP DEFAULT; + +ALTER TABLE community + ALTER COLUMN visibility TYPE community_visibility + USING visibility::text::community_visibility; + +ALTER TABLE community + ALTER COLUMN visibility SET DEFAULT 'Public'; + +DROP TYPE community_visibility__; + +-- Revert community follower changes +CREATE OR REPLACE FUNCTION convert_follower_state (s community_follower_state) + RETURNS bool + LANGUAGE sql + AS $$ + SELECT + CASE WHEN s = 'Pending' THEN + TRUE + ELSE + FALSE + END +$$; + +ALTER TABLE community_follower + ALTER COLUMN state TYPE bool + USING convert_follower_state (state); + +DROP FUNCTION convert_follower_state; + +ALTER TABLE community_follower + ALTER COLUMN state SET DEFAULT FALSE; + +ALTER TABLE community_follower RENAME COLUMN state TO pending; + +DROP TYPE community_follower_state; + +ALTER TABLE community_follower + DROP COLUMN approver_id; + +ALTER TABLE ONLY local_site + ALTER COLUMN federation_signed_fetch SET DEFAULT FALSE; + diff --git a/migrations/2024-10-29-090055_private-community/up.sql b/migrations/2024-10-29-090055_private-community/up.sql new file mode 100644 index 000000000..d1c0585ae --- /dev/null +++ b/migrations/2024-10-29-090055_private-community/up.sql @@ -0,0 +1,47 @@ +ALTER TYPE community_visibility + ADD value 'Private'; + +-- Change `community_follower.pending` to `state` enum +CREATE TYPE community_follower_state AS enum ( + 'Accepted', + 'Pending', + 'ApprovalRequired' +); + +ALTER TABLE community_follower + ALTER COLUMN pending DROP DEFAULT; + +CREATE OR REPLACE FUNCTION convert_follower_state (b bool) + RETURNS community_follower_state + LANGUAGE sql + AS $$ + SELECT + CASE WHEN b = TRUE THEN + 'Pending'::community_follower_state + ELSE + 'Accepted'::community_follower_state + END +$$; + +ALTER TABLE community_follower + ALTER COLUMN pending TYPE community_follower_state + USING convert_follower_state (pending); + +DROP FUNCTION convert_follower_state; + +ALTER TABLE community_follower RENAME COLUMN pending TO state; + +-- Add column for mod who approved the private community follower +-- Dont use foreign key here, otherwise joining to person table doesnt work easily +ALTER TABLE community_follower + ADD COLUMN approver_id int REFERENCES person ON UPDATE CASCADE ON DELETE CASCADE; + +-- Enable signed fetch, necessary to fetch content in private communities +ALTER TABLE ONLY local_site + ALTER COLUMN federation_signed_fetch SET DEFAULT TRUE; + +UPDATE + local_site +SET + federation_signed_fetch = TRUE; + diff --git a/scripts/test.sh b/scripts/test.sh index e08148db0..d3e95886f 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -20,9 +20,7 @@ if [ -n "$PACKAGE" ]; then cargo test -p $PACKAGE --all-features --no-fail-fast $TEST else - cargo test --workspace --no-fail-fast - # Testing lemmy utils all features in particular (for ts-rs bindings) - cargo test -p lemmy_utils --all-features --no-fail-fast + cargo test --workspace --all-features --no-fail-fast fi # Add this to do printlns: -- --nocapture diff --git a/src/api_routes_http.rs b/src/api_routes_http.rs index df1aebf84..fd65e0671 100644 --- a/src/api_routes_http.rs +++ b/src/api_routes_http.rs @@ -17,6 +17,11 @@ use lemmy_api::{ block::block_community, follow::follow_community, hide::hide_community, + pending_follows::{ + approve::post_pending_follows_approve, + count::get_pending_follows_count, + list::get_pending_follows_list, + }, random::get_random_community, transfer::transfer_community, }, @@ -204,7 +209,14 @@ pub fn config(cfg: &mut web::ServiceConfig, rate_limit: &RateLimitCell) { .route("/remove", web::post().to(remove_community)) .route("/transfer", web::post().to(transfer_community)) .route("/ban_user", web::post().to(ban_from_community)) - .route("/mod", web::post().to(add_mod_to_community)), + .route("/mod", web::post().to(add_mod_to_community)) + .service( + web::scope("/pending_follows") + .wrap(rate_limit.message()) + .route("/count", web::get().to(get_pending_follows_count)) + .route("/list", web::get().to(get_pending_follows_list)) + .route("/approve", web::post().to(post_pending_follows_approve)), + ), ) .service( web::scope("/federated_instances") diff --git a/src/lib.rs b/src/lib.rs index 4aee4be69..9da09f65b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -116,7 +116,7 @@ pub async fn start_lemmy_server(args: CmdArgs) -> LemmyResult<()> { } // Set up the connection pool - let pool = build_db_pool().await?; + let pool = build_db_pool()?; // Run the Code-required migrations run_advanced_migrations(&mut (&pool).into(), &SETTINGS).await?; diff --git a/src/prometheus_metrics.rs b/src/prometheus_metrics.rs index c4ab204e7..512d63f38 100644 --- a/src/prometheus_metrics.rs +++ b/src/prometheus_metrics.rs @@ -47,7 +47,7 @@ pub fn serve_prometheus(config: PrometheusConfig, lemmy_context: LemmyContext) - // handler for the /metrics path async fn metrics(context: web::Data>) -> LemmyResult { // collect metrics - collect_db_pool_metrics(&context).await; + collect_db_pool_metrics(&context); let mut buffer = Vec::new(); let encoder = TextEncoder::new(); @@ -84,7 +84,7 @@ fn create_db_pool_metrics() -> LemmyResult { Ok(metrics) } -async fn collect_db_pool_metrics(context: &PromContext) { +fn collect_db_pool_metrics(context: &PromContext) { let pool_status = context.lemmy.inner_pool().status(); context .db_pool_metrics diff --git a/src/scheduled_tasks.rs b/src/scheduled_tasks.rs index e7c8a676c..37f2ff809 100644 --- a/src/scheduled_tasks.rs +++ b/src/scheduled_tasks.rs @@ -496,7 +496,6 @@ async fn publish_scheduled_posts(context: &Data) { // send out post via federation and webmention let send_activity = SendActivityData::CreatePost(post.clone()); ActivityChannel::submit_activity(send_activity, context) - .await .inspect_err(|e| error!("Failed federate scheduled post: {e}")) .ok(); send_webmention(post, community); diff --git a/src/session_middleware.rs b/src/session_middleware.rs index ec8f4399c..b495bdbb9 100644 --- a/src/session_middleware.rs +++ b/src/session_middleware.rs @@ -125,7 +125,7 @@ mod tests { // hack, necessary so that config file can be loaded from hardcoded, relative path set_current_dir("crates/utils")?; - let pool_ = build_db_pool_for_tests().await; + let pool_ = build_db_pool_for_tests(); let pool = &mut (&pool_).into(); let secret = Secret::init(pool).await?; From 441b8518fa334dc21505c818d5867ca648ded889 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Thu, 7 Nov 2024 12:30:58 -0500 Subject: [PATCH 17/19] Increase speed check limit. (#5175) --- crates/db_views/src/post_view.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/db_views/src/post_view.rs b/crates/db_views/src/post_view.rs index 78b10cc3f..5ac514a4c 100644 --- a/crates/db_views/src/post_view.rs +++ b/crates/db_views/src/post_view.rs @@ -2047,7 +2047,7 @@ mod tests { let data = init_data(pool).await?; // Make sure the post_view query is less than this time - let duration_max = Duration::from_millis(40); + let duration_max = Duration::from_millis(80); // Create some dummy posts let num_posts = 1000; From 39eeb2cbb3bd45a01501647db2da87068662945b Mon Sep 17 00:00:00 2001 From: Dessalines Date: Thu, 7 Nov 2024 22:16:28 -0500 Subject: [PATCH 18/19] Allow disabling private messages. Fixes #3640 (#4094) * Allow disabling private messages. Fixes #3640 * Fix typo. * Fixing local user check in apub code. * Removing pointless local check. --- crates/api/src/local_user/save_settings.rs | 1 + crates/api_common/src/person.rs | 3 +++ crates/api_common/src/utils.rs | 10 ++++++++++ crates/api_crud/src/private_message/create.rs | 11 +++++++++++ crates/apub/src/objects/private_message.rs | 15 ++++++++++++++- crates/db_schema/src/schema.rs | 1 + crates/db_schema/src/source/local_user.rs | 5 +++++ .../db_views/src/registration_application_view.rs | 1 + .../down.sql | 3 +++ .../up.sql | 3 +++ 10 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 migrations/2023-10-24-140438_enable_private_messages/down.sql create mode 100644 migrations/2023-10-24-140438_enable_private_messages/up.sql diff --git a/crates/api/src/local_user/save_settings.rs b/crates/api/src/local_user/save_settings.rs index 08820cadd..ac2e321a1 100644 --- a/crates/api/src/local_user/save_settings.rs +++ b/crates/api/src/local_user/save_settings.rs @@ -141,6 +141,7 @@ pub async fn save_user_settings( post_listing_mode: data.post_listing_mode, enable_keyboard_navigation: data.enable_keyboard_navigation, enable_animated_images: data.enable_animated_images, + enable_private_messages: data.enable_private_messages, collapse_bot_comments: data.collapse_bot_comments, ..Default::default() }; diff --git a/crates/api_common/src/person.rs b/crates/api_common/src/person.rs index 6b64d8467..742dc88db 100644 --- a/crates/api_common/src/person.rs +++ b/crates/api_common/src/person.rs @@ -163,6 +163,9 @@ pub struct SaveUserSettings { /// should be paused #[cfg_attr(feature = "full", ts(optional))] pub enable_animated_images: Option, + /// Whether a user can send / receive private messages + #[cfg_attr(feature = "full", ts(optional))] + pub enable_private_messages: Option, /// Whether to auto-collapse bot comments. #[cfg_attr(feature = "full", ts(optional))] pub collapse_bot_comments: Option, diff --git a/crates/api_common/src/utils.rs b/crates/api_common/src/utils.rs index 6b79ce6ba..64b0df346 100644 --- a/crates/api_common/src/utils.rs +++ b/crates/api_common/src/utils.rs @@ -355,6 +355,16 @@ pub fn check_private_instance( } } +/// If private messages are disabled, dont allow them to be sent / received +#[tracing::instrument(skip_all)] +pub fn check_private_messages_enabled(local_user_view: &LocalUserView) -> Result<(), LemmyError> { + if !local_user_view.local_user.enable_private_messages { + Err(LemmyErrorType::CouldntCreatePrivateMessage)? + } else { + Ok(()) + } +} + #[tracing::instrument(skip_all)] pub async fn build_federated_instances( local_site: &LocalSite, diff --git a/crates/api_crud/src/private_message/create.rs b/crates/api_crud/src/private_message/create.rs index 5f3c7b639..1a6a78d00 100644 --- a/crates/api_crud/src/private_message/create.rs +++ b/crates/api_crud/src/private_message/create.rs @@ -5,6 +5,7 @@ use lemmy_api_common::{ private_message::{CreatePrivateMessage, PrivateMessageResponse}, send_activity::{ActivityChannel, SendActivityData}, utils::{ + check_private_messages_enabled, get_interface_language, get_url_blocklist, local_site_to_slur_regex, @@ -46,6 +47,16 @@ pub async fn create_private_message( ) .await?; + check_private_messages_enabled(&local_user_view)?; + + // Don't allow local sends to people who have private messages disabled + let recipient_local_user_opt = LocalUserView::read_person(&mut context.pool(), data.recipient_id) + .await + .ok(); + if let Some(recipient_local_user) = recipient_local_user_opt { + check_private_messages_enabled(&recipient_local_user)?; + } + let private_message_form = PrivateMessageInsertForm::new( local_user_view.person.id, data.recipient_id, diff --git a/crates/apub/src/objects/private_message.rs b/crates/apub/src/objects/private_message.rs index 3a61eb4a5..f3a9f140c 100644 --- a/crates/apub/src/objects/private_message.rs +++ b/crates/apub/src/objects/private_message.rs @@ -16,7 +16,12 @@ use activitypub_federation::{ use chrono::{DateTime, Utc}; use lemmy_api_common::{ context::LemmyContext, - utils::{get_url_blocklist, local_site_opt_to_slur_regex, process_markdown}, + utils::{ + check_private_messages_enabled, + get_url_blocklist, + local_site_opt_to_slur_regex, + process_markdown, + }, }; use lemmy_db_schema::{ source::{ @@ -28,6 +33,7 @@ use lemmy_db_schema::{ traits::Crud, utils::naive_now, }; +use lemmy_db_views::structs::LocalUserView; use lemmy_utils::{ error::{FederationError, LemmyError, LemmyErrorType, LemmyResult}, utils::markdown::markdown_to_html, @@ -130,9 +136,16 @@ impl Object for ApubPrivateMessage { let recipient = note.to[0].dereference(context).await?; PersonBlock::read(&mut context.pool(), recipient.id, creator.id).await?; + // Check that they can receive private messages + if let Ok(recipient_local_user) = + LocalUserView::read_person(&mut context.pool(), recipient.id).await + { + check_private_messages_enabled(&recipient_local_user)?; + } let local_site = LocalSite::read(&mut context.pool()).await.ok(); let slur_regex = &local_site_opt_to_slur_regex(&local_site); let url_blocklist = get_url_blocklist(context).await?; + let content = read_from_string_or_source(¬e.content, &None, ¬e.source); let content = process_markdown(&content, slur_regex, &url_blocklist, context).await?; let content = markdown_rewrite_remote_links(content, context).await; diff --git a/crates/db_schema/src/schema.rs b/crates/db_schema/src/schema.rs index a986f55d1..960abf44a 100644 --- a/crates/db_schema/src/schema.rs +++ b/crates/db_schema/src/schema.rs @@ -480,6 +480,7 @@ diesel::table! { totp_2fa_enabled -> Bool, enable_keyboard_navigation -> Bool, enable_animated_images -> Bool, + enable_private_messages -> Bool, collapse_bot_comments -> Bool, default_comment_sort_type -> CommentSortTypeEnum, } diff --git a/crates/db_schema/src/source/local_user.rs b/crates/db_schema/src/source/local_user.rs index d5bbfbe19..fd15253cc 100644 --- a/crates/db_schema/src/source/local_user.rs +++ b/crates/db_schema/src/source/local_user.rs @@ -63,6 +63,8 @@ pub struct LocalUser { /// Whether user avatars and inline images in the UI that are gifs should be allowed to play or /// should be paused pub enable_animated_images: bool, + /// Whether a user can send / receive private messages + pub enable_private_messages: bool, /// Whether to auto-collapse bot comments. pub collapse_bot_comments: bool, pub default_comment_sort_type: CommentSortType, @@ -117,6 +119,8 @@ pub struct LocalUserInsertForm { #[new(default)] pub enable_animated_images: Option, #[new(default)] + pub enable_private_messages: Option, + #[new(default)] pub collapse_bot_comments: Option, #[new(default)] pub default_comment_sort_type: Option, @@ -148,6 +152,7 @@ pub struct LocalUserUpdateForm { pub totp_2fa_enabled: Option, pub enable_keyboard_navigation: Option, pub enable_animated_images: Option, + pub enable_private_messages: Option, pub collapse_bot_comments: Option, pub default_comment_sort_type: Option, } diff --git a/crates/db_views/src/registration_application_view.rs b/crates/db_views/src/registration_application_view.rs index e0a1ea953..b5821ef26 100644 --- a/crates/db_views/src/registration_application_view.rs +++ b/crates/db_views/src/registration_application_view.rs @@ -240,6 +240,7 @@ mod tests { totp_2fa_enabled: inserted_sara_local_user.totp_2fa_enabled, enable_keyboard_navigation: inserted_sara_local_user.enable_keyboard_navigation, enable_animated_images: inserted_sara_local_user.enable_animated_images, + enable_private_messages: inserted_sara_local_user.enable_private_messages, collapse_bot_comments: inserted_sara_local_user.collapse_bot_comments, }, creator: Person { diff --git a/migrations/2023-10-24-140438_enable_private_messages/down.sql b/migrations/2023-10-24-140438_enable_private_messages/down.sql new file mode 100644 index 000000000..0b4846679 --- /dev/null +++ b/migrations/2023-10-24-140438_enable_private_messages/down.sql @@ -0,0 +1,3 @@ +ALTER TABLE local_user + DROP COLUMN enable_private_messages; + diff --git a/migrations/2023-10-24-140438_enable_private_messages/up.sql b/migrations/2023-10-24-140438_enable_private_messages/up.sql new file mode 100644 index 000000000..a0c2919de --- /dev/null +++ b/migrations/2023-10-24-140438_enable_private_messages/up.sql @@ -0,0 +1,3 @@ +ALTER TABLE local_user + ADD COLUMN enable_private_messages boolean DEFAULT TRUE NOT NULL; + From 70b0d394755654bcd98073895b972c29fe98e742 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Fri, 8 Nov 2024 07:29:48 -0500 Subject: [PATCH 19/19] Upping default max_image_size from 256 to 512. (#5177) - Context: https://github.com/LemmyNet/lemmy-ui/issues/2796 --- config/defaults.hjson | 2 +- crates/utils/src/settings/structs.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/config/defaults.hjson b/config/defaults.hjson index f0b9d56df..96dc30b79 100644 --- a/config/defaults.hjson +++ b/config/defaults.hjson @@ -76,7 +76,7 @@ # Timeout for uploading images to pictrs (in seconds) upload_timeout: 30 # Resize post thumbnails to this maximum width/height. - max_thumbnail_size: 256 + max_thumbnail_size: 512 } # Email sending configuration. All options except login/password are mandatory email: { diff --git a/crates/utils/src/settings/structs.rs b/crates/utils/src/settings/structs.rs index 8c28d908a..c95f66644 100644 --- a/crates/utils/src/settings/structs.rs +++ b/crates/utils/src/settings/structs.rs @@ -92,7 +92,7 @@ pub struct PictrsConfig { pub upload_timeout: u64, /// Resize post thumbnails to this maximum width/height. - #[default(256)] + #[default(512)] pub max_thumbnail_size: u32, }