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
# 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
image: rust:1.64-buster
image: rust:1.65-buster
commands:
- apt-get update
- apt-get -y install protobuf-compiler libprotobuf-dev
- 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
- name: cargo test

View file

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

View file

@ -1,14 +1,72 @@
use actix_web::{web, web::Data};
use captcha::Captcha;
use lemmy_api_common::{
comment::*,
community::*,
person::*,
post::*,
private_message::*,
site::*,
comment::{
CreateCommentLike,
CreateCommentReport,
ListCommentReports,
ResolveCommentReport,
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,
websocket::*,
websocket::{CommunityJoin, ModJoin, PostJoin, UserJoin},
};
use lemmy_db_schema::source::local_site::LocalSite;
use lemmy_utils::{error::LemmyError, utils::check_slurs, ConnectionId};

View file

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

View file

@ -41,7 +41,7 @@ impl Perform for ChangePassword {
}
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 =
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 {
answer,
uuid: uuid.to_owned(),
uuid: uuid.clone(),
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 matrix_user_id = diesel_option_overwrite(&data.matrix_user_id);
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);
if let Some(Some(email)) = &email {
@ -116,8 +116,8 @@ impl Perform for SaveUserSettings {
.show_scores(data.show_scores)
.default_sort_type(default_sort_type)
.default_listing_type(default_listing_type)
.theme(data.theme.to_owned())
.interface_language(data.interface_language.to_owned())
.theme(data.theme.clone())
.interface_language(data.interface_language.clone())
.build();
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?;
// Mod tables
let reason = data.reason.to_owned();
let reason = data.reason.clone();
let form = AdminPurgeCommentForm {
admin_person_id: local_user_view.person.id,
reason,

View file

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

View file

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

View file

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

View file

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

View file

@ -45,7 +45,7 @@ impl Perform for Search {
// TODO no clean / non-nsfw searching rn
let q = data.q.to_owned();
let q = data.q.clone();
let page = data.page;
let limit = data.limit;
let sort = data.sort;
@ -122,7 +122,7 @@ impl Perform for Search {
// If the community or creator is included, dont search communities or users
let community_or_creator_included =
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();
posts = PostQuery::builder()
@ -140,8 +140,8 @@ impl Perform for Search {
.list()
.await?;
let q = data.q.to_owned();
let community_actor_id = community_actor_id.to_owned();
let q = data.q.clone();
let community_actor_id = community_actor_id.clone();
let local_user_ = local_user.clone();
comments = CommentQuery::builder()
@ -159,7 +159,7 @@ impl Perform for Search {
.list()
.await?;
let q = data.q.to_owned();
let q = data.q.clone();
communities = if community_or_creator_included {
vec![]
@ -177,7 +177,7 @@ impl Perform for Search {
.await?
};
let q = data.q.to_owned();
let q = data.q.clone();
users = if community_or_creator_included {
vec![]
@ -216,21 +216,21 @@ impl Perform for Search {
.iter_mut()
.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
.iter_mut()
.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
.iter_mut()
.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 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_websocket::{
messages::{JoinCommunityRoom, JoinModRoom, JoinPostRoom, JoinUserRoom},

View file

@ -72,12 +72,12 @@ fn html_to_site_metadata(html_bytes: &[u8]) -> Result<SiteMetadata, LemmyError>
.opengraph
.properties
.get("description")
.map(|t| t.to_string());
.map(std::string::ToString::to_string);
let og_title = page
.opengraph
.properties
.get("title")
.map(|t| t.to_string());
.map(std::string::ToString::to_string);
let og_image = page
.opengraph
.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
Some(metadata_image) => fetch_pictrs(client, settings, metadata_image)
.await
.map(|r| r.files[0].file.to_owned()),
.map(|r| r.files[0].file.clone()),
// Metadata, but no image
None => fetch_pictrs(client, settings, url)
.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
None => fetch_pictrs(client, settings, url)
.await
.map(|r| r.files[0].file.to_owned()),
.map(|r| r.files[0].file.clone()),
};
// The full urls are necessary for federation
@ -271,7 +271,7 @@ mod tests {
// These helped with testing
#[actix_rt::test]
async fn test_site_metadata() {
let settings = &SETTINGS.to_owned();
let settings = &SETTINGS.clone();
let client = reqwest::Client::builder()
.user_agent(build_user_agent(settings))
.build()

View file

@ -351,7 +351,7 @@ pub async fn send_password_reset_email(
let local_user_id = user.local_user.id;
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 subject = &lang.password_reset_subject(&user.person.name);
let protocol_and_hostname = settings.get_protocol_and_hostname();
@ -391,7 +391,7 @@ pub fn send_email_verification_success(
user: &LocalUserView,
settings: &Settings,
) -> 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 subject = &lang.email_verified_subject(&user.person.actor_id);
let body = &lang.email_verified_body();
@ -449,7 +449,7 @@ pub fn send_application_approved_email(
user: &LocalUserView,
settings: &Settings,
) -> 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 subject = lang.registration_approved_subject(&user.person.actor_id);
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 {
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 subject = lang.new_application_subject(applicant_username, &settings.hostname);
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 content_slurs_removed = remove_slurs(
&data.content.to_owned(),
&data.content.clone(),
&local_site_to_slur_regex(&local_site),
);
@ -102,7 +102,7 @@ impl PerformCrud for CreateComment {
.await?;
let comment_form = CommentInsertForm::builder()
.content(content_slurs_removed.to_owned())
.content(content_slurs_removed.clone())
.post_id(data.post_id)
.creator_id(local_user_view.person.id)
.language_id(Some(language_id))
@ -110,7 +110,7 @@ impl PerformCrud for CreateComment {
// Create the comment
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())
.await
.map_err(|e| LemmyError::from_error_message(e, "couldnt_create_comment"))?;
@ -200,7 +200,7 @@ impl PerformCrud for CreateComment {
inserted_comment.id,
UserOperationCrud::CreateComment,
websocket_id,
data.form_id.to_owned(),
data.form_id.clone(),
Some(local_user_view.person.id),
recipient_ids,
context,

View file

@ -59,7 +59,7 @@ impl PerformCrud for GetComments {
None
};
let parent_path_cloned = parent_path.to_owned();
let parent_path_cloned = parent_path.clone();
let post_id = data.post_id;
let local_user = local_user_view.map(|l| l.local_user);
let mut comments = CommentQuery::builder()
@ -85,7 +85,7 @@ impl PerformCrud for GetComments {
.iter_mut()
.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 })

View file

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

View file

@ -102,7 +102,7 @@ impl PerformCrud for EditComment {
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
// 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 recipient_ids = send_local_notifs(
mentions,
@ -128,7 +128,7 @@ impl PerformCrud for EditComment {
data.comment_id,
UserOperationCrud::EditComment,
websocket_id,
data.form_id.to_owned(),
data.form_id.clone(),
None,
recipient_ids,
context,

View file

@ -85,13 +85,13 @@ impl PerformCrud for CreateCommunity {
let keypair = generate_actor_keypair()?;
let community_form = CommunityInsertForm::builder()
.name(data.name.to_owned())
.title(data.title.to_owned())
.description(data.description.to_owned())
.name(data.name.clone())
.title(data.title.clone())
.description(data.description.clone())
.icon(icon)
.banner(banner)
.nsfw(data.nsfw)
.actor_id(Some(community_actor_id.to_owned()))
.actor_id(Some(community_actor_id.clone()))
.private_key(Some(keypair.private_key))
.public_key(keypair.public_key)
.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)?;
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 listing_type = data.type_;
@ -51,7 +51,7 @@ impl PerformCrud for ListCommunities {
.iter_mut()
.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 {
Some(id) => id,
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)
.await
.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,
community_id: data.community_id,
removed: Some(removed),
reason: data.reason.to_owned(),
reason: data.reason.clone(),
expires,
};
ModRemoveCommunity::create(context.pool(), &form).await?;
@ -71,7 +71,7 @@ impl PerformCrud for RemoveCommunity {
local_user_view.person,
updated_community,
deletable,
data.reason.clone().or_else(|| Some("".to_string())),
data.reason.clone().or_else(|| Some(String::new())),
removed,
context,
)

View file

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

View file

@ -1,5 +1,24 @@
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_websocket::{serialize_websocket_message, LemmyContext, UserOperationCrud};
use serde::Deserialize;

View file

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

View file

@ -74,14 +74,14 @@ impl PerformCrud for GetPosts {
.iter_mut()
.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
.iter_mut()
.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,
post_id: data.post_id,
removed: Some(removed),
reason: data.reason.to_owned(),
reason: data.reason.clone(),
};
ModRemovePost::create(context.pool(), &form).await?;
@ -83,7 +83,7 @@ impl PerformCrud for RemovePost {
local_user_view.person,
community,
deletable,
data.reason.clone().or_else(|| Some("".to_string())),
data.reason.clone().or_else(|| Some(String::new())),
removed,
context,
)

View file

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

View file

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

View file

@ -51,7 +51,7 @@ impl PerformCrud for GetPrivateMessages {
.filter(|pmv| pmv.private_message.deleted)
{
pmv.private_message = pmv
.to_owned()
.clone()
.private_message
.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 keypair = generate_actor_keypair()?;
let site_form = SiteUpdateForm::builder()
.name(Some(data.name.to_owned()))
.name(Some(data.name.clone()))
.sidebar(sidebar)
.description(description)
.icon(icon)
@ -116,7 +116,7 @@ impl PerformCrud for CreateSite {
.federation_http_fetch_retry_limit(data.federation_http_fetch_retry_limit)
.federation_worker_count(data.federation_worker_count)
.captcha_enabled(data.captcha_enabled)
.captcha_difficulty(data.captcha_difficulty.to_owned())
.captcha_difficulty(data.captcha_difficulty.clone())
.build();
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?;
}
let name = data.name.to_owned();
let name = data.name.clone();
let site_form = SiteUpdateForm::builder()
.name(name)
.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_worker_count(data.federation_worker_count)
.captcha_enabled(data.captcha_enabled)
.captcha_difficulty(data.captcha_difficulty.to_owned())
.captcha_difficulty(data.captcha_difficulty.clone())
.build();
let update_local_site = LocalSite::update(context.pool(), &local_site_form)
@ -145,9 +145,9 @@ impl PerformCrud for EditSite {
.ok();
// 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?;
let blocked = data.blocked_instances.to_owned();
let blocked = data.blocked_instances.clone();
FederationBlockList::replace(context.pool(), blocked).await?;
// TODO can't think of a better way to do this.

View file

@ -77,8 +77,8 @@ impl PerformCrud for Register {
let check = context
.chat_server()
.send(CheckCaptcha {
uuid: data.captcha_uuid.to_owned().unwrap_or_default(),
answer: data.captcha_answer.to_owned().unwrap_or_default(),
uuid: data.captcha_uuid.clone().unwrap_or_default(),
answer: data.captcha_answer.clone().unwrap_or_default(),
})
.await?;
if !check {
@ -104,7 +104,7 @@ impl PerformCrud for Register {
// Register the new person
let person_form = PersonInsertForm::builder()
.name(data.username.to_owned())
.name(data.username.clone())
.actor_id(Some(actor_id.clone()))
.private_key(Some(actor_keypair.private_key))
.public_key(actor_keypair.public_key)
@ -123,7 +123,7 @@ impl PerformCrud for Register {
// Create the local user
let local_user_form = LocalUserInsertForm::builder()
.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())
.show_nsfw(Some(data.show_nsfw))
.build();
@ -151,7 +151,7 @@ impl PerformCrud for Register {
let form = RegistrationApplicationInsertForm {
local_user_id: inserted_local_user.id,
// 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?;

View file

@ -64,7 +64,7 @@ impl PerformCrud for GetPersonDetails {
let saved_only = data.saved_only;
let community_id = data.community_id;
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()
.pool(context.pool())

View file

@ -182,7 +182,7 @@ mod tests {
file_to_json_object("assets/lemmy/collections/group_moderators.json").unwrap();
let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
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)
.await
.unwrap();

View file

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

View file

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

View file

@ -135,7 +135,7 @@ impl ApubObject for ApubCommunity {
context: &LemmyContext,
request_counter: &mut i32,
) -> 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 form = Group::into_insert_form(group.clone(), instance.id);
@ -180,16 +180,16 @@ impl Actor for ApubCommunity {
}
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 {
fn actor_id(&self) -> Url {
self.actor_id.to_owned().into()
self.actor_id.clone().into()
}
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,
_request_counter: &mut i32,
) -> 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 site_form = SiteInsertForm {
@ -160,10 +160,10 @@ impl ApubObject for ApubSite {
impl ActorType for ApubSite {
fn actor_id(&self) -> Url {
self.actor_id.to_owned().into()
self.actor_id.clone().into()
}
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.
pub(crate) async fn init_context() -> LemmyContext {
async fn x() -> Result<String, LemmyError> {
Ok(String::new())
}
// call this to run migrations
let pool = build_db_pool_for_tests().await;
let settings = SETTINGS.to_owned();
let settings = SETTINGS.clone();
let client = Client::builder()
.user_agent(build_user_agent(&settings))
.build()
@ -97,11 +100,8 @@ pub(crate) mod tests {
let client = ClientBuilder::new(client).with(BlockedMiddleware).build();
let secret = Secret {
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_cell = RateLimitCell::new(rate_limit_config).await;

View file

@ -144,7 +144,7 @@ impl ApubObject for ApubPerson {
context: &LemmyContext,
request_counter: &mut i32,
) -> 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 person_form = PersonInsertForm {
@ -181,11 +181,11 @@ impl ApubObject for ApubPerson {
impl ActorType for ApubPerson {
fn actor_id(&self) -> Url {
self.actor_id.to_owned().into()
self.actor_id.clone().into()
}
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> {
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)),
media_type: Some(MediaTypeMarkdownOrHtml::Html),
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(),
image: self.thumbnail_url.clone().map(ImageObject::new),
comments_enabled: Some(!self.locked),
@ -167,7 +167,7 @@ impl ApubObject for ApubPost {
let community = page.extract_community(context, request_counter).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() {
first_attachment
} else if page.kind == PageType::Video {

View file

@ -63,13 +63,13 @@ impl Note {
);
match parent.deref() {
PostOrComment::Post(p) => {
let post = p.deref().to_owned();
let post = p.deref().clone();
Ok((post, None))
}
PostOrComment::Comment(c) => {
let post_id = c.post_id;
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)))
}
}

View file

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

View file

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

View file

@ -2,10 +2,29 @@ use crate::{
diesel::JoinOnDsl,
newtypes::{CommunityId, InstanceId, LanguageId, LocalUserId, SiteId},
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},
};
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 lemmy_utils::error::LemmyError;
use tokio::sync::OnceCell;
@ -15,7 +34,11 @@ impl LocalUserLanguage {
pool: &DbPool,
for_local_user_id: LocalUserId,
) -> 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?;
conn
@ -48,7 +71,7 @@ impl LocalUserLanguage {
.build_transaction()
.run(|conn| {
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
delete(local_user_language.filter(local_user_id.eq(for_local_user_id)))
.execute(conn)
@ -109,7 +132,7 @@ impl SiteLanguage {
.build_transaction()
.run(|conn| {
Box::pin(async move {
use crate::schema::site_language::dsl::*;
use crate::schema::site_language::dsl::{site_id, site_language};
// Clear the current languages
delete(site_language.filter(site_id.eq(for_site_id)))
@ -144,7 +167,7 @@ impl CommunityLanguage {
for_language_id: Option<LanguageId>,
for_community_id: CommunityId,
) -> 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?;
if let Some(for_language_id) = for_language_id {
@ -200,7 +223,7 @@ impl CommunityLanguage {
pool: &DbPool,
for_community_id: CommunityId,
) -> 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 langs = community_language
@ -227,7 +250,7 @@ impl CommunityLanguage {
.build_transaction()
.run(|conn| {
Box::pin(async move {
use crate::schema::community_language::dsl::*;
use crate::schema::community_language::dsl::{community_id, community_language};
// Clear the current languages
delete(community_language.filter(community_id.eq(for_community_id)))
.execute(conn)
@ -255,8 +278,8 @@ pub async fn default_post_language(
community_id: CommunityId,
local_user_id: LocalUserId,
) -> 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};
let conn = &mut get_conn(pool).await?;
let intersection = ul::local_user_language
.inner_join(cl::community_language.on(ul::language_id.eq(cl::language_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();
let count = ALL_LANGUAGES_COUNT
.get_or_init(|| async {
use crate::schema::language::dsl::*;
use crate::schema::language::dsl::{id, language};
let count: i64 = language
.select(count(id))
.first(conn)
@ -318,7 +341,20 @@ async fn convert_read_languages(
#[cfg(test)]
mod tests {
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::{
community::{Community, CommunityInsertForm},
instance::Instance,
@ -382,10 +418,10 @@ mod tests {
#[tokio::test]
#[serial]
async fn test_convert_read_languages() {
use crate::schema::language::dsl::{id, language};
let pool = &build_db_pool_for_tests().await;
// call with all languages, returns empty vec
use crate::schema::language::dsl::*;
let conn = &mut get_conn(pool).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();

View file

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

View file

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

View file

@ -1,11 +1,16 @@
use crate::{
newtypes::{CommentReportId, PersonId},
schema::comment_report::dsl::*,
schema::comment_report::dsl::{comment_report, resolved, resolver_id, updated},
source::comment_report::{CommentReport, CommentReportForm},
traits::Reportable,
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;
#[async_trait]

View file

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

View file

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

View file

@ -1,10 +1,21 @@
use crate::{
newtypes::LocalUserId,
schema::email_verification::dsl::*,
source::email_verification::*,
schema::email_verification::dsl::{
email_verification,
local_user_id,
published,
verification_token,
},
source::email_verification::{EmailVerification, EmailVerificationForm},
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;
impl EmailVerification {

View file

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

View file

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

View file

@ -4,7 +4,7 @@ use crate::{
source::instance::{Instance, InstanceForm},
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 lemmy_utils::utils::generate_domain_url;
use url::Url;

View file

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

View file

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

View file

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

View file

@ -1,6 +1,12 @@
use crate::{
newtypes::LocalUserId,
schema::local_user::dsl::*,
schema::local_user::dsl::{
accepted_application,
email_verified,
local_user,
password_encrypted,
validator_time,
},
source::{
actor_language::{LocalUserLanguage, SiteLanguage},
local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm},
@ -9,12 +15,30 @@ use crate::{
utils::{get_conn, naive_now, DbPool},
};
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;
mod safe_settings_type {
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,
traits::ToSafeSettings,
};

View file

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

View file

@ -1,11 +1,16 @@
use crate::{
newtypes::LocalUserId,
schema::password_reset_request::dsl::*,
source::password_reset_request::*,
schema::password_reset_request::dsl::{password_reset_request, published, token_encrypted},
source::password_reset_request::{PasswordResetRequest, PasswordResetRequestForm},
traits::Crud,
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 sha2::{Digest, Sha256};
@ -86,7 +91,7 @@ mod tests {
instance::Instance,
local_user::{LocalUser, LocalUserInsertForm},
password_reset_request::PasswordResetRequest,
person::*,
person::{Person, PersonInsertForm},
},
traits::Crud,
utils::build_db_pool_for_tests,

View file

@ -1,15 +1,51 @@
use crate::{
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},
traits::{ApubActor, Crud},
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;
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 = (
id,
@ -186,7 +222,10 @@ impl ApubActor for Person {
#[cfg(test)]
mod tests {
use crate::{
source::{instance::Instance, person::*},
source::{
instance::Instance,
person::{Person, PersonInsertForm, PersonUpdateForm},
},
traits::Crud,
utils::build_db_pool_for_tests,
};
@ -217,7 +256,7 @@ mod tests {
deleted: false,
published: inserted_person.published,
updated: None,
actor_id: inserted_person.actor_id.to_owned(),
actor_id: inserted_person.actor_id.clone(),
bio: None,
local: true,
bot_account: false,
@ -225,7 +264,7 @@ mod tests {
private_key: None,
public_key: "nada".to_owned(),
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,
matrix_user_id: None,
ban_expires: None,
@ -235,7 +274,7 @@ mod tests {
let read_person = Person::read(pool, inserted_person.id).await.unwrap();
let update_person_form = PersonUpdateForm::builder()
.actor_id(Some(inserted_person.actor_id.to_owned()))
.actor_id(Some(inserted_person.actor_id.clone()))
.build();
let updated_person = Person::update(pool, inserted_person.id, &update_person_form)
.await

View file

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

View file

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

View file

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

View file

@ -1,11 +1,16 @@
use crate::{
newtypes::{PersonId, PostReportId},
schema::post_report::dsl::*,
source::post_report::*,
schema::post_report::dsl::{post_report, resolved, resolver_id, updated},
source::post_report::{PostReport, PostReportForm},
traits::Reportable,
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;
#[async_trait]

View file

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

View file

@ -1,11 +1,16 @@
use crate::{
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},
traits::Reportable,
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;
#[async_trait]

View file

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

View file

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

View file

@ -1,11 +1,14 @@
use crate::{
newtypes::{DbUrl, SiteId},
schema::site::dsl::*,
source::{actor_language::SiteLanguage, site::*},
schema::site::dsl::{actor_id, id, site},
source::{
actor_language::SiteLanguage,
site::{Site, SiteInsertForm, SiteUpdateForm},
},
traits::Crud,
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 url::Url;

View file

@ -120,7 +120,7 @@ pub struct LtreeDef(pub String);
impl Display for DbUrl {
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(
pool: &DbPool,
) -> Result<PooledConnection<AsyncDieselConnectionManager<AsyncPgConnection>>, DieselError> {
// TODO Maybe find a better diesel error for this
pool.get().await.map_err(|_| DieselError::NotInTransaction)
pool.get().await.map_err(|e| QueryBuilderError(e.into()))
}
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
Some(unwrapped) => {
if !unwrapped.eq("") {
Some(Some(unwrapped.to_owned()))
Some(Some(unwrapped.clone()))
} else {
Some(None)
}
@ -106,7 +105,7 @@ pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
pub fn diesel_option_overwrite_to_url(
opt: &Option<String>,
) -> 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
Some("") => Ok(Some(None)),
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(
opt: &Option<String>,
) -> 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
Some("") => Ok(None),
Some(str_url) => match Url::parse(str_url) {
@ -207,7 +206,7 @@ static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
});
pub mod functions {
use diesel::sql_types::*;
use diesel::sql_types::{BigInt, Text, Timestamp};
sql_function! {
fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
@ -265,7 +264,7 @@ mod tests {
#[test]
fn test_diesel_option_overwrite() {
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!(
diesel_option_overwrite(&Some("test".to_string())),
Some(Some("test".to_string()))
@ -276,7 +275,7 @@ mod tests {
fn test_diesel_option_overwrite_to_url() {
assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
assert!(matches!(
diesel_option_overwrite_to_url(&Some("".to_string())),
diesel_option_overwrite_to_url(&Some(String::new())),
Ok(Some(None))
));
assert!(matches!(

View file

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

View file

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

View file

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

View file

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

View file

@ -67,7 +67,7 @@ impl PrivateMessageReportView {
/// Returns the current unresolved post report count for the communities you mod
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?;
private_message_report::table

View file

@ -53,7 +53,7 @@ impl PrivateMessageView {
/// Gets the number of unread messages
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?;
private_message::table
.filter(private_message::read.eq(false))

View file

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

View file

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

View file

@ -1,5 +1,5 @@
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 lemmy_db_schema::{
newtypes::{CommunityId, PersonId},

View file

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

View file

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

View file

@ -1,6 +1,6 @@
use crate::structs::PersonViewSafe;
use diesel::{
dsl::*,
dsl::{now, IntervalDsl},
result::Error,
BoolExpressionMethods,
ExpressionMethods,
@ -90,7 +90,7 @@ impl<'a> PersonQuery<'a> {
if let Some(search_term) = self.search_term {
let searcher = fuzzy_search(&search_term);
query = query
.filter(person::name.ilike(searcher.to_owned()))
.filter(person::name.ilike(searcher.clone()))
.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 chrono::{DateTime, NaiveDateTime, Utc};
use lemmy_db_schema::{
@ -102,7 +102,7 @@ async fn get_feed_data(
let mut channel_builder = ChannelBuilder::default();
channel_builder
.namespaces(RSS_NAMESPACE.to_owned())
.namespaces(RSS_NAMESPACE.clone())
.title(&format!("{} - {}", site_view.site.name, listing_type))
.link(context.settings().get_protocol_and_hostname())
.items(items);
@ -138,7 +138,7 @@ async fn get_feed(
_ => 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 builder = match request_type {
@ -176,7 +176,7 @@ async fn get_feed(
fn get_sort_type(info: web::Query<Params>) -> Result<SortType, ParseError> {
let sort_query = info
.sort
.to_owned()
.clone()
.unwrap_or_else(|| SortType::Hot.to_string());
SortType::from_str(&sort_query)
}
@ -205,7 +205,7 @@ async fn get_feed_user(
let mut channel_builder = ChannelBuilder::default();
channel_builder
.namespaces(RSS_NAMESPACE.to_owned())
.namespaces(RSS_NAMESPACE.clone())
.title(&format!("{} - {}", site_view.site.name, person.name))
.link(person.actor_id.to_string())
.items(items);
@ -236,7 +236,7 @@ async fn get_feed_community(
let mut channel_builder = ChannelBuilder::default();
channel_builder
.namespaces(RSS_NAMESPACE.to_owned())
.namespaces(RSS_NAMESPACE.clone())
.title(&format!("{} - {}", site_view.site.name, community.name))
.link(community.actor_id.to_string())
.items(items);
@ -274,7 +274,7 @@ async fn get_feed_front(
let mut channel_builder = ChannelBuilder::default();
channel_builder
.namespaces(RSS_NAMESPACE.to_owned())
.namespaces(RSS_NAMESPACE.clone())
.title(&format!("{} - Subscribed", site_view.site.name))
.link(protocol_and_hostname)
.items(items);
@ -327,7 +327,7 @@ async fn get_feed_inbox(
let mut channel_builder = ChannelBuilder::default();
channel_builder
.namespaces(RSS_NAMESPACE.to_owned())
.namespaces(RSS_NAMESPACE.clone())
.title(&format!("{} - Inbox", site_view.site.name))
.link(format!("{}/inbox", protocol_and_hostname,))
.items(items);
@ -429,8 +429,8 @@ fn create_post_items(
i.pub_date(dt.to_rfc2822());
let post_url = format!("{}/post/{}", protocol_and_hostname, p.post.id);
i.link(post_url.to_owned());
i.comments(post_url.to_owned());
i.link(post_url.clone());
i.comments(post_url.clone());
let guid = GuidBuilder::default()
.permalink(true)
.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 lemmy_db_views::structs::SiteView;
use lemmy_utils::{error::LemmyError, version};

View file

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

View file

@ -24,9 +24,9 @@ pub fn send_email(
) -> Result<(), LemmyError> {
let email_config = settings
.email
.to_owned()
.clone()
.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 email_and_port = email_config.smtp_server.split(':').collect::<Vec<&str>>();

View file

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

View file

@ -81,24 +81,24 @@ impl Settings {
/// `lemmy-alpha` instead. It has no effect in production.
pub fn get_hostname_without_port(&self) -> Result<String, anyhow::Error> {
Ok(
self
(*self
.hostname
.split(':')
.collect::<Vec<&str>>()
.first()
.context(location_info!())?
.to_string(),
.context(location_info!())?)
.to_string(),
)
}
pub fn webfinger_regex(&self) -> Regex {
WEBFINGER_REGEX.to_owned()
WEBFINGER_REGEX.clone()
}
pub fn pictrs_config(&self) -> Result<PictrsConfig, LemmyError> {
self
.pictrs
.to_owned()
.clone()
.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(slur_free, &slur_regex), Ok(()));
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> {
if let Err(slurs) = slur_check(text, slur_regex) {
Err(LemmyError::from_error_message(
anyhow::anyhow!("{}", slurs_vec_to_str(slurs)),
anyhow::anyhow!("{}", slurs_vec_to_str(&slurs)),
"slurs",
))
} 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 combined = &slurs.join(", ");
[start, combined].concat()
@ -193,7 +193,7 @@ pub fn get_ip(conn_info: &ConnectionInfo) -> IpAddr {
}
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() {
let new_query = url
.query_pairs()

View file

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

View file

@ -1,6 +1,25 @@
use crate::{
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,
};
use actix::{Actor, Context, Handler, ResponseFuture};
@ -83,11 +102,10 @@ impl Handler<StandardMessage> for ChatServer {
type Result = ResponseFuture<Result<String, std::convert::Infallible>>;
fn handle(&mut self, msg: StandardMessage, ctx: &mut Context<Self>) -> Self::Result {
use tracing::Instrument;
let fut = self.parse_json_message(msg, ctx);
let span = root_span();
use tracing::Instrument;
Box::pin(
async move {
match fut.await {

View file

@ -24,11 +24,11 @@ pub async fn chat_route(
) -> Result<HttpResponse, Error> {
ws::start(
WsSession {
cs_addr: context.chat_server().to_owned(),
cs_addr: context.chat_server().clone(),
id: 0,
hb: Instant::now(),
ip: get_ip(&req.connection_info()),
rate_limiter: rate_limiter.as_ref().to_owned(),
rate_limiter: rate_limiter.as_ref().clone(),
},
&req,
stream,
@ -70,7 +70,7 @@ impl Actor for WsSession {
.cs_addr
.send(Connect {
addr: addr.recipient(),
ip: self.ip.to_owned(),
ip: self.ip.clone(),
})
.into_actor(self)
.then(|res, act, ctx| {
@ -88,7 +88,7 @@ impl Actor for WsSession {
// notify chat server
self.cs_addr.do_send(Disconnect {
id: self.id,
ip: self.ip.to_owned(),
ip: self.ip.clone(),
});
Running::Stop
}
@ -169,7 +169,7 @@ impl WsSession {
// notify chat server
act.cs_addr.do_send(Disconnect {
id: act.id,
ip: act.ip.to_owned(),
ip: act.ip.clone(),
});
// stop actor
@ -185,7 +185,7 @@ impl WsSession {
/// Check the rate limit, and stop the ctx if it fails
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 {
debug!("Websocket join with IP: {} has been rate limited.", self.ip);
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_common::{
comment::*,
community::*,
person::*,
post::*,
private_message::*,
site::*,
websocket::*,
comment::{
CreateComment,
CreateCommentLike,
CreateCommentReport,
DeleteComment,
EditComment,
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_utils::rate_limit::RateLimitCell;

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