From 5a33fce8bd09e2333787f424c6268f6232e94253 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Wed, 10 Feb 2021 11:05:12 -0500 Subject: [PATCH 01/18] Listing columns. --- crates/db_schema/src/source/user.rs | 56 ++++++++++++++--------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/crates/db_schema/src/source/user.rs b/crates/db_schema/src/source/user.rs index d72929fa8..cb7ae87d5 100644 --- a/crates/db_schema/src/source/user.rs +++ b/crates/db_schema/src/source/user.rs @@ -7,34 +7,34 @@ use serde::Serialize; #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "user_"] pub struct User_ { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub password_encrypted: String, - pub email: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, - pub show_avatars: bool, - pub send_notifications_to_email: bool, - pub matrix_user_id: Option, - pub actor_id: Url, - pub bio: Option, - pub local: bool, - pub private_key: Option, - pub public_key: Option, - pub last_refreshed_at: chrono::NaiveDateTime, - pub banner: Option, - pub deleted: bool, - pub inbox_url: Url, - pub shared_inbox_url: Option, + pub id: i32, // person + pub name: String, // person + pub preferred_username: Option, // person + pub password_encrypted: String, // local_user + pub email: Option, // local_user + pub avatar: Option, // person + pub admin: bool, // local_user + pub banned: bool, // person? + pub published: chrono::NaiveDateTime, // person + pub updated: Option, // person + pub show_nsfw: bool, // local_user + pub theme: String, // local_user + pub default_sort_type: i16, // local_user + pub default_listing_type: i16, // local_user + pub lang: String, // local_user + pub show_avatars: bool, // local_user + pub send_notifications_to_email: bool, // local_user + pub matrix_user_id: Option, // local_user + pub actor_id: Url, // person + pub bio: Option, // person + pub local: bool, // person + pub private_key: Option, // person + pub public_key: Option, // person + pub last_refreshed_at: chrono::NaiveDateTime, // person + pub banner: Option, // person + pub deleted: bool, // local_user + pub inbox_url: Url, // person + pub shared_inbox_url: Option, // person } /// A safe representation of user, without the sensitive info From d0bd02eea0d2813df7401d71af7822d6ecacd318 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Sun, 14 Feb 2021 13:46:16 -0500 Subject: [PATCH 02/18] Starting on user_ to person migration. --- crates/db_schema/src/source/user.rs | 2 +- .../down.sql | 59 ++++++++++++ .../2021-02-14-041356_split_user_table/up.sql | 93 +++++++++++++++++++ 3 files changed, 153 insertions(+), 1 deletion(-) create mode 100644 migrations/2021-02-14-041356_split_user_table/down.sql create mode 100644 migrations/2021-02-14-041356_split_user_table/up.sql diff --git a/crates/db_schema/src/source/user.rs b/crates/db_schema/src/source/user.rs index cb7ae87d5..17e8734cc 100644 --- a/crates/db_schema/src/source/user.rs +++ b/crates/db_schema/src/source/user.rs @@ -32,7 +32,7 @@ pub struct User_ { pub public_key: Option, // person pub last_refreshed_at: chrono::NaiveDateTime, // person pub banner: Option, // person - pub deleted: bool, // local_user + pub deleted: bool, // person pub inbox_url: Url, // person pub shared_inbox_url: Option, // person } diff --git a/migrations/2021-02-14-041356_split_user_table/down.sql b/migrations/2021-02-14-041356_split_user_table/down.sql new file mode 100644 index 000000000..218aaec2d --- /dev/null +++ b/migrations/2021-02-14-041356_split_user_table/down.sql @@ -0,0 +1,59 @@ +-- user_ table +-- Drop views +drop view person_alias_1, person_alias_2; + +-- Rename indexes +alter index person__pkey rename to user__pkey; +alter index idx_person_actor_id rename to idx_user_actor_id; +alter index idx_person_inbox_url rename to idx_user_inbox_url; +alter index idx_person_lower_actor_id rename to idx_user_lower_actor_id; +alter index idx_person_published rename to idx_user_published; + +-- Rename triggers +alter trigger site_aggregates_person_delete on person rename to site_aggregates_user_delete; +alter trigger site_aggregates_person_insert on person rename to site_aggregates_user_insert; +alter trigger person_aggregates_person on person rename to user_aggregates_user; + +-- Rename the trigger functions +alter function site_aggregates_person_delete() rename to site_aggregates_user_delete; +alter function site_aggregates_person_insert() rename to site_aggregates_user_insert; +alter function person_aggregates_person() rename to user_aggregates_user; + +-- Rename the table back to user_ +alter table person rename to user_; + +-- Add the columns back in +alter table user_ + add column password_encrypted text not null default 'changeme', + add column email text, + add column admin boolean default false not null, + add column show_nsfw boolean default false not null, + add column theme character varying(20) default 'darkly'::character varying not null, + add column default_sort_type smallint default 0 not null, + add column default_listing_type smallint default 1 not null, + add column lang character varying(20) default 'browser'::character varying not null, + add column show_avatars boolean default true not null, + add column send_notifications_to_email boolean default false not null, + add column matrix_user_id text; + +-- Update the user_ table with the local_user data +update user_ u set + password_encrypted = lu.password_encrypted, + email = lu.email, + admin = lu.admin, + show_nsfw = lu.show_nsfw, + theme = lu.theme, + default_sort_type = lu.default_sort_type, + default_listing_type = lu.default_listing_type, + lang = lu.lang, + show_avatars = lu.show_avatars, + send_notifications_to_email = lu.send_notifications_to_email, + matrix_user_id = lu.matrix_user_id +from local_user lu +where lu.user_id = u.id; + +create view user_alias_1 as select * from user_; +create view user_alias_2 as select * from user_; + +drop table local_user; + diff --git a/migrations/2021-02-14-041356_split_user_table/up.sql b/migrations/2021-02-14-041356_split_user_table/up.sql new file mode 100644 index 000000000..7d673c432 --- /dev/null +++ b/migrations/2021-02-14-041356_split_user_table/up.sql @@ -0,0 +1,93 @@ +-- Drop the 2 views user_alias_1, user_alias_2 +drop view user_alias_1, user_alias_2; + +-- rename the user_ table to person +alter table user_ rename to person; + +-- create a new table local_user +create table local_user ( + id serial primary key, + user_id int references person on update cascade on delete cascade not null, + password_encrypted text not null, + email text, + admin boolean default false not null, + show_nsfw boolean default false not null, + theme character varying(20) default 'darkly'::character varying not null, + default_sort_type smallint default 0 not null, + default_listing_type smallint default 1 not null, + lang character varying(20) default 'browser'::character varying not null, + show_avatars boolean default true not null, + send_notifications_to_email boolean default false not null, + matrix_user_id text, + unique (user_id) +); + +-- Copy the local users over to the new table +insert into local_user +( + user_id, + password_encrypted, + email, + admin, + show_nsfw, + theme, + default_sort_type, + default_listing_type, + lang, + show_avatars, + send_notifications_to_email, + matrix_user_id +) +select + id, + password_encrypted, + email, + admin, + show_nsfw, + theme, + default_sort_type, + default_listing_type, + lang, + show_avatars, + send_notifications_to_email, + matrix_user_id +from person +where local = true; + +-- Drop those columns from person +alter table person + drop column password_encrypted, + drop column email, + drop column admin, + drop column show_nsfw, + drop column theme, + drop column default_sort_type, + drop column default_listing_type, + drop column lang, + drop column show_avatars, + drop column send_notifications_to_email, + drop column matrix_user_id; + +-- Rename indexes +alter index user__pkey rename to person__pkey; +alter index idx_user_actor_id rename to idx_person_actor_id; +alter index idx_user_inbox_url rename to idx_person_inbox_url; +alter index idx_user_lower_actor_id rename to idx_person_lower_actor_id; +alter index idx_user_published rename to idx_person_published; + +-- Rename triggers +alter trigger site_aggregates_user_delete on person rename to site_aggregates_person_delete; +alter trigger site_aggregates_user_insert on person rename to site_aggregates_person_insert; +alter trigger user_aggregates_user on person rename to person_aggregates_person; + +-- Rename the trigger functions +alter function site_aggregates_user_delete() rename to site_aggregates_person_delete; +alter function site_aggregates_user_insert() rename to site_aggregates_person_insert; +alter function user_aggregates_user() rename to person_aggregates_person; + +-- Create views +create view person_alias_1 as select * from person; +create view person_alias_2 as select * from person; + +-- Rename every user_id column to person_id + From a1838158708df84ed115de5e70539734a1332c4c Mon Sep 17 00:00:00 2001 From: Dessalines Date: Mon, 15 Feb 2021 14:34:10 -0500 Subject: [PATCH 03/18] Adding a few more tables. --- .rgignore | 2 +- .../down.sql | 187 +++++++++++++++++- .../2021-02-14-041356_split_user_table/up.sql | 186 ++++++++++++++++- 3 files changed, 369 insertions(+), 6 deletions(-) diff --git a/.rgignore b/.rgignore index d1b811b7d..eab207b73 100644 --- a/.rgignore +++ b/.rgignore @@ -1 +1 @@ -*.sql +*.sqldump diff --git a/migrations/2021-02-14-041356_split_user_table/down.sql b/migrations/2021-02-14-041356_split_user_table/down.sql index 218aaec2d..c39a8ac8b 100644 --- a/migrations/2021-02-14-041356_split_user_table/down.sql +++ b/migrations/2021-02-14-041356_split_user_table/down.sql @@ -1,3 +1,42 @@ +-- user_ban +alter table person_ban rename to user_ban; +alter sequence person_ban_id_seq rename to user_ban_id_seq; +alter index person_ban_pkey rename to user_ban_pkey; +alter index person_ban_person_id_key rename to user_ban_user_id_key; +alter table user_ban rename constraint person_ban_person_id_fkey to user_ban_user_id_fkey; + +-- user_mention +alter table person_mention rename to user_mention; +alter sequence person_mention_id_seq rename to user_mention_id_seq; +alter index person_mention_pkey rename to user_mention_pkey; +alter index person_mention_recipient_id_comment_id_key rename to user_mention_recipient_id_comment_id_key; +alter table user_mention rename constraint person_mention_comment_id_fkey to user_mention_comment_id_fkey; +alter table user_mention rename constraint person_mention_recipient_id_fkey to user_mention_recipient_id_fkey; + +-- User aggregates table +alter table person_aggregates rename to user_aggregates; +alter sequence person_aggregates_id_seq rename to user_aggregates_id_seq; +alter table user_aggregates rename column person_id to user_id; + +-- Indexes +alter index person_aggregates_pkey rename to user_aggregates_pkey; +alter index idx_person_aggregates_comment_score rename to idx_user_aggregates_comment_score; +alter index person_aggregates_person_id_key rename to user_aggregates_user_id_key; +alter table user_aggregates rename constraint person_aggregates_person_id_fkey to user_aggregates_user_id_fkey; + +-- Redo the user_aggregates table +drop trigger person_aggregates_person on person; +drop trigger person_aggregates_post_count on post; +drop trigger person_aggregates_post_score on post_like; +drop trigger person_aggregates_comment_count on comment; +drop trigger person_aggregates_comment_score on comment_like; +drop function + person_aggregates_person, + person_aggregates_post_count, + person_aggregates_post_score, + person_aggregates_comment_count, + person_aggregates_comment_score; + -- user_ table -- Drop views drop view person_alias_1, person_alias_2; @@ -12,15 +51,14 @@ alter index idx_person_published rename to idx_user_published; -- Rename triggers alter trigger site_aggregates_person_delete on person rename to site_aggregates_user_delete; alter trigger site_aggregates_person_insert on person rename to site_aggregates_user_insert; -alter trigger person_aggregates_person on person rename to user_aggregates_user; -- Rename the trigger functions alter function site_aggregates_person_delete() rename to site_aggregates_user_delete; alter function site_aggregates_person_insert() rename to site_aggregates_user_insert; -alter function person_aggregates_person() rename to user_aggregates_user; -- Rename the table back to user_ alter table person rename to user_; +alter sequence person_id_seq rename to user__id_seq; -- Add the columns back in alter table user_ @@ -57,3 +95,148 @@ create view user_alias_2 as select * from user_; drop table local_user; +-- Add the user_aggregates table triggers + +-- initial user add +create function user_aggregates_user() +returns trigger language plpgsql +as $$ +begin + IF (TG_OP = 'INSERT') THEN + insert into user_aggregates (user_id) values (NEW.id); + ELSIF (TG_OP = 'DELETE') THEN + delete from user_aggregates where user_id = OLD.id; + END IF; + return null; +end $$; + +create trigger user_aggregates_user +after insert or delete on user_ +for each row +execute procedure user_aggregates_user(); + +-- post count +create function user_aggregates_post_count() +returns trigger language plpgsql +as $$ +begin + IF (TG_OP = 'INSERT') THEN + update user_aggregates + set post_count = post_count + 1 where user_id = NEW.creator_id; + + ELSIF (TG_OP = 'DELETE') THEN + update user_aggregates + set post_count = post_count - 1 where user_id = OLD.creator_id; + + -- If the post gets deleted, the score calculation trigger won't fire, + -- so you need to re-calculate + update user_aggregates ua + set post_score = pd.score + from ( + select u.id, + coalesce(0, sum(pl.score)) as score + -- User join because posts could be empty + from user_ u + left join post p on u.id = p.creator_id + left join post_like pl on p.id = pl.post_id + group by u.id + ) pd + where ua.user_id = OLD.creator_id; + + END IF; + return null; +end $$; + +create trigger user_aggregates_post_count +after insert or delete on post +for each row +execute procedure user_aggregates_post_count(); + +-- post score +create function user_aggregates_post_score() +returns trigger language plpgsql +as $$ +begin + IF (TG_OP = 'INSERT') THEN + -- Need to get the post creator, not the voter + update user_aggregates ua + set post_score = post_score + NEW.score + from post p + where ua.user_id = p.creator_id and p.id = NEW.post_id; + + ELSIF (TG_OP = 'DELETE') THEN + update user_aggregates ua + set post_score = post_score - OLD.score + from post p + where ua.user_id = p.creator_id and p.id = OLD.post_id; + END IF; + return null; +end $$; + +create trigger user_aggregates_post_score +after insert or delete on post_like +for each row +execute procedure user_aggregates_post_score(); + +-- comment count +create function user_aggregates_comment_count() +returns trigger language plpgsql +as $$ +begin + IF (TG_OP = 'INSERT') THEN + update user_aggregates + set comment_count = comment_count + 1 where user_id = NEW.creator_id; + ELSIF (TG_OP = 'DELETE') THEN + update user_aggregates + set comment_count = comment_count - 1 where user_id = OLD.creator_id; + + -- If the comment gets deleted, the score calculation trigger won't fire, + -- so you need to re-calculate + update user_aggregates ua + set comment_score = cd.score + from ( + select u.id, + coalesce(0, sum(cl.score)) as score + -- User join because comments could be empty + from user_ u + left join comment c on u.id = c.creator_id + left join comment_like cl on c.id = cl.comment_id + group by u.id + ) cd + where ua.user_id = OLD.creator_id; + END IF; + return null; +end $$; + +create trigger user_aggregates_comment_count +after insert or delete on comment +for each row +execute procedure user_aggregates_comment_count(); + +-- comment score +create function user_aggregates_comment_score() +returns trigger language plpgsql +as $$ +begin + IF (TG_OP = 'INSERT') THEN + -- Need to get the post creator, not the voter + update user_aggregates ua + set comment_score = comment_score + NEW.score + from comment c + where ua.user_id = c.creator_id and c.id = NEW.comment_id; + ELSIF (TG_OP = 'DELETE') THEN + update user_aggregates ua + set comment_score = comment_score - OLD.score + from comment c + where ua.user_id = c.creator_id and c.id = OLD.comment_id; + END IF; + return null; +end $$; + +create trigger user_aggregates_comment_score +after insert or delete on comment_like +for each row +execute procedure user_aggregates_comment_score(); + + + diff --git a/migrations/2021-02-14-041356_split_user_table/up.sql b/migrations/2021-02-14-041356_split_user_table/up.sql index 7d673c432..107ee4fc8 100644 --- a/migrations/2021-02-14-041356_split_user_table/up.sql +++ b/migrations/2021-02-14-041356_split_user_table/up.sql @@ -1,8 +1,10 @@ +-- Person -- Drop the 2 views user_alias_1, user_alias_2 drop view user_alias_1, user_alias_2; -- rename the user_ table to person alter table user_ rename to person; +alter sequence user__id_seq rename to person_id_seq; -- create a new table local_user create table local_user ( @@ -78,16 +80,194 @@ alter index idx_user_published rename to idx_person_published; -- Rename triggers alter trigger site_aggregates_user_delete on person rename to site_aggregates_person_delete; alter trigger site_aggregates_user_insert on person rename to site_aggregates_person_insert; -alter trigger user_aggregates_user on person rename to person_aggregates_person; -- Rename the trigger functions alter function site_aggregates_user_delete() rename to site_aggregates_person_delete; alter function site_aggregates_user_insert() rename to site_aggregates_person_insert; -alter function user_aggregates_user() rename to person_aggregates_person; -- Create views create view person_alias_1 as select * from person; create view person_alias_2 as select * from person; --- Rename every user_id column to person_id +-- Redo user aggregates into person_aggregates +alter table user_aggregates rename to person_aggregates; +alter sequence user_aggregates_id_seq rename to person_aggregates_id_seq; +alter table person_aggregates rename column user_id to person_id; + +-- index +alter index user_aggregates_pkey rename to person_aggregates_pkey; +alter index idx_user_aggregates_comment_score rename to idx_person_aggregates_comment_score; +alter index user_aggregates_user_id_key rename to person_aggregates_person_id_key; +alter table person_aggregates rename constraint user_aggregates_user_id_fkey to person_aggregates_person_id_fkey; + + +-- Drop all the old triggers and functions +drop trigger user_aggregates_user on person; +drop trigger user_aggregates_post_count on post; +drop trigger user_aggregates_post_score on post_like; +drop trigger user_aggregates_comment_count on comment; +drop trigger user_aggregates_comment_score on comment_like; +drop function + user_aggregates_user, + user_aggregates_post_count, + user_aggregates_post_score, + user_aggregates_comment_count, + user_aggregates_comment_score; + +-- initial user add +create function person_aggregates_person() +returns trigger language plpgsql +as $$ +begin + IF (TG_OP = 'INSERT') THEN + insert into person_aggregates (person_id) values (NEW.id); + ELSIF (TG_OP = 'DELETE') THEN + delete from person_aggregates where person_id = OLD.id; + END IF; + return null; +end $$; + +create trigger person_aggregates_person +after insert or delete on person +for each row +execute procedure person_aggregates_person(); + +-- post count +create function person_aggregates_post_count() +returns trigger language plpgsql +as $$ +begin + IF (TG_OP = 'INSERT') THEN + update person_aggregates + set post_count = post_count + 1 where person_id = NEW.creator_id; + + ELSIF (TG_OP = 'DELETE') THEN + update person_aggregates + set post_count = post_count - 1 where person_id = OLD.creator_id; + + -- If the post gets deleted, the score calculation trigger won't fire, + -- so you need to re-calculate + update person_aggregates ua + set post_score = pd.score + from ( + select u.id, + coalesce(0, sum(pl.score)) as score + -- User join because posts could be empty + from person u + left join post p on u.id = p.creator_id + left join post_like pl on p.id = pl.post_id + group by u.id + ) pd + where ua.person_id = OLD.creator_id; + + END IF; + return null; +end $$; + +create trigger person_aggregates_post_count +after insert or delete on post +for each row +execute procedure person_aggregates_post_count(); + +-- post score +create function person_aggregates_post_score() +returns trigger language plpgsql +as $$ +begin + IF (TG_OP = 'INSERT') THEN + -- Need to get the post creator, not the voter + update person_aggregates ua + set post_score = post_score + NEW.score + from post p + where ua.person_id = p.creator_id and p.id = NEW.post_id; + + ELSIF (TG_OP = 'DELETE') THEN + update person_aggregates ua + set post_score = post_score - OLD.score + from post p + where ua.person_id = p.creator_id and p.id = OLD.post_id; + END IF; + return null; +end $$; + +create trigger person_aggregates_post_score +after insert or delete on post_like +for each row +execute procedure person_aggregates_post_score(); + +-- comment count +create function person_aggregates_comment_count() +returns trigger language plpgsql +as $$ +begin + IF (TG_OP = 'INSERT') THEN + update person_aggregates + set comment_count = comment_count + 1 where person_id = NEW.creator_id; + ELSIF (TG_OP = 'DELETE') THEN + update person_aggregates + set comment_count = comment_count - 1 where person_id = OLD.creator_id; + + -- If the comment gets deleted, the score calculation trigger won't fire, + -- so you need to re-calculate + update person_aggregates ua + set comment_score = cd.score + from ( + select u.id, + coalesce(0, sum(cl.score)) as score + -- User join because comments could be empty + from person u + left join comment c on u.id = c.creator_id + left join comment_like cl on c.id = cl.comment_id + group by u.id + ) cd + where ua.person_id = OLD.creator_id; + END IF; + return null; +end $$; + +create trigger person_aggregates_comment_count +after insert or delete on comment +for each row +execute procedure person_aggregates_comment_count(); + +-- comment score +create function person_aggregates_comment_score() +returns trigger language plpgsql +as $$ +begin + IF (TG_OP = 'INSERT') THEN + -- Need to get the post creator, not the voter + update person_aggregates ua + set comment_score = comment_score + NEW.score + from comment c + where ua.person_id = c.creator_id and c.id = NEW.comment_id; + ELSIF (TG_OP = 'DELETE') THEN + update person_aggregates ua + set comment_score = comment_score - OLD.score + from comment c + where ua.person_id = c.creator_id and c.id = OLD.comment_id; + END IF; + return null; +end $$; + +create trigger person_aggregates_comment_score +after insert or delete on comment_like +for each row +execute procedure person_aggregates_comment_score(); + +-- person_mention +alter table user_mention rename to person_mention; +alter sequence user_mention_id_seq rename to person_mention_id_seq; +alter index user_mention_pkey rename to person_mention_pkey; +alter index user_mention_recipient_id_comment_id_key rename to person_mention_recipient_id_comment_id_key; +alter table person_mention rename constraint user_mention_comment_id_fkey to person_mention_comment_id_fkey; +alter table person_mention rename constraint user_mention_recipient_id_fkey to person_mention_recipient_id_fkey; + +-- user_ban +alter table user_ban rename to person_ban; +alter sequence user_ban_id_seq rename to person_ban_id_seq; +alter index user_ban_pkey rename to person_ban_pkey; +alter index user_ban_user_id_key rename to person_ban_person_id_key; +alter table person_ban rename constraint user_ban_user_id_fkey to person_ban_person_id_fkey; + From efc9047f879f214e0126b0220ebe2f04bf8344a8 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Thu, 25 Feb 2021 14:04:12 -0500 Subject: [PATCH 04/18] Done with user->person migrations, now to code. --- .../down.sql | 123 ++++++++++++++++- .../up.sql | 124 +++++++++++++++++- 2 files changed, 241 insertions(+), 6 deletions(-) rename migrations/{2021-02-14-041356_split_user_table => 2021-02-25-173454_split_user_table_1}/down.sql (55%) rename migrations/{2021-02-14-041356_split_user_table => 2021-02-25-173454_split_user_table_1}/up.sql (55%) diff --git a/migrations/2021-02-14-041356_split_user_table/down.sql b/migrations/2021-02-25-173454_split_user_table_1/down.sql similarity index 55% rename from migrations/2021-02-14-041356_split_user_table/down.sql rename to migrations/2021-02-25-173454_split_user_table_1/down.sql index c39a8ac8b..e1d55a205 100644 --- a/migrations/2021-02-14-041356_split_user_table/down.sql +++ b/migrations/2021-02-25-173454_split_user_table_1/down.sql @@ -1,8 +1,104 @@ +-- post_saved +alter table post_saved rename column person_id to user_id; +alter table post_saved rename constraint post_saved_post_id_person_id_key to post_saved_post_id_user_id_key; +alter table post_saved rename constraint post_saved_person_id_fkey to post_saved_user_id_fkey; + +-- post_read +alter table post_read rename column person_id to user_id; +alter table post_read rename constraint post_read_post_id_person_id_key to post_read_post_id_user_id_key; +alter table post_read rename constraint post_read_person_id_fkey to post_read_user_id_fkey; + +-- post_like +alter table post_like rename column person_id to user_id; +alter index idx_post_like_person rename to idx_post_like_user; +alter table post_like rename constraint post_like_post_id_person_id_key to post_like_post_id_user_id_key; +alter table post_like rename constraint post_like_person_id_fkey to post_like_user_id_fkey; + +-- password_reset_request +delete from password_reset_request; +alter table password_reset_request drop column local_user_id; +alter table password_reset_request add column user_id integer not null references person(id) on update cascade on delete cascade; + +-- mod_sticky_post +alter table mod_sticky_post rename column mod_person_id to mod_user_id; +alter table mod_sticky_post rename constraint mod_sticky_post_mod_person_id_fkey to mod_sticky_post_mod_user_id_fkey; + +-- mod_remove_post +alter table mod_remove_post rename column mod_person_id to mod_user_id; +alter table mod_remove_post rename constraint mod_remove_post_mod_person_id_fkey to mod_remove_post_mod_user_id_fkey; + +-- mod_remove_community +alter table mod_remove_community rename column mod_person_id to mod_user_id; +alter table mod_remove_community rename constraint mod_remove_community_mod_person_id_fkey to mod_remove_community_mod_user_id_fkey; + +-- mod_remove_comment +alter table mod_remove_comment rename column mod_person_id to mod_user_id; +alter table mod_remove_comment rename constraint mod_remove_comment_mod_person_id_fkey to mod_remove_comment_mod_user_id_fkey; + +-- mod_lock_post +alter table mod_lock_post rename column mod_person_id to mod_user_id; +alter table mod_lock_post rename constraint mod_lock_post_mod_person_id_fkey to mod_lock_post_mod_user_id_fkey; + +-- mod_add_community +alter table mod_ban_from_community rename column mod_person_id to mod_user_id; +alter table mod_ban_from_community rename column other_person_id to other_user_id; +alter table mod_ban_from_community rename constraint mod_ban_from_community_mod_person_id_fkey to mod_ban_from_community_mod_user_id_fkey; +alter table mod_ban_from_community rename constraint mod_ban_from_community_other_person_id_fkey to mod_ban_from_community_other_user_id_fkey; + +-- mod_ban +alter table mod_ban rename column mod_person_id to mod_user_id; +alter table mod_ban rename column other_person_id to other_user_id; +alter table mod_ban rename constraint mod_ban_mod_person_id_fkey to mod_ban_mod_user_id_fkey; +alter table mod_ban rename constraint mod_ban_other_person_id_fkey to mod_ban_other_user_id_fkey; + +-- mod_add_community +alter table mod_add_community rename column mod_person_id to mod_user_id; +alter table mod_add_community rename column other_person_id to other_user_id; +alter table mod_add_community rename constraint mod_add_community_mod_person_id_fkey to mod_add_community_mod_user_id_fkey; +alter table mod_add_community rename constraint mod_add_community_other_person_id_fkey to mod_add_community_other_user_id_fkey; + +-- mod_add +alter table mod_add rename column mod_person_id to mod_user_id; +alter table mod_add rename column other_person_id to other_user_id; +alter table mod_add rename constraint mod_add_mod_person_id_fkey to mod_add_mod_user_id_fkey; +alter table mod_add rename constraint mod_add_other_person_id_fkey to mod_add_other_user_id_fkey; + +-- community_user_ban +alter table community_person_ban rename to community_user_ban; +alter sequence community_person_ban_id_seq rename to community_user_ban_id_seq; +alter table community_user_ban rename column person_id to user_id; +alter table community_user_ban rename constraint community_person_ban_pkey to community_user_ban_pkey; +alter table community_user_ban rename constraint community_person_ban_community_id_fkey to community_user_ban_community_id_fkey; +alter table community_user_ban rename constraint community_person_ban_community_id_person_id_key to community_user_ban_community_id_user_id_key; +alter table community_user_ban rename constraint community_person_ban_person_id_fkey to community_user_ban_user_id_fkey; + +-- community_moderator +alter table community_moderator rename column person_id to user_id; +alter table community_moderator rename constraint community_moderator_community_id_person_id_key to community_moderator_community_id_user_id_key; +alter table community_moderator rename constraint community_moderator_person_id_fkey to community_moderator_user_id_fkey; + +-- community_follower +alter table community_follower rename column person_id to user_id; +alter table community_follower rename constraint community_follower_community_id_person_id_key to community_follower_community_id_user_id_key; +alter table community_follower rename constraint community_follower_person_id_fkey to community_follower_user_id_fkey; + +-- comment_saved +alter table comment_saved rename column person_id to user_id; +alter table comment_saved rename constraint comment_saved_comment_id_person_id_key to comment_saved_comment_id_user_id_key; +alter table comment_saved rename constraint comment_saved_person_id_fkey to comment_saved_user_id_fkey; + +-- comment_like +alter table comment_like rename column person_id to user_id; +alter index idx_comment_like_person rename to idx_comment_like_user; +alter table comment_like rename constraint comment_like_comment_id_person_id_key to comment_like_comment_id_user_id_key; +alter table comment_like rename constraint comment_like_person_id_fkey to comment_like_user_id_fkey; + -- user_ban alter table person_ban rename to user_ban; alter sequence person_ban_id_seq rename to user_ban_id_seq; alter index person_ban_pkey rename to user_ban_pkey; alter index person_ban_person_id_key rename to user_ban_user_id_key; +alter table user_ban rename column person_id to user_id; alter table user_ban rename constraint person_ban_person_id_fkey to user_ban_user_id_fkey; -- user_mention @@ -88,7 +184,7 @@ update user_ u set send_notifications_to_email = lu.send_notifications_to_email, matrix_user_id = lu.matrix_user_id from local_user lu -where lu.user_id = u.id; +where lu.person_id = u.id; create view user_alias_1 as select * from user_; create view user_alias_2 as select * from user_; @@ -238,5 +334,26 @@ after insert or delete on comment_like for each row execute procedure user_aggregates_comment_score(); - - +-- redo site aggregates trigger +create or replace function site_aggregates_activity(i text) returns integer + language plpgsql + as $$ +declare + count_ integer; +begin + select count(*) + into count_ + from ( + select c.creator_id from comment c + inner join user_ u on c.creator_id = u.id + where c.published > ('now'::timestamp - i::interval) + and u.local = true + union + select p.creator_id from post p + inner join user_ u on p.creator_id = u.id + where p.published > ('now'::timestamp - i::interval) + and u.local = true + ) a; + return count_; +end; +$$; diff --git a/migrations/2021-02-14-041356_split_user_table/up.sql b/migrations/2021-02-25-173454_split_user_table_1/up.sql similarity index 55% rename from migrations/2021-02-14-041356_split_user_table/up.sql rename to migrations/2021-02-25-173454_split_user_table_1/up.sql index 107ee4fc8..d20bf0213 100644 --- a/migrations/2021-02-14-041356_split_user_table/up.sql +++ b/migrations/2021-02-25-173454_split_user_table_1/up.sql @@ -9,7 +9,7 @@ alter sequence user__id_seq rename to person_id_seq; -- create a new table local_user create table local_user ( id serial primary key, - user_id int references person on update cascade on delete cascade not null, + person_id int references person on update cascade on delete cascade not null, password_encrypted text not null, email text, admin boolean default false not null, @@ -21,13 +21,13 @@ create table local_user ( show_avatars boolean default true not null, send_notifications_to_email boolean default false not null, matrix_user_id text, - unique (user_id) + unique (person_id) ); -- Copy the local users over to the new table insert into local_user ( - user_id, + person_id, password_encrypted, email, admin, @@ -268,6 +268,124 @@ alter table user_ban rename to person_ban; alter sequence user_ban_id_seq rename to person_ban_id_seq; alter index user_ban_pkey rename to person_ban_pkey; alter index user_ban_user_id_key rename to person_ban_person_id_key; +alter table person_ban rename column user_id to person_id; alter table person_ban rename constraint user_ban_user_id_fkey to person_ban_person_id_fkey; +-- comment_like +alter table comment_like rename column user_id to person_id; +alter index idx_comment_like_user rename to idx_comment_like_person; +alter table comment_like rename constraint comment_like_comment_id_user_id_key to comment_like_comment_id_person_id_key; +alter table comment_like rename constraint comment_like_user_id_fkey to comment_like_person_id_fkey; +-- comment_saved +alter table comment_saved rename column user_id to person_id; +alter table comment_saved rename constraint comment_saved_comment_id_user_id_key to comment_saved_comment_id_person_id_key; +alter table comment_saved rename constraint comment_saved_user_id_fkey to comment_saved_person_id_fkey; + +-- community_follower +alter table community_follower rename column user_id to person_id; +alter table community_follower rename constraint community_follower_community_id_user_id_key to community_follower_community_id_person_id_key; +alter table community_follower rename constraint community_follower_user_id_fkey to community_follower_person_id_fkey; + +-- community_moderator +alter table community_moderator rename column user_id to person_id; +alter table community_moderator rename constraint community_moderator_community_id_user_id_key to community_moderator_community_id_person_id_key; +alter table community_moderator rename constraint community_moderator_user_id_fkey to community_moderator_person_id_fkey; + +-- community_user_ban +alter table community_user_ban rename to community_person_ban; +alter sequence community_user_ban_id_seq rename to community_person_ban_id_seq; +alter table community_person_ban rename column user_id to person_id; +alter table community_person_ban rename constraint community_user_ban_pkey to community_person_ban_pkey; +alter table community_person_ban rename constraint community_user_ban_community_id_fkey to community_person_ban_community_id_fkey; +alter table community_person_ban rename constraint community_user_ban_community_id_user_id_key to community_person_ban_community_id_person_id_key; +alter table community_person_ban rename constraint community_user_ban_user_id_fkey to community_person_ban_person_id_fkey; + +-- mod_add +alter table mod_add rename column mod_user_id to mod_person_id; +alter table mod_add rename column other_user_id to other_person_id; +alter table mod_add rename constraint mod_add_mod_user_id_fkey to mod_add_mod_person_id_fkey; +alter table mod_add rename constraint mod_add_other_user_id_fkey to mod_add_other_person_id_fkey; + +-- mod_add_community +alter table mod_add_community rename column mod_user_id to mod_person_id; +alter table mod_add_community rename column other_user_id to other_person_id; +alter table mod_add_community rename constraint mod_add_community_mod_user_id_fkey to mod_add_community_mod_person_id_fkey; +alter table mod_add_community rename constraint mod_add_community_other_user_id_fkey to mod_add_community_other_person_id_fkey; + +-- mod_ban +alter table mod_ban rename column mod_user_id to mod_person_id; +alter table mod_ban rename column other_user_id to other_person_id; +alter table mod_ban rename constraint mod_ban_mod_user_id_fkey to mod_ban_mod_person_id_fkey; +alter table mod_ban rename constraint mod_ban_other_user_id_fkey to mod_ban_other_person_id_fkey; + +-- mod_ban_community +alter table mod_ban_from_community rename column mod_user_id to mod_person_id; +alter table mod_ban_from_community rename column other_user_id to other_person_id; +alter table mod_ban_from_community rename constraint mod_ban_from_community_mod_user_id_fkey to mod_ban_from_community_mod_person_id_fkey; +alter table mod_ban_from_community rename constraint mod_ban_from_community_other_user_id_fkey to mod_ban_from_community_other_person_id_fkey; + +-- mod_lock_post +alter table mod_lock_post rename column mod_user_id to mod_person_id; +alter table mod_lock_post rename constraint mod_lock_post_mod_user_id_fkey to mod_lock_post_mod_person_id_fkey; + +-- mod_remove_comment +alter table mod_remove_comment rename column mod_user_id to mod_person_id; +alter table mod_remove_comment rename constraint mod_remove_comment_mod_user_id_fkey to mod_remove_comment_mod_person_id_fkey; + +-- mod_remove_community +alter table mod_remove_community rename column mod_user_id to mod_person_id; +alter table mod_remove_community rename constraint mod_remove_community_mod_user_id_fkey to mod_remove_community_mod_person_id_fkey; + +-- mod_remove_post +alter table mod_remove_post rename column mod_user_id to mod_person_id; +alter table mod_remove_post rename constraint mod_remove_post_mod_user_id_fkey to mod_remove_post_mod_person_id_fkey; + +-- mod_sticky_post +alter table mod_sticky_post rename column mod_user_id to mod_person_id; +alter table mod_sticky_post rename constraint mod_sticky_post_mod_user_id_fkey to mod_sticky_post_mod_person_id_fkey; + +-- password_reset_request +delete from password_reset_request; +alter table password_reset_request drop column user_id; +alter table password_reset_request add column local_user_id integer not null references local_user(id) on update cascade on delete cascade; + +-- post_like +alter table post_like rename column user_id to person_id; +alter index idx_post_like_user rename to idx_post_like_person; +alter table post_like rename constraint post_like_post_id_user_id_key to post_like_post_id_person_id_key; +alter table post_like rename constraint post_like_user_id_fkey to post_like_person_id_fkey; + +-- post_read +alter table post_read rename column user_id to person_id; +alter table post_read rename constraint post_read_post_id_user_id_key to post_read_post_id_person_id_key; +alter table post_read rename constraint post_read_user_id_fkey to post_read_person_id_fkey; + +-- post_saved +alter table post_saved rename column user_id to person_id; +alter table post_saved rename constraint post_saved_post_id_user_id_key to post_saved_post_id_person_id_key; +alter table post_saved rename constraint post_saved_user_id_fkey to post_saved_person_id_fkey; + +-- redo site aggregates trigger +create or replace function site_aggregates_activity(i text) returns integer + language plpgsql + as $$ +declare + count_ integer; +begin + select count(*) + into count_ + from ( + select c.creator_id from comment c + inner join person u on c.creator_id = u.id + where c.published > ('now'::timestamp - i::interval) + and u.local = true + union + select p.creator_id from post p + inner join person u on p.creator_id = u.id + where p.published > ('now'::timestamp - i::interval) + and u.local = true + ) a; + return count_; +end; +$$; From a869a2823b5be33a94341c4f8112ab6827315dd2 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Fri, 26 Feb 2021 08:49:58 -0500 Subject: [PATCH 05/18] Still continuing on.... --- crates/api/src/comment.rs | 8 +- crates/api/src/community.rs | 34 +- crates/api/src/lib.rs | 2 +- crates/api/src/post.rs | 12 +- crates/api/src/site.rs | 4 +- crates/api/src/user.rs | 14 +- crates/apub/src/activities/receive/comment.rs | 4 +- crates/apub/src/activities/receive/post.rs | 4 +- crates/apub/src/activities/send/user.rs | 2 +- crates/apub/src/fetcher/community.rs | 2 +- crates/apub/src/inbox/community_inbox.rs | 4 +- .../src/aggregates/comment_aggregates.rs | 64 +-- .../src/aggregates/community_aggregates.rs | 74 ++- crates/db_queries/src/aggregates/mod.rs | 2 +- ...ser_aggregates.rs => person_aggregates.rs} | 94 ++-- .../src/aggregates/post_aggregates.rs | 59 +-- .../src/aggregates/site_aggregates.rs | 35 +- crates/db_queries/src/source/activity.rs | 27 +- crates/db_queries/src/source/comment.rs | 48 +- crates/db_queries/src/source/community.rs | 112 ++--- crates/db_queries/src/source/local_user.rs | 76 +++ crates/db_queries/src/source/mod.rs | 5 +- crates/db_queries/src/source/moderator.rs | 96 ++-- .../src/source/password_reset_request.rs | 30 +- crates/db_queries/src/source/person.rs | 364 ++++++++++++++ .../{user_mention.rs => person_mention.rs} | 110 ++--- crates/db_queries/src/source/post.rs | 58 +-- .../db_queries/src/source/private_message.rs | 38 +- crates/db_queries/src/source/user.rs | 458 ------------------ crates/db_schema/src/schema.rs | 287 ++++++----- crates/db_schema/src/source/comment.rs | 8 +- crates/db_schema/src/source/community.rs | 22 +- crates/db_schema/src/source/local_user.rs | 66 +++ crates/db_schema/src/source/mod.rs | 5 +- crates/db_schema/src/source/moderator.rs | 52 +- .../src/source/password_reset_request.rs | 4 +- crates/db_schema/src/source/person.rs | 154 ++++++ .../{user_mention.rs => person_mention.rs} | 10 +- crates/db_schema/src/source/post.rs | 16 +- crates/db_schema/src/source/user.rs | 220 --------- crates/db_views/src/comment_view.rs | 6 +- crates/db_views/src/post_view.rs | 8 +- .../db_views_actor/src/user_mention_view.rs | 4 +- 43 files changed, 1232 insertions(+), 1470 deletions(-) rename crates/db_queries/src/aggregates/{user_aggregates.rs => person_aggregates.rs} (66%) create mode 100644 crates/db_queries/src/source/local_user.rs create mode 100644 crates/db_queries/src/source/person.rs rename crates/db_queries/src/source/{user_mention.rs => person_mention.rs} (60%) delete mode 100644 crates/db_queries/src/source/user.rs create mode 100644 crates/db_schema/src/source/local_user.rs create mode 100644 crates/db_schema/src/source/person.rs rename crates/db_schema/src/source/{user_mention.rs => person_mention.rs} (66%) delete mode 100644 crates/db_schema/src/source/user.rs diff --git a/crates/api/src/comment.rs b/crates/api/src/comment.rs index 02acc7f85..bd4f33f5e 100644 --- a/crates/api/src/comment.rs +++ b/crates/api/src/comment.rs @@ -134,7 +134,7 @@ impl Perform for CreateComment { let like_form = CommentLikeForm { comment_id: inserted_comment.id, post_id, - user_id: user.id, + person_id: user.id, score: 1, }; @@ -375,7 +375,7 @@ impl Perform for RemoveComment { // Mod tables let form = ModRemoveCommentForm { - mod_user_id: user.id, + mod_person_id: user.id, comment_id: data.comment_id, removed: Some(removed), reason: data.reason.to_owned(), @@ -498,7 +498,7 @@ impl Perform for SaveComment { let comment_saved_form = CommentSavedForm { comment_id: data.comment_id, - user_id: user.id, + person_id: user.id, }; if data.save { @@ -559,7 +559,7 @@ impl Perform for CreateCommentLike { let like_form = CommentLikeForm { comment_id: data.comment_id, post_id: orig_comment.post.id, - user_id: user.id, + person_id: user.id, score: data.score, }; diff --git a/crates/api/src/community.rs b/crates/api/src/community.rs index 128d8b303..40dc345ec 100644 --- a/crates/api/src/community.rs +++ b/crates/api/src/community.rs @@ -198,7 +198,7 @@ impl Perform for CreateCommunity { // The community creator becomes a moderator let community_moderator_form = CommunityModeratorForm { community_id: inserted_community.id, - user_id: user.id, + person_id: user.id, }; let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); @@ -209,7 +209,7 @@ impl Perform for CreateCommunity { // Follow your own community let community_follower_form = CommunityFollowerForm { community_id: inserted_community.id, - user_id: user.id, + person_id: user.id, pending: false, }; @@ -405,7 +405,7 @@ impl Perform for RemoveCommunity { None => None, }; let form = ModRemoveCommunityForm { - mod_user_id: user.id, + mod_person_id: user.id, community_id: data.community_id, removed: Some(removed), reason: data.reason.to_owned(), @@ -501,7 +501,7 @@ impl Perform for FollowCommunity { .await??; let community_follower_form = CommunityFollowerForm { community_id: data.community_id, - user_id: user.id, + person_id: user.id, pending: false, }; @@ -595,13 +595,13 @@ impl Perform for BanFromCommunity { // Verify that only mods or admins can ban is_mod_or_admin(context.pool(), user.id, community_id).await?; - let community_user_ban_form = CommunityUserBanForm { + let community_user_ban_form = CommunityPersonBanForm { community_id: data.community_id, - user_id: data.user_id, + person_id: data.user_id, }; if data.ban { - let ban = move |conn: &'_ _| CommunityUserBan::ban(conn, &community_user_ban_form); + let ban = move |conn: &'_ _| CommunityPersonBan::ban(conn, &community_user_ban_form); if blocking(context.pool(), ban).await?.is_err() { return Err(ApiError::err("community_user_already_banned").into()); } @@ -609,7 +609,7 @@ impl Perform for BanFromCommunity { // Also unsubscribe them from the community, if they are subscribed let community_follower_form = CommunityFollowerForm { community_id: data.community_id, - user_id: banned_user_id, + person_id: banned_user_id, pending: false, }; blocking(context.pool(), move |conn: &'_ _| { @@ -618,7 +618,7 @@ impl Perform for BanFromCommunity { .await? .ok(); } else { - let unban = move |conn: &'_ _| CommunityUserBan::unban(conn, &community_user_ban_form); + let unban = move |conn: &'_ _| CommunityPersonBan::unban(conn, &community_user_ban_form); if blocking(context.pool(), unban).await?.is_err() { return Err(ApiError::err("community_user_already_banned").into()); } @@ -660,8 +660,8 @@ impl Perform for BanFromCommunity { }; let form = ModBanFromCommunityForm { - mod_user_id: user.id, - other_user_id: data.user_id, + mod_person_id: user.id, + other_person_id: data.user_id, community_id: data.community_id, reason: data.reason.to_owned(), banned: Some(data.ban), @@ -708,7 +708,7 @@ impl Perform for AddModToCommunity { let community_moderator_form = CommunityModeratorForm { community_id: data.community_id, - user_id: data.user_id, + person_id: data.user_id, }; let community_id = data.community_id; @@ -730,8 +730,8 @@ impl Perform for AddModToCommunity { // Mod tables let form = ModAddCommunityForm { - mod_user_id: user.id, - other_user_id: data.user_id, + mod_person_id: user.id, + other_person_id: data.user_id, community_id: data.community_id, removed: Some(!data.added), }; @@ -829,7 +829,7 @@ impl Perform for TransferCommunity { for cmod in &community_mods { let community_moderator_form = CommunityModeratorForm { community_id: cmod.community.id, - user_id: cmod.moderator.id, + person_id: cmod.moderator.id, }; let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); @@ -840,8 +840,8 @@ impl Perform for TransferCommunity { // Mod tables let form = ModAddCommunityForm { - mod_user_id: user.id, - other_user_id: data.user_id, + mod_person_id: user.id, + other_person_id: data.user_id, community_id: data.community_id, removed: Some(false), }; diff --git a/crates/api/src/lib.rs b/crates/api/src/lib.rs index 5642c4b9c..ab0bc8ac1 100644 --- a/crates/api/src/lib.rs +++ b/crates/api/src/lib.rs @@ -165,7 +165,7 @@ pub(crate) async fn collect_moderated_communities( Ok(vec![community_id]) } else { let ids = blocking(pool, move |conn: &'_ _| { - CommunityModerator::get_user_moderated_communities(conn, user_id) + CommunityModerator::get_person_moderated_communities(conn, user_id) }) .await??; Ok(ids) diff --git a/crates/api/src/post.rs b/crates/api/src/post.rs index 4ef07ae56..33983a4e1 100644 --- a/crates/api/src/post.rs +++ b/crates/api/src/post.rs @@ -129,7 +129,7 @@ impl Perform for CreatePost { // They like their own post by default let like_form = PostLikeForm { post_id: inserted_post.id, - user_id: user.id, + person_id: user.id, score: 1, }; @@ -303,7 +303,7 @@ impl Perform for CreatePostLike { let like_form = PostLikeForm { post_id: data.post_id, - user_id: user.id, + person_id: user.id, score: data.score, }; @@ -534,7 +534,7 @@ impl Perform for RemovePost { // Mod tables let form = ModRemovePostForm { - mod_user_id: user.id, + mod_person_id: user.id, post_id: data.post_id, removed: Some(removed), reason: data.reason.to_owned(), @@ -601,7 +601,7 @@ impl Perform for LockPost { // Mod tables let form = ModLockPostForm { - mod_user_id: user.id, + mod_person_id: user.id, post_id: data.post_id, locked: Some(locked), }; @@ -659,7 +659,7 @@ impl Perform for StickyPost { // Mod tables let form = ModStickyPostForm { - mod_user_id: user.id, + mod_person_id: user.id, post_id: data.post_id, stickied: Some(stickied), }; @@ -705,7 +705,7 @@ impl Perform for SavePost { let post_saved_form = PostSavedForm { post_id: data.post_id, - user_id: user.id, + person_id: user.id, }; if data.save { diff --git a/crates/api/src/site.rs b/crates/api/src/site.rs index b545a72ea..56f14dea7 100644 --- a/crates/api/src/site.rs +++ b/crates/api/src/site.rs @@ -511,8 +511,8 @@ impl Perform for TransferSite { // Mod tables let form = ModAddForm { - mod_user_id: user.id, - other_user_id: data.user_id, + mod_person_id: user.id, + other_person_id: data.user_id, removed: Some(false), }; diff --git a/crates/api/src/user.rs b/crates/api/src/user.rs index c6877fe0d..a8f1477f8 100644 --- a/crates/api/src/user.rs +++ b/crates/api/src/user.rs @@ -278,7 +278,7 @@ impl Perform for Register { // Sign them up for main community no matter what let community_follower_form = CommunityFollowerForm { community_id: main_community.id, - user_id: inserted_user.id, + person_id: inserted_user.id, pending: false, }; @@ -291,7 +291,7 @@ impl Perform for Register { if no_admins { let community_moderator_form = CommunityModeratorForm { community_id: main_community.id, - user_id: inserted_user.id, + person_id: inserted_user.id, }; let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); @@ -611,8 +611,8 @@ impl Perform for AddAdmin { // Mod tables let form = ModAddForm { - mod_user_id: user.id, - other_user_id: data.user_id, + mod_person_id: user.id, + other_person_id: data.user_id, removed: Some(!data.added), }; @@ -693,8 +693,8 @@ impl Perform for BanUser { }; let form = ModBanForm { - mod_user_id: user.id, - other_user_id: data.user_id, + mod_person_id: user.id, + other_person_id: data.user_id, reason: data.reason.to_owned(), banned: Some(data.ban), expires, @@ -989,7 +989,7 @@ impl Perform for PasswordChange { // Fetch the user_id from the token let token = data.token.clone(); let user_id = blocking(context.pool(), move |conn| { - PasswordResetRequest::read_from_token(conn, &token).map(|p| p.user_id) + PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id) }) .await??; diff --git a/crates/apub/src/activities/receive/comment.rs b/crates/apub/src/activities/receive/comment.rs index 6136f63bb..6d1817938 100644 --- a/crates/apub/src/activities/receive/comment.rs +++ b/crates/apub/src/activities/receive/comment.rs @@ -109,7 +109,7 @@ pub(crate) async fn receive_like_comment( let like_form = CommentLikeForm { comment_id, post_id: comment.post_id, - user_id: user.id, + person_id: user.id, score: 1, }; let user_id = user.id; @@ -154,7 +154,7 @@ pub(crate) async fn receive_dislike_comment( let like_form = CommentLikeForm { comment_id, post_id: comment.post_id, - user_id: user.id, + person_id: user.id, score: -1, }; let user_id = user.id; diff --git a/crates/apub/src/activities/receive/post.rs b/crates/apub/src/activities/receive/post.rs index 426358646..4f1530045 100644 --- a/crates/apub/src/activities/receive/post.rs +++ b/crates/apub/src/activities/receive/post.rs @@ -80,7 +80,7 @@ pub(crate) async fn receive_like_post( let post_id = post.id; let like_form = PostLikeForm { post_id, - user_id: user.id, + person_id: user.id, score: 1, }; let user_id = user.id; @@ -118,7 +118,7 @@ pub(crate) async fn receive_dislike_post( let post_id = post.id; let like_form = PostLikeForm { post_id, - user_id: user.id, + person_id: user.id, score: -1, }; let user_id = user.id; diff --git a/crates/apub/src/activities/send/user.rs b/crates/apub/src/activities/send/user.rs index 1847ec5c5..13ec73400 100644 --- a/crates/apub/src/activities/send/user.rs +++ b/crates/apub/src/activities/send/user.rs @@ -62,7 +62,7 @@ impl ActorType for User_ { let community_follower_form = CommunityFollowerForm { community_id: community.id, - user_id: self.id, + person_id: self.id, pending: true, }; blocking(&context.pool(), move |conn| { diff --git a/crates/apub/src/fetcher/community.rs b/crates/apub/src/fetcher/community.rs index cb9ec8651..e1211f33b 100644 --- a/crates/apub/src/fetcher/community.rs +++ b/crates/apub/src/fetcher/community.rs @@ -104,7 +104,7 @@ async fn fetch_remote_community( for mod_ in creator_and_moderators { let community_moderator_form = CommunityModeratorForm { community_id, - user_id: mod_.id, + person_id: mod_.id, }; CommunityModerator::join(conn, &community_moderator_form)?; diff --git a/crates/apub/src/inbox/community_inbox.rs b/crates/apub/src/inbox/community_inbox.rs index f9056a770..6a51f9fd7 100644 --- a/crates/apub/src/inbox/community_inbox.rs +++ b/crates/apub/src/inbox/community_inbox.rs @@ -191,7 +191,7 @@ async fn handle_follow( let community_follower_form = CommunityFollowerForm { community_id: community.id, - user_id: user.id, + person_id: user.id, pending: false, }; @@ -246,7 +246,7 @@ async fn handle_undo_follow( .await??; let community_follower_form = CommunityFollowerForm { community_id: community.id, - user_id: user.id, + person_id: user.id, pending: false, }; diff --git a/crates/db_queries/src/aggregates/comment_aggregates.rs b/crates/db_queries/src/aggregates/comment_aggregates.rs index a4db471b6..9f7d678e2 100644 --- a/crates/db_queries/src/aggregates/comment_aggregates.rs +++ b/crates/db_queries/src/aggregates/comment_aggregates.rs @@ -35,35 +35,25 @@ mod tests { comment::{Comment, CommentForm, CommentLike, CommentLikeForm}, community::{Community, CommunityForm}, post::{Post, PostForm}, - user::{UserForm, User_}, + person::{PersonForm, Person}, }; #[test] fn test_crud() { let conn = establish_unpooled_connection(); - let new_user = UserForm { + let new_person = PersonForm { name: "thommy_comment_agg".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, - banned: Some(false), + banned: None, + deleted: None, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, - local: true, + local: None, private_key: None, public_key: None, last_refreshed_at: None, @@ -71,30 +61,20 @@ mod tests { shared_inbox_url: None, }; - let inserted_user = User_::create(&conn, &new_user).unwrap(); + let inserted_person = Person::create(&conn, &new_person).unwrap(); - let another_user = UserForm { + let another_person = PersonForm { name: "jerry_comment_agg".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, - banned: Some(false), + banned: None, + deleted: None, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, - local: true, + local: None, private_key: None, public_key: None, last_refreshed_at: None, @@ -102,11 +82,11 @@ mod tests { shared_inbox_url: None, }; - let another_inserted_user = User_::create(&conn, &another_user).unwrap(); + let another_inserted_person = Person::create(&conn, &another_person).unwrap(); let new_community = CommunityForm { name: "TIL_comment_agg".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, title: "nada".to_owned(), description: None, nsfw: false, @@ -132,7 +112,7 @@ mod tests { name: "A test post".into(), url: None, body: None, - creator_id: inserted_user.id, + creator_id: inserted_person.id, community_id: inserted_community.id, removed: None, deleted: None, @@ -153,7 +133,7 @@ mod tests { let comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -169,7 +149,7 @@ mod tests { let child_comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -186,7 +166,7 @@ mod tests { let comment_like = CommentLikeForm { comment_id: inserted_comment.id, post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_person.id, score: 1, }; @@ -198,11 +178,11 @@ mod tests { assert_eq!(1, comment_aggs_before_delete.upvotes); assert_eq!(0, comment_aggs_before_delete.downvotes); - // Add a post dislike from the other user + // Add a post dislike from the other person let comment_dislike = CommentLikeForm { comment_id: inserted_comment.id, post_id: inserted_post.id, - user_id: another_inserted_user.id, + person_id: another_inserted_person.id, score: -1, }; @@ -215,7 +195,7 @@ mod tests { assert_eq!(1, comment_aggs_after_dislike.downvotes); // Remove the first comment like - CommentLike::remove(&conn, inserted_user.id, inserted_comment.id).unwrap(); + CommentLike::remove(&conn, inserted_person.id, inserted_comment.id).unwrap(); let after_like_remove = CommentAggregates::read(&conn, inserted_comment.id).unwrap(); assert_eq!(-1, after_like_remove.score); assert_eq!(0, after_like_remove.upvotes); @@ -229,8 +209,8 @@ mod tests { assert!(after_delete.is_err()); // This should delete all the associated rows, and fire triggers - User_::delete(&conn, another_inserted_user.id).unwrap(); - let user_num_deleted = User_::delete(&conn, inserted_user.id).unwrap(); - assert_eq!(1, user_num_deleted); + Person::delete(&conn, another_inserted_person.id).unwrap(); + let person_num_deleted = Person::delete(&conn, inserted_person.id).unwrap(); + assert_eq!(1, person_num_deleted); } } diff --git a/crates/db_queries/src/aggregates/community_aggregates.rs b/crates/db_queries/src/aggregates/community_aggregates.rs index f5cd577e4..159b323e8 100644 --- a/crates/db_queries/src/aggregates/community_aggregates.rs +++ b/crates/db_queries/src/aggregates/community_aggregates.rs @@ -39,32 +39,22 @@ mod tests { comment::{Comment, CommentForm}, community::{Community, CommunityFollower, CommunityFollowerForm, CommunityForm}, post::{Post, PostForm}, - user::{UserForm, User_}, + person::{PersonForm, Person}, }; #[test] fn test_crud() { let conn = establish_unpooled_connection(); - let new_user = UserForm { + let new_person = PersonForm { name: "thommy_community_agg".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -75,27 +65,17 @@ mod tests { shared_inbox_url: None, }; - let inserted_user = User_::create(&conn, &new_user).unwrap(); + let inserted_person = Person::create(&conn, &new_person).unwrap(); - let another_user = UserForm { + let another_person = PersonForm { name: "jerry_community_agg".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -106,11 +86,11 @@ mod tests { shared_inbox_url: None, }; - let another_inserted_user = User_::create(&conn, &another_user).unwrap(); + let another_inserted_person = Person::create(&conn, &another_person).unwrap(); let new_community = CommunityForm { name: "TIL_community_agg".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, title: "nada".to_owned(), description: None, nsfw: false, @@ -134,7 +114,7 @@ mod tests { let another_community = CommunityForm { name: "TIL_community_agg_2".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, title: "nada".to_owned(), description: None, nsfw: false, @@ -156,25 +136,25 @@ mod tests { let another_inserted_community = Community::create(&conn, &another_community).unwrap(); - let first_user_follow = CommunityFollowerForm { + let first_person_follow = CommunityFollowerForm { community_id: inserted_community.id, - user_id: inserted_user.id, + person_id: inserted_person.id, pending: false, }; - CommunityFollower::follow(&conn, &first_user_follow).unwrap(); + CommunityFollower::follow(&conn, &first_person_follow).unwrap(); - let second_user_follow = CommunityFollowerForm { + let second_person_follow = CommunityFollowerForm { community_id: inserted_community.id, - user_id: another_inserted_user.id, + person_id: another_inserted_person.id, pending: false, }; - CommunityFollower::follow(&conn, &second_user_follow).unwrap(); + CommunityFollower::follow(&conn, &second_person_follow).unwrap(); let another_community_follow = CommunityFollowerForm { community_id: another_inserted_community.id, - user_id: inserted_user.id, + person_id: inserted_person.id, pending: false, }; @@ -184,7 +164,7 @@ mod tests { name: "A test post".into(), url: None, body: None, - creator_id: inserted_user.id, + creator_id: inserted_person.id, community_id: inserted_community.id, removed: None, deleted: None, @@ -205,7 +185,7 @@ mod tests { let comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -221,7 +201,7 @@ mod tests { let child_comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -250,12 +230,12 @@ mod tests { assert_eq!(0, another_community_aggs.comments); // Unfollow test - CommunityFollower::unfollow(&conn, &second_user_follow).unwrap(); + CommunityFollower::unfollow(&conn, &second_person_follow).unwrap(); let after_unfollow = CommunityAggregates::read(&conn, inserted_community.id).unwrap(); assert_eq!(1, after_unfollow.subscribers); // Follow again just for the later tests - CommunityFollower::follow(&conn, &second_user_follow).unwrap(); + CommunityFollower::follow(&conn, &second_person_follow).unwrap(); let after_follow_again = CommunityAggregates::read(&conn, inserted_community.id).unwrap(); assert_eq!(2, after_follow_again.subscribers); @@ -265,14 +245,14 @@ mod tests { assert_eq!(0, after_parent_post_delete.comments); assert_eq!(0, after_parent_post_delete.posts); - // Remove the 2nd user - User_::delete(&conn, another_inserted_user.id).unwrap(); - let after_user_delete = CommunityAggregates::read(&conn, inserted_community.id).unwrap(); - assert_eq!(1, after_user_delete.subscribers); + // Remove the 2nd person + Person::delete(&conn, another_inserted_person.id).unwrap(); + let after_person_delete = CommunityAggregates::read(&conn, inserted_community.id).unwrap(); + assert_eq!(1, after_person_delete.subscribers); // This should delete all the associated rows, and fire triggers - let user_num_deleted = User_::delete(&conn, inserted_user.id).unwrap(); - assert_eq!(1, user_num_deleted); + let person_num_deleted = Person::delete(&conn, inserted_person.id).unwrap(); + assert_eq!(1, person_num_deleted); // Should be none found, since the creator was deleted let after_delete = CommunityAggregates::read(&conn, inserted_community.id); diff --git a/crates/db_queries/src/aggregates/mod.rs b/crates/db_queries/src/aggregates/mod.rs index bdef6591d..23854dfda 100644 --- a/crates/db_queries/src/aggregates/mod.rs +++ b/crates/db_queries/src/aggregates/mod.rs @@ -2,4 +2,4 @@ pub mod comment_aggregates; pub mod community_aggregates; pub mod post_aggregates; pub mod site_aggregates; -pub mod user_aggregates; +pub mod person_aggregates; diff --git a/crates/db_queries/src/aggregates/user_aggregates.rs b/crates/db_queries/src/aggregates/person_aggregates.rs similarity index 66% rename from crates/db_queries/src/aggregates/user_aggregates.rs rename to crates/db_queries/src/aggregates/person_aggregates.rs index fcda1d462..ccbba8db0 100644 --- a/crates/db_queries/src/aggregates/user_aggregates.rs +++ b/crates/db_queries/src/aggregates/person_aggregates.rs @@ -1,22 +1,22 @@ use diesel::{result::Error, *}; -use lemmy_db_schema::schema::user_aggregates; +use lemmy_db_schema::schema::person_aggregates; use serde::Serialize; #[derive(Queryable, Associations, Identifiable, PartialEq, Debug, Serialize, Clone)] -#[table_name = "user_aggregates"] -pub struct UserAggregates { +#[table_name = "person_aggregates"] +pub struct PersonAggregates { pub id: i32, - pub user_id: i32, + pub person_id: i32, pub post_count: i64, pub post_score: i64, pub comment_count: i64, pub comment_score: i64, } -impl UserAggregates { - pub fn read(conn: &PgConnection, user_id: i32) -> Result { - user_aggregates::table - .filter(user_aggregates::user_id.eq(user_id)) +impl PersonAggregates { + pub fn read(conn: &PgConnection, person_id: i32) -> Result { + person_aggregates::table + .filter(person_aggregates::person_id.eq(person_id)) .first::(conn) } } @@ -24,7 +24,7 @@ impl UserAggregates { #[cfg(test)] mod tests { use crate::{ - aggregates::user_aggregates::UserAggregates, + aggregates::person_aggregates::PersonAggregates, establish_unpooled_connection, Crud, Likeable, @@ -35,32 +35,22 @@ mod tests { comment::{Comment, CommentForm, CommentLike, CommentLikeForm}, community::{Community, CommunityForm}, post::{Post, PostForm, PostLike, PostLikeForm}, - user::{UserForm, User_}, + person::{PersonForm, Person}, }; #[test] fn test_crud() { let conn = establish_unpooled_connection(); - let new_user = UserForm { + let new_person = PersonForm { name: "thommy_user_agg".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -71,27 +61,17 @@ mod tests { shared_inbox_url: None, }; - let inserted_user = User_::create(&conn, &new_user).unwrap(); + let inserted_person = Person::create(&conn, &new_person).unwrap(); - let another_user = UserForm { + let another_person = PersonForm { name: "jerry_user_agg".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -102,11 +82,11 @@ mod tests { shared_inbox_url: None, }; - let another_inserted_user = User_::create(&conn, &another_user).unwrap(); + let another_inserted_person = Person::create(&conn, &another_person).unwrap(); let new_community = CommunityForm { name: "TIL_site_agg".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, title: "nada".to_owned(), description: None, nsfw: false, @@ -132,7 +112,7 @@ mod tests { name: "A test post".into(), url: None, body: None, - creator_id: inserted_user.id, + creator_id: inserted_person.id, community_id: inserted_community.id, removed: None, deleted: None, @@ -153,7 +133,7 @@ mod tests { let post_like = PostLikeForm { post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_person.id, score: 1, }; @@ -161,7 +141,7 @@ mod tests { let comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -177,7 +157,7 @@ mod tests { let mut comment_like = CommentLikeForm { comment_id: inserted_comment.id, - user_id: inserted_user.id, + person_id: inserted_person.id, post_id: inserted_post.id, score: 1, }; @@ -186,7 +166,7 @@ mod tests { let mut child_comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -202,28 +182,28 @@ mod tests { let child_comment_like = CommentLikeForm { comment_id: inserted_child_comment.id, - user_id: another_inserted_user.id, + person_id: another_inserted_person.id, post_id: inserted_post.id, score: 1, }; let _inserted_child_comment_like = CommentLike::like(&conn, &child_comment_like).unwrap(); - let user_aggregates_before_delete = UserAggregates::read(&conn, inserted_user.id).unwrap(); + let person_aggregates_before_delete = PersonAggregates::read(&conn, inserted_person.id).unwrap(); - assert_eq!(1, user_aggregates_before_delete.post_count); - assert_eq!(1, user_aggregates_before_delete.post_score); - assert_eq!(2, user_aggregates_before_delete.comment_count); - assert_eq!(2, user_aggregates_before_delete.comment_score); + assert_eq!(1, person_aggregates_before_delete.post_count); + assert_eq!(1, person_aggregates_before_delete.post_score); + assert_eq!(2, person_aggregates_before_delete.comment_count); + assert_eq!(2, person_aggregates_before_delete.comment_score); // Remove a post like - PostLike::remove(&conn, inserted_user.id, inserted_post.id).unwrap(); - let after_post_like_remove = UserAggregates::read(&conn, inserted_user.id).unwrap(); + PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap(); + let after_post_like_remove = PersonAggregates::read(&conn, inserted_person.id).unwrap(); assert_eq!(0, after_post_like_remove.post_score); // Remove a parent comment (the scores should also be removed) Comment::delete(&conn, inserted_comment.id).unwrap(); - let after_parent_comment_delete = UserAggregates::read(&conn, inserted_user.id).unwrap(); + let after_parent_comment_delete = PersonAggregates::read(&conn, inserted_person.id).unwrap(); assert_eq!(0, after_parent_comment_delete.comment_count); assert_eq!(0, after_parent_comment_delete.comment_score); @@ -233,24 +213,24 @@ mod tests { Comment::create(&conn, &child_comment_form).unwrap(); comment_like.comment_id = new_parent_comment.id; CommentLike::like(&conn, &comment_like).unwrap(); - let after_comment_add = UserAggregates::read(&conn, inserted_user.id).unwrap(); + let after_comment_add = PersonAggregates::read(&conn, inserted_person.id).unwrap(); assert_eq!(2, after_comment_add.comment_count); assert_eq!(1, after_comment_add.comment_score); Post::delete(&conn, inserted_post.id).unwrap(); - let after_post_delete = UserAggregates::read(&conn, inserted_user.id).unwrap(); + let after_post_delete = PersonAggregates::read(&conn, inserted_person.id).unwrap(); assert_eq!(0, after_post_delete.comment_score); assert_eq!(0, after_post_delete.comment_count); assert_eq!(0, after_post_delete.post_score); assert_eq!(0, after_post_delete.post_count); // This should delete all the associated rows, and fire triggers - let user_num_deleted = User_::delete(&conn, inserted_user.id).unwrap(); - assert_eq!(1, user_num_deleted); - User_::delete(&conn, another_inserted_user.id).unwrap(); + let person_num_deleted = Person::delete(&conn, inserted_person.id).unwrap(); + assert_eq!(1, person_num_deleted); + Person::delete(&conn, another_inserted_person.id).unwrap(); // Should be none found - let after_delete = UserAggregates::read(&conn, inserted_user.id); + let after_delete = PersonAggregates::read(&conn, inserted_person.id); assert!(after_delete.is_err()); } } diff --git a/crates/db_queries/src/aggregates/post_aggregates.rs b/crates/db_queries/src/aggregates/post_aggregates.rs index fa8b69255..f272e4f8c 100644 --- a/crates/db_queries/src/aggregates/post_aggregates.rs +++ b/crates/db_queries/src/aggregates/post_aggregates.rs @@ -31,40 +31,27 @@ mod tests { aggregates::post_aggregates::PostAggregates, establish_unpooled_connection, Crud, - Likeable, - ListingType, - SortType, }; use lemmy_db_schema::source::{ comment::{Comment, CommentForm}, community::{Community, CommunityForm}, post::{Post, PostForm, PostLike, PostLikeForm}, - user::{UserForm, User_}, + person::{PersonForm, Person}, }; #[test] fn test_crud() { let conn = establish_unpooled_connection(); - let new_user = UserForm { + let new_person = PersonForm { name: "thommy_community_agg".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -75,27 +62,17 @@ mod tests { shared_inbox_url: None, }; - let inserted_user = User_::create(&conn, &new_user).unwrap(); + let inserted_person = Person::create(&conn, &new_person).unwrap(); - let another_user = UserForm { + let another_person = PersonForm { name: "jerry_community_agg".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -106,11 +83,11 @@ mod tests { shared_inbox_url: None, }; - let another_inserted_user = User_::create(&conn, &another_user).unwrap(); + let another_inserted_person = Person::create(&conn, &another_person).unwrap(); let new_community = CommunityForm { name: "TIL_community_agg".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, title: "nada".to_owned(), description: None, nsfw: false, @@ -136,7 +113,7 @@ mod tests { name: "A test post".into(), url: None, body: None, - creator_id: inserted_user.id, + creator_id: inserted_person.id, community_id: inserted_community.id, removed: None, deleted: None, @@ -157,7 +134,7 @@ mod tests { let comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -173,7 +150,7 @@ mod tests { let child_comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -189,7 +166,7 @@ mod tests { let post_like = PostLikeForm { post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_person.id, score: 1, }; @@ -202,10 +179,10 @@ mod tests { assert_eq!(1, post_aggs_before_delete.upvotes); assert_eq!(0, post_aggs_before_delete.downvotes); - // Add a post dislike from the other user + // Add a post dislike from the other person let post_dislike = PostLikeForm { post_id: inserted_post.id, - user_id: another_inserted_user.id, + person_id: another_inserted_person.id, score: -1, }; @@ -227,7 +204,7 @@ mod tests { assert_eq!(1, after_comment_delete.downvotes); // Remove the first post like - PostLike::remove(&conn, inserted_user.id, inserted_post.id).unwrap(); + PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap(); let after_like_remove = PostAggregates::read(&conn, inserted_post.id).unwrap(); assert_eq!(0, after_like_remove.comments); assert_eq!(-1, after_like_remove.score); @@ -235,9 +212,9 @@ mod tests { assert_eq!(1, after_like_remove.downvotes); // This should delete all the associated rows, and fire triggers - User_::delete(&conn, another_inserted_user.id).unwrap(); - let user_num_deleted = User_::delete(&conn, inserted_user.id).unwrap(); - assert_eq!(1, user_num_deleted); + Person::delete(&conn, another_inserted_person.id).unwrap(); + let person_num_deleted = Person::delete(&conn, inserted_person.id).unwrap(); + assert_eq!(1, person_num_deleted); // Should be none found, since the creator was deleted let after_delete = PostAggregates::read(&conn, inserted_post.id); diff --git a/crates/db_queries/src/aggregates/site_aggregates.rs b/crates/db_queries/src/aggregates/site_aggregates.rs index 46db2f0cd..2f33b507d 100644 --- a/crates/db_queries/src/aggregates/site_aggregates.rs +++ b/crates/db_queries/src/aggregates/site_aggregates.rs @@ -28,41 +28,28 @@ mod tests { use crate::{ aggregates::site_aggregates::SiteAggregates, establish_unpooled_connection, - Crud, - ListingType, - SortType, }; use lemmy_db_schema::source::{ comment::{Comment, CommentForm}, community::{Community, CommunityForm}, post::{Post, PostForm}, site::{Site, SiteForm}, - user::{UserForm, User_}, + person::{PersonForm, Person}, }; #[test] fn test_crud() { let conn = establish_unpooled_connection(); - let new_user = UserForm { + let new_person = PersonForm { name: "thommy_site_agg".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -73,14 +60,14 @@ mod tests { shared_inbox_url: None, }; - let inserted_user = User_::create(&conn, &new_user).unwrap(); + let inserted_person = Person::create(&conn, &new_person).unwrap(); let site_form = SiteForm { name: "test_site".into(), description: None, icon: None, banner: None, - creator_id: inserted_user.id, + creator_id: inserted_person.id, enable_downvotes: true, open_registration: true, enable_nsfw: true, @@ -91,7 +78,7 @@ mod tests { let new_community = CommunityForm { name: "TIL_site_agg".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, title: "nada".to_owned(), description: None, nsfw: false, @@ -117,7 +104,7 @@ mod tests { name: "A test post".into(), url: None, body: None, - creator_id: inserted_user.id, + creator_id: inserted_person.id, community_id: inserted_community.id, removed: None, deleted: None, @@ -140,7 +127,7 @@ mod tests { let comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -157,7 +144,7 @@ mod tests { let child_comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -185,8 +172,8 @@ mod tests { assert_eq!(0, site_aggregates_after_post_delete.comments); // This shouuld delete all the associated rows, and fire triggers - let user_num_deleted = User_::delete(&conn, inserted_user.id).unwrap(); - assert_eq!(1, user_num_deleted); + let person_num_deleted = Person::delete(&conn, inserted_person.id).unwrap(); + assert_eq!(1, person_num_deleted); let after_delete = SiteAggregates::read(&conn); assert!(after_delete.is_err()); diff --git a/crates/db_queries/src/source/activity.rs b/crates/db_queries/src/source/activity.rs index 59e1754aa..7c00681e4 100644 --- a/crates/db_queries/src/source/activity.rs +++ b/crates/db_queries/src/source/activity.rs @@ -124,13 +124,10 @@ mod tests { use crate::{ establish_unpooled_connection, source::activity::Activity_, - Crud, - ListingType, - SortType, }; use lemmy_db_schema::source::{ activity::{Activity, ActivityForm}, - user::{UserForm, User_}, + person::{PersonForm, Person}, }; use serde_json::Value; @@ -138,28 +135,18 @@ mod tests { fn test_crud() { let conn = establish_unpooled_connection(); - let creator_form = UserForm { + let creator_form = PersonForm { name: "activity_creator_pm".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, - banned: Some(false), + banned: None, + deleted: None, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, - local: true, + local: None, private_key: None, public_key: None, last_refreshed_at: None, @@ -167,7 +154,7 @@ mod tests { shared_inbox_url: None, }; - let inserted_creator = User_::create(&conn, &creator_form).unwrap(); + let inserted_creator = Person::create(&conn, &creator_form).unwrap(); let ap_id = "https://enterprise.lemmy.ml/activities/delete/f1b5d57c-80f8-4e03-a615-688d552e946c"; @@ -207,7 +194,7 @@ mod tests { let read_activity = Activity::read(&conn, inserted_activity.id).unwrap(); let read_activity_by_apub_id = Activity::read_from_apub_id(&conn, ap_id).unwrap(); - User_::delete(&conn, inserted_creator.id).unwrap(); + Person::delete(&conn, inserted_creator.id).unwrap(); Activity::delete(&conn, inserted_activity.id).unwrap(); assert_eq!(expected_activity, read_activity); diff --git a/crates/db_queries/src/source/comment.rs b/crates/db_queries/src/source/comment.rs index 709a8aa39..583a59e6d 100644 --- a/crates/db_queries/src/source/comment.rs +++ b/crates/db_queries/src/source/comment.rs @@ -166,17 +166,17 @@ impl Likeable for CommentLike { use lemmy_db_schema::schema::comment_like::dsl::*; insert_into(comment_like) .values(comment_like_form) - .on_conflict((comment_id, user_id)) + .on_conflict((comment_id, person_id)) .do_update() .set(comment_like_form) .get_result::(conn) } - fn remove(conn: &PgConnection, user_id: i32, comment_id: i32) -> Result { + fn remove(conn: &PgConnection, person_id: i32, comment_id: i32) -> Result { use lemmy_db_schema::schema::comment_like::dsl; diesel::delete( dsl::comment_like .filter(dsl::comment_id.eq(comment_id)) - .filter(dsl::user_id.eq(user_id)), + .filter(dsl::person_id.eq(person_id)), ) .execute(conn) } @@ -197,7 +197,7 @@ impl Saveable for CommentSaved { diesel::delete( comment_saved .filter(comment_id.eq(comment_saved_form.comment_id)) - .filter(user_id.eq(comment_saved_form.user_id)), + .filter(user_id.eq(comment_saved_form.person_id)), ) .execute(conn) } @@ -210,32 +210,22 @@ mod tests { comment::*, community::{Community, CommunityForm}, post::*, - user::{UserForm, User_}, + person::{PersonForm, Person}, }; #[test] fn test_crud() { let conn = establish_unpooled_connection(); - let new_user = UserForm { + let new_person = PersonForm { name: "terry".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -246,13 +236,13 @@ mod tests { shared_inbox_url: None, }; - let inserted_user = User_::create(&conn, &new_user).unwrap(); + let inserted_persod = Person::create(&conn, &new_person).unwrap(); let new_community = CommunityForm { name: "test community".to_string(), title: "nada".to_owned(), description: None, - creator_id: inserted_user.id, + creator_id: inserted_persod.id, removed: None, deleted: None, updated: None, @@ -274,7 +264,7 @@ mod tests { let new_post = PostForm { name: "A test post".into(), - creator_id: inserted_user.id, + creator_id: inserted_persod.id, url: None, body: None, community_id: inserted_community.id, @@ -297,7 +287,7 @@ mod tests { let comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_persod.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -314,7 +304,7 @@ mod tests { let expected_comment = Comment { id: inserted_comment.id, content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_persod.id, post_id: inserted_post.id, removed: false, deleted: false, @@ -328,7 +318,7 @@ mod tests { let child_comment_form = CommentForm { content: "A child comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_persod.id, post_id: inserted_post.id, parent_id: Some(inserted_comment.id), removed: None, @@ -346,7 +336,7 @@ mod tests { let comment_like_form = CommentLikeForm { comment_id: inserted_comment.id, post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_persod.id, score: 1, }; @@ -356,7 +346,7 @@ mod tests { id: inserted_comment_like.id, comment_id: inserted_comment.id, post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_persod.id, published: inserted_comment_like.published, score: 1, }; @@ -364,7 +354,7 @@ mod tests { // Comment Saved let comment_saved_form = CommentSavedForm { comment_id: inserted_comment.id, - user_id: inserted_user.id, + person_id: inserted_persod.id, }; let inserted_comment_saved = CommentSaved::save(&conn, &comment_saved_form).unwrap(); @@ -372,19 +362,19 @@ mod tests { let expected_comment_saved = CommentSaved { id: inserted_comment_saved.id, comment_id: inserted_comment.id, - user_id: inserted_user.id, + person_id: inserted_persod.id, published: inserted_comment_saved.published, }; let read_comment = Comment::read(&conn, inserted_comment.id).unwrap(); let updated_comment = Comment::update(&conn, inserted_comment.id, &comment_form).unwrap(); - let like_removed = CommentLike::remove(&conn, inserted_user.id, inserted_comment.id).unwrap(); + let like_removed = CommentLike::remove(&conn, inserted_persod.id, inserted_comment.id).unwrap(); let saved_removed = CommentSaved::unsave(&conn, &comment_saved_form).unwrap(); let num_deleted = Comment::delete(&conn, inserted_comment.id).unwrap(); Comment::delete(&conn, inserted_child_comment.id).unwrap(); Post::delete(&conn, inserted_post.id).unwrap(); Community::delete(&conn, inserted_community.id).unwrap(); - User_::delete(&conn, inserted_user.id).unwrap(); + Person::delete(&conn, inserted_persod.id).unwrap(); assert_eq!(expected_comment, read_comment); assert_eq!(expected_comment, inserted_comment); diff --git a/crates/db_queries/src/source/community.rs b/crates/db_queries/src/source/community.rs index 08421bd5d..2b61d312f 100644 --- a/crates/db_queries/src/source/community.rs +++ b/crates/db_queries/src/source/community.rs @@ -9,8 +9,8 @@ use lemmy_db_schema::{ CommunityForm, CommunityModerator, CommunityModeratorForm, - CommunityUserBan, - CommunityUserBanForm, + CommunityPersonBan, + CommunityPersonBanForm, }, Url, }; @@ -206,23 +206,23 @@ impl Community_ for Community { impl Joinable for CommunityModerator { fn join( conn: &PgConnection, - community_user_form: &CommunityModeratorForm, + community_moderator_form: &CommunityModeratorForm, ) -> Result { use lemmy_db_schema::schema::community_moderator::dsl::*; insert_into(community_moderator) - .values(community_user_form) + .values(community_moderator_form) .get_result::(conn) } fn leave( conn: &PgConnection, - community_user_form: &CommunityModeratorForm, + community_moderator_form: &CommunityModeratorForm, ) -> Result { use lemmy_db_schema::schema::community_moderator::dsl::*; diesel::delete( community_moderator - .filter(community_id.eq(community_user_form.community_id)) - .filter(user_id.eq(community_user_form.user_id)), + .filter(community_id.eq(community_moderator_form.community_id)) + .filter(person_id.eq(community_moderator_form.person_id)), ) .execute(conn) } @@ -230,9 +230,9 @@ impl Joinable for CommunityModerator { pub trait CommunityModerator_ { fn delete_for_community(conn: &PgConnection, for_community_id: i32) -> Result; - fn get_user_moderated_communities( + fn get_person_moderated_communities( conn: &PgConnection, - for_user_id: i32, + for_person_id: i32, ) -> Result, Error>; } @@ -242,38 +242,38 @@ impl CommunityModerator_ for CommunityModerator { diesel::delete(community_moderator.filter(community_id.eq(for_community_id))).execute(conn) } - fn get_user_moderated_communities( + fn get_person_moderated_communities( conn: &PgConnection, - for_user_id: i32, + for_person_id: i32, ) -> Result, Error> { use lemmy_db_schema::schema::community_moderator::dsl::*; community_moderator - .filter(user_id.eq(for_user_id)) + .filter(person_id.eq(for_person_id)) .select(community_id) .load::(conn) } } -impl Bannable for CommunityUserBan { +impl Bannable for CommunityPersonBan { fn ban( conn: &PgConnection, - community_user_ban_form: &CommunityUserBanForm, + community_person_ban_form: &CommunityPersonBanForm, ) -> Result { - use lemmy_db_schema::schema::community_user_ban::dsl::*; - insert_into(community_user_ban) - .values(community_user_ban_form) + use lemmy_db_schema::schema::community_person_ban::dsl::*; + insert_into(community_person_ban) + .values(community_person_ban_form) .get_result::(conn) } fn unban( conn: &PgConnection, - community_user_ban_form: &CommunityUserBanForm, + community_person_ban_form: &CommunityPersonBanForm, ) -> Result { - use lemmy_db_schema::schema::community_user_ban::dsl::*; + use lemmy_db_schema::schema::community_person_ban::dsl::*; diesel::delete( - community_user_ban - .filter(community_id.eq(community_user_ban_form.community_id)) - .filter(user_id.eq(community_user_ban_form.user_id)), + community_person_ban + .filter(community_id.eq(community_person_ban_form.community_id)) + .filter(person_id.eq(community_person_ban_form.person_id)), ) .execute(conn) } @@ -313,7 +313,7 @@ impl Followable for CommunityFollower { diesel::delete( community_follower .filter(community_id.eq(&community_follower_form.community_id)) - .filter(user_id.eq(&community_follower_form.user_id)), + .filter(user_id.eq(&community_follower_form.person_id)), ) .execute(conn) } @@ -339,31 +339,21 @@ mod tests { ListingType, SortType, }; - use lemmy_db_schema::source::{community::*, user::*}; + use lemmy_db_schema::source::{community::*, person::*}; #[test] fn test_crud() { let conn = establish_unpooled_connection(); - let new_user = UserForm { + let new_person = PersonForm { name: "bobbee".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -374,11 +364,11 @@ mod tests { shared_inbox_url: None, }; - let inserted_user = User_::create(&conn, &new_user).unwrap(); + let inserted_person = Person::create(&conn, &new_person).unwrap(); let new_community = CommunityForm { name: "TIL".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, title: "nada".to_owned(), description: None, nsfw: false, @@ -402,7 +392,7 @@ mod tests { let expected_community = Community { id: inserted_community.id, - creator_id: inserted_user.id, + creator_id: inserted_person.id, name: "TIL".into(), title: "nada".to_owned(), description: None, @@ -425,7 +415,7 @@ mod tests { let community_follower_form = CommunityFollowerForm { community_id: inserted_community.id, - user_id: inserted_user.id, + person_id: inserted_person.id, pending: false, }; @@ -435,55 +425,55 @@ mod tests { let expected_community_follower = CommunityFollower { id: inserted_community_follower.id, community_id: inserted_community.id, - user_id: inserted_user.id, + person_id: inserted_person.id, pending: Some(false), published: inserted_community_follower.published, }; - let community_user_form = CommunityModeratorForm { + let community_moderator_form = CommunityModeratorForm { community_id: inserted_community.id, - user_id: inserted_user.id, + person_id: inserted_person.id, }; - let inserted_community_user = CommunityModerator::join(&conn, &community_user_form).unwrap(); + let inserted_community_moderator = CommunityModerator::join(&conn, &community_moderator_form).unwrap(); - let expected_community_user = CommunityModerator { - id: inserted_community_user.id, + let expected_community_moderator = CommunityModerator { + id: inserted_community_moderator.id, community_id: inserted_community.id, - user_id: inserted_user.id, - published: inserted_community_user.published, + person_id: inserted_person.id, + published: inserted_community_moderator.published, }; - let community_user_ban_form = CommunityUserBanForm { + let community_person_ban_form = CommunityPersonBanForm { community_id: inserted_community.id, - user_id: inserted_user.id, + person_id: inserted_person.id, }; - let inserted_community_user_ban = - CommunityUserBan::ban(&conn, &community_user_ban_form).unwrap(); + let inserted_community_person_ban = + CommunityPersonBan::ban(&conn, &community_person_ban_form).unwrap(); - let expected_community_user_ban = CommunityUserBan { - id: inserted_community_user_ban.id, + let expected_community_person_ban = CommunityPersonBan { + id: inserted_community_person_ban.id, community_id: inserted_community.id, - user_id: inserted_user.id, - published: inserted_community_user_ban.published, + person_id: inserted_person.id, + published: inserted_community_person_ban.published, }; let read_community = Community::read(&conn, inserted_community.id).unwrap(); let updated_community = Community::update(&conn, inserted_community.id, &new_community).unwrap(); let ignored_community = CommunityFollower::unfollow(&conn, &community_follower_form).unwrap(); - let left_community = CommunityModerator::leave(&conn, &community_user_form).unwrap(); - let unban = CommunityUserBan::unban(&conn, &community_user_ban_form).unwrap(); + let left_community = CommunityModerator::leave(&conn, &community_moderator_form).unwrap(); + let unban = CommunityPersonBan::unban(&conn, &community_person_ban_form).unwrap(); let num_deleted = Community::delete(&conn, inserted_community.id).unwrap(); - User_::delete(&conn, inserted_user.id).unwrap(); + Person::delete(&conn, inserted_person.id).unwrap(); assert_eq!(expected_community, read_community); assert_eq!(expected_community, inserted_community); assert_eq!(expected_community, updated_community); assert_eq!(expected_community_follower, inserted_community_follower); - assert_eq!(expected_community_user, inserted_community_user); - assert_eq!(expected_community_user_ban, inserted_community_user_ban); + assert_eq!(expected_community_moderator, inserted_community_moderator); + assert_eq!(expected_community_person_ban, inserted_community_person_ban); assert_eq!(1, ignored_community); assert_eq!(1, left_community); assert_eq!(1, unban); diff --git a/crates/db_queries/src/source/local_user.rs b/crates/db_queries/src/source/local_user.rs new file mode 100644 index 000000000..537438642 --- /dev/null +++ b/crates/db_queries/src/source/local_user.rs @@ -0,0 +1,76 @@ +use crate::{is_email_regex, ApubObject, Crud, ToSafeSettings}; +mod safe_settings_type { + use crate::ToSafeSettings; + use lemmy_db_schema::{schema::user_::columns::*, source::user::User_}; + + type Columns = ( + id, + name, + preferred_username, + email, + avatar, + admin, + banned, + published, + updated, + show_nsfw, + theme, + default_sort_type, + default_listing_type, + lang, + show_avatars, + send_notifications_to_email, + matrix_user_id, + actor_id, + bio, + local, + last_refreshed_at, + banner, + deleted, + ); + + impl ToSafeSettings for User_ { + type SafeSettingsColumns = Columns; + fn safe_settings_columns_tuple() -> Self::SafeSettingsColumns { + ( + id, + name, + preferred_username, + email, + avatar, + admin, + banned, + published, + updated, + show_nsfw, + theme, + default_sort_type, + default_listing_type, + lang, + show_avatars, + send_notifications_to_email, + matrix_user_id, + actor_id, + bio, + local, + last_refreshed_at, + banner, + deleted, + ) + } + } +} + +pub trait UserSafeSettings_ { + fn read(conn: &PgConnection, user_id: i32) -> Result; +} + +impl UserSafeSettings_ for UserSafeSettings { + fn read(conn: &PgConnection, user_id: i32) -> Result { + user_ + .select(User_::safe_settings_columns_tuple()) + .filter(deleted.eq(false)) + .find(user_id) + .first::(conn) + } +} diff --git a/crates/db_queries/src/source/mod.rs b/crates/db_queries/src/source/mod.rs index a39dc1108..4882ddf4b 100644 --- a/crates/db_queries/src/source/mod.rs +++ b/crates/db_queries/src/source/mod.rs @@ -8,5 +8,6 @@ pub mod post; pub mod post_report; pub mod private_message; pub mod site; -pub mod user; -pub mod user_mention; +pub mod person; +pub mod person_mention; +pub mod local_user; diff --git a/crates/db_queries/src/source/moderator.rs b/crates/db_queries/src/source/moderator.rs index 9b6e58edf..36d90fdd3 100644 --- a/crates/db_queries/src/source/moderator.rs +++ b/crates/db_queries/src/source/moderator.rs @@ -198,32 +198,22 @@ impl Crud for ModAdd { #[cfg(test)] mod tests { use crate::{establish_unpooled_connection, Crud, ListingType, SortType}; - use lemmy_db_schema::source::{comment::*, community::*, moderator::*, post::*, user::*}; + use lemmy_db_schema::source::{comment::*, community::*, moderator::*, post::*, person::*}; // use Crud; #[test] fn test_crud() { let conn = establish_unpooled_connection(); - let new_mod = UserForm { + let new_mod = PersonForm { name: "the mod".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -234,27 +224,17 @@ mod tests { shared_inbox_url: None, }; - let inserted_mod = User_::create(&conn, &new_mod).unwrap(); + let inserted_mod = Person::create(&conn, &new_mod).unwrap(); - let new_user = UserForm { + let new_person = PersonForm { name: "jim2".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -265,13 +245,13 @@ mod tests { shared_inbox_url: None, }; - let inserted_user = User_::create(&conn, &new_user).unwrap(); + let inserted_person = Person::create(&conn, &new_person).unwrap(); let new_community = CommunityForm { name: "mod_community".to_string(), title: "nada".to_owned(), description: None, - creator_id: inserted_user.id, + creator_id: inserted_person.id, removed: None, deleted: None, updated: None, @@ -295,7 +275,7 @@ mod tests { name: "A test post thweep".into(), url: None, body: None, - creator_id: inserted_user.id, + creator_id: inserted_person.id, community_id: inserted_community.id, removed: None, deleted: None, @@ -316,7 +296,7 @@ mod tests { let comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -334,7 +314,7 @@ mod tests { // remove post let mod_remove_post_form = ModRemovePostForm { - mod_user_id: inserted_mod.id, + mod_person_id: inserted_mod.id, post_id: inserted_post.id, reason: None, removed: None, @@ -344,7 +324,7 @@ mod tests { let expected_mod_remove_post = ModRemovePost { id: inserted_mod_remove_post.id, post_id: inserted_post.id, - mod_user_id: inserted_mod.id, + mod_person_id: inserted_mod.id, reason: None, removed: Some(true), when_: inserted_mod_remove_post.when_, @@ -353,7 +333,7 @@ mod tests { // lock post let mod_lock_post_form = ModLockPostForm { - mod_user_id: inserted_mod.id, + mod_person_id: inserted_mod.id, post_id: inserted_post.id, locked: None, }; @@ -362,7 +342,7 @@ mod tests { let expected_mod_lock_post = ModLockPost { id: inserted_mod_lock_post.id, post_id: inserted_post.id, - mod_user_id: inserted_mod.id, + mod_person_id: inserted_mod.id, locked: Some(true), when_: inserted_mod_lock_post.when_, }; @@ -370,7 +350,7 @@ mod tests { // sticky post let mod_sticky_post_form = ModStickyPostForm { - mod_user_id: inserted_mod.id, + mod_person_id: inserted_mod.id, post_id: inserted_post.id, stickied: None, }; @@ -379,7 +359,7 @@ mod tests { let expected_mod_sticky_post = ModStickyPost { id: inserted_mod_sticky_post.id, post_id: inserted_post.id, - mod_user_id: inserted_mod.id, + mod_person_id: inserted_mod.id, stickied: Some(true), when_: inserted_mod_sticky_post.when_, }; @@ -387,7 +367,7 @@ mod tests { // comment let mod_remove_comment_form = ModRemoveCommentForm { - mod_user_id: inserted_mod.id, + mod_person_id: inserted_mod.id, comment_id: inserted_comment.id, reason: None, removed: None, @@ -399,7 +379,7 @@ mod tests { let expected_mod_remove_comment = ModRemoveComment { id: inserted_mod_remove_comment.id, comment_id: inserted_comment.id, - mod_user_id: inserted_mod.id, + mod_person_id: inserted_mod.id, reason: None, removed: Some(true), when_: inserted_mod_remove_comment.when_, @@ -408,7 +388,7 @@ mod tests { // community let mod_remove_community_form = ModRemoveCommunityForm { - mod_user_id: inserted_mod.id, + mod_person_id: inserted_mod.id, community_id: inserted_community.id, reason: None, removed: None, @@ -421,7 +401,7 @@ mod tests { let expected_mod_remove_community = ModRemoveCommunity { id: inserted_mod_remove_community.id, community_id: inserted_community.id, - mod_user_id: inserted_mod.id, + mod_person_id: inserted_mod.id, reason: None, removed: Some(true), expires: None, @@ -431,8 +411,8 @@ mod tests { // ban from community let mod_ban_from_community_form = ModBanFromCommunityForm { - mod_user_id: inserted_mod.id, - other_user_id: inserted_user.id, + mod_person_id: inserted_mod.id, + other_person_id: inserted_person.id, community_id: inserted_community.id, reason: None, banned: None, @@ -445,8 +425,8 @@ mod tests { let expected_mod_ban_from_community = ModBanFromCommunity { id: inserted_mod_ban_from_community.id, community_id: inserted_community.id, - mod_user_id: inserted_mod.id, - other_user_id: inserted_user.id, + mod_person_id: inserted_mod.id, + other_person_id: inserted_person.id, reason: None, banned: Some(true), expires: None, @@ -456,8 +436,8 @@ mod tests { // ban let mod_ban_form = ModBanForm { - mod_user_id: inserted_mod.id, - other_user_id: inserted_user.id, + mod_person_id: inserted_mod.id, + other_person_id: inserted_person.id, reason: None, banned: None, expires: None, @@ -466,8 +446,8 @@ mod tests { let read_mod_ban = ModBan::read(&conn, inserted_mod_ban.id).unwrap(); let expected_mod_ban = ModBan { id: inserted_mod_ban.id, - mod_user_id: inserted_mod.id, - other_user_id: inserted_user.id, + mod_person_id: inserted_mod.id, + other_person_id: inserted_person.id, reason: None, banned: Some(true), expires: None, @@ -477,8 +457,8 @@ mod tests { // mod add community let mod_add_community_form = ModAddCommunityForm { - mod_user_id: inserted_mod.id, - other_user_id: inserted_user.id, + mod_person_id: inserted_mod.id, + other_person_id: inserted_person.id, community_id: inserted_community.id, removed: None, }; @@ -489,8 +469,8 @@ mod tests { let expected_mod_add_community = ModAddCommunity { id: inserted_mod_add_community.id, community_id: inserted_community.id, - mod_user_id: inserted_mod.id, - other_user_id: inserted_user.id, + mod_person_id: inserted_mod.id, + other_person_id: inserted_person.id, removed: Some(false), when_: inserted_mod_add_community.when_, }; @@ -498,16 +478,16 @@ mod tests { // mod add let mod_add_form = ModAddForm { - mod_user_id: inserted_mod.id, - other_user_id: inserted_user.id, + mod_person_id: inserted_mod.id, + other_person_id: inserted_person.id, removed: None, }; let inserted_mod_add = ModAdd::create(&conn, &mod_add_form).unwrap(); let read_mod_add = ModAdd::read(&conn, inserted_mod_add.id).unwrap(); let expected_mod_add = ModAdd { id: inserted_mod_add.id, - mod_user_id: inserted_mod.id, - other_user_id: inserted_user.id, + mod_person_id: inserted_mod.id, + other_person_id: inserted_person.id, removed: Some(false), when_: inserted_mod_add.when_, }; @@ -515,8 +495,8 @@ mod tests { Comment::delete(&conn, inserted_comment.id).unwrap(); Post::delete(&conn, inserted_post.id).unwrap(); Community::delete(&conn, inserted_community.id).unwrap(); - User_::delete(&conn, inserted_user.id).unwrap(); - User_::delete(&conn, inserted_mod.id).unwrap(); + Person::delete(&conn, inserted_person.id).unwrap(); + Person::delete(&conn, inserted_mod.id).unwrap(); assert_eq!(expected_mod_remove_post, read_mod_remove_post); assert_eq!(expected_mod_lock_post, read_mod_lock_post); diff --git a/crates/db_queries/src/source/password_reset_request.rs b/crates/db_queries/src/source/password_reset_request.rs index f58d2c014..a8524cfb5 100644 --- a/crates/db_queries/src/source/password_reset_request.rs +++ b/crates/db_queries/src/source/password_reset_request.rs @@ -28,7 +28,7 @@ impl Crud for PasswordResetRequest { pub trait PasswordResetRequest_ { fn create_token( conn: &PgConnection, - from_user_id: i32, + from_local_user_id: i32, token: &str, ) -> Result; fn read_from_token(conn: &PgConnection, token: &str) -> Result; @@ -37,7 +37,7 @@ pub trait PasswordResetRequest_ { impl PasswordResetRequest_ for PasswordResetRequest { fn create_token( conn: &PgConnection, - from_user_id: i32, + from_local_user_id: i32, token: &str, ) -> Result { let mut hasher = Sha256::new(); @@ -45,7 +45,7 @@ impl PasswordResetRequest_ for PasswordResetRequest { let token_hash: String = bytes_to_hex(hasher.finalize().to_vec()); let form = PasswordResetRequestForm { - user_id: from_user_id, + local_user_id: from_local_user_id, token_encrypted: token_hash, }; @@ -79,31 +79,21 @@ mod tests { ListingType, SortType, }; - use lemmy_db_schema::source::{password_reset_request::PasswordResetRequest, user::*}; + use lemmy_db_schema::source::{password_reset_request::PasswordResetRequest, person::*}; #[test] fn test_crud() { let conn = establish_unpooled_connection(); - let new_user = UserForm { + let new_person = PersonForm { name: "thommy prw".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -114,23 +104,23 @@ mod tests { shared_inbox_url: None, }; - let inserted_user = User_::create(&conn, &new_user).unwrap(); + let inserted_person = Person::create(&conn, &new_person).unwrap(); let token = "nope"; let token_encrypted_ = "ca3704aa0b06f5954c79ee837faa152d84d6b2d42838f0637a15eda8337dbdce"; let inserted_password_reset_request = - PasswordResetRequest::create_token(&conn, inserted_user.id, token).unwrap(); + PasswordResetRequest::create_token(&conn, inserted_person.id, token).unwrap(); let expected_password_reset_request = PasswordResetRequest { id: inserted_password_reset_request.id, - user_id: inserted_user.id, + local_user_id: inserted_person.id, token_encrypted: token_encrypted_.to_string(), published: inserted_password_reset_request.published, }; let read_password_reset_request = PasswordResetRequest::read_from_token(&conn, token).unwrap(); - let num_deleted = User_::delete(&conn, inserted_user.id).unwrap(); + let num_deleted = Person::delete(&conn, inserted_person.id).unwrap(); assert_eq!(expected_password_reset_request, read_password_reset_request); assert_eq!( diff --git a/crates/db_queries/src/source/person.rs b/crates/db_queries/src/source/person.rs new file mode 100644 index 000000000..e17fcda5a --- /dev/null +++ b/crates/db_queries/src/source/person.rs @@ -0,0 +1,364 @@ +use crate::{is_email_regex, ApubObject, Crud, ToSafeSettings}; +use bcrypt::{hash, DEFAULT_COST}; +use diesel::{dsl::*, result::Error, *}; +use lemmy_db_schema::{ + naive_now, + schema::person::dsl::*, + source::person::{PersonForm, Person}, + Url, +}; +use lemmy_utils::settings::Settings; + +mod safe_type { + use crate::ToSafe; + use lemmy_db_schema::{schema::person::columns::*, source::person::Person}; + + type Columns = ( + id, + name, + preferred_username, + avatar, + banned, + published, + updated, + actor_id, + bio, + local, + last_refreshed_at, + banner, + deleted, + inbox_url, + shared_inbox_url, + ); + + impl ToSafe for Person { + type SafeColumns = Columns; + fn safe_columns_tuple() -> Self::SafeColumns { + ( + id, + name, + preferred_username, + avatar, + banned, + published, + updated, + actor_id, + bio, + local, + last_refreshed_at, + banner, + deleted, + inbox_url, + shared_inbox_url, + ) + } + } +} + +mod safe_type_alias_1 { + use crate::ToSafe; + use lemmy_db_schema::{schema::person_alias_1::columns::*, source::person::PersonAlias1}; + + type Columns = ( + id, + name, + preferred_username, + avatar, + banned, + published, + updated, + actor_id, + bio, + local, + last_refreshed_at, + banner, + deleted, + inbox_url, + shared_inbox_url, + ); + + impl ToSafe for PersonAlias1 { + type SafeColumns = Columns; + fn safe_columns_tuple() -> Self::SafeColumns { + ( + id, + name, + preferred_username, + avatar, + banned, + published, + updated, + actor_id, + bio, + local, + last_refreshed_at, + banner, + deleted, + inbox_url, + shared_inbox_url, + ) + } + } +} + +mod safe_type_alias_2 { + use crate::ToSafe; + use lemmy_db_schema::{schema::person_alias_2::columns::*, source::person::PersonAlias2}; + + type Columns = ( + id, + name, + preferred_username, + avatar, + banned, + published, + updated, + actor_id, + bio, + local, + last_refreshed_at, + banner, + deleted, + inbox_url, + shared_inbox_url, + ); + + impl ToSafe for PersonAlias2 { + type SafeColumns = Columns; + fn safe_columns_tuple() -> Self::SafeColumns { + ( + id, + name, + preferred_username, + avatar, + banned, + published, + updated, + actor_id, + bio, + local, + last_refreshed_at, + banner, + deleted, + inbox_url, + shared_inbox_url, + ) + } + } +} + +impl Crud for Person { + fn read(conn: &PgConnection, person_id: i32) -> Result { + person + .filter(deleted.eq(false)) + .find(person_id) + .first::(conn) + } + fn delete(conn: &PgConnection, person_id: i32) -> Result { + diesel::delete(person.find(person_id)).execute(conn) + } + fn create(conn: &PgConnection, form: &PersonForm) -> Result { + insert_into(person).values(form).get_result::(conn) + } + fn update(conn: &PgConnection, person_id: i32, form: &PersonForm) -> Result { + diesel::update(person.find(person_id)) + .set(form) + .get_result::(conn) + } +} + +impl ApubObject for Person { + fn read_from_apub_id(conn: &PgConnection, object_id: &Url) -> Result { + use lemmy_db_schema::schema::person::dsl::*; + person + .filter(deleted.eq(false)) + .filter(actor_id.eq(object_id)) + .first::(conn) + } + + fn upsert(conn: &PgConnection, person_form: &PersonForm) -> Result { + insert_into(person) + .values(person_form) + .on_conflict(actor_id) + .do_update() + .set(person_form) + .get_result::(conn) + } +} + +pub trait Person_ { + fn register(conn: &PgConnection, form: &PersonForm) -> Result; + fn update_password(conn: &PgConnection, person_id: i32, new_password: &str) + -> Result; + fn read_from_name(conn: &PgConnection, from_name: &str) -> Result; + fn add_admin(conn: &PgConnection, person_id: i32, added: bool) -> Result; + fn ban_person(conn: &PgConnection, person_id: i32, ban: bool) -> Result; + fn find_by_email_or_name( + conn: &PgConnection, + name_or_email: &str, + ) -> Result; + fn find_by_name(conn: &PgConnection, name: &str) -> Result; + fn find_by_email(conn: &PgConnection, from_email: &str) -> Result; + fn get_profile_url(&self, hostname: &str) -> String; + fn mark_as_updated(conn: &PgConnection, person_id: i32) -> Result; + fn delete_account(conn: &PgConnection, person_id: i32) -> Result; +} + +impl Person_ for Person { + fn register(conn: &PgConnection, form: &PersonForm) -> Result { + let mut edited_person = form.clone(); + let password_hash = + hash(&form.password_encrypted, DEFAULT_COST).expect("Couldn't hash password"); + edited_person.password_encrypted = password_hash; + + Self::create(&conn, &edited_person) + } + + // TODO do more individual updates like these + fn update_password(conn: &PgConnection, person_id: i32, new_password: &str) -> Result { + let password_hash = hash(new_password, DEFAULT_COST).expect("Couldn't hash password"); + + diesel::update(person.find(person_id)) + .set(( + password_encrypted.eq(password_hash), + updated.eq(naive_now()), + )) + .get_result::(conn) + } + + fn read_from_name(conn: &PgConnection, from_name: &str) -> Result { + person + .filter(local.eq(true)) + .filter(deleted.eq(false)) + .filter(name.eq(from_name)) + .first::(conn) + } + + fn add_admin(conn: &PgConnection, person_id: i32, added: bool) -> Result { + diesel::update(person.find(person_id)) + .set(admin.eq(added)) + .get_result::(conn) + } + + fn ban_person(conn: &PgConnection, person_id: i32, ban: bool) -> Result { + diesel::update(person.find(person_id)) + .set(banned.eq(ban)) + .get_result::(conn) + } + + fn find_by_email_or_name( + conn: &PgConnection, + name_or_email: &str, + ) -> Result { + if is_email_regex(name_or_email) { + Self::find_by_email(conn, name_or_email) + } else { + Self::find_by_name(conn, name_or_email) + } + } + + fn find_by_name(conn: &PgConnection, name: &str) -> Result { + person + .filter(deleted.eq(false)) + .filter(local.eq(true)) + .filter(name.ilike(name)) + .first::(conn) + } + + fn find_by_email(conn: &PgConnection, from_email: &str) -> Result { + person + .filter(deleted.eq(false)) + .filter(local.eq(true)) + .filter(email.eq(from_email)) + .first::(conn) + } + + fn get_profile_url(&self, hostname: &str) -> String { + format!( + "{}://{}/u/{}", + Settings::get().get_protocol_string(), + hostname, + self.name + ) + } + + fn mark_as_updated(conn: &PgConnection, person_id: i32) -> Result { + diesel::update(person.find(person_id)) + .set((last_refreshed_at.eq(naive_now()),)) + .get_result::(conn) + } + + fn delete_account(conn: &PgConnection, person_id: i32) -> Result { + diesel::update(person.find(person_id)) + .set(( + preferred_username.eq::>(None), + email.eq::>(None), + matrix_user_id.eq::>(None), + bio.eq::>(None), + deleted.eq(true), + updated.eq(naive_now()), + )) + .get_result::(conn) + } +} + +#[cfg(test)] +mod tests { + use crate::{establish_unpooled_connection, source::person::*, ListingType, SortType}; + + #[test] + fn test_crud() { + let conn = establish_unpooled_connection(); + + let new_person = PersonForm { + name: "thommy".into(), + preferred_username: None, + avatar: None, + banner: None, + banned: Some(false), + deleted: false, + published: None, + updated: None, + actor_id: None, + bio: None, + local: true, + private_key: None, + public_key: None, + last_refreshed_at: None, + inbox_url: None, + shared_inbox_url: None, + }; + + let inserted_person = Person::create(&conn, &new_person).unwrap(); + + let expected_person = Person { + id: inserted_person.id, + name: "thommy".into(), + preferred_username: None, + avatar: None, + banner: None, + banned: false, + deleted: false, + published: inserted_person.published, + updated: None, + actor_id: inserted_person.actor_id.to_owned(), + bio: None, + local: true, + private_key: None, + public_key: None, + last_refreshed_at: inserted_person.published, + deleted: false, + inbox_url: inserted_person.inbox_url.to_owned(), + shared_inbox_url: None, + }; + + let read_person = Person::read(&conn, inserted_person.id).unwrap(); + let updated_person = Person::update(&conn, inserted_person.id, &new_person).unwrap(); + let num_deleted = Person::delete(&conn, inserted_person.id).unwrap(); + + assert_eq!(expected_person, read_person); + assert_eq!(expected_person, inserted_person); + assert_eq!(expected_person, updated_person); + assert_eq!(1, num_deleted); + } +} diff --git a/crates/db_queries/src/source/user_mention.rs b/crates/db_queries/src/source/person_mention.rs similarity index 60% rename from crates/db_queries/src/source/user_mention.rs rename to crates/db_queries/src/source/person_mention.rs index b0c97572f..73543b959 100644 --- a/crates/db_queries/src/source/user_mention.rs +++ b/crates/db_queries/src/source/person_mention.rs @@ -1,57 +1,57 @@ use crate::Crud; use diesel::{dsl::*, result::Error, *}; -use lemmy_db_schema::source::user_mention::*; +use lemmy_db_schema::source::person_mention::*; -impl Crud for UserMention { - fn read(conn: &PgConnection, user_mention_id: i32) -> Result { - use lemmy_db_schema::schema::user_mention::dsl::*; - user_mention.find(user_mention_id).first::(conn) +impl Crud for PersonMention { + fn read(conn: &PgConnection, person_mention_id: i32) -> Result { + use lemmy_db_schema::schema::person_mention::dsl::*; + person_mention.find(person_mention_id).first::(conn) } - fn create(conn: &PgConnection, user_mention_form: &UserMentionForm) -> Result { - use lemmy_db_schema::schema::user_mention::dsl::*; + fn create(conn: &PgConnection, person_mention_form: &PersonMentionForm) -> Result { + use lemmy_db_schema::schema::person_mention::dsl::*; // since the return here isnt utilized, we dont need to do an update // but get_result doesnt return the existing row here - insert_into(user_mention) - .values(user_mention_form) + insert_into(person_mention) + .values(person_mention_form) .on_conflict((recipient_id, comment_id)) .do_update() - .set(user_mention_form) + .set(person_mention_form) .get_result::(conn) } fn update( conn: &PgConnection, - user_mention_id: i32, - user_mention_form: &UserMentionForm, + person_mention_id: i32, + person_mention_form: &PersonMentionForm, ) -> Result { - use lemmy_db_schema::schema::user_mention::dsl::*; - diesel::update(user_mention.find(user_mention_id)) - .set(user_mention_form) + use lemmy_db_schema::schema::person_mention::dsl::*; + diesel::update(person_mention.find(person_mention_id)) + .set(person_mention_form) .get_result::(conn) } } -pub trait UserMention_ { +pub trait PersonMention_ { fn update_read( conn: &PgConnection, - user_mention_id: i32, + person_mention_id: i32, new_read: bool, - ) -> Result; + ) -> Result; fn mark_all_as_read( conn: &PgConnection, for_recipient_id: i32, - ) -> Result, Error>; + ) -> Result, Error>; } -impl UserMention_ for UserMention { +impl PersonMention_ for PersonMention { fn update_read( conn: &PgConnection, - user_mention_id: i32, + person_mention_id: i32, new_read: bool, - ) -> Result { - use lemmy_db_schema::schema::user_mention::dsl::*; - diesel::update(user_mention.find(user_mention_id)) + ) -> Result { + use lemmy_db_schema::schema::person_mention::dsl::*; + diesel::update(person_mention.find(person_mention_id)) .set(read.eq(new_read)) .get_result::(conn) } @@ -59,10 +59,10 @@ impl UserMention_ for UserMention { fn mark_all_as_read( conn: &PgConnection, for_recipient_id: i32, - ) -> Result, Error> { - use lemmy_db_schema::schema::user_mention::dsl::*; + ) -> Result, Error> { + use lemmy_db_schema::schema::person_mention::dsl::*; diesel::update( - user_mention + person_mention .filter(recipient_id.eq(for_recipient_id)) .filter(read.eq(false)), ) @@ -78,33 +78,23 @@ mod tests { comment::*, community::{Community, CommunityForm}, post::*, - user::*, - user_mention::*, + person::*, + person_mention::*, }; #[test] fn test_crud() { let conn = establish_unpooled_connection(); - let new_user = UserForm { + let new_person = PersonForm { name: "terrylake".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -115,27 +105,17 @@ mod tests { shared_inbox_url: None, }; - let inserted_user = User_::create(&conn, &new_user).unwrap(); + let inserted_person = Person::create(&conn, &new_person).unwrap(); - let recipient_form = UserForm { + let recipient_form = PersonForm { name: "terrylakes recipient".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -146,13 +126,13 @@ mod tests { shared_inbox_url: None, }; - let inserted_recipient = User_::create(&conn, &recipient_form).unwrap(); + let inserted_recipient = Person::create(&conn, &recipient_form).unwrap(); let new_community = CommunityForm { name: "test community lake".to_string(), title: "nada".to_owned(), description: None, - creator_id: inserted_user.id, + creator_id: inserted_person.id, removed: None, deleted: None, updated: None, @@ -174,7 +154,7 @@ mod tests { let new_post = PostForm { name: "A test post".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, url: None, body: None, community_id: inserted_community.id, @@ -197,7 +177,7 @@ mod tests { let comment_form = CommentForm { content: "A test comment".into(), - creator_id: inserted_user.id, + creator_id: inserted_person.id, post_id: inserted_post.id, removed: None, deleted: None, @@ -211,15 +191,15 @@ mod tests { let inserted_comment = Comment::create(&conn, &comment_form).unwrap(); - let user_mention_form = UserMentionForm { + let person_mention_form = PersonMentionForm { recipient_id: inserted_recipient.id, comment_id: inserted_comment.id, read: None, }; - let inserted_mention = UserMention::create(&conn, &user_mention_form).unwrap(); + let inserted_mention = PersonMention::create(&conn, &person_mention_form).unwrap(); - let expected_mention = UserMention { + let expected_mention = PersonMention { id: inserted_mention.id, recipient_id: inserted_mention.recipient_id, comment_id: inserted_mention.comment_id, @@ -227,14 +207,14 @@ mod tests { published: inserted_mention.published, }; - let read_mention = UserMention::read(&conn, inserted_mention.id).unwrap(); + let read_mention = PersonMention::read(&conn, inserted_mention.id).unwrap(); let updated_mention = - UserMention::update(&conn, inserted_mention.id, &user_mention_form).unwrap(); + PersonMention::update(&conn, inserted_mention.id, &person_mention_form).unwrap(); Comment::delete(&conn, inserted_comment.id).unwrap(); Post::delete(&conn, inserted_post.id).unwrap(); Community::delete(&conn, inserted_community.id).unwrap(); - User_::delete(&conn, inserted_user.id).unwrap(); - User_::delete(&conn, inserted_recipient.id).unwrap(); + Person::delete(&conn, inserted_person.id).unwrap(); + Person::delete(&conn, inserted_recipient.id).unwrap(); assert_eq!(expected_mention, read_mention); assert_eq!(expected_mention, inserted_mention); diff --git a/crates/db_queries/src/source/post.rs b/crates/db_queries/src/source/post.rs index 1c19e53d0..6a66a79c1 100644 --- a/crates/db_queries/src/source/post.rs +++ b/crates/db_queries/src/source/post.rs @@ -54,7 +54,7 @@ pub trait Post_ { ) -> Result, Error>; fn update_locked(conn: &PgConnection, post_id: i32, new_locked: bool) -> Result; fn update_stickied(conn: &PgConnection, post_id: i32, new_stickied: bool) -> Result; - fn is_post_creator(user_id: i32, post_creator_id: i32) -> bool; + fn is_post_creator(person_id: i32, post_creator_id: i32) -> bool; } impl Post_ for Post { @@ -141,8 +141,8 @@ impl Post_ for Post { .get_result::(conn) } - fn is_post_creator(user_id: i32, post_creator_id: i32) -> bool { - user_id == post_creator_id + fn is_post_creator(person_id: i32, post_creator_id: i32) -> bool { + person_id == post_creator_id } } @@ -168,17 +168,17 @@ impl Likeable for PostLike { use lemmy_db_schema::schema::post_like::dsl::*; insert_into(post_like) .values(post_like_form) - .on_conflict((post_id, user_id)) + .on_conflict((post_id, person_id)) .do_update() .set(post_like_form) .get_result::(conn) } - fn remove(conn: &PgConnection, user_id: i32, post_id: i32) -> Result { + fn remove(conn: &PgConnection, person_id: i32, post_id: i32) -> Result { use lemmy_db_schema::schema::post_like::dsl; diesel::delete( dsl::post_like .filter(dsl::post_id.eq(post_id)) - .filter(dsl::user_id.eq(user_id)), + .filter(dsl::person_id.eq(person_id)), ) .execute(conn) } @@ -189,7 +189,7 @@ impl Saveable for PostSaved { use lemmy_db_schema::schema::post_saved::dsl::*; insert_into(post_saved) .values(post_saved_form) - .on_conflict((post_id, user_id)) + .on_conflict((post_id, person_id)) .do_update() .set(post_saved_form) .get_result::(conn) @@ -199,7 +199,7 @@ impl Saveable for PostSaved { diesel::delete( post_saved .filter(post_id.eq(post_saved_form.post_id)) - .filter(user_id.eq(post_saved_form.user_id)), + .filter(person_id.eq(post_saved_form.person_id)), ) .execute(conn) } @@ -218,7 +218,7 @@ impl Readable for PostRead { diesel::delete( post_read .filter(post_id.eq(post_read_form.post_id)) - .filter(user_id.eq(post_read_form.user_id)), + .filter(person_id.eq(post_read_form.person_id)), ) .execute(conn) } @@ -229,32 +229,22 @@ mod tests { use crate::{establish_unpooled_connection, source::post::*, ListingType, SortType}; use lemmy_db_schema::source::{ community::{Community, CommunityForm}, - user::*, + person::*, }; #[test] fn test_crud() { let conn = establish_unpooled_connection(); - let new_user = UserForm { + let new_person = PersonForm { name: "jim".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -265,13 +255,13 @@ mod tests { shared_inbox_url: None, }; - let inserted_user = User_::create(&conn, &new_user).unwrap(); + let inserted_person = Person::create(&conn, &new_person).unwrap(); let new_community = CommunityForm { name: "test community_3".to_string(), title: "nada".to_owned(), description: None, - creator_id: inserted_user.id, + creator_id: inserted_person.id, removed: None, deleted: None, updated: None, @@ -295,7 +285,7 @@ mod tests { name: "A test post".into(), url: None, body: None, - creator_id: inserted_user.id, + creator_id: inserted_person.id, community_id: inserted_community.id, removed: None, deleted: None, @@ -319,7 +309,7 @@ mod tests { name: "A test post".into(), url: None, body: None, - creator_id: inserted_user.id, + creator_id: inserted_person.id, community_id: inserted_community.id, published: inserted_post.published, removed: false, @@ -339,7 +329,7 @@ mod tests { // Post Like let post_like_form = PostLikeForm { post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_person.id, score: 1, }; @@ -348,7 +338,7 @@ mod tests { let expected_post_like = PostLike { id: inserted_post_like.id, post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_person.id, published: inserted_post_like.published, score: 1, }; @@ -356,7 +346,7 @@ mod tests { // Post Save let post_saved_form = PostSavedForm { post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_person.id, }; let inserted_post_saved = PostSaved::save(&conn, &post_saved_form).unwrap(); @@ -364,14 +354,14 @@ mod tests { let expected_post_saved = PostSaved { id: inserted_post_saved.id, post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_person.id, published: inserted_post_saved.published, }; // Post Read let post_read_form = PostReadForm { post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_person.id, }; let inserted_post_read = PostRead::mark_as_read(&conn, &post_read_form).unwrap(); @@ -379,18 +369,18 @@ mod tests { let expected_post_read = PostRead { id: inserted_post_read.id, post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_person.id, published: inserted_post_read.published, }; let read_post = Post::read(&conn, inserted_post.id).unwrap(); let updated_post = Post::update(&conn, inserted_post.id, &new_post).unwrap(); - let like_removed = PostLike::remove(&conn, inserted_user.id, inserted_post.id).unwrap(); + let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap(); let saved_removed = PostSaved::unsave(&conn, &post_saved_form).unwrap(); let read_removed = PostRead::mark_as_unread(&conn, &post_read_form).unwrap(); let num_deleted = Post::delete(&conn, inserted_post.id).unwrap(); Community::delete(&conn, inserted_community.id).unwrap(); - User_::delete(&conn, inserted_user.id).unwrap(); + Person::delete(&conn, inserted_person.id).unwrap(); assert_eq!(expected_post, read_post); assert_eq!(expected_post, inserted_post); diff --git a/crates/db_queries/src/source/private_message.rs b/crates/db_queries/src/source/private_message.rs index 8cace9384..e4ca3c6b3 100644 --- a/crates/db_queries/src/source/private_message.rs +++ b/crates/db_queries/src/source/private_message.rs @@ -146,31 +146,21 @@ mod tests { ListingType, SortType, }; - use lemmy_db_schema::source::{private_message::*, user::*}; + use lemmy_db_schema::source::{private_message::*, person::*}; #[test] fn test_crud() { let conn = establish_unpooled_connection(); - let creator_form = UserForm { + let creator_form = PersonForm { name: "creator_pm".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -181,27 +171,17 @@ mod tests { shared_inbox_url: None, }; - let inserted_creator = User_::create(&conn, &creator_form).unwrap(); + let inserted_creator = Person::create(&conn, &creator_form).unwrap(); - let recipient_form = UserForm { + let recipient_form = PersonForm { name: "recipient_pm".into(), preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, avatar: None, banner: None, - admin: false, banned: Some(false), + deleted: false, published: None, updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: None, bio: None, local: true, @@ -212,7 +192,7 @@ mod tests { shared_inbox_url: None, }; - let inserted_recipient = User_::create(&conn, &recipient_form).unwrap(); + let inserted_recipient = Person::create(&conn, &recipient_form).unwrap(); let private_message_form = PrivateMessageForm { content: "A test private message".into(), @@ -248,8 +228,8 @@ mod tests { PrivateMessage::update_deleted(&conn, inserted_private_message.id, true).unwrap(); let marked_read_private_message = PrivateMessage::update_read(&conn, inserted_private_message.id, true).unwrap(); - User_::delete(&conn, inserted_creator.id).unwrap(); - User_::delete(&conn, inserted_recipient.id).unwrap(); + Person::delete(&conn, inserted_creator.id).unwrap(); + Person::delete(&conn, inserted_recipient.id).unwrap(); assert_eq!(expected_private_message, read_private_message); assert_eq!(expected_private_message, updated_private_message); diff --git a/crates/db_queries/src/source/user.rs b/crates/db_queries/src/source/user.rs deleted file mode 100644 index 5f3fa6cbb..000000000 --- a/crates/db_queries/src/source/user.rs +++ /dev/null @@ -1,458 +0,0 @@ -use crate::{is_email_regex, ApubObject, Crud, ToSafeSettings}; -use bcrypt::{hash, DEFAULT_COST}; -use diesel::{dsl::*, result::Error, *}; -use lemmy_db_schema::{ - naive_now, - schema::user_::dsl::*, - source::user::{UserForm, UserSafeSettings, User_}, - Url, -}; -use lemmy_utils::settings::Settings; - -mod safe_type { - use crate::ToSafe; - use lemmy_db_schema::{schema::user_::columns::*, source::user::User_}; - - type Columns = ( - id, - name, - preferred_username, - avatar, - admin, - banned, - published, - updated, - matrix_user_id, - actor_id, - bio, - local, - banner, - deleted, - inbox_url, - shared_inbox_url, - ); - - impl ToSafe for User_ { - type SafeColumns = Columns; - fn safe_columns_tuple() -> Self::SafeColumns { - ( - id, - name, - preferred_username, - avatar, - admin, - banned, - published, - updated, - matrix_user_id, - actor_id, - bio, - local, - banner, - deleted, - inbox_url, - shared_inbox_url, - ) - } - } -} - -mod safe_type_alias_1 { - use crate::ToSafe; - use lemmy_db_schema::{schema::user_alias_1::columns::*, source::user::UserAlias1}; - - type Columns = ( - id, - name, - preferred_username, - avatar, - admin, - banned, - published, - updated, - matrix_user_id, - actor_id, - bio, - local, - banner, - deleted, - ); - - impl ToSafe for UserAlias1 { - type SafeColumns = Columns; - fn safe_columns_tuple() -> Self::SafeColumns { - ( - id, - name, - preferred_username, - avatar, - admin, - banned, - published, - updated, - matrix_user_id, - actor_id, - bio, - local, - banner, - deleted, - ) - } - } -} - -mod safe_type_alias_2 { - use crate::ToSafe; - use lemmy_db_schema::{schema::user_alias_2::columns::*, source::user::UserAlias2}; - - type Columns = ( - id, - name, - preferred_username, - avatar, - admin, - banned, - published, - updated, - matrix_user_id, - actor_id, - bio, - local, - banner, - deleted, - ); - - impl ToSafe for UserAlias2 { - type SafeColumns = Columns; - fn safe_columns_tuple() -> Self::SafeColumns { - ( - id, - name, - preferred_username, - avatar, - admin, - banned, - published, - updated, - matrix_user_id, - actor_id, - bio, - local, - banner, - deleted, - ) - } - } -} - -mod safe_settings_type { - use crate::ToSafeSettings; - use lemmy_db_schema::{schema::user_::columns::*, source::user::User_}; - - type Columns = ( - id, - name, - preferred_username, - email, - avatar, - admin, - banned, - published, - updated, - show_nsfw, - theme, - default_sort_type, - default_listing_type, - lang, - show_avatars, - send_notifications_to_email, - matrix_user_id, - actor_id, - bio, - local, - last_refreshed_at, - banner, - deleted, - ); - - impl ToSafeSettings for User_ { - type SafeSettingsColumns = Columns; - fn safe_settings_columns_tuple() -> Self::SafeSettingsColumns { - ( - id, - name, - preferred_username, - email, - avatar, - admin, - banned, - published, - updated, - show_nsfw, - theme, - default_sort_type, - default_listing_type, - lang, - show_avatars, - send_notifications_to_email, - matrix_user_id, - actor_id, - bio, - local, - last_refreshed_at, - banner, - deleted, - ) - } - } -} - -pub trait UserSafeSettings_ { - fn read(conn: &PgConnection, user_id: i32) -> Result; -} - -impl UserSafeSettings_ for UserSafeSettings { - fn read(conn: &PgConnection, user_id: i32) -> Result { - user_ - .select(User_::safe_settings_columns_tuple()) - .filter(deleted.eq(false)) - .find(user_id) - .first::(conn) - } -} - -impl Crud for User_ { - fn read(conn: &PgConnection, user_id: i32) -> Result { - user_ - .filter(deleted.eq(false)) - .find(user_id) - .first::(conn) - } - fn delete(conn: &PgConnection, user_id: i32) -> Result { - diesel::delete(user_.find(user_id)).execute(conn) - } - fn create(conn: &PgConnection, form: &UserForm) -> Result { - insert_into(user_).values(form).get_result::(conn) - } - fn update(conn: &PgConnection, user_id: i32, form: &UserForm) -> Result { - diesel::update(user_.find(user_id)) - .set(form) - .get_result::(conn) - } -} - -impl ApubObject for User_ { - fn read_from_apub_id(conn: &PgConnection, object_id: &Url) -> Result { - use lemmy_db_schema::schema::user_::dsl::*; - user_ - .filter(deleted.eq(false)) - .filter(actor_id.eq(object_id)) - .first::(conn) - } - - fn upsert(conn: &PgConnection, user_form: &UserForm) -> Result { - insert_into(user_) - .values(user_form) - .on_conflict(actor_id) - .do_update() - .set(user_form) - .get_result::(conn) - } -} - -pub trait User { - fn register(conn: &PgConnection, form: &UserForm) -> Result; - fn update_password(conn: &PgConnection, user_id: i32, new_password: &str) - -> Result; - fn read_from_name(conn: &PgConnection, from_user_name: &str) -> Result; - fn add_admin(conn: &PgConnection, user_id: i32, added: bool) -> Result; - fn ban_user(conn: &PgConnection, user_id: i32, ban: bool) -> Result; - fn find_by_email_or_username( - conn: &PgConnection, - username_or_email: &str, - ) -> Result; - fn find_by_username(conn: &PgConnection, username: &str) -> Result; - fn find_by_email(conn: &PgConnection, from_email: &str) -> Result; - fn get_profile_url(&self, hostname: &str) -> String; - fn mark_as_updated(conn: &PgConnection, user_id: i32) -> Result; - fn delete_account(conn: &PgConnection, user_id: i32) -> Result; -} - -impl User for User_ { - fn register(conn: &PgConnection, form: &UserForm) -> Result { - let mut edited_user = form.clone(); - let password_hash = - hash(&form.password_encrypted, DEFAULT_COST).expect("Couldn't hash password"); - edited_user.password_encrypted = password_hash; - - Self::create(&conn, &edited_user) - } - - // TODO do more individual updates like these - fn update_password(conn: &PgConnection, user_id: i32, new_password: &str) -> Result { - let password_hash = hash(new_password, DEFAULT_COST).expect("Couldn't hash password"); - - diesel::update(user_.find(user_id)) - .set(( - password_encrypted.eq(password_hash), - updated.eq(naive_now()), - )) - .get_result::(conn) - } - - fn read_from_name(conn: &PgConnection, from_user_name: &str) -> Result { - user_ - .filter(local.eq(true)) - .filter(deleted.eq(false)) - .filter(name.eq(from_user_name)) - .first::(conn) - } - - fn add_admin(conn: &PgConnection, user_id: i32, added: bool) -> Result { - diesel::update(user_.find(user_id)) - .set(admin.eq(added)) - .get_result::(conn) - } - - fn ban_user(conn: &PgConnection, user_id: i32, ban: bool) -> Result { - diesel::update(user_.find(user_id)) - .set(banned.eq(ban)) - .get_result::(conn) - } - - fn find_by_email_or_username( - conn: &PgConnection, - username_or_email: &str, - ) -> Result { - if is_email_regex(username_or_email) { - Self::find_by_email(conn, username_or_email) - } else { - Self::find_by_username(conn, username_or_email) - } - } - - fn find_by_username(conn: &PgConnection, username: &str) -> Result { - user_ - .filter(deleted.eq(false)) - .filter(local.eq(true)) - .filter(name.ilike(username)) - .first::(conn) - } - - fn find_by_email(conn: &PgConnection, from_email: &str) -> Result { - user_ - .filter(deleted.eq(false)) - .filter(local.eq(true)) - .filter(email.eq(from_email)) - .first::(conn) - } - - fn get_profile_url(&self, hostname: &str) -> String { - format!( - "{}://{}/u/{}", - Settings::get().get_protocol_string(), - hostname, - self.name - ) - } - - fn mark_as_updated(conn: &PgConnection, user_id: i32) -> Result { - diesel::update(user_.find(user_id)) - .set((last_refreshed_at.eq(naive_now()),)) - .get_result::(conn) - } - - fn delete_account(conn: &PgConnection, user_id: i32) -> Result { - diesel::update(user_.find(user_id)) - .set(( - preferred_username.eq::>(None), - email.eq::>(None), - matrix_user_id.eq::>(None), - bio.eq::>(None), - deleted.eq(true), - updated.eq(naive_now()), - )) - .get_result::(conn) - } -} - -#[cfg(test)] -mod tests { - use crate::{establish_unpooled_connection, source::user::*, ListingType, SortType}; - - #[test] - fn test_crud() { - let conn = establish_unpooled_connection(); - - let new_user = UserForm { - name: "thommy".into(), - preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, - avatar: None, - banner: None, - admin: false, - banned: Some(false), - published: None, - updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, - actor_id: None, - bio: None, - local: true, - private_key: None, - public_key: None, - last_refreshed_at: None, - inbox_url: None, - shared_inbox_url: None, - }; - - let inserted_user = User_::create(&conn, &new_user).unwrap(); - - let expected_user = User_ { - id: inserted_user.id, - name: "thommy".into(), - preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, - avatar: None, - banner: None, - admin: false, - banned: false, - published: inserted_user.published, - updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, - actor_id: inserted_user.actor_id.to_owned(), - bio: None, - local: true, - private_key: None, - public_key: None, - last_refreshed_at: inserted_user.published, - deleted: false, - inbox_url: inserted_user.inbox_url.to_owned(), - shared_inbox_url: None, - }; - - let read_user = User_::read(&conn, inserted_user.id).unwrap(); - let updated_user = User_::update(&conn, inserted_user.id, &new_user).unwrap(); - let num_deleted = User_::delete(&conn, inserted_user.id).unwrap(); - - assert_eq!(expected_user, read_user); - assert_eq!(expected_user, inserted_user); - assert_eq!(expected_user, updated_user); - assert_eq!(1, num_deleted); - } -} diff --git a/crates/db_schema/src/schema.rs b/crates/db_schema/src/schema.rs index 3786e00ca..0641bdee0 100644 --- a/crates/db_schema/src/schema.rs +++ b/crates/db_schema/src/schema.rs @@ -41,7 +41,7 @@ table! { table! { comment_like (id) { id -> Int4, - user_id -> Int4, + person_id -> Int4, comment_id -> Int4, post_id -> Int4, score -> Int2, @@ -67,7 +67,7 @@ table! { comment_saved (id) { id -> Int4, comment_id -> Int4, - user_id -> Int4, + person_id -> Int4, published -> Timestamp, } } @@ -91,9 +91,9 @@ table! { last_refreshed_at -> Timestamp, icon -> Nullable, banner -> Nullable, - followers_url -> Text, - inbox_url -> Text, - shared_inbox_url -> Nullable, + followers_url -> Varchar, + inbox_url -> Varchar, + shared_inbox_url -> Nullable, } } @@ -116,7 +116,7 @@ table! { community_follower (id) { id -> Int4, community_id -> Int4, - user_id -> Int4, + person_id -> Int4, published -> Timestamp, pending -> Nullable, } @@ -126,25 +126,43 @@ table! { community_moderator (id) { id -> Int4, community_id -> Int4, - user_id -> Int4, + person_id -> Int4, published -> Timestamp, } } table! { - community_user_ban (id) { + community_person_ban (id) { id -> Int4, community_id -> Int4, - user_id -> Int4, + person_id -> Int4, published -> Timestamp, } } +table! { + local_user (id) { + id -> Int4, + person_id -> Int4, + password_encrypted -> Text, + email -> Nullable, + admin -> Bool, + show_nsfw -> Bool, + theme -> Varchar, + default_sort_type -> Int2, + default_listing_type -> Int2, + lang -> Varchar, + show_avatars -> Bool, + send_notifications_to_email -> Bool, + matrix_user_id -> Nullable, + } +} + table! { mod_add (id) { id -> Int4, - mod_user_id -> Int4, - other_user_id -> Int4, + mod_person_id -> Int4, + other_person_id -> Int4, removed -> Nullable, when_ -> Timestamp, } @@ -153,8 +171,8 @@ table! { table! { mod_add_community (id) { id -> Int4, - mod_user_id -> Int4, - other_user_id -> Int4, + mod_person_id -> Int4, + other_person_id -> Int4, community_id -> Int4, removed -> Nullable, when_ -> Timestamp, @@ -164,8 +182,8 @@ table! { table! { mod_ban (id) { id -> Int4, - mod_user_id -> Int4, - other_user_id -> Int4, + mod_person_id -> Int4, + other_person_id -> Int4, reason -> Nullable, banned -> Nullable, expires -> Nullable, @@ -176,8 +194,8 @@ table! { table! { mod_ban_from_community (id) { id -> Int4, - mod_user_id -> Int4, - other_user_id -> Int4, + mod_person_id -> Int4, + other_person_id -> Int4, community_id -> Int4, reason -> Nullable, banned -> Nullable, @@ -189,7 +207,7 @@ table! { table! { mod_lock_post (id) { id -> Int4, - mod_user_id -> Int4, + mod_person_id -> Int4, post_id -> Int4, locked -> Nullable, when_ -> Timestamp, @@ -199,7 +217,7 @@ table! { table! { mod_remove_comment (id) { id -> Int4, - mod_user_id -> Int4, + mod_person_id -> Int4, comment_id -> Int4, reason -> Nullable, removed -> Nullable, @@ -210,7 +228,7 @@ table! { table! { mod_remove_community (id) { id -> Int4, - mod_user_id -> Int4, + mod_person_id -> Int4, community_id -> Int4, reason -> Nullable, removed -> Nullable, @@ -222,7 +240,7 @@ table! { table! { mod_remove_post (id) { id -> Int4, - mod_user_id -> Int4, + mod_person_id -> Int4, post_id -> Int4, reason -> Nullable, removed -> Nullable, @@ -233,7 +251,7 @@ table! { table! { mod_sticky_post (id) { id -> Int4, - mod_user_id -> Int4, + mod_person_id -> Int4, post_id -> Int4, stickied -> Nullable, when_ -> Timestamp, @@ -243,9 +261,60 @@ table! { table! { password_reset_request (id) { id -> Int4, - user_id -> Int4, token_encrypted -> Text, published -> Timestamp, + local_user_id -> Int4, + } +} + +table! { + person (id) { + id -> Int4, + name -> Varchar, + preferred_username -> Nullable, + avatar -> Nullable, + banned -> Bool, + published -> Timestamp, + updated -> Nullable, + actor_id -> Varchar, + bio -> Nullable, + local -> Bool, + private_key -> Nullable, + public_key -> Nullable, + last_refreshed_at -> Timestamp, + banner -> Nullable, + deleted -> Bool, + inbox_url -> Varchar, + shared_inbox_url -> Nullable, + } +} + +table! { + person_aggregates (id) { + id -> Int4, + person_id -> Int4, + post_count -> Int8, + post_score -> Int8, + comment_count -> Int8, + comment_score -> Int8, + } +} + +table! { + person_ban (id) { + id -> Int4, + person_id -> Int4, + published -> Timestamp, + } +} + +table! { + person_mention (id) { + id -> Int4, + recipient_id -> Int4, + comment_id -> Int4, + read -> Bool, + published -> Timestamp, } } @@ -292,7 +361,7 @@ table! { post_like (id) { id -> Int4, post_id -> Int4, - user_id -> Int4, + person_id -> Int4, score -> Int2, published -> Timestamp, } @@ -302,7 +371,7 @@ table! { post_read (id) { id -> Int4, post_id -> Int4, - user_id -> Int4, + person_id -> Int4, published -> Timestamp, } } @@ -327,7 +396,7 @@ table! { post_saved (id) { id -> Int4, post_id -> Int4, - user_id -> Int4, + person_id -> Int4, published -> Timestamp, } } @@ -378,68 +447,6 @@ table! { } } -table! { - user_ (id) { - id -> Int4, - name -> Varchar, - preferred_username -> Nullable, - password_encrypted -> Text, - email -> Nullable, - avatar -> Nullable, - admin -> Bool, - banned -> Bool, - published -> Timestamp, - updated -> Nullable, - show_nsfw -> Bool, - theme -> Varchar, - default_sort_type -> Int2, - default_listing_type -> Int2, - lang -> Varchar, - show_avatars -> Bool, - send_notifications_to_email -> Bool, - matrix_user_id -> Nullable, - actor_id -> Varchar, - bio -> Nullable, - local -> Bool, - private_key -> Nullable, - public_key -> Nullable, - last_refreshed_at -> Timestamp, - banner -> Nullable, - deleted -> Bool, - inbox_url -> Text, - shared_inbox_url -> Nullable, - } -} - -table! { - user_aggregates (id) { - id -> Int4, - user_id -> Int4, - post_count -> Int8, - post_score -> Int8, - comment_count -> Int8, - comment_score -> Int8, - } -} - -table! { - user_ban (id) { - id -> Int4, - user_id -> Int4, - published -> Timestamp, - } -} - -table! { - user_mention (id) { - id -> Int4, - recipient_id -> Int4, - comment_id -> Int4, - read -> Bool, - published -> Timestamp, - } -} - // These are necessary since diesel doesn't have self joins / aliases table! { comment_alias_1 (id) { @@ -459,25 +466,14 @@ table! { } table! { - user_alias_1 (id) { + person_alias_1 (id) { id -> Int4, name -> Varchar, preferred_username -> Nullable, - password_encrypted -> Text, - email -> Nullable, avatar -> Nullable, - admin -> Bool, banned -> Bool, published -> Timestamp, updated -> Nullable, - show_nsfw -> Bool, - theme -> Varchar, - default_sort_type -> Int2, - default_listing_type -> Int2, - lang -> Varchar, - show_avatars -> Bool, - send_notifications_to_email -> Bool, - matrix_user_id -> Nullable, actor_id -> Varchar, bio -> Nullable, local -> Bool, @@ -486,29 +482,20 @@ table! { last_refreshed_at -> Timestamp, banner -> Nullable, deleted -> Bool, + inbox_url -> Varchar, + shared_inbox_url -> Nullable, } } table! { - user_alias_2 (id) { + person_alias_2 (id) { id -> Int4, name -> Varchar, preferred_username -> Nullable, - password_encrypted -> Text, - email -> Nullable, avatar -> Nullable, - admin -> Bool, banned -> Bool, published -> Timestamp, updated -> Nullable, - show_nsfw -> Bool, - theme -> Varchar, - default_sort_type -> Int2, - default_listing_type -> Int2, - lang -> Varchar, - show_avatars -> Bool, - send_notifications_to_email -> Bool, - matrix_user_id -> Nullable, actor_id -> Varchar, bio -> Nullable, local -> Bool, @@ -517,64 +504,67 @@ table! { last_refreshed_at -> Timestamp, banner -> Nullable, deleted -> Bool, + inbox_url -> Varchar, + shared_inbox_url -> Nullable, } } -joinable!(comment_alias_1 -> user_alias_1 (creator_id)); +joinable!(comment_alias_1 -> person_alias_1 (creator_id)); joinable!(comment -> comment_alias_1 (parent_id)); -joinable!(user_mention -> user_alias_1 (recipient_id)); -joinable!(post -> user_alias_1 (creator_id)); -joinable!(comment -> user_alias_1 (creator_id)); +joinable!(person_mention -> person_alias_1 (recipient_id)); +joinable!(post -> person_alias_1 (creator_id)); +joinable!(comment -> person_alias_1 (creator_id)); -joinable!(post_report -> user_alias_2 (resolver_id)); -joinable!(comment_report -> user_alias_2 (resolver_id)); +joinable!(post_report -> person_alias_2 (resolver_id)); +joinable!(comment_report -> person_alias_2 (resolver_id)); +joinable!(comment -> person (creator_id)); joinable!(comment -> post (post_id)); -joinable!(comment -> user_ (creator_id)); joinable!(comment_aggregates -> comment (comment_id)); joinable!(comment_like -> comment (comment_id)); +joinable!(comment_like -> person (person_id)); joinable!(comment_like -> post (post_id)); -joinable!(comment_like -> user_ (user_id)); joinable!(comment_report -> comment (comment_id)); joinable!(comment_saved -> comment (comment_id)); -joinable!(comment_saved -> user_ (user_id)); -joinable!(community -> user_ (creator_id)); +joinable!(comment_saved -> person (person_id)); +joinable!(community -> person (creator_id)); joinable!(community_aggregates -> community (community_id)); joinable!(community_follower -> community (community_id)); -joinable!(community_follower -> user_ (user_id)); +joinable!(community_follower -> person (person_id)); joinable!(community_moderator -> community (community_id)); -joinable!(community_moderator -> user_ (user_id)); -joinable!(community_user_ban -> community (community_id)); -joinable!(community_user_ban -> user_ (user_id)); +joinable!(community_moderator -> person (person_id)); +joinable!(community_person_ban -> community (community_id)); +joinable!(community_person_ban -> person (person_id)); +joinable!(local_user -> person (person_id)); joinable!(mod_add_community -> community (community_id)); joinable!(mod_ban_from_community -> community (community_id)); +joinable!(mod_lock_post -> person (mod_person_id)); joinable!(mod_lock_post -> post (post_id)); -joinable!(mod_lock_post -> user_ (mod_user_id)); joinable!(mod_remove_comment -> comment (comment_id)); -joinable!(mod_remove_comment -> user_ (mod_user_id)); +joinable!(mod_remove_comment -> person (mod_person_id)); joinable!(mod_remove_community -> community (community_id)); -joinable!(mod_remove_community -> user_ (mod_user_id)); +joinable!(mod_remove_community -> person (mod_person_id)); +joinable!(mod_remove_post -> person (mod_person_id)); joinable!(mod_remove_post -> post (post_id)); -joinable!(mod_remove_post -> user_ (mod_user_id)); +joinable!(mod_sticky_post -> person (mod_person_id)); joinable!(mod_sticky_post -> post (post_id)); -joinable!(mod_sticky_post -> user_ (mod_user_id)); -joinable!(password_reset_request -> user_ (user_id)); +joinable!(password_reset_request -> local_user (local_user_id)); +joinable!(person_aggregates -> person (person_id)); +joinable!(person_ban -> person (person_id)); +joinable!(person_mention -> comment (comment_id)); +joinable!(person_mention -> person (recipient_id)); joinable!(post -> community (community_id)); -joinable!(post -> user_ (creator_id)); +joinable!(post -> person (creator_id)); joinable!(post_aggregates -> post (post_id)); +joinable!(post_like -> person (person_id)); joinable!(post_like -> post (post_id)); -joinable!(post_like -> user_ (user_id)); +joinable!(post_read -> person (person_id)); joinable!(post_read -> post (post_id)); -joinable!(post_read -> user_ (user_id)); joinable!(post_report -> post (post_id)); +joinable!(post_saved -> person (person_id)); joinable!(post_saved -> post (post_id)); -joinable!(post_saved -> user_ (user_id)); -joinable!(site -> user_ (creator_id)); +joinable!(site -> person (creator_id)); joinable!(site_aggregates -> site (site_id)); -joinable!(user_aggregates -> user_ (user_id)); -joinable!(user_ban -> user_ (user_id)); -joinable!(user_mention -> comment (comment_id)); -joinable!(user_mention -> user_ (recipient_id)); allow_tables_to_appear_in_same_query!( activity, @@ -587,7 +577,8 @@ allow_tables_to_appear_in_same_query!( community_aggregates, community_follower, community_moderator, - community_user_ban, + community_person_ban, + local_user, mod_add, mod_add_community, mod_ban, @@ -598,6 +589,10 @@ allow_tables_to_appear_in_same_query!( mod_remove_post, mod_sticky_post, password_reset_request, + person, + person_aggregates, + person_ban, + person_mention, post, post_aggregates, post_like, @@ -607,11 +602,7 @@ allow_tables_to_appear_in_same_query!( private_message, site, site_aggregates, - user_, - user_aggregates, - user_ban, - user_mention, comment_alias_1, - user_alias_1, - user_alias_2, + person_alias_1, + person_alias_2, ); diff --git a/crates/db_schema/src/source/comment.rs b/crates/db_schema/src/source/comment.rs index 72b9e740a..7871d1dd0 100644 --- a/crates/db_schema/src/source/comment.rs +++ b/crates/db_schema/src/source/comment.rs @@ -69,7 +69,7 @@ pub struct CommentForm { #[table_name = "comment_like"] pub struct CommentLike { pub id: i32, - pub user_id: i32, + pub person_id: i32, pub comment_id: i32, pub post_id: i32, // TODO this is redundant pub score: i16, @@ -79,7 +79,7 @@ pub struct CommentLike { #[derive(Insertable, AsChangeset, Clone)] #[table_name = "comment_like"] pub struct CommentLikeForm { - pub user_id: i32, + pub person_id: i32, pub comment_id: i32, pub post_id: i32, // TODO this is redundant pub score: i16, @@ -91,7 +91,7 @@ pub struct CommentLikeForm { pub struct CommentSaved { pub id: i32, pub comment_id: i32, - pub user_id: i32, + pub person_id: i32, pub published: chrono::NaiveDateTime, } @@ -99,5 +99,5 @@ pub struct CommentSaved { #[table_name = "comment_saved"] pub struct CommentSavedForm { pub comment_id: i32, - pub user_id: i32, + pub person_id: i32, } diff --git a/crates/db_schema/src/source/community.rs b/crates/db_schema/src/source/community.rs index b8702ca97..bc99a575a 100644 --- a/crates/db_schema/src/source/community.rs +++ b/crates/db_schema/src/source/community.rs @@ -1,5 +1,5 @@ use crate::{ - schema::{community, community_follower, community_moderator, community_user_ban}, + schema::{community, community_follower, community_moderator, community_person_ban}, Url, }; use serde::Serialize; @@ -79,7 +79,7 @@ pub struct CommunityForm { pub struct CommunityModerator { pub id: i32, pub community_id: i32, - pub user_id: i32, + pub person_id: i32, pub published: chrono::NaiveDateTime, } @@ -87,24 +87,24 @@ pub struct CommunityModerator { #[table_name = "community_moderator"] pub struct CommunityModeratorForm { pub community_id: i32, - pub user_id: i32, + pub person_id: i32, } #[derive(Identifiable, Queryable, Associations, PartialEq, Debug)] #[belongs_to(Community)] -#[table_name = "community_user_ban"] -pub struct CommunityUserBan { +#[table_name = "community_person_ban"] +pub struct CommunityPersonBan { pub id: i32, pub community_id: i32, - pub user_id: i32, + pub person_id: i32, pub published: chrono::NaiveDateTime, } #[derive(Insertable, AsChangeset, Clone)] -#[table_name = "community_user_ban"] -pub struct CommunityUserBanForm { +#[table_name = "community_person_ban"] +pub struct CommunityPersonBanForm { pub community_id: i32, - pub user_id: i32, + pub person_id: i32, } #[derive(Identifiable, Queryable, Associations, PartialEq, Debug)] @@ -113,7 +113,7 @@ pub struct CommunityUserBanForm { pub struct CommunityFollower { pub id: i32, pub community_id: i32, - pub user_id: i32, + pub person_id: i32, pub published: chrono::NaiveDateTime, pub pending: Option, } @@ -122,6 +122,6 @@ pub struct CommunityFollower { #[table_name = "community_follower"] pub struct CommunityFollowerForm { pub community_id: i32, - pub user_id: i32, + pub person_id: i32, pub pending: bool, } diff --git a/crates/db_schema/src/source/local_user.rs b/crates/db_schema/src/source/local_user.rs new file mode 100644 index 000000000..c4300dfdb --- /dev/null +++ b/crates/db_schema/src/source/local_user.rs @@ -0,0 +1,66 @@ +use crate::schema::local_user; +use serde::Serialize; + +#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] +#[table_name = "local_user"] +pub struct LocalUser { + pub id: i32, + pub person_id: i32, + pub password_encrypted: String, + pub email: Option, + pub admin: bool, + pub show_nsfw: bool, + pub theme: String, + pub default_sort_type: i16, + pub default_listing_type: i16, + pub lang: String, + pub show_avatars: bool, + pub send_notifications_to_email: bool, + pub matrix_user_id: Option, +} + +// TODO redo these, check table defaults +#[derive(Insertable, AsChangeset, Clone)] +#[table_name = "local_user"] +pub struct LocalUserForm { + pub person_id: i32, + pub password_encrypted: String, + pub email: Option>, + pub admin: Option, + pub show_nsfw: Option, + pub theme: Option, + pub default_sort_type: Option, + pub default_listing_type: Option, + pub lang: Option, + pub show_avatars: Option, + pub send_notifications_to_email: Option, + pub matrix_user_id: Option>, +} + +/// A safe local user view, without settings, password, or email +#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] +#[table_name = "local_user"] +pub struct LocalUserSafe { + pub id: i32, + pub person_id: i32, + pub admin: bool, + pub matrix_user_id: Option, +} + +/// A local user view that removes password encrypted +#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] +#[table_name = "local_user"] +pub struct LocalUserSettings{ + pub id: i32, + pub person_id: i32, + pub email: Option, + pub admin: bool, + pub show_nsfw: bool, + pub theme: String, + pub default_sort_type: i16, + pub default_listing_type: i16, + pub lang: String, + pub show_avatars: bool, + pub send_notifications_to_email: bool, + pub matrix_user_id: Option, +} diff --git a/crates/db_schema/src/source/mod.rs b/crates/db_schema/src/source/mod.rs index a39dc1108..4882ddf4b 100644 --- a/crates/db_schema/src/source/mod.rs +++ b/crates/db_schema/src/source/mod.rs @@ -8,5 +8,6 @@ pub mod post; pub mod post_report; pub mod private_message; pub mod site; -pub mod user; -pub mod user_mention; +pub mod person; +pub mod person_mention; +pub mod local_user; diff --git a/crates/db_schema/src/source/moderator.rs b/crates/db_schema/src/source/moderator.rs index d1a5d8308..dc890f16d 100644 --- a/crates/db_schema/src/source/moderator.rs +++ b/crates/db_schema/src/source/moderator.rs @@ -15,7 +15,7 @@ use serde::Serialize; #[table_name = "mod_remove_post"] pub struct ModRemovePost { pub id: i32, - pub mod_user_id: i32, + pub mod_person_id: i32, pub post_id: i32, pub reason: Option, pub removed: Option, @@ -25,7 +25,7 @@ pub struct ModRemovePost { #[derive(Insertable, AsChangeset)] #[table_name = "mod_remove_post"] pub struct ModRemovePostForm { - pub mod_user_id: i32, + pub mod_person_id: i32, pub post_id: i32, pub reason: Option, pub removed: Option, @@ -35,7 +35,7 @@ pub struct ModRemovePostForm { #[table_name = "mod_lock_post"] pub struct ModLockPost { pub id: i32, - pub mod_user_id: i32, + pub mod_person_id: i32, pub post_id: i32, pub locked: Option, pub when_: chrono::NaiveDateTime, @@ -44,7 +44,7 @@ pub struct ModLockPost { #[derive(Insertable, AsChangeset)] #[table_name = "mod_lock_post"] pub struct ModLockPostForm { - pub mod_user_id: i32, + pub mod_person_id: i32, pub post_id: i32, pub locked: Option, } @@ -53,7 +53,7 @@ pub struct ModLockPostForm { #[table_name = "mod_sticky_post"] pub struct ModStickyPost { pub id: i32, - pub mod_user_id: i32, + pub mod_person_id: i32, pub post_id: i32, pub stickied: Option, pub when_: chrono::NaiveDateTime, @@ -62,7 +62,7 @@ pub struct ModStickyPost { #[derive(Insertable, AsChangeset)] #[table_name = "mod_sticky_post"] pub struct ModStickyPostForm { - pub mod_user_id: i32, + pub mod_person_id: i32, pub post_id: i32, pub stickied: Option, } @@ -71,7 +71,7 @@ pub struct ModStickyPostForm { #[table_name = "mod_remove_comment"] pub struct ModRemoveComment { pub id: i32, - pub mod_user_id: i32, + pub mod_person_id: i32, pub comment_id: i32, pub reason: Option, pub removed: Option, @@ -81,7 +81,7 @@ pub struct ModRemoveComment { #[derive(Insertable, AsChangeset)] #[table_name = "mod_remove_comment"] pub struct ModRemoveCommentForm { - pub mod_user_id: i32, + pub mod_person_id: i32, pub comment_id: i32, pub reason: Option, pub removed: Option, @@ -91,7 +91,7 @@ pub struct ModRemoveCommentForm { #[table_name = "mod_remove_community"] pub struct ModRemoveCommunity { pub id: i32, - pub mod_user_id: i32, + pub mod_person_id: i32, pub community_id: i32, pub reason: Option, pub removed: Option, @@ -102,7 +102,7 @@ pub struct ModRemoveCommunity { #[derive(Insertable, AsChangeset)] #[table_name = "mod_remove_community"] pub struct ModRemoveCommunityForm { - pub mod_user_id: i32, + pub mod_person_id: i32, pub community_id: i32, pub reason: Option, pub removed: Option, @@ -113,8 +113,8 @@ pub struct ModRemoveCommunityForm { #[table_name = "mod_ban_from_community"] pub struct ModBanFromCommunity { pub id: i32, - pub mod_user_id: i32, - pub other_user_id: i32, + pub mod_person_id: i32, + pub other_person_id: i32, pub community_id: i32, pub reason: Option, pub banned: Option, @@ -125,8 +125,8 @@ pub struct ModBanFromCommunity { #[derive(Insertable, AsChangeset)] #[table_name = "mod_ban_from_community"] pub struct ModBanFromCommunityForm { - pub mod_user_id: i32, - pub other_user_id: i32, + pub mod_person_id: i32, + pub other_person_id: i32, pub community_id: i32, pub reason: Option, pub banned: Option, @@ -137,8 +137,8 @@ pub struct ModBanFromCommunityForm { #[table_name = "mod_ban"] pub struct ModBan { pub id: i32, - pub mod_user_id: i32, - pub other_user_id: i32, + pub mod_person_id: i32, + pub other_person_id: i32, pub reason: Option, pub banned: Option, pub expires: Option, @@ -148,8 +148,8 @@ pub struct ModBan { #[derive(Insertable, AsChangeset)] #[table_name = "mod_ban"] pub struct ModBanForm { - pub mod_user_id: i32, - pub other_user_id: i32, + pub mod_person_id: i32, + pub other_person_id: i32, pub reason: Option, pub banned: Option, pub expires: Option, @@ -159,8 +159,8 @@ pub struct ModBanForm { #[table_name = "mod_add_community"] pub struct ModAddCommunity { pub id: i32, - pub mod_user_id: i32, - pub other_user_id: i32, + pub mod_person_id: i32, + pub other_person_id: i32, pub community_id: i32, pub removed: Option, pub when_: chrono::NaiveDateTime, @@ -169,8 +169,8 @@ pub struct ModAddCommunity { #[derive(Insertable, AsChangeset)] #[table_name = "mod_add_community"] pub struct ModAddCommunityForm { - pub mod_user_id: i32, - pub other_user_id: i32, + pub mod_person_id: i32, + pub other_person_id: i32, pub community_id: i32, pub removed: Option, } @@ -179,8 +179,8 @@ pub struct ModAddCommunityForm { #[table_name = "mod_add"] pub struct ModAdd { pub id: i32, - pub mod_user_id: i32, - pub other_user_id: i32, + pub mod_person_id: i32, + pub other_person_id: i32, pub removed: Option, pub when_: chrono::NaiveDateTime, } @@ -188,7 +188,7 @@ pub struct ModAdd { #[derive(Insertable, AsChangeset)] #[table_name = "mod_add"] pub struct ModAddForm { - pub mod_user_id: i32, - pub other_user_id: i32, + pub mod_person_id: i32, + pub other_person_id: i32, pub removed: Option, } diff --git a/crates/db_schema/src/source/password_reset_request.rs b/crates/db_schema/src/source/password_reset_request.rs index f81f28efe..ce1a423f1 100644 --- a/crates/db_schema/src/source/password_reset_request.rs +++ b/crates/db_schema/src/source/password_reset_request.rs @@ -4,7 +4,7 @@ use crate::schema::password_reset_request; #[table_name = "password_reset_request"] pub struct PasswordResetRequest { pub id: i32, - pub user_id: i32, + pub local_user_id: i32, pub token_encrypted: String, pub published: chrono::NaiveDateTime, } @@ -12,6 +12,6 @@ pub struct PasswordResetRequest { #[derive(Insertable, AsChangeset)] #[table_name = "password_reset_request"] pub struct PasswordResetRequestForm { - pub user_id: i32, + pub local_user_id: i32, pub token_encrypted: String, } diff --git a/crates/db_schema/src/source/person.rs b/crates/db_schema/src/source/person.rs new file mode 100644 index 000000000..cd0720776 --- /dev/null +++ b/crates/db_schema/src/source/person.rs @@ -0,0 +1,154 @@ +use crate::{ + schema::{person, person_alias_1, person_alias_2}, + Url, +}; +use serde::Serialize; + +#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] +#[table_name = "person"] +pub struct Person { + pub id: i32, + pub name: String, + pub preferred_username: Option, + pub avatar: Option, + pub banned: bool, + pub published: chrono::NaiveDateTime, + pub updated: Option, + pub actor_id: Url, + pub bio: Option, + pub local: bool, + pub private_key: Option, + pub public_key: Option, + pub last_refreshed_at: chrono::NaiveDateTime, + pub banner: Option, + pub deleted: bool, + pub inbox_url: Url, + pub shared_inbox_url: Option, +} + +/// A safe representation of user, without the sensitive info +#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] +#[table_name = "person"] +pub struct PersonSafe { + pub id: i32, + pub name: String, + pub preferred_username: Option, + pub avatar: Option, + pub banned: bool, + pub published: chrono::NaiveDateTime, + pub updated: Option, + pub actor_id: Url, + pub bio: Option, + pub local: bool, + pub last_refreshed_at: chrono::NaiveDateTime, + pub banner: Option, + pub deleted: bool, + pub inbox_url: Url, + pub shared_inbox_url: Option, +} + + +#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] +#[table_name = "person_alias_1"] +pub struct PersonAlias1 { + pub id: i32, + pub name: String, + pub preferred_username: Option, + pub avatar: Option, + pub banned: bool, + pub published: chrono::NaiveDateTime, + pub updated: Option, + pub actor_id: Url, + pub bio: Option, + pub local: bool, + pub private_key: Option, + pub public_key: Option, + pub last_refreshed_at: chrono::NaiveDateTime, + pub banner: Option, + pub deleted: bool, + pub inbox_url: Url, + pub shared_inbox_url: Option, +} + +#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] +#[table_name = "person_alias_1"] +pub struct PersonSafeAlias1 { + pub id: i32, + pub name: String, + pub preferred_username: Option, + pub avatar: Option, + pub banned: bool, + pub published: chrono::NaiveDateTime, + pub updated: Option, + pub actor_id: Url, + pub bio: Option, + pub local: bool, + pub last_refreshed_at: chrono::NaiveDateTime, + pub banner: Option, + pub deleted: bool, + pub inbox_url: Url, + pub shared_inbox_url: Option, +} + +#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] +#[table_name = "person_alias_2"] +pub struct PersonAlias2 { + pub id: i32, + pub name: String, + pub preferred_username: Option, + pub avatar: Option, + pub banned: bool, + pub published: chrono::NaiveDateTime, + pub updated: Option, + pub actor_id: Url, + pub bio: Option, + pub local: bool, + pub private_key: Option, + pub public_key: Option, + pub last_refreshed_at: chrono::NaiveDateTime, + pub banner: Option, + pub deleted: bool, + pub inbox_url: Url, + pub shared_inbox_url: Option, +} + +#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] +#[table_name = "person_alias_1"] +pub struct PersonSafeAlias2 { + pub id: i32, + pub name: String, + pub preferred_username: Option, + pub avatar: Option, + pub banned: bool, + pub published: chrono::NaiveDateTime, + pub updated: Option, + pub actor_id: Url, + pub bio: Option, + pub local: bool, + pub last_refreshed_at: chrono::NaiveDateTime, + pub banner: Option, + pub deleted: bool, + pub inbox_url: Url, + pub shared_inbox_url: Option, +} + +#[derive(Insertable, AsChangeset, Clone)] +#[table_name = "person"] +pub struct PersonForm { + pub name: String, + pub preferred_username: Option>, + pub avatar: Option>, + pub banned: Option, + pub published: Option, + pub updated: Option, + pub actor_id: Option, + pub bio: Option>, + pub local: Option, + pub private_key: Option>, + pub public_key: Option>, + pub last_refreshed_at: Option, + pub banner: Option>, + pub deleted: Option, + pub inbox_url: Option, + pub shared_inbox_url: Option>, +} diff --git a/crates/db_schema/src/source/user_mention.rs b/crates/db_schema/src/source/person_mention.rs similarity index 66% rename from crates/db_schema/src/source/user_mention.rs rename to crates/db_schema/src/source/person_mention.rs index 64fd56006..6ad9c078f 100644 --- a/crates/db_schema/src/source/user_mention.rs +++ b/crates/db_schema/src/source/person_mention.rs @@ -1,10 +1,10 @@ -use crate::{schema::user_mention, source::comment::Comment}; +use crate::{schema::person_mention, source::comment::Comment}; use serde::Serialize; #[derive(Clone, Queryable, Associations, Identifiable, PartialEq, Debug, Serialize)] #[belongs_to(Comment)] -#[table_name = "user_mention"] -pub struct UserMention { +#[table_name = "person_mention"] +pub struct PersonMention { pub id: i32, pub recipient_id: i32, pub comment_id: i32, @@ -13,8 +13,8 @@ pub struct UserMention { } #[derive(Insertable, AsChangeset)] -#[table_name = "user_mention"] -pub struct UserMentionForm { +#[table_name = "person_mention"] +pub struct PersonMentionForm { pub recipient_id: i32, pub comment_id: i32, pub read: Option, diff --git a/crates/db_schema/src/source/post.rs b/crates/db_schema/src/source/post.rs index 4ec6b56d0..03d6e7e85 100644 --- a/crates/db_schema/src/source/post.rs +++ b/crates/db_schema/src/source/post.rs @@ -57,7 +57,7 @@ pub struct PostForm { pub struct PostLike { pub id: i32, pub post_id: i32, - pub user_id: i32, + pub person_id: i32, pub score: i16, pub published: chrono::NaiveDateTime, } @@ -66,7 +66,7 @@ pub struct PostLike { #[table_name = "post_like"] pub struct PostLikeForm { pub post_id: i32, - pub user_id: i32, + pub person_id: i32, pub score: i16, } @@ -76,7 +76,7 @@ pub struct PostLikeForm { pub struct PostSaved { pub id: i32, pub post_id: i32, - pub user_id: i32, + pub person_id: i32, pub published: chrono::NaiveDateTime, } @@ -84,7 +84,7 @@ pub struct PostSaved { #[table_name = "post_saved"] pub struct PostSavedForm { pub post_id: i32, - pub user_id: i32, + pub person_id: i32, } #[derive(Identifiable, Queryable, Associations, PartialEq, Debug)] @@ -92,11 +92,8 @@ pub struct PostSavedForm { #[table_name = "post_read"] pub struct PostRead { pub id: i32, - pub post_id: i32, - - pub user_id: i32, - + pub person_id: i32, pub published: chrono::NaiveDateTime, } @@ -104,6 +101,5 @@ pub struct PostRead { #[table_name = "post_read"] pub struct PostReadForm { pub post_id: i32, - - pub user_id: i32, + pub person_id: i32, } diff --git a/crates/db_schema/src/source/user.rs b/crates/db_schema/src/source/user.rs deleted file mode 100644 index 17e8734cc..000000000 --- a/crates/db_schema/src/source/user.rs +++ /dev/null @@ -1,220 +0,0 @@ -use crate::{ - schema::{user_, user_alias_1, user_alias_2}, - Url, -}; -use serde::Serialize; - -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_"] -pub struct User_ { - pub id: i32, // person - pub name: String, // person - pub preferred_username: Option, // person - pub password_encrypted: String, // local_user - pub email: Option, // local_user - pub avatar: Option, // person - pub admin: bool, // local_user - pub banned: bool, // person? - pub published: chrono::NaiveDateTime, // person - pub updated: Option, // person - pub show_nsfw: bool, // local_user - pub theme: String, // local_user - pub default_sort_type: i16, // local_user - pub default_listing_type: i16, // local_user - pub lang: String, // local_user - pub show_avatars: bool, // local_user - pub send_notifications_to_email: bool, // local_user - pub matrix_user_id: Option, // local_user - pub actor_id: Url, // person - pub bio: Option, // person - pub local: bool, // person - pub private_key: Option, // person - pub public_key: Option, // person - pub last_refreshed_at: chrono::NaiveDateTime, // person - pub banner: Option, // person - pub deleted: bool, // person - pub inbox_url: Url, // person - pub shared_inbox_url: Option, // person -} - -/// A safe representation of user, without the sensitive info -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_"] -pub struct UserSafe { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub matrix_user_id: Option, - pub actor_id: Url, - pub bio: Option, - pub local: bool, - pub banner: Option, - pub deleted: bool, - pub inbox_url: Url, - pub shared_inbox_url: Option, -} - -/// A safe user view with only settings -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_"] -pub struct UserSafeSettings { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub email: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, - pub show_avatars: bool, - pub send_notifications_to_email: bool, - pub matrix_user_id: Option, - pub actor_id: Url, - pub bio: Option, - pub local: bool, - pub last_refreshed_at: chrono::NaiveDateTime, - pub banner: Option, - pub deleted: bool, -} - -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_alias_1"] -pub struct UserAlias1 { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub password_encrypted: String, - pub email: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, - pub show_avatars: bool, - pub send_notifications_to_email: bool, - pub matrix_user_id: Option, - pub actor_id: Url, - pub bio: Option, - pub local: bool, - pub private_key: Option, - pub public_key: Option, - pub last_refreshed_at: chrono::NaiveDateTime, - pub banner: Option, - pub deleted: bool, -} - -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_alias_1"] -pub struct UserSafeAlias1 { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub matrix_user_id: Option, - pub actor_id: Url, - pub bio: Option, - pub local: bool, - pub banner: Option, - pub deleted: bool, -} - -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_alias_2"] -pub struct UserAlias2 { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub password_encrypted: String, - pub email: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, - pub show_avatars: bool, - pub send_notifications_to_email: bool, - pub matrix_user_id: Option, - pub actor_id: Url, - pub bio: Option, - pub local: bool, - pub private_key: Option, - pub public_key: Option, - pub last_refreshed_at: chrono::NaiveDateTime, - pub banner: Option, - pub deleted: bool, -} - -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_alias_2"] -pub struct UserSafeAlias2 { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub matrix_user_id: Option, - pub actor_id: Url, - pub bio: Option, - pub local: bool, - pub banner: Option, - pub deleted: bool, -} - -#[derive(Insertable, AsChangeset, Clone)] -#[table_name = "user_"] -pub struct UserForm { - pub name: String, - pub preferred_username: Option>, - pub password_encrypted: String, - pub admin: bool, - pub banned: Option, - pub email: Option>, - pub avatar: Option>, - pub published: Option, - pub updated: Option, - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, - pub show_avatars: bool, - pub send_notifications_to_email: bool, - pub matrix_user_id: Option>, - pub actor_id: Option, - pub bio: Option>, - pub local: bool, - pub private_key: Option, - pub public_key: Option, - pub last_refreshed_at: Option, - pub banner: Option>, - pub inbox_url: Option, - pub shared_inbox_url: Option>, -} diff --git a/crates/db_views/src/comment_view.rs b/crates/db_views/src/comment_view.rs index 4f9a6a5f7..0db27794b 100644 --- a/crates/db_views/src/comment_view.rs +++ b/crates/db_views/src/comment_view.rs @@ -26,7 +26,7 @@ use lemmy_db_schema::{ }, source::{ comment::{Comment, CommentAlias1, CommentSaved}, - community::{Community, CommunityFollower, CommunitySafe, CommunityUserBan}, + community::{Community, CommunityFollower, CommunitySafe, CommunityPersonBan}, post::Post, user::{UserAlias1, UserSafe, UserSafeAlias1, User_}, }, @@ -55,7 +55,7 @@ type CommentViewTuple = ( Post, CommunitySafe, CommentAggregates, - Option, + Option, Option, Option, Option, @@ -545,7 +545,7 @@ mod tests { let comment_like_form = CommentLikeForm { comment_id: inserted_comment.id, post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_user.id, score: 1, }; diff --git a/crates/db_views/src/post_view.rs b/crates/db_views/src/post_view.rs index ed1ef4ce1..f56c2f9be 100644 --- a/crates/db_views/src/post_view.rs +++ b/crates/db_views/src/post_view.rs @@ -23,7 +23,7 @@ use lemmy_db_schema::{ user_, }, source::{ - community::{Community, CommunityFollower, CommunitySafe, CommunityUserBan}, + community::{Community, CommunityFollower, CommunitySafe, CommunityPersonBan}, post::{Post, PostRead, PostSaved}, user::{UserSafe, User_}, }, @@ -48,7 +48,7 @@ type PostViewTuple = ( Post, UserSafe, CommunitySafe, - Option, + Option, PostAggregates, Option, Option, @@ -523,7 +523,7 @@ mod tests { let post_like_form = PostLikeForm { post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_user.id, score: 1, }; @@ -532,7 +532,7 @@ mod tests { let expected_post_like = PostLike { id: inserted_post_like.id, post_id: inserted_post.id, - user_id: inserted_user.id, + person_id: inserted_user.id, published: inserted_post_like.published, score: 1, }; diff --git a/crates/db_views_actor/src/user_mention_view.rs b/crates/db_views_actor/src/user_mention_view.rs index ffdbe0300..dc37a8804 100644 --- a/crates/db_views_actor/src/user_mention_view.rs +++ b/crates/db_views_actor/src/user_mention_view.rs @@ -24,7 +24,7 @@ use lemmy_db_schema::{ }, source::{ comment::{Comment, CommentSaved}, - community::{Community, CommunityFollower, CommunitySafe, CommunityUserBan}, + community::{Community, CommunityFollower, CommunitySafe, CommunityPersonBan}, post::Post, user::{UserAlias1, UserSafe, UserSafeAlias1, User_}, user_mention::UserMention, @@ -55,7 +55,7 @@ type UserMentionViewTuple = ( CommunitySafe, UserSafeAlias1, CommentAggregates, - Option, + Option, Option, Option, Option, From 9cb4dad4b401ea0d322acd680147f5c6c831d73e Mon Sep 17 00:00:00 2001 From: Dessalines Date: Wed, 10 Mar 2021 23:43:11 -0500 Subject: [PATCH 06/18] A first pass. --- crates/api/src/comment.rs | 80 ++- crates/api/src/community.rs | 15 +- crates/api/src/lib.rs | 38 +- crates/api/src/{user.rs => local_user.rs} | 455 +++++++++-------- crates/api/src/post.rs | 96 +++- crates/api/src/routes.rs | 2 +- crates/api/src/site.rs | 10 +- crates/api_structs/src/lib.rs | 30 +- crates/api_structs/src/person.rs | 16 +- crates/api_structs/src/site.rs | 7 +- crates/apub/src/activities/receive/comment.rs | 11 +- crates/apub/src/activities/send/comment.rs | 13 +- crates/apub/src/activities/send/mod.rs | 2 +- crates/apub/src/activities/send/post.rs | 8 +- .../src/activities/send/private_message.rs | 14 +- crates/apub/src/fetcher/mod.rs | 2 +- crates/apub/src/fetcher/person.rs | 6 +- crates/apub/src/fetcher/search.rs | 4 +- crates/apub/src/http/mod.rs | 2 +- crates/apub/src/inbox/community_inbox.rs | 3 +- crates/apub/src/inbox/mod.rs | 2 +- crates/apub/src/inbox/person_inbox.rs | 2 +- crates/apub/src/lib.rs | 50 +- crates/apub/src/objects/comment.rs | 5 +- crates/apub/src/objects/mod.rs | 2 +- crates/apub/src/objects/person.rs | 7 +- crates/apub/src/objects/post.rs | 5 +- crates/apub/src/objects/private_message.rs | 5 +- crates/apub/src/routes.rs | 13 +- .../src/aggregates/comment_aggregates.rs | 2 +- .../src/aggregates/community_aggregates.rs | 2 +- crates/db_queries/src/aggregates/mod.rs | 2 +- .../src/aggregates/person_aggregates.rs | 5 +- .../src/aggregates/post_aggregates.rs | 2 +- .../src/aggregates/site_aggregates.rs | 8 +- crates/db_queries/src/source/activity.rs | 7 +- crates/db_queries/src/source/comment.rs | 2 +- crates/db_queries/src/source/community.rs | 17 +- crates/db_queries/src/source/local_user.rs | 61 +-- crates/db_queries/src/source/mod.rs | 6 +- crates/db_queries/src/source/moderator.rs | 2 +- crates/db_queries/src/source/person.rs | 108 ++--- .../db_queries/src/source/person_mention.rs | 2 +- .../db_queries/src/source/private_message.rs | 8 +- crates/db_queries/src/source/user.rs | 459 ------------------ crates/db_schema/src/source/local_user.rs | 72 +-- crates/db_schema/src/source/mod.rs | 6 +- crates/db_schema/src/source/person.rs | 205 ++++---- crates/db_schema/src/source/user.rs | 220 --------- crates/db_views/src/comment_report_view.rs | 4 +- crates/db_views/src/comment_view.rs | 13 +- crates/db_views/src/lib.rs | 2 +- crates/db_views/src/local_user_view.rs | 93 +++- crates/db_views/src/post_report_view.rs | 12 +- crates/db_views/src/post_view.rs | 18 +- crates/db_views/src/private_message_view.rs | 4 +- crates/db_views/src/site_view.rs | 4 +- .../src/community_follower_view.rs | 12 +- .../src/community_moderator_view.rs | 12 +- .../src/community_person_ban_view.rs | 7 +- crates/db_views_actor/src/community_view.rs | 7 +- .../db_views_actor/src/person_mention_view.rs | 8 +- crates/db_views_actor/src/person_view.rs | 4 +- .../src/mod_add_community_view.rs | 6 +- crates/db_views_moderator/src/mod_add_view.rs | 2 +- .../src/mod_ban_from_community_view.rs | 9 +- crates/db_views_moderator/src/mod_ban_view.rs | 2 +- .../src/mod_lock_post_view.rs | 4 +- .../src/mod_remove_comment_view.rs | 4 +- .../src/mod_remove_community_view.rs | 2 +- .../src/mod_remove_post_view.rs | 4 +- .../src/mod_sticky_post_view.rs | 4 +- src/code_migrations.rs | 66 ++- 73 files changed, 1010 insertions(+), 1394 deletions(-) rename crates/api/src/{user.rs => local_user.rs} (74%) delete mode 100644 crates/db_queries/src/source/user.rs delete mode 100644 crates/db_schema/src/source/user.rs diff --git a/crates/api/src/comment.rs b/crates/api/src/comment.rs index 711e8e725..aff39e024 100644 --- a/crates/api/src/comment.rs +++ b/crates/api/src/comment.rs @@ -2,9 +2,9 @@ use crate::{ check_community_ban, check_downvotes_enabled, collect_moderated_communities, - get_post, get_local_user_view_from_jwt, get_local_user_view_from_jwt_opt, + get_post, is_mod_or_admin, Perform, }; @@ -115,7 +115,9 @@ impl Perform for CreateComment { Err(_e) => return Err(ApiError::err("couldnt_create_comment").into()), }; - updated_comment.send_create(&local_user_view.person, context).await?; + updated_comment + .send_create(&local_user_view.person, context) + .await?; // Scan the comment for user mentions, add those rows let post_id = post.id; @@ -143,7 +145,9 @@ impl Perform for CreateComment { return Err(ApiError::err("couldnt_like_comment").into()); } - updated_comment.send_like(&local_user_view.person, context).await?; + updated_comment + .send_like(&local_user_view.person, context) + .await?; let person_id = local_user_view.person.id; let mut comment_view = blocking(context.pool(), move |conn| { @@ -201,7 +205,12 @@ impl Perform for EditComment { }) .await??; - check_community_ban(local_user_view.person.id, orig_comment.community.id, context.pool()).await?; + check_community_ban( + local_user_view.person.id, + orig_comment.community.id, + context.pool(), + ) + .await?; // Verify that only the creator can edit if local_user_view.person.id != orig_comment.creator.id { @@ -221,7 +230,9 @@ impl Perform for EditComment { }; // Send the apub update - updated_comment.send_update(&local_user_view.person, context).await?; + updated_comment + .send_update(&local_user_view.person, context) + .await?; // Do the mentions / recipients let updated_comment_content = updated_comment.content.to_owned(); @@ -277,7 +288,12 @@ impl Perform for DeleteComment { }) .await??; - check_community_ban(local_user_view.person.id, orig_comment.community.id, context.pool()).await?; + check_community_ban( + local_user_view.person.id, + orig_comment.community.id, + context.pool(), + ) + .await?; // Verify that only the creator can delete if local_user_view.person.id != orig_comment.creator.id { @@ -297,9 +313,13 @@ impl Perform for DeleteComment { // Send the apub message if deleted { - updated_comment.send_delete(&local_user_view.person, context).await?; + updated_comment + .send_delete(&local_user_view.person, context) + .await?; } else { - updated_comment.send_undo_delete(&local_user_view.person, context).await?; + updated_comment + .send_undo_delete(&local_user_view.person, context) + .await?; } // Refetch it @@ -357,10 +377,20 @@ impl Perform for RemoveComment { }) .await??; - check_community_ban(local_user_view.person.id, orig_comment.community.id, context.pool()).await?; + check_community_ban( + local_user_view.person.id, + orig_comment.community.id, + context.pool(), + ) + .await?; // Verify that only a mod or admin can remove - is_mod_or_admin(context.pool(), local_user_view.person.id, orig_comment.community.id).await?; + is_mod_or_admin( + context.pool(), + local_user_view.person.id, + orig_comment.community.id, + ) + .await?; // Do the remove let removed = data.removed; @@ -387,9 +417,13 @@ impl Perform for RemoveComment { // Send the apub message if removed { - updated_comment.send_remove(&local_user_view.person, context).await?; + updated_comment + .send_remove(&local_user_view.person, context) + .await?; } else { - updated_comment.send_undo_remove(&local_user_view.person, context).await?; + updated_comment + .send_undo_remove(&local_user_view.person, context) + .await?; } // Refetch it @@ -448,7 +482,12 @@ impl Perform for MarkCommentAsRead { }) .await??; - check_community_ban(local_user_view.person.id, orig_comment.community.id, context.pool()).await?; + check_community_ban( + local_user_view.person.id, + orig_comment.community.id, + context.pool(), + ) + .await?; // Verify that only the recipient can mark as read if local_user_view.person.id != orig_comment.get_recipient_id() { @@ -551,7 +590,12 @@ impl Perform for CreateCommentLike { }) .await??; - check_community_ban(local_user_view.person.id, orig_comment.community.id, context.pool()).await?; + check_community_ban( + local_user_view.person.id, + orig_comment.community.id, + context.pool(), + ) + .await?; // Add parent user to recipients recipient_ids.push(orig_comment.get_recipient_id()); @@ -583,10 +627,14 @@ impl Perform for CreateCommentLike { if like_form.score == 1 { comment.send_like(&local_user_view.person, context).await?; } else if like_form.score == -1 { - comment.send_dislike(&local_user_view.person, context).await?; + comment + .send_dislike(&local_user_view.person, context) + .await?; } } else { - comment.send_undo_like(&local_user_view.person, context).await?; + comment + .send_undo_like(&local_user_view.person, context) + .await?; } // Have to refetch the comment to get the current state diff --git a/crates/api/src/community.rs b/crates/api/src/community.rs index 6949a4a99..53b99c226 100644 --- a/crates/api/src/community.rs +++ b/crates/api/src/community.rs @@ -517,9 +517,15 @@ impl Perform for FollowCommunity { } else if data.follow { // Dont actually add to the community followers here, because you need // to wait for the accept - local_user_view.person.send_follow(&community.actor_id(), context).await?; + local_user_view + .person + .send_follow(&community.actor_id(), context) + .await?; } else { - local_user_view.person.send_unfollow(&community.actor_id(), context).await?; + local_user_view + .person + .send_unfollow(&community.actor_id(), context) + .await?; let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form); if blocking(context.pool(), unfollow).await?.is_err() { return Err(ApiError::err("community_follower_already_exists").into()); @@ -788,7 +794,10 @@ impl Perform for TransferCommunity { // Make sure user is the creator, or an admin if local_user_view.person.id != read_community.creator_id - && !admins.iter().map(|a| a.person.id).any(|x| x == local_user_view.person.id) + && !admins + .iter() + .map(|a| a.person.id) + .any(|x| x == local_user_view.person.id) { return Err(ApiError::err("not_an_admin").into()); } diff --git a/crates/api/src/lib.rs b/crates/api/src/lib.rs index 3fe3bc7ab..d71f4b6ee 100644 --- a/crates/api/src/lib.rs +++ b/crates/api/src/lib.rs @@ -3,17 +3,15 @@ use lemmy_api_structs::{ blocking, comment::*, community::*, + person::*, post::*, site::*, - person::*, websocket::*, }; use lemmy_db_queries::{ source::{ community::{CommunityModerator_, Community_}, site::Site_, - local_user::LocalUserSettings_, - local_user::LocalUser_, }, Crud, DbPool, @@ -22,15 +20,12 @@ use lemmy_db_schema::source::{ community::{Community, CommunityModerator}, post::Post, site::Site, - person::{Person, PersonSafe}, - local_user::LocalUserSettings, - local_user::LocalUser, }; +use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView}; use lemmy_db_views_actor::{ community_person_ban_view::CommunityPersonBanView, community_view::CommunityView, }; -use lemmy_db_views::local_user_view::{LocalUserView, LocalUserSettingsView}; use lemmy_utils::{ claims::Claims, settings::structs::Settings, @@ -45,10 +40,10 @@ use url::Url; pub mod comment; pub mod community; +pub mod local_user; pub mod post; pub mod routes; pub mod site; -pub mod user; pub mod websocket; #[async_trait::async_trait(?Send)] @@ -100,13 +95,19 @@ pub(crate) async fn get_post(post_id: i32, pool: &DbPool) -> Result Result { +pub(crate) async fn get_local_user_view_from_jwt( + jwt: &str, + pool: &DbPool, +) -> Result { let claims = match Claims::decode(&jwt) { Ok(claims) => claims.claims, Err(_e) => return Err(ApiError::err("not_logged_in").into()), }; let person_id = claims.id; - let local_user_view = blocking(pool, move |conn| LocalUserView::read(conn, person_id)).await??; + let local_user_view = blocking(pool, move |conn| { + LocalUserView::read_person(conn, person_id) + }) + .await??; // Check for a site ban if local_user_view.person.banned { return Err(ApiError::err("site_ban").into()); @@ -124,13 +125,19 @@ pub(crate) async fn get_local_user_view_from_jwt_opt( } } -pub(crate) async fn get_local_user_settings_view_from_jwt(jwt: &str, pool: &DbPool) -> Result { +pub(crate) async fn get_local_user_settings_view_from_jwt( + jwt: &str, + pool: &DbPool, +) -> Result { let claims = match Claims::decode(&jwt) { Ok(claims) => claims.claims, Err(_e) => return Err(ApiError::err("not_logged_in").into()), }; let person_id = claims.id; - let local_user_view = blocking(pool, move |conn| LocalUserSettingsView::read(conn, person_id)).await??; + let local_user_view = blocking(pool, move |conn| { + LocalUserSettingsView::read(conn, person_id) + }) + .await??; // Check for a site ban if local_user_view.person.banned { return Err(ApiError::err("site_ban").into()); @@ -143,7 +150,9 @@ pub(crate) async fn get_local_user_settings_view_from_jwt_opt( pool: &DbPool, ) -> Result, LemmyError> { match jwt { - Some(jwt) => Ok(Some(get_local_user_settings_view_from_jwt(jwt, pool).await?)), + Some(jwt) => Ok(Some( + get_local_user_settings_view_from_jwt(jwt, pool).await?, + )), None => Ok(None), } } @@ -153,7 +162,8 @@ pub(crate) async fn check_community_ban( community_id: i32, pool: &DbPool, ) -> Result<(), LemmyError> { - let is_banned = move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok(); + let is_banned = + move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok(); if blocking(pool, is_banned).await? { Err(ApiError::err("community_ban").into()) } else { diff --git a/crates/api/src/user.rs b/crates/api/src/local_user.rs similarity index 74% rename from crates/api/src/user.rs rename to crates/api/src/local_user.rs index 112814904..781ef8f9a 100644 --- a/crates/api/src/user.rs +++ b/crates/api/src/local_user.rs @@ -12,7 +12,7 @@ use anyhow::Context; use bcrypt::verify; use captcha::{gen, Difficulty}; use chrono::Duration; -use lemmy_api_structs::{blocking, send_email_to_user, person::*}; +use lemmy_api_structs::{blocking, person::*, send_email_to_user}; use lemmy_apub::{ generate_apub_endpoint, generate_followers_url, @@ -27,12 +27,13 @@ use lemmy_db_queries::{ source::{ comment::Comment_, community::Community_, + local_user::LocalUser_, password_reset_request::PasswordResetRequest_, + person::Person_, + person_mention::PersonMention_, post::Post_, private_message::PrivateMessage_, site::Site_, - person::Person_, - person_mention::PersonMention_, }, Crud, Followable, @@ -40,14 +41,28 @@ use lemmy_db_queries::{ ListingType, SortType, }; -use lemmy_db_schema::{naive_now, source::{comment::Comment, community::*, local_user::LocalUserForm, moderator::*, password_reset_request::*, person::*, person_mention::*, post::Post, private_message::*, site::*}}; +use lemmy_db_schema::{ + naive_now, + source::{ + comment::Comment, + community::*, + local_user::{LocalUser, LocalUserForm}, + moderator::*, + password_reset_request::*, + person::*, + person_mention::*, + post::Post, + private_message::*, + site::*, + }, +}; use lemmy_db_views::{ comment_report_view::CommentReportView, comment_view::CommentQueryBuilder, + local_user_view::LocalUserView, post_report_view::PostReportView, post_view::PostQueryBuilder, private_message_view::{PrivateMessageQueryBuilder, PrivateMessageView}, - local_user_view::LocalUserView, }; use lemmy_db_views_actor::{ community_follower_view::CommunityFollowerView, @@ -103,7 +118,11 @@ impl Perform for Login { }; // Verify the password - let valid: bool = verify(&data.password, &local_user_view.local_user.password_encrypted).unwrap_or(false); + let valid: bool = verify( + &data.password, + &local_user_view.local_user.password_encrypted, + ) + .unwrap_or(false); if !valid { return Err(ApiError::err("password_incorrect").into()); } @@ -175,7 +194,7 @@ impl Perform for Register { let actor_id = generate_apub_endpoint(EndpointType::Person, &data.username)?; // We have to create both a person, and local_user - + // Register the new person let person_form = PersonForm { name: data.username.to_owned(), @@ -186,18 +205,11 @@ impl Perform for Register { updated: None, banned: None, deleted: None, - show_nsfw: data.show_nsfw, - theme: "browser".into(), - default_sort_type: SortType::Active as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, actor_id: Some(actor_id.clone()), bio: None, - local: true, - private_key: Some(actor_keypair.private_key), - public_key: Some(actor_keypair.public_key), + local: Some(true), + private_key: Some(Some(actor_keypair.private_key)), + public_key: Some(Some(actor_keypair.public_key)), last_refreshed_at: None, inbox_url: Some(generate_inbox_url(&actor_id)?), shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)), @@ -209,8 +221,8 @@ impl Perform for Register { }) .await? { - Ok(user) => user, - Err(e) => { + Ok(u) => u, + Err(_) => { return Err(ApiError::err("user_already_exists").into()); } }; @@ -221,11 +233,17 @@ impl Perform for Register { email: Some(data.email.to_owned()), matrix_user_id: None, password_encrypted: data.password.to_owned(), - admin: no_admins, - + admin: Some(no_admins), + show_nsfw: Some(data.show_nsfw), + theme: Some("browser".into()), + default_sort_type: Some(SortType::Active as i16), + default_listing_type: Some(ListingType::Subscribed as i16), + lang: Some("browser".into()), + show_avatars: Some(true), + send_notifications_to_email: Some(false), }; - let inserted_local_user = match blocking(context.pool(), move |conn| { + match blocking(context.pool(), move |conn| { LocalUser::register(conn, &local_user_form) }) .await? @@ -241,12 +259,14 @@ impl Perform for Register { }; // If the local user creation errored, then delete that person - blocking(context.pool(), move |conn| Person::delete(&conn, inserted_person.id)).await??; + blocking(context.pool(), move |conn| { + Person::delete(&conn, inserted_person.id) + }) + .await??; return Err(ApiError::err(err_type).into()); } }; - let main_community_keypair = generate_actor_keypair()?; @@ -374,7 +394,7 @@ impl Perform for SaveUserSettings { _websocket_id: Option, ) -> Result { let data: &SaveUserSettings = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let avatar = diesel_option_overwrite_to_url(&data.avatar)?; let banner = diesel_option_overwrite_to_url(&data.banner)?; @@ -395,7 +415,8 @@ impl Perform for SaveUserSettings { } } - let user_id = user.id; + let local_user_id = local_user_view.local_user.id; + let person_id = local_user_view.person.id; let password_encrypted = match &data.new_password { Some(new_password) => { match &data.new_password_verify { @@ -410,13 +431,15 @@ impl Perform for SaveUserSettings { // Check the old password match &data.old_password { Some(old_password) => { - let valid: bool = verify(old_password, &user.password_encrypted).unwrap_or(false); + let valid: bool = + verify(old_password, &local_user_view.local_user.password_encrypted) + .unwrap_or(false); if !valid { return Err(ApiError::err("password_incorrect").into()); } let new_password = new_password.to_owned(); let user = blocking(context.pool(), move |conn| { - User_::update_password(conn, user_id, &new_password) + LocalUser::update_password(conn, local_user_id, &new_password) }) .await??; user.password_encrypted @@ -427,25 +450,48 @@ impl Perform for SaveUserSettings { None => return Err(ApiError::err("passwords_dont_match").into()), } } - None => user.password_encrypted, + None => local_user_view.local_user.password_encrypted, }; let default_listing_type = data.default_listing_type; let default_sort_type = data.default_sort_type; - let user_form = UserForm { - name: user.name, - email, - matrix_user_id, + let person_form = PersonForm { + name: local_user_view.person.name, avatar, banner, inbox_url: None, - password_encrypted, preferred_username, - published: Some(user.published), + published: None, updated: Some(naive_now()), - admin: user.admin, - banned: Some(user.banned), + banned: None, + deleted: None, + actor_id: None, + bio, + local: None, + private_key: None, + public_key: None, + last_refreshed_at: None, + shared_inbox_url: None, + }; + + let person_res = blocking(context.pool(), move |conn| { + Person::update(conn, person_id, &person_form) + }) + .await?; + let updated_person: Person = match person_res { + Ok(p) => p, + Err(_) => { + return Err(ApiError::err("user_already_exists").into()); + } + }; + + let local_user_form = LocalUserForm { + person_id, + email, + matrix_user_id, + password_encrypted, + admin: None, show_nsfw: data.show_nsfw, theme: data.theme.to_owned(), default_sort_type, @@ -453,24 +499,17 @@ impl Perform for SaveUserSettings { lang: data.lang.to_owned(), show_avatars: data.show_avatars, send_notifications_to_email: data.send_notifications_to_email, - actor_id: Some(user.actor_id), - bio, - local: user.local, - private_key: user.private_key, - public_key: user.public_key, - last_refreshed_at: None, - shared_inbox_url: None, }; - let res = blocking(context.pool(), move |conn| { - User_::update(conn, user_id, &user_form) + let local_user_res = blocking(context.pool(), move |conn| { + LocalUser::update(conn, local_user_id, &local_user_form) }) .await?; - let updated_user: User_ = match res { + match local_user_res { Ok(user) => user, Err(e) => { let err_type = if e.to_string() - == "duplicate key value violates unique constraint \"user__email_key\"" + == "duplicate key value violates unique constraint \"local_user_email_key\"" { "email_already_exists" } else { @@ -483,25 +522,25 @@ impl Perform for SaveUserSettings { // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(updated_user.id, Settings::get().hostname())?, + jwt: Claims::jwt(updated_person.id, Settings::get().hostname())?, }) } } #[async_trait::async_trait(?Send)] -impl Perform for GetUserDetails { - type Response = GetUserDetailsResponse; +impl Perform for GetPersonDetails { + type Response = GetPersonDetailsResponse; async fn perform( &self, context: &Data, _websocket_id: Option, - ) -> Result { - let data: &GetUserDetails = &self; - let user = get_local_user_view_from_jwt_opt(&data.auth, context.pool()).await?; + ) -> Result { + let data: &GetPersonDetails = &self; + let local_user_view = get_local_user_view_from_jwt_opt(&data.auth, context.pool()).await?; - let show_nsfw = match &user { - Some(user) => user.show_nsfw, + let show_nsfw = match &local_user_view { + Some(uv) => uv.local_user.show_nsfw, None => false, }; @@ -511,26 +550,26 @@ impl Perform for GetUserDetails { .username .to_owned() .unwrap_or_else(|| "admin".to_string()); - let user_details_id = match data.user_id { + let person_details_id = match data.person_id { Some(id) => id, None => { - let user = blocking(context.pool(), move |conn| { - User_::read_from_name(conn, &username) + let person = blocking(context.pool(), move |conn| { + Person::find_by_name(conn, &username) }) .await?; - match user { - Ok(user) => user.id, + match person { + Ok(p) => p.id, Err(_e) => return Err(ApiError::err("couldnt_find_that_username_or_email").into()), } } }; - let user_id = user.map(|u| u.id); + let person_id = local_user_view.map(|uv| uv.person.id); // You don't need to return settings for the user, since this comes back with GetSite // `my_user` - let user_view = blocking(context.pool(), move |conn| { - UserViewSafe::read(conn, user_details_id) + let person_view = blocking(context.pool(), move |conn| { + PersonViewSafe::read(conn, person_details_id) }) .await??; @@ -545,12 +584,12 @@ impl Perform for GetUserDetails { .show_nsfw(show_nsfw) .saved_only(saved_only) .community_id(community_id) - .my_user_id(user_id) + .my_person_id(person_id) .page(page) .limit(limit); let mut comments_query = CommentQueryBuilder::create(conn) - .my_person_id(user_id) + .my_person_id(person_id) .sort(&sort) .saved_only(saved_only) .page(page) @@ -559,8 +598,8 @@ impl Perform for GetUserDetails { // If its saved only, you don't care what creator it was // Or, if its not saved, then you only want it for that specific creator if !saved_only { - posts_query = posts_query.creator_id(user_details_id); - comments_query = comments_query.creator_id(user_details_id); + posts_query = posts_query.creator_id(person_details_id); + comments_query = comments_query.creator_id(person_details_id); } let posts = posts_query.list()?; @@ -571,22 +610,22 @@ impl Perform for GetUserDetails { .await??; let mut follows = vec![]; - if let Some(uid) = user_id { - if uid == user_details_id { + if let Some(pid) = person_id { + if pid == person_details_id { follows = blocking(context.pool(), move |conn| { - CommunityFollowerView::for_user(conn, user_details_id) + CommunityFollowerView::for_person(conn, person_details_id) }) .await??; } }; let moderates = blocking(context.pool(), move |conn| { - CommunityModeratorView::for_person(conn, user_details_id) + CommunityModeratorView::for_person(conn, person_details_id) }) .await??; // Return the jwt - Ok(GetUserDetailsResponse { - user_view, + Ok(GetPersonDetailsResponse { + person_view, follows, moderates, comments, @@ -605,22 +644,28 @@ impl Perform for AddAdmin { websocket_id: Option, ) -> Result { let data: &AddAdmin = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; // Make sure user is an admin - is_admin(context.pool(), user.id).await?; + is_admin(&local_user_view)?; let added = data.added; - let added_user_id = data.user_id; - let add_admin = move |conn: &'_ _| User_::add_admin(conn, added_user_id, added); - if blocking(context.pool(), add_admin).await?.is_err() { - return Err(ApiError::err("couldnt_update_user").into()); - } + let added_local_user_id = data.local_user_id; + let added_admin = match blocking(context.pool(), move |conn| { + LocalUser::add_admin(conn, added_local_user_id, added) + }) + .await? + { + Ok(a) => a, + Err(_) => { + return Err(ApiError::err("couldnt_update_user").into()); + } + }; // Mod tables let form = ModAddForm { - mod_person_id: user.id, - other_person_id: data.user_id, + mod_person_id: local_user_view.person.id, + other_person_id: added_admin.person_id, removed: Some(!data.added), }; @@ -631,13 +676,13 @@ impl Perform for AddAdmin { }) .await??; - let mut admins = blocking(context.pool(), move |conn| UserViewSafe::admins(conn)).await??; + let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??; let creator_index = admins .iter() - .position(|r| r.user.id == site_creator_id) + .position(|r| r.person.id == site_creator_id) .context(location_info!())?; - let creator_user = admins.remove(creator_index); - admins.insert(0, creator_user); + let creator_person = admins.remove(creator_index); + admins.insert(0, creator_person); let res = AddAdminResponse { admins }; @@ -652,24 +697,24 @@ impl Perform for AddAdmin { } #[async_trait::async_trait(?Send)] -impl Perform for BanUser { - type Response = BanUserResponse; +impl Perform for BanPerson { + type Response = BanPersonResponse; async fn perform( &self, context: &Data, websocket_id: Option, - ) -> Result { - let data: &BanUser = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + ) -> Result { + let data: &BanPerson = &self; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; // Make sure user is an admin - is_admin(context.pool(), user.id).await?; + is_admin(&local_user_view)?; let ban = data.ban; - let banned_user_id = data.user_id; - let ban_user = move |conn: &'_ _| User_::ban_user(conn, banned_user_id, ban); - if blocking(context.pool(), ban_user).await?.is_err() { + let banned_person_id = data.person_id; + let ban_person = move |conn: &'_ _| Person::ban_person(conn, banned_person_id, ban); + if blocking(context.pool(), ban_person).await?.is_err() { return Err(ApiError::err("couldnt_update_user").into()); } @@ -677,19 +722,19 @@ impl Perform for BanUser { if data.remove_data { // Posts blocking(context.pool(), move |conn: &'_ _| { - Post::update_removed_for_creator(conn, banned_user_id, None, true) + Post::update_removed_for_creator(conn, banned_person_id, None, true) }) .await??; // Communities blocking(context.pool(), move |conn: &'_ _| { - Community::update_removed_for_creator(conn, banned_user_id, true) + Community::update_removed_for_creator(conn, banned_person_id, true) }) .await??; // Comments blocking(context.pool(), move |conn: &'_ _| { - Comment::update_removed_for_creator(conn, banned_user_id, true) + Comment::update_removed_for_creator(conn, banned_person_id, true) }) .await??; } @@ -701,8 +746,8 @@ impl Perform for BanUser { }; let form = ModBanForm { - mod_person_id: user.id, - other_person_id: data.user_id, + mod_person_id: local_user_view.person.id, + other_person_id: data.person_id, reason: data.reason.to_owned(), banned: Some(data.ban), expires, @@ -710,14 +755,14 @@ impl Perform for BanUser { blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??; - let user_id = data.user_id; - let user_view = blocking(context.pool(), move |conn| { - UserViewSafe::read(conn, user_id) + let person_id = data.person_id; + let person_view = blocking(context.pool(), move |conn| { + PersonViewSafe::read(conn, person_id) }) .await??; - let res = BanUserResponse { - user_view, + let res = BanPersonResponse { + person_view, banned: data.ban, }; @@ -741,20 +786,20 @@ impl Perform for GetReplies { _websocket_id: Option, ) -> Result { let data: &GetReplies = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let sort = SortType::from_str(&data.sort)?; let page = data.page; let limit = data.limit; let unread_only = data.unread_only; - let user_id = user.id; + let person_id = local_user_view.person.id; let replies = blocking(context.pool(), move |conn| { CommentQueryBuilder::create(conn) .sort(&sort) .unread_only(unread_only) - .recipient_id(user_id) - .my_person_id(user_id) + .recipient_id(person_id) + .my_person_id(person_id) .page(page) .limit(limit) .list() @@ -766,27 +811,27 @@ impl Perform for GetReplies { } #[async_trait::async_trait(?Send)] -impl Perform for GetUserMentions { - type Response = GetUserMentionsResponse; +impl Perform for GetPersonMentions { + type Response = GetPersonMentionsResponse; async fn perform( &self, context: &Data, _websocket_id: Option, - ) -> Result { - let data: &GetUserMentions = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + ) -> Result { + let data: &GetPersonMentions = &self; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let sort = SortType::from_str(&data.sort)?; let page = data.page; let limit = data.limit; let unread_only = data.unread_only; - let user_id = user.id; + let person_id = local_user_view.person.id; let mentions = blocking(context.pool(), move |conn| { - UserMentionQueryBuilder::create(conn) - .recipient_id(user_id) - .my_user_id(user_id) + PersonMentionQueryBuilder::create(conn) + .recipient_id(person_id) + .my_person_id(person_id) .sort(&sort) .unread_only(unread_only) .page(page) @@ -795,47 +840,50 @@ impl Perform for GetUserMentions { }) .await??; - Ok(GetUserMentionsResponse { mentions }) + Ok(GetPersonMentionsResponse { mentions }) } } #[async_trait::async_trait(?Send)] -impl Perform for MarkUserMentionAsRead { - type Response = UserMentionResponse; +impl Perform for MarkPersonMentionAsRead { + type Response = PersonMentionResponse; async fn perform( &self, context: &Data, _websocket_id: Option, - ) -> Result { - let data: &MarkUserMentionAsRead = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + ) -> Result { + let data: &MarkPersonMentionAsRead = &self; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; - let user_mention_id = data.user_mention_id; - let read_user_mention = blocking(context.pool(), move |conn| { - UserMention::read(conn, user_mention_id) + let person_mention_id = data.person_mention_id; + let read_person_mention = blocking(context.pool(), move |conn| { + PersonMention::read(conn, person_mention_id) }) .await??; - if user.id != read_user_mention.recipient_id { + if local_user_view.person.id != read_person_mention.recipient_id { return Err(ApiError::err("couldnt_update_comment").into()); } - let user_mention_id = read_user_mention.id; + let person_mention_id = read_person_mention.id; let read = data.read; - let update_mention = move |conn: &'_ _| UserMention::update_read(conn, user_mention_id, read); + let update_mention = + move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read); if blocking(context.pool(), update_mention).await?.is_err() { return Err(ApiError::err("couldnt_update_comment").into()); }; - let user_mention_id = read_user_mention.id; - let user_id = user.id; - let user_mention_view = blocking(context.pool(), move |conn| { - UserMentionView::read(conn, user_mention_id, Some(user_id)) + let person_mention_id = read_person_mention.id; + let person_id = local_user_view.person.id; + let person_mention_view = blocking(context.pool(), move |conn| { + PersonMentionView::read(conn, person_mention_id, Some(person_id)) }) .await??; - Ok(UserMentionResponse { user_mention_view }) + Ok(PersonMentionResponse { + person_mention_view, + }) } } @@ -849,13 +897,13 @@ impl Perform for MarkAllAsRead { _websocket_id: Option, ) -> Result { let data: &MarkAllAsRead = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; - let user_id = user.id; + let person_id = local_user_view.person.id; let replies = blocking(context.pool(), move |conn| { CommentQueryBuilder::create(conn) - .my_person_id(user_id) - .recipient_id(user_id) + .my_person_id(person_id) + .recipient_id(person_id) .unread_only(true) .page(1) .limit(999) @@ -875,8 +923,9 @@ impl Perform for MarkAllAsRead { } // Mark all user mentions as read - let update_user_mentions = move |conn: &'_ _| UserMention::mark_all_as_read(conn, user_id); - if blocking(context.pool(), update_user_mentions) + let update_person_mentions = + move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id); + if blocking(context.pool(), update_person_mentions) .await? .is_err() { @@ -884,7 +933,7 @@ impl Perform for MarkAllAsRead { } // Mark all private_messages as read - let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, user_id); + let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id); if blocking(context.pool(), update_pm).await?.is_err() { return Err(ApiError::err("couldnt_update_private_message").into()); } @@ -903,29 +952,33 @@ impl Perform for DeleteAccount { _websocket_id: Option, ) -> Result { let data: &DeleteAccount = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; // Verify the password - let valid: bool = verify(&data.password, &user.password_encrypted).unwrap_or(false); + let valid: bool = verify( + &data.password, + &local_user_view.local_user.password_encrypted, + ) + .unwrap_or(false); if !valid { return Err(ApiError::err("password_incorrect").into()); } // Comments - let user_id = user.id; - let permadelete = move |conn: &'_ _| Comment::permadelete_for_creator(conn, user_id); + let person_id = local_user_view.person.id; + let permadelete = move |conn: &'_ _| Comment::permadelete_for_creator(conn, person_id); if blocking(context.pool(), permadelete).await?.is_err() { return Err(ApiError::err("couldnt_update_comment").into()); } // Posts - let permadelete = move |conn: &'_ _| Post::permadelete_for_creator(conn, user_id); + let permadelete = move |conn: &'_ _| Post::permadelete_for_creator(conn, person_id); if blocking(context.pool(), permadelete).await?.is_err() { return Err(ApiError::err("couldnt_update_post").into()); } blocking(context.pool(), move |conn| { - User_::delete_account(conn, user_id) + Person::delete_account(conn, person_id) }) .await??; @@ -948,12 +1001,12 @@ impl Perform for PasswordReset { // Fetch that email let email = data.email.clone(); - let user = match blocking(context.pool(), move |conn| { - User_::find_by_email(conn, &email) + let local_user_view = match blocking(context.pool(), move |conn| { + LocalUserView::find_by_email(conn, &email) }) .await? { - Ok(user) => user, + Ok(lu) => lu, Err(_e) => return Err(ApiError::err("couldnt_find_that_username_or_email").into()), }; @@ -962,19 +1015,19 @@ impl Perform for PasswordReset { // Insert the row let token2 = token.clone(); - let user_id = user.id; + let local_user_id = local_user_view.local_user.id; blocking(context.pool(), move |conn| { - PasswordResetRequest::create_token(conn, user_id, &token2) + PasswordResetRequest::create_token(conn, local_user_id, &token2) }) .await??; // Email the pure token to the user. // TODO no i18n support here. - let user_email = &user.email.expect("email"); - let subject = &format!("Password reset for {}", user.name); + let email = &local_user_view.local_user.email.expect("email"); + let subject = &format!("Password reset for {}", local_user_view.person.name); let hostname = &Settings::get().get_protocol_and_hostname(); - let html = &format!("

Password Reset Request for {}


Click here to reset your password", user.name, hostname, &token); - match send_email(subject, user_email, &user.name, html) { + let html = &format!("

Password Reset Request for {}


Click here to reset your password", local_user_view.person.name, hostname, &token); + match send_email(subject, email, &local_user_view.person.name, html) { Ok(_o) => _o, Err(_e) => return Err(ApiError::err(&_e).into()), }; @@ -996,7 +1049,7 @@ impl Perform for PasswordChange { // Fetch the user_id from the token let token = data.token.clone(); - let user_id = blocking(context.pool(), move |conn| { + let local_user_id = blocking(context.pool(), move |conn| { PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id) }) .await??; @@ -1010,18 +1063,18 @@ impl Perform for PasswordChange { // Update the user with the new password let password = data.password.clone(); - let updated_user = match blocking(context.pool(), move |conn| { - User_::update_password(conn, user_id, &password) + let updated_local_user = match blocking(context.pool(), move |conn| { + LocalUser::update_password(conn, local_user_id, &password) }) .await? { - Ok(user) => user, + Ok(u) => u, Err(_e) => return Err(ApiError::err("couldnt_update_user").into()), }; // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(updated_user.id, Settings::get().hostname())?, + jwt: Claims::jwt(updated_local_user.id, Settings::get().hostname())?, }) } } @@ -1036,13 +1089,13 @@ impl Perform for CreatePrivateMessage { websocket_id: Option, ) -> Result { let data: &CreatePrivateMessage = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let content_slurs_removed = remove_slurs(&data.content.to_owned()); let private_message_form = PrivateMessageForm { content: content_slurs_removed.to_owned(), - creator_id: user.id, + creator_id: local_user_view.person.id, recipient_id: data.recipient_id, deleted: None, read: None, @@ -1084,28 +1137,32 @@ impl Perform for CreatePrivateMessage { Err(_e) => return Err(ApiError::err("couldnt_create_private_message").into()), }; - updated_private_message.send_create(&user, context).await?; + updated_private_message + .send_create(&local_user_view.person, context) + .await?; // Send notifications to the recipient let recipient_id = data.recipient_id; - let recipient_user = - blocking(context.pool(), move |conn| User_::read(conn, recipient_id)).await??; - if recipient_user.send_notifications_to_email { + let recipient = blocking(context.pool(), move |conn| { + LocalUserView::read_person(conn, recipient_id) + }) + .await??; + if recipient.local_user.send_notifications_to_email { send_email_to_user( - recipient_user, + recipient, "Private Message from", "Private Message", &content_slurs_removed, ); } - let message = blocking(context.pool(), move |conn| { + let private_message_view = blocking(context.pool(), move |conn| { PrivateMessageView::read(conn, inserted_private_message.id) }) .await??; let res = PrivateMessageResponse { - private_message_view: message, + private_message_view, }; context.chat_server().do_send(SendUserRoomMessage { @@ -1129,7 +1186,7 @@ impl Perform for EditPrivateMessage { websocket_id: Option, ) -> Result { let data: &EditPrivateMessage = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; // Checking permissions let private_message_id = data.private_message_id; @@ -1137,7 +1194,7 @@ impl Perform for EditPrivateMessage { PrivateMessage::read(conn, private_message_id) }) .await??; - if user.id != orig_private_message.creator_id { + if local_user_view.person.id != orig_private_message.creator_id { return Err(ApiError::err("no_private_message_edit_allowed").into()); } @@ -1154,17 +1211,19 @@ impl Perform for EditPrivateMessage { }; // Send the apub update - updated_private_message.send_update(&user, context).await?; + updated_private_message + .send_update(&local_user_view.person, context) + .await?; let private_message_id = data.private_message_id; - let message = blocking(context.pool(), move |conn| { + let private_message_view = blocking(context.pool(), move |conn| { PrivateMessageView::read(conn, private_message_id) }) .await??; - let recipient_id = message.recipient.id; + let recipient_id = private_message_view.recipient.id; let res = PrivateMessageResponse { - private_message_view: message, + private_message_view, }; context.chat_server().do_send(SendUserRoomMessage { @@ -1188,7 +1247,7 @@ impl Perform for DeletePrivateMessage { websocket_id: Option, ) -> Result { let data: &DeletePrivateMessage = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; // Checking permissions let private_message_id = data.private_message_id; @@ -1196,7 +1255,7 @@ impl Perform for DeletePrivateMessage { PrivateMessage::read(conn, private_message_id) }) .await??; - if user.id != orig_private_message.creator_id { + if local_user_view.person.id != orig_private_message.creator_id { return Err(ApiError::err("no_private_message_edit_allowed").into()); } @@ -1214,22 +1273,24 @@ impl Perform for DeletePrivateMessage { // Send the apub update if data.deleted { - updated_private_message.send_delete(&user, context).await?; + updated_private_message + .send_delete(&local_user_view.person, context) + .await?; } else { updated_private_message - .send_undo_delete(&user, context) + .send_undo_delete(&local_user_view.person, context) .await?; } let private_message_id = data.private_message_id; - let message = blocking(context.pool(), move |conn| { + let private_message_view = blocking(context.pool(), move |conn| { PrivateMessageView::read(conn, private_message_id) }) .await??; - let recipient_id = message.recipient.id; + let recipient_id = private_message_view.recipient.id; let res = PrivateMessageResponse { - private_message_view: message, + private_message_view, }; context.chat_server().do_send(SendUserRoomMessage { @@ -1253,7 +1314,7 @@ impl Perform for MarkPrivateMessageAsRead { websocket_id: Option, ) -> Result { let data: &MarkPrivateMessageAsRead = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; // Checking permissions let private_message_id = data.private_message_id; @@ -1261,7 +1322,7 @@ impl Perform for MarkPrivateMessageAsRead { PrivateMessage::read(conn, private_message_id) }) .await??; - if user.id != orig_private_message.recipient_id { + if local_user_view.person.id != orig_private_message.recipient_id { return Err(ApiError::err("couldnt_update_private_message").into()); } @@ -1280,14 +1341,14 @@ impl Perform for MarkPrivateMessageAsRead { // No need to send an apub update let private_message_id = data.private_message_id; - let message = blocking(context.pool(), move |conn| { + let private_message_view = blocking(context.pool(), move |conn| { PrivateMessageView::read(conn, private_message_id) }) .await??; - let recipient_id = message.recipient.id; + let recipient_id = private_message_view.recipient.id; let res = PrivateMessageResponse { - private_message_view: message, + private_message_view, }; context.chat_server().do_send(SendUserRoomMessage { @@ -1311,14 +1372,14 @@ impl Perform for GetPrivateMessages { _websocket_id: Option, ) -> Result { let data: &GetPrivateMessages = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; - let user_id = user.id; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + let person_id = local_user_view.person.id; let page = data.page; let limit = data.limit; let unread_only = data.unread_only; let messages = blocking(context.pool(), move |conn| { - PrivateMessageQueryBuilder::create(&conn, user_id) + PrivateMessageQueryBuilder::create(&conn, person_id) .page(page) .limit(limit) .unread_only(unread_only) @@ -1342,12 +1403,12 @@ impl Perform for GetReportCount { websocket_id: Option, ) -> Result { let data: &GetReportCount = &self; - let user = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; + let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; - let user_id = user.id; + let person_id = local_user_view.person.id; let community_id = data.community; let community_ids = - collect_moderated_communities(user_id, community_id, context.pool()).await?; + collect_moderated_communities(person_id, community_id, context.pool()).await?; let res = { if community_ids.is_empty() { @@ -1380,7 +1441,7 @@ impl Perform for GetReportCount { context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::GetReportCount, response: res.clone(), - recipient_id: user.id, + recipient_id: local_user_view.person.id, websocket_id, }); diff --git a/crates/api/src/post.rs b/crates/api/src/post.rs index 922261715..5515575e6 100644 --- a/crates/api/src/post.rs +++ b/crates/api/src/post.rs @@ -122,7 +122,9 @@ impl Perform for CreatePost { Err(_e) => return Err(ApiError::err("couldnt_create_post").into()), }; - updated_post.send_create(&local_user_view.person, context).await?; + updated_post + .send_create(&local_user_view.person, context) + .await?; // They like their own post by default let like_form = PostLikeForm { @@ -136,7 +138,9 @@ impl Perform for CreatePost { return Err(ApiError::err("couldnt_like_post").into()); } - updated_post.send_like(&local_user_view.person, context).await?; + updated_post + .send_like(&local_user_view.person, context) + .await?; // Refetch the view let inserted_post_id = inserted_post.id; @@ -327,7 +331,9 @@ impl Perform for CreatePostLike { post.send_dislike(&local_user_view.person, context).await?; } } else { - post.send_undo_like(&local_user_view.person, context).await?; + post + .send_undo_like(&local_user_view.person, context) + .await?; } let post_id = data.post_id; @@ -375,7 +381,12 @@ impl Perform for EditPost { let post_id = data.post_id; let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; - check_community_ban(local_user_view.person.id, orig_post.community_id, context.pool()).await?; + check_community_ban( + local_user_view.person.id, + orig_post.community_id, + context.pool(), + ) + .await?; // Verify that only the creator can edit if !Post::is_post_creator(local_user_view.person.id, orig_post.creator_id) { @@ -427,7 +438,9 @@ impl Perform for EditPost { }; // Send apub update - updated_post.send_update(&local_user_view.person, context).await?; + updated_post + .send_update(&local_user_view.person, context) + .await?; let post_id = data.post_id; let post_view = blocking(context.pool(), move |conn| { @@ -462,7 +475,12 @@ impl Perform for DeletePost { let post_id = data.post_id; let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; - check_community_ban(local_user_view.person.id, orig_post.community_id, context.pool()).await?; + check_community_ban( + local_user_view.person.id, + orig_post.community_id, + context.pool(), + ) + .await?; // Verify that only the creator can delete if !Post::is_post_creator(local_user_view.person.id, orig_post.creator_id) { @@ -479,9 +497,13 @@ impl Perform for DeletePost { // apub updates if deleted { - updated_post.send_delete(&local_user_view.person, context).await?; + updated_post + .send_delete(&local_user_view.person, context) + .await?; } else { - updated_post.send_undo_delete(&local_user_view.person, context).await?; + updated_post + .send_undo_delete(&local_user_view.person, context) + .await?; } // Refetch the post @@ -518,10 +540,20 @@ impl Perform for RemovePost { let post_id = data.post_id; let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; - check_community_ban(local_user_view.person.id, orig_post.community_id, context.pool()).await?; + check_community_ban( + local_user_view.person.id, + orig_post.community_id, + context.pool(), + ) + .await?; // Verify that only the mods can remove - is_mod_or_admin(context.pool(), local_user_view.person.id, orig_post.community_id).await?; + is_mod_or_admin( + context.pool(), + local_user_view.person.id, + orig_post.community_id, + ) + .await?; // Update the post let post_id = data.post_id; @@ -545,9 +577,13 @@ impl Perform for RemovePost { // apub updates if removed { - updated_post.send_remove(&local_user_view.person, context).await?; + updated_post + .send_remove(&local_user_view.person, context) + .await?; } else { - updated_post.send_undo_remove(&local_user_view.person, context).await?; + updated_post + .send_undo_remove(&local_user_view.person, context) + .await?; } // Refetch the post @@ -585,10 +621,20 @@ impl Perform for LockPost { let post_id = data.post_id; let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; - check_community_ban(local_user_view.person.id, orig_post.community_id, context.pool()).await?; + check_community_ban( + local_user_view.person.id, + orig_post.community_id, + context.pool(), + ) + .await?; // Verify that only the mods can lock - is_mod_or_admin(context.pool(), local_user_view.person.id, orig_post.community_id).await?; + is_mod_or_admin( + context.pool(), + local_user_view.person.id, + orig_post.community_id, + ) + .await?; // Update the post let post_id = data.post_id; @@ -607,7 +653,9 @@ impl Perform for LockPost { blocking(context.pool(), move |conn| ModLockPost::create(conn, &form)).await??; // apub updates - updated_post.send_update(&local_user_view.person, context).await?; + updated_post + .send_update(&local_user_view.person, context) + .await?; // Refetch the post let post_id = data.post_id; @@ -643,10 +691,20 @@ impl Perform for StickyPost { let post_id = data.post_id; let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; - check_community_ban(local_user_view.person.id, orig_post.community_id, context.pool()).await?; + check_community_ban( + local_user_view.person.id, + orig_post.community_id, + context.pool(), + ) + .await?; // Verify that only the mods can sticky - is_mod_or_admin(context.pool(), local_user_view.person.id, orig_post.community_id).await?; + is_mod_or_admin( + context.pool(), + local_user_view.person.id, + orig_post.community_id, + ) + .await?; // Update the post let post_id = data.post_id; @@ -669,7 +727,9 @@ impl Perform for StickyPost { // Apub updates // TODO stickied should pry work like locked for ease of use - updated_post.send_update(&local_user_view.person, context).await?; + updated_post + .send_update(&local_user_view.person, context) + .await?; // Refetch the post let post_id = data.post_id; diff --git a/crates/api/src/routes.rs b/crates/api/src/routes.rs index 0c70dc0d3..6fc46ca4c 100644 --- a/crates/api/src/routes.rs +++ b/crates/api/src/routes.rs @@ -1,6 +1,6 @@ use crate::Perform; use actix_web::{error::ErrorBadRequest, *}; -use lemmy_api_structs::{comment::*, community::*, post::*, site::*, person::*, websocket::*}; +use lemmy_api_structs::{comment::*, community::*, person::*, post::*, site::*, websocket::*}; use lemmy_utils::rate_limit::RateLimit; use lemmy_websocket::{routes::chat_route, LemmyContext}; use serde::Deserialize; diff --git a/crates/api/src/site.rs b/crates/api/src/site.rs index 5acd099c4..4d561ab21 100644 --- a/crates/api/src/site.rs +++ b/crates/api/src/site.rs @@ -1,14 +1,15 @@ use crate::{ build_federated_instances, + get_local_user_settings_view_from_jwt, + get_local_user_settings_view_from_jwt_opt, get_local_user_view_from_jwt, get_local_user_view_from_jwt_opt, - get_local_user_settings_view_from_jwt_opt, is_admin, Perform, }; use actix_web::web::Data; use anyhow::Context; -use lemmy_api_structs::{blocking, site::*, person::Register}; +use lemmy_api_structs::{blocking, person::Register, site::*}; use lemmy_apub::fetcher::search::search_by_apub_id; use lemmy_db_queries::{ diesel_option_overwrite_to_url, @@ -536,13 +537,15 @@ impl Perform for TransferSite { let banned = blocking(context.pool(), move |conn| PersonViewSafe::banned(conn)).await??; let federated_instances = build_federated_instances(context.pool()).await?; + let my_user = Some(get_local_user_settings_view_from_jwt(&data.auth, context.pool()).await?); + Ok(GetSiteResponse { site_view: Some(site_view), admins, banned, online: 0, version: version::VERSION.to_string(), - my_user: Some(local_user_view), + my_user, federated_instances, }) } @@ -582,7 +585,6 @@ impl Perform for SaveSiteConfig { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; // Only let admins read this - let person_id = local_user_view.person.id; is_admin(&local_user_view)?; // Make sure docker doesn't have :ro at the end of the volume, so its not a read-only filesystem diff --git a/crates/api_structs/src/lib.rs b/crates/api_structs/src/lib.rs index b28cb37f9..c861136a1 100644 --- a/crates/api_structs/src/lib.rs +++ b/crates/api_structs/src/lib.rs @@ -1,17 +1,17 @@ pub mod comment; pub mod community; +pub mod person; pub mod post; pub mod site; -pub mod person; pub mod websocket; use diesel::PgConnection; use lemmy_db_queries::{Crud, DbPool}; use lemmy_db_schema::source::{ comment::Comment, - post::Post, person::Person, person_mention::{PersonMention, PersonMentionForm}, + post::Post, }; use lemmy_db_views::local_user_view::LocalUserView; use lemmy_utils::{email::send_email, settings::structs::Settings, utils::MentionData, LemmyError}; @@ -119,11 +119,17 @@ fn do_send_local_notifs( Some(parent_id) => { if let Ok(parent_comment) = Comment::read(&conn, parent_id) { if parent_comment.creator_id != person.id { - if let Ok(parent_user_view) = LocalUserView::read(&conn, parent_comment.creator_id) { + if let Ok(parent_user_view) = LocalUserView::read_person(&conn, parent_comment.creator_id) + { recipient_ids.push(parent_user_view.person.id); if do_send_email && parent_user_view.local_user.send_notifications_to_email { - send_email_to_user(parent_user_view, "Reply from", "Comment Reply", &comment.content) + send_email_to_user( + parent_user_view, + "Reply from", + "Comment Reply", + &comment.content, + ) } } } @@ -132,11 +138,16 @@ fn do_send_local_notifs( // Its a post None => { if post.creator_id != person.id { - if let Ok(parent_user_view) = LocalUserView::read(&conn, post.creator_id) { + if let Ok(parent_user_view) = LocalUserView::read_person(&conn, post.creator_id) { recipient_ids.push(parent_user_view.person.id); if do_send_email && parent_user_view.local_user.send_notifications_to_email { - send_email_to_user(parent_user_view, "Reply from", "Post Reply", &comment.content) + send_email_to_user( + parent_user_view, + "Reply from", + "Post Reply", + &comment.content, + ) } } } @@ -145,7 +156,12 @@ fn do_send_local_notifs( recipient_ids } -pub fn send_email_to_user(local_user_view: LocalUserView, subject_text: &str, body_text: &str, comment_content: &str) { +pub fn send_email_to_user( + local_user_view: LocalUserView, + subject_text: &str, + body_text: &str, + comment_content: &str, +) { if local_user_view.person.banned { return; } diff --git a/crates/api_structs/src/person.rs b/crates/api_structs/src/person.rs index ac1cca858..53e6d9f8d 100644 --- a/crates/api_structs/src/person.rs +++ b/crates/api_structs/src/person.rs @@ -45,11 +45,11 @@ pub struct CaptchaResponse { #[derive(Deserialize)] pub struct SaveUserSettings { - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, + pub show_nsfw: Option, + pub theme: Option, + pub default_sort_type: Option, + pub default_listing_type: Option, + pub lang: Option, pub avatar: Option, pub banner: Option, pub preferred_username: Option, @@ -59,8 +59,8 @@ pub struct SaveUserSettings { pub new_password: Option, pub new_password_verify: Option, pub old_password: Option, - pub show_avatars: bool, - pub send_notifications_to_email: bool, + pub show_avatars: Option, + pub send_notifications_to_email: Option, pub auth: String, } @@ -107,7 +107,7 @@ pub struct MarkAllAsRead { #[derive(Deserialize)] pub struct AddAdmin { - pub person_id: i32, + pub local_user_id: i32, pub added: bool, pub auth: String, } diff --git a/crates/api_structs/src/site.rs b/crates/api_structs/src/site.rs index d574a1604..f2781668d 100644 --- a/crates/api_structs/src/site.rs +++ b/crates/api_structs/src/site.rs @@ -1,4 +1,9 @@ -use lemmy_db_views::{comment_view::CommentView, post_view::PostView, site_view::SiteView, local_user_view::LocalUserSettingsView}; +use lemmy_db_views::{ + comment_view::CommentView, + local_user_view::LocalUserSettingsView, + post_view::PostView, + site_view::SiteView, +}; use lemmy_db_views_actor::{community_view::CommunityView, person_view::PersonViewSafe}; use lemmy_db_views_moderator::{ mod_add_community_view::ModAddCommunityView, diff --git a/crates/apub/src/activities/receive/comment.rs b/crates/apub/src/activities/receive/comment.rs index 5e01533d9..9ab14dabf 100644 --- a/crates/apub/src/activities/receive/comment.rs +++ b/crates/apub/src/activities/receive/comment.rs @@ -33,8 +33,15 @@ pub(crate) async fn receive_create_comment( // Its much easier to scrape them from the comment body, since the API has to do that // anyway. let mentions = scrape_text_for_mentions(&comment.content); - let recipient_ids = - send_local_notifs(mentions, comment.clone(), person, post, context.pool(), true).await?; + let recipient_ids = send_local_notifs( + mentions, + comment.clone(), + person, + post, + context.pool(), + true, + ) + .await?; // Refetch the view let comment_view = blocking(context.pool(), move |conn| { diff --git a/crates/apub/src/activities/send/comment.rs b/crates/apub/src/activities/send/comment.rs index c11e86b73..867e45e9f 100644 --- a/crates/apub/src/activities/send/comment.rs +++ b/crates/apub/src/activities/send/comment.rs @@ -28,7 +28,7 @@ use anyhow::anyhow; use itertools::Itertools; use lemmy_api_structs::{blocking, WebFingerResponse}; use lemmy_db_queries::{Crud, DbPool}; -use lemmy_db_schema::source::{comment::Comment, community::Community, post::Post, person::Person}; +use lemmy_db_schema::source::{comment::Comment, community::Community, person::Person, post::Post}; use lemmy_utils::{ request::{retry, RecvError}, settings::structs::Settings, @@ -197,7 +197,11 @@ impl ApubObjectType for Comment { Ok(()) } - async fn send_undo_remove(&self, mod_: &Person, context: &LemmyContext) -> Result<(), LemmyError> { + async fn send_undo_remove( + &self, + mod_: &Person, + context: &LemmyContext, + ) -> Result<(), LemmyError> { let post_id = self.post_id; let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; @@ -389,7 +393,10 @@ async fn collect_non_local_mentions( /// Returns the apub ID of the person this comment is responding to. Meaning, in case this is a /// top-level comment, the creator of the post, otherwise the creator of the parent comment. -async fn get_comment_parent_creator(pool: &DbPool, comment: &Comment) -> Result { +async fn get_comment_parent_creator( + pool: &DbPool, + comment: &Comment, +) -> Result { let parent_creator_id = if let Some(parent_comment_id) = comment.parent_id { let parent_comment = blocking(pool, move |conn| Comment::read(conn, parent_comment_id)).await??; diff --git a/crates/apub/src/activities/send/mod.rs b/crates/apub/src/activities/send/mod.rs index 7f19d0426..10dd8a263 100644 --- a/crates/apub/src/activities/send/mod.rs +++ b/crates/apub/src/activities/send/mod.rs @@ -4,9 +4,9 @@ use uuid::Uuid; pub(crate) mod comment; pub(crate) mod community; +pub(crate) mod person; pub(crate) mod post; pub(crate) mod private_message; -pub(crate) mod person; /// Generate a unique ID for an activity, in the format: /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36` diff --git a/crates/apub/src/activities/send/post.rs b/crates/apub/src/activities/send/post.rs index 0fe3f6344..4d3bb9d1b 100644 --- a/crates/apub/src/activities/send/post.rs +++ b/crates/apub/src/activities/send/post.rs @@ -23,7 +23,7 @@ use activitystreams::{ }; use lemmy_api_structs::blocking; use lemmy_db_queries::Crud; -use lemmy_db_schema::source::{community::Community, post::Post, person::Person}; +use lemmy_db_schema::source::{community::Community, person::Person, post::Post}; use lemmy_utils::LemmyError; use lemmy_websocket::LemmyContext; @@ -155,7 +155,11 @@ impl ApubObjectType for Post { Ok(()) } - async fn send_undo_remove(&self, mod_: &Person, context: &LemmyContext) -> Result<(), LemmyError> { + async fn send_undo_remove( + &self, + mod_: &Person, + context: &LemmyContext, + ) -> Result<(), LemmyError> { let community_id = self.community_id; let community = blocking(context.pool(), move |conn| { Community::read(conn, community_id) diff --git a/crates/apub/src/activities/send/private_message.rs b/crates/apub/src/activities/send/private_message.rs index cf0046fa4..92d818ab9 100644 --- a/crates/apub/src/activities/send/private_message.rs +++ b/crates/apub/src/activities/send/private_message.rs @@ -18,7 +18,7 @@ use activitystreams::{ }; use lemmy_api_structs::blocking; use lemmy_db_queries::Crud; -use lemmy_db_schema::source::{private_message::PrivateMessage, person::Person}; +use lemmy_db_schema::source::{person::Person, private_message::PrivateMessage}; use lemmy_utils::LemmyError; use lemmy_websocket::LemmyContext; @@ -29,7 +29,8 @@ impl ApubObjectType for PrivateMessage { let note = self.to_apub(context.pool()).await?; let recipient_id = self.recipient_id; - let recipient = blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??; + let recipient = + blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??; let mut create = Create::new( creator.actor_id.to_owned().into_inner(), @@ -50,7 +51,8 @@ impl ApubObjectType for PrivateMessage { let note = self.to_apub(context.pool()).await?; let recipient_id = self.recipient_id; - let recipient = blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??; + let recipient = + blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??; let mut update = Update::new( creator.actor_id.to_owned().into_inner(), @@ -67,7 +69,8 @@ impl ApubObjectType for PrivateMessage { async fn send_delete(&self, creator: &Person, context: &LemmyContext) -> Result<(), LemmyError> { let recipient_id = self.recipient_id; - let recipient = blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??; + let recipient = + blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??; let mut delete = Delete::new( creator.actor_id.to_owned().into_inner(), @@ -88,7 +91,8 @@ impl ApubObjectType for PrivateMessage { context: &LemmyContext, ) -> Result<(), LemmyError> { let recipient_id = self.recipient_id; - let recipient = blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??; + let recipient = + blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??; let mut delete = Delete::new( creator.actor_id.to_owned().into_inner(), diff --git a/crates/apub/src/fetcher/mod.rs b/crates/apub/src/fetcher/mod.rs index 2c1b6b9af..234a929b9 100644 --- a/crates/apub/src/fetcher/mod.rs +++ b/crates/apub/src/fetcher/mod.rs @@ -1,8 +1,8 @@ pub(crate) mod community; mod fetch; pub(crate) mod objects; -pub mod search; pub(crate) mod person; +pub mod search; use crate::{ fetcher::{ diff --git a/crates/apub/src/fetcher/person.rs b/crates/apub/src/fetcher/person.rs index 120ff8453..792e63707 100644 --- a/crates/apub/src/fetcher/person.rs +++ b/crates/apub/src/fetcher/person.rs @@ -46,7 +46,8 @@ pub(crate) async fn get_or_fetch_and_upsert_person( return Ok(u); } - let person = Person::from_apub(&person?, context, apub_id.to_owned(), recursion_counter).await?; + let person = + Person::from_apub(&person?, context, apub_id.to_owned(), recursion_counter).await?; let person_id = person.id; blocking(context.pool(), move |conn| { @@ -62,7 +63,8 @@ pub(crate) async fn get_or_fetch_and_upsert_person( let person = fetch_remote_object::(context.client(), apub_id, recursion_counter).await?; - let person = Person::from_apub(&person, context, apub_id.to_owned(), recursion_counter).await?; + let person = + Person::from_apub(&person, context, apub_id.to_owned(), recursion_counter).await?; Ok(person) } diff --git a/crates/apub/src/fetcher/search.rs b/crates/apub/src/fetcher/search.rs index 0b2921c7b..36482eed9 100644 --- a/crates/apub/src/fetcher/search.rs +++ b/crates/apub/src/fetcher/search.rs @@ -20,18 +20,18 @@ use lemmy_db_queries::{ source::{ comment::Comment_, community::Community_, + person::Person_, post::Post_, private_message::PrivateMessage_, - person::Person_, }, SearchType, }; use lemmy_db_schema::source::{ comment::Comment, community::Community, + person::Person, post::Post, private_message::PrivateMessage, - person::Person, }; use lemmy_db_views::{comment_view::CommentView, post_view::PostView}; use lemmy_db_views_actor::{community_view::CommunityView, person_view::PersonViewSafe}; diff --git a/crates/apub/src/http/mod.rs b/crates/apub/src/http/mod.rs index 5a1add8d7..77cd5e797 100644 --- a/crates/apub/src/http/mod.rs +++ b/crates/apub/src/http/mod.rs @@ -11,8 +11,8 @@ use url::Url; pub mod comment; pub mod community; -pub mod post; pub mod person; +pub mod post; /// Convert the data to json and turn it into an HTTP Response with the correct ActivityPub /// headers. diff --git a/crates/apub/src/inbox/community_inbox.rs b/crates/apub/src/inbox/community_inbox.rs index f82b1b55f..cb697184c 100644 --- a/crates/apub/src/inbox/community_inbox.rs +++ b/crates/apub/src/inbox/community_inbox.rs @@ -268,7 +268,8 @@ pub(crate) async fn check_community_or_site_ban( return Err(anyhow!("Person is banned from site").into()); } let person_id = person.id; - let is_banned = move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok(); + let is_banned = + move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok(); if blocking(pool, is_banned).await? { return Err(anyhow!("Person is banned from community").into()); } diff --git a/crates/apub/src/inbox/mod.rs b/crates/apub/src/inbox/mod.rs index 71d1c1338..5a3b9d3d5 100644 --- a/crates/apub/src/inbox/mod.rs +++ b/crates/apub/src/inbox/mod.rs @@ -26,9 +26,9 @@ use std::fmt::Debug; use url::Url; pub mod community_inbox; +pub mod person_inbox; mod receive_for_community; pub mod shared_inbox; -pub mod person_inbox; pub(crate) fn get_activity_id(activity: &T, creator_uri: &Url) -> Result where diff --git a/crates/apub/src/inbox/person_inbox.rs b/crates/apub/src/inbox/person_inbox.rs index c83c5037b..14d76f0c8 100644 --- a/crates/apub/src/inbox/person_inbox.rs +++ b/crates/apub/src/inbox/person_inbox.rs @@ -52,8 +52,8 @@ use lemmy_api_structs::blocking; use lemmy_db_queries::{source::person::Person_, ApubObject, Followable}; use lemmy_db_schema::source::{ community::{Community, CommunityFollower}, - private_message::PrivateMessage, person::Person, + private_message::PrivateMessage, }; use lemmy_utils::{location_info, LemmyError}; use lemmy_websocket::LemmyContext; diff --git a/crates/apub/src/lib.rs b/crates/apub/src/lib.rs index 2def37d91..38b039ca9 100644 --- a/crates/apub/src/lib.rs +++ b/crates/apub/src/lib.rs @@ -31,9 +31,9 @@ use lemmy_db_schema::{ activity::Activity, comment::Comment, community::Community, + person::Person as DbPerson, post::Post, private_message::PrivateMessage, - person::Person as DbPerson, }, DbUrl, }; @@ -121,24 +121,38 @@ fn check_is_apub_id_valid(apub_id: &Url) -> Result<(), LemmyError> { /// and actors in Lemmy. #[async_trait::async_trait(?Send)] pub trait ApubObjectType { - async fn send_create(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>; - async fn send_update(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>; - async fn send_delete(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>; + async fn send_create(&self, creator: &DbPerson, context: &LemmyContext) + -> Result<(), LemmyError>; + async fn send_update(&self, creator: &DbPerson, context: &LemmyContext) + -> Result<(), LemmyError>; + async fn send_delete(&self, creator: &DbPerson, context: &LemmyContext) + -> Result<(), LemmyError>; async fn send_undo_delete( &self, creator: &DbPerson, context: &LemmyContext, ) -> Result<(), LemmyError>; async fn send_remove(&self, mod_: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>; - async fn send_undo_remove(&self, mod_: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>; + async fn send_undo_remove( + &self, + mod_: &DbPerson, + context: &LemmyContext, + ) -> Result<(), LemmyError>; } #[async_trait::async_trait(?Send)] pub trait ApubLikeableType { async fn send_like(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>; - async fn send_dislike(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>; - async fn send_undo_like(&self, creator: &DbPerson, context: &LemmyContext) - -> Result<(), LemmyError>; + async fn send_dislike( + &self, + creator: &DbPerson, + context: &LemmyContext, + ) -> Result<(), LemmyError>; + async fn send_undo_like( + &self, + creator: &DbPerson, + context: &LemmyContext, + ) -> Result<(), LemmyError>; } /// Common methods provided by ActivityPub actors (community and person). Not all methods are @@ -316,11 +330,11 @@ pub(crate) async fn find_post_or_comment_by_id( } pub(crate) enum Object { - Comment(Comment), - Post(Post), - Community(Community), - Person(DbPerson), - PrivateMessage(PrivateMessage), + Comment(Box), + Post(Box), + Community(Box), + Person(Box), + PrivateMessage(Box), } pub(crate) async fn find_object_by_id( @@ -330,8 +344,8 @@ pub(crate) async fn find_object_by_id( let ap_id = apub_id.clone(); if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await { return Ok(match pc { - PostOrComment::Post(p) => Object::Post(*p), - PostOrComment::Comment(c) => Object::Comment(*c), + PostOrComment::Post(p) => Object::Post(Box::new(*p)), + PostOrComment::Comment(c) => Object::Comment(Box::new(*c)), }); } @@ -341,7 +355,7 @@ pub(crate) async fn find_object_by_id( }) .await?; if let Ok(u) = person { - return Ok(Object::Person(u)); + return Ok(Object::Person(Box::new(u))); } let ap_id = apub_id.clone(); @@ -350,7 +364,7 @@ pub(crate) async fn find_object_by_id( }) .await?; if let Ok(c) = community { - return Ok(Object::Community(c)); + return Ok(Object::Community(Box::new(c))); } let private_message = blocking(context.pool(), move |conn| { @@ -358,7 +372,7 @@ pub(crate) async fn find_object_by_id( }) .await?; if let Ok(pm) = private_message { - return Ok(Object::PrivateMessage(pm)); + return Ok(Object::PrivateMessage(Box::new(pm))); } Err(NotFound.into()) diff --git a/crates/apub/src/objects/comment.rs b/crates/apub/src/objects/comment.rs index ae5537e3f..0d9aab16e 100644 --- a/crates/apub/src/objects/comment.rs +++ b/crates/apub/src/objects/comment.rs @@ -25,8 +25,8 @@ use lemmy_api_structs::blocking; use lemmy_db_queries::{Crud, DbPool}; use lemmy_db_schema::source::{ comment::{Comment, CommentForm}, - post::Post, person::Person, + post::Post, }; use lemmy_utils::{ location_info, @@ -135,7 +135,8 @@ impl FromApubToForm for CommentForm { .as_single_xsd_any_uri() .context(location_info!())?; - let creator = get_or_fetch_and_upsert_person(creator_actor_id, context, request_counter).await?; + let creator = + get_or_fetch_and_upsert_person(creator_actor_id, context, request_counter).await?; let mut in_reply_tos = note .in_reply_to() diff --git a/crates/apub/src/objects/mod.rs b/crates/apub/src/objects/mod.rs index 235d5223c..b21a3a21d 100644 --- a/crates/apub/src/objects/mod.rs +++ b/crates/apub/src/objects/mod.rs @@ -26,9 +26,9 @@ use url::Url; pub(crate) mod comment; pub(crate) mod community; +pub(crate) mod person; pub(crate) mod post; pub(crate) mod private_message; -pub(crate) mod person; /// Trait for converting an object or actor into the respective ActivityPub type. #[async_trait::async_trait(?Send)] diff --git a/crates/apub/src/objects/person.rs b/crates/apub/src/objects/person.rs index a632fcdb0..de45aedd3 100644 --- a/crates/apub/src/objects/person.rs +++ b/crates/apub/src/objects/person.rs @@ -22,7 +22,7 @@ use lemmy_api_structs::blocking; use lemmy_db_queries::{ApubObject, DbPool}; use lemmy_db_schema::{ naive_now, - source::person::{PersonForm, Person as DbPerson}, + source::person::{Person as DbPerson, PersonForm}, }; use lemmy_utils::{ location_info, @@ -105,7 +105,10 @@ impl FromApub for DbPerson { } else { let person_form = PersonForm::from_apub(person, context, expected_domain, request_counter).await?; - let person = blocking(context.pool(), move |conn| DbPerson::upsert(conn, &person_form)).await??; + let person = blocking(context.pool(), move |conn| { + DbPerson::upsert(conn, &person_form) + }) + .await??; Ok(person) } } diff --git a/crates/apub/src/objects/post.rs b/crates/apub/src/objects/post.rs index a189c2dee..776946cbd 100644 --- a/crates/apub/src/objects/post.rs +++ b/crates/apub/src/objects/post.rs @@ -28,8 +28,8 @@ use lemmy_db_schema::{ self, source::{ community::Community, - post::{Post, PostForm}, person::Person, + post::{Post, PostForm}, }, }; use lemmy_utils::{ @@ -142,7 +142,8 @@ impl FromApubToForm for PostForm { .as_single_xsd_any_uri() .context(location_info!())?; - let creator = get_or_fetch_and_upsert_person(creator_actor_id, context, request_counter).await?; + let creator = + get_or_fetch_and_upsert_person(creator_actor_id, context, request_counter).await?; let community = get_to_community(page, context, request_counter).await?; diff --git a/crates/apub/src/objects/private_message.rs b/crates/apub/src/objects/private_message.rs index 09b49dd08..d8c0077cf 100644 --- a/crates/apub/src/objects/private_message.rs +++ b/crates/apub/src/objects/private_message.rs @@ -22,8 +22,8 @@ use anyhow::Context; use lemmy_api_structs::blocking; use lemmy_db_queries::{Crud, DbPool}; use lemmy_db_schema::source::{ - private_message::{PrivateMessage, PrivateMessageForm}, person::Person, + private_message::{PrivateMessage, PrivateMessageForm}, }; use lemmy_utils::{location_info, utils::convert_datetime, LemmyError}; use lemmy_websocket::LemmyContext; @@ -97,7 +97,8 @@ impl FromApubToForm for PrivateMessageForm { .single_xsd_any_uri() .context(location_info!())?; - let creator = get_or_fetch_and_upsert_person(&creator_actor_id, context, request_counter).await?; + let creator = + get_or_fetch_and_upsert_person(&creator_actor_id, context, request_counter).await?; let recipient_actor_id = note .to() .context(location_info!())? diff --git a/crates/apub/src/routes.rs b/crates/apub/src/routes.rs index 6cc887785..37fdd66f0 100644 --- a/crates/apub/src/routes.rs +++ b/crates/apub/src/routes.rs @@ -8,10 +8,14 @@ use crate::{ get_apub_community_outbox, }, get_activity, - post::get_apub_post, person::{get_apub_person_http, get_apub_person_inbox, get_apub_person_outbox}, + post::get_apub_post, + }, + inbox::{ + community_inbox::community_inbox, + person_inbox::person_inbox, + shared_inbox::shared_inbox, }, - inbox::{community_inbox::community_inbox, shared_inbox::shared_inbox, person_inbox::person_inbox}, APUB_JSON_CONTENT_TYPE, }; use actix_web::*; @@ -54,7 +58,10 @@ pub fn config(cfg: &mut web::ServiceConfig) { web::get().to(get_apub_community_inbox), ) .route("/u/{user_name}", web::get().to(get_apub_person_http)) - .route("/u/{user_name}/outbox", web::get().to(get_apub_person_outbox)) + .route( + "/u/{user_name}/outbox", + web::get().to(get_apub_person_outbox), + ) .route("/u/{user_name}/inbox", web::get().to(get_apub_person_inbox)) .route("/post/{post_id}", web::get().to(get_apub_post)) .route("/comment/{comment_id}", web::get().to(get_apub_comment)) diff --git a/crates/db_queries/src/aggregates/comment_aggregates.rs b/crates/db_queries/src/aggregates/comment_aggregates.rs index 5d4fe5dc2..72bdd0242 100644 --- a/crates/db_queries/src/aggregates/comment_aggregates.rs +++ b/crates/db_queries/src/aggregates/comment_aggregates.rs @@ -32,8 +32,8 @@ mod tests { use lemmy_db_schema::source::{ comment::{Comment, CommentForm, CommentLike, CommentLikeForm}, community::{Community, CommunityForm}, + person::{Person, PersonForm}, post::{Post, PostForm}, - person::{PersonForm, Person}, }; use serial_test::serial; diff --git a/crates/db_queries/src/aggregates/community_aggregates.rs b/crates/db_queries/src/aggregates/community_aggregates.rs index 23fbe8bd6..4bf524596 100644 --- a/crates/db_queries/src/aggregates/community_aggregates.rs +++ b/crates/db_queries/src/aggregates/community_aggregates.rs @@ -36,8 +36,8 @@ mod tests { use lemmy_db_schema::source::{ comment::{Comment, CommentForm}, community::{Community, CommunityFollower, CommunityFollowerForm, CommunityForm}, + person::{Person, PersonForm}, post::{Post, PostForm}, - person::{PersonForm, Person}, }; use serial_test::serial; diff --git a/crates/db_queries/src/aggregates/mod.rs b/crates/db_queries/src/aggregates/mod.rs index 23854dfda..ad20f8a66 100644 --- a/crates/db_queries/src/aggregates/mod.rs +++ b/crates/db_queries/src/aggregates/mod.rs @@ -1,5 +1,5 @@ pub mod comment_aggregates; pub mod community_aggregates; +pub mod person_aggregates; pub mod post_aggregates; pub mod site_aggregates; -pub mod person_aggregates; diff --git a/crates/db_queries/src/aggregates/person_aggregates.rs b/crates/db_queries/src/aggregates/person_aggregates.rs index cebf70b02..473dac32c 100644 --- a/crates/db_queries/src/aggregates/person_aggregates.rs +++ b/crates/db_queries/src/aggregates/person_aggregates.rs @@ -32,8 +32,8 @@ mod tests { use lemmy_db_schema::source::{ comment::{Comment, CommentForm, CommentLike, CommentLikeForm}, community::{Community, CommunityForm}, + person::{Person, PersonForm}, post::{Post, PostForm, PostLike, PostLikeForm}, - person::{PersonForm, Person}, }; use serial_test::serial; @@ -189,7 +189,8 @@ mod tests { let _inserted_child_comment_like = CommentLike::like(&conn, &child_comment_like).unwrap(); - let person_aggregates_before_delete = PersonAggregates::read(&conn, inserted_person.id).unwrap(); + let person_aggregates_before_delete = + PersonAggregates::read(&conn, inserted_person.id).unwrap(); assert_eq!(1, person_aggregates_before_delete.post_count); assert_eq!(1, person_aggregates_before_delete.post_score); diff --git a/crates/db_queries/src/aggregates/post_aggregates.rs b/crates/db_queries/src/aggregates/post_aggregates.rs index be4e8dc72..a88918ae1 100644 --- a/crates/db_queries/src/aggregates/post_aggregates.rs +++ b/crates/db_queries/src/aggregates/post_aggregates.rs @@ -36,8 +36,8 @@ mod tests { use lemmy_db_schema::source::{ comment::{Comment, CommentForm}, community::{Community, CommunityForm}, + person::{Person, PersonForm}, post::{Post, PostForm, PostLike, PostLikeForm}, - person::{PersonForm, Person}, }; use serial_test::serial; diff --git a/crates/db_queries/src/aggregates/site_aggregates.rs b/crates/db_queries/src/aggregates/site_aggregates.rs index fe25c969d..a685ad0da 100644 --- a/crates/db_queries/src/aggregates/site_aggregates.rs +++ b/crates/db_queries/src/aggregates/site_aggregates.rs @@ -25,17 +25,13 @@ impl SiteAggregates { #[cfg(test)] mod tests { - use crate::{ - aggregates::site_aggregates::SiteAggregates, - establish_unpooled_connection, - Crud, - }; + use crate::{aggregates::site_aggregates::SiteAggregates, establish_unpooled_connection, Crud}; use lemmy_db_schema::source::{ comment::{Comment, CommentForm}, community::{Community, CommunityForm}, + person::{Person, PersonForm}, post::{Post, PostForm}, site::{Site, SiteForm}, - person::{PersonForm, Person}, }; use serial_test::serial; diff --git a/crates/db_queries/src/source/activity.rs b/crates/db_queries/src/source/activity.rs index 06b9bd875..bd1bf451f 100644 --- a/crates/db_queries/src/source/activity.rs +++ b/crates/db_queries/src/source/activity.rs @@ -122,13 +122,10 @@ impl Activity_ for Activity { #[cfg(test)] mod tests { use super::*; - use crate::{ - establish_unpooled_connection, - source::activity::Activity_, - }; + use crate::{establish_unpooled_connection, source::activity::Activity_}; use lemmy_db_schema::source::{ activity::{Activity, ActivityForm}, - person::{PersonForm, Person}, + person::{Person, PersonForm}, }; use serde_json::Value; use serial_test::serial; diff --git a/crates/db_queries/src/source/comment.rs b/crates/db_queries/src/source/comment.rs index e4feef80c..674888984 100644 --- a/crates/db_queries/src/source/comment.rs +++ b/crates/db_queries/src/source/comment.rs @@ -209,8 +209,8 @@ mod tests { use lemmy_db_schema::source::{ comment::*, community::{Community, CommunityForm}, + person::{Person, PersonForm}, post::*, - person::{PersonForm, Person}, }; use serial_test::serial; diff --git a/crates/db_queries/src/source/community.rs b/crates/db_queries/src/source/community.rs index 9a6a0560f..2981f2309 100644 --- a/crates/db_queries/src/source/community.rs +++ b/crates/db_queries/src/source/community.rs @@ -295,7 +295,11 @@ impl Followable for CommunityFollower { .set(community_follower_form) .get_result::(conn) } - fn follow_accepted(conn: &PgConnection, community_id_: i32, person_id_: i32) -> Result + fn follow_accepted( + conn: &PgConnection, + community_id_: i32, + person_id_: i32, + ) -> Result where Self: Sized, { @@ -333,13 +337,7 @@ impl Followable for CommunityFollower { #[cfg(test)] mod tests { - use crate::{ - establish_unpooled_connection, - Bannable, - Crud, - Followable, - Joinable, - }; + use crate::{establish_unpooled_connection, Bannable, Crud, Followable, Joinable}; use lemmy_db_schema::source::{community::*, person::*}; use serial_test::serial; @@ -438,7 +436,8 @@ mod tests { person_id: inserted_person.id, }; - let inserted_community_moderator = CommunityModerator::join(&conn, &community_moderator_form).unwrap(); + let inserted_community_moderator = + CommunityModerator::join(&conn, &community_moderator_form).unwrap(); let expected_community_moderator = CommunityModerator { id: inserted_community_moderator.id, diff --git a/crates/db_queries/src/source/local_user.rs b/crates/db_queries/src/source/local_user.rs index 644c3eacb..58579f962 100644 --- a/crates/db_queries/src/source/local_user.rs +++ b/crates/db_queries/src/source/local_user.rs @@ -1,30 +1,21 @@ -use crate::{is_email_regex, Crud, ToSafeSettings}; -use diesel::{dsl::*, result::Error, *}; -use lemmy_db_schema::source::local_user::LocalUserSettings; -use lemmy_db_schema::schema::local_user::dsl::*; -use lemmy_db_schema::source::local_user::{LocalUser, LocalUserForm}; +use crate::{Crud, ToSafeSettings}; use bcrypt::{hash, DEFAULT_COST}; +use diesel::{dsl::*, result::Error, *}; +use lemmy_db_schema::{ + schema::local_user::dsl::*, + source::local_user::{LocalUser, LocalUserForm, LocalUserSettings}, +}; mod safe_type { use crate::ToSafe; use lemmy_db_schema::{schema::local_user::columns::*, source::local_user::LocalUser}; - type Columns = ( - id, - person_id, - admin, - matrix_user_id, - ); + type Columns = (id, person_id, admin, matrix_user_id); impl ToSafe for LocalUser { type SafeColumns = Columns; fn safe_columns_tuple() -> Self::SafeColumns { - ( - id, - person_id, - admin, - matrix_user_id, - ) + (id, person_id, admin, matrix_user_id) } } } @@ -50,7 +41,7 @@ mod safe_settings_type { impl ToSafeSettings for LocalUser { type SafeSettingsColumns = Columns; - + /// Includes everything but the hashed password fn safe_settings_columns_tuple() -> Self::SafeSettingsColumns { ( @@ -73,10 +64,12 @@ mod safe_settings_type { pub trait LocalUser_ { fn register(conn: &PgConnection, form: &LocalUserForm) -> Result; - fn update_password(conn: &PgConnection, person_id: i32, new_password: &str) - -> Result; + fn update_password( + conn: &PgConnection, + local_user_id: i32, + new_password: &str, + ) -> Result; fn add_admin(conn: &PgConnection, local_user_id: i32, added: bool) -> Result; - fn find_by_email(conn: &PgConnection, from_email: &str) -> Result; fn find_by_person(conn: &PgConnection, from_person_id: i32) -> Result; } @@ -91,13 +84,15 @@ impl LocalUser_ for LocalUser { } // TODO do more individual updates like these - fn update_password(conn: &PgConnection, local_user_id: i32, new_password: &str) -> Result { + fn update_password( + conn: &PgConnection, + local_user_id: i32, + new_password: &str, + ) -> Result { let password_hash = hash(new_password, DEFAULT_COST).expect("Couldn't hash password"); diesel::update(local_user.find(local_user_id)) - .set(( - password_encrypted.eq(password_hash), - )) + .set((password_encrypted.eq(password_hash),)) .get_result::(conn) } @@ -108,33 +103,25 @@ impl LocalUser_ for LocalUser { .get_result::(conn) } - // TODO is this used? - fn find_by_email(conn: &PgConnection, from_email: &str) -> Result { - local_user - .filter(email.eq(from_email)) - .first::(conn) - } - // TODO is this used? fn find_by_person(conn: &PgConnection, for_person_id: i32) -> Result { local_user .filter(person_id.eq(for_person_id)) .first::(conn) } - } impl Crud for LocalUser { fn read(conn: &PgConnection, local_user_id: i32) -> Result { - local_user - .find(local_user_id) - .first::(conn) + local_user.find(local_user_id).first::(conn) } fn delete(conn: &PgConnection, local_user_id: i32) -> Result { diesel::delete(local_user.find(local_user_id)).execute(conn) } fn create(conn: &PgConnection, form: &LocalUserForm) -> Result { - insert_into(local_user).values(form).get_result::(conn) + insert_into(local_user) + .values(form) + .get_result::(conn) } fn update(conn: &PgConnection, local_user_id: i32, form: &LocalUserForm) -> Result { diesel::update(local_user.find(local_user_id)) diff --git a/crates/db_queries/src/source/mod.rs b/crates/db_queries/src/source/mod.rs index 4882ddf4b..db928bd4f 100644 --- a/crates/db_queries/src/source/mod.rs +++ b/crates/db_queries/src/source/mod.rs @@ -2,12 +2,12 @@ pub mod activity; pub mod comment; pub mod comment_report; pub mod community; +pub mod local_user; pub mod moderator; pub mod password_reset_request; +pub mod person; +pub mod person_mention; pub mod post; pub mod post_report; pub mod private_message; pub mod site; -pub mod person; -pub mod person_mention; -pub mod local_user; diff --git a/crates/db_queries/src/source/moderator.rs b/crates/db_queries/src/source/moderator.rs index 4477b55e4..0a3fd7ef4 100644 --- a/crates/db_queries/src/source/moderator.rs +++ b/crates/db_queries/src/source/moderator.rs @@ -198,7 +198,7 @@ impl Crud for ModAdd { #[cfg(test)] mod tests { use crate::{establish_unpooled_connection, Crud}; - use lemmy_db_schema::source::{comment::*, community::*, moderator::*, post::*, person::*}; + use lemmy_db_schema::source::{comment::*, community::*, moderator::*, person::*, post::*}; use serial_test::serial; // use Crud; diff --git a/crates/db_queries/src/source/person.rs b/crates/db_queries/src/source/person.rs index 86b04925d..1e6622aea 100644 --- a/crates/db_queries/src/source/person.rs +++ b/crates/db_queries/src/source/person.rs @@ -1,32 +1,31 @@ -use crate::{is_email_regex, ApubObject, Crud}; +use crate::{ApubObject, Crud}; use diesel::{dsl::*, result::Error, *}; use lemmy_db_schema::{ naive_now, schema::person::dsl::*, - source::person::{PersonForm, Person}, + source::person::{Person, PersonForm}, DbUrl, }; -use lemmy_utils::settings::structs::Settings; mod safe_type { use crate::ToSafe; use lemmy_db_schema::{schema::person::columns::*, source::person::Person}; type Columns = ( - id, - name, - preferred_username, - avatar, - banned, - published, - updated, - actor_id, - bio, - local, - banner, - deleted, - inbox_url, - shared_inbox_url, + id, + name, + preferred_username, + avatar, + banned, + published, + updated, + actor_id, + bio, + local, + banner, + deleted, + inbox_url, + shared_inbox_url, ); impl ToSafe for Person { @@ -57,20 +56,20 @@ mod safe_type_alias_1 { use lemmy_db_schema::{schema::person_alias_1::columns::*, source::person::PersonAlias1}; type Columns = ( - id, - name, - preferred_username, - avatar, - banned, - published, - updated, - actor_id, - bio, - local, - banner, - deleted, - inbox_url, - shared_inbox_url, + id, + name, + preferred_username, + avatar, + banned, + published, + updated, + actor_id, + bio, + local, + banner, + deleted, + inbox_url, + shared_inbox_url, ); impl ToSafe for PersonAlias1 { @@ -101,20 +100,20 @@ mod safe_type_alias_2 { use lemmy_db_schema::{schema::person_alias_2::columns::*, source::person::PersonAlias2}; type Columns = ( - id, - name, - preferred_username, - avatar, - banned, - published, - updated, - actor_id, - bio, - local, - banner, - deleted, - inbox_url, - shared_inbox_url, + id, + name, + preferred_username, + avatar, + banned, + published, + updated, + actor_id, + bio, + local, + banner, + deleted, + inbox_url, + shared_inbox_url, ); impl ToSafe for PersonAlias2 { @@ -181,36 +180,19 @@ impl ApubObject for Person { pub trait Person_ { fn ban_person(conn: &PgConnection, person_id: i32, ban: bool) -> Result; - // TODO - // fn find_by_email_or_name( - // conn: &PgConnection, - // name_or_email: &str, - // ) -> Result; fn find_by_name(conn: &PgConnection, name: &str) -> Result; fn mark_as_updated(conn: &PgConnection, person_id: i32) -> Result; fn delete_account(conn: &PgConnection, person_id: i32) -> Result; } impl Person_ for Person { - fn ban_person(conn: &PgConnection, person_id: i32, ban: bool) -> Result { diesel::update(person.find(person_id)) .set(banned.eq(ban)) .get_result::(conn) } - // TODO this needs to get moved to aggregates i think - // fn find_by_email_or_name( - // conn: &PgConnection, - // name_or_email: &str, - // ) -> Result { - // if is_email_regex(name_or_email) { - // Self::find_by_email(conn, name_or_email) - // } else { - // Self::find_by_name(conn, name_or_email) - // } - // } - + // TODO is this used? fn find_by_name(conn: &PgConnection, from_name: &str) -> Result { person .filter(deleted.eq(false)) diff --git a/crates/db_queries/src/source/person_mention.rs b/crates/db_queries/src/source/person_mention.rs index ba40c17fe..7a568ba9b 100644 --- a/crates/db_queries/src/source/person_mention.rs +++ b/crates/db_queries/src/source/person_mention.rs @@ -77,9 +77,9 @@ mod tests { use lemmy_db_schema::source::{ comment::*, community::{Community, CommunityForm}, - post::*, person::*, person_mention::*, + post::*, }; use serial_test::serial; diff --git a/crates/db_queries/src/source/private_message.rs b/crates/db_queries/src/source/private_message.rs index c0f74367f..936471f13 100644 --- a/crates/db_queries/src/source/private_message.rs +++ b/crates/db_queries/src/source/private_message.rs @@ -139,12 +139,8 @@ impl PrivateMessage_ for PrivateMessage { #[cfg(test)] mod tests { - use crate::{ - establish_unpooled_connection, - source::private_message::PrivateMessage_, - Crud, - }; - use lemmy_db_schema::source::{private_message::*, person::*}; + use crate::{establish_unpooled_connection, source::private_message::PrivateMessage_, Crud}; + use lemmy_db_schema::source::{person::*, private_message::*}; use serial_test::serial; #[test] diff --git a/crates/db_queries/src/source/user.rs b/crates/db_queries/src/source/user.rs deleted file mode 100644 index 077b3e783..000000000 --- a/crates/db_queries/src/source/user.rs +++ /dev/null @@ -1,459 +0,0 @@ -use crate::{is_email_regex, ApubObject, Crud, ToSafeSettings}; -use bcrypt::{hash, DEFAULT_COST}; -use diesel::{dsl::*, result::Error, *}; -use lemmy_db_schema::{ - naive_now, - schema::user_::dsl::*, - source::user::{UserForm, UserSafeSettings, User_}, - DbUrl, -}; -use lemmy_utils::settings::structs::Settings; - -mod safe_type { - use crate::ToSafe; - use lemmy_db_schema::{schema::user_::columns::*, source::user::User_}; - - type Columns = ( - id, - name, - preferred_username, - avatar, - admin, - banned, - published, - updated, - matrix_user_id, - actor_id, - bio, - local, - banner, - deleted, - inbox_url, - shared_inbox_url, - ); - - impl ToSafe for User_ { - type SafeColumns = Columns; - fn safe_columns_tuple() -> Self::SafeColumns { - ( - id, - name, - preferred_username, - avatar, - admin, - banned, - published, - updated, - matrix_user_id, - actor_id, - bio, - local, - banner, - deleted, - inbox_url, - shared_inbox_url, - ) - } - } -} - -mod safe_type_alias_1 { - use crate::ToSafe; - use lemmy_db_schema::{schema::user_alias_1::columns::*, source::user::UserAlias1}; - - type Columns = ( - id, - name, - preferred_username, - avatar, - admin, - banned, - published, - updated, - matrix_user_id, - actor_id, - bio, - local, - banner, - deleted, - ); - - impl ToSafe for UserAlias1 { - type SafeColumns = Columns; - fn safe_columns_tuple() -> Self::SafeColumns { - ( - id, - name, - preferred_username, - avatar, - admin, - banned, - published, - updated, - matrix_user_id, - actor_id, - bio, - local, - banner, - deleted, - ) - } - } -} - -mod safe_type_alias_2 { - use crate::ToSafe; - use lemmy_db_schema::{schema::user_alias_2::columns::*, source::user::UserAlias2}; - - type Columns = ( - id, - name, - preferred_username, - avatar, - admin, - banned, - published, - updated, - matrix_user_id, - actor_id, - bio, - local, - banner, - deleted, - ); - - impl ToSafe for UserAlias2 { - type SafeColumns = Columns; - fn safe_columns_tuple() -> Self::SafeColumns { - ( - id, - name, - preferred_username, - avatar, - admin, - banned, - published, - updated, - matrix_user_id, - actor_id, - bio, - local, - banner, - deleted, - ) - } - } -} - -mod safe_settings_type { - use crate::ToSafeSettings; - use lemmy_db_schema::{schema::user_::columns::*, source::user::User_}; - - type Columns = ( - id, - name, - preferred_username, - email, - avatar, - admin, - banned, - published, - updated, - show_nsfw, - theme, - default_sort_type, - default_listing_type, - lang, - show_avatars, - send_notifications_to_email, - matrix_user_id, - actor_id, - bio, - local, - last_refreshed_at, - banner, - deleted, - ); - - impl ToSafeSettings for User_ { - type SafeSettingsColumns = Columns; - fn safe_settings_columns_tuple() -> Self::SafeSettingsColumns { - ( - id, - name, - preferred_username, - email, - avatar, - admin, - banned, - published, - updated, - show_nsfw, - theme, - default_sort_type, - default_listing_type, - lang, - show_avatars, - send_notifications_to_email, - matrix_user_id, - actor_id, - bio, - local, - last_refreshed_at, - banner, - deleted, - ) - } - } -} - -pub trait UserSafeSettings_ { - fn read(conn: &PgConnection, user_id: i32) -> Result; -} - -impl UserSafeSettings_ for UserSafeSettings { - fn read(conn: &PgConnection, user_id: i32) -> Result { - user_ - .select(User_::safe_settings_columns_tuple()) - .filter(deleted.eq(false)) - .find(user_id) - .first::(conn) - } -} - -impl Crud for User_ { - fn read(conn: &PgConnection, user_id: i32) -> Result { - user_ - .filter(deleted.eq(false)) - .find(user_id) - .first::(conn) - } - fn delete(conn: &PgConnection, user_id: i32) -> Result { - diesel::delete(user_.find(user_id)).execute(conn) - } - fn create(conn: &PgConnection, form: &UserForm) -> Result { - insert_into(user_).values(form).get_result::(conn) - } - fn update(conn: &PgConnection, user_id: i32, form: &UserForm) -> Result { - diesel::update(user_.find(user_id)) - .set(form) - .get_result::(conn) - } -} - -impl ApubObject for User_ { - fn read_from_apub_id(conn: &PgConnection, object_id: &DbUrl) -> Result { - use lemmy_db_schema::schema::user_::dsl::*; - user_ - .filter(deleted.eq(false)) - .filter(actor_id.eq(object_id)) - .first::(conn) - } - - fn upsert(conn: &PgConnection, user_form: &UserForm) -> Result { - insert_into(user_) - .values(user_form) - .on_conflict(actor_id) - .do_update() - .set(user_form) - .get_result::(conn) - } -} - -pub trait User { - fn register(conn: &PgConnection, form: &UserForm) -> Result; - fn update_password(conn: &PgConnection, user_id: i32, new_password: &str) - -> Result; - fn read_from_name(conn: &PgConnection, from_user_name: &str) -> Result; - fn add_admin(conn: &PgConnection, user_id: i32, added: bool) -> Result; - fn ban_user(conn: &PgConnection, user_id: i32, ban: bool) -> Result; - fn find_by_email_or_username( - conn: &PgConnection, - username_or_email: &str, - ) -> Result; - fn find_by_username(conn: &PgConnection, username: &str) -> Result; - fn get_profile_url(&self, hostname: &str) -> String; - fn mark_as_updated(conn: &PgConnection, user_id: i32) -> Result; - fn delete_account(conn: &PgConnection, user_id: i32) -> Result; -} - -impl User for User_ { - fn register(conn: &PgConnection, form: &UserForm) -> Result { - let mut edited_user = form.clone(); - let password_hash = - hash(&form.password_encrypted, DEFAULT_COST).expect("Couldn't hash password"); - edited_user.password_encrypted = password_hash; - - Self::create(&conn, &edited_user) - } - - // TODO do more individual updates like these - fn update_password(conn: &PgConnection, user_id: i32, new_password: &str) -> Result { - let password_hash = hash(new_password, DEFAULT_COST).expect("Couldn't hash password"); - - diesel::update(user_.find(user_id)) - .set(( - password_encrypted.eq(password_hash), - updated.eq(naive_now()), - )) - .get_result::(conn) - } - - fn read_from_name(conn: &PgConnection, from_user_name: &str) -> Result { - user_ - .filter(local.eq(true)) - .filter(deleted.eq(false)) - .filter(name.eq(from_user_name)) - .first::(conn) - } - - fn add_admin(conn: &PgConnection, user_id: i32, added: bool) -> Result { - diesel::update(user_.find(user_id)) - .set(admin.eq(added)) - .get_result::(conn) - } - - fn ban_user(conn: &PgConnection, user_id: i32, ban: bool) -> Result { - diesel::update(user_.find(user_id)) - .set(banned.eq(ban)) - .get_result::(conn) - } - - fn find_by_email_or_username( - conn: &PgConnection, - username_or_email: &str, - ) -> Result { - if is_email_regex(username_or_email) { - Self::find_by_email(conn, username_or_email) - } else { - Self::find_by_username(conn, username_or_email) - } - } - - fn find_by_username(conn: &PgConnection, username: &str) -> Result { - user_ - .filter(deleted.eq(false)) - .filter(local.eq(true)) - .filter(name.ilike(username)) - .first::(conn) - } - - fn find_by_email(conn: &PgConnection, from_email: &str) -> Result { - user_ - .filter(deleted.eq(false)) - .filter(local.eq(true)) - .filter(email.eq(from_email)) - .first::(conn) - } - - fn get_profile_url(&self, hostname: &str) -> String { - format!( - "{}://{}/u/{}", - Settings::get().get_protocol_string(), - hostname, - self.name - ) - } - - fn mark_as_updated(conn: &PgConnection, user_id: i32) -> Result { - diesel::update(user_.find(user_id)) - .set((last_refreshed_at.eq(naive_now()),)) - .get_result::(conn) - } - - fn delete_account(conn: &PgConnection, user_id: i32) -> Result { - diesel::update(user_.find(user_id)) - .set(( - preferred_username.eq::>(None), - email.eq::>(None), - matrix_user_id.eq::>(None), - bio.eq::>(None), - deleted.eq(true), - updated.eq(naive_now()), - )) - .get_result::(conn) - } -} - -#[cfg(test)] -mod tests { - use crate::{establish_unpooled_connection, source::user::*, ListingType, SortType}; - use serial_test::serial; - - #[test] - #[serial] - fn test_crud() { - let conn = establish_unpooled_connection(); - - let new_user = UserForm { - name: "thommy".into(), - preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, - avatar: None, - banner: None, - admin: false, - banned: Some(false), - published: None, - updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, - actor_id: None, - bio: None, - local: true, - private_key: None, - public_key: None, - last_refreshed_at: None, - inbox_url: None, - shared_inbox_url: None, - }; - - let inserted_user = User_::create(&conn, &new_user).unwrap(); - - let expected_user = User_ { - id: inserted_user.id, - name: "thommy".into(), - preferred_username: None, - password_encrypted: "nope".into(), - email: None, - matrix_user_id: None, - avatar: None, - banner: None, - admin: false, - banned: false, - published: inserted_user.published, - updated: None, - show_nsfw: false, - theme: "browser".into(), - default_sort_type: SortType::Hot as i16, - default_listing_type: ListingType::Subscribed as i16, - lang: "browser".into(), - show_avatars: true, - send_notifications_to_email: false, - actor_id: inserted_user.actor_id.to_owned(), - bio: None, - local: true, - private_key: None, - public_key: None, - last_refreshed_at: inserted_user.published, - deleted: false, - inbox_url: inserted_user.inbox_url.to_owned(), - shared_inbox_url: None, - }; - - let read_user = User_::read(&conn, inserted_user.id).unwrap(); - let updated_user = User_::update(&conn, inserted_user.id, &new_user).unwrap(); - let num_deleted = User_::delete(&conn, inserted_user.id).unwrap(); - - assert_eq!(expected_user, read_user); - assert_eq!(expected_user, inserted_user); - assert_eq!(expected_user, updated_user); - assert_eq!(1, num_deleted); - } -} diff --git a/crates/db_schema/src/source/local_user.rs b/crates/db_schema/src/source/local_user.rs index 68a8bdcfc..692017974 100644 --- a/crates/db_schema/src/source/local_user.rs +++ b/crates/db_schema/src/source/local_user.rs @@ -4,53 +4,53 @@ use serde::Serialize; #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "local_user"] pub struct LocalUser { - pub id: i32, - pub person_id: i32, - pub password_encrypted: String, - pub email: Option, - pub admin: bool, - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, - pub show_avatars: bool, - pub send_notifications_to_email: bool, - pub matrix_user_id: Option, + pub id: i32, + pub person_id: i32, + pub password_encrypted: String, + pub email: Option, + pub admin: bool, + pub show_nsfw: bool, + pub theme: String, + pub default_sort_type: i16, + pub default_listing_type: i16, + pub lang: String, + pub show_avatars: bool, + pub send_notifications_to_email: bool, + pub matrix_user_id: Option, } // TODO redo these, check table defaults #[derive(Insertable, AsChangeset, Clone)] #[table_name = "local_user"] pub struct LocalUserForm { - pub person_id: i32, - pub password_encrypted: String, + pub person_id: i32, + pub password_encrypted: String, pub email: Option>, - pub admin: Option, - pub show_nsfw: Option, - pub theme: Option, - pub default_sort_type: Option, - pub default_listing_type: Option, - pub lang: Option, - pub show_avatars: Option, - pub send_notifications_to_email: Option, + pub admin: Option, + pub show_nsfw: Option, + pub theme: Option, + pub default_sort_type: Option, + pub default_listing_type: Option, + pub lang: Option, + pub show_avatars: Option, + pub send_notifications_to_email: Option, pub matrix_user_id: Option>, } /// A local user view that removes password encrypted #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "local_user"] -pub struct LocalUserSettings{ - pub id: i32, - pub person_id: i32, - pub email: Option, - pub admin: bool, - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, - pub show_avatars: bool, - pub send_notifications_to_email: bool, - pub matrix_user_id: Option, +pub struct LocalUserSettings { + pub id: i32, + pub person_id: i32, + pub email: Option, + pub admin: bool, + pub show_nsfw: bool, + pub theme: String, + pub default_sort_type: i16, + pub default_listing_type: i16, + pub lang: String, + pub show_avatars: bool, + pub send_notifications_to_email: bool, + pub matrix_user_id: Option, } diff --git a/crates/db_schema/src/source/mod.rs b/crates/db_schema/src/source/mod.rs index 4882ddf4b..db928bd4f 100644 --- a/crates/db_schema/src/source/mod.rs +++ b/crates/db_schema/src/source/mod.rs @@ -2,12 +2,12 @@ pub mod activity; pub mod comment; pub mod comment_report; pub mod community; +pub mod local_user; pub mod moderator; pub mod password_reset_request; +pub mod person; +pub mod person_mention; pub mod post; pub mod post_report; pub mod private_message; pub mod site; -pub mod person; -pub mod person_mention; -pub mod local_user; diff --git a/crates/db_schema/src/source/person.rs b/crates/db_schema/src/source/person.rs index 5971d9303..7fc3692f8 100644 --- a/crates/db_schema/src/source/person.rs +++ b/crates/db_schema/src/source/person.rs @@ -7,145 +7,144 @@ use serde::Serialize; #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person"] pub struct Person { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub avatar: Option, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub private_key: Option, - pub public_key: Option, - pub last_refreshed_at: chrono::NaiveDateTime, - pub banner: Option, - pub deleted: bool, - pub inbox_url: DbUrl, - pub shared_inbox_url: Option, + pub id: i32, + pub name: String, + pub preferred_username: Option, + pub avatar: Option, + pub banned: bool, + pub published: chrono::NaiveDateTime, + pub updated: Option, + pub actor_id: DbUrl, + pub bio: Option, + pub local: bool, + pub private_key: Option, + pub public_key: Option, + pub last_refreshed_at: chrono::NaiveDateTime, + pub banner: Option, + pub deleted: bool, + pub inbox_url: DbUrl, + pub shared_inbox_url: Option, } /// A safe representation of user, without the sensitive info #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person"] pub struct PersonSafe { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub avatar: Option, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub banner: Option, - pub deleted: bool, - pub inbox_url: DbUrl, - pub shared_inbox_url: Option, + pub id: i32, + pub name: String, + pub preferred_username: Option, + pub avatar: Option, + pub banned: bool, + pub published: chrono::NaiveDateTime, + pub updated: Option, + pub actor_id: DbUrl, + pub bio: Option, + pub local: bool, + pub banner: Option, + pub deleted: bool, + pub inbox_url: DbUrl, + pub shared_inbox_url: Option, } - #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person_alias_1"] pub struct PersonAlias1 { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub avatar: Option, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub private_key: Option, - pub public_key: Option, - pub last_refreshed_at: chrono::NaiveDateTime, - pub banner: Option, - pub deleted: bool, - pub inbox_url: DbUrl, - pub shared_inbox_url: Option, + pub id: i32, + pub name: String, + pub preferred_username: Option, + pub avatar: Option, + pub banned: bool, + pub published: chrono::NaiveDateTime, + pub updated: Option, + pub actor_id: DbUrl, + pub bio: Option, + pub local: bool, + pub private_key: Option, + pub public_key: Option, + pub last_refreshed_at: chrono::NaiveDateTime, + pub banner: Option, + pub deleted: bool, + pub inbox_url: DbUrl, + pub shared_inbox_url: Option, } #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person_alias_1"] pub struct PersonSafeAlias1 { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub avatar: Option, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub banner: Option, - pub deleted: bool, - pub inbox_url: DbUrl, - pub shared_inbox_url: Option, + pub id: i32, + pub name: String, + pub preferred_username: Option, + pub avatar: Option, + pub banned: bool, + pub published: chrono::NaiveDateTime, + pub updated: Option, + pub actor_id: DbUrl, + pub bio: Option, + pub local: bool, + pub banner: Option, + pub deleted: bool, + pub inbox_url: DbUrl, + pub shared_inbox_url: Option, } #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person_alias_2"] pub struct PersonAlias2 { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub avatar: Option, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub private_key: Option, - pub public_key: Option, - pub last_refreshed_at: chrono::NaiveDateTime, - pub banner: Option, - pub deleted: bool, - pub inbox_url: DbUrl, - pub shared_inbox_url: Option, + pub id: i32, + pub name: String, + pub preferred_username: Option, + pub avatar: Option, + pub banned: bool, + pub published: chrono::NaiveDateTime, + pub updated: Option, + pub actor_id: DbUrl, + pub bio: Option, + pub local: bool, + pub private_key: Option, + pub public_key: Option, + pub last_refreshed_at: chrono::NaiveDateTime, + pub banner: Option, + pub deleted: bool, + pub inbox_url: DbUrl, + pub shared_inbox_url: Option, } #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person_alias_1"] pub struct PersonSafeAlias2 { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub avatar: Option, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub banner: Option, - pub deleted: bool, - pub inbox_url: DbUrl, - pub shared_inbox_url: Option, + pub id: i32, + pub name: String, + pub preferred_username: Option, + pub avatar: Option, + pub banned: bool, + pub published: chrono::NaiveDateTime, + pub updated: Option, + pub actor_id: DbUrl, + pub bio: Option, + pub local: bool, + pub banner: Option, + pub deleted: bool, + pub inbox_url: DbUrl, + pub shared_inbox_url: Option, } #[derive(Insertable, AsChangeset, Clone)] #[table_name = "person"] pub struct PersonForm { - pub name: String, + pub name: String, pub preferred_username: Option>, pub avatar: Option>, - pub banned: Option, + pub banned: Option, pub published: Option, pub updated: Option, - pub actor_id: Option, - pub bio: Option>, - pub local: Option, - pub private_key: Option>, - pub public_key: Option>, + pub actor_id: Option, + pub bio: Option>, + pub local: Option, + pub private_key: Option>, + pub public_key: Option>, pub last_refreshed_at: Option, pub banner: Option>, - pub deleted: Option, - pub inbox_url: Option, + pub deleted: Option, + pub inbox_url: Option, pub shared_inbox_url: Option>, } diff --git a/crates/db_schema/src/source/user.rs b/crates/db_schema/src/source/user.rs deleted file mode 100644 index f04b9a609..000000000 --- a/crates/db_schema/src/source/user.rs +++ /dev/null @@ -1,220 +0,0 @@ -use crate::{ - schema::{user_, user_alias_1, user_alias_2}, - DbUrl, -}; -use serde::Serialize; - -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_"] -pub struct User_ { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub password_encrypted: String, - pub email: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, - pub show_avatars: bool, - pub send_notifications_to_email: bool, - pub matrix_user_id: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub private_key: Option, - pub public_key: Option, - pub last_refreshed_at: chrono::NaiveDateTime, - pub banner: Option, - pub deleted: bool, - pub inbox_url: DbUrl, - pub shared_inbox_url: Option, -} - -/// A safe representation of user, without the sensitive info -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_"] -pub struct UserSafe { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub matrix_user_id: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub banner: Option, - pub deleted: bool, - pub inbox_url: DbUrl, - pub shared_inbox_url: Option, -} - -/// A safe user view with only settings -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_"] -pub struct UserSafeSettings { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub email: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, - pub show_avatars: bool, - pub send_notifications_to_email: bool, - pub matrix_user_id: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub last_refreshed_at: chrono::NaiveDateTime, - pub banner: Option, - pub deleted: bool, -} - -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_alias_1"] -pub struct UserAlias1 { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub password_encrypted: String, - pub email: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, - pub show_avatars: bool, - pub send_notifications_to_email: bool, - pub matrix_user_id: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub private_key: Option, - pub public_key: Option, - pub last_refreshed_at: chrono::NaiveDateTime, - pub banner: Option, - pub deleted: bool, -} - -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_alias_1"] -pub struct UserSafeAlias1 { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub matrix_user_id: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub banner: Option, - pub deleted: bool, -} - -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_alias_2"] -pub struct UserAlias2 { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub password_encrypted: String, - pub email: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, - pub show_avatars: bool, - pub send_notifications_to_email: bool, - pub matrix_user_id: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub private_key: Option, - pub public_key: Option, - pub last_refreshed_at: chrono::NaiveDateTime, - pub banner: Option, - pub deleted: bool, -} - -#[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] -#[table_name = "user_alias_2"] -pub struct UserSafeAlias2 { - pub id: i32, - pub name: String, - pub preferred_username: Option, - pub avatar: Option, - pub admin: bool, - pub banned: bool, - pub published: chrono::NaiveDateTime, - pub updated: Option, - pub matrix_user_id: Option, - pub actor_id: DbUrl, - pub bio: Option, - pub local: bool, - pub banner: Option, - pub deleted: bool, -} - -#[derive(Insertable, AsChangeset, Clone)] -#[table_name = "user_"] -pub struct UserForm { - pub name: String, - pub preferred_username: Option>, - pub password_encrypted: String, - pub admin: bool, - pub banned: Option, - pub email: Option>, - pub avatar: Option>, - pub published: Option, - pub updated: Option, - pub show_nsfw: bool, - pub theme: String, - pub default_sort_type: i16, - pub default_listing_type: i16, - pub lang: String, - pub show_avatars: bool, - pub send_notifications_to_email: bool, - pub matrix_user_id: Option>, - pub actor_id: Option, - pub bio: Option>, - pub local: bool, - pub private_key: Option, - pub public_key: Option, - pub last_refreshed_at: Option, - pub banner: Option>, - pub inbox_url: Option, - pub shared_inbox_url: Option>, -} diff --git a/crates/db_views/src/comment_report_view.rs b/crates/db_views/src/comment_report_view.rs index eb10bffbe..d06d17fbb 100644 --- a/crates/db_views/src/comment_report_view.rs +++ b/crates/db_views/src/comment_report_view.rs @@ -1,13 +1,13 @@ use diesel::{result::Error, *}; use lemmy_db_queries::{limit_and_offset, MaybeOptional, ToSafe, ViewToVec}; use lemmy_db_schema::{ - schema::{comment, comment_report, community, post, person, person_alias_1, person_alias_2}, + schema::{comment, comment_report, community, person, person_alias_1, person_alias_2, post}, source::{ comment::Comment, comment_report::CommentReport, community::{Community, CommunitySafe}, + person::{Person, PersonAlias1, PersonAlias2, PersonSafe, PersonSafeAlias1, PersonSafeAlias2}, post::Post, - person::{PersonAlias1, PersonAlias2, PersonSafe, PersonSafeAlias1, PersonSafeAlias2, Person}, }, }; use serde::Serialize; diff --git a/crates/db_views/src/comment_view.rs b/crates/db_views/src/comment_view.rs index eb95a2ccd..49bad6c03 100644 --- a/crates/db_views/src/comment_view.rs +++ b/crates/db_views/src/comment_view.rs @@ -20,15 +20,15 @@ use lemmy_db_schema::{ community, community_follower, community_person_ban, - post, person, person_alias_1, + post, }, source::{ comment::{Comment, CommentAlias1, CommentSaved}, - community::{Community, CommunityFollower, CommunitySafe, CommunityPersonBan}, + community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe}, + person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, post::Post, - person::{PersonAlias1, PersonSafe, PersonSafeAlias1, Person}, }, }; use serde::Serialize; @@ -440,7 +440,7 @@ mod tests { Crud, Likeable, }; - use lemmy_db_schema::source::{comment::*, community::*, post::*, person::*}; + use lemmy_db_schema::source::{comment::*, community::*, person::*, post::*}; use serial_test::serial; #[test] @@ -646,7 +646,10 @@ mod tests { Community::delete(&conn, inserted_community.id).unwrap(); Person::delete(&conn, inserted_person.id).unwrap(); - assert_eq!(expected_comment_view_no_person, read_comment_views_no_person[0]); + assert_eq!( + expected_comment_view_no_person, + read_comment_views_no_person[0] + ); assert_eq!( expected_comment_view_with_person, read_comment_views_with_person[0] diff --git a/crates/db_views/src/lib.rs b/crates/db_views/src/lib.rs index d37a1d3ed..54435c1e2 100644 --- a/crates/db_views/src/lib.rs +++ b/crates/db_views/src/lib.rs @@ -3,8 +3,8 @@ extern crate serial_test; pub mod comment_report_view; pub mod comment_view; +pub mod local_user_view; pub mod post_report_view; pub mod post_view; pub mod private_message_view; pub mod site_view; -pub mod local_user_view; diff --git a/crates/db_views/src/local_user_view.rs b/crates/db_views/src/local_user_view.rs index 384bf9007..d377af633 100644 --- a/crates/db_views/src/local_user_view.rs +++ b/crates/db_views/src/local_user_view.rs @@ -1,13 +1,11 @@ use diesel::{result::Error, *}; -use lemmy_db_queries::{ - aggregates::person_aggregates::PersonAggregates, - ToSafe, - ToSafeSettings, -}; +use lemmy_db_queries::{aggregates::person_aggregates::PersonAggregates, ToSafe, ToSafeSettings}; use lemmy_db_schema::{ - schema::{person, person_aggregates, local_user}, - source::person::{PersonSafe, Person}, - source::local_user::{LocalUser, LocalUserSettings}, + schema::{local_user, person, person_aggregates}, + source::{ + local_user::{LocalUser, LocalUserSettings}, + person::{Person, PersonSafe}, + }, }; use serde::Serialize; @@ -21,14 +19,22 @@ pub struct LocalUserView { type LocalUserViewTuple = (Person, PersonAggregates, LocalUser); impl LocalUserView { - pub fn read(conn: &PgConnection, person_id: i32) -> Result { + pub fn read_person(conn: &PgConnection, person_id: i32) -> Result { let (person, counts, local_user) = person::table .find(person_id) .inner_join(person_aggregates::table) .inner_join(local_user::table) - .select((person::all_columns, person_aggregates::all_columns, local_user::all_columns)) + .select(( + person::all_columns, + person_aggregates::all_columns, + local_user::all_columns, + )) .first::(conn)?; - Ok(Self { person, counts, local_user }) + Ok(Self { + person, + counts, + local_user, + }) } // TODO check where this is used @@ -37,22 +43,57 @@ impl LocalUserView { .filter(person::name.eq(name)) .inner_join(person_aggregates::table) .inner_join(local_user::table) - .select((person::all_columns, person_aggregates::all_columns, local_user::all_columns)) + .select(( + person::all_columns, + person_aggregates::all_columns, + local_user::all_columns, + )) .first::(conn)?; - Ok(Self { person, counts, local_user }) + Ok(Self { + person, + counts, + local_user, + }) } - pub fn find_by_email_or_name( - conn: &PgConnection, - name_or_email: &str, - ) -> Result { + pub fn find_by_email_or_name(conn: &PgConnection, name_or_email: &str) -> Result { let (person, counts, local_user) = person::table .inner_join(person_aggregates::table) .inner_join(local_user::table) - .filter(person::name.ilike(name_or_email).or(local_user::email.ilike(name_or_email))) - .select((person::all_columns, person_aggregates::all_columns, local_user::all_columns)) + .filter( + person::name + .ilike(name_or_email) + .or(local_user::email.ilike(name_or_email)), + ) + .select(( + person::all_columns, + person_aggregates::all_columns, + local_user::all_columns, + )) .first::(conn)?; - Ok(Self { person, counts, local_user }) + Ok(Self { + person, + counts, + local_user, + }) + } + + pub fn find_by_email(conn: &PgConnection, from_email: &str) -> Result { + let (person, counts, local_user) = person::table + .inner_join(person_aggregates::table) + .inner_join(local_user::table) + .filter(local_user::email.eq(from_email)) + .select(( + person::all_columns, + person_aggregates::all_columns, + local_user::all_columns, + )) + .first::(conn)?; + Ok(Self { + person, + counts, + local_user, + }) } } @@ -71,8 +112,16 @@ impl LocalUserSettingsView { .find(person_id) .inner_join(person_aggregates::table) .inner_join(local_user::table) - .select((Person::safe_columns_tuple(), person_aggregates::all_columns, LocalUser::safe_settings_columns_tuple())) + .select(( + Person::safe_columns_tuple(), + person_aggregates::all_columns, + LocalUser::safe_settings_columns_tuple(), + )) .first::(conn)?; - Ok(Self { person, counts, local_user }) + Ok(Self { + person, + counts, + local_user, + }) } } diff --git a/crates/db_views/src/post_report_view.rs b/crates/db_views/src/post_report_view.rs index 192a3d7b1..e8221c72c 100644 --- a/crates/db_views/src/post_report_view.rs +++ b/crates/db_views/src/post_report_view.rs @@ -1,12 +1,12 @@ use diesel::{result::Error, *}; use lemmy_db_queries::{limit_and_offset, MaybeOptional, ToSafe, ViewToVec}; use lemmy_db_schema::{ - schema::{community, post, post_report, person, person_alias_1, person_alias_2}, + schema::{community, person, person_alias_1, person_alias_2, post, post_report}, source::{ community::{Community, CommunitySafe}, + person::{Person, PersonAlias1, PersonAlias2, PersonSafe, PersonSafeAlias1, PersonSafeAlias2}, post::Post, post_report::PostReport, - person::{PersonAlias1, PersonAlias2, PersonSafe, PersonSafeAlias1, PersonSafeAlias2, Person}, }, }; use serde::Serialize; @@ -41,7 +41,9 @@ impl PostReportView { .inner_join(community::table.on(post::community_id.eq(community::id))) .inner_join(person::table.on(post_report::creator_id.eq(person::id))) .inner_join(person_alias_1::table.on(post::creator_id.eq(person_alias_1::id))) - .left_join(person_alias_2::table.on(post_report::resolver_id.eq(person_alias_2::id.nullable()))) + .left_join( + person_alias_2::table.on(post_report::resolver_id.eq(person_alias_2::id.nullable())), + ) .select(( post_report::all_columns, post::all_columns, @@ -126,7 +128,9 @@ impl<'a> PostReportQueryBuilder<'a> { .inner_join(community::table.on(post::community_id.eq(community::id))) .inner_join(person::table.on(post_report::creator_id.eq(person::id))) .inner_join(person_alias_1::table.on(post::creator_id.eq(person_alias_1::id))) - .left_join(person_alias_2::table.on(post_report::resolver_id.eq(person_alias_2::id.nullable()))) + .left_join( + person_alias_2::table.on(post_report::resolver_id.eq(person_alias_2::id.nullable())), + ) .select(( post_report::all_columns, post::all_columns, diff --git a/crates/db_views/src/post_view.rs b/crates/db_views/src/post_view.rs index 4aca33286..2db35fff4 100644 --- a/crates/db_views/src/post_view.rs +++ b/crates/db_views/src/post_view.rs @@ -15,17 +15,17 @@ use lemmy_db_schema::{ community, community_follower, community_person_ban, + person, post, post_aggregates, post_like, post_read, post_saved, - person, }, source::{ - community::{Community, CommunityFollower, CommunitySafe, CommunityPersonBan}, + community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe}, + person::{Person, PersonSafe}, post::{Post, PostRead, PostSaved}, - person::{PersonSafe, Person}, }, }; use log::debug; @@ -433,7 +433,7 @@ mod tests { ListingType, SortType, }; - use lemmy_db_schema::source::{community::*, post::*, person::*}; + use lemmy_db_schema::source::{community::*, person::*, post::*}; use serial_test::serial; #[test] @@ -638,11 +638,17 @@ mod tests { expected_post_listing_with_user, read_post_listings_with_person[0] ); - assert_eq!(expected_post_listing_with_user, read_post_listing_with_person); + assert_eq!( + expected_post_listing_with_user, + read_post_listing_with_person + ); assert_eq!(1, read_post_listings_with_person.len()); // Without the user - assert_eq!(expected_post_listing_no_person, read_post_listings_no_person[0]); + assert_eq!( + expected_post_listing_no_person, + read_post_listings_no_person[0] + ); assert_eq!(expected_post_listing_no_person, read_post_listing_no_person); assert_eq!(1, read_post_listings_no_person.len()); diff --git a/crates/db_views/src/private_message_view.rs b/crates/db_views/src/private_message_view.rs index 29b1e4644..e4dd3d3f4 100644 --- a/crates/db_views/src/private_message_view.rs +++ b/crates/db_views/src/private_message_view.rs @@ -1,10 +1,10 @@ use diesel::{pg::Pg, result::Error, *}; use lemmy_db_queries::{limit_and_offset, MaybeOptional, ToSafe, ViewToVec}; use lemmy_db_schema::{ - schema::{private_message, person, person_alias_1}, + schema::{person, person_alias_1, private_message}, source::{ + person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, private_message::PrivateMessage, - person::{PersonAlias1, PersonSafe, PersonSafeAlias1, Person}, }, }; use log::debug; diff --git a/crates/db_views/src/site_view.rs b/crates/db_views/src/site_view.rs index 391cf84b1..87fded01b 100644 --- a/crates/db_views/src/site_view.rs +++ b/crates/db_views/src/site_view.rs @@ -1,10 +1,10 @@ use diesel::{result::Error, *}; use lemmy_db_queries::{aggregates::site_aggregates::SiteAggregates, ToSafe}; use lemmy_db_schema::{ - schema::{site, site_aggregates, person}, + schema::{person, site, site_aggregates}, source::{ + person::{Person, PersonSafe}, site::Site, - person::{PersonSafe, Person}, }, }; use serde::Serialize; diff --git a/crates/db_views_actor/src/community_follower_view.rs b/crates/db_views_actor/src/community_follower_view.rs index 6673acb53..337c28cd0 100644 --- a/crates/db_views_actor/src/community_follower_view.rs +++ b/crates/db_views_actor/src/community_follower_view.rs @@ -4,7 +4,7 @@ use lemmy_db_schema::{ schema::{community, community_follower, person}, source::{ community::{Community, CommunitySafe}, - person::{PersonSafe, Person}, + person::{Person, PersonSafe}, }, }; use serde::Serialize; @@ -22,7 +22,10 @@ impl CommunityFollowerView { let res = community_follower::table .inner_join(community::table) .inner_join(person::table) - .select((Community::safe_columns_tuple(), Person::safe_columns_tuple())) + .select(( + Community::safe_columns_tuple(), + Person::safe_columns_tuple(), + )) .filter(community_follower::community_id.eq(community_id)) .order_by(community_follower::published) .load::(conn)?; @@ -34,7 +37,10 @@ impl CommunityFollowerView { let res = community_follower::table .inner_join(community::table) .inner_join(person::table) - .select((Community::safe_columns_tuple(), Person::safe_columns_tuple())) + .select(( + Community::safe_columns_tuple(), + Person::safe_columns_tuple(), + )) .filter(community_follower::person_id.eq(person_id)) .order_by(community_follower::published) .load::(conn)?; diff --git a/crates/db_views_actor/src/community_moderator_view.rs b/crates/db_views_actor/src/community_moderator_view.rs index 7cc208472..bdddf917f 100644 --- a/crates/db_views_actor/src/community_moderator_view.rs +++ b/crates/db_views_actor/src/community_moderator_view.rs @@ -4,7 +4,7 @@ use lemmy_db_schema::{ schema::{community, community_moderator, person}, source::{ community::{Community, CommunitySafe}, - person::{PersonSafe, Person}, + person::{Person, PersonSafe}, }, }; use serde::Serialize; @@ -22,7 +22,10 @@ impl CommunityModeratorView { let res = community_moderator::table .inner_join(community::table) .inner_join(person::table) - .select((Community::safe_columns_tuple(), Person::safe_columns_tuple())) + .select(( + Community::safe_columns_tuple(), + Person::safe_columns_tuple(), + )) .filter(community_moderator::community_id.eq(community_id)) .order_by(community_moderator::published) .load::(conn)?; @@ -34,7 +37,10 @@ impl CommunityModeratorView { let res = community_moderator::table .inner_join(community::table) .inner_join(person::table) - .select((Community::safe_columns_tuple(), Person::safe_columns_tuple())) + .select(( + Community::safe_columns_tuple(), + Person::safe_columns_tuple(), + )) .filter(community_moderator::person_id.eq(person_id)) .order_by(community_moderator::published) .load::(conn)?; diff --git a/crates/db_views_actor/src/community_person_ban_view.rs b/crates/db_views_actor/src/community_person_ban_view.rs index 651fcbf8e..c63d15a0f 100644 --- a/crates/db_views_actor/src/community_person_ban_view.rs +++ b/crates/db_views_actor/src/community_person_ban_view.rs @@ -4,7 +4,7 @@ use lemmy_db_schema::{ schema::{community, community_person_ban, person}, source::{ community::{Community, CommunitySafe}, - person::{PersonSafe, Person}, + person::{Person, PersonSafe}, }, }; use serde::Serialize; @@ -24,7 +24,10 @@ impl CommunityPersonBanView { let (community, person) = community_person_ban::table .inner_join(community::table) .inner_join(person::table) - .select((Community::safe_columns_tuple(), Person::safe_columns_tuple())) + .select(( + Community::safe_columns_tuple(), + Person::safe_columns_tuple(), + )) .filter(community_person_ban::community_id.eq(from_community_id)) .filter(community_person_ban::person_id.eq(from_person_id)) .order_by(community_person_ban::published) diff --git a/crates/db_views_actor/src/community_view.rs b/crates/db_views_actor/src/community_view.rs index 47d0b1e22..2e7f1746d 100644 --- a/crates/db_views_actor/src/community_view.rs +++ b/crates/db_views_actor/src/community_view.rs @@ -15,7 +15,7 @@ use lemmy_db_schema::{ schema::{community, community_aggregates, community_follower, person}, source::{ community::{Community, CommunityFollower, CommunitySafe}, - person::{PersonSafe, Person}, + person::{Person, PersonSafe}, }, }; use serde::Serialize; @@ -78,8 +78,9 @@ impl CommunityView { &mut CommunityModeratorView::for_community(conn, community_id) .map(|v| v.into_iter().map(|m| m.moderator.id).collect())?, ); - mods_and_admins - .append(&mut PersonViewSafe::admins(conn).map(|v| v.into_iter().map(|a| a.person.id).collect())?); + mods_and_admins.append( + &mut PersonViewSafe::admins(conn).map(|v| v.into_iter().map(|a| a.person.id).collect())?, + ); Ok(mods_and_admins) } diff --git a/crates/db_views_actor/src/person_mention_view.rs b/crates/db_views_actor/src/person_mention_view.rs index 5d7ee9833..daa6599b2 100644 --- a/crates/db_views_actor/src/person_mention_view.rs +++ b/crates/db_views_actor/src/person_mention_view.rs @@ -17,17 +17,17 @@ use lemmy_db_schema::{ community, community_follower, community_person_ban, - post, person, person_alias_1, person_mention, + post, }, source::{ comment::{Comment, CommentSaved}, - community::{Community, CommunityFollower, CommunitySafe, CommunityPersonBan}, - post::Post, - person::{PersonAlias1, PersonSafe, PersonSafeAlias1, Person}, + community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe}, + person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, person_mention::PersonMention, + post::Post, }, }; use serde::Serialize; diff --git a/crates/db_views_actor/src/person_view.rs b/crates/db_views_actor/src/person_view.rs index ff936d6de..920e59009 100644 --- a/crates/db_views_actor/src/person_view.rs +++ b/crates/db_views_actor/src/person_view.rs @@ -9,8 +9,8 @@ use lemmy_db_queries::{ ViewToVec, }; use lemmy_db_schema::{ - schema::{person, person_aggregates, local_user}, - source::person::{PersonSafe, Person}, + schema::{local_user, person, person_aggregates}, + source::person::{Person, PersonSafe}, }; use serde::Serialize; diff --git a/crates/db_views_moderator/src/mod_add_community_view.rs b/crates/db_views_moderator/src/mod_add_community_view.rs index 32988c190..8fabe7409 100644 --- a/crates/db_views_moderator/src/mod_add_community_view.rs +++ b/crates/db_views_moderator/src/mod_add_community_view.rs @@ -5,7 +5,7 @@ use lemmy_db_schema::{ source::{ community::{Community, CommunitySafe}, moderator::ModAddCommunity, - person::{PersonAlias1, PersonSafe, PersonSafeAlias1, Person}, + person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, }, }; use serde::Serialize; @@ -31,7 +31,9 @@ impl ModAddCommunityView { let mut query = mod_add_community::table .inner_join(person::table.on(mod_add_community::mod_person_id.eq(person::id))) .inner_join(community::table) - .inner_join(person_alias_1::table.on(mod_add_community::other_person_id.eq(person_alias_1::id))) + .inner_join( + person_alias_1::table.on(mod_add_community::other_person_id.eq(person_alias_1::id)), + ) .select(( mod_add_community::all_columns, Person::safe_columns_tuple(), diff --git a/crates/db_views_moderator/src/mod_add_view.rs b/crates/db_views_moderator/src/mod_add_view.rs index e4a665c5e..a6ce44722 100644 --- a/crates/db_views_moderator/src/mod_add_view.rs +++ b/crates/db_views_moderator/src/mod_add_view.rs @@ -4,7 +4,7 @@ use lemmy_db_schema::{ schema::{mod_add, person, person_alias_1}, source::{ moderator::ModAdd, - person::{PersonAlias1, PersonSafe, PersonSafeAlias1, Person}, + person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, }, }; use serde::Serialize; diff --git a/crates/db_views_moderator/src/mod_ban_from_community_view.rs b/crates/db_views_moderator/src/mod_ban_from_community_view.rs index a60ede61b..2d16edb04 100644 --- a/crates/db_views_moderator/src/mod_ban_from_community_view.rs +++ b/crates/db_views_moderator/src/mod_ban_from_community_view.rs @@ -5,7 +5,7 @@ use lemmy_db_schema::{ source::{ community::{Community, CommunitySafe}, moderator::ModBanFromCommunity, - person::{PersonAlias1, PersonSafe, PersonSafeAlias1, Person}, + person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, }, }; use serde::Serialize; @@ -18,7 +18,12 @@ pub struct ModBanFromCommunityView { pub banned_person: PersonSafeAlias1, } -type ModBanFromCommunityViewTuple = (ModBanFromCommunity, PersonSafe, CommunitySafe, PersonSafeAlias1); +type ModBanFromCommunityViewTuple = ( + ModBanFromCommunity, + PersonSafe, + CommunitySafe, + PersonSafeAlias1, +); impl ModBanFromCommunityView { pub fn list( diff --git a/crates/db_views_moderator/src/mod_ban_view.rs b/crates/db_views_moderator/src/mod_ban_view.rs index 2c55d5149..2a3c1864f 100644 --- a/crates/db_views_moderator/src/mod_ban_view.rs +++ b/crates/db_views_moderator/src/mod_ban_view.rs @@ -4,7 +4,7 @@ use lemmy_db_schema::{ schema::{mod_ban, person, person_alias_1}, source::{ moderator::ModBan, - person::{PersonAlias1, PersonSafe, PersonSafeAlias1, Person}, + person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, }, }; use serde::Serialize; diff --git a/crates/db_views_moderator/src/mod_lock_post_view.rs b/crates/db_views_moderator/src/mod_lock_post_view.rs index 9369ba99b..5f5e7346e 100644 --- a/crates/db_views_moderator/src/mod_lock_post_view.rs +++ b/crates/db_views_moderator/src/mod_lock_post_view.rs @@ -1,12 +1,12 @@ use diesel::{result::Error, *}; use lemmy_db_queries::{limit_and_offset, ToSafe, ViewToVec}; use lemmy_db_schema::{ - schema::{community, mod_lock_post, post, person}, + schema::{community, mod_lock_post, person, post}, source::{ community::{Community, CommunitySafe}, moderator::ModLockPost, + person::{Person, PersonSafe}, post::Post, - person::{PersonSafe, Person}, }, }; use serde::Serialize; diff --git a/crates/db_views_moderator/src/mod_remove_comment_view.rs b/crates/db_views_moderator/src/mod_remove_comment_view.rs index 9633f2009..2e8dfccc0 100644 --- a/crates/db_views_moderator/src/mod_remove_comment_view.rs +++ b/crates/db_views_moderator/src/mod_remove_comment_view.rs @@ -1,13 +1,13 @@ use diesel::{result::Error, *}; use lemmy_db_queries::{limit_and_offset, ToSafe, ViewToVec}; use lemmy_db_schema::{ - schema::{comment, community, mod_remove_comment, post, person, person_alias_1}, + schema::{comment, community, mod_remove_comment, person, person_alias_1, post}, source::{ comment::Comment, community::{Community, CommunitySafe}, moderator::ModRemoveComment, + person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, post::Post, - person::{PersonAlias1, PersonSafe, PersonSafeAlias1, Person}, }, }; use serde::Serialize; diff --git a/crates/db_views_moderator/src/mod_remove_community_view.rs b/crates/db_views_moderator/src/mod_remove_community_view.rs index 6d49acbe5..767bcdc40 100644 --- a/crates/db_views_moderator/src/mod_remove_community_view.rs +++ b/crates/db_views_moderator/src/mod_remove_community_view.rs @@ -5,7 +5,7 @@ use lemmy_db_schema::{ source::{ community::{Community, CommunitySafe}, moderator::ModRemoveCommunity, - person::{PersonSafe, Person}, + person::{Person, PersonSafe}, }, }; use serde::Serialize; diff --git a/crates/db_views_moderator/src/mod_remove_post_view.rs b/crates/db_views_moderator/src/mod_remove_post_view.rs index 8530656cc..7456ff8a6 100644 --- a/crates/db_views_moderator/src/mod_remove_post_view.rs +++ b/crates/db_views_moderator/src/mod_remove_post_view.rs @@ -1,12 +1,12 @@ use diesel::{result::Error, *}; use lemmy_db_queries::{limit_and_offset, ToSafe, ViewToVec}; use lemmy_db_schema::{ - schema::{community, mod_remove_post, post, person}, + schema::{community, mod_remove_post, person, post}, source::{ community::{Community, CommunitySafe}, moderator::ModRemovePost, + person::{Person, PersonSafe}, post::Post, - person::{PersonSafe, Person}, }, }; use serde::Serialize; diff --git a/crates/db_views_moderator/src/mod_sticky_post_view.rs b/crates/db_views_moderator/src/mod_sticky_post_view.rs index 9f4ea4af6..c0629a4e3 100644 --- a/crates/db_views_moderator/src/mod_sticky_post_view.rs +++ b/crates/db_views_moderator/src/mod_sticky_post_view.rs @@ -1,12 +1,12 @@ use diesel::{result::Error, *}; use lemmy_db_queries::{limit_and_offset, ToSafe, ViewToVec}; use lemmy_db_schema::{ - schema::{community, mod_sticky_post, post, person}, + schema::{community, mod_sticky_post, person, post}, source::{ community::{Community, CommunitySafe}, moderator::ModStickyPost, + person::{Person, PersonSafe}, post::Post, - person::{PersonSafe, Person}, }, }; use serde::Serialize; diff --git a/src/code_migrations.rs b/src/code_migrations.rs index 009b7afb6..bd67fe699 100644 --- a/src/code_migrations.rs +++ b/src/code_migrations.rs @@ -19,9 +19,9 @@ use lemmy_db_schema::{ source::{ comment::Comment, community::{Community, CommunityForm}, + person::{Person, PersonForm}, post::Post, private_message::PrivateMessage, - user::{UserForm, User_}, }, }; use lemmy_utils::{apub::generate_actor_keypair, settings::structs::Settings, LemmyError}; @@ -40,52 +40,42 @@ pub fn run_advanced_migrations(conn: &PgConnection) -> Result<(), LemmyError> { } fn user_updates_2020_04_02(conn: &PgConnection) -> Result<(), LemmyError> { - use lemmy_db_schema::schema::user_::dsl::*; + use lemmy_db_schema::schema::person::dsl::*; info!("Running user_updates_2020_04_02"); // Update the actor_id, private_key, and public_key, last_refreshed_at - let incorrect_users = user_ + let incorrect_persons = person .filter(actor_id.like("http://changeme_%")) .filter(local.eq(true)) - .load::(conn)?; + .load::(conn)?; - for cuser in &incorrect_users { + for cperson in &incorrect_persons { let keypair = generate_actor_keypair()?; - let form = UserForm { - name: cuser.name.to_owned(), - email: Some(cuser.email.to_owned()), - matrix_user_id: Some(cuser.matrix_user_id.to_owned()), - avatar: Some(cuser.avatar.to_owned()), - banner: Some(cuser.banner.to_owned()), - password_encrypted: cuser.password_encrypted.to_owned(), - preferred_username: Some(cuser.preferred_username.to_owned()), - published: Some(cuser.published), + let form = PersonForm { + name: cperson.name.to_owned(), + avatar: None, + banner: None, + preferred_username: None, + published: None, updated: None, - admin: cuser.admin, - banned: Some(cuser.banned), - show_nsfw: cuser.show_nsfw, - theme: cuser.theme.to_owned(), - default_sort_type: cuser.default_sort_type, - default_listing_type: cuser.default_listing_type, - lang: cuser.lang.to_owned(), - show_avatars: cuser.show_avatars, - send_notifications_to_email: cuser.send_notifications_to_email, - actor_id: Some(generate_apub_endpoint(EndpointType::Person, &cuser.name)?), - bio: Some(cuser.bio.to_owned()), - local: cuser.local, - private_key: Some(keypair.private_key), - public_key: Some(keypair.public_key), + banned: None, + deleted: None, + actor_id: Some(generate_apub_endpoint(EndpointType::Person, &cperson.name)?), + bio: None, + local: None, + private_key: Some(Some(keypair.private_key)), + public_key: Some(Some(keypair.public_key)), last_refreshed_at: Some(naive_now()), inbox_url: None, shared_inbox_url: None, }; - User_::update(&conn, cuser.id, &form)?; + Person::update(&conn, cperson.id, &form)?; } - info!("{} user rows updated.", incorrect_users.len()); + info!("{} person rows updated.", incorrect_persons.len()); Ok(()) } @@ -231,20 +221,20 @@ fn post_thumbnail_url_updates_2020_07_27(conn: &PgConnection) -> Result<(), Lemm fn apub_columns_2021_02_02(conn: &PgConnection) -> Result<(), LemmyError> { info!("Running apub_columns_2021_02_02"); { - use lemmy_db_schema::schema::user_::dsl::*; - let users = user_ + use lemmy_db_schema::schema::person::dsl::*; + let persons = person .filter(inbox_url.like("http://changeme_%")) - .load::(conn)?; + .load::(conn)?; - for u in &users { - let inbox_url_ = generate_inbox_url(&u.actor_id)?; - let shared_inbox_url_ = generate_shared_inbox_url(&u.actor_id)?; - diesel::update(user_.find(u.id)) + for p in &persons { + let inbox_url_ = generate_inbox_url(&p.actor_id)?; + let shared_inbox_url_ = generate_shared_inbox_url(&p.actor_id)?; + diesel::update(person.find(p.id)) .set(( inbox_url.eq(inbox_url_), shared_inbox_url.eq(shared_inbox_url_), )) - .get_result::(conn)?; + .get_result::(conn)?; } } From 1a4c8c08ee05fa992342078c278737c24d5bbcc1 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Thu, 11 Mar 2021 11:41:04 -0500 Subject: [PATCH 07/18] Fixing some tests --- .../src/source/password_reset_request.rs | 27 ++++++++++++++++--- crates/db_views/src/comment_view.rs | 2 +- scripts/clear_db.sh | 3 +++ restore_db.sh => scripts/restore_db.sh | 0 4 files changed, 28 insertions(+), 4 deletions(-) create mode 100755 scripts/clear_db.sh rename restore_db.sh => scripts/restore_db.sh (100%) diff --git a/crates/db_queries/src/source/password_reset_request.rs b/crates/db_queries/src/source/password_reset_request.rs index 96fd06477..dd00e6ff3 100644 --- a/crates/db_queries/src/source/password_reset_request.rs +++ b/crates/db_queries/src/source/password_reset_request.rs @@ -77,7 +77,11 @@ mod tests { source::password_reset_request::PasswordResetRequest_, Crud, }; - use lemmy_db_schema::source::{password_reset_request::PasswordResetRequest, person::*}; + use lemmy_db_schema::source::{ + local_user::{LocalUser, LocalUserForm}, + password_reset_request::PasswordResetRequest, + person::*, + }; use serial_test::serial; #[test] @@ -106,15 +110,32 @@ mod tests { let inserted_person = Person::create(&conn, &new_person).unwrap(); + let new_local_user = LocalUserForm { + person_id: inserted_person.id, + password_encrypted: "pass".to_string(), + email: None, + matrix_user_id: None, + admin: None, + show_nsfw: None, + theme: None, + default_sort_type: None, + default_listing_type: None, + lang: None, + show_avatars: None, + send_notifications_to_email: None, + }; + + let inserted_local_user = LocalUser::create(&conn, &new_local_user).unwrap(); + let token = "nope"; let token_encrypted_ = "ca3704aa0b06f5954c79ee837faa152d84d6b2d42838f0637a15eda8337dbdce"; let inserted_password_reset_request = - PasswordResetRequest::create_token(&conn, inserted_person.id, token).unwrap(); + PasswordResetRequest::create_token(&conn, inserted_local_user.id, token).unwrap(); let expected_password_reset_request = PasswordResetRequest { id: inserted_password_reset_request.id, - local_user_id: inserted_person.id, + local_user_id: inserted_local_user.id, token_encrypted: token_encrypted_.to_string(), published: inserted_password_reset_request.published, }; diff --git a/crates/db_views/src/comment_view.rs b/crates/db_views/src/comment_view.rs index 49bad6c03..79c420036 100644 --- a/crates/db_views/src/comment_view.rs +++ b/crates/db_views/src/comment_view.rs @@ -449,7 +449,7 @@ mod tests { let conn = establish_unpooled_connection(); let new_person = PersonForm { - name: "thommy".into(), + name: "timmy".into(), preferred_username: None, avatar: None, banner: None, diff --git a/scripts/clear_db.sh b/scripts/clear_db.sh new file mode 100755 index 000000000..b62490e12 --- /dev/null +++ b/scripts/clear_db.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +psql -U lemmy -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public; DROP SCHEMA utils CASCADE;" diff --git a/restore_db.sh b/scripts/restore_db.sh similarity index 100% rename from restore_db.sh rename to scripts/restore_db.sh From 5d8ccbafe46bdb7322fcc0a10fa4b00e994b8cad Mon Sep 17 00:00:00 2001 From: Dessalines Date: Thu, 11 Mar 2021 11:54:03 -0500 Subject: [PATCH 08/18] Fixing some tests 2 --- crates/db_queries/src/source/person.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/db_queries/src/source/person.rs b/crates/db_queries/src/source/person.rs index 1e6622aea..f167e7f7a 100644 --- a/crates/db_queries/src/source/person.rs +++ b/crates/db_queries/src/source/person.rs @@ -238,7 +238,7 @@ mod tests { let conn = establish_unpooled_connection(); let new_person = PersonForm { - name: "thommy".into(), + name: "holly".into(), preferred_username: None, avatar: None, banner: None, @@ -260,7 +260,7 @@ mod tests { let expected_person = Person { id: inserted_person.id, - name: "thommy".into(), + name: "holly".into(), preferred_username: None, avatar: None, banner: None, From 7d04f371a5933adccddecc366ed3630fc552847b Mon Sep 17 00:00:00 2001 From: Dessalines Date: Thu, 11 Mar 2021 12:08:30 -0500 Subject: [PATCH 09/18] fixing tests 3 --- .drone.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.drone.yml b/.drone.yml index 8b9f15919..bb27984f9 100644 --- a/.drone.yml +++ b/.drone.yml @@ -30,6 +30,7 @@ steps: environment: LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432/lemmy RUST_BACKTRACE: 1 + RUST_TEST_THREADS: 1 commands: - sudo apt-get update - sudo apt-get -y install --no-install-recommends espeak postgresql-client @@ -107,6 +108,7 @@ steps: environment: LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432/lemmy RUST_BACKTRACE: 1 + RUST_TEST_THREADS: 1 commands: - apt-get update - apt-get -y install --no-install-recommends espeak postgresql-client libssl-dev pkg-config libpq-dev From 7c039340ed175a464a7304b7bc686468e0f3353b Mon Sep 17 00:00:00 2001 From: Dessalines Date: Thu, 11 Mar 2021 17:47:44 -0500 Subject: [PATCH 10/18] 2nd pass. JWT now uses local_user_id --- crates/api/src/lib.rs | 20 +++--- crates/api/src/local_user.rs | 14 ++-- crates/api/src/websocket.rs | 3 +- crates/api_structs/src/lib.rs | 8 +-- crates/db_queries/src/lib.rs | 4 +- crates/db_queries/src/source/local_user.rs | 29 +-------- crates/db_queries/src/source/person.rs | 1 - crates/db_schema/src/source/person.rs | 2 +- crates/db_views/src/comment_view.rs | 2 +- crates/db_views/src/local_user_view.rs | 74 ++++++++++++++-------- crates/routes/src/webfinger.rs | 8 +-- crates/utils/src/claims.rs | 4 +- crates/utils/src/lib.rs | 2 +- crates/websocket/src/handlers.rs | 2 +- crates/websocket/src/messages.rs | 2 +- 15 files changed, 82 insertions(+), 93 deletions(-) diff --git a/crates/api/src/lib.rs b/crates/api/src/lib.rs index d71f4b6ee..65d97c4a4 100644 --- a/crates/api/src/lib.rs +++ b/crates/api/src/lib.rs @@ -103,11 +103,9 @@ pub(crate) async fn get_local_user_view_from_jwt( Ok(claims) => claims.claims, Err(_e) => return Err(ApiError::err("not_logged_in").into()), }; - let person_id = claims.id; - let local_user_view = blocking(pool, move |conn| { - LocalUserView::read_person(conn, person_id) - }) - .await??; + let local_user_id = claims.id; + let local_user_view = + blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??; // Check for a site ban if local_user_view.person.banned { return Err(ApiError::err("site_ban").into()); @@ -133,9 +131,9 @@ pub(crate) async fn get_local_user_settings_view_from_jwt( Ok(claims) => claims.claims, Err(_e) => return Err(ApiError::err("not_logged_in").into()), }; - let person_id = claims.id; + let local_user_id = claims.id; let local_user_view = blocking(pool, move |conn| { - LocalUserSettingsView::read(conn, person_id) + LocalUserSettingsView::read(conn, local_user_id) }) .await??; // Check for a site ban @@ -185,21 +183,21 @@ pub(crate) async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result /// or if a community_id is supplied validates the user is a moderator /// of that community and returns the community id in a vec /// -/// * `user_id` - the user id of the moderator +/// * `person_id` - the person id of the moderator /// * `community_id` - optional community id to check for moderator privileges /// * `pool` - the diesel db pool pub(crate) async fn collect_moderated_communities( - user_id: i32, + person_id: i32, community_id: Option, pool: &DbPool, ) -> Result, LemmyError> { if let Some(community_id) = community_id { // if the user provides a community_id, just check for mod/admin privileges - is_mod_or_admin(pool, user_id, community_id).await?; + is_mod_or_admin(pool, person_id, community_id).await?; Ok(vec![community_id]) } else { let ids = blocking(pool, move |conn: &'_ _| { - CommunityModerator::get_person_moderated_communities(conn, user_id) + CommunityModerator::get_person_moderated_communities(conn, person_id) }) .await??; Ok(ids) diff --git a/crates/api/src/local_user.rs b/crates/api/src/local_user.rs index 781ef8f9a..9b5611f2c 100644 --- a/crates/api/src/local_user.rs +++ b/crates/api/src/local_user.rs @@ -129,7 +129,7 @@ impl Perform for Login { // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(local_user_view.person.id, Settings::get().hostname())?, + jwt: Claims::jwt(local_user_view.local_user.id, Settings::get().hostname())?, }) } } @@ -243,7 +243,7 @@ impl Perform for Register { send_notifications_to_email: Some(false), }; - match blocking(context.pool(), move |conn| { + let inserted_local_user = match blocking(context.pool(), move |conn| { LocalUser::register(conn, &local_user_form) }) .await? @@ -332,7 +332,7 @@ impl Perform for Register { // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(inserted_person.id, Settings::get().hostname())?, + jwt: Claims::jwt(inserted_local_user.id, Settings::get().hostname())?, }) } } @@ -479,7 +479,7 @@ impl Perform for SaveUserSettings { Person::update(conn, person_id, &person_form) }) .await?; - let updated_person: Person = match person_res { + let _updated_person: Person = match person_res { Ok(p) => p, Err(_) => { return Err(ApiError::err("user_already_exists").into()); @@ -505,8 +505,8 @@ impl Perform for SaveUserSettings { LocalUser::update(conn, local_user_id, &local_user_form) }) .await?; - match local_user_res { - Ok(user) => user, + let updated_local_user = match local_user_res { + Ok(u) => u, Err(e) => { let err_type = if e.to_string() == "duplicate key value violates unique constraint \"local_user_email_key\"" @@ -522,7 +522,7 @@ impl Perform for SaveUserSettings { // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(updated_person.id, Settings::get().hostname())?, + jwt: Claims::jwt(updated_local_user.id, Settings::get().hostname())?, }) } } diff --git a/crates/api/src/websocket.rs b/crates/api/src/websocket.rs index 47e21091f..ae5ba8940 100644 --- a/crates/api/src/websocket.rs +++ b/crates/api/src/websocket.rs @@ -21,8 +21,7 @@ impl Perform for UserJoin { if let Some(ws_id) = websocket_id { context.chat_server().do_send(JoinUserRoom { - // TODO this should probably be the local_user_id - user_id: local_user_view.person.id, + local_user_id: local_user_view.local_user.id, id: ws_id, }); } diff --git a/crates/api_structs/src/lib.rs b/crates/api_structs/src/lib.rs index c861136a1..e675d02ae 100644 --- a/crates/api_structs/src/lib.rs +++ b/crates/api_structs/src/lib.rs @@ -90,7 +90,7 @@ fn do_send_local_notifs( // TODO // At some point, make it so you can't tag the parent creator either // This can cause two notifications, one for reply and the other for mention - recipient_ids.push(mention_user_view.person.id); + recipient_ids.push(mention_user_view.local_user.id); let user_mention_form = PersonMentionForm { recipient_id: mention_user_view.person.id, @@ -102,7 +102,7 @@ fn do_send_local_notifs( // Let the uniqueness handle this fail PersonMention::create(&conn, &user_mention_form).ok(); - // Send an email to those users that have notifications on + // Send an email to those local users that have notifications on if do_send_email && mention_user_view.local_user.send_notifications_to_email { send_email_to_user( mention_user_view, @@ -121,7 +121,7 @@ fn do_send_local_notifs( if parent_comment.creator_id != person.id { if let Ok(parent_user_view) = LocalUserView::read_person(&conn, parent_comment.creator_id) { - recipient_ids.push(parent_user_view.person.id); + recipient_ids.push(parent_user_view.local_user.id); if do_send_email && parent_user_view.local_user.send_notifications_to_email { send_email_to_user( @@ -139,7 +139,7 @@ fn do_send_local_notifs( None => { if post.creator_id != person.id { if let Ok(parent_user_view) = LocalUserView::read_person(&conn, post.creator_id) { - recipient_ids.push(parent_user_view.person.id); + recipient_ids.push(parent_user_view.local_user.id); if do_send_email && parent_user_view.local_user.send_notifications_to_email { send_email_to_user( diff --git a/crates/db_queries/src/lib.rs b/crates/db_queries/src/lib.rs index f19d36263..e027cfc91 100644 --- a/crates/db_queries/src/lib.rs +++ b/crates/db_queries/src/lib.rs @@ -47,7 +47,7 @@ pub trait Followable { fn follow(conn: &PgConnection, form: &T) -> Result where Self: Sized; - fn follow_accepted(conn: &PgConnection, community_id: i32, user_id: i32) -> Result + fn follow_accepted(conn: &PgConnection, community_id: i32, person_id: i32) -> Result where Self: Sized; fn unfollow(conn: &PgConnection, form: &T) -> Result @@ -69,7 +69,7 @@ pub trait Likeable { fn like(conn: &PgConnection, form: &T) -> Result where Self: Sized; - fn remove(conn: &PgConnection, user_id: i32, item_id: i32) -> Result + fn remove(conn: &PgConnection, person_id: i32, item_id: i32) -> Result where Self: Sized; } diff --git a/crates/db_queries/src/source/local_user.rs b/crates/db_queries/src/source/local_user.rs index 58579f962..4ca557c59 100644 --- a/crates/db_queries/src/source/local_user.rs +++ b/crates/db_queries/src/source/local_user.rs @@ -1,9 +1,9 @@ -use crate::{Crud, ToSafeSettings}; +use crate::Crud; use bcrypt::{hash, DEFAULT_COST}; use diesel::{dsl::*, result::Error, *}; use lemmy_db_schema::{ schema::local_user::dsl::*, - source::local_user::{LocalUser, LocalUserForm, LocalUserSettings}, + source::local_user::{LocalUser, LocalUserForm}, }; mod safe_type { @@ -70,7 +70,6 @@ pub trait LocalUser_ { new_password: &str, ) -> Result; fn add_admin(conn: &PgConnection, local_user_id: i32, added: bool) -> Result; - fn find_by_person(conn: &PgConnection, from_person_id: i32) -> Result; } impl LocalUser_ for LocalUser { @@ -83,7 +82,6 @@ impl LocalUser_ for LocalUser { Self::create(&conn, &edited_user) } - // TODO do more individual updates like these fn update_password( conn: &PgConnection, local_user_id: i32, @@ -96,19 +94,11 @@ impl LocalUser_ for LocalUser { .get_result::(conn) } - // TODO is this used? fn add_admin(conn: &PgConnection, local_user_id: i32, added: bool) -> Result { diesel::update(local_user.find(local_user_id)) .set(admin.eq(added)) .get_result::(conn) } - - // TODO is this used? - fn find_by_person(conn: &PgConnection, for_person_id: i32) -> Result { - local_user - .filter(person_id.eq(for_person_id)) - .first::(conn) - } } impl Crud for LocalUser { @@ -129,18 +119,3 @@ impl Crud for LocalUser { .get_result::(conn) } } - -// TODO is this used? -pub trait LocalUserSettings_ { - fn read(conn: &PgConnection, user_id: i32) -> Result; -} - -// TODO is this used? -impl LocalUserSettings_ for LocalUserSettings { - fn read(conn: &PgConnection, user_id: i32) -> Result { - local_user - .select(LocalUser::safe_settings_columns_tuple()) - .find(user_id) - .first::(conn) - } -} diff --git a/crates/db_queries/src/source/person.rs b/crates/db_queries/src/source/person.rs index f167e7f7a..81df7b717 100644 --- a/crates/db_queries/src/source/person.rs +++ b/crates/db_queries/src/source/person.rs @@ -192,7 +192,6 @@ impl Person_ for Person { .get_result::(conn) } - // TODO is this used? fn find_by_name(conn: &PgConnection, from_name: &str) -> Result { person .filter(deleted.eq(false)) diff --git a/crates/db_schema/src/source/person.rs b/crates/db_schema/src/source/person.rs index 7fc3692f8..b3af21c3d 100644 --- a/crates/db_schema/src/source/person.rs +++ b/crates/db_schema/src/source/person.rs @@ -26,7 +26,7 @@ pub struct Person { pub shared_inbox_url: Option, } -/// A safe representation of user, without the sensitive info +/// A safe representation of person, without the sensitive info #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person"] pub struct PersonSafe { diff --git a/crates/db_views/src/comment_view.rs b/crates/db_views/src/comment_view.rs index 79c420036..d3e97c642 100644 --- a/crates/db_views/src/comment_view.rs +++ b/crates/db_views/src/comment_view.rs @@ -367,7 +367,7 @@ impl<'a> CommentQueryBuilder<'a> { query = match self.listing_type { // ListingType::Subscribed => query.filter(community_follower::subscribed.eq(true)), - ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::user_id.eq(user_id_join)), + ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::person_id.eq(person_id_join)), ListingType::Local => query.filter(community::local.eq(true)), _ => query, }; diff --git a/crates/db_views/src/local_user_view.rs b/crates/db_views/src/local_user_view.rs index d377af633..ee4811b65 100644 --- a/crates/db_views/src/local_user_view.rs +++ b/crates/db_views/src/local_user_view.rs @@ -11,42 +11,60 @@ use serde::Serialize; #[derive(Debug, Serialize, Clone)] pub struct LocalUserView { + pub local_user: LocalUser, pub person: Person, pub counts: PersonAggregates, - pub local_user: LocalUser, } -type LocalUserViewTuple = (Person, PersonAggregates, LocalUser); +type LocalUserViewTuple = (LocalUser, Person, PersonAggregates); impl LocalUserView { - pub fn read_person(conn: &PgConnection, person_id: i32) -> Result { - let (person, counts, local_user) = person::table - .find(person_id) - .inner_join(person_aggregates::table) - .inner_join(local_user::table) + pub fn read(conn: &PgConnection, local_user_id: i32) -> Result { + let (local_user, person, counts) = local_user::table + .find(local_user_id) + .inner_join(person::table) + .inner_join(person_aggregates::table.on(person::id.eq(person_aggregates::person_id))) .select(( + local_user::all_columns, person::all_columns, person_aggregates::all_columns, - local_user::all_columns, )) .first::(conn)?; Ok(Self { + local_user, person, counts, + }) + } + + pub fn read_person(conn: &PgConnection, person_id: i32) -> Result { + let (local_user, person, counts) = local_user::table + .filter(person::id.eq(person_id)) + .inner_join(person::table) + .inner_join(person_aggregates::table.on(person::id.eq(person_aggregates::person_id))) + .select(( + local_user::all_columns, + person::all_columns, + person_aggregates::all_columns, + )) + .first::(conn)?; + Ok(Self { local_user, + person, + counts, }) } // TODO check where this is used pub fn read_from_name(conn: &PgConnection, name: &str) -> Result { - let (person, counts, local_user) = person::table + let (local_user, person, counts) = local_user::table .filter(person::name.eq(name)) - .inner_join(person_aggregates::table) - .inner_join(local_user::table) + .inner_join(person::table) + .inner_join(person_aggregates::table.on(person::id.eq(person_aggregates::person_id))) .select(( + local_user::all_columns, person::all_columns, person_aggregates::all_columns, - local_user::all_columns, )) .first::(conn)?; Ok(Self { @@ -57,18 +75,18 @@ impl LocalUserView { } pub fn find_by_email_or_name(conn: &PgConnection, name_or_email: &str) -> Result { - let (person, counts, local_user) = person::table - .inner_join(person_aggregates::table) - .inner_join(local_user::table) + let (local_user, person, counts) = local_user::table + .inner_join(person::table) + .inner_join(person_aggregates::table.on(person::id.eq(person_aggregates::person_id))) .filter( person::name .ilike(name_or_email) .or(local_user::email.ilike(name_or_email)), ) .select(( + local_user::all_columns, person::all_columns, person_aggregates::all_columns, - local_user::all_columns, )) .first::(conn)?; Ok(Self { @@ -79,14 +97,14 @@ impl LocalUserView { } pub fn find_by_email(conn: &PgConnection, from_email: &str) -> Result { - let (person, counts, local_user) = person::table - .inner_join(person_aggregates::table) - .inner_join(local_user::table) + let (local_user, person, counts) = local_user::table + .inner_join(person::table) + .inner_join(person_aggregates::table.on(person::id.eq(person_aggregates::person_id))) .filter(local_user::email.eq(from_email)) .select(( + local_user::all_columns, person::all_columns, person_aggregates::all_columns, - local_user::all_columns, )) .first::(conn)?; Ok(Self { @@ -99,23 +117,23 @@ impl LocalUserView { #[derive(Debug, Serialize, Clone)] pub struct LocalUserSettingsView { + pub local_user: LocalUserSettings, pub person: PersonSafe, pub counts: PersonAggregates, - pub local_user: LocalUserSettings, } -type LocalUserSettingsViewTuple = (PersonSafe, PersonAggregates, LocalUserSettings); +type LocalUserSettingsViewTuple = (LocalUserSettings, PersonSafe, PersonAggregates); impl LocalUserSettingsView { - pub fn read(conn: &PgConnection, person_id: i32) -> Result { - let (person, counts, local_user) = person::table - .find(person_id) - .inner_join(person_aggregates::table) - .inner_join(local_user::table) + pub fn read(conn: &PgConnection, local_user_id: i32) -> Result { + let (local_user, person, counts) = local_user::table + .find(local_user_id) + .inner_join(person::table) + .inner_join(person_aggregates::table.on(person::id.eq(person_aggregates::person_id))) .select(( + LocalUser::safe_settings_columns_tuple(), Person::safe_columns_tuple(), person_aggregates::all_columns, - LocalUser::safe_settings_columns_tuple(), )) .first::(conn)?; Ok(Self { diff --git a/crates/routes/src/webfinger.rs b/crates/routes/src/webfinger.rs index c444451e9..8ab2a5b6a 100644 --- a/crates/routes/src/webfinger.rs +++ b/crates/routes/src/webfinger.rs @@ -7,7 +7,7 @@ use lemmy_utils::{ settings::structs::Settings, LemmyError, WEBFINGER_COMMUNITY_REGEX, - WEBFINGER_USER_REGEX, + WEBFINGER_USERNAME_REGEX, }; use lemmy_websocket::LemmyContext; use serde::Deserialize; @@ -41,7 +41,7 @@ async fn get_webfinger_response( .map(|c| c.get(1)) .flatten(); - let user_regex_parsed = WEBFINGER_USER_REGEX + let username_regex_parsed = WEBFINGER_USERNAME_REGEX .captures(&info.resource) .map(|c| c.get(1)) .flatten(); @@ -55,9 +55,9 @@ async fn get_webfinger_response( .await? .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))? .actor_id - } else if let Some(person_name) = user_regex_parsed { + } else if let Some(person_name) = username_regex_parsed { let person_name = person_name.as_str().to_owned(); - // Make sure the requested user exists. + // Make sure the requested person exists. blocking(context.pool(), move |conn| { Person::find_by_name(conn, &person_name) }) diff --git a/crates/utils/src/claims.rs b/crates/utils/src/claims.rs index 3d9232e6b..3529f5f19 100644 --- a/crates/utils/src/claims.rs +++ b/crates/utils/src/claims.rs @@ -23,9 +23,9 @@ impl Claims { ) } - pub fn jwt(user_id: i32, hostname: String) -> Result { + pub fn jwt(local_user_id: i32, hostname: String) -> Result { let my_claims = Claims { - id: user_id, + id: local_user_id, iss: hostname, }; encode( diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs index bd2b56844..5e76e8bc5 100644 --- a/crates/utils/src/lib.rs +++ b/crates/utils/src/lib.rs @@ -87,7 +87,7 @@ lazy_static! { Settings::get().hostname() )) .expect("compile webfinger regex"); - pub static ref WEBFINGER_USER_REGEX: Regex = Regex::new(&format!( + pub static ref WEBFINGER_USERNAME_REGEX: Regex = Regex::new(&format!( "^acct:([a-z0-9_]{{3, 20}})@{}$", Settings::get().hostname() )) diff --git a/crates/websocket/src/handlers.rs b/crates/websocket/src/handlers.rs index 0762b9485..7198fcb78 100644 --- a/crates/websocket/src/handlers.rs +++ b/crates/websocket/src/handlers.rs @@ -155,7 +155,7 @@ impl Handler for ChatServer { type Result = (); fn handle(&mut self, msg: JoinUserRoom, _: &mut Context) { - self.join_user_room(msg.user_id, msg.id).ok(); + self.join_user_room(msg.local_user_id, msg.id).ok(); } } diff --git a/crates/websocket/src/messages.rs b/crates/websocket/src/messages.rs index 89f3f2b3e..b3d98d066 100644 --- a/crates/websocket/src/messages.rs +++ b/crates/websocket/src/messages.rs @@ -91,7 +91,7 @@ pub struct SendComment { #[derive(Message)] #[rtype(result = "()")] pub struct JoinUserRoom { - pub user_id: UserId, + pub local_user_id: UserId, pub id: ConnectionId, } From 75a95acf0430966264c223d52af765a70d2a15dd Mon Sep 17 00:00:00 2001 From: Dessalines Date: Fri, 12 Mar 2021 10:54:47 -0500 Subject: [PATCH 11/18] Change joinuser, sendusermessage to use local_user_id --- crates/utils/src/lib.rs | 2 +- crates/websocket/src/chat_server.rs | 12 ++++++++---- crates/websocket/src/messages.rs | 6 +++--- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs index 5e76e8bc5..373cacab5 100644 --- a/crates/utils/src/lib.rs +++ b/crates/utils/src/lib.rs @@ -23,7 +23,7 @@ use thiserror::Error; pub type ConnectionId = usize; pub type PostId = i32; pub type CommunityId = i32; -pub type UserId = i32; +pub type LocalUserId = i32; pub type IpAddr = String; #[macro_export] diff --git a/crates/websocket/src/chat_server.rs b/crates/websocket/src/chat_server.rs index 9978d1ec6..ea4a651ad 100644 --- a/crates/websocket/src/chat_server.rs +++ b/crates/websocket/src/chat_server.rs @@ -15,8 +15,8 @@ use lemmy_utils::{ ConnectionId, IpAddr, LemmyError, + LocalUserId, PostId, - UserId, }; use rand::rngs::ThreadRng; use reqwest::Client; @@ -51,7 +51,7 @@ pub struct ChatServer { /// A map from user id to its connection ID for joined users. Remember a user can have multiple /// sessions (IE clients) - pub(super) user_rooms: HashMap>, + pub(super) user_rooms: HashMap>, pub(super) rng: ThreadRng, @@ -185,7 +185,11 @@ impl ChatServer { Ok(()) } - pub fn join_user_room(&mut self, user_id: UserId, id: ConnectionId) -> Result<(), LemmyError> { + pub fn join_user_room( + &mut self, + user_id: LocalUserId, + id: ConnectionId, + ) -> Result<(), LemmyError> { // remove session from all rooms for sessions in self.user_rooms.values_mut() { sessions.remove(&id); @@ -302,7 +306,7 @@ impl ChatServer { &self, op: &UserOperation, response: &Response, - recipient_id: UserId, + recipient_id: LocalUserId, websocket_id: Option, ) -> Result<(), LemmyError> where diff --git a/crates/websocket/src/messages.rs b/crates/websocket/src/messages.rs index b3d98d066..e66ffe110 100644 --- a/crates/websocket/src/messages.rs +++ b/crates/websocket/src/messages.rs @@ -1,7 +1,7 @@ use crate::UserOperation; use actix::{prelude::*, Recipient}; use lemmy_api_structs::{comment::CommentResponse, post::PostResponse}; -use lemmy_utils::{CommunityId, ConnectionId, IpAddr, PostId, UserId}; +use lemmy_utils::{CommunityId, ConnectionId, IpAddr, LocalUserId, PostId}; use serde::{Deserialize, Serialize}; /// Chat server sends this messages to session @@ -50,7 +50,7 @@ pub struct SendAllMessage { pub struct SendUserRoomMessage { pub op: UserOperation, pub response: Response, - pub recipient_id: UserId, + pub recipient_id: LocalUserId, pub websocket_id: Option, } @@ -91,7 +91,7 @@ pub struct SendComment { #[derive(Message)] #[rtype(result = "()")] pub struct JoinUserRoom { - pub local_user_id: UserId, + pub local_user_id: LocalUserId, pub id: ConnectionId, } From 434fb53dd1d6d09a3be912bc05465b970f6402b6 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Fri, 12 Mar 2021 14:09:03 -0500 Subject: [PATCH 12/18] Trying to fix API tests. --- api_tests/package.json | 2 +- api_tests/src/community.spec.ts | 3 --- api_tests/src/post.spec.ts | 16 ++++++++-------- api_tests/src/shared.ts | 33 ++++++++++++++++----------------- api_tests/src/user.spec.ts | 20 ++++++++++---------- api_tests/yarn.lock | 8 ++++---- 6 files changed, 39 insertions(+), 43 deletions(-) diff --git a/api_tests/package.json b/api_tests/package.json index e2c4f37a0..d4232ed53 100644 --- a/api_tests/package.json +++ b/api_tests/package.json @@ -16,7 +16,7 @@ "eslint": "^7.18.0", "eslint-plugin-jane": "^9.0.3", "jest": "^26.6.3", - "lemmy-js-client": "0.9.1-rc.1", + "lemmy-js-client": "0.10.0-rc.4", "node-fetch": "^2.6.1", "prettier": "^2.1.2", "ts-jest": "^26.4.4", diff --git a/api_tests/src/community.spec.ts b/api_tests/src/community.spec.ts index 25d8109c3..7be6f4c59 100644 --- a/api_tests/src/community.spec.ts +++ b/api_tests/src/community.spec.ts @@ -33,9 +33,6 @@ function assertCommunityFederation( ); expect(communityOne.creator.actor_id).toBe(communityTwo.creator.actor_id); expect(communityOne.community.nsfw).toBe(communityTwo.community.nsfw); - expect(communityOne.community.category_id).toBe( - communityTwo.community.category_id - ); expect(communityOne.community.removed).toBe(communityTwo.community.removed); expect(communityOne.community.deleted).toBe(communityTwo.community.deleted); } diff --git a/api_tests/src/post.spec.ts b/api_tests/src/post.spec.ts index 01befa60c..a79ee198b 100644 --- a/api_tests/src/post.spec.ts +++ b/api_tests/src/post.spec.ts @@ -20,9 +20,9 @@ import { getPost, unfollowRemotes, searchForUser, - banUserFromSite, + banPersonFromSite, searchPostLocal, - banUserFromCommunity, + banPersonFromCommunity, } from './shared'; import { PostView, CommunityView } from 'lemmy-js-client'; @@ -305,7 +305,7 @@ test('Enforce site ban for federated user', async () => { expect(alphaUser).toBeDefined(); // ban alpha from beta site - let banAlpha = await banUserFromSite(beta, alphaUser.user.id, true); + let banAlpha = await banPersonFromSite(beta, alphaUser.person.id, true); expect(banAlpha.banned).toBe(true); // Alpha makes post on beta @@ -321,7 +321,7 @@ test('Enforce site ban for federated user', async () => { expect(betaPost).toBeUndefined(); // Unban alpha - let unBanAlpha = await banUserFromSite(beta, alphaUser.user.id, false); + let unBanAlpha = await banPersonFromSite(beta, alphaUser.person.id, false); expect(unBanAlpha.banned).toBe(false); }); @@ -332,8 +332,8 @@ test('Enforce community ban for federated user', async () => { expect(alphaUser).toBeDefined(); // ban alpha from beta site - await banUserFromCommunity(beta, alphaUser.user.id, 2, false); - let banAlpha = await banUserFromCommunity(beta, alphaUser.user.id, 2, true); + await banPersonFromCommunity(beta, alphaUser.person.id, 2, false); + let banAlpha = await banPersonFromCommunity(beta, alphaUser.person.id, 2, true); expect(banAlpha.banned).toBe(true); // Alpha makes post on beta @@ -349,9 +349,9 @@ test('Enforce community ban for federated user', async () => { expect(betaPost).toBeUndefined(); // Unban alpha - let unBanAlpha = await banUserFromCommunity( + let unBanAlpha = await banPersonFromCommunity( beta, - alphaUser.user.id, + alphaUser.person.id, 2, false ); diff --git a/api_tests/src/shared.ts b/api_tests/src/shared.ts index 0c12d29c0..c11fa3b0e 100644 --- a/api_tests/src/shared.ts +++ b/api_tests/src/shared.ts @@ -25,7 +25,7 @@ import { CreateCommunity, DeleteCommunity, RemoveCommunity, - GetUserMentions, + GetPersonMentions, CreateCommentLike, CreatePostLike, EditPrivateMessage, @@ -36,15 +36,15 @@ import { GetPost, PrivateMessageResponse, PrivateMessagesResponse, - GetUserMentionsResponse, + GetPersonMentionsResponse, SaveUserSettings, SortType, ListingType, GetSiteResponse, SearchType, LemmyHttp, - BanUserResponse, - BanUser, + BanPersonResponse, + BanPerson, BanFromCommunity, BanFromCommunityResponse, Post, @@ -289,32 +289,32 @@ export async function searchForUser( return api.client.search(form); } -export async function banUserFromSite( +export async function banPersonFromSite( api: API, - user_id: number, + person_id: number, ban: boolean -): Promise { +): Promise { // Make sure lemmy-beta/c/main is cached on lemmy_alpha // Use short-hand search url - let form: BanUser = { - user_id, + let form: BanPerson = { + person_id, ban, remove_data: false, auth: api.auth, }; - return api.client.banUser(form); + return api.client.banPerson(form); } -export async function banUserFromCommunity( +export async function banPersonFromCommunity( api: API, - user_id: number, + person_id: number, community_id: number, ban: boolean ): Promise { // Make sure lemmy-beta/c/main is cached on lemmy_alpha // Use short-hand search url let form: BanFromCommunity = { - user_id, + person_id, community_id, remove_data: false, ban, @@ -413,13 +413,13 @@ export async function removeComment( return api.client.removeComment(form); } -export async function getMentions(api: API): Promise { - let form: GetUserMentions = { +export async function getMentions(api: API): Promise { + let form: GetPersonMentions = { sort: SortType.New, unread_only: false, auth: api.auth, }; - return api.client.getUserMentions(form); + return api.client.getPersonMentions(form); } export async function likeComment( @@ -448,7 +448,6 @@ export async function createCommunity( description, icon, banner, - category_id: 1, nsfw: false, auth: api.auth, }; diff --git a/api_tests/src/user.spec.ts b/api_tests/src/user.spec.ts index 4352aa423..a10876cf5 100644 --- a/api_tests/src/user.spec.ts +++ b/api_tests/src/user.spec.ts @@ -8,7 +8,7 @@ import { getSite, } from './shared'; import { - UserViewSafe, + PersonViewSafe, SaveUserSettings, SortType, ListingType, @@ -17,14 +17,14 @@ import { let auth: string; let apShortname: string; -function assertUserFederation(userOne: UserViewSafe, userTwo: UserViewSafe) { - expect(userOne.user.name).toBe(userTwo.user.name); - expect(userOne.user.preferred_username).toBe(userTwo.user.preferred_username); - expect(userOne.user.bio).toBe(userTwo.user.bio); - expect(userOne.user.actor_id).toBe(userTwo.user.actor_id); - expect(userOne.user.avatar).toBe(userTwo.user.avatar); - expect(userOne.user.banner).toBe(userTwo.user.banner); - expect(userOne.user.published).toBe(userTwo.user.published); +function assertUserFederation(userOne: PersonViewSafe, userTwo: PersonViewSafe) { + expect(userOne.person.name).toBe(userTwo.person.name); + expect(userOne.person.preferred_username).toBe(userTwo.person.preferred_username); + expect(userOne.person.bio).toBe(userTwo.person.bio); + expect(userOne.person.actor_id).toBe(userTwo.person.actor_id); + expect(userOne.person.avatar).toBe(userTwo.person.avatar); + expect(userOne.person.banner).toBe(userTwo.person.banner); + expect(userOne.person.published).toBe(userTwo.person.published); } test('Create user', async () => { @@ -34,7 +34,7 @@ test('Create user', async () => { let site = await getSite(alpha, auth); expect(site.my_user).toBeDefined(); - apShortname = `@${site.my_user.name}@lemmy-alpha:8541`; + apShortname = `@${site.my_user.person.name}@lemmy-alpha:8541`; }); test('Set some user settings, check that they are federated', async () => { diff --git a/api_tests/yarn.lock b/api_tests/yarn.lock index 8e29aa041..a6d1be5a3 100644 --- a/api_tests/yarn.lock +++ b/api_tests/yarn.lock @@ -3233,10 +3233,10 @@ language-tags@^1.0.5: dependencies: language-subtag-registry "~0.3.2" -lemmy-js-client@0.9.1-rc.1: - version "0.9.1-rc.1" - resolved "https://registry.yarnpkg.com/lemmy-js-client/-/lemmy-js-client-0.9.1-rc.1.tgz#afe3cb0d4852f849dd087a4756a3771bc920a907" - integrity sha512-aVvo4IeJvIPUvypipk4GnyLB6nVQVLfB0arYrMkVV4L7zrZ/0pGtpkMDLaOAj/KpA6O0u9eLmaou5RberZQolA== +lemmy-js-client@0.10.0-rc.4: + version "0.10.0-rc.4" + resolved "https://registry.yarnpkg.com/lemmy-js-client/-/lemmy-js-client-0.10.0-rc.4.tgz#ac6fe6940fc5f73260ddb166ce0ef3c0520901fc" + integrity sha512-yJPnvGaWneOOwjKEqb4qXtQk+4DbRgO+hEzSin2GgUgnxluY43gemwiCPt6EnV+j4ueKoi0+QORVg2RuRC2PaQ== leven@^3.1.0: version "3.1.0" From 5998c83b2adf3e92d30b5acf77a43f7d63fa46ed Mon Sep 17 00:00:00 2001 From: Dessalines Date: Fri, 12 Mar 2021 15:18:03 -0500 Subject: [PATCH 13/18] Only sending private message if its a local user. --- crates/api/src/comment.rs | 4 +- crates/api/src/local_user.rs | 114 +++++++++++------- crates/api/src/post.rs | 4 +- crates/api_structs/src/lib.rs | 10 +- .../src/activities/receive/private_message.rs | 39 +++++- crates/websocket/src/handlers.rs | 7 +- crates/websocket/src/messages.rs | 2 +- 7 files changed, 120 insertions(+), 60 deletions(-) diff --git a/crates/api/src/comment.rs b/crates/api/src/comment.rs index aff39e024..e59eefd9c 100644 --- a/crates/api/src/comment.rs +++ b/crates/api/src/comment.rs @@ -754,7 +754,7 @@ impl Perform for CreateCommentReport { context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::CreateCommentReport, response: res.clone(), - recipient_id: local_user_view.person.id, + local_recipient_id: local_user_view.person.id, websocket_id, }); @@ -856,7 +856,7 @@ impl Perform for ListCommentReports { context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::ListCommentReports, response: res.clone(), - recipient_id: local_user_view.person.id, + local_recipient_id: local_user_view.person.id, websocket_id, }); diff --git a/crates/api/src/local_user.rs b/crates/api/src/local_user.rs index 9b5611f2c..b3ec92825 100644 --- a/crates/api/src/local_user.rs +++ b/crates/api/src/local_user.rs @@ -1141,21 +1141,6 @@ impl Perform for CreatePrivateMessage { .send_create(&local_user_view.person, context) .await?; - // Send notifications to the recipient - let recipient_id = data.recipient_id; - let recipient = blocking(context.pool(), move |conn| { - LocalUserView::read_person(conn, recipient_id) - }) - .await??; - if recipient.local_user.send_notifications_to_email { - send_email_to_user( - recipient, - "Private Message from", - "Private Message", - &content_slurs_removed, - ); - } - let private_message_view = blocking(context.pool(), move |conn| { PrivateMessageView::read(conn, inserted_private_message.id) }) @@ -1165,12 +1150,30 @@ impl Perform for CreatePrivateMessage { private_message_view, }; - context.chat_server().do_send(SendUserRoomMessage { - op: UserOperation::CreatePrivateMessage, - response: res.clone(), - recipient_id, - websocket_id, - }); + // Send notifications to the local recipient, if one exists + let recipient_id = data.recipient_id; + if let Ok(local_recipient) = blocking(context.pool(), move |conn| { + LocalUserView::read_person(conn, recipient_id) + }) + .await? + { + if local_recipient.local_user.send_notifications_to_email { + send_email_to_user( + &local_recipient, + "Private Message from", + "Private Message", + &content_slurs_removed, + ); + } + + let local_recipient_id = local_recipient.local_user.id; + context.chat_server().do_send(SendUserRoomMessage { + op: UserOperation::CreatePrivateMessage, + response: res.clone(), + local_recipient_id, + websocket_id, + }); + } Ok(res) } @@ -1220,18 +1223,26 @@ impl Perform for EditPrivateMessage { PrivateMessageView::read(conn, private_message_id) }) .await??; - let recipient_id = private_message_view.recipient.id; let res = PrivateMessageResponse { private_message_view, }; - context.chat_server().do_send(SendUserRoomMessage { - op: UserOperation::EditPrivateMessage, - response: res.clone(), - recipient_id, - websocket_id, - }); + // Send notifications to the local recipient, if one exists + let recipient_id = orig_private_message.recipient_id; + if let Ok(local_recipient) = blocking(context.pool(), move |conn| { + LocalUserView::read_person(conn, recipient_id) + }) + .await? + { + let local_recipient_id = local_recipient.local_user.id; + context.chat_server().do_send(SendUserRoomMessage { + op: UserOperation::EditPrivateMessage, + response: res.clone(), + local_recipient_id, + websocket_id, + }); + } Ok(res) } @@ -1287,18 +1298,26 @@ impl Perform for DeletePrivateMessage { PrivateMessageView::read(conn, private_message_id) }) .await??; - let recipient_id = private_message_view.recipient.id; let res = PrivateMessageResponse { private_message_view, }; - context.chat_server().do_send(SendUserRoomMessage { - op: UserOperation::DeletePrivateMessage, - response: res.clone(), - recipient_id, - websocket_id, - }); + // Send notifications to the local recipient, if one exists + let recipient_id = orig_private_message.recipient_id; + if let Ok(local_recipient) = blocking(context.pool(), move |conn| { + LocalUserView::read_person(conn, recipient_id) + }) + .await? + { + let local_recipient_id = local_recipient.local_user.id; + context.chat_server().do_send(SendUserRoomMessage { + op: UserOperation::DeletePrivateMessage, + response: res.clone(), + local_recipient_id, + websocket_id, + }); + } Ok(res) } @@ -1339,24 +1358,31 @@ impl Perform for MarkPrivateMessageAsRead { }; // No need to send an apub update - let private_message_id = data.private_message_id; let private_message_view = blocking(context.pool(), move |conn| { PrivateMessageView::read(conn, private_message_id) }) .await??; - let recipient_id = private_message_view.recipient.id; let res = PrivateMessageResponse { private_message_view, }; - context.chat_server().do_send(SendUserRoomMessage { - op: UserOperation::MarkPrivateMessageAsRead, - response: res.clone(), - recipient_id, - websocket_id, - }); + // Send notifications to the local recipient, if one exists + let recipient_id = orig_private_message.recipient_id; + if let Ok(local_recipient) = blocking(context.pool(), move |conn| { + LocalUserView::read_person(conn, recipient_id) + }) + .await? + { + let local_recipient_id = local_recipient.local_user.id; + context.chat_server().do_send(SendUserRoomMessage { + op: UserOperation::MarkPrivateMessageAsRead, + response: res.clone(), + local_recipient_id, + websocket_id, + }); + } Ok(res) } @@ -1441,7 +1467,7 @@ impl Perform for GetReportCount { context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::GetReportCount, response: res.clone(), - recipient_id: local_user_view.person.id, + local_recipient_id: local_user_view.person.id, websocket_id, }); diff --git a/crates/api/src/post.rs b/crates/api/src/post.rs index 5515575e6..9911f6722 100644 --- a/crates/api/src/post.rs +++ b/crates/api/src/post.rs @@ -844,7 +844,7 @@ impl Perform for CreatePostReport { context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::CreatePostReport, response: res.clone(), - recipient_id: local_user_view.person.id, + local_recipient_id: local_user_view.local_user.id, websocket_id, }); @@ -945,7 +945,7 @@ impl Perform for ListPostReports { context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::ListPostReports, response: res.clone(), - recipient_id: local_user_view.person.id, + local_recipient_id: local_user_view.local_user.id, websocket_id, }); diff --git a/crates/api_structs/src/lib.rs b/crates/api_structs/src/lib.rs index e675d02ae..e0fab6b24 100644 --- a/crates/api_structs/src/lib.rs +++ b/crates/api_structs/src/lib.rs @@ -105,7 +105,7 @@ fn do_send_local_notifs( // Send an email to those local users that have notifications on if do_send_email && mention_user_view.local_user.send_notifications_to_email { send_email_to_user( - mention_user_view, + &mention_user_view, "Mentioned by", "Person Mention", &comment.content, @@ -125,7 +125,7 @@ fn do_send_local_notifs( if do_send_email && parent_user_view.local_user.send_notifications_to_email { send_email_to_user( - parent_user_view, + &parent_user_view, "Reply from", "Comment Reply", &comment.content, @@ -143,7 +143,7 @@ fn do_send_local_notifs( if do_send_email && parent_user_view.local_user.send_notifications_to_email { send_email_to_user( - parent_user_view, + &parent_user_view, "Reply from", "Post Reply", &comment.content, @@ -157,7 +157,7 @@ fn do_send_local_notifs( } pub fn send_email_to_user( - local_user_view: LocalUserView, + local_user_view: &LocalUserView, subject_text: &str, body_text: &str, comment_content: &str, @@ -166,7 +166,7 @@ pub fn send_email_to_user( return; } - if let Some(user_email) = local_user_view.local_user.email { + if let Some(user_email) = &local_user_view.local_user.email { let subject = &format!( "{} - {} {}", subject_text, diff --git a/crates/apub/src/activities/receive/private_message.rs b/crates/apub/src/activities/receive/private_message.rs index 45d4a689d..daae54d91 100644 --- a/crates/apub/src/activities/receive/private_message.rs +++ b/crates/apub/src/activities/receive/private_message.rs @@ -16,7 +16,7 @@ use anyhow::{anyhow, Context}; use lemmy_api_structs::{blocking, person::PrivateMessageResponse}; use lemmy_db_queries::source::private_message::PrivateMessage_; use lemmy_db_schema::source::private_message::PrivateMessage; -use lemmy_db_views::private_message_view::PrivateMessageView; +use lemmy_db_views::{local_user_view::LocalUserView, private_message_view::PrivateMessageView}; use lemmy_utils::{location_info, LemmyError}; use lemmy_websocket::{messages::SendUserRoomMessage, LemmyContext, UserOperation}; use url::Url; @@ -50,12 +50,19 @@ pub(crate) async fn receive_create_private_message( private_message_view: message, }; + // Send notifications to the local recipient, if one exists let recipient_id = res.private_message_view.recipient.id; + let local_recipient_id = blocking(context.pool(), move |conn| { + LocalUserView::read_person(conn, recipient_id) + }) + .await?? + .local_user + .id; context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::CreatePrivateMessage, response: res, - recipient_id, + local_recipient_id, websocket_id: None, }); @@ -91,11 +98,17 @@ pub(crate) async fn receive_update_private_message( }; let recipient_id = res.private_message_view.recipient.id; + let local_recipient_id = blocking(context.pool(), move |conn| { + LocalUserView::read_person(conn, recipient_id) + }) + .await?? + .local_user + .id; context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::EditPrivateMessage, response: res, - recipient_id, + local_recipient_id, websocket_id: None, }); @@ -123,11 +136,19 @@ pub(crate) async fn receive_delete_private_message( let res = PrivateMessageResponse { private_message_view: message, }; + let recipient_id = res.private_message_view.recipient.id; + let local_recipient_id = blocking(context.pool(), move |conn| { + LocalUserView::read_person(conn, recipient_id) + }) + .await?? + .local_user + .id; + context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::EditPrivateMessage, response: res, - recipient_id, + local_recipient_id, websocket_id: None, }); @@ -160,11 +181,19 @@ pub(crate) async fn receive_undo_delete_private_message( let res = PrivateMessageResponse { private_message_view: message, }; + let recipient_id = res.private_message_view.recipient.id; + let local_recipient_id = blocking(context.pool(), move |conn| { + LocalUserView::read_person(conn, recipient_id) + }) + .await?? + .local_user + .id; + context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::EditPrivateMessage, response: res, - recipient_id, + local_recipient_id, websocket_id: None, }); diff --git a/crates/websocket/src/handlers.rs b/crates/websocket/src/handlers.rs index 7198fcb78..ccc2d099c 100644 --- a/crates/websocket/src/handlers.rs +++ b/crates/websocket/src/handlers.rs @@ -102,7 +102,12 @@ where fn handle(&mut self, msg: SendUserRoomMessage, _: &mut Context) { self - .send_user_room_message(&msg.op, &msg.response, msg.recipient_id, msg.websocket_id) + .send_user_room_message( + &msg.op, + &msg.response, + msg.local_recipient_id, + msg.websocket_id, + ) .ok(); } } diff --git a/crates/websocket/src/messages.rs b/crates/websocket/src/messages.rs index e66ffe110..675563f37 100644 --- a/crates/websocket/src/messages.rs +++ b/crates/websocket/src/messages.rs @@ -50,7 +50,7 @@ pub struct SendAllMessage { pub struct SendUserRoomMessage { pub op: UserOperation, pub response: Response, - pub recipient_id: LocalUserId, + pub local_recipient_id: LocalUserId, pub websocket_id: Option, } From 8ee624a5429ab1f95e3d5efdff0b6a1cbfb506f8 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Mon, 15 Mar 2021 14:02:27 -0400 Subject: [PATCH 14/18] Some changes - Changing claim name to local_user_id to facilitate logout. - Changing AddAdmin back to using person_id --- crates/api/src/lib.rs | 4 ++-- crates/api/src/local_user.rs | 4 ++-- crates/api_structs/src/person.rs | 2 +- crates/db_queries/src/source/local_user.rs | 6 +++--- crates/routes/src/feeds.rs | 9 ++++++--- crates/utils/src/claims.rs | 4 ++-- 6 files changed, 16 insertions(+), 13 deletions(-) diff --git a/crates/api/src/lib.rs b/crates/api/src/lib.rs index 65d97c4a4..21afcee24 100644 --- a/crates/api/src/lib.rs +++ b/crates/api/src/lib.rs @@ -103,7 +103,7 @@ pub(crate) async fn get_local_user_view_from_jwt( Ok(claims) => claims.claims, Err(_e) => return Err(ApiError::err("not_logged_in").into()), }; - let local_user_id = claims.id; + let local_user_id = claims.local_user_id; let local_user_view = blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??; // Check for a site ban @@ -131,7 +131,7 @@ pub(crate) async fn get_local_user_settings_view_from_jwt( Ok(claims) => claims.claims, Err(_e) => return Err(ApiError::err("not_logged_in").into()), }; - let local_user_id = claims.id; + let local_user_id = claims.local_user_id; let local_user_view = blocking(pool, move |conn| { LocalUserSettingsView::read(conn, local_user_id) }) diff --git a/crates/api/src/local_user.rs b/crates/api/src/local_user.rs index b3ec92825..50cc028bc 100644 --- a/crates/api/src/local_user.rs +++ b/crates/api/src/local_user.rs @@ -650,9 +650,9 @@ impl Perform for AddAdmin { is_admin(&local_user_view)?; let added = data.added; - let added_local_user_id = data.local_user_id; + let added_person_id = data.person_id; let added_admin = match blocking(context.pool(), move |conn| { - LocalUser::add_admin(conn, added_local_user_id, added) + LocalUser::add_admin(conn, added_person_id, added) }) .await? { diff --git a/crates/api_structs/src/person.rs b/crates/api_structs/src/person.rs index 53e6d9f8d..5555bb4b5 100644 --- a/crates/api_structs/src/person.rs +++ b/crates/api_structs/src/person.rs @@ -107,7 +107,7 @@ pub struct MarkAllAsRead { #[derive(Deserialize)] pub struct AddAdmin { - pub local_user_id: i32, + pub person_id: i32, pub added: bool, pub auth: String, } diff --git a/crates/db_queries/src/source/local_user.rs b/crates/db_queries/src/source/local_user.rs index 4ca557c59..a3d2b85b1 100644 --- a/crates/db_queries/src/source/local_user.rs +++ b/crates/db_queries/src/source/local_user.rs @@ -69,7 +69,7 @@ pub trait LocalUser_ { local_user_id: i32, new_password: &str, ) -> Result; - fn add_admin(conn: &PgConnection, local_user_id: i32, added: bool) -> Result; + fn add_admin(conn: &PgConnection, person_id: i32, added: bool) -> Result; } impl LocalUser_ for LocalUser { @@ -94,8 +94,8 @@ impl LocalUser_ for LocalUser { .get_result::(conn) } - fn add_admin(conn: &PgConnection, local_user_id: i32, added: bool) -> Result { - diesel::update(local_user.find(local_user_id)) + fn add_admin(conn: &PgConnection, for_person_id: i32, added: bool) -> Result { + diesel::update(local_user.filter(person_id.eq(for_person_id))) .set(admin.eq(added)) .get_result::(conn) } diff --git a/crates/routes/src/feeds.rs b/crates/routes/src/feeds.rs index 568107984..30f5f9639 100644 --- a/crates/routes/src/feeds.rs +++ b/crates/routes/src/feeds.rs @@ -5,10 +5,11 @@ use diesel::PgConnection; use lemmy_api_structs::blocking; use lemmy_db_queries::{ source::{community::Community_, person::Person_}, + Crud, ListingType, SortType, }; -use lemmy_db_schema::source::{community::Community, person::Person}; +use lemmy_db_schema::source::{community::Community, local_user::LocalUser, person::Person}; use lemmy_db_views::{ comment_view::{CommentQueryBuilder, CommentView}, post_view::{PostQueryBuilder, PostView}, @@ -223,7 +224,8 @@ fn get_feed_front( jwt: String, ) -> Result { let site_view = SiteView::read(&conn)?; - let person_id = Claims::decode(&jwt)?.claims.id; + let local_user_id = Claims::decode(&jwt)?.claims.local_user_id; + let person_id = LocalUser::read(&conn, local_user_id)?.person_id; let posts = PostQueryBuilder::create(&conn) .listing_type(&ListingType::Subscribed) @@ -249,7 +251,8 @@ fn get_feed_front( fn get_feed_inbox(conn: &PgConnection, jwt: String) -> Result { let site_view = SiteView::read(&conn)?; - let person_id = Claims::decode(&jwt)?.claims.id; + let local_user_id = Claims::decode(&jwt)?.claims.local_user_id; + let person_id = LocalUser::read(&conn, local_user_id)?.person_id; let sort = SortType::New; diff --git a/crates/utils/src/claims.rs b/crates/utils/src/claims.rs index 3529f5f19..e84f34f91 100644 --- a/crates/utils/src/claims.rs +++ b/crates/utils/src/claims.rs @@ -6,7 +6,7 @@ type Jwt = String; #[derive(Debug, Serialize, Deserialize)] pub struct Claims { - pub id: i32, + pub local_user_id: i32, pub iss: String, } @@ -25,7 +25,7 @@ impl Claims { pub fn jwt(local_user_id: i32, hostname: String) -> Result { let my_claims = Claims { - id: local_user_id, + local_user_id, iss: hostname, }; encode( From b9f483bc27b84db11c899b84897194b92981e50b Mon Sep 17 00:00:00 2001 From: Dessalines Date: Mon, 15 Mar 2021 14:50:50 -0400 Subject: [PATCH 15/18] Version 0.10.0-rc.5 --- ansible/VERSION | 2 +- crates/utils/src/version.rs | 2 +- docker/dev/docker-compose.yml | 2 +- docker/federation/docker-compose.yml | 10 +++++----- docker/prod/docker-compose.yml | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/ansible/VERSION b/ansible/VERSION index 7e310bae1..4bcce4252 100644 --- a/ansible/VERSION +++ b/ansible/VERSION @@ -1 +1 @@ -0.9.9 +0.10.0-rc.5 diff --git a/crates/utils/src/version.rs b/crates/utils/src/version.rs index a3074cb92..7e3d00073 100644 --- a/crates/utils/src/version.rs +++ b/crates/utils/src/version.rs @@ -1 +1 @@ -pub const VERSION: &str = "0.9.9"; +pub const VERSION: &str = "0.10.0-rc.5"; diff --git a/docker/dev/docker-compose.yml b/docker/dev/docker-compose.yml index a23f1e0ed..25cf2e13f 100644 --- a/docker/dev/docker-compose.yml +++ b/docker/dev/docker-compose.yml @@ -17,7 +17,7 @@ services: - iframely lemmy-ui: - image: dessalines/lemmy-ui:0.9.9 + image: dessalines/lemmy-ui:0.10.0-rc.5 ports: - "1235:1234" restart: always diff --git a/docker/federation/docker-compose.yml b/docker/federation/docker-compose.yml index c40de9022..899d72baf 100644 --- a/docker/federation/docker-compose.yml +++ b/docker/federation/docker-compose.yml @@ -29,7 +29,7 @@ services: - ./volumes/pictrs_alpha:/mnt lemmy-alpha-ui: - image: dessalines/lemmy-ui:0.9.9 + image: dessalines/lemmy-ui:0.10.0-rc.5 environment: - LEMMY_INTERNAL_HOST=lemmy-alpha:8541 - LEMMY_EXTERNAL_HOST=localhost:8541 @@ -58,7 +58,7 @@ services: - ./volumes/postgres_alpha:/var/lib/postgresql/data lemmy-beta-ui: - image: dessalines/lemmy-ui:0.9.9 + image: dessalines/lemmy-ui:0.10.0-rc.5 environment: - LEMMY_INTERNAL_HOST=lemmy-beta:8551 - LEMMY_EXTERNAL_HOST=localhost:8551 @@ -87,7 +87,7 @@ services: - ./volumes/postgres_beta:/var/lib/postgresql/data lemmy-gamma-ui: - image: dessalines/lemmy-ui:0.9.9 + image: dessalines/lemmy-ui:0.10.0-rc.5 environment: - LEMMY_INTERNAL_HOST=lemmy-gamma:8561 - LEMMY_EXTERNAL_HOST=localhost:8561 @@ -117,7 +117,7 @@ services: # An instance with only an allowlist for beta lemmy-delta-ui: - image: dessalines/lemmy-ui:0.9.9 + image: dessalines/lemmy-ui:0.10.0-rc.5 environment: - LEMMY_INTERNAL_HOST=lemmy-delta:8571 - LEMMY_EXTERNAL_HOST=localhost:8571 @@ -147,7 +147,7 @@ services: # An instance who has a blocklist, with lemmy-alpha blocked lemmy-epsilon-ui: - image: dessalines/lemmy-ui:0.9.9 + image: dessalines/lemmy-ui:0.10.0-rc.5 environment: - LEMMY_INTERNAL_HOST=lemmy-epsilon:8581 - LEMMY_EXTERNAL_HOST=localhost:8581 diff --git a/docker/prod/docker-compose.yml b/docker/prod/docker-compose.yml index e219bdef8..296c4be94 100644 --- a/docker/prod/docker-compose.yml +++ b/docker/prod/docker-compose.yml @@ -12,7 +12,7 @@ services: restart: always lemmy: - image: dessalines/lemmy:0.9.9 + image: dessalines/lemmy:0.10.0-rc.5 ports: - "127.0.0.1:8536:8536" restart: always @@ -26,7 +26,7 @@ services: - iframely lemmy-ui: - image: dessalines/lemmy-ui:0.9.9 + image: dessalines/lemmy-ui:0.10.0-rc.5 ports: - "127.0.0.1:1235:1234" restart: always From 270ce539bf3ebbd85a7929edacbc9ffb52e5ea26 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Mon, 15 Mar 2021 18:18:50 -0400 Subject: [PATCH 16/18] Removing some TODOS. --- crates/api/src/lib.rs | 9 --------- crates/api_structs/src/lib.rs | 2 -- 2 files changed, 11 deletions(-) diff --git a/crates/api/src/lib.rs b/crates/api/src/lib.rs index 21afcee24..aebabde8a 100644 --- a/crates/api/src/lib.rs +++ b/crates/api/src/lib.rs @@ -72,15 +72,6 @@ pub(crate) async fn is_mod_or_admin( Ok(()) } -// TODO this probably isn't necessary anymore -// pub async fn is_admin(pool: &DbPool, person_id: i32) -> Result<(), LemmyError> { -// let user = blocking(pool, move |conn| LocalUser::read(conn, person_id)).await??; -// if !user.admin { -// return Err(ApiError::err("not_an_admin").into()); -// } -// Ok(()) -// } - pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> { if !local_user_view.local_user.admin { return Err(ApiError::err("not_an_admin").into()); diff --git a/crates/api_structs/src/lib.rs b/crates/api_structs/src/lib.rs index e0fab6b24..e25b05791 100644 --- a/crates/api_structs/src/lib.rs +++ b/crates/api_structs/src/lib.rs @@ -68,7 +68,6 @@ pub async fn send_local_notifs( Ok(ids) } -// TODO should this really use person_ids as recipient ids? or local_user_ids ? fn do_send_local_notifs( conn: &PgConnection, mentions: &[MentionData], @@ -85,7 +84,6 @@ fn do_send_local_notifs( .filter(|m| m.is_local() && m.name.ne(&person.name)) .collect::>() { - // TODO do a local user fetch if let Ok(mention_user_view) = LocalUserView::read_from_name(&conn, &mention.name) { // TODO // At some point, make it so you can't tag the parent creator either From 99e5a4d1c39f25f94c623964d43dea57d3c42bbc Mon Sep 17 00:00:00 2001 From: Dessalines Date: Thu, 18 Mar 2021 10:52:25 -0400 Subject: [PATCH 17/18] Moving send email check inside function. --- crates/api/src/local_user.rs | 14 ++++++-------- crates/api_structs/src/lib.rs | 8 ++++---- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/crates/api/src/local_user.rs b/crates/api/src/local_user.rs index 50cc028bc..bca48ffaf 100644 --- a/crates/api/src/local_user.rs +++ b/crates/api/src/local_user.rs @@ -1157,14 +1157,12 @@ impl Perform for CreatePrivateMessage { }) .await? { - if local_recipient.local_user.send_notifications_to_email { - send_email_to_user( - &local_recipient, - "Private Message from", - "Private Message", - &content_slurs_removed, - ); - } + send_email_to_user( + &local_recipient, + "Private Message from", + "Private Message", + &content_slurs_removed, + ); let local_recipient_id = local_recipient.local_user.id; context.chat_server().do_send(SendUserRoomMessage { diff --git a/crates/api_structs/src/lib.rs b/crates/api_structs/src/lib.rs index e25b05791..ea3a05566 100644 --- a/crates/api_structs/src/lib.rs +++ b/crates/api_structs/src/lib.rs @@ -101,7 +101,7 @@ fn do_send_local_notifs( PersonMention::create(&conn, &user_mention_form).ok(); // Send an email to those local users that have notifications on - if do_send_email && mention_user_view.local_user.send_notifications_to_email { + if do_send_email { send_email_to_user( &mention_user_view, "Mentioned by", @@ -121,7 +121,7 @@ fn do_send_local_notifs( { recipient_ids.push(parent_user_view.local_user.id); - if do_send_email && parent_user_view.local_user.send_notifications_to_email { + if do_send_email { send_email_to_user( &parent_user_view, "Reply from", @@ -139,7 +139,7 @@ fn do_send_local_notifs( if let Ok(parent_user_view) = LocalUserView::read_person(&conn, post.creator_id) { recipient_ids.push(parent_user_view.local_user.id); - if do_send_email && parent_user_view.local_user.send_notifications_to_email { + if do_send_email { send_email_to_user( &parent_user_view, "Reply from", @@ -160,7 +160,7 @@ pub fn send_email_to_user( body_text: &str, comment_content: &str, ) { - if local_user_view.person.banned { + if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email { return; } From 5899b89ef2ee4fd2bce972ee890cd3e7d2554c20 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Thu, 18 Mar 2021 10:59:17 -0400 Subject: [PATCH 18/18] Adding some comments to notifs. --- crates/api_structs/src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/api_structs/src/lib.rs b/crates/api_structs/src/lib.rs index ea3a05566..462f521b4 100644 --- a/crates/api_structs/src/lib.rs +++ b/crates/api_structs/src/lib.rs @@ -116,7 +116,9 @@ fn do_send_local_notifs( match comment.parent_id { Some(parent_id) => { if let Ok(parent_comment) = Comment::read(&conn, parent_id) { + // Don't send a notif to yourself if parent_comment.creator_id != person.id { + // Get the parent commenter local_user if let Ok(parent_user_view) = LocalUserView::read_person(&conn, parent_comment.creator_id) { recipient_ids.push(parent_user_view.local_user.id);