Various pedantic clippy fixes (#2568)

* Various pedantic clippy fixes

* more clippy pedantic fixes

* try to fix ci

* add fix clippy script, use rust 1.65

* fix clippy
This commit is contained in:
Nutomic 2022-11-19 04:33:54 +00:00 committed by GitHub
parent a39cf31466
commit 6f3bf4634b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
103 changed files with 972 additions and 449 deletions

View file

@ -23,13 +23,19 @@ steps:
- /root/.cargo/bin/cargo fmt -- --check - /root/.cargo/bin/cargo fmt -- --check
# latest rust for clippy to get extra checks # latest rust for clippy to get extra checks
# when adding new clippy lints, make sure to also add them in scripts/fix-clippy.sh
- name: cargo clippy - name: cargo clippy
image: rust:1.64-buster image: rust:1.65-buster
commands: commands:
- apt-get update - apt-get update
- apt-get -y install protobuf-compiler libprotobuf-dev - apt-get -y install protobuf-compiler libprotobuf-dev
- rustup component add clippy - rustup component add clippy
- cargo clippy --workspace --tests --all-targets --all-features -- -D warnings -D deprecated -D clippy::perf -D clippy::complexity -D clippy::dbg_macro - cargo clippy --workspace --tests --all-targets --all-features --
-D warnings -D deprecated -D clippy::perf -D clippy::complexity
-D clippy::dbg_macro -D clippy::inefficient_to_string
-D clippy::items-after-statements -D clippy::implicit_clone
-D clippy::wildcard_imports -D clippy::cast_lossless
-D clippy::manual_string_new -D clippy::redundant_closure_for_method_calls
- cargo clippy --workspace --all-features -- -D clippy::unwrap_used - cargo clippy --workspace --all-features -- -D clippy::unwrap_used
- name: cargo test - name: cargo test

View file

@ -108,7 +108,7 @@ impl Perform for BanFromCommunity {
mod_person_id: local_user_view.person.id, mod_person_id: local_user_view.person.id,
other_person_id: data.person_id, other_person_id: data.person_id,
community_id: data.community_id, community_id: data.community_id,
reason: data.reason.to_owned(), reason: data.reason.clone(),
banned: Some(data.ban), banned: Some(data.ban),
expires, expires,
}; };

View file

@ -1,14 +1,72 @@
use actix_web::{web, web::Data}; use actix_web::{web, web::Data};
use captcha::Captcha; use captcha::Captcha;
use lemmy_api_common::{ use lemmy_api_common::{
comment::*, comment::{
community::*, CreateCommentLike,
person::*, CreateCommentReport,
post::*, ListCommentReports,
private_message::*, ResolveCommentReport,
site::*, SaveComment,
},
community::{
AddModToCommunity,
BanFromCommunity,
BlockCommunity,
FollowCommunity,
TransferCommunity,
},
person::{
AddAdmin,
BanPerson,
BlockPerson,
ChangePassword,
GetBannedPersons,
GetCaptcha,
GetPersonMentions,
GetReplies,
GetReportCount,
GetUnreadCount,
Login,
MarkAllAsRead,
MarkCommentReplyAsRead,
MarkPersonMentionAsRead,
PasswordChangeAfterReset,
PasswordReset,
SaveUserSettings,
VerifyEmail,
},
post::{
CreatePostLike,
CreatePostReport,
GetSiteMetadata,
ListPostReports,
LockPost,
MarkPostAsRead,
ResolvePostReport,
SavePost,
StickyPost,
},
private_message::{
CreatePrivateMessageReport,
ListPrivateMessageReports,
MarkPrivateMessageAsRead,
ResolvePrivateMessageReport,
},
site::{
ApproveRegistrationApplication,
GetModlog,
GetUnreadRegistrationApplicationCount,
LeaveAdmin,
ListRegistrationApplications,
PurgeComment,
PurgeCommunity,
PurgePerson,
PurgePost,
ResolveObject,
Search,
},
utils::local_site_to_slur_regex, utils::local_site_to_slur_regex,
websocket::*, websocket::{CommunityJoin, ModJoin, PostJoin, UserJoin},
}; };
use lemmy_db_schema::source::local_site::LocalSite; use lemmy_db_schema::source::local_site::LocalSite;
use lemmy_utils::{error::LemmyError, utils::check_slurs, ConnectionId}; use lemmy_utils::{error::LemmyError, utils::check_slurs, ConnectionId};

View file

@ -68,7 +68,7 @@ impl Perform for BanPerson {
let form = ModBanForm { let form = ModBanForm {
mod_person_id: local_user_view.person.id, mod_person_id: local_user_view.person.id,
other_person_id: data.person_id, other_person_id: data.person_id,
reason: data.reason.to_owned(), reason: data.reason.clone(),
banned: Some(data.ban), banned: Some(data.ban),
expires, expires,
}; };

View file

@ -41,7 +41,7 @@ impl Perform for ChangePassword {
} }
let local_user_id = local_user_view.local_user.id; let local_user_id = local_user_view.local_user.id;
let new_password = data.new_password.to_owned(); let new_password = data.new_password.clone();
let updated_local_user = let updated_local_user =
LocalUser::update_password(context.pool(), local_user_id, &new_password).await?; LocalUser::update_password(context.pool(), local_user_id, &new_password).await?;

View file

@ -39,7 +39,7 @@ impl Perform for GetCaptcha {
let captcha_item = CaptchaItem { let captcha_item = CaptchaItem {
answer, answer,
uuid: uuid.to_owned(), uuid: uuid.clone(),
expires: naive_now() + Duration::minutes(10), // expires in 10 minutes expires: naive_now() + Duration::minutes(10), // expires in 10 minutes
}; };

View file

@ -43,7 +43,7 @@ impl Perform for SaveUserSettings {
let display_name = diesel_option_overwrite(&data.display_name); let display_name = diesel_option_overwrite(&data.display_name);
let matrix_user_id = diesel_option_overwrite(&data.matrix_user_id); let matrix_user_id = diesel_option_overwrite(&data.matrix_user_id);
let bot_account = data.bot_account; let bot_account = data.bot_account;
let email_deref = data.email.as_deref().map(|e| e.to_lowercase()); let email_deref = data.email.as_deref().map(str::to_lowercase);
let email = diesel_option_overwrite(&email_deref); let email = diesel_option_overwrite(&email_deref);
if let Some(Some(email)) = &email { if let Some(Some(email)) = &email {
@ -116,8 +116,8 @@ impl Perform for SaveUserSettings {
.show_scores(data.show_scores) .show_scores(data.show_scores)
.default_sort_type(default_sort_type) .default_sort_type(default_sort_type)
.default_listing_type(default_listing_type) .default_listing_type(default_listing_type)
.theme(data.theme.to_owned()) .theme(data.theme.clone())
.interface_language(data.interface_language.to_owned()) .interface_language(data.interface_language.clone())
.build(); .build();
let local_user_res = LocalUser::update(context.pool(), local_user_id, &local_user_form).await; let local_user_res = LocalUser::update(context.pool(), local_user_id, &local_user_form).await;

View file

@ -43,7 +43,7 @@ impl Perform for PurgeComment {
Comment::delete(context.pool(), comment_id).await?; Comment::delete(context.pool(), comment_id).await?;
// Mod tables // Mod tables
let reason = data.reason.to_owned(); let reason = data.reason.clone();
let form = AdminPurgeCommentForm { let form = AdminPurgeCommentForm {
admin_person_id: local_user_view.person.id, admin_person_id: local_user_view.person.id,
reason, reason,

View file

@ -60,7 +60,7 @@ impl Perform for PurgeCommunity {
Community::delete(context.pool(), community_id).await?; Community::delete(context.pool(), community_id).await?;
// Mod tables // Mod tables
let reason = data.reason.to_owned(); let reason = data.reason.clone();
let form = AdminPurgeCommunityForm { let form = AdminPurgeCommunityForm {
admin_person_id: local_user_view.person.id, admin_person_id: local_user_view.person.id,
reason, reason,

View file

@ -59,7 +59,7 @@ impl Perform for PurgePerson {
Person::delete(context.pool(), person_id).await?; Person::delete(context.pool(), person_id).await?;
// Mod tables // Mod tables
let reason = data.reason.to_owned(); let reason = data.reason.clone();
let form = AdminPurgePersonForm { let form = AdminPurgePersonForm {
admin_person_id: local_user_view.person.id, admin_person_id: local_user_view.person.id,
reason, reason,

View file

@ -55,7 +55,7 @@ impl Perform for PurgePost {
Post::delete(context.pool(), post_id).await?; Post::delete(context.pool(), post_id).await?;
// Mod tables // Mod tables
let reason = data.reason.to_owned(); let reason = data.reason.clone();
let form = AdminPurgePostForm { let form = AdminPurgePostForm {
admin_person_id: local_user_view.person.id, admin_person_id: local_user_view.person.id,
reason, reason,

View file

@ -42,6 +42,7 @@ async fn convert_response(
user_id: Option<PersonId>, user_id: Option<PersonId>,
pool: &DbPool, pool: &DbPool,
) -> Result<ResolveObjectResponse, LemmyError> { ) -> Result<ResolveObjectResponse, LemmyError> {
use SearchableObjects::*;
let removed_or_deleted; let removed_or_deleted;
let mut res = ResolveObjectResponse { let mut res = ResolveObjectResponse {
comment: None, comment: None,
@ -49,7 +50,6 @@ async fn convert_response(
community: None, community: None,
person: None, person: None,
}; };
use SearchableObjects::*;
match object { match object {
Person(p) => { Person(p) => {
removed_or_deleted = p.deleted; removed_or_deleted = p.deleted;

View file

@ -45,7 +45,7 @@ impl Perform for Search {
// TODO no clean / non-nsfw searching rn // TODO no clean / non-nsfw searching rn
let q = data.q.to_owned(); let q = data.q.clone();
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let sort = data.sort; let sort = data.sort;
@ -122,7 +122,7 @@ impl Perform for Search {
// If the community or creator is included, dont search communities or users // If the community or creator is included, dont search communities or users
let community_or_creator_included = let community_or_creator_included =
data.community_id.is_some() || data.community_name.is_some() || data.creator_id.is_some(); data.community_id.is_some() || data.community_name.is_some() || data.creator_id.is_some();
let community_actor_id_2 = community_actor_id.to_owned(); let community_actor_id_2 = community_actor_id.clone();
let local_user_ = local_user.clone(); let local_user_ = local_user.clone();
posts = PostQuery::builder() posts = PostQuery::builder()
@ -140,8 +140,8 @@ impl Perform for Search {
.list() .list()
.await?; .await?;
let q = data.q.to_owned(); let q = data.q.clone();
let community_actor_id = community_actor_id.to_owned(); let community_actor_id = community_actor_id.clone();
let local_user_ = local_user.clone(); let local_user_ = local_user.clone();
comments = CommentQuery::builder() comments = CommentQuery::builder()
@ -159,7 +159,7 @@ impl Perform for Search {
.list() .list()
.await?; .await?;
let q = data.q.to_owned(); let q = data.q.clone();
communities = if community_or_creator_included { communities = if community_or_creator_included {
vec![] vec![]
@ -177,7 +177,7 @@ impl Perform for Search {
.await? .await?
}; };
let q = data.q.to_owned(); let q = data.q.clone();
users = if community_or_creator_included { users = if community_or_creator_included {
vec![] vec![]
@ -216,21 +216,21 @@ impl Perform for Search {
.iter_mut() .iter_mut()
.filter(|cv| cv.community.deleted || cv.community.removed) .filter(|cv| cv.community.deleted || cv.community.removed)
{ {
cv.community = cv.to_owned().community.blank_out_deleted_or_removed_info(); cv.community = cv.clone().community.blank_out_deleted_or_removed_info();
} }
for pv in posts for pv in posts
.iter_mut() .iter_mut()
.filter(|p| p.post.deleted || p.post.removed) .filter(|p| p.post.deleted || p.post.removed)
{ {
pv.post = pv.to_owned().post.blank_out_deleted_or_removed_info(); pv.post = pv.clone().post.blank_out_deleted_or_removed_info();
} }
for cv in comments for cv in comments
.iter_mut() .iter_mut()
.filter(|cv| cv.comment.deleted || cv.comment.removed) .filter(|cv| cv.comment.deleted || cv.comment.removed)
{ {
cv.comment = cv.to_owned().comment.blank_out_deleted_or_removed_info(); cv.comment = cv.clone().comment.blank_out_deleted_or_removed_info();
} }
} }

View file

@ -1,6 +1,18 @@
use crate::Perform; use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{utils::get_local_user_view_from_jwt, websocket::*}; use lemmy_api_common::{
utils::get_local_user_view_from_jwt,
websocket::{
CommunityJoin,
CommunityJoinResponse,
ModJoin,
ModJoinResponse,
PostJoin,
PostJoinResponse,
UserJoin,
UserJoinResponse,
},
};
use lemmy_utils::{error::LemmyError, ConnectionId}; use lemmy_utils::{error::LemmyError, ConnectionId};
use lemmy_websocket::{ use lemmy_websocket::{
messages::{JoinCommunityRoom, JoinModRoom, JoinPostRoom, JoinUserRoom}, messages::{JoinCommunityRoom, JoinModRoom, JoinPostRoom, JoinUserRoom},

View file

@ -72,12 +72,12 @@ fn html_to_site_metadata(html_bytes: &[u8]) -> Result<SiteMetadata, LemmyError>
.opengraph .opengraph
.properties .properties
.get("description") .get("description")
.map(|t| t.to_string()); .map(std::string::ToString::to_string);
let og_title = page let og_title = page
.opengraph .opengraph
.properties .properties
.get("title") .get("title")
.map(|t| t.to_string()); .map(std::string::ToString::to_string);
let og_image = page let og_image = page
.opengraph .opengraph
.images .images
@ -207,16 +207,16 @@ pub async fn fetch_site_data(
// Try to generate a small thumbnail if there's a full sized one from post-links // Try to generate a small thumbnail if there's a full sized one from post-links
Some(metadata_image) => fetch_pictrs(client, settings, metadata_image) Some(metadata_image) => fetch_pictrs(client, settings, metadata_image)
.await .await
.map(|r| r.files[0].file.to_owned()), .map(|r| r.files[0].file.clone()),
// Metadata, but no image // Metadata, but no image
None => fetch_pictrs(client, settings, url) None => fetch_pictrs(client, settings, url)
.await .await
.map(|r| r.files[0].file.to_owned()), .map(|r| r.files[0].file.clone()),
}, },
// No metadata, try to fetch the URL as an image // No metadata, try to fetch the URL as an image
None => fetch_pictrs(client, settings, url) None => fetch_pictrs(client, settings, url)
.await .await
.map(|r| r.files[0].file.to_owned()), .map(|r| r.files[0].file.clone()),
}; };
// The full urls are necessary for federation // The full urls are necessary for federation
@ -271,7 +271,7 @@ mod tests {
// These helped with testing // These helped with testing
#[actix_rt::test] #[actix_rt::test]
async fn test_site_metadata() { async fn test_site_metadata() {
let settings = &SETTINGS.to_owned(); let settings = &SETTINGS.clone();
let client = reqwest::Client::builder() let client = reqwest::Client::builder()
.user_agent(build_user_agent(settings)) .user_agent(build_user_agent(settings))
.build() .build()

View file

@ -351,7 +351,7 @@ pub async fn send_password_reset_email(
let local_user_id = user.local_user.id; let local_user_id = user.local_user.id;
PasswordResetRequest::create_token(pool, local_user_id, &token2).await?; PasswordResetRequest::create_token(pool, local_user_id, &token2).await?;
let email = &user.local_user.email.to_owned().expect("email"); let email = &user.local_user.email.clone().expect("email");
let lang = get_interface_language(user); let lang = get_interface_language(user);
let subject = &lang.password_reset_subject(&user.person.name); let subject = &lang.password_reset_subject(&user.person.name);
let protocol_and_hostname = settings.get_protocol_and_hostname(); let protocol_and_hostname = settings.get_protocol_and_hostname();
@ -391,7 +391,7 @@ pub fn send_email_verification_success(
user: &LocalUserView, user: &LocalUserView,
settings: &Settings, settings: &Settings,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let email = &user.local_user.email.to_owned().expect("email"); let email = &user.local_user.email.clone().expect("email");
let lang = get_interface_language(user); let lang = get_interface_language(user);
let subject = &lang.email_verified_subject(&user.person.actor_id); let subject = &lang.email_verified_subject(&user.person.actor_id);
let body = &lang.email_verified_body(); let body = &lang.email_verified_body();
@ -449,7 +449,7 @@ pub fn send_application_approved_email(
user: &LocalUserView, user: &LocalUserView,
settings: &Settings, settings: &Settings,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let email = &user.local_user.email.to_owned().expect("email"); let email = &user.local_user.email.clone().expect("email");
let lang = get_interface_language(user); let lang = get_interface_language(user);
let subject = lang.registration_approved_subject(&user.person.actor_id); let subject = lang.registration_approved_subject(&user.person.actor_id);
let body = lang.registration_approved_body(&settings.hostname); let body = lang.registration_approved_body(&settings.hostname);
@ -471,7 +471,7 @@ pub async fn send_new_applicant_email_to_admins(
); );
for admin in &admins { for admin in &admins {
let email = &admin.local_user.email.to_owned().expect("email"); let email = &admin.local_user.email.clone().expect("email");
let lang = get_interface_language_from_settings(admin); let lang = get_interface_language_from_settings(admin);
let subject = lang.new_application_subject(applicant_username, &settings.hostname); let subject = lang.new_application_subject(applicant_username, &settings.hostname);
let body = lang.new_application_body(applications_link); let body = lang.new_application_body(applications_link);

View file

@ -54,7 +54,7 @@ impl PerformCrud for CreateComment {
let local_site = LocalSite::read(context.pool()).await?; let local_site = LocalSite::read(context.pool()).await?;
let content_slurs_removed = remove_slurs( let content_slurs_removed = remove_slurs(
&data.content.to_owned(), &data.content.clone(),
&local_site_to_slur_regex(&local_site), &local_site_to_slur_regex(&local_site),
); );
@ -102,7 +102,7 @@ impl PerformCrud for CreateComment {
.await?; .await?;
let comment_form = CommentInsertForm::builder() let comment_form = CommentInsertForm::builder()
.content(content_slurs_removed.to_owned()) .content(content_slurs_removed.clone())
.post_id(data.post_id) .post_id(data.post_id)
.creator_id(local_user_view.person.id) .creator_id(local_user_view.person.id)
.language_id(Some(language_id)) .language_id(Some(language_id))
@ -110,7 +110,7 @@ impl PerformCrud for CreateComment {
// Create the comment // Create the comment
let comment_form2 = comment_form.clone(); let comment_form2 = comment_form.clone();
let parent_path = parent_opt.to_owned().map(|t| t.path); let parent_path = parent_opt.clone().map(|t| t.path);
let inserted_comment = Comment::create(context.pool(), &comment_form2, parent_path.as_ref()) let inserted_comment = Comment::create(context.pool(), &comment_form2, parent_path.as_ref())
.await .await
.map_err(|e| LemmyError::from_error_message(e, "couldnt_create_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_comment"))?;
@ -200,7 +200,7 @@ impl PerformCrud for CreateComment {
inserted_comment.id, inserted_comment.id,
UserOperationCrud::CreateComment, UserOperationCrud::CreateComment,
websocket_id, websocket_id,
data.form_id.to_owned(), data.form_id.clone(),
Some(local_user_view.person.id), Some(local_user_view.person.id),
recipient_ids, recipient_ids,
context, context,

View file

@ -59,7 +59,7 @@ impl PerformCrud for GetComments {
None None
}; };
let parent_path_cloned = parent_path.to_owned(); let parent_path_cloned = parent_path.clone();
let post_id = data.post_id; let post_id = data.post_id;
let local_user = local_user_view.map(|l| l.local_user); let local_user = local_user_view.map(|l| l.local_user);
let mut comments = CommentQuery::builder() let mut comments = CommentQuery::builder()
@ -85,7 +85,7 @@ impl PerformCrud for GetComments {
.iter_mut() .iter_mut()
.filter(|cv| cv.comment.deleted || cv.comment.removed) .filter(|cv| cv.comment.deleted || cv.comment.removed)
{ {
cv.comment = cv.to_owned().comment.blank_out_deleted_or_removed_info(); cv.comment = cv.clone().comment.blank_out_deleted_or_removed_info();
} }
Ok(GetCommentsResponse { comments }) Ok(GetCommentsResponse { comments })

View file

@ -69,7 +69,7 @@ impl PerformCrud for RemoveComment {
mod_person_id: local_user_view.person.id, mod_person_id: local_user_view.person.id,
comment_id: data.comment_id, comment_id: data.comment_id,
removed: Some(removed), removed: Some(removed),
reason: data.reason.to_owned(), reason: data.reason.clone(),
}; };
ModRemoveComment::create(context.pool(), &form).await?; ModRemoveComment::create(context.pool(), &form).await?;
@ -103,7 +103,7 @@ impl PerformCrud for RemoveComment {
local_user_view.person, local_user_view.person,
community, community,
deletable, deletable,
data.reason.clone().or_else(|| Some("".to_string())), data.reason.clone().or_else(|| Some(String::new())),
removed, removed,
context, context,
) )

View file

@ -102,7 +102,7 @@ impl PerformCrud for EditComment {
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
// Do the mentions / recipients // Do the mentions / recipients
let updated_comment_content = updated_comment.content.to_owned(); let updated_comment_content = updated_comment.content.clone();
let mentions = scrape_text_for_mentions(&updated_comment_content); let mentions = scrape_text_for_mentions(&updated_comment_content);
let recipient_ids = send_local_notifs( let recipient_ids = send_local_notifs(
mentions, mentions,
@ -128,7 +128,7 @@ impl PerformCrud for EditComment {
data.comment_id, data.comment_id,
UserOperationCrud::EditComment, UserOperationCrud::EditComment,
websocket_id, websocket_id,
data.form_id.to_owned(), data.form_id.clone(),
None, None,
recipient_ids, recipient_ids,
context, context,

View file

@ -85,13 +85,13 @@ impl PerformCrud for CreateCommunity {
let keypair = generate_actor_keypair()?; let keypair = generate_actor_keypair()?;
let community_form = CommunityInsertForm::builder() let community_form = CommunityInsertForm::builder()
.name(data.name.to_owned()) .name(data.name.clone())
.title(data.title.to_owned()) .title(data.title.clone())
.description(data.description.to_owned()) .description(data.description.clone())
.icon(icon) .icon(icon)
.banner(banner) .banner(banner)
.nsfw(data.nsfw) .nsfw(data.nsfw)
.actor_id(Some(community_actor_id.to_owned())) .actor_id(Some(community_actor_id.clone()))
.private_key(Some(keypair.private_key)) .private_key(Some(keypair.private_key))
.public_key(keypair.public_key) .public_key(keypair.public_key)
.followers_url(Some(generate_followers_url(&community_actor_id)?)) .followers_url(Some(generate_followers_url(&community_actor_id)?))

View file

@ -27,7 +27,7 @@ impl PerformCrud for ListCommunities {
check_private_instance(&local_user_view, &local_site)?; check_private_instance(&local_user_view, &local_site)?;
let person_id = local_user_view.to_owned().map(|l| l.person.id); let person_id = local_user_view.clone().map(|l| l.person.id);
let sort = data.sort; let sort = data.sort;
let listing_type = data.type_; let listing_type = data.type_;
@ -51,7 +51,7 @@ impl PerformCrud for ListCommunities {
.iter_mut() .iter_mut()
.filter(|cv| cv.community.deleted || cv.community.removed) .filter(|cv| cv.community.deleted || cv.community.removed)
{ {
cv.community = cv.to_owned().community.blank_out_deleted_or_removed_info(); cv.community = cv.clone().community.blank_out_deleted_or_removed_info();
} }
} }

View file

@ -49,7 +49,7 @@ impl PerformCrud for GetCommunity {
let community_id = match data.id { let community_id = match data.id {
Some(id) => id, Some(id) => id,
None => { None => {
let name = data.name.to_owned().unwrap_or_else(|| "main".to_string()); let name = data.name.clone().unwrap_or_else(|| "main".to_string());
resolve_actor_identifier::<ApubCommunity, Community>(&name, context, true) resolve_actor_identifier::<ApubCommunity, Community>(&name, context, true)
.await .await
.map_err(|e| e.with_message("couldnt_find_community"))? .map_err(|e| e.with_message("couldnt_find_community"))?

View file

@ -51,7 +51,7 @@ impl PerformCrud for RemoveCommunity {
mod_person_id: local_user_view.person.id, mod_person_id: local_user_view.person.id,
community_id: data.community_id, community_id: data.community_id,
removed: Some(removed), removed: Some(removed),
reason: data.reason.to_owned(), reason: data.reason.clone(),
expires, expires,
}; };
ModRemoveCommunity::create(context.pool(), &form).await?; ModRemoveCommunity::create(context.pool(), &form).await?;
@ -71,7 +71,7 @@ impl PerformCrud for RemoveCommunity {
local_user_view.person, local_user_view.person,
updated_community, updated_community,
deletable, deletable,
data.reason.clone().or_else(|| Some("".to_string())), data.reason.clone().or_else(|| Some(String::new())),
removed, removed,
context, context,
) )

View file

@ -64,7 +64,7 @@ impl PerformCrud for EditCommunity {
} }
let community_form = CommunityUpdateForm::builder() let community_form = CommunityUpdateForm::builder()
.title(data.title.to_owned()) .title(data.title.clone())
.description(description) .description(description)
.icon(icon) .icon(icon)
.banner(banner) .banner(banner)

View file

@ -1,5 +1,24 @@
use actix_web::{web, web::Data}; use actix_web::{web, web::Data};
use lemmy_api_common::{comment::*, community::*, person::*, post::*, private_message::*, site::*}; use lemmy_api_common::{
comment::{CreateComment, DeleteComment, EditComment, GetComment, GetComments, RemoveComment},
community::{
CreateCommunity,
DeleteCommunity,
EditCommunity,
GetCommunity,
ListCommunities,
RemoveCommunity,
},
person::{DeleteAccount, GetPersonDetails, Register},
post::{CreatePost, DeletePost, EditPost, GetPost, GetPosts, RemovePost},
private_message::{
CreatePrivateMessage,
DeletePrivateMessage,
EditPrivateMessage,
GetPrivateMessages,
},
site::{CreateSite, EditSite, GetSite},
};
use lemmy_utils::{error::LemmyError, ConnectionId}; use lemmy_utils::{error::LemmyError, ConnectionId};
use lemmy_websocket::{serialize_websocket_message, LemmyContext, UserOperationCrud}; use lemmy_websocket::{serialize_websocket_message, LemmyContext, UserOperationCrud};
use serde::Deserialize; use serde::Deserialize;

View file

@ -103,7 +103,7 @@ impl PerformCrud for CreatePost {
let post_form = PostInsertForm::builder() let post_form = PostInsertForm::builder()
.name(data.name.trim().to_owned()) .name(data.name.trim().to_owned())
.url(url) .url(url)
.body(data.body.to_owned()) .body(data.body.clone())
.community_id(data.community_id) .community_id(data.community_id)
.creator_id(local_user_view.person.id) .creator_id(local_user_view.person.id)
.nsfw(data.nsfw) .nsfw(data.nsfw)

View file

@ -74,14 +74,14 @@ impl PerformCrud for GetPosts {
.iter_mut() .iter_mut()
.filter(|p| p.post.deleted || p.post.removed) .filter(|p| p.post.deleted || p.post.removed)
{ {
pv.post = pv.to_owned().post.blank_out_deleted_or_removed_info(); pv.post = pv.clone().post.blank_out_deleted_or_removed_info();
} }
for pv in posts for pv in posts
.iter_mut() .iter_mut()
.filter(|p| p.community.deleted || p.community.removed) .filter(|p| p.community.deleted || p.community.removed)
{ {
pv.community = pv.to_owned().community.blank_out_deleted_or_removed_info(); pv.community = pv.clone().community.blank_out_deleted_or_removed_info();
} }
} }

View file

@ -63,7 +63,7 @@ impl PerformCrud for RemovePost {
mod_person_id: local_user_view.person.id, mod_person_id: local_user_view.person.id,
post_id: data.post_id, post_id: data.post_id,
removed: Some(removed), removed: Some(removed),
reason: data.reason.to_owned(), reason: data.reason.clone(),
}; };
ModRemovePost::create(context.pool(), &form).await?; ModRemovePost::create(context.pool(), &form).await?;
@ -83,7 +83,7 @@ impl PerformCrud for RemovePost {
local_user_view.person, local_user_view.person,
community, community,
deletable, deletable,
data.reason.clone().or_else(|| Some("".to_string())), data.reason.clone().or_else(|| Some(String::new())),
removed, removed,
context, context,
) )

View file

@ -95,7 +95,7 @@ impl PerformCrud for EditPost {
.await?; .await?;
let post_form = PostUpdateForm::builder() let post_form = PostUpdateForm::builder()
.name(data.name.to_owned()) .name(data.name.clone())
.url(url) .url(url)
.body(body) .body(body)
.nsfw(data.nsfw) .nsfw(data.nsfw)

View file

@ -45,14 +45,14 @@ impl PerformCrud for CreatePrivateMessage {
let local_site = LocalSite::read(context.pool()).await?; let local_site = LocalSite::read(context.pool()).await?;
let content_slurs_removed = remove_slurs( let content_slurs_removed = remove_slurs(
&data.content.to_owned(), &data.content.clone(),
&local_site_to_slur_regex(&local_site), &local_site_to_slur_regex(&local_site),
); );
check_person_block(local_user_view.person.id, data.recipient_id, context.pool()).await?; check_person_block(local_user_view.person.id, data.recipient_id, context.pool()).await?;
let private_message_form = PrivateMessageInsertForm::builder() let private_message_form = PrivateMessageInsertForm::builder()
.content(content_slurs_removed.to_owned()) .content(content_slurs_removed.clone())
.creator_id(local_user_view.person.id) .creator_id(local_user_view.person.id)
.recipient_id(data.recipient_id) .recipient_id(data.recipient_id)
.build(); .build();

View file

@ -51,7 +51,7 @@ impl PerformCrud for GetPrivateMessages {
.filter(|pmv| pmv.private_message.deleted) .filter(|pmv| pmv.private_message.deleted)
{ {
pmv.private_message = pmv pmv.private_message = pmv
.to_owned() .clone()
.private_message .private_message
.blank_out_deleted_or_removed_info(); .blank_out_deleted_or_removed_info();
} }

View file

@ -75,7 +75,7 @@ impl PerformCrud for CreateSite {
let inbox_url = Some(generate_site_inbox_url(&actor_id)?); let inbox_url = Some(generate_site_inbox_url(&actor_id)?);
let keypair = generate_actor_keypair()?; let keypair = generate_actor_keypair()?;
let site_form = SiteUpdateForm::builder() let site_form = SiteUpdateForm::builder()
.name(Some(data.name.to_owned())) .name(Some(data.name.clone()))
.sidebar(sidebar) .sidebar(sidebar)
.description(description) .description(description)
.icon(icon) .icon(icon)
@ -116,7 +116,7 @@ impl PerformCrud for CreateSite {
.federation_http_fetch_retry_limit(data.federation_http_fetch_retry_limit) .federation_http_fetch_retry_limit(data.federation_http_fetch_retry_limit)
.federation_worker_count(data.federation_worker_count) .federation_worker_count(data.federation_worker_count)
.captcha_enabled(data.captcha_enabled) .captcha_enabled(data.captcha_enabled)
.captcha_difficulty(data.captcha_difficulty.to_owned()) .captcha_difficulty(data.captcha_difficulty.clone())
.build(); .build();
LocalSite::update(context.pool(), &local_site_form).await?; LocalSite::update(context.pool(), &local_site_form).await?;

View file

@ -79,7 +79,7 @@ impl PerformCrud for EditSite {
SiteLanguage::update(context.pool(), discussion_languages.clone(), &site).await?; SiteLanguage::update(context.pool(), discussion_languages.clone(), &site).await?;
} }
let name = data.name.to_owned(); let name = data.name.clone();
let site_form = SiteUpdateForm::builder() let site_form = SiteUpdateForm::builder()
.name(name) .name(name)
.sidebar(diesel_option_overwrite(&data.sidebar)) .sidebar(diesel_option_overwrite(&data.sidebar))
@ -118,7 +118,7 @@ impl PerformCrud for EditSite {
.federation_http_fetch_retry_limit(data.federation_http_fetch_retry_limit) .federation_http_fetch_retry_limit(data.federation_http_fetch_retry_limit)
.federation_worker_count(data.federation_worker_count) .federation_worker_count(data.federation_worker_count)
.captcha_enabled(data.captcha_enabled) .captcha_enabled(data.captcha_enabled)
.captcha_difficulty(data.captcha_difficulty.to_owned()) .captcha_difficulty(data.captcha_difficulty.clone())
.build(); .build();
let update_local_site = LocalSite::update(context.pool(), &local_site_form) let update_local_site = LocalSite::update(context.pool(), &local_site_form)
@ -145,9 +145,9 @@ impl PerformCrud for EditSite {
.ok(); .ok();
// Replace the blocked and allowed instances // Replace the blocked and allowed instances
let allowed = data.allowed_instances.to_owned(); let allowed = data.allowed_instances.clone();
FederationAllowList::replace(context.pool(), allowed).await?; FederationAllowList::replace(context.pool(), allowed).await?;
let blocked = data.blocked_instances.to_owned(); let blocked = data.blocked_instances.clone();
FederationBlockList::replace(context.pool(), blocked).await?; FederationBlockList::replace(context.pool(), blocked).await?;
// TODO can't think of a better way to do this. // TODO can't think of a better way to do this.

View file

@ -77,8 +77,8 @@ impl PerformCrud for Register {
let check = context let check = context
.chat_server() .chat_server()
.send(CheckCaptcha { .send(CheckCaptcha {
uuid: data.captcha_uuid.to_owned().unwrap_or_default(), uuid: data.captcha_uuid.clone().unwrap_or_default(),
answer: data.captcha_answer.to_owned().unwrap_or_default(), answer: data.captcha_answer.clone().unwrap_or_default(),
}) })
.await?; .await?;
if !check { if !check {
@ -104,7 +104,7 @@ impl PerformCrud for Register {
// Register the new person // Register the new person
let person_form = PersonInsertForm::builder() let person_form = PersonInsertForm::builder()
.name(data.username.to_owned()) .name(data.username.clone())
.actor_id(Some(actor_id.clone())) .actor_id(Some(actor_id.clone()))
.private_key(Some(actor_keypair.private_key)) .private_key(Some(actor_keypair.private_key))
.public_key(actor_keypair.public_key) .public_key(actor_keypair.public_key)
@ -123,7 +123,7 @@ impl PerformCrud for Register {
// Create the local user // Create the local user
let local_user_form = LocalUserInsertForm::builder() let local_user_form = LocalUserInsertForm::builder()
.person_id(inserted_person.id) .person_id(inserted_person.id)
.email(data.email.as_deref().map(|s| s.to_lowercase())) .email(data.email.as_deref().map(str::to_lowercase))
.password_encrypted(data.password.to_string()) .password_encrypted(data.password.to_string())
.show_nsfw(Some(data.show_nsfw)) .show_nsfw(Some(data.show_nsfw))
.build(); .build();
@ -151,7 +151,7 @@ impl PerformCrud for Register {
let form = RegistrationApplicationInsertForm { let form = RegistrationApplicationInsertForm {
local_user_id: inserted_local_user.id, local_user_id: inserted_local_user.id,
// We already made sure answer was not null above // We already made sure answer was not null above
answer: data.answer.to_owned().expect("must have an answer"), answer: data.answer.clone().expect("must have an answer"),
}; };
RegistrationApplication::create(context.pool(), &form).await?; RegistrationApplication::create(context.pool(), &form).await?;

View file

@ -64,7 +64,7 @@ impl PerformCrud for GetPersonDetails {
let saved_only = data.saved_only; let saved_only = data.saved_only;
let community_id = data.community_id; let community_id = data.community_id;
let local_user = local_user_view.map(|l| l.local_user); let local_user = local_user_view.map(|l| l.local_user);
let local_user_clone = local_user.to_owned(); let local_user_clone = local_user.clone();
let posts_query = PostQuery::builder() let posts_query = PostQuery::builder()
.pool(context.pool()) .pool(context.pool())

View file

@ -182,7 +182,7 @@ mod tests {
file_to_json_object("assets/lemmy/collections/group_moderators.json").unwrap(); file_to_json_object("assets/lemmy/collections/group_moderators.json").unwrap();
let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap(); let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
let mut request_counter = 0; let mut request_counter = 0;
let community_context = CommunityContext(community, context.to_owned()); let community_context = CommunityContext(community, context.clone());
ApubCommunityModerators::verify(&json, &url, &community_context, &mut request_counter) ApubCommunityModerators::verify(&json, &url, &community_context, &mut request_counter)
.await .await
.unwrap(); .unwrap();

View file

@ -53,6 +53,7 @@ where
ActorT: ApubObject<DataType = LemmyContext, Error = LemmyError> + Actor + Send + 'static, ActorT: ApubObject<DataType = LemmyContext, Error = LemmyError> + Actor + Send + 'static,
for<'de2> <ActorT as ApubObject>::ApubType: serde::Deserialize<'de2>, for<'de2> <ActorT as ApubObject>::ApubType: serde::Deserialize<'de2>,
{ {
static DATA: OnceCell<Data<LemmyContext>> = OnceCell::new();
let activity_value: Value = serde_json::from_str(&payload)?; let activity_value: Value = serde_json::from_str(&payload)?;
debug!("Parsing activity {}", payload); debug!("Parsing activity {}", payload);
let activity: Activity = serde_json::from_value(activity_value.clone())?; let activity: Activity = serde_json::from_value(activity_value.clone())?;
@ -64,7 +65,6 @@ where
} }
info!("Received activity {}", payload); info!("Received activity {}", payload);
static DATA: OnceCell<Data<LemmyContext>> = OnceCell::new();
let data = DATA.get_or_init(|| Data::new(context.get_ref().clone())); let data = DATA.get_or_init(|| Data::new(context.get_ref().clone()));
receive_activity::<Activity, ActorT, LemmyContext>( receive_activity::<Activity, ActorT, LemmyContext>(
request, request,

View file

@ -62,7 +62,7 @@ async fn local_instance(context: &LemmyContext) -> &'static LocalInstance {
.build() .build()
.expect("configure federation"); .expect("configure federation");
LocalInstance::new( LocalInstance::new(
context.settings().hostname.to_owned(), context.settings().hostname.clone(),
context.client().clone(), context.client().clone(),
settings, settings,
) )
@ -187,7 +187,7 @@ pub(crate) fn check_apub_id_valid_with_strictness(
if is_strict || strict_allowlist { if is_strict || strict_allowlist {
// need to allow this explicitly because apub receive might contain objects from our local // need to allow this explicitly because apub receive might contain objects from our local
// instance. // instance.
let mut allowed_and_local = allowed.to_owned(); let mut allowed_and_local = allowed.clone();
allowed_and_local.push(local_instance); allowed_and_local.push(local_instance);
if !allowed_and_local.contains(&domain) { if !allowed_and_local.contains(&domain) {
@ -248,7 +248,7 @@ pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError>
if let Some(port) = actor_id.port() { if let Some(port) = actor_id.port() {
format!(":{}", port) format!(":{}", port)
} else { } else {
"".to_string() String::new()
}, },
); );
Ok(Url::parse(&url)?.into()) Ok(Url::parse(&url)?.into())
@ -272,7 +272,7 @@ async fn insert_activity(
sensitive: bool, sensitive: bool,
pool: &DbPool, pool: &DbPool,
) -> Result<bool, LemmyError> { ) -> Result<bool, LemmyError> {
let ap_id = ap_id.to_owned().into(); let ap_id = ap_id.clone().into();
Ok(Activity::insert(pool, ap_id, activity, local, Some(sensitive)).await?) Ok(Activity::insert(pool, ap_id, activity, local, Some(sensitive)).await?)
} }

View file

@ -135,7 +135,7 @@ impl ApubObject for ApubCommunity {
context: &LemmyContext, context: &LemmyContext,
request_counter: &mut i32, request_counter: &mut i32,
) -> Result<ApubCommunity, LemmyError> { ) -> Result<ApubCommunity, LemmyError> {
let apub_id = group.id.inner().to_owned(); let apub_id = group.id.inner().clone();
let instance = Instance::create_from_actor_id(context.pool(), &apub_id).await?; let instance = Instance::create_from_actor_id(context.pool(), &apub_id).await?;
let form = Group::into_insert_form(group.clone(), instance.id); let form = Group::into_insert_form(group.clone(), instance.id);
@ -180,16 +180,16 @@ impl Actor for ApubCommunity {
} }
fn shared_inbox(&self) -> Option<Url> { fn shared_inbox(&self) -> Option<Url> {
self.shared_inbox_url.clone().map(|s| s.into()) self.shared_inbox_url.clone().map(Into::into)
} }
} }
impl ActorType for ApubCommunity { impl ActorType for ApubCommunity {
fn actor_id(&self) -> Url { fn actor_id(&self) -> Url {
self.actor_id.to_owned().into() self.actor_id.clone().into()
} }
fn private_key(&self) -> Option<String> { fn private_key(&self) -> Option<String> {
self.private_key.to_owned() self.private_key.clone()
} }
} }

View file

@ -133,7 +133,7 @@ impl ApubObject for ApubSite {
data: &Self::DataType, data: &Self::DataType,
_request_counter: &mut i32, _request_counter: &mut i32,
) -> Result<Self, LemmyError> { ) -> Result<Self, LemmyError> {
let apub_id = apub.id.inner().to_owned(); let apub_id = apub.id.inner().clone();
let instance = DbInstance::create_from_actor_id(data.pool(), &apub_id).await?; let instance = DbInstance::create_from_actor_id(data.pool(), &apub_id).await?;
let site_form = SiteInsertForm { let site_form = SiteInsertForm {
@ -160,10 +160,10 @@ impl ApubObject for ApubSite {
impl ActorType for ApubSite { impl ActorType for ApubSite {
fn actor_id(&self) -> Url { fn actor_id(&self) -> Url {
self.actor_id.to_owned().into() self.actor_id.clone().into()
} }
fn private_key(&self) -> Option<String> { fn private_key(&self) -> Option<String> {
self.private_key.to_owned() self.private_key.clone()
} }
} }

View file

@ -85,10 +85,13 @@ pub(crate) mod tests {
// TODO: would be nice if we didnt have to use a full context for tests. // TODO: would be nice if we didnt have to use a full context for tests.
pub(crate) async fn init_context() -> LemmyContext { pub(crate) async fn init_context() -> LemmyContext {
async fn x() -> Result<String, LemmyError> {
Ok(String::new())
}
// call this to run migrations // call this to run migrations
let pool = build_db_pool_for_tests().await; let pool = build_db_pool_for_tests().await;
let settings = SETTINGS.to_owned(); let settings = SETTINGS.clone();
let client = Client::builder() let client = Client::builder()
.user_agent(build_user_agent(&settings)) .user_agent(build_user_agent(&settings))
.build() .build()
@ -97,11 +100,8 @@ pub(crate) mod tests {
let client = ClientBuilder::new(client).with(BlockedMiddleware).build(); let client = ClientBuilder::new(client).with(BlockedMiddleware).build();
let secret = Secret { let secret = Secret {
id: 0, id: 0,
jwt_secret: "".to_string(), jwt_secret: String::new(),
}; };
async fn x() -> Result<String, LemmyError> {
Ok("".to_string())
}
let rate_limit_config = RateLimitConfig::builder().build(); let rate_limit_config = RateLimitConfig::builder().build();
let rate_limit_cell = RateLimitCell::new(rate_limit_config).await; let rate_limit_cell = RateLimitCell::new(rate_limit_config).await;

View file

@ -144,7 +144,7 @@ impl ApubObject for ApubPerson {
context: &LemmyContext, context: &LemmyContext,
request_counter: &mut i32, request_counter: &mut i32,
) -> Result<ApubPerson, LemmyError> { ) -> Result<ApubPerson, LemmyError> {
let apub_id = person.id.inner().to_owned(); let apub_id = person.id.inner().clone();
let instance = Instance::create_from_actor_id(context.pool(), &apub_id).await?; let instance = Instance::create_from_actor_id(context.pool(), &apub_id).await?;
let person_form = PersonInsertForm { let person_form = PersonInsertForm {
@ -181,11 +181,11 @@ impl ApubObject for ApubPerson {
impl ActorType for ApubPerson { impl ActorType for ApubPerson {
fn actor_id(&self) -> Url { fn actor_id(&self) -> Url {
self.actor_id.to_owned().into() self.actor_id.clone().into()
} }
fn private_key(&self) -> Option<String> { fn private_key(&self) -> Option<String> {
self.private_key.to_owned() self.private_key.clone()
} }
} }
@ -199,7 +199,7 @@ impl Actor for ApubPerson {
} }
fn shared_inbox(&self) -> Option<Url> { fn shared_inbox(&self) -> Option<Url> {
self.shared_inbox_url.clone().map(|s| s.into()) self.shared_inbox_url.clone().map(Into::into)
} }
} }

View file

@ -108,7 +108,7 @@ impl ApubObject for ApubPost {
content: self.body.as_ref().map(|b| markdown_to_html(b)), content: self.body.as_ref().map(|b| markdown_to_html(b)),
media_type: Some(MediaTypeMarkdownOrHtml::Html), media_type: Some(MediaTypeMarkdownOrHtml::Html),
source: self.body.clone().map(Source::new), source: self.body.clone().map(Source::new),
url: self.url.clone().map(|u| u.into()), url: self.url.clone().map(Into::into),
attachment: self.url.clone().map(Attachment::new).into_iter().collect(), attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
image: self.thumbnail_url.clone().map(ImageObject::new), image: self.thumbnail_url.clone().map(ImageObject::new),
comments_enabled: Some(!self.locked), comments_enabled: Some(!self.locked),
@ -167,7 +167,7 @@ impl ApubObject for ApubPost {
let community = page.extract_community(context, request_counter).await?; let community = page.extract_community(context, request_counter).await?;
let form = if !page.is_mod_action(context).await? { let form = if !page.is_mod_action(context).await? {
let first_attachment = page.attachment.into_iter().map(|a| a.url()).next(); let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
let url = if first_attachment.is_some() { let url = if first_attachment.is_some() {
first_attachment first_attachment
} else if page.kind == PageType::Video { } else if page.kind == PageType::Video {

View file

@ -63,13 +63,13 @@ impl Note {
); );
match parent.deref() { match parent.deref() {
PostOrComment::Post(p) => { PostOrComment::Post(p) => {
let post = p.deref().to_owned(); let post = p.deref().clone();
Ok((post, None)) Ok((post, None))
} }
PostOrComment::Comment(c) => { PostOrComment::Comment(c) => {
let post_id = c.post_id; let post_id = c.post_id;
let post = Post::read(context.pool(), post_id).await?; let post = Post::read(context.pool(), post_id).await?;
let comment = c.deref().to_owned(); let comment = c.deref().clone();
Ok((post.into(), Some(comment))) Ok((post.into(), Some(comment)))
} }
} }

View file

@ -2,7 +2,7 @@ use crate::{
aggregates::structs::{PersonPostAggregates, PersonPostAggregatesForm}, aggregates::structs::{PersonPostAggregates, PersonPostAggregatesForm},
diesel::BoolExpressionMethods, diesel::BoolExpressionMethods,
newtypes::{PersonId, PostId}, newtypes::{PersonId, PostId},
schema::person_post_aggregates::dsl::*, schema::person_post_aggregates::dsl::{person_id, person_post_aggregates, post_id},
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{insert_into, result::Error, ExpressionMethods, QueryDsl}; use diesel::{insert_into, result::Error, ExpressionMethods, QueryDsl};

View file

@ -1,12 +1,12 @@
use crate::{ use crate::{
newtypes::DbUrl, newtypes::DbUrl,
schema::activity::dsl::*, schema::activity::dsl::{activity, ap_id},
source::activity::*, source::activity::{Activity, ActivityInsertForm, ActivityUpdateForm},
traits::Crud, traits::Crud,
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{ use diesel::{
dsl::*, dsl::insert_into,
result::{DatabaseErrorKind, Error}, result::{DatabaseErrorKind, Error},
ExpressionMethods, ExpressionMethods,
QueryDsl, QueryDsl,
@ -140,7 +140,7 @@ mod tests {
.unwrap(); .unwrap();
let activity_form = ActivityInsertForm { let activity_form = ActivityInsertForm {
ap_id: ap_id_.clone(), ap_id: ap_id_.clone(),
data: test_json.to_owned(), data: test_json.clone(),
local: Some(true), local: Some(true),
sensitive: Some(false), sensitive: Some(false),
updated: None, updated: None,

View file

@ -2,10 +2,29 @@ use crate::{
diesel::JoinOnDsl, diesel::JoinOnDsl,
newtypes::{CommunityId, InstanceId, LanguageId, LocalUserId, SiteId}, newtypes::{CommunityId, InstanceId, LanguageId, LocalUserId, SiteId},
schema::{local_site, site, site_language}, schema::{local_site, site, site_language},
source::{actor_language::*, language::Language, site::Site}, source::{
actor_language::{
CommunityLanguage,
CommunityLanguageForm,
LocalUserLanguage,
LocalUserLanguageForm,
SiteLanguage,
SiteLanguageForm,
},
language::Language,
site::Site,
},
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{delete, dsl::*, insert_into, result::Error, select, ExpressionMethods, QueryDsl}; use diesel::{
delete,
dsl::{count, exists},
insert_into,
result::Error,
select,
ExpressionMethods,
QueryDsl,
};
use diesel_async::{AsyncPgConnection, RunQueryDsl}; use diesel_async::{AsyncPgConnection, RunQueryDsl};
use lemmy_utils::error::LemmyError; use lemmy_utils::error::LemmyError;
use tokio::sync::OnceCell; use tokio::sync::OnceCell;
@ -15,7 +34,11 @@ impl LocalUserLanguage {
pool: &DbPool, pool: &DbPool,
for_local_user_id: LocalUserId, for_local_user_id: LocalUserId,
) -> Result<Vec<LanguageId>, Error> { ) -> Result<Vec<LanguageId>, Error> {
use crate::schema::local_user_language::dsl::*; use crate::schema::local_user_language::dsl::{
language_id,
local_user_id,
local_user_language,
};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
conn conn
@ -48,7 +71,7 @@ impl LocalUserLanguage {
.build_transaction() .build_transaction()
.run(|conn| { .run(|conn| {
Box::pin(async move { Box::pin(async move {
use crate::schema::local_user_language::dsl::*; use crate::schema::local_user_language::dsl::{local_user_id, local_user_language};
// Clear the current user languages // Clear the current user languages
delete(local_user_language.filter(local_user_id.eq(for_local_user_id))) delete(local_user_language.filter(local_user_id.eq(for_local_user_id)))
.execute(conn) .execute(conn)
@ -109,7 +132,7 @@ impl SiteLanguage {
.build_transaction() .build_transaction()
.run(|conn| { .run(|conn| {
Box::pin(async move { Box::pin(async move {
use crate::schema::site_language::dsl::*; use crate::schema::site_language::dsl::{site_id, site_language};
// Clear the current languages // Clear the current languages
delete(site_language.filter(site_id.eq(for_site_id))) delete(site_language.filter(site_id.eq(for_site_id)))
@ -144,7 +167,7 @@ impl CommunityLanguage {
for_language_id: Option<LanguageId>, for_language_id: Option<LanguageId>,
for_community_id: CommunityId, for_community_id: CommunityId,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
use crate::schema::community_language::dsl::*; use crate::schema::community_language::dsl::{community_id, community_language, language_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
if let Some(for_language_id) = for_language_id { if let Some(for_language_id) = for_language_id {
@ -200,7 +223,7 @@ impl CommunityLanguage {
pool: &DbPool, pool: &DbPool,
for_community_id: CommunityId, for_community_id: CommunityId,
) -> Result<Vec<LanguageId>, Error> { ) -> Result<Vec<LanguageId>, Error> {
use crate::schema::community_language::dsl::*; use crate::schema::community_language::dsl::{community_id, community_language, language_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
let langs = community_language let langs = community_language
@ -227,7 +250,7 @@ impl CommunityLanguage {
.build_transaction() .build_transaction()
.run(|conn| { .run(|conn| {
Box::pin(async move { Box::pin(async move {
use crate::schema::community_language::dsl::*; use crate::schema::community_language::dsl::{community_id, community_language};
// Clear the current languages // Clear the current languages
delete(community_language.filter(community_id.eq(for_community_id))) delete(community_language.filter(community_id.eq(for_community_id)))
.execute(conn) .execute(conn)
@ -255,8 +278,8 @@ pub async fn default_post_language(
community_id: CommunityId, community_id: CommunityId,
local_user_id: LocalUserId, local_user_id: LocalUserId,
) -> Result<Option<LanguageId>, Error> { ) -> Result<Option<LanguageId>, Error> {
let conn = &mut get_conn(pool).await?;
use crate::schema::{community_language::dsl as cl, local_user_language::dsl as ul}; use crate::schema::{community_language::dsl as cl, local_user_language::dsl as ul};
let conn = &mut get_conn(pool).await?;
let intersection = ul::local_user_language let intersection = ul::local_user_language
.inner_join(cl::community_language.on(ul::language_id.eq(cl::language_id))) .inner_join(cl::community_language.on(ul::language_id.eq(cl::language_id)))
.filter(ul::local_user_id.eq(local_user_id)) .filter(ul::local_user_id.eq(local_user_id))
@ -298,7 +321,7 @@ async fn convert_read_languages(
static ALL_LANGUAGES_COUNT: OnceCell<usize> = OnceCell::const_new(); static ALL_LANGUAGES_COUNT: OnceCell<usize> = OnceCell::const_new();
let count = ALL_LANGUAGES_COUNT let count = ALL_LANGUAGES_COUNT
.get_or_init(|| async { .get_or_init(|| async {
use crate::schema::language::dsl::*; use crate::schema::language::dsl::{id, language};
let count: i64 = language let count: i64 = language
.select(count(id)) .select(count(id))
.first(conn) .first(conn)
@ -318,7 +341,20 @@ async fn convert_read_languages(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::{ use crate::{
impls::actor_language::*, impls::actor_language::{
convert_read_languages,
convert_update_languages,
default_post_language,
get_conn,
CommunityLanguage,
DbPool,
Language,
LanguageId,
LocalUserLanguage,
QueryDsl,
RunQueryDsl,
SiteLanguage,
},
source::{ source::{
community::{Community, CommunityInsertForm}, community::{Community, CommunityInsertForm},
instance::Instance, instance::Instance,
@ -382,10 +418,10 @@ mod tests {
#[tokio::test] #[tokio::test]
#[serial] #[serial]
async fn test_convert_read_languages() { async fn test_convert_read_languages() {
use crate::schema::language::dsl::{id, language};
let pool = &build_db_pool_for_tests().await; let pool = &build_db_pool_for_tests().await;
// call with all languages, returns empty vec // call with all languages, returns empty vec
use crate::schema::language::dsl::*;
let conn = &mut get_conn(pool).await.unwrap(); let conn = &mut get_conn(pool).await.unwrap();
let all_langs = language.select(id).get_results(conn).await.unwrap(); let all_langs = language.select(id).get_results(conn).await.unwrap();
let converted1: Vec<LanguageId> = convert_read_languages(conn, all_langs).await.unwrap(); let converted1: Vec<LanguageId> = convert_read_languages(conn, all_langs).await.unwrap();

View file

@ -1,6 +1,6 @@
use crate::{ use crate::{
newtypes::{CommentId, DbUrl, PersonId}, newtypes::{CommentId, DbUrl, PersonId},
schema::comment::dsl::*, schema::comment::dsl::{ap_id, comment, content, creator_id, deleted, path, removed, updated},
source::comment::{ source::comment::{
Comment, Comment,
CommentInsertForm, CommentInsertForm,
@ -13,7 +13,12 @@ use crate::{
traits::{Crud, DeleteableOrRemoveable, Likeable, Saveable}, traits::{Crud, DeleteableOrRemoveable, Likeable, Saveable},
utils::{get_conn, naive_now, DbPool}, utils::{get_conn, naive_now, DbPool},
}; };
use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl}; use diesel::{
dsl::{insert_into, sql_query},
result::Error,
ExpressionMethods,
QueryDsl,
};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use diesel_ltree::Ltree; use diesel_ltree::Ltree;
use url::Url; use url::Url;
@ -179,7 +184,7 @@ impl Likeable for CommentLike {
type Form = CommentLikeForm; type Form = CommentLikeForm;
type IdType = CommentId; type IdType = CommentId;
async fn like(pool: &DbPool, comment_like_form: &CommentLikeForm) -> Result<Self, Error> { async fn like(pool: &DbPool, comment_like_form: &CommentLikeForm) -> Result<Self, Error> {
use crate::schema::comment_like::dsl::*; use crate::schema::comment_like::dsl::{comment_id, comment_like, person_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(comment_like) insert_into(comment_like)
.values(comment_like_form) .values(comment_like_form)
@ -194,7 +199,7 @@ impl Likeable for CommentLike {
person_id_: PersonId, person_id_: PersonId,
comment_id_: CommentId, comment_id_: CommentId,
) -> Result<usize, Error> { ) -> Result<usize, Error> {
use crate::schema::comment_like::dsl::*; use crate::schema::comment_like::dsl::{comment_id, comment_like, person_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::delete( diesel::delete(
comment_like comment_like
@ -210,7 +215,7 @@ impl Likeable for CommentLike {
impl Saveable for CommentSaved { impl Saveable for CommentSaved {
type Form = CommentSavedForm; type Form = CommentSavedForm;
async fn save(pool: &DbPool, comment_saved_form: &CommentSavedForm) -> Result<Self, Error> { async fn save(pool: &DbPool, comment_saved_form: &CommentSavedForm) -> Result<Self, Error> {
use crate::schema::comment_saved::dsl::*; use crate::schema::comment_saved::dsl::{comment_id, comment_saved, person_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(comment_saved) insert_into(comment_saved)
.values(comment_saved_form) .values(comment_saved_form)
@ -221,7 +226,7 @@ impl Saveable for CommentSaved {
.await .await
} }
async fn unsave(pool: &DbPool, comment_saved_form: &CommentSavedForm) -> Result<usize, Error> { async fn unsave(pool: &DbPool, comment_saved_form: &CommentSavedForm) -> Result<usize, Error> {
use crate::schema::comment_saved::dsl::*; use crate::schema::comment_saved::dsl::{comment_id, comment_saved, person_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::delete( diesel::delete(
comment_saved comment_saved
@ -235,7 +240,7 @@ impl Saveable for CommentSaved {
impl DeleteableOrRemoveable for Comment { impl DeleteableOrRemoveable for Comment {
fn blank_out_deleted_or_removed_info(mut self) -> Self { fn blank_out_deleted_or_removed_info(mut self) -> Self {
self.content = "".into(); self.content = String::new();
self self
} }
} }
@ -245,11 +250,19 @@ mod tests {
use crate::{ use crate::{
newtypes::LanguageId, newtypes::LanguageId,
source::{ source::{
comment::*, comment::{
Comment,
CommentInsertForm,
CommentLike,
CommentLikeForm,
CommentSaved,
CommentSavedForm,
CommentUpdateForm,
},
community::{Community, CommunityInsertForm}, community::{Community, CommunityInsertForm},
instance::Instance, instance::Instance,
person::{Person, PersonInsertForm}, person::{Person, PersonInsertForm},
post::*, post::{Post, PostInsertForm},
}, },
traits::{Crud, Likeable, Saveable}, traits::{Crud, Likeable, Saveable},
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,
@ -307,7 +320,7 @@ mod tests {
path: Ltree(format!("0.{}", inserted_comment.id)), path: Ltree(format!("0.{}", inserted_comment.id)),
published: inserted_comment.published, published: inserted_comment.published,
updated: None, updated: None,
ap_id: inserted_comment.ap_id.to_owned(), ap_id: inserted_comment.ap_id.clone(),
distinguished: false, distinguished: false,
local: true, local: true,
language_id: LanguageId::default(), language_id: LanguageId::default(),

View file

@ -1,11 +1,11 @@
use crate::{ use crate::{
newtypes::{CommentId, CommentReplyId, PersonId}, newtypes::{CommentId, CommentReplyId, PersonId},
schema::comment_reply::dsl::*, schema::comment_reply::dsl::{comment_id, comment_reply, read, recipient_id},
source::comment_reply::*, source::comment_reply::{CommentReply, CommentReplyInsertForm, CommentReplyUpdateForm},
traits::Crud, traits::Crud,
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl}; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
#[async_trait] #[async_trait]
@ -77,12 +77,12 @@ impl CommentReply {
mod tests { mod tests {
use crate::{ use crate::{
source::{ source::{
comment::*, comment::{Comment, CommentInsertForm},
comment_reply::*, comment_reply::{CommentReply, CommentReplyInsertForm, CommentReplyUpdateForm},
community::{Community, CommunityInsertForm}, community::{Community, CommunityInsertForm},
instance::Instance, instance::Instance,
person::*, person::{Person, PersonInsertForm},
post::*, post::{Post, PostInsertForm},
}, },
traits::Crud, traits::Crud,
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,

View file

@ -1,11 +1,16 @@
use crate::{ use crate::{
newtypes::{CommentReportId, PersonId}, newtypes::{CommentReportId, PersonId},
schema::comment_report::dsl::*, schema::comment_report::dsl::{comment_report, resolved, resolver_id, updated},
source::comment_report::{CommentReport, CommentReportForm}, source::comment_report::{CommentReport, CommentReportForm},
traits::Reportable, traits::Reportable,
utils::{get_conn, naive_now, DbPool}, utils::{get_conn, naive_now, DbPool},
}; };
use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl}; use diesel::{
dsl::{insert_into, update},
result::Error,
ExpressionMethods,
QueryDsl,
};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
#[async_trait] #[async_trait]

View file

@ -1,6 +1,6 @@
use crate::{ use crate::{
newtypes::{CommunityId, DbUrl, PersonId}, newtypes::{CommunityId, DbUrl, PersonId},
schema::community::dsl::*, schema::community::dsl::{actor_id, community, deleted, local, name, removed},
source::{ source::{
actor_language::{CommunityLanguage, SiteLanguage}, actor_language::{CommunityLanguage, SiteLanguage},
community::{ community::{
@ -20,11 +20,38 @@ use crate::{
utils::{functions::lower, get_conn, DbPool}, utils::{functions::lower, get_conn, DbPool},
SubscribedType, SubscribedType,
}; };
use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl, TextExpressionMethods}; use diesel::{
dsl::{exists, insert_into},
result::Error,
ExpressionMethods,
QueryDsl,
TextExpressionMethods,
};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
mod safe_type { mod safe_type {
use crate::{schema::community::*, source::community::Community, traits::ToSafe}; use crate::{
schema::community::{
actor_id,
banner,
deleted,
description,
hidden,
icon,
id,
instance_id,
local,
name,
nsfw,
posting_restricted_to_mods,
published,
removed,
title,
updated,
},
source::community::Community,
traits::ToSafe,
};
type Columns = ( type Columns = (
id, id,
@ -129,7 +156,7 @@ impl Joinable for CommunityModerator {
pool: &DbPool, pool: &DbPool,
community_moderator_form: &CommunityModeratorForm, community_moderator_form: &CommunityModeratorForm,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
use crate::schema::community_moderator::dsl::*; use crate::schema::community_moderator::dsl::community_moderator;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(community_moderator) insert_into(community_moderator)
.values(community_moderator_form) .values(community_moderator_form)
@ -141,7 +168,7 @@ impl Joinable for CommunityModerator {
pool: &DbPool, pool: &DbPool,
community_moderator_form: &CommunityModeratorForm, community_moderator_form: &CommunityModeratorForm,
) -> Result<usize, Error> { ) -> Result<usize, Error> {
use crate::schema::community_moderator::dsl::*; use crate::schema::community_moderator::dsl::{community_id, community_moderator, person_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::delete( diesel::delete(
community_moderator community_moderator
@ -155,7 +182,7 @@ impl Joinable for CommunityModerator {
impl DeleteableOrRemoveable for CommunitySafe { impl DeleteableOrRemoveable for CommunitySafe {
fn blank_out_deleted_or_removed_info(mut self) -> Self { fn blank_out_deleted_or_removed_info(mut self) -> Self {
self.title = "".into(); self.title = String::new();
self.description = None; self.description = None;
self.icon = None; self.icon = None;
self.banner = None; self.banner = None;
@ -165,7 +192,7 @@ impl DeleteableOrRemoveable for CommunitySafe {
impl DeleteableOrRemoveable for Community { impl DeleteableOrRemoveable for Community {
fn blank_out_deleted_or_removed_info(mut self) -> Self { fn blank_out_deleted_or_removed_info(mut self) -> Self {
self.title = "".into(); self.title = String::new();
self.description = None; self.description = None;
self.icon = None; self.icon = None;
self.banner = None; self.banner = None;
@ -178,7 +205,7 @@ impl CommunityModerator {
pool: &DbPool, pool: &DbPool,
for_community_id: CommunityId, for_community_id: CommunityId,
) -> Result<usize, Error> { ) -> Result<usize, Error> {
use crate::schema::community_moderator::dsl::*; use crate::schema::community_moderator::dsl::{community_id, community_moderator};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::delete(community_moderator.filter(community_id.eq(for_community_id))) diesel::delete(community_moderator.filter(community_id.eq(for_community_id)))
@ -190,7 +217,7 @@ impl CommunityModerator {
pool: &DbPool, pool: &DbPool,
for_person_id: PersonId, for_person_id: PersonId,
) -> Result<Vec<CommunityId>, Error> { ) -> Result<Vec<CommunityId>, Error> {
use crate::schema::community_moderator::dsl::*; use crate::schema::community_moderator::dsl::{community_id, community_moderator, person_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
community_moderator community_moderator
.filter(person_id.eq(for_person_id)) .filter(person_id.eq(for_person_id))
@ -207,7 +234,7 @@ impl Bannable for CommunityPersonBan {
pool: &DbPool, pool: &DbPool,
community_person_ban_form: &CommunityPersonBanForm, community_person_ban_form: &CommunityPersonBanForm,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
use crate::schema::community_person_ban::dsl::*; use crate::schema::community_person_ban::dsl::{community_id, community_person_ban, person_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(community_person_ban) insert_into(community_person_ban)
.values(community_person_ban_form) .values(community_person_ban_form)
@ -222,7 +249,7 @@ impl Bannable for CommunityPersonBan {
pool: &DbPool, pool: &DbPool,
community_person_ban_form: &CommunityPersonBanForm, community_person_ban_form: &CommunityPersonBanForm,
) -> Result<usize, Error> { ) -> Result<usize, Error> {
use crate::schema::community_person_ban::dsl::*; use crate::schema::community_person_ban::dsl::{community_id, community_person_ban, person_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::delete( diesel::delete(
community_person_ban community_person_ban
@ -257,7 +284,7 @@ impl Followable for CommunityFollower {
pool: &DbPool, pool: &DbPool,
community_follower_form: &CommunityFollowerForm, community_follower_form: &CommunityFollowerForm,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
use crate::schema::community_follower::dsl::*; use crate::schema::community_follower::dsl::{community_follower, community_id, person_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(community_follower) insert_into(community_follower)
.values(community_follower_form) .values(community_follower_form)
@ -272,7 +299,12 @@ impl Followable for CommunityFollower {
community_id_: CommunityId, community_id_: CommunityId,
person_id_: PersonId, person_id_: PersonId,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
use crate::schema::community_follower::dsl::*; use crate::schema::community_follower::dsl::{
community_follower,
community_id,
pending,
person_id,
};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update( diesel::update(
community_follower community_follower
@ -287,7 +319,7 @@ impl Followable for CommunityFollower {
pool: &DbPool, pool: &DbPool,
community_follower_form: &CommunityFollowerForm, community_follower_form: &CommunityFollowerForm,
) -> Result<usize, Error> { ) -> Result<usize, Error> {
use crate::schema::community_follower::dsl::*; use crate::schema::community_follower::dsl::{community_follower, community_id, person_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::delete( diesel::delete(
community_follower community_follower
@ -300,7 +332,7 @@ impl Followable for CommunityFollower {
// TODO: this function name only makes sense if you call it with a remote community. for a local // TODO: this function name only makes sense if you call it with a remote community. for a local
// community, it will also return true if only remote followers exist // community, it will also return true if only remote followers exist
async fn has_local_followers(pool: &DbPool, community_id_: CommunityId) -> Result<bool, Error> { async fn has_local_followers(pool: &DbPool, community_id_: CommunityId) -> Result<bool, Error> {
use crate::schema::community_follower::dsl::*; use crate::schema::community_follower::dsl::{community_follower, community_id};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::select(exists( diesel::select(exists(
community_follower.filter(community_id.eq(community_id_)), community_follower.filter(community_id.eq(community_id_)),
@ -357,7 +389,21 @@ impl ApubActor for Community {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::{ use crate::{
source::{community::*, instance::Instance, person::*}, source::{
community::{
Community,
CommunityFollower,
CommunityFollowerForm,
CommunityInsertForm,
CommunityModerator,
CommunityModeratorForm,
CommunityPersonBan,
CommunityPersonBanForm,
CommunityUpdateForm,
},
instance::Instance,
person::{Person, PersonInsertForm},
},
traits::{Bannable, Crud, Followable, Joinable}, traits::{Bannable, Crud, Followable, Joinable},
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,
}; };
@ -397,15 +443,15 @@ mod tests {
deleted: false, deleted: false,
published: inserted_community.published, published: inserted_community.published,
updated: None, updated: None,
actor_id: inserted_community.actor_id.to_owned(), actor_id: inserted_community.actor_id.clone(),
local: true, local: true,
private_key: None, private_key: None,
public_key: "pubkey".to_owned(), public_key: "pubkey".to_owned(),
last_refreshed_at: inserted_community.published, last_refreshed_at: inserted_community.published,
icon: None, icon: None,
banner: None, banner: None,
followers_url: inserted_community.followers_url.to_owned(), followers_url: inserted_community.followers_url.clone(),
inbox_url: inserted_community.inbox_url.to_owned(), inbox_url: inserted_community.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
hidden: false, hidden: false,
posting_restricted_to_mods: false, posting_restricted_to_mods: false,

View file

@ -1,10 +1,10 @@
use crate::{ use crate::{
schema::community_block::dsl::*, schema::community_block::dsl::{community_block, community_id, person_id},
source::community_block::{CommunityBlock, CommunityBlockForm}, source::community_block::{CommunityBlock, CommunityBlockForm},
traits::Blockable, traits::Blockable,
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, result::Error, *}; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
#[async_trait] #[async_trait]

View file

@ -1,10 +1,21 @@
use crate::{ use crate::{
newtypes::LocalUserId, newtypes::LocalUserId,
schema::email_verification::dsl::*, schema::email_verification::dsl::{
source::email_verification::*, email_verification,
local_user_id,
published,
verification_token,
},
source::email_verification::{EmailVerification, EmailVerificationForm},
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, insert_into, result::Error, ExpressionMethods, QueryDsl}; use diesel::{
dsl::{now, IntervalDsl},
insert_into,
result::Error,
ExpressionMethods,
QueryDsl,
};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
impl EmailVerification { impl EmailVerification {

View file

@ -6,7 +6,7 @@ use crate::{
}, },
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, result::Error}; use diesel::{dsl::insert_into, result::Error};
use diesel_async::{AsyncPgConnection, RunQueryDsl}; use diesel_async::{AsyncPgConnection, RunQueryDsl};
impl FederationAllowList { impl FederationAllowList {

View file

@ -6,7 +6,7 @@ use crate::{
}, },
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, result::Error}; use diesel::{dsl::insert_into, result::Error};
use diesel_async::{AsyncPgConnection, RunQueryDsl}; use diesel_async::{AsyncPgConnection, RunQueryDsl};
impl FederationBlockList { impl FederationBlockList {

View file

@ -4,7 +4,7 @@ use crate::{
source::instance::{Instance, InstanceForm}, source::instance::{Instance, InstanceForm},
utils::{get_conn, naive_now, DbPool}, utils::{get_conn, naive_now, DbPool},
}; };
use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl}; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl};
use diesel_async::{AsyncPgConnection, RunQueryDsl}; use diesel_async::{AsyncPgConnection, RunQueryDsl};
use lemmy_utils::utils::generate_domain_url; use lemmy_utils::utils::generate_domain_url;
use url::Url; use url::Url;

View file

@ -1,7 +1,7 @@
use crate::{ use crate::{
diesel::ExpressionMethods, diesel::ExpressionMethods,
newtypes::LanguageId, newtypes::LanguageId,
schema::language::dsl::*, schema::language::dsl::{code, id, language},
source::language::Language, source::language::Language,
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };

View file

@ -1,9 +1,9 @@
use crate::{ use crate::{
schema::local_site::dsl::*, schema::local_site::dsl::local_site,
source::local_site::*, source::local_site::{LocalSite, LocalSiteInsertForm, LocalSiteUpdateForm},
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, result::Error}; use diesel::{dsl::insert_into, result::Error};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
impl LocalSite { impl LocalSite {

View file

@ -1,9 +1,13 @@
use crate::{ use crate::{
schema::local_site_rate_limit, schema::local_site_rate_limit,
source::local_site_rate_limit::*, source::local_site_rate_limit::{
LocalSiteRateLimit,
LocalSiteRateLimitInsertForm,
LocalSiteRateLimitUpdateForm,
},
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, result::Error}; use diesel::{dsl::insert_into, result::Error};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
impl LocalSiteRateLimit { impl LocalSiteRateLimit {

View file

@ -1,6 +1,12 @@
use crate::{ use crate::{
newtypes::LocalUserId, newtypes::LocalUserId,
schema::local_user::dsl::*, schema::local_user::dsl::{
accepted_application,
email_verified,
local_user,
password_encrypted,
validator_time,
},
source::{ source::{
actor_language::{LocalUserLanguage, SiteLanguage}, actor_language::{LocalUserLanguage, SiteLanguage},
local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm}, local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm},
@ -9,12 +15,30 @@ use crate::{
utils::{get_conn, naive_now, DbPool}, utils::{get_conn, naive_now, DbPool},
}; };
use bcrypt::{hash, DEFAULT_COST}; use bcrypt::{hash, DEFAULT_COST};
use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl}; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
mod safe_settings_type { mod safe_settings_type {
use crate::{ use crate::{
schema::local_user::columns::*, schema::local_user::columns::{
accepted_application,
default_listing_type,
default_sort_type,
email,
email_verified,
id,
interface_language,
person_id,
send_notifications_to_email,
show_avatars,
show_bot_accounts,
show_new_post_notifs,
show_nsfw,
show_read_posts,
show_scores,
theme,
validator_time,
},
source::local_user::LocalUser, source::local_user::LocalUser,
traits::ToSafeSettings, traits::ToSafeSettings,
}; };

View file

@ -1,9 +1,40 @@
use crate::{ use crate::{
source::moderator::*, source::moderator::{
AdminPurgeComment,
AdminPurgeCommentForm,
AdminPurgeCommunity,
AdminPurgeCommunityForm,
AdminPurgePerson,
AdminPurgePersonForm,
AdminPurgePost,
AdminPurgePostForm,
ModAdd,
ModAddCommunity,
ModAddCommunityForm,
ModAddForm,
ModBan,
ModBanForm,
ModBanFromCommunity,
ModBanFromCommunityForm,
ModHideCommunity,
ModHideCommunityForm,
ModLockPost,
ModLockPostForm,
ModRemoveComment,
ModRemoveCommentForm,
ModRemoveCommunity,
ModRemoveCommunityForm,
ModRemovePost,
ModRemovePostForm,
ModStickyPost,
ModStickyPostForm,
ModTransferCommunity,
ModTransferCommunityForm,
},
traits::Crud, traits::Crud,
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, result::Error, QueryDsl}; use diesel::{dsl::insert_into, result::Error, QueryDsl};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
#[async_trait] #[async_trait]
@ -12,13 +43,13 @@ impl Crud for ModRemovePost {
type UpdateForm = ModRemovePostForm; type UpdateForm = ModRemovePostForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::mod_remove_post::dsl::*; use crate::schema::mod_remove_post::dsl::mod_remove_post;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
mod_remove_post.find(from_id).first::<Self>(conn).await mod_remove_post.find(from_id).first::<Self>(conn).await
} }
async fn create(pool: &DbPool, form: &ModRemovePostForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &ModRemovePostForm) -> Result<Self, Error> {
use crate::schema::mod_remove_post::dsl::*; use crate::schema::mod_remove_post::dsl::mod_remove_post;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(mod_remove_post) insert_into(mod_remove_post)
.values(form) .values(form)
@ -27,7 +58,7 @@ impl Crud for ModRemovePost {
} }
async fn update(pool: &DbPool, from_id: i32, form: &ModRemovePostForm) -> Result<Self, Error> { async fn update(pool: &DbPool, from_id: i32, form: &ModRemovePostForm) -> Result<Self, Error> {
use crate::schema::mod_remove_post::dsl::*; use crate::schema::mod_remove_post::dsl::mod_remove_post;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(mod_remove_post.find(from_id)) diesel::update(mod_remove_post.find(from_id))
.set(form) .set(form)
@ -42,13 +73,13 @@ impl Crud for ModLockPost {
type UpdateForm = ModLockPostForm; type UpdateForm = ModLockPostForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::mod_lock_post::dsl::*; use crate::schema::mod_lock_post::dsl::mod_lock_post;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
mod_lock_post.find(from_id).first::<Self>(conn).await mod_lock_post.find(from_id).first::<Self>(conn).await
} }
async fn create(pool: &DbPool, form: &ModLockPostForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &ModLockPostForm) -> Result<Self, Error> {
use crate::schema::mod_lock_post::dsl::*; use crate::schema::mod_lock_post::dsl::mod_lock_post;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(mod_lock_post) insert_into(mod_lock_post)
.values(form) .values(form)
@ -57,7 +88,7 @@ impl Crud for ModLockPost {
} }
async fn update(pool: &DbPool, from_id: i32, form: &ModLockPostForm) -> Result<Self, Error> { async fn update(pool: &DbPool, from_id: i32, form: &ModLockPostForm) -> Result<Self, Error> {
use crate::schema::mod_lock_post::dsl::*; use crate::schema::mod_lock_post::dsl::mod_lock_post;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(mod_lock_post.find(from_id)) diesel::update(mod_lock_post.find(from_id))
.set(form) .set(form)
@ -72,13 +103,13 @@ impl Crud for ModStickyPost {
type UpdateForm = ModStickyPostForm; type UpdateForm = ModStickyPostForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::mod_sticky_post::dsl::*; use crate::schema::mod_sticky_post::dsl::mod_sticky_post;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
mod_sticky_post.find(from_id).first::<Self>(conn).await mod_sticky_post.find(from_id).first::<Self>(conn).await
} }
async fn create(pool: &DbPool, form: &ModStickyPostForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &ModStickyPostForm) -> Result<Self, Error> {
use crate::schema::mod_sticky_post::dsl::*; use crate::schema::mod_sticky_post::dsl::mod_sticky_post;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(mod_sticky_post) insert_into(mod_sticky_post)
.values(form) .values(form)
@ -87,7 +118,7 @@ impl Crud for ModStickyPost {
} }
async fn update(pool: &DbPool, from_id: i32, form: &ModStickyPostForm) -> Result<Self, Error> { async fn update(pool: &DbPool, from_id: i32, form: &ModStickyPostForm) -> Result<Self, Error> {
use crate::schema::mod_sticky_post::dsl::*; use crate::schema::mod_sticky_post::dsl::mod_sticky_post;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(mod_sticky_post.find(from_id)) diesel::update(mod_sticky_post.find(from_id))
.set(form) .set(form)
@ -102,13 +133,13 @@ impl Crud for ModRemoveComment {
type UpdateForm = ModRemoveCommentForm; type UpdateForm = ModRemoveCommentForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::mod_remove_comment::dsl::*; use crate::schema::mod_remove_comment::dsl::mod_remove_comment;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
mod_remove_comment.find(from_id).first::<Self>(conn).await mod_remove_comment.find(from_id).first::<Self>(conn).await
} }
async fn create(pool: &DbPool, form: &ModRemoveCommentForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &ModRemoveCommentForm) -> Result<Self, Error> {
use crate::schema::mod_remove_comment::dsl::*; use crate::schema::mod_remove_comment::dsl::mod_remove_comment;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(mod_remove_comment) insert_into(mod_remove_comment)
.values(form) .values(form)
@ -117,7 +148,7 @@ impl Crud for ModRemoveComment {
} }
async fn update(pool: &DbPool, from_id: i32, form: &ModRemoveCommentForm) -> Result<Self, Error> { async fn update(pool: &DbPool, from_id: i32, form: &ModRemoveCommentForm) -> Result<Self, Error> {
use crate::schema::mod_remove_comment::dsl::*; use crate::schema::mod_remove_comment::dsl::mod_remove_comment;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(mod_remove_comment.find(from_id)) diesel::update(mod_remove_comment.find(from_id))
.set(form) .set(form)
@ -132,13 +163,13 @@ impl Crud for ModRemoveCommunity {
type UpdateForm = ModRemoveCommunityForm; type UpdateForm = ModRemoveCommunityForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::mod_remove_community::dsl::*; use crate::schema::mod_remove_community::dsl::mod_remove_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
mod_remove_community.find(from_id).first::<Self>(conn).await mod_remove_community.find(from_id).first::<Self>(conn).await
} }
async fn create(pool: &DbPool, form: &ModRemoveCommunityForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &ModRemoveCommunityForm) -> Result<Self, Error> {
use crate::schema::mod_remove_community::dsl::*; use crate::schema::mod_remove_community::dsl::mod_remove_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(mod_remove_community) insert_into(mod_remove_community)
.values(form) .values(form)
@ -151,7 +182,7 @@ impl Crud for ModRemoveCommunity {
from_id: i32, from_id: i32,
form: &ModRemoveCommunityForm, form: &ModRemoveCommunityForm,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
use crate::schema::mod_remove_community::dsl::*; use crate::schema::mod_remove_community::dsl::mod_remove_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(mod_remove_community.find(from_id)) diesel::update(mod_remove_community.find(from_id))
.set(form) .set(form)
@ -166,7 +197,7 @@ impl Crud for ModBanFromCommunity {
type UpdateForm = ModBanFromCommunityForm; type UpdateForm = ModBanFromCommunityForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::mod_ban_from_community::dsl::*; use crate::schema::mod_ban_from_community::dsl::mod_ban_from_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
mod_ban_from_community mod_ban_from_community
.find(from_id) .find(from_id)
@ -175,7 +206,7 @@ impl Crud for ModBanFromCommunity {
} }
async fn create(pool: &DbPool, form: &ModBanFromCommunityForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &ModBanFromCommunityForm) -> Result<Self, Error> {
use crate::schema::mod_ban_from_community::dsl::*; use crate::schema::mod_ban_from_community::dsl::mod_ban_from_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(mod_ban_from_community) insert_into(mod_ban_from_community)
.values(form) .values(form)
@ -188,7 +219,7 @@ impl Crud for ModBanFromCommunity {
from_id: i32, from_id: i32,
form: &ModBanFromCommunityForm, form: &ModBanFromCommunityForm,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
use crate::schema::mod_ban_from_community::dsl::*; use crate::schema::mod_ban_from_community::dsl::mod_ban_from_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(mod_ban_from_community.find(from_id)) diesel::update(mod_ban_from_community.find(from_id))
.set(form) .set(form)
@ -203,13 +234,13 @@ impl Crud for ModBan {
type UpdateForm = ModBanForm; type UpdateForm = ModBanForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::mod_ban::dsl::*; use crate::schema::mod_ban::dsl::mod_ban;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
mod_ban.find(from_id).first::<Self>(conn).await mod_ban.find(from_id).first::<Self>(conn).await
} }
async fn create(pool: &DbPool, form: &ModBanForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &ModBanForm) -> Result<Self, Error> {
use crate::schema::mod_ban::dsl::*; use crate::schema::mod_ban::dsl::mod_ban;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(mod_ban) insert_into(mod_ban)
.values(form) .values(form)
@ -218,7 +249,7 @@ impl Crud for ModBan {
} }
async fn update(pool: &DbPool, from_id: i32, form: &ModBanForm) -> Result<Self, Error> { async fn update(pool: &DbPool, from_id: i32, form: &ModBanForm) -> Result<Self, Error> {
use crate::schema::mod_ban::dsl::*; use crate::schema::mod_ban::dsl::mod_ban;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(mod_ban.find(from_id)) diesel::update(mod_ban.find(from_id))
.set(form) .set(form)
@ -234,13 +265,13 @@ impl Crud for ModHideCommunity {
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::mod_hide_community::dsl::*; use crate::schema::mod_hide_community::dsl::mod_hide_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
mod_hide_community.find(from_id).first::<Self>(conn).await mod_hide_community.find(from_id).first::<Self>(conn).await
} }
async fn create(pool: &DbPool, form: &ModHideCommunityForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &ModHideCommunityForm) -> Result<Self, Error> {
use crate::schema::mod_hide_community::dsl::*; use crate::schema::mod_hide_community::dsl::mod_hide_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(mod_hide_community) insert_into(mod_hide_community)
.values(form) .values(form)
@ -249,7 +280,7 @@ impl Crud for ModHideCommunity {
} }
async fn update(pool: &DbPool, from_id: i32, form: &ModHideCommunityForm) -> Result<Self, Error> { async fn update(pool: &DbPool, from_id: i32, form: &ModHideCommunityForm) -> Result<Self, Error> {
use crate::schema::mod_hide_community::dsl::*; use crate::schema::mod_hide_community::dsl::mod_hide_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(mod_hide_community.find(from_id)) diesel::update(mod_hide_community.find(from_id))
.set(form) .set(form)
@ -264,13 +295,13 @@ impl Crud for ModAddCommunity {
type UpdateForm = ModAddCommunityForm; type UpdateForm = ModAddCommunityForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::mod_add_community::dsl::*; use crate::schema::mod_add_community::dsl::mod_add_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
mod_add_community.find(from_id).first::<Self>(conn).await mod_add_community.find(from_id).first::<Self>(conn).await
} }
async fn create(pool: &DbPool, form: &ModAddCommunityForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &ModAddCommunityForm) -> Result<Self, Error> {
use crate::schema::mod_add_community::dsl::*; use crate::schema::mod_add_community::dsl::mod_add_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(mod_add_community) insert_into(mod_add_community)
.values(form) .values(form)
@ -279,7 +310,7 @@ impl Crud for ModAddCommunity {
} }
async fn update(pool: &DbPool, from_id: i32, form: &ModAddCommunityForm) -> Result<Self, Error> { async fn update(pool: &DbPool, from_id: i32, form: &ModAddCommunityForm) -> Result<Self, Error> {
use crate::schema::mod_add_community::dsl::*; use crate::schema::mod_add_community::dsl::mod_add_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(mod_add_community.find(from_id)) diesel::update(mod_add_community.find(from_id))
.set(form) .set(form)
@ -294,7 +325,7 @@ impl Crud for ModTransferCommunity {
type UpdateForm = ModTransferCommunityForm; type UpdateForm = ModTransferCommunityForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::mod_transfer_community::dsl::*; use crate::schema::mod_transfer_community::dsl::mod_transfer_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
mod_transfer_community mod_transfer_community
.find(from_id) .find(from_id)
@ -303,7 +334,7 @@ impl Crud for ModTransferCommunity {
} }
async fn create(pool: &DbPool, form: &ModTransferCommunityForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &ModTransferCommunityForm) -> Result<Self, Error> {
use crate::schema::mod_transfer_community::dsl::*; use crate::schema::mod_transfer_community::dsl::mod_transfer_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(mod_transfer_community) insert_into(mod_transfer_community)
.values(form) .values(form)
@ -316,7 +347,7 @@ impl Crud for ModTransferCommunity {
from_id: i32, from_id: i32,
form: &ModTransferCommunityForm, form: &ModTransferCommunityForm,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
use crate::schema::mod_transfer_community::dsl::*; use crate::schema::mod_transfer_community::dsl::mod_transfer_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(mod_transfer_community.find(from_id)) diesel::update(mod_transfer_community.find(from_id))
.set(form) .set(form)
@ -331,13 +362,13 @@ impl Crud for ModAdd {
type UpdateForm = ModAddForm; type UpdateForm = ModAddForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::mod_add::dsl::*; use crate::schema::mod_add::dsl::mod_add;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
mod_add.find(from_id).first::<Self>(conn).await mod_add.find(from_id).first::<Self>(conn).await
} }
async fn create(pool: &DbPool, form: &ModAddForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &ModAddForm) -> Result<Self, Error> {
use crate::schema::mod_add::dsl::*; use crate::schema::mod_add::dsl::mod_add;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(mod_add) insert_into(mod_add)
.values(form) .values(form)
@ -346,7 +377,7 @@ impl Crud for ModAdd {
} }
async fn update(pool: &DbPool, from_id: i32, form: &ModAddForm) -> Result<Self, Error> { async fn update(pool: &DbPool, from_id: i32, form: &ModAddForm) -> Result<Self, Error> {
use crate::schema::mod_add::dsl::*; use crate::schema::mod_add::dsl::mod_add;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(mod_add.find(from_id)) diesel::update(mod_add.find(from_id))
.set(form) .set(form)
@ -361,13 +392,13 @@ impl Crud for AdminPurgePerson {
type UpdateForm = AdminPurgePersonForm; type UpdateForm = AdminPurgePersonForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::admin_purge_person::dsl::*; use crate::schema::admin_purge_person::dsl::admin_purge_person;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
admin_purge_person.find(from_id).first::<Self>(conn).await admin_purge_person.find(from_id).first::<Self>(conn).await
} }
async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result<Self, Error> {
use crate::schema::admin_purge_person::dsl::*; use crate::schema::admin_purge_person::dsl::admin_purge_person;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(admin_purge_person) insert_into(admin_purge_person)
.values(form) .values(form)
@ -376,7 +407,7 @@ impl Crud for AdminPurgePerson {
} }
async fn update(pool: &DbPool, from_id: i32, form: &Self::InsertForm) -> Result<Self, Error> { async fn update(pool: &DbPool, from_id: i32, form: &Self::InsertForm) -> Result<Self, Error> {
use crate::schema::admin_purge_person::dsl::*; use crate::schema::admin_purge_person::dsl::admin_purge_person;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(admin_purge_person.find(from_id)) diesel::update(admin_purge_person.find(from_id))
.set(form) .set(form)
@ -391,7 +422,7 @@ impl Crud for AdminPurgeCommunity {
type UpdateForm = AdminPurgeCommunityForm; type UpdateForm = AdminPurgeCommunityForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::admin_purge_community::dsl::*; use crate::schema::admin_purge_community::dsl::admin_purge_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
admin_purge_community admin_purge_community
.find(from_id) .find(from_id)
@ -400,7 +431,7 @@ impl Crud for AdminPurgeCommunity {
} }
async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result<Self, Error> {
use crate::schema::admin_purge_community::dsl::*; use crate::schema::admin_purge_community::dsl::admin_purge_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(admin_purge_community) insert_into(admin_purge_community)
.values(form) .values(form)
@ -409,7 +440,7 @@ impl Crud for AdminPurgeCommunity {
} }
async fn update(pool: &DbPool, from_id: i32, form: &Self::InsertForm) -> Result<Self, Error> { async fn update(pool: &DbPool, from_id: i32, form: &Self::InsertForm) -> Result<Self, Error> {
use crate::schema::admin_purge_community::dsl::*; use crate::schema::admin_purge_community::dsl::admin_purge_community;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(admin_purge_community.find(from_id)) diesel::update(admin_purge_community.find(from_id))
.set(form) .set(form)
@ -424,13 +455,13 @@ impl Crud for AdminPurgePost {
type UpdateForm = AdminPurgePostForm; type UpdateForm = AdminPurgePostForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::admin_purge_post::dsl::*; use crate::schema::admin_purge_post::dsl::admin_purge_post;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
admin_purge_post.find(from_id).first::<Self>(conn).await admin_purge_post.find(from_id).first::<Self>(conn).await
} }
async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result<Self, Error> {
use crate::schema::admin_purge_post::dsl::*; use crate::schema::admin_purge_post::dsl::admin_purge_post;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(admin_purge_post) insert_into(admin_purge_post)
.values(form) .values(form)
@ -439,7 +470,7 @@ impl Crud for AdminPurgePost {
} }
async fn update(pool: &DbPool, from_id: i32, form: &Self::InsertForm) -> Result<Self, Error> { async fn update(pool: &DbPool, from_id: i32, form: &Self::InsertForm) -> Result<Self, Error> {
use crate::schema::admin_purge_post::dsl::*; use crate::schema::admin_purge_post::dsl::admin_purge_post;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(admin_purge_post.find(from_id)) diesel::update(admin_purge_post.find(from_id))
.set(form) .set(form)
@ -454,13 +485,13 @@ impl Crud for AdminPurgeComment {
type UpdateForm = AdminPurgeCommentForm; type UpdateForm = AdminPurgeCommentForm;
type IdType = i32; type IdType = i32;
async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> { async fn read(pool: &DbPool, from_id: i32) -> Result<Self, Error> {
use crate::schema::admin_purge_comment::dsl::*; use crate::schema::admin_purge_comment::dsl::admin_purge_comment;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
admin_purge_comment.find(from_id).first::<Self>(conn).await admin_purge_comment.find(from_id).first::<Self>(conn).await
} }
async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result<Self, Error> { async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result<Self, Error> {
use crate::schema::admin_purge_comment::dsl::*; use crate::schema::admin_purge_comment::dsl::admin_purge_comment;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(admin_purge_comment) insert_into(admin_purge_comment)
.values(form) .values(form)
@ -469,7 +500,7 @@ impl Crud for AdminPurgeComment {
} }
async fn update(pool: &DbPool, from_id: i32, form: &Self::InsertForm) -> Result<Self, Error> { async fn update(pool: &DbPool, from_id: i32, form: &Self::InsertForm) -> Result<Self, Error> {
use crate::schema::admin_purge_comment::dsl::*; use crate::schema::admin_purge_comment::dsl::admin_purge_comment;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::update(admin_purge_comment.find(from_id)) diesel::update(admin_purge_comment.find(from_id))
.set(form) .set(form)
@ -481,11 +512,38 @@ impl Crud for AdminPurgeComment {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::{ use crate::{
source::{comment::*, community::*, instance::Instance, moderator::*, person::*, post::*}, source::{
comment::{Comment, CommentInsertForm},
community::{Community, CommunityInsertForm},
instance::Instance,
moderator::{
ModAdd,
ModAddCommunity,
ModAddCommunityForm,
ModAddForm,
ModBan,
ModBanForm,
ModBanFromCommunity,
ModBanFromCommunityForm,
ModLockPost,
ModLockPostForm,
ModRemoveComment,
ModRemoveCommentForm,
ModRemoveCommunity,
ModRemoveCommunityForm,
ModRemovePost,
ModRemovePostForm,
ModStickyPost,
ModStickyPostForm,
},
person::{Person, PersonInsertForm},
post::{Post, PostInsertForm},
},
traits::Crud, traits::Crud,
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,
}; };
use serial_test::serial; use serial_test::serial;
#[tokio::test] #[tokio::test]
#[serial] #[serial]
async fn test_crud() { async fn test_crud() {

View file

@ -1,11 +1,16 @@
use crate::{ use crate::{
newtypes::LocalUserId, newtypes::LocalUserId,
schema::password_reset_request::dsl::*, schema::password_reset_request::dsl::{password_reset_request, published, token_encrypted},
source::password_reset_request::*, source::password_reset_request::{PasswordResetRequest, PasswordResetRequestForm},
traits::Crud, traits::Crud,
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl}; use diesel::{
dsl::{insert_into, now, IntervalDsl},
result::Error,
ExpressionMethods,
QueryDsl,
};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
@ -86,7 +91,7 @@ mod tests {
instance::Instance, instance::Instance,
local_user::{LocalUser, LocalUserInsertForm}, local_user::{LocalUser, LocalUserInsertForm},
password_reset_request::PasswordResetRequest, password_reset_request::PasswordResetRequest,
person::*, person::{Person, PersonInsertForm},
}, },
traits::Crud, traits::Crud,
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,

View file

@ -1,15 +1,51 @@
use crate::{ use crate::{
newtypes::{DbUrl, PersonId}, newtypes::{DbUrl, PersonId},
schema::person::dsl::*, schema::person::dsl::{
actor_id,
avatar,
banner,
bio,
deleted,
display_name,
local,
matrix_user_id,
name,
person,
updated,
},
source::person::{Person, PersonInsertForm, PersonUpdateForm}, source::person::{Person, PersonInsertForm, PersonUpdateForm},
traits::{ApubActor, Crud}, traits::{ApubActor, Crud},
utils::{functions::lower, get_conn, naive_now, DbPool}, utils::{functions::lower, get_conn, naive_now, DbPool},
}; };
use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl, TextExpressionMethods}; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl, TextExpressionMethods};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
mod safe_type { mod safe_type {
use crate::{schema::person::columns::*, source::person::Person, traits::ToSafe}; use crate::{
schema::person::columns::{
actor_id,
admin,
avatar,
ban_expires,
banned,
banner,
bio,
bot_account,
deleted,
display_name,
id,
inbox_url,
instance_id,
local,
matrix_user_id,
name,
published,
shared_inbox_url,
updated,
},
source::person::Person,
traits::ToSafe,
};
type Columns = ( type Columns = (
id, id,
@ -186,7 +222,10 @@ impl ApubActor for Person {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::{ use crate::{
source::{instance::Instance, person::*}, source::{
instance::Instance,
person::{Person, PersonInsertForm, PersonUpdateForm},
},
traits::Crud, traits::Crud,
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,
}; };
@ -217,7 +256,7 @@ mod tests {
deleted: false, deleted: false,
published: inserted_person.published, published: inserted_person.published,
updated: None, updated: None,
actor_id: inserted_person.actor_id.to_owned(), actor_id: inserted_person.actor_id.clone(),
bio: None, bio: None,
local: true, local: true,
bot_account: false, bot_account: false,
@ -225,7 +264,7 @@ mod tests {
private_key: None, private_key: None,
public_key: "nada".to_owned(), public_key: "nada".to_owned(),
last_refreshed_at: inserted_person.published, last_refreshed_at: inserted_person.published,
inbox_url: inserted_person.inbox_url.to_owned(), inbox_url: inserted_person.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
ban_expires: None, ban_expires: None,
@ -235,7 +274,7 @@ mod tests {
let read_person = Person::read(pool, inserted_person.id).await.unwrap(); let read_person = Person::read(pool, inserted_person.id).await.unwrap();
let update_person_form = PersonUpdateForm::builder() let update_person_form = PersonUpdateForm::builder()
.actor_id(Some(inserted_person.actor_id.to_owned())) .actor_id(Some(inserted_person.actor_id.clone()))
.build(); .build();
let updated_person = Person::update(pool, inserted_person.id, &update_person_form) let updated_person = Person::update(pool, inserted_person.id, &update_person_form)
.await .await

View file

@ -1,11 +1,11 @@
use crate::{ use crate::{
newtypes::PersonId, newtypes::PersonId,
schema::person_block::dsl::*, schema::person_block::dsl::{person_block, person_id, target_id},
source::person_block::{PersonBlock, PersonBlockForm}, source::person_block::{PersonBlock, PersonBlockForm},
traits::Blockable, traits::Blockable,
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl}; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
impl PersonBlock { impl PersonBlock {

View file

@ -1,11 +1,11 @@
use crate::{ use crate::{
newtypes::{CommentId, PersonId, PersonMentionId}, newtypes::{CommentId, PersonId, PersonMentionId},
schema::person_mention::dsl::*, schema::person_mention::dsl::{comment_id, person_mention, read, recipient_id},
source::person_mention::*, source::person_mention::{PersonMention, PersonMentionInsertForm, PersonMentionUpdateForm},
traits::Crud, traits::Crud,
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, result::Error, *}; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
#[async_trait] #[async_trait]
@ -81,12 +81,12 @@ impl PersonMention {
mod tests { mod tests {
use crate::{ use crate::{
source::{ source::{
comment::*, comment::{Comment, CommentInsertForm},
community::{Community, CommunityInsertForm}, community::{Community, CommunityInsertForm},
instance::Instance, instance::Instance,
person::*, person::{Person, PersonInsertForm},
person_mention::*, person_mention::{PersonMention, PersonMentionInsertForm, PersonMentionUpdateForm},
post::*, post::{Post, PostInsertForm},
}, },
traits::Crud, traits::Crud,
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,

View file

@ -1,6 +1,20 @@
use crate::{ use crate::{
newtypes::{CommunityId, DbUrl, PersonId, PostId}, newtypes::{CommunityId, DbUrl, PersonId, PostId},
schema::post::dsl::*, schema::post::dsl::{
ap_id,
body,
community_id,
creator_id,
deleted,
name,
post,
published,
removed,
stickied,
thumbnail_url,
updated,
url,
},
source::post::{ source::post::{
Post, Post,
PostInsertForm, PostInsertForm,
@ -16,7 +30,7 @@ use crate::{
utils::{get_conn, naive_now, DbPool, FETCH_LIMIT_MAX}, utils::{get_conn, naive_now, DbPool, FETCH_LIMIT_MAX},
}; };
use ::url::Url; use ::url::Url;
use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl, TextExpressionMethods}; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl, TextExpressionMethods};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
#[async_trait] #[async_trait]
@ -138,7 +152,6 @@ impl Post {
pool: &DbPool, pool: &DbPool,
for_creator_id: PersonId, for_creator_id: PersonId,
) -> Result<Vec<Self>, Error> { ) -> Result<Vec<Self>, Error> {
use crate::schema::post::dsl::*;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
let pictrs_search = "%pictrs/image%"; let pictrs_search = "%pictrs/image%";
@ -210,7 +223,7 @@ impl Likeable for PostLike {
type Form = PostLikeForm; type Form = PostLikeForm;
type IdType = PostId; type IdType = PostId;
async fn like(pool: &DbPool, post_like_form: &PostLikeForm) -> Result<Self, Error> { async fn like(pool: &DbPool, post_like_form: &PostLikeForm) -> Result<Self, Error> {
use crate::schema::post_like::dsl::*; use crate::schema::post_like::dsl::{person_id, post_id, post_like};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(post_like) insert_into(post_like)
.values(post_like_form) .values(post_like_form)
@ -237,7 +250,7 @@ impl Likeable for PostLike {
impl Saveable for PostSaved { impl Saveable for PostSaved {
type Form = PostSavedForm; type Form = PostSavedForm;
async fn save(pool: &DbPool, post_saved_form: &PostSavedForm) -> Result<Self, Error> { async fn save(pool: &DbPool, post_saved_form: &PostSavedForm) -> Result<Self, Error> {
use crate::schema::post_saved::dsl::*; use crate::schema::post_saved::dsl::{person_id, post_id, post_saved};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(post_saved) insert_into(post_saved)
.values(post_saved_form) .values(post_saved_form)
@ -248,7 +261,7 @@ impl Saveable for PostSaved {
.await .await
} }
async fn unsave(pool: &DbPool, post_saved_form: &PostSavedForm) -> Result<usize, Error> { async fn unsave(pool: &DbPool, post_saved_form: &PostSavedForm) -> Result<usize, Error> {
use crate::schema::post_saved::dsl::*; use crate::schema::post_saved::dsl::{person_id, post_id, post_saved};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::delete( diesel::delete(
post_saved post_saved
@ -264,7 +277,7 @@ impl Saveable for PostSaved {
impl Readable for PostRead { impl Readable for PostRead {
type Form = PostReadForm; type Form = PostReadForm;
async fn mark_as_read(pool: &DbPool, post_read_form: &PostReadForm) -> Result<Self, Error> { async fn mark_as_read(pool: &DbPool, post_read_form: &PostReadForm) -> Result<Self, Error> {
use crate::schema::post_read::dsl::*; use crate::schema::post_read::dsl::{person_id, post_id, post_read};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
insert_into(post_read) insert_into(post_read)
.values(post_read_form) .values(post_read_form)
@ -276,7 +289,7 @@ impl Readable for PostRead {
} }
async fn mark_as_unread(pool: &DbPool, post_read_form: &PostReadForm) -> Result<usize, Error> { async fn mark_as_unread(pool: &DbPool, post_read_form: &PostReadForm) -> Result<usize, Error> {
use crate::schema::post_read::dsl::*; use crate::schema::post_read::dsl::{person_id, post_id, post_read};
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::delete( diesel::delete(
post_read post_read
@ -290,7 +303,7 @@ impl Readable for PostRead {
impl DeleteableOrRemoveable for Post { impl DeleteableOrRemoveable for Post {
fn blank_out_deleted_or_removed_info(mut self) -> Self { fn blank_out_deleted_or_removed_info(mut self) -> Self {
self.name = "".into(); self.name = String::new();
self.url = None; self.url = None;
self.body = None; self.body = None;
self.embed_title = None; self.embed_title = None;
@ -308,8 +321,18 @@ mod tests {
source::{ source::{
community::{Community, CommunityInsertForm}, community::{Community, CommunityInsertForm},
instance::Instance, instance::Instance,
person::*, person::{Person, PersonInsertForm},
post::*, post::{
Post,
PostInsertForm,
PostLike,
PostLikeForm,
PostRead,
PostReadForm,
PostSaved,
PostSavedForm,
PostUpdateForm,
},
}, },
traits::{Crud, Likeable, Readable, Saveable}, traits::{Crud, Likeable, Readable, Saveable},
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,
@ -366,7 +389,7 @@ mod tests {
embed_description: None, embed_description: None,
embed_video_url: None, embed_video_url: None,
thumbnail_url: None, thumbnail_url: None,
ap_id: inserted_post.ap_id.to_owned(), ap_id: inserted_post.ap_id.clone(),
local: true, local: true,
language_id: Default::default(), language_id: Default::default(),
}; };

View file

@ -1,11 +1,16 @@
use crate::{ use crate::{
newtypes::{PersonId, PostReportId}, newtypes::{PersonId, PostReportId},
schema::post_report::dsl::*, schema::post_report::dsl::{post_report, resolved, resolver_id, updated},
source::post_report::*, source::post_report::{PostReport, PostReportForm},
traits::Reportable, traits::Reportable,
utils::{get_conn, naive_now, DbPool}, utils::{get_conn, naive_now, DbPool},
}; };
use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl}; use diesel::{
dsl::{insert_into, update},
result::Error,
ExpressionMethods,
QueryDsl,
};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
#[async_trait] #[async_trait]

View file

@ -1,11 +1,11 @@
use crate::{ use crate::{
newtypes::{DbUrl, PersonId, PrivateMessageId}, newtypes::{DbUrl, PersonId, PrivateMessageId},
schema::private_message::dsl::*, schema::private_message::dsl::{ap_id, private_message, read, recipient_id},
source::private_message::*, source::private_message::{PrivateMessage, PrivateMessageInsertForm, PrivateMessageUpdateForm},
traits::{Crud, DeleteableOrRemoveable}, traits::{Crud, DeleteableOrRemoveable},
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, result::Error, *}; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use lemmy_utils::error::LemmyError; use lemmy_utils::error::LemmyError;
use url::Url; use url::Url;
@ -88,7 +88,7 @@ impl PrivateMessage {
impl DeleteableOrRemoveable for PrivateMessage { impl DeleteableOrRemoveable for PrivateMessage {
fn blank_out_deleted_or_removed_info(mut self) -> Self { fn blank_out_deleted_or_removed_info(mut self) -> Self {
self.content = "".into(); self.content = String::new();
self self
} }
} }
@ -96,7 +96,11 @@ impl DeleteableOrRemoveable for PrivateMessage {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::{ use crate::{
source::{instance::Instance, person::*, private_message::*}, source::{
instance::Instance,
person::{Person, PersonInsertForm},
private_message::{PrivateMessage, PrivateMessageInsertForm, PrivateMessageUpdateForm},
},
traits::Crud, traits::Crud,
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,
}; };
@ -144,7 +148,7 @@ mod tests {
read: false, read: false,
updated: None, updated: None,
published: inserted_private_message.published, published: inserted_private_message.published,
ap_id: inserted_private_message.ap_id.to_owned(), ap_id: inserted_private_message.ap_id.clone(),
local: true, local: true,
}; };

View file

@ -1,11 +1,16 @@
use crate::{ use crate::{
newtypes::{PersonId, PrivateMessageReportId}, newtypes::{PersonId, PrivateMessageReportId},
schema::private_message_report::dsl::*, schema::private_message_report::dsl::{private_message_report, resolved, resolver_id, updated},
source::private_message_report::{PrivateMessageReport, PrivateMessageReportForm}, source::private_message_report::{PrivateMessageReport, PrivateMessageReportForm},
traits::Reportable, traits::Reportable,
utils::{get_conn, naive_now, DbPool}, utils::{get_conn, naive_now, DbPool},
}; };
use diesel::{dsl::*, result::Error, *}; use diesel::{
dsl::{insert_into, update},
result::Error,
ExpressionMethods,
QueryDsl,
};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
#[async_trait] #[async_trait]

View file

@ -1,7 +1,11 @@
use crate::{ use crate::{
newtypes::LocalUserId, newtypes::LocalUserId,
schema::registration_application::dsl::*, schema::registration_application::dsl::{local_user_id, registration_application},
source::registration_application::*, source::registration_application::{
RegistrationApplication,
RegistrationApplicationInsertForm,
RegistrationApplicationUpdateForm,
},
traits::Crud, traits::Crud,
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };

View file

@ -1,5 +1,5 @@
use crate::{ use crate::{
schema::secret::dsl::*, schema::secret::dsl::secret,
source::secret::Secret, source::secret::Secret,
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };

View file

@ -1,11 +1,14 @@
use crate::{ use crate::{
newtypes::{DbUrl, SiteId}, newtypes::{DbUrl, SiteId},
schema::site::dsl::*, schema::site::dsl::{actor_id, id, site},
source::{actor_language::SiteLanguage, site::*}, source::{
actor_language::SiteLanguage,
site::{Site, SiteInsertForm, SiteUpdateForm},
},
traits::Crud, traits::Crud,
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl}; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use url::Url; use url::Url;

View file

@ -120,7 +120,7 @@ pub struct LtreeDef(pub String);
impl Display for DbUrl { impl Display for DbUrl {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.to_owned().0.fmt(f) self.clone().0.fmt(f)
} }
} }

View file

@ -36,8 +36,7 @@ pub type DbPool = Pool<AsyncPgConnection>;
pub async fn get_conn( pub async fn get_conn(
pool: &DbPool, pool: &DbPool,
) -> Result<PooledConnection<AsyncDieselConnectionManager<AsyncPgConnection>>, DieselError> { ) -> Result<PooledConnection<AsyncDieselConnectionManager<AsyncPgConnection>>, DieselError> {
// TODO Maybe find a better diesel error for this pool.get().await.map_err(|e| QueryBuilderError(e.into()))
pool.get().await.map_err(|_| DieselError::NotInTransaction)
} }
pub fn get_database_url_from_env() -> Result<String, VarError> { pub fn get_database_url_from_env() -> Result<String, VarError> {
@ -94,7 +93,7 @@ pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
// An empty string is an erase // An empty string is an erase
Some(unwrapped) => { Some(unwrapped) => {
if !unwrapped.eq("") { if !unwrapped.eq("") {
Some(Some(unwrapped.to_owned())) Some(Some(unwrapped.clone()))
} else { } else {
Some(None) Some(None)
} }
@ -106,7 +105,7 @@ pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
pub fn diesel_option_overwrite_to_url( pub fn diesel_option_overwrite_to_url(
opt: &Option<String>, opt: &Option<String>,
) -> Result<Option<Option<DbUrl>>, LemmyError> { ) -> Result<Option<Option<DbUrl>>, LemmyError> {
match opt.as_ref().map(|s| s.as_str()) { match opt.as_ref().map(std::string::String::as_str) {
// An empty string is an erase // An empty string is an erase
Some("") => Ok(Some(None)), Some("") => Ok(Some(None)),
Some(str_url) => match Url::parse(str_url) { Some(str_url) => match Url::parse(str_url) {
@ -120,7 +119,7 @@ pub fn diesel_option_overwrite_to_url(
pub fn diesel_option_overwrite_to_url_create( pub fn diesel_option_overwrite_to_url_create(
opt: &Option<String>, opt: &Option<String>,
) -> Result<Option<DbUrl>, LemmyError> { ) -> Result<Option<DbUrl>, LemmyError> {
match opt.as_ref().map(|s| s.as_str()) { match opt.as_ref().map(std::string::String::as_str) {
// An empty string is nothing // An empty string is nothing
Some("") => Ok(None), Some("") => Ok(None),
Some(str_url) => match Url::parse(str_url) { Some(str_url) => match Url::parse(str_url) {
@ -207,7 +206,7 @@ static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
}); });
pub mod functions { pub mod functions {
use diesel::sql_types::*; use diesel::sql_types::{BigInt, Text, Timestamp};
sql_function! { sql_function! {
fn hot_rank(score: BigInt, time: Timestamp) -> Integer; fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
@ -265,7 +264,7 @@ mod tests {
#[test] #[test]
fn test_diesel_option_overwrite() { fn test_diesel_option_overwrite() {
assert_eq!(diesel_option_overwrite(&None), None); assert_eq!(diesel_option_overwrite(&None), None);
assert_eq!(diesel_option_overwrite(&Some("".to_string())), Some(None)); assert_eq!(diesel_option_overwrite(&Some(String::new())), Some(None));
assert_eq!( assert_eq!(
diesel_option_overwrite(&Some("test".to_string())), diesel_option_overwrite(&Some("test".to_string())),
Some(Some("test".to_string())) Some(Some("test".to_string()))
@ -276,7 +275,7 @@ mod tests {
fn test_diesel_option_overwrite_to_url() { fn test_diesel_option_overwrite_to_url() {
assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None))); assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
assert!(matches!( assert!(matches!(
diesel_option_overwrite_to_url(&Some("".to_string())), diesel_option_overwrite_to_url(&Some(String::new())),
Ok(Some(None)) Ok(Some(None))
)); ));
assert!(matches!( assert!(matches!(

View file

@ -1,6 +1,6 @@
use crate::structs::CommentReportView; use crate::structs::CommentReportView;
use diesel::{ use diesel::{
dsl::*, dsl::now,
result::Error, result::Error,
BoolExpressionMethods, BoolExpressionMethods,
ExpressionMethods, ExpressionMethods,
@ -145,7 +145,7 @@ impl CommentReportView {
admin: bool, admin: bool,
community_id: Option<CommunityId>, community_id: Option<CommunityId>,
) -> Result<i64, Error> { ) -> Result<i64, Error> {
use diesel::dsl::*; use diesel::dsl::count;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
@ -311,7 +311,20 @@ mod tests {
use crate::comment_report_view::{CommentReportQuery, CommentReportView}; use crate::comment_report_view::{CommentReportQuery, CommentReportView};
use lemmy_db_schema::{ use lemmy_db_schema::{
aggregates::structs::CommentAggregates, aggregates::structs::CommentAggregates,
source::{comment::*, comment_report::*, community::*, instance::Instance, person::*, post::*}, source::{
comment::{Comment, CommentInsertForm},
comment_report::{CommentReport, CommentReportForm},
community::{
Community,
CommunityInsertForm,
CommunityModerator,
CommunityModeratorForm,
CommunitySafe,
},
instance::Instance,
person::{Person, PersonInsertForm, PersonSafe},
post::{Post, PostInsertForm},
},
traits::{Crud, Joinable, Reportable}, traits::{Crud, Joinable, Reportable},
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,
}; };
@ -417,8 +430,8 @@ mod tests {
.await .await
.unwrap(); .unwrap();
let expected_jessica_report_view = CommentReportView { let expected_jessica_report_view = CommentReportView {
comment_report: inserted_jessica_report.to_owned(), comment_report: inserted_jessica_report.clone(),
comment: inserted_comment.to_owned(), comment: inserted_comment.clone(),
post: inserted_post, post: inserted_post,
community: CommunitySafe { community: CommunitySafe {
id: inserted_community.id, id: inserted_community.id,
@ -427,7 +440,7 @@ mod tests {
removed: false, removed: false,
deleted: false, deleted: false,
nsfw: false, nsfw: false,
actor_id: inserted_community.actor_id.to_owned(), actor_id: inserted_community.actor_id.clone(),
local: true, local: true,
title: inserted_community.title, title: inserted_community.title,
description: None, description: None,
@ -444,7 +457,7 @@ mod tests {
display_name: None, display_name: None,
published: inserted_jessica.published, published: inserted_jessica.published,
avatar: None, avatar: None,
actor_id: inserted_jessica.actor_id.to_owned(), actor_id: inserted_jessica.actor_id.clone(),
local: true, local: true,
banned: false, banned: false,
deleted: false, deleted: false,
@ -453,7 +466,7 @@ mod tests {
bio: None, bio: None,
banner: None, banner: None,
updated: None, updated: None,
inbox_url: inserted_jessica.inbox_url.to_owned(), inbox_url: inserted_jessica.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
ban_expires: None, ban_expires: None,
@ -461,11 +474,11 @@ mod tests {
}, },
comment_creator: PersonSafe { comment_creator: PersonSafe {
id: inserted_timmy.id, id: inserted_timmy.id,
name: inserted_timmy.name.to_owned(), name: inserted_timmy.name.clone(),
display_name: None, display_name: None,
published: inserted_timmy.published, published: inserted_timmy.published,
avatar: None, avatar: None,
actor_id: inserted_timmy.actor_id.to_owned(), actor_id: inserted_timmy.actor_id.clone(),
local: true, local: true,
banned: false, banned: false,
deleted: false, deleted: false,
@ -474,7 +487,7 @@ mod tests {
bio: None, bio: None,
banner: None, banner: None,
updated: None, updated: None,
inbox_url: inserted_timmy.inbox_url.to_owned(), inbox_url: inserted_timmy.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
ban_expires: None, ban_expires: None,
@ -504,7 +517,7 @@ mod tests {
display_name: None, display_name: None,
published: inserted_sara.published, published: inserted_sara.published,
avatar: None, avatar: None,
actor_id: inserted_sara.actor_id.to_owned(), actor_id: inserted_sara.actor_id.clone(),
local: true, local: true,
banned: false, banned: false,
deleted: false, deleted: false,
@ -513,7 +526,7 @@ mod tests {
bio: None, bio: None,
banner: None, banner: None,
updated: None, updated: None,
inbox_url: inserted_sara.inbox_url.to_owned(), inbox_url: inserted_sara.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
ban_expires: None, ban_expires: None,
@ -533,8 +546,8 @@ mod tests {
assert_eq!( assert_eq!(
reports, reports,
[ [
expected_jessica_report_view.to_owned(), expected_jessica_report_view.clone(),
expected_sara_report_view.to_owned() expected_sara_report_view.clone()
] ]
); );
@ -567,11 +580,11 @@ mod tests {
.updated; .updated;
expected_jessica_report_view_after_resolve.resolver = Some(PersonSafe { expected_jessica_report_view_after_resolve.resolver = Some(PersonSafe {
id: inserted_timmy.id, id: inserted_timmy.id,
name: inserted_timmy.name.to_owned(), name: inserted_timmy.name.clone(),
display_name: None, display_name: None,
published: inserted_timmy.published, published: inserted_timmy.published,
avatar: None, avatar: None,
actor_id: inserted_timmy.actor_id.to_owned(), actor_id: inserted_timmy.actor_id.clone(),
local: true, local: true,
banned: false, banned: false,
deleted: false, deleted: false,
@ -580,7 +593,7 @@ mod tests {
bio: None, bio: None,
banner: None, banner: None,
updated: None, updated: None,
inbox_url: inserted_timmy.inbox_url.to_owned(), inbox_url: inserted_timmy.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
ban_expires: None, ban_expires: None,

View file

@ -1,6 +1,6 @@
use crate::structs::CommentView; use crate::structs::CommentView;
use diesel::{ use diesel::{
dsl::*, dsl::now,
result::Error, result::Error,
BoolExpressionMethods, BoolExpressionMethods,
ExpressionMethods, ExpressionMethods,
@ -185,7 +185,6 @@ pub struct CommentQuery<'a> {
impl<'a> CommentQuery<'a> { impl<'a> CommentQuery<'a> {
pub async fn list(self) -> Result<Vec<CommentView>, Error> { pub async fn list(self) -> Result<Vec<CommentView>, Error> {
use diesel::dsl::*;
let conn = &mut get_conn(self.pool).await?; let conn = &mut get_conn(self.pool).await?;
// The left join below will return None in this case // The left join below will return None in this case
@ -403,20 +402,33 @@ impl ViewToVec for CommentView {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::comment_view::*; use crate::comment_view::{
Comment,
CommentQuery,
CommentSortType,
CommentView,
Community,
CommunitySafe,
DbPool,
LocalUser,
Person,
PersonBlock,
PersonSafe,
Post,
};
use lemmy_db_schema::{ use lemmy_db_schema::{
aggregates::structs::CommentAggregates, aggregates::structs::CommentAggregates,
newtypes::LanguageId, newtypes::LanguageId,
source::{ source::{
actor_language::LocalUserLanguage, actor_language::LocalUserLanguage,
comment::*, comment::{CommentInsertForm, CommentLike, CommentLikeForm},
community::*, community::CommunityInsertForm,
instance::Instance, instance::Instance,
language::Language, language::Language,
local_user::LocalUserInsertForm, local_user::LocalUserInsertForm,
person::*, person::PersonInsertForm,
person_block::PersonBlockForm, person_block::PersonBlockForm,
post::*, post::PostInsertForm,
}, },
traits::{Blockable, Crud, Likeable}, traits::{Blockable, Crud, Likeable},
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,
@ -447,7 +459,7 @@ mod tests {
let inserted_person = Person::create(pool, &new_person).await.unwrap(); let inserted_person = Person::create(pool, &new_person).await.unwrap();
let local_user_form = LocalUserInsertForm::builder() let local_user_form = LocalUserInsertForm::builder()
.person_id(inserted_person.id) .person_id(inserted_person.id)
.password_encrypted("".to_string()) .password_encrypted(String::new())
.build(); .build();
let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap(); let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
@ -594,7 +606,7 @@ mod tests {
let expected_comment_view_no_person = expected_comment_view(&data, pool).await; let expected_comment_view_no_person = expected_comment_view(&data, pool).await;
let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned(); let mut expected_comment_view_with_person = expected_comment_view_no_person.clone();
expected_comment_view_with_person.my_vote = Some(1); expected_comment_view_with_person.my_vote = Some(1);
let read_comment_views_no_person = CommentQuery::builder() let read_comment_views_no_person = CommentQuery::builder()
@ -815,7 +827,7 @@ mod tests {
updated: None, updated: None,
local: true, local: true,
distinguished: false, distinguished: false,
path: data.inserted_comment_0.to_owned().path, path: data.inserted_comment_0.clone().path,
language_id: LanguageId(0), language_id: LanguageId(0),
}, },
creator: PersonSafe { creator: PersonSafe {
@ -824,7 +836,7 @@ mod tests {
display_name: None, display_name: None,
published: data.inserted_person.published, published: data.inserted_person.published,
avatar: None, avatar: None,
actor_id: data.inserted_person.actor_id.to_owned(), actor_id: data.inserted_person.actor_id.clone(),
local: true, local: true,
banned: false, banned: false,
deleted: false, deleted: false,
@ -833,7 +845,7 @@ mod tests {
bio: None, bio: None,
banner: None, banner: None,
updated: None, updated: None,
inbox_url: data.inserted_person.inbox_url.to_owned(), inbox_url: data.inserted_person.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
ban_expires: None, ban_expires: None,
@ -841,7 +853,7 @@ mod tests {
}, },
post: Post { post: Post {
id: data.inserted_post.id, id: data.inserted_post.id,
name: data.inserted_post.name.to_owned(), name: data.inserted_post.name.clone(),
creator_id: data.inserted_person.id, creator_id: data.inserted_person.id,
url: None, url: None,
body: None, body: None,
@ -857,7 +869,7 @@ mod tests {
embed_description: None, embed_description: None,
embed_video_url: None, embed_video_url: None,
thumbnail_url: None, thumbnail_url: None,
ap_id: data.inserted_post.ap_id.to_owned(), ap_id: data.inserted_post.ap_id.clone(),
local: true, local: true,
language_id: Default::default(), language_id: Default::default(),
}, },
@ -868,7 +880,7 @@ mod tests {
removed: false, removed: false,
deleted: false, deleted: false,
nsfw: false, nsfw: false,
actor_id: data.inserted_community.actor_id.to_owned(), actor_id: data.inserted_community.actor_id.clone(),
local: true, local: true,
title: "nada".to_owned(), title: "nada".to_owned(),
description: None, description: None,

View file

@ -1,6 +1,6 @@
use crate::structs::PostReportView; use crate::structs::PostReportView;
use diesel::{ use diesel::{
dsl::*, dsl::now,
result::Error, result::Error,
BoolExpressionMethods, BoolExpressionMethods,
ExpressionMethods, ExpressionMethods,
@ -132,7 +132,7 @@ impl PostReportView {
admin: bool, admin: bool,
community_id: Option<CommunityId>, community_id: Option<CommunityId>,
) -> Result<i64, Error> { ) -> Result<i64, Error> {
use diesel::dsl::*; use diesel::dsl::count;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
let mut query = post_report::table let mut query = post_report::table
.inner_join(post::table) .inner_join(post::table)
@ -289,10 +289,16 @@ mod tests {
use lemmy_db_schema::{ use lemmy_db_schema::{
aggregates::structs::PostAggregates, aggregates::structs::PostAggregates,
source::{ source::{
community::*, community::{
Community,
CommunityInsertForm,
CommunityModerator,
CommunityModeratorForm,
CommunitySafe,
},
instance::Instance, instance::Instance,
person::*, person::{Person, PersonInsertForm, PersonSafe},
post::*, post::{Post, PostInsertForm},
post_report::{PostReport, PostReportForm}, post_report::{PostReport, PostReportForm},
}, },
traits::{Crud, Joinable, Reportable}, traits::{Crud, Joinable, Reportable},
@ -392,8 +398,8 @@ mod tests {
.await .await
.unwrap(); .unwrap();
let expected_jessica_report_view = PostReportView { let expected_jessica_report_view = PostReportView {
post_report: inserted_jessica_report.to_owned(), post_report: inserted_jessica_report.clone(),
post: inserted_post.to_owned(), post: inserted_post.clone(),
community: CommunitySafe { community: CommunitySafe {
id: inserted_community.id, id: inserted_community.id,
name: inserted_community.name, name: inserted_community.name,
@ -401,7 +407,7 @@ mod tests {
removed: false, removed: false,
deleted: false, deleted: false,
nsfw: false, nsfw: false,
actor_id: inserted_community.actor_id.to_owned(), actor_id: inserted_community.actor_id.clone(),
local: true, local: true,
title: inserted_community.title, title: inserted_community.title,
description: None, description: None,
@ -418,7 +424,7 @@ mod tests {
display_name: None, display_name: None,
published: inserted_jessica.published, published: inserted_jessica.published,
avatar: None, avatar: None,
actor_id: inserted_jessica.actor_id.to_owned(), actor_id: inserted_jessica.actor_id.clone(),
local: true, local: true,
banned: false, banned: false,
deleted: false, deleted: false,
@ -427,7 +433,7 @@ mod tests {
bio: None, bio: None,
banner: None, banner: None,
updated: None, updated: None,
inbox_url: inserted_jessica.inbox_url.to_owned(), inbox_url: inserted_jessica.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
ban_expires: None, ban_expires: None,
@ -435,11 +441,11 @@ mod tests {
}, },
post_creator: PersonSafe { post_creator: PersonSafe {
id: inserted_timmy.id, id: inserted_timmy.id,
name: inserted_timmy.name.to_owned(), name: inserted_timmy.name.clone(),
display_name: None, display_name: None,
published: inserted_timmy.published, published: inserted_timmy.published,
avatar: None, avatar: None,
actor_id: inserted_timmy.actor_id.to_owned(), actor_id: inserted_timmy.actor_id.clone(),
local: true, local: true,
banned: false, banned: false,
deleted: false, deleted: false,
@ -448,7 +454,7 @@ mod tests {
bio: None, bio: None,
banner: None, banner: None,
updated: None, updated: None,
inbox_url: inserted_timmy.inbox_url.to_owned(), inbox_url: inserted_timmy.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
ban_expires: None, ban_expires: None,
@ -482,7 +488,7 @@ mod tests {
display_name: None, display_name: None,
published: inserted_sara.published, published: inserted_sara.published,
avatar: None, avatar: None,
actor_id: inserted_sara.actor_id.to_owned(), actor_id: inserted_sara.actor_id.clone(),
local: true, local: true,
banned: false, banned: false,
deleted: false, deleted: false,
@ -491,7 +497,7 @@ mod tests {
bio: None, bio: None,
banner: None, banner: None,
updated: None, updated: None,
inbox_url: inserted_sara.inbox_url.to_owned(), inbox_url: inserted_sara.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
ban_expires: None, ban_expires: None,
@ -511,8 +517,8 @@ mod tests {
assert_eq!( assert_eq!(
reports, reports,
[ [
expected_jessica_report_view.to_owned(), expected_jessica_report_view.clone(),
expected_sara_report_view.to_owned() expected_sara_report_view.clone()
] ]
); );
@ -543,11 +549,11 @@ mod tests {
.updated = read_jessica_report_view_after_resolve.post_report.updated; .updated = read_jessica_report_view_after_resolve.post_report.updated;
expected_jessica_report_view_after_resolve.resolver = Some(PersonSafe { expected_jessica_report_view_after_resolve.resolver = Some(PersonSafe {
id: inserted_timmy.id, id: inserted_timmy.id,
name: inserted_timmy.name.to_owned(), name: inserted_timmy.name.clone(),
display_name: None, display_name: None,
published: inserted_timmy.published, published: inserted_timmy.published,
avatar: None, avatar: None,
actor_id: inserted_timmy.actor_id.to_owned(), actor_id: inserted_timmy.actor_id.clone(),
local: true, local: true,
banned: false, banned: false,
deleted: false, deleted: false,
@ -556,7 +562,7 @@ mod tests {
bio: None, bio: None,
banner: None, banner: None,
updated: None, updated: None,
inbox_url: inserted_timmy.inbox_url.to_owned(), inbox_url: inserted_timmy.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
ban_expires: None, ban_expires: None,

View file

@ -1,7 +1,7 @@
use crate::structs::PostView; use crate::structs::PostView;
use diesel::{ use diesel::{
debug_query, debug_query,
dsl::*, dsl::{now, IntervalDsl},
pg::Pg, pg::Pg,
result::Error, result::Error,
sql_function, sql_function,
@ -207,7 +207,6 @@ pub struct PostQuery<'a> {
impl<'a> PostQuery<'a> { impl<'a> PostQuery<'a> {
pub async fn list(self) -> Result<Vec<PostView>, Error> { pub async fn list(self) -> Result<Vec<PostView>, Error> {
use diesel::dsl::*;
let conn = &mut get_conn(self.pool).await?; let conn = &mut get_conn(self.pool).await?;
// The left join below will return None in this case // The left join below will return None in this case
@ -346,7 +345,7 @@ impl<'a> PostQuery<'a> {
let searcher = fuzzy_search(&search_term); let searcher = fuzzy_search(&search_term);
query = query.filter( query = query.filter(
post::name post::name
.ilike(searcher.to_owned()) .ilike(searcher.clone())
.or(post::body.ilike(searcher)), .or(post::body.ilike(searcher)),
); );
} }
@ -472,14 +471,14 @@ mod tests {
newtypes::LanguageId, newtypes::LanguageId,
source::{ source::{
actor_language::LocalUserLanguage, actor_language::LocalUserLanguage,
community::*, community::{Community, CommunityInsertForm, CommunitySafe},
community_block::{CommunityBlock, CommunityBlockForm}, community_block::{CommunityBlock, CommunityBlockForm},
instance::Instance, instance::Instance,
language::Language, language::Language,
local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm}, local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm},
person::*, person::{Person, PersonInsertForm, PersonSafe},
person_block::{PersonBlock, PersonBlockForm}, person_block::{PersonBlock, PersonBlockForm},
post::*, post::{Post, PostInsertForm, PostLike, PostLikeForm},
}, },
traits::{Blockable, Crud, Likeable}, traits::{Blockable, Crud, Likeable},
utils::{build_db_pool_for_tests, DbPool}, utils::{build_db_pool_for_tests, DbPool},
@ -504,7 +503,7 @@ mod tests {
let person_name = "tegan".to_string(); let person_name = "tegan".to_string();
let new_person = PersonInsertForm::builder() let new_person = PersonInsertForm::builder()
.name(person_name.to_owned()) .name(person_name.clone())
.public_key("pubkey".to_string()) .public_key("pubkey".to_string())
.instance_id(inserted_instance.id) .instance_id(inserted_instance.id)
.build(); .build();
@ -513,7 +512,7 @@ mod tests {
let local_user_form = LocalUserInsertForm::builder() let local_user_form = LocalUserInsertForm::builder()
.person_id(inserted_person.id) .person_id(inserted_person.id)
.password_encrypted("".to_string()) .password_encrypted(String::new())
.build(); .build();
let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap(); let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
@ -867,7 +866,7 @@ mod tests {
embed_description: None, embed_description: None,
embed_video_url: None, embed_video_url: None,
thumbnail_url: None, thumbnail_url: None,
ap_id: inserted_post.ap_id.to_owned(), ap_id: inserted_post.ap_id.clone(),
local: true, local: true,
language_id: LanguageId(47), language_id: LanguageId(47),
}, },
@ -879,7 +878,7 @@ mod tests {
display_name: None, display_name: None,
published: inserted_person.published, published: inserted_person.published,
avatar: None, avatar: None,
actor_id: inserted_person.actor_id.to_owned(), actor_id: inserted_person.actor_id.clone(),
local: true, local: true,
admin: false, admin: false,
bot_account: false, bot_account: false,
@ -888,7 +887,7 @@ mod tests {
bio: None, bio: None,
banner: None, banner: None,
updated: None, updated: None,
inbox_url: inserted_person.inbox_url.to_owned(), inbox_url: inserted_person.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
ban_expires: None, ban_expires: None,
@ -902,7 +901,7 @@ mod tests {
removed: false, removed: false,
deleted: false, deleted: false,
nsfw: false, nsfw: false,
actor_id: inserted_community.actor_id.to_owned(), actor_id: inserted_community.actor_id.clone(),
local: true, local: true,
title: "nada".to_owned(), title: "nada".to_owned(),
description: None, description: None,

View file

@ -67,7 +67,7 @@ impl PrivateMessageReportView {
/// Returns the current unresolved post report count for the communities you mod /// Returns the current unresolved post report count for the communities you mod
pub async fn get_report_count(pool: &DbPool) -> Result<i64, Error> { pub async fn get_report_count(pool: &DbPool) -> Result<i64, Error> {
use diesel::dsl::*; use diesel::dsl::count;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
private_message_report::table private_message_report::table

View file

@ -53,7 +53,7 @@ impl PrivateMessageView {
/// Gets the number of unread messages /// Gets the number of unread messages
pub async fn get_unread_messages(pool: &DbPool, my_person_id: PersonId) -> Result<i64, Error> { pub async fn get_unread_messages(pool: &DbPool, my_person_id: PersonId) -> Result<i64, Error> {
use diesel::dsl::*; use diesel::dsl::count;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
private_message::table private_message::table
.filter(private_message::read.eq(false)) .filter(private_message::read.eq(false))

View file

@ -169,7 +169,7 @@ mod tests {
source::{ source::{
instance::Instance, instance::Instance,
local_user::{LocalUser, LocalUserInsertForm, LocalUserSettings, LocalUserUpdateForm}, local_user::{LocalUser, LocalUserInsertForm, LocalUserSettings, LocalUserUpdateForm},
person::*, person::{Person, PersonInsertForm, PersonSafe},
registration_application::{ registration_application::{
RegistrationApplication, RegistrationApplication,
RegistrationApplicationInsertForm, RegistrationApplicationInsertForm,
@ -269,7 +269,7 @@ mod tests {
.unwrap(); .unwrap();
let mut expected_sara_app_view = RegistrationApplicationView { let mut expected_sara_app_view = RegistrationApplicationView {
registration_application: sara_app.to_owned(), registration_application: sara_app.clone(),
creator_local_user: LocalUserSettings { creator_local_user: LocalUserSettings {
id: inserted_sara_local_user.id, id: inserted_sara_local_user.id,
person_id: inserted_sara_local_user.person_id, person_id: inserted_sara_local_user.person_id,
@ -291,11 +291,11 @@ mod tests {
}, },
creator: PersonSafe { creator: PersonSafe {
id: inserted_sara_person.id, id: inserted_sara_person.id,
name: inserted_sara_person.name.to_owned(), name: inserted_sara_person.name.clone(),
display_name: None, display_name: None,
published: inserted_sara_person.published, published: inserted_sara_person.published,
avatar: None, avatar: None,
actor_id: inserted_sara_person.actor_id.to_owned(), actor_id: inserted_sara_person.actor_id.clone(),
local: true, local: true,
banned: false, banned: false,
ban_expires: None, ban_expires: None,
@ -305,7 +305,7 @@ mod tests {
bio: None, bio: None,
banner: None, banner: None,
updated: None, updated: None,
inbox_url: inserted_sara_person.inbox_url.to_owned(), inbox_url: inserted_sara_person.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
instance_id: inserted_instance.id, instance_id: inserted_instance.id,
@ -326,10 +326,7 @@ mod tests {
assert_eq!( assert_eq!(
apps, apps,
[ [read_jess_app_view.clone(), expected_sara_app_view.clone()]
read_jess_app_view.to_owned(),
expected_sara_app_view.to_owned()
]
); );
// Make sure the counts are correct // Make sure the counts are correct
@ -369,11 +366,11 @@ mod tests {
expected_sara_app_view.admin = Some(PersonSafe { expected_sara_app_view.admin = Some(PersonSafe {
id: inserted_timmy_person.id, id: inserted_timmy_person.id,
name: inserted_timmy_person.name.to_owned(), name: inserted_timmy_person.name.clone(),
display_name: None, display_name: None,
published: inserted_timmy_person.published, published: inserted_timmy_person.published,
avatar: None, avatar: None,
actor_id: inserted_timmy_person.actor_id.to_owned(), actor_id: inserted_timmy_person.actor_id.clone(),
local: true, local: true,
banned: false, banned: false,
ban_expires: None, ban_expires: None,
@ -383,7 +380,7 @@ mod tests {
bio: None, bio: None,
banner: None, banner: None,
updated: None, updated: None,
inbox_url: inserted_timmy_person.inbox_url.to_owned(), inbox_url: inserted_timmy_person.inbox_url.clone(),
shared_inbox_url: None, shared_inbox_url: None,
matrix_user_id: None, matrix_user_id: None,
instance_id: inserted_instance.id, instance_id: inserted_instance.id,

View file

@ -1,6 +1,6 @@
use crate::structs::CommentReplyView; use crate::structs::CommentReplyView;
use diesel::{ use diesel::{
dsl::*, dsl::now,
result::Error, result::Error,
BoolExpressionMethods, BoolExpressionMethods,
ExpressionMethods, ExpressionMethods,
@ -162,7 +162,7 @@ impl CommentReplyView {
/// Gets the number of unread replies /// Gets the number of unread replies
pub async fn get_unread_replies(pool: &DbPool, my_person_id: PersonId) -> Result<i64, Error> { pub async fn get_unread_replies(pool: &DbPool, my_person_id: PersonId) -> Result<i64, Error> {
use diesel::dsl::*; use diesel::dsl::count;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
@ -194,7 +194,6 @@ pub struct CommentReplyQuery<'a> {
impl<'a> CommentReplyQuery<'a> { impl<'a> CommentReplyQuery<'a> {
pub async fn list(self) -> Result<Vec<CommentReplyView>, Error> { pub async fn list(self) -> Result<Vec<CommentReplyView>, Error> {
use diesel::dsl::*;
let conn = &mut get_conn(self.pool).await?; let conn = &mut get_conn(self.pool).await?;
let person_alias_1 = diesel::alias!(person as person1); let person_alias_1 = diesel::alias!(person as person1);

View file

@ -1,5 +1,5 @@
use crate::structs::CommunityPersonBanView; use crate::structs::CommunityPersonBanView;
use diesel::{dsl::*, result::Error, BoolExpressionMethods, ExpressionMethods, QueryDsl}; use diesel::{dsl::now, result::Error, BoolExpressionMethods, ExpressionMethods, QueryDsl};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use lemmy_db_schema::{ use lemmy_db_schema::{
newtypes::{CommunityId, PersonId}, newtypes::{CommunityId, PersonId},

View file

@ -155,7 +155,7 @@ impl<'a> CommunityQuery<'a> {
if let Some(search_term) = self.search_term { if let Some(search_term) = self.search_term {
let searcher = fuzzy_search(&search_term); let searcher = fuzzy_search(&search_term);
query = query query = query
.filter(community::name.ilike(searcher.to_owned())) .filter(community::name.ilike(searcher.clone()))
.or_filter(community::title.ilike(searcher)); .or_filter(community::title.ilike(searcher));
}; };

View file

@ -1,6 +1,6 @@
use crate::structs::PersonMentionView; use crate::structs::PersonMentionView;
use diesel::{ use diesel::{
dsl::*, dsl::now,
result::Error, result::Error,
BoolExpressionMethods, BoolExpressionMethods,
ExpressionMethods, ExpressionMethods,
@ -162,7 +162,7 @@ impl PersonMentionView {
/// Gets the number of unread mentions /// Gets the number of unread mentions
pub async fn get_unread_mentions(pool: &DbPool, my_person_id: PersonId) -> Result<i64, Error> { pub async fn get_unread_mentions(pool: &DbPool, my_person_id: PersonId) -> Result<i64, Error> {
use diesel::dsl::*; use diesel::dsl::count;
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
person_mention::table person_mention::table
@ -193,7 +193,6 @@ pub struct PersonMentionQuery<'a> {
impl<'a> PersonMentionQuery<'a> { impl<'a> PersonMentionQuery<'a> {
pub async fn list(self) -> Result<Vec<PersonMentionView>, Error> { pub async fn list(self) -> Result<Vec<PersonMentionView>, Error> {
use diesel::dsl::*;
let conn = &mut get_conn(self.pool).await?; let conn = &mut get_conn(self.pool).await?;
let person_alias_1 = diesel::alias!(person as person1); let person_alias_1 = diesel::alias!(person as person1);

View file

@ -1,6 +1,6 @@
use crate::structs::PersonViewSafe; use crate::structs::PersonViewSafe;
use diesel::{ use diesel::{
dsl::*, dsl::{now, IntervalDsl},
result::Error, result::Error,
BoolExpressionMethods, BoolExpressionMethods,
ExpressionMethods, ExpressionMethods,
@ -90,7 +90,7 @@ impl<'a> PersonQuery<'a> {
if let Some(search_term) = self.search_term { if let Some(search_term) = self.search_term {
let searcher = fuzzy_search(&search_term); let searcher = fuzzy_search(&search_term);
query = query query = query
.filter(person::name.ilike(searcher.to_owned())) .filter(person::name.ilike(searcher.clone()))
.or_filter(person::display_name.ilike(searcher)); .or_filter(person::display_name.ilike(searcher));
} }

View file

@ -1,4 +1,4 @@
use actix_web::{error::ErrorBadRequest, *}; use actix_web::{error::ErrorBadRequest, web, Error, HttpRequest, HttpResponse, Result};
use anyhow::anyhow; use anyhow::anyhow;
use chrono::{DateTime, NaiveDateTime, Utc}; use chrono::{DateTime, NaiveDateTime, Utc};
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -102,7 +102,7 @@ async fn get_feed_data(
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
.namespaces(RSS_NAMESPACE.to_owned()) .namespaces(RSS_NAMESPACE.clone())
.title(&format!("{} - {}", site_view.site.name, listing_type)) .title(&format!("{} - {}", site_view.site.name, listing_type))
.link(context.settings().get_protocol_and_hostname()) .link(context.settings().get_protocol_and_hostname())
.items(items); .items(items);
@ -138,7 +138,7 @@ async fn get_feed(
_ => return Err(ErrorBadRequest(LemmyError::from(anyhow!("wrong_type")))), _ => return Err(ErrorBadRequest(LemmyError::from(anyhow!("wrong_type")))),
}; };
let jwt_secret = context.secret().jwt_secret.to_owned(); let jwt_secret = context.secret().jwt_secret.clone();
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let builder = match request_type { let builder = match request_type {
@ -176,7 +176,7 @@ async fn get_feed(
fn get_sort_type(info: web::Query<Params>) -> Result<SortType, ParseError> { fn get_sort_type(info: web::Query<Params>) -> Result<SortType, ParseError> {
let sort_query = info let sort_query = info
.sort .sort
.to_owned() .clone()
.unwrap_or_else(|| SortType::Hot.to_string()); .unwrap_or_else(|| SortType::Hot.to_string());
SortType::from_str(&sort_query) SortType::from_str(&sort_query)
} }
@ -205,7 +205,7 @@ async fn get_feed_user(
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
.namespaces(RSS_NAMESPACE.to_owned()) .namespaces(RSS_NAMESPACE.clone())
.title(&format!("{} - {}", site_view.site.name, person.name)) .title(&format!("{} - {}", site_view.site.name, person.name))
.link(person.actor_id.to_string()) .link(person.actor_id.to_string())
.items(items); .items(items);
@ -236,7 +236,7 @@ async fn get_feed_community(
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
.namespaces(RSS_NAMESPACE.to_owned()) .namespaces(RSS_NAMESPACE.clone())
.title(&format!("{} - {}", site_view.site.name, community.name)) .title(&format!("{} - {}", site_view.site.name, community.name))
.link(community.actor_id.to_string()) .link(community.actor_id.to_string())
.items(items); .items(items);
@ -274,7 +274,7 @@ async fn get_feed_front(
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
.namespaces(RSS_NAMESPACE.to_owned()) .namespaces(RSS_NAMESPACE.clone())
.title(&format!("{} - Subscribed", site_view.site.name)) .title(&format!("{} - Subscribed", site_view.site.name))
.link(protocol_and_hostname) .link(protocol_and_hostname)
.items(items); .items(items);
@ -327,7 +327,7 @@ async fn get_feed_inbox(
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
.namespaces(RSS_NAMESPACE.to_owned()) .namespaces(RSS_NAMESPACE.clone())
.title(&format!("{} - Inbox", site_view.site.name)) .title(&format!("{} - Inbox", site_view.site.name))
.link(format!("{}/inbox", protocol_and_hostname,)) .link(format!("{}/inbox", protocol_and_hostname,))
.items(items); .items(items);
@ -429,8 +429,8 @@ fn create_post_items(
i.pub_date(dt.to_rfc2822()); i.pub_date(dt.to_rfc2822());
let post_url = format!("{}/post/{}", protocol_and_hostname, p.post.id); let post_url = format!("{}/post/{}", protocol_and_hostname, p.post.id);
i.link(post_url.to_owned()); i.link(post_url.clone());
i.comments(post_url.to_owned()); i.comments(post_url.clone());
let guid = GuidBuilder::default() let guid = GuidBuilder::default()
.permalink(true) .permalink(true)
.value(&post_url) .value(&post_url)

View file

@ -1,4 +1,4 @@
use actix_web::{error::ErrorBadRequest, *}; use actix_web::{error::ErrorBadRequest, web, Error, HttpResponse, Result};
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_db_views::structs::SiteView; use lemmy_db_views::structs::SiteView;
use lemmy_utils::{error::LemmyError, version}; use lemmy_utils::{error::LemmyError, version};

View file

@ -62,7 +62,7 @@ async fn get_webfinger_response(
.collect(); .collect();
let json = WebfingerResponse { let json = WebfingerResponse {
subject: info.resource.to_owned(), subject: info.resource.clone(),
links, links,
}; };
@ -75,7 +75,7 @@ fn webfinger_link_for_actor(url: Option<Url>) -> Vec<WebfingerLink> {
WebfingerLink { WebfingerLink {
rel: Some("http://webfinger.net/rel/profile-page".to_string()), rel: Some("http://webfinger.net/rel/profile-page".to_string()),
kind: Some("text/html".to_string()), kind: Some("text/html".to_string()),
href: Some(url.to_owned()), href: Some(url.clone()),
}, },
WebfingerLink { WebfingerLink {
rel: Some("self".to_string()), rel: Some("self".to_string()),

View file

@ -24,9 +24,9 @@ pub fn send_email(
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let email_config = settings let email_config = settings
.email .email
.to_owned() .clone()
.ok_or_else(|| LemmyError::from_message("no_email_setup"))?; .ok_or_else(|| LemmyError::from_message("no_email_setup"))?;
let domain = settings.hostname.to_owned(); let domain = settings.hostname.clone();
let (smtp_server, smtp_port) = { let (smtp_server, smtp_port) = {
let email_and_port = email_config.smtp_server.split(':').collect::<Vec<&str>>(); let email_and_port = email_config.smtp_server.split(':').collect::<Vec<&str>>();

View file

@ -65,13 +65,13 @@ impl RateLimitStorage {
// The initial value // The initial value
if rate_limit.allowance == -2f64 { if rate_limit.allowance == -2f64 {
rate_limit.allowance = rate as f64; rate_limit.allowance = f64::from(rate);
}; };
rate_limit.last_checked = current; rate_limit.last_checked = current;
rate_limit.allowance += time_passed * (rate as f64 / per as f64); rate_limit.allowance += time_passed * (f64::from(rate) / f64::from(per));
if rate_limit.allowance > rate as f64 { if rate_limit.allowance > f64::from(rate) {
rate_limit.allowance = rate as f64; rate_limit.allowance = f64::from(rate);
} }
if rate_limit.allowance < 1.0 { if rate_limit.allowance < 1.0 {

View file

@ -81,24 +81,24 @@ impl Settings {
/// `lemmy-alpha` instead. It has no effect in production. /// `lemmy-alpha` instead. It has no effect in production.
pub fn get_hostname_without_port(&self) -> Result<String, anyhow::Error> { pub fn get_hostname_without_port(&self) -> Result<String, anyhow::Error> {
Ok( Ok(
self (*self
.hostname .hostname
.split(':') .split(':')
.collect::<Vec<&str>>() .collect::<Vec<&str>>()
.first() .first()
.context(location_info!())? .context(location_info!())?)
.to_string(), .to_string(),
) )
} }
pub fn webfinger_regex(&self) -> Regex { pub fn webfinger_regex(&self) -> Regex {
WEBFINGER_REGEX.to_owned() WEBFINGER_REGEX.clone()
} }
pub fn pictrs_config(&self) -> Result<PictrsConfig, LemmyError> { pub fn pictrs_config(&self) -> Result<PictrsConfig, LemmyError> {
self self
.pictrs .pictrs
.to_owned() .clone()
.ok_or_else(|| anyhow!("images_disabled").into()) .ok_or_else(|| anyhow!("images_disabled").into())
} }
} }

View file

@ -86,7 +86,7 @@ fn test_slur_filter() {
assert_eq!(slur_check(test, &slur_regex), Err(has_slurs_vec)); assert_eq!(slur_check(test, &slur_regex), Err(has_slurs_vec));
assert_eq!(slur_check(slur_free, &slur_regex), Ok(())); assert_eq!(slur_check(slur_free, &slur_regex), Ok(()));
if let Err(slur_vec) = slur_check(test, &slur_regex) { if let Err(slur_vec) = slur_check(test, &slur_regex) {
assert_eq!(&slurs_vec_to_str(slur_vec), has_slurs_err_str); assert_eq!(&slurs_vec_to_str(&slur_vec), has_slurs_err_str);
} }
} }

View file

@ -76,7 +76,7 @@ pub fn build_slur_regex(regex_str: Option<&str>) -> Option<Regex> {
pub fn check_slurs(text: &str, slur_regex: &Option<Regex>) -> Result<(), LemmyError> { pub fn check_slurs(text: &str, slur_regex: &Option<Regex>) -> Result<(), LemmyError> {
if let Err(slurs) = slur_check(text, slur_regex) { if let Err(slurs) = slur_check(text, slur_regex) {
Err(LemmyError::from_error_message( Err(LemmyError::from_error_message(
anyhow::anyhow!("{}", slurs_vec_to_str(slurs)), anyhow::anyhow!("{}", slurs_vec_to_str(&slurs)),
"slurs", "slurs",
)) ))
} else { } else {
@ -94,7 +94,7 @@ pub fn check_slurs_opt(
} }
} }
pub(crate) fn slurs_vec_to_str(slurs: Vec<&str>) -> String { pub(crate) fn slurs_vec_to_str(slurs: &[&str]) -> String {
let start = "No slurs - "; let start = "No slurs - ";
let combined = &slurs.join(", "); let combined = &slurs.join(", ");
[start, combined].concat() [start, combined].concat()
@ -193,7 +193,7 @@ pub fn get_ip(conn_info: &ConnectionInfo) -> IpAddr {
} }
pub fn clean_url_params(url: &Url) -> Url { pub fn clean_url_params(url: &Url) -> Url {
let mut url_out = url.to_owned(); let mut url_out = url.clone();
if url.query().is_some() { if url.query().is_some() {
let new_query = url let new_query = url
.query_pairs() .query_pairs()

View file

@ -1,5 +1,5 @@
use crate::{ use crate::{
messages::*, messages::{CaptchaItem, StandardMessage, WsMessage},
serialize_websocket_message, serialize_websocket_message,
LemmyContext, LemmyContext,
OperationType, OperationType,
@ -8,7 +8,7 @@ use crate::{
}; };
use actix::prelude::*; use actix::prelude::*;
use anyhow::Context as acontext; use anyhow::Context as acontext;
use lemmy_api_common::{comment::*, post::*}; use lemmy_api_common::{comment::CommentResponse, post::PostResponse};
use lemmy_db_schema::{ use lemmy_db_schema::{
newtypes::{CommunityId, LocalUserId, PostId}, newtypes::{CommunityId, LocalUserId, PostId},
source::secret::Secret, source::secret::Secret,
@ -446,17 +446,17 @@ impl ChatServer {
ctx: &mut Context<Self>, ctx: &mut Context<Self>,
) -> impl Future<Output = Result<String, LemmyError>> { ) -> impl Future<Output = Result<String, LemmyError>> {
let ip: IpAddr = match self.sessions.get(&msg.id) { let ip: IpAddr = match self.sessions.get(&msg.id) {
Some(info) => info.ip.to_owned(), Some(info) => info.ip.clone(),
None => IpAddr("blank_ip".to_string()), None => IpAddr("blank_ip".to_string()),
}; };
let context = LemmyContext { let context = LemmyContext {
pool: self.pool.clone(), pool: self.pool.clone(),
chat_server: ctx.address(), chat_server: ctx.address(),
client: self.client.to_owned(), client: self.client.clone(),
settings: self.settings.to_owned(), settings: self.settings.clone(),
secret: self.secret.to_owned(), secret: self.secret.clone(),
rate_limit_cell: self.rate_limit_cell.to_owned(), rate_limit_cell: self.rate_limit_cell.clone(),
}; };
let message_handler_crud = self.message_handler_crud; let message_handler_crud = self.message_handler_crud;
let message_handler = self.message_handler; let message_handler = self.message_handler;

View file

@ -1,6 +1,25 @@
use crate::{ use crate::{
chat_server::{ChatServer, SessionInfo}, chat_server::{ChatServer, SessionInfo},
messages::*, messages::{
CaptchaItem,
CheckCaptcha,
Connect,
Disconnect,
GetCommunityUsersOnline,
GetPostUsersOnline,
GetUsersOnline,
JoinCommunityRoom,
JoinModRoom,
JoinPostRoom,
JoinUserRoom,
SendAllMessage,
SendComment,
SendCommunityRoomMessage,
SendModRoomMessage,
SendPost,
SendUserRoomMessage,
StandardMessage,
},
OperationType, OperationType,
}; };
use actix::{Actor, Context, Handler, ResponseFuture}; use actix::{Actor, Context, Handler, ResponseFuture};
@ -83,11 +102,10 @@ impl Handler<StandardMessage> for ChatServer {
type Result = ResponseFuture<Result<String, std::convert::Infallible>>; type Result = ResponseFuture<Result<String, std::convert::Infallible>>;
fn handle(&mut self, msg: StandardMessage, ctx: &mut Context<Self>) -> Self::Result { fn handle(&mut self, msg: StandardMessage, ctx: &mut Context<Self>) -> Self::Result {
use tracing::Instrument;
let fut = self.parse_json_message(msg, ctx); let fut = self.parse_json_message(msg, ctx);
let span = root_span(); let span = root_span();
use tracing::Instrument;
Box::pin( Box::pin(
async move { async move {
match fut.await { match fut.await {

View file

@ -24,11 +24,11 @@ pub async fn chat_route(
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
ws::start( ws::start(
WsSession { WsSession {
cs_addr: context.chat_server().to_owned(), cs_addr: context.chat_server().clone(),
id: 0, id: 0,
hb: Instant::now(), hb: Instant::now(),
ip: get_ip(&req.connection_info()), ip: get_ip(&req.connection_info()),
rate_limiter: rate_limiter.as_ref().to_owned(), rate_limiter: rate_limiter.as_ref().clone(),
}, },
&req, &req,
stream, stream,
@ -70,7 +70,7 @@ impl Actor for WsSession {
.cs_addr .cs_addr
.send(Connect { .send(Connect {
addr: addr.recipient(), addr: addr.recipient(),
ip: self.ip.to_owned(), ip: self.ip.clone(),
}) })
.into_actor(self) .into_actor(self)
.then(|res, act, ctx| { .then(|res, act, ctx| {
@ -88,7 +88,7 @@ impl Actor for WsSession {
// notify chat server // notify chat server
self.cs_addr.do_send(Disconnect { self.cs_addr.do_send(Disconnect {
id: self.id, id: self.id,
ip: self.ip.to_owned(), ip: self.ip.clone(),
}); });
Running::Stop Running::Stop
} }
@ -169,7 +169,7 @@ impl WsSession {
// notify chat server // notify chat server
act.cs_addr.do_send(Disconnect { act.cs_addr.do_send(Disconnect {
id: act.id, id: act.id,
ip: act.ip.to_owned(), ip: act.ip.clone(),
}); });
// stop actor // stop actor
@ -185,7 +185,7 @@ impl WsSession {
/// Check the rate limit, and stop the ctx if it fails /// Check the rate limit, and stop the ctx if it fails
fn rate_limit_check(&mut self, ctx: &mut ws::WebsocketContext<Self>) -> bool { fn rate_limit_check(&mut self, ctx: &mut ws::WebsocketContext<Self>) -> bool {
let check = self.rate_limiter.message().check(self.ip.to_owned()); let check = self.rate_limiter.message().check(self.ip.clone());
if !check { if !check {
debug!("Websocket join with IP: {} has been rate limited.", self.ip); debug!("Websocket join with IP: {} has been rate limited.", self.ip);
ctx.stop() ctx.stop()

9
scripts/fix-clippy.sh Executable file
View file

@ -0,0 +1,9 @@
#!/bin/bash
set -e
cargo workspaces exec cargo clippy --fix --allow-dirty --tests --all-targets --all-features -- \
-D warnings -D deprecated -D clippy::perf -D clippy::complexity \
-D clippy::dbg_macro -D clippy::inefficient_to_string \
-D clippy::items-after-statements -D clippy::implicit_clone \
-D clippy::wildcard_imports -D clippy::cast_lossless \
-D clippy::manual_string_new -D clippy::redundant_closure_for_method_calls

View file

@ -1,13 +1,100 @@
use actix_web::*; use actix_web::{guard, web, Error, HttpResponse, Result};
use lemmy_api::Perform; use lemmy_api::Perform;
use lemmy_api_common::{ use lemmy_api_common::{
comment::*, comment::{
community::*, CreateComment,
person::*, CreateCommentLike,
post::*, CreateCommentReport,
private_message::*, DeleteComment,
site::*, EditComment,
websocket::*, GetComment,
GetComments,
ListCommentReports,
RemoveComment,
ResolveCommentReport,
SaveComment,
},
community::{
AddModToCommunity,
BanFromCommunity,
BlockCommunity,
CreateCommunity,
DeleteCommunity,
EditCommunity,
FollowCommunity,
GetCommunity,
HideCommunity,
ListCommunities,
RemoveCommunity,
TransferCommunity,
},
person::{
AddAdmin,
BanPerson,
BlockPerson,
ChangePassword,
DeleteAccount,
GetBannedPersons,
GetCaptcha,
GetPersonDetails,
GetPersonMentions,
GetReplies,
GetReportCount,
GetUnreadCount,
Login,
MarkAllAsRead,
MarkCommentReplyAsRead,
MarkPersonMentionAsRead,
PasswordChangeAfterReset,
PasswordReset,
Register,
SaveUserSettings,
VerifyEmail,
},
post::{
CreatePost,
CreatePostLike,
CreatePostReport,
DeletePost,
EditPost,
GetPost,
GetPosts,
GetSiteMetadata,
ListPostReports,
LockPost,
MarkPostAsRead,
RemovePost,
ResolvePostReport,
SavePost,
StickyPost,
},
private_message::{
CreatePrivateMessage,
CreatePrivateMessageReport,
DeletePrivateMessage,
EditPrivateMessage,
GetPrivateMessages,
ListPrivateMessageReports,
MarkPrivateMessageAsRead,
ResolvePrivateMessageReport,
},
site::{
ApproveRegistrationApplication,
CreateSite,
EditSite,
GetModlog,
GetSite,
GetUnreadRegistrationApplicationCount,
LeaveAdmin,
ListRegistrationApplications,
PurgeComment,
PurgeCommunity,
PurgePerson,
PurgePost,
ResolveObject,
Search,
},
websocket::{CommunityJoin, ModJoin, PostJoin, UserJoin},
}; };
use lemmy_api_crud::PerformCrud; use lemmy_api_crud::PerformCrud;
use lemmy_utils::rate_limit::RateLimitCell; use lemmy_utils::rate_limit::RateLimitCell;

Some files were not shown because too many files have changed in this diff Show more