From c3efb9f7cfb9f761489d119e8af78f15aa960d89 Mon Sep 17 00:00:00 2001 From: Dessalines <tyhou13@gmx.com> Date: Thu, 18 Mar 2021 16:25:21 -0400 Subject: [PATCH] Strictly typing DB id fields. Fixes #1498 --- Cargo.lock | 222 +++++++++++------- crates/api/src/comment.rs | 21 +- crates/api/src/community.rs | 3 +- crates/api/src/lib.rs | 34 +-- crates/api/src/local_user.rs | 80 ++++--- crates/api_structs/src/comment.rs | 25 +- crates/api_structs/src/community.rs | 23 +- crates/api_structs/src/lib.rs | 17 +- crates/api_structs/src/person.rs | 23 +- crates/api_structs/src/post.rs | 25 +- crates/api_structs/src/site.rs | 9 +- crates/api_structs/src/websocket.rs | 7 +- crates/apub/src/http/comment.rs | 4 +- crates/apub/src/http/post.rs | 4 +- crates/apub/src/inbox/community_inbox.rs | 11 +- crates/apub/src/objects/comment.rs | 13 +- crates/apub/src/objects/mod.rs | 8 +- .../src/aggregates/comment_aggregates.rs | 6 +- .../src/aggregates/community_aggregates.rs | 6 +- .../src/aggregates/person_aggregates.rs | 6 +- .../src/aggregates/post_aggregates.rs | 6 +- crates/db_queries/src/lib.rs | 68 +++--- crates/db_queries/src/source/activity.rs | 2 +- crates/db_queries/src/source/comment.rs | 65 +++-- .../db_queries/src/source/comment_report.rs | 13 +- crates/db_queries/src/source/community.rs | 56 +++-- crates/db_queries/src/source/local_user.rs | 22 +- crates/db_queries/src/source/moderator.rs | 18 +- .../src/source/password_reset_request.rs | 12 +- crates/db_queries/src/source/person.rs | 21 +- .../db_queries/src/source/person_mention.rs | 16 +- crates/db_queries/src/source/post.rs | 85 +++++-- crates/db_queries/src/source/post_report.rs | 14 +- .../db_queries/src/source/private_message.rs | 28 +-- crates/db_queries/src/source/site.rs | 8 +- crates/db_schema/Cargo.toml | 1 + crates/db_schema/src/lib.rs | 43 ++++ crates/db_schema/src/source/comment.rs | 45 ++-- crates/db_schema/src/source/comment_report.rs | 12 +- crates/db_schema/src/source/community.rs | 36 +-- crates/db_schema/src/source/local_user.rs | 12 +- crates/db_schema/src/source/moderator.rs | 106 +++++---- .../src/source/password_reset_request.rs | 6 +- crates/db_schema/src/source/person.rs | 13 +- crates/db_schema/src/source/person_mention.rs | 18 +- crates/db_schema/src/source/post.rs | 37 +-- crates/db_schema/src/source/post_report.rs | 12 +- .../db_schema/src/source/private_message.rs | 12 +- crates/db_schema/src/source/site.rs | 6 +- crates/db_views/src/comment_report_view.rs | 10 +- crates/db_views/src/comment_view.rs | 34 +-- crates/db_views/src/local_user_view.rs | 8 +- crates/db_views/src/post_report_view.rs | 10 +- crates/db_views/src/post_view.rs | 25 +- crates/db_views/src/private_message_view.rs | 8 +- .../src/community_follower_view.rs | 6 +- .../src/community_moderator_view.rs | 6 +- .../src/community_person_ban_view.rs | 6 +- crates/db_views_actor/src/community_view.rs | 27 ++- .../db_views_actor/src/person_mention_view.rs | 18 +- crates/db_views_actor/src/person_view.rs | 5 +- .../src/mod_add_community_view.rs | 6 +- crates/db_views_moderator/src/mod_add_view.rs | 3 +- .../src/mod_ban_from_community_view.rs | 6 +- crates/db_views_moderator/src/mod_ban_view.rs | 3 +- .../src/mod_lock_post_view.rs | 6 +- .../src/mod_remove_comment_view.rs | 6 +- .../src/mod_remove_community_view.rs | 3 +- .../src/mod_remove_post_view.rs | 6 +- .../src/mod_sticky_post_view.rs | 6 +- crates/routes/src/feeds.rs | 9 +- crates/utils/src/lib.rs | 14 +- crates/utils/src/rate_limit/mod.rs | 3 +- crates/utils/src/rate_limit/rate_limiter.rs | 6 +- crates/utils/src/utils.rs | 20 +- crates/websocket/src/chat_server.rs | 15 +- crates/websocket/src/handlers.rs | 3 +- crates/websocket/src/messages.rs | 3 +- crates/websocket/src/routes.rs | 6 +- 79 files changed, 974 insertions(+), 653 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 959aec10..0821ee33 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -144,8 +144,8 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ca8ce00b267af8ccebbd647de0d61e0674b6e61185cc7a592ff88772bed655" dependencies = [ - "quote", - "syn", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -333,9 +333,9 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad26f77093333e0e7c6ffe54ebe3582d908a104e448723eec6d43d08b07143fb" dependencies = [ - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -344,9 +344,9 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b95aceadaf327f18f0df5962fedc1bde2f870566a0b9f65c89508a3b1f79334c" dependencies = [ - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -406,9 +406,9 @@ version = "0.1.42" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d3a45e77e34375a7923b1e8febb049bb011f064714a8e17a1a616fef01da13d" dependencies = [ - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -916,10 +916,10 @@ checksum = "f0c960ae2da4de88a91b2d920c2a7233b400bc33cb28453a2987822d8392519b" dependencies = [ "fnv", "ident_case", - "proc-macro2", - "quote", + "proc-macro2 1.0.24", + "quote 1.0.8", "strsim", - "syn", + "syn 1.0.60", ] [[package]] @@ -929,8 +929,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9b5a2f4ac4969822c62224815d069952656cadc7084fdca9751e6d959189b72" dependencies = [ "darling_core", - "quote", - "syn", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -951,9 +951,9 @@ checksum = "a2658621297f2cf68762a6f7dc0bb7e1ff2cfd6583daef8ee0fed6f7ec468ec0" dependencies = [ "darling", "derive_builder_core", - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -963,9 +963,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2791ea3e372c8495c0bc2033991d76b512cd799d07491fbd6890124db9458bef" dependencies = [ "darling", - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -974,9 +974,9 @@ version = "0.99.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41cb0e6161ad61ed084a36ba71fbba9e3ac5aee3606fb607fe08da6acbcf3d8c" dependencies = [ - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -1003,15 +1003,27 @@ dependencies = [ "serde_json", ] +[[package]] +name = "diesel-derive-newtype" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e844e8e6f65dcf27aa0b97d4234f974d93dfbf56816033d71b5e0c7eb701709f" +dependencies = [ + "diesel", + "proc-macro2 0.4.30", + "quote 0.6.13", + "syn 0.14.9", +] + [[package]] name = "diesel_derives" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45f5098f628d02a7a0f68ddba586fb61e80edec3bdc1be3b921f4ceec60858d3" dependencies = [ - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -1085,9 +1097,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c5f0096a91d210159eceb2ff5e1c4da18388a170e1e3ce948aac9c8fdbbf595" dependencies = [ "heck", - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -1253,9 +1265,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c287d25add322d9f9abdcdc5927ca398917996600182178774032e9f8258fedd" dependencies = [ "proc-macro-hack", - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -1852,6 +1864,7 @@ version = "0.1.0" dependencies = [ "chrono", "diesel", + "diesel-derive-newtype", "log", "serde", "serde_json", @@ -2144,9 +2157,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "209d075476da2e63b4b29e72a2ef627b840589588e71400a25e3565c4f849d07" dependencies = [ "proc-macro-error", - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -2165,9 +2178,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9753f12909fd8d923f75ae5c3258cae1ed3c8ec052e1b38c93c21a6d157f789c" dependencies = [ "migrations_internals", - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -2475,9 +2488,9 @@ checksum = "99b8db626e31e5b81787b9783425769681b347011cc59471e33ea46d2ea0cf55" dependencies = [ "pest", "pest_meta", - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -2515,9 +2528,9 @@ version = "0.4.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65ad2ae56b6abe3a1ee25f15ee605bacadb9a764edaba9c2bf4103800d4a1895" dependencies = [ - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -2526,9 +2539,9 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "caa25a6393f22ce819b0f50e0be89287292fda8d425be38ee0ca14c4931d9e71" dependencies = [ - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -2589,9 +2602,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" dependencies = [ "proc-macro-error-attr", - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", "version_check", ] @@ -2601,8 +2614,8 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" dependencies = [ - "proc-macro2", - "quote", + "proc-macro2 1.0.24", + "quote 1.0.8", "version_check", ] @@ -2618,13 +2631,22 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc881b2c22681370c6a780e47af9840ef841837bc98118431d4e1868bd0c1086" +[[package]] +name = "proc-macro2" +version = "0.4.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" +dependencies = [ + "unicode-xid 0.1.0", +] + [[package]] name = "proc-macro2" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" dependencies = [ - "unicode-xid", + "unicode-xid 0.2.1", ] [[package]] @@ -2643,13 +2665,22 @@ dependencies = [ "memchr", ] +[[package]] +name = "quote" +version = "0.6.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" +dependencies = [ + "proc-macro2 0.4.30", +] + [[package]] name = "quote" version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "991431c3519a3f36861882da93630ce66b52918dcf1b8e2fd66b397fc96f28df" dependencies = [ - "proc-macro2", + "proc-macro2 1.0.24", ] [[package]] @@ -3032,9 +3063,9 @@ version = "1.0.123" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9391c295d64fc0abb2c556bad848f33cb8296276b1ad2677d1ae1ace4f258f31" dependencies = [ - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -3078,9 +3109,9 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2acd6defeddb41eb60bb468f8825d0cfd0c2a76bc03bfd235b6a1dc4f6a1ad5" dependencies = [ - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -3211,11 +3242,11 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c87a60a40fccc84bef0652345bbbbbe20a605bf5d0ce81719fc476f5c03b50ef" dependencies = [ - "proc-macro2", - "quote", + "proc-macro2 1.0.24", + "quote 1.0.8", "serde", "serde_derive", - "syn", + "syn 1.0.60", ] [[package]] @@ -3225,13 +3256,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "58fa5ff6ad0d98d1ffa8cb115892b6e69d67799f6763e162a1c9db421dc22e11" dependencies = [ "base-x", - "proc-macro2", - "quote", + "proc-macro2 1.0.24", + "quote 1.0.8", "serde", "serde_derive", "serde_json", "sha1", - "syn", + "syn 1.0.60", ] [[package]] @@ -3259,9 +3290,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee8bc6b87a5112aeeab1f4a9f7ab634fe6cbefc4850006df31267f4cfb9e3149" dependencies = [ "heck", - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", +] + +[[package]] +name = "syn" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261ae9ecaa397c42b960649561949d69311f08eeaea86a65696e6e46517cf741" +dependencies = [ + "proc-macro2 0.4.30", + "quote 0.6.13", + "unicode-xid 0.1.0", ] [[package]] @@ -3270,9 +3312,9 @@ version = "1.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c700597eca8a5a762beb35753ef6b94df201c81cca676604f547495a0d7f0081" dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", + "proc-macro2 1.0.24", + "quote 1.0.8", + "unicode-xid 0.2.1", ] [[package]] @@ -3319,9 +3361,9 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9be73a2caec27583d0046ef3796c3794f868a5bc813db689eed00c7631275cd1" dependencies = [ - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", ] [[package]] @@ -3396,10 +3438,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5c3be1edfad6027c69f5491cf4cb310d1a71ecd6af742788c6ff8bced86b8fa" dependencies = [ "proc-macro-hack", - "proc-macro2", - "quote", + "proc-macro2 1.0.24", + "quote 1.0.8", "standback", - "syn", + "syn 1.0.60", ] [[package]] @@ -3635,6 +3677,12 @@ version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0d2e7be6ae3a5fa87eed5fb451aff96f2573d2694942e40543ae0bbe19c796" +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" + [[package]] name = "unicode-xid" version = "0.2.1" @@ -3731,9 +3779,9 @@ dependencies = [ "bumpalo", "lazy_static", "log", - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", "wasm-bindgen-shared", ] @@ -3755,7 +3803,7 @@ version = "0.2.70" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b8853882eef39593ad4174dd26fc9865a64e84026d223f63bb2c42affcbba2c" dependencies = [ - "quote", + "quote 1.0.8", "wasm-bindgen-macro-support", ] @@ -3765,9 +3813,9 @@ version = "0.2.70" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4133b5e7f2a531fa413b3a1695e925038a05a71cf67e87dafa295cb645a01385" dependencies = [ - "proc-macro2", - "quote", - "syn", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.60", "wasm-bindgen-backend", "wasm-bindgen-shared", ] diff --git a/crates/api/src/comment.rs b/crates/api/src/comment.rs index e59eefd9..4fd3f7b2 100644 --- a/crates/api/src/comment.rs +++ b/crates/api/src/comment.rs @@ -20,10 +20,14 @@ use lemmy_db_queries::{ Saveable, SortType, }; -use lemmy_db_schema::source::{comment::*, comment_report::*, moderator::*}; +use lemmy_db_schema::{ + source::{comment::*, comment_report::*, moderator::*}, + LocalUserId, +}; use lemmy_db_views::{ comment_report_view::{CommentReportQueryBuilder, CommentReportView}, comment_view::{CommentQueryBuilder, CommentView}, + local_user_view::LocalUserView, }; use lemmy_utils::{ utils::{remove_slurs, scrape_text_for_mentions}, @@ -579,7 +583,7 @@ impl Perform for CreateCommentLike { let data: &CreateCommentLike = &self; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; - let mut recipient_ids = Vec::new(); + let mut recipient_ids = Vec::<LocalUserId>::new(); // Don't do a downvote if site has downvotes disabled check_downvotes_enabled(data.score, context.pool()).await?; @@ -598,7 +602,14 @@ impl Perform for CreateCommentLike { .await?; // Add parent user to recipients - recipient_ids.push(orig_comment.get_recipient_id()); + let recipient_id = orig_comment.get_recipient_id(); + if let Ok(local_recipient) = blocking(context.pool(), move |conn| { + LocalUserView::read_person(conn, recipient_id) + }) + .await? + { + recipient_ids.push(local_recipient.local_user.id); + } let like_form = CommentLikeForm { comment_id: data.comment_id, @@ -754,7 +765,7 @@ impl Perform for CreateCommentReport { context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::CreateCommentReport, response: res.clone(), - local_recipient_id: local_user_view.person.id, + local_recipient_id: local_user_view.local_user.id, websocket_id, }); @@ -856,7 +867,7 @@ impl Perform for ListCommentReports { context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::ListCommentReports, response: res.clone(), - local_recipient_id: local_user_view.person.id, + local_recipient_id: local_user_view.local_user.id, websocket_id, }); diff --git a/crates/api/src/community.rs b/crates/api/src/community.rs index 53b99c22..f6ecbf12 100644 --- a/crates/api/src/community.rs +++ b/crates/api/src/community.rs @@ -35,6 +35,7 @@ use lemmy_db_queries::{ use lemmy_db_schema::{ naive_now, source::{comment::Comment, community::*, moderator::*, post::Post, site::*}, + PersonId, }; use lemmy_db_views::comment_view::CommentQueryBuilder; use lemmy_db_views_actor::{ @@ -241,7 +242,7 @@ impl Perform for EditCommunity { // Verify its a mod (only mods can edit it) let community_id = data.community_id; - let mods: Vec<i32> = blocking(context.pool(), move |conn| { + let mods: Vec<PersonId> = blocking(context.pool(), move |conn| { CommunityModeratorView::for_community(conn, community_id) .map(|v| v.into_iter().map(|m| m.moderator.id).collect()) }) diff --git a/crates/api/src/lib.rs b/crates/api/src/lib.rs index aebabde8..a2e9bfed 100644 --- a/crates/api/src/lib.rs +++ b/crates/api/src/lib.rs @@ -16,10 +16,16 @@ use lemmy_db_queries::{ Crud, DbPool, }; -use lemmy_db_schema::source::{ - community::{Community, CommunityModerator}, - post::Post, - site::Site, +use lemmy_db_schema::{ + source::{ + community::{Community, CommunityModerator}, + post::Post, + site::Site, + }, + CommunityId, + LocalUserId, + PersonId, + PostId, }; use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView}; use lemmy_db_views_actor::{ @@ -59,8 +65,8 @@ pub trait Perform { pub(crate) async fn is_mod_or_admin( pool: &DbPool, - person_id: i32, - community_id: i32, + person_id: PersonId, + community_id: CommunityId, ) -> Result<(), LemmyError> { let is_mod_or_admin = blocking(pool, move |conn| { CommunityView::is_mod_or_admin(conn, person_id, community_id) @@ -79,7 +85,7 @@ pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> { Ok(()) } -pub(crate) async fn get_post(post_id: i32, pool: &DbPool) -> Result<Post, LemmyError> { +pub(crate) async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> { match blocking(pool, move |conn| Post::read(conn, post_id)).await? { Ok(post) => Ok(post), Err(_e) => Err(ApiError::err("couldnt_find_post").into()), @@ -94,7 +100,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.local_user_id; + let local_user_id = LocalUserId(claims.local_user_id); let local_user_view = blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??; // Check for a site ban @@ -122,7 +128,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.local_user_id; + let local_user_id = LocalUserId(claims.local_user_id); let local_user_view = blocking(pool, move |conn| { LocalUserSettingsView::read(conn, local_user_id) }) @@ -147,8 +153,8 @@ pub(crate) async fn get_local_user_settings_view_from_jwt_opt( } pub(crate) async fn check_community_ban( - person_id: i32, - community_id: i32, + person_id: PersonId, + community_id: CommunityId, pool: &DbPool, ) -> Result<(), LemmyError> { let is_banned = @@ -178,10 +184,10 @@ pub(crate) async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result /// * `community_id` - optional community id to check for moderator privileges /// * `pool` - the diesel db pool pub(crate) async fn collect_moderated_communities( - person_id: i32, - community_id: Option<i32>, + person_id: PersonId, + community_id: Option<CommunityId>, pool: &DbPool, -) -> Result<Vec<i32>, LemmyError> { +) -> Result<Vec<CommunityId>, 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, person_id, community_id).await?; diff --git a/crates/api/src/local_user.rs b/crates/api/src/local_user.rs index bca48ffa..e9daa819 100644 --- a/crates/api/src/local_user.rs +++ b/crates/api/src/local_user.rs @@ -55,6 +55,7 @@ use lemmy_db_schema::{ private_message::*, site::*, }, + CommunityId, }; use lemmy_db_views::{ comment_report_view::CommentReportView, @@ -129,7 +130,7 @@ impl Perform for Login { // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(local_user_view.local_user.id, Settings::get().hostname())?, + jwt: Claims::jwt(local_user_view.local_user.id.0, Settings::get().hostname())?, }) } } @@ -271,39 +272,42 @@ impl Perform for Register { let main_community_keypair = generate_actor_keypair()?; // Create the main community if it doesn't exist - let main_community = - match blocking(context.pool(), move |conn| Community::read(conn, 2)).await? { - Ok(c) => c, - Err(_e) => { - let default_community_name = "main"; - let actor_id = generate_apub_endpoint(EndpointType::Community, default_community_name)?; - let community_form = CommunityForm { - name: default_community_name.to_string(), - title: "The Default Community".to_string(), - description: Some("The Default Community".to_string()), - nsfw: false, - creator_id: inserted_person.id, - removed: None, - deleted: None, - updated: None, - actor_id: Some(actor_id.to_owned()), - local: true, - private_key: Some(main_community_keypair.private_key), - public_key: Some(main_community_keypair.public_key), - last_refreshed_at: None, - published: None, - icon: None, - banner: None, - followers_url: Some(generate_followers_url(&actor_id)?), - inbox_url: Some(generate_inbox_url(&actor_id)?), - shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)), - }; - blocking(context.pool(), move |conn| { - Community::create(conn, &community_form) - }) - .await?? - } - }; + let main_community = match blocking(context.pool(), move |conn| { + Community::read(conn, CommunityId(2)) + }) + .await? + { + Ok(c) => c, + Err(_e) => { + let default_community_name = "main"; + let actor_id = generate_apub_endpoint(EndpointType::Community, default_community_name)?; + let community_form = CommunityForm { + name: default_community_name.to_string(), + title: "The Default Community".to_string(), + description: Some("The Default Community".to_string()), + nsfw: false, + creator_id: inserted_person.id, + removed: None, + deleted: None, + updated: None, + actor_id: Some(actor_id.to_owned()), + local: true, + private_key: Some(main_community_keypair.private_key), + public_key: Some(main_community_keypair.public_key), + last_refreshed_at: None, + published: None, + icon: None, + banner: None, + followers_url: Some(generate_followers_url(&actor_id)?), + inbox_url: Some(generate_inbox_url(&actor_id)?), + shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)), + }; + blocking(context.pool(), move |conn| { + Community::create(conn, &community_form) + }) + .await?? + } + }; // Sign them up for main community no matter what let community_follower_form = CommunityFollowerForm { @@ -332,7 +336,7 @@ impl Perform for Register { // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(inserted_local_user.id, Settings::get().hostname())?, + jwt: Claims::jwt(inserted_local_user.id.0, Settings::get().hostname())?, }) } } @@ -522,7 +526,7 @@ impl Perform for SaveUserSettings { // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(updated_local_user.id, Settings::get().hostname())?, + jwt: Claims::jwt(updated_local_user.id.0, Settings::get().hostname())?, }) } } @@ -1074,7 +1078,7 @@ impl Perform for PasswordChange { // Return the jwt Ok(LoginResponse { - jwt: Claims::jwt(updated_local_user.id, Settings::get().hostname())?, + jwt: Claims::jwt(updated_local_user.id.0, Settings::get().hostname())?, }) } } @@ -1465,7 +1469,7 @@ impl Perform for GetReportCount { context.chat_server().do_send(SendUserRoomMessage { op: UserOperation::GetReportCount, response: res.clone(), - local_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/comment.rs b/crates/api_structs/src/comment.rs index 71c26e11..f62c41aa 100644 --- a/crates/api_structs/src/comment.rs +++ b/crates/api_structs/src/comment.rs @@ -1,11 +1,12 @@ +use lemmy_db_schema::{CommentId, CommunityId, LocalUserId, PostId}; use lemmy_db_views::{comment_report_view::CommentReportView, comment_view::CommentView}; use serde::{Deserialize, Serialize}; #[derive(Deserialize)] pub struct CreateComment { pub content: String, - pub parent_id: Option<i32>, - pub post_id: i32, + pub parent_id: Option<CommentId>, + pub post_id: PostId, pub form_id: Option<String>, pub auth: String, } @@ -13,21 +14,21 @@ pub struct CreateComment { #[derive(Deserialize)] pub struct EditComment { pub content: String, - pub comment_id: i32, + pub comment_id: CommentId, pub form_id: Option<String>, pub auth: String, } #[derive(Deserialize)] pub struct DeleteComment { - pub comment_id: i32, + pub comment_id: CommentId, pub deleted: bool, pub auth: String, } #[derive(Deserialize)] pub struct RemoveComment { - pub comment_id: i32, + pub comment_id: CommentId, pub removed: bool, pub reason: Option<String>, pub auth: String, @@ -35,14 +36,14 @@ pub struct RemoveComment { #[derive(Deserialize)] pub struct MarkCommentAsRead { - pub comment_id: i32, + pub comment_id: CommentId, pub read: bool, pub auth: String, } #[derive(Deserialize)] pub struct SaveComment { - pub comment_id: i32, + pub comment_id: CommentId, pub save: bool, pub auth: String, } @@ -50,13 +51,13 @@ pub struct SaveComment { #[derive(Serialize, Clone)] pub struct CommentResponse { pub comment_view: CommentView, - pub recipient_ids: Vec<i32>, // TODO another way to do this? Maybe a UserMention belongs to Comment + pub recipient_ids: Vec<LocalUserId>, pub form_id: Option<String>, // An optional front end ID, to tell which is coming back } #[derive(Deserialize)] pub struct CreateCommentLike { - pub comment_id: i32, + pub comment_id: CommentId, pub score: i16, pub auth: String, } @@ -67,7 +68,7 @@ pub struct GetComments { pub sort: String, pub page: Option<i64>, pub limit: Option<i64>, - pub community_id: Option<i32>, + pub community_id: Option<CommunityId>, pub community_name: Option<String>, pub auth: Option<String>, } @@ -79,7 +80,7 @@ pub struct GetCommentsResponse { #[derive(Serialize, Deserialize)] pub struct CreateCommentReport { - pub comment_id: i32, + pub comment_id: CommentId, pub reason: String, pub auth: String, } @@ -108,7 +109,7 @@ pub struct ListCommentReports { pub page: Option<i64>, pub limit: Option<i64>, /// if no community is given, it returns reports for all communities moderated by the auth user - pub community: Option<i32>, + pub community: Option<CommunityId>, pub auth: String, } diff --git a/crates/api_structs/src/community.rs b/crates/api_structs/src/community.rs index d9313ce9..bd0e129d 100644 --- a/crates/api_structs/src/community.rs +++ b/crates/api_structs/src/community.rs @@ -1,3 +1,4 @@ +use lemmy_db_schema::{CommunityId, PersonId}; use lemmy_db_views_actor::{ community_follower_view::CommunityFollowerView, community_moderator_view::CommunityModeratorView, @@ -8,7 +9,7 @@ use serde::{Deserialize, Serialize}; #[derive(Deserialize)] pub struct GetCommunity { - pub id: Option<i32>, + pub id: Option<CommunityId>, pub name: Option<String>, pub auth: Option<String>, } @@ -52,8 +53,8 @@ pub struct ListCommunitiesResponse { #[derive(Deserialize, Clone)] pub struct BanFromCommunity { - pub community_id: i32, - pub person_id: i32, + pub community_id: CommunityId, + pub person_id: PersonId, pub ban: bool, pub remove_data: bool, pub reason: Option<String>, @@ -69,8 +70,8 @@ pub struct BanFromCommunityResponse { #[derive(Deserialize)] pub struct AddModToCommunity { - pub community_id: i32, - pub person_id: i32, + pub community_id: CommunityId, + pub person_id: PersonId, pub added: bool, pub auth: String, } @@ -82,7 +83,7 @@ pub struct AddModToCommunityResponse { #[derive(Deserialize)] pub struct EditCommunity { - pub community_id: i32, + pub community_id: CommunityId, pub title: String, pub description: Option<String>, pub icon: Option<String>, @@ -93,14 +94,14 @@ pub struct EditCommunity { #[derive(Deserialize)] pub struct DeleteCommunity { - pub community_id: i32, + pub community_id: CommunityId, pub deleted: bool, pub auth: String, } #[derive(Deserialize)] pub struct RemoveCommunity { - pub community_id: i32, + pub community_id: CommunityId, pub removed: bool, pub reason: Option<String>, pub expires: Option<i64>, @@ -109,7 +110,7 @@ pub struct RemoveCommunity { #[derive(Deserialize)] pub struct FollowCommunity { - pub community_id: i32, + pub community_id: CommunityId, pub follow: bool, pub auth: String, } @@ -126,7 +127,7 @@ pub struct GetFollowedCommunitiesResponse { #[derive(Deserialize)] pub struct TransferCommunity { - pub community_id: i32, - pub person_id: i32, + pub community_id: CommunityId, + pub person_id: PersonId, pub auth: String, } diff --git a/crates/api_structs/src/lib.rs b/crates/api_structs/src/lib.rs index 462f521b..f57d7f2b 100644 --- a/crates/api_structs/src/lib.rs +++ b/crates/api_structs/src/lib.rs @@ -7,11 +7,14 @@ pub mod websocket; use diesel::PgConnection; use lemmy_db_queries::{Crud, DbPool}; -use lemmy_db_schema::source::{ - comment::Comment, - person::Person, - person_mention::{PersonMention, PersonMentionForm}, - post::Post, +use lemmy_db_schema::{ + source::{ + comment::Comment, + person::Person, + person_mention::{PersonMention, PersonMentionForm}, + post::Post, + }, + LocalUserId, }; use lemmy_db_views::local_user_view::LocalUserView; use lemmy_utils::{email::send_email, settings::structs::Settings, utils::MentionData, LemmyError}; @@ -59,7 +62,7 @@ pub async fn send_local_notifs( post: Post, pool: &DbPool, do_send_email: bool, -) -> Result<Vec<i32>, LemmyError> { +) -> Result<Vec<LocalUserId>, LemmyError> { let ids = blocking(pool, move |conn| { do_send_local_notifs(conn, &mentions, &comment, &person, &post, do_send_email) }) @@ -75,7 +78,7 @@ fn do_send_local_notifs( person: &Person, post: &Post, do_send_email: bool, -) -> Vec<i32> { +) -> Vec<LocalUserId> { let mut recipient_ids = Vec::new(); // Send the local mentions diff --git a/crates/api_structs/src/person.rs b/crates/api_structs/src/person.rs index 5555bb4b..7767da46 100644 --- a/crates/api_structs/src/person.rs +++ b/crates/api_structs/src/person.rs @@ -16,6 +16,7 @@ pub struct Login { pub username_or_email: String, pub password: String, } +use lemmy_db_schema::{CommunityId, PersonId, PersonMentionId, PrivateMessageId}; #[derive(Deserialize)] pub struct Register { @@ -71,12 +72,12 @@ pub struct LoginResponse { #[derive(Deserialize)] pub struct GetPersonDetails { - pub person_id: Option<i32>, + pub person_id: Option<PersonId>, pub username: Option<String>, pub sort: String, pub page: Option<i64>, pub limit: Option<i64>, - pub community_id: Option<i32>, + pub community_id: Option<CommunityId>, pub saved_only: bool, pub auth: Option<String>, } @@ -107,7 +108,7 @@ pub struct MarkAllAsRead { #[derive(Deserialize)] pub struct AddAdmin { - pub person_id: i32, + pub person_id: PersonId, pub added: bool, pub auth: String, } @@ -119,7 +120,7 @@ pub struct AddAdminResponse { #[derive(Deserialize)] pub struct BanPerson { - pub person_id: i32, + pub person_id: PersonId, pub ban: bool, pub remove_data: bool, pub reason: Option<String>, @@ -153,7 +154,7 @@ pub struct GetPersonMentions { #[derive(Deserialize)] pub struct MarkPersonMentionAsRead { - pub person_mention_id: i32, + pub person_mention_id: PersonMentionId, pub read: bool, pub auth: String, } @@ -187,27 +188,27 @@ pub struct PasswordChange { #[derive(Deserialize)] pub struct CreatePrivateMessage { pub content: String, - pub recipient_id: i32, + pub recipient_id: PersonId, pub auth: String, } #[derive(Deserialize)] pub struct EditPrivateMessage { - pub private_message_id: i32, + pub private_message_id: PrivateMessageId, pub content: String, pub auth: String, } #[derive(Deserialize)] pub struct DeletePrivateMessage { - pub private_message_id: i32, + pub private_message_id: PrivateMessageId, pub deleted: bool, pub auth: String, } #[derive(Deserialize)] pub struct MarkPrivateMessageAsRead { - pub private_message_id: i32, + pub private_message_id: PrivateMessageId, pub read: bool, pub auth: String, } @@ -232,13 +233,13 @@ pub struct PrivateMessageResponse { #[derive(Serialize, Deserialize, Debug)] pub struct GetReportCount { - pub community: Option<i32>, + pub community: Option<CommunityId>, pub auth: String, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct GetReportCountResponse { - pub community: Option<i32>, + pub community: Option<CommunityId>, pub comment_reports: i64, pub post_reports: i64, } diff --git a/crates/api_structs/src/post.rs b/crates/api_structs/src/post.rs index 82be6617..d0991166 100644 --- a/crates/api_structs/src/post.rs +++ b/crates/api_structs/src/post.rs @@ -1,3 +1,4 @@ +use lemmy_db_schema::{CommunityId, PostId}; use lemmy_db_views::{ comment_view::CommentView, post_report_view::PostReportView, @@ -16,7 +17,7 @@ pub struct CreatePost { pub url: Option<Url>, pub body: Option<String>, pub nsfw: bool, - pub community_id: i32, + pub community_id: CommunityId, pub auth: String, } @@ -27,7 +28,7 @@ pub struct PostResponse { #[derive(Deserialize)] pub struct GetPost { - pub id: i32, + pub id: PostId, pub auth: Option<String>, } @@ -46,7 +47,7 @@ pub struct GetPosts { pub sort: String, pub page: Option<i64>, pub limit: Option<i64>, - pub community_id: Option<i32>, + pub community_id: Option<CommunityId>, pub community_name: Option<String>, pub auth: Option<String>, } @@ -58,14 +59,14 @@ pub struct GetPostsResponse { #[derive(Deserialize)] pub struct CreatePostLike { - pub post_id: i32, + pub post_id: PostId, pub score: i16, pub auth: String, } #[derive(Deserialize)] pub struct EditPost { - pub post_id: i32, + pub post_id: PostId, pub name: String, pub url: Option<Url>, pub body: Option<String>, @@ -75,14 +76,14 @@ pub struct EditPost { #[derive(Deserialize)] pub struct DeletePost { - pub post_id: i32, + pub post_id: PostId, pub deleted: bool, pub auth: String, } #[derive(Deserialize)] pub struct RemovePost { - pub post_id: i32, + pub post_id: PostId, pub removed: bool, pub reason: Option<String>, pub auth: String, @@ -90,28 +91,28 @@ pub struct RemovePost { #[derive(Deserialize)] pub struct LockPost { - pub post_id: i32, + pub post_id: PostId, pub locked: bool, pub auth: String, } #[derive(Deserialize)] pub struct StickyPost { - pub post_id: i32, + pub post_id: PostId, pub stickied: bool, pub auth: String, } #[derive(Deserialize)] pub struct SavePost { - pub post_id: i32, + pub post_id: PostId, pub save: bool, pub auth: String, } #[derive(Serialize, Deserialize)] pub struct CreatePostReport { - pub post_id: i32, + pub post_id: PostId, pub reason: String, pub auth: String, } @@ -138,7 +139,7 @@ pub struct ResolvePostReportResponse { pub struct ListPostReports { pub page: Option<i64>, pub limit: Option<i64>, - pub community: Option<i32>, + pub community: Option<CommunityId>, pub auth: String, } diff --git a/crates/api_structs/src/site.rs b/crates/api_structs/src/site.rs index f2781668..090fa8f5 100644 --- a/crates/api_structs/src/site.rs +++ b/crates/api_structs/src/site.rs @@ -1,3 +1,4 @@ +use lemmy_db_schema::{CommunityId, PersonId}; use lemmy_db_views::{ comment_view::CommentView, local_user_view::LocalUserSettingsView, @@ -23,7 +24,7 @@ use url::Url; pub struct Search { pub q: String, pub type_: String, - pub community_id: Option<i32>, + pub community_id: Option<CommunityId>, pub community_name: Option<String>, pub sort: String, pub page: Option<i64>, @@ -42,8 +43,8 @@ pub struct SearchResponse { #[derive(Deserialize)] pub struct GetModlog { - pub mod_person_id: Option<i32>, - pub community_id: Option<i32>, + pub mod_person_id: Option<PersonId>, + pub community_id: Option<CommunityId>, pub page: Option<i64>, pub limit: Option<i64>, } @@ -108,7 +109,7 @@ pub struct GetSiteResponse { #[derive(Deserialize)] pub struct TransferSite { - pub person_id: i32, + pub person_id: PersonId, pub auth: String, } diff --git a/crates/api_structs/src/websocket.rs b/crates/api_structs/src/websocket.rs index c3ae1465..c64a56c0 100644 --- a/crates/api_structs/src/websocket.rs +++ b/crates/api_structs/src/websocket.rs @@ -1,3 +1,4 @@ +use lemmy_db_schema::{CommunityId, PostId}; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Debug)] @@ -12,7 +13,7 @@ pub struct UserJoinResponse { #[derive(Deserialize, Debug)] pub struct CommunityJoin { - pub community_id: i32, + pub community_id: CommunityId, } #[derive(Serialize, Clone)] @@ -22,7 +23,7 @@ pub struct CommunityJoinResponse { #[derive(Deserialize, Debug)] pub struct ModJoin { - pub community_id: i32, + pub community_id: CommunityId, } #[derive(Serialize, Clone)] @@ -32,7 +33,7 @@ pub struct ModJoinResponse { #[derive(Deserialize, Debug)] pub struct PostJoin { - pub post_id: i32, + pub post_id: PostId, } #[derive(Serialize, Clone)] diff --git a/crates/apub/src/http/comment.rs b/crates/apub/src/http/comment.rs index d4287224..286367ac 100644 --- a/crates/apub/src/http/comment.rs +++ b/crates/apub/src/http/comment.rs @@ -6,7 +6,7 @@ use actix_web::{body::Body, web, web::Path, HttpResponse}; use diesel::result::Error::NotFound; use lemmy_api_structs::blocking; use lemmy_db_queries::Crud; -use lemmy_db_schema::source::comment::Comment; +use lemmy_db_schema::{source::comment::Comment, CommentId}; use lemmy_utils::LemmyError; use lemmy_websocket::LemmyContext; use serde::Deserialize; @@ -21,7 +21,7 @@ pub async fn get_apub_comment( info: Path<CommentQuery>, context: web::Data<LemmyContext>, ) -> Result<HttpResponse<Body>, LemmyError> { - let id = info.comment_id.parse::<i32>()?; + let id = CommentId(info.comment_id.parse::<i32>()?); let comment = blocking(context.pool(), move |conn| Comment::read(conn, id)).await??; if !comment.local { return Err(NotFound.into()); diff --git a/crates/apub/src/http/post.rs b/crates/apub/src/http/post.rs index 8bdded2a..797d1807 100644 --- a/crates/apub/src/http/post.rs +++ b/crates/apub/src/http/post.rs @@ -6,7 +6,7 @@ use actix_web::{body::Body, web, HttpResponse}; use diesel::result::Error::NotFound; use lemmy_api_structs::blocking; use lemmy_db_queries::Crud; -use lemmy_db_schema::source::post::Post; +use lemmy_db_schema::{source::post::Post, PostId}; use lemmy_utils::LemmyError; use lemmy_websocket::LemmyContext; use serde::Deserialize; @@ -21,7 +21,7 @@ pub async fn get_apub_post( info: web::Path<PostQuery>, context: web::Data<LemmyContext>, ) -> Result<HttpResponse<Body>, LemmyError> { - let id = info.post_id.parse::<i32>()?; + let id = PostId(info.post_id.parse::<i32>()?); let post = blocking(context.pool(), move |conn| Post::read(conn, id)).await??; if !post.local { return Err(NotFound.into()); diff --git a/crates/apub/src/inbox/community_inbox.rs b/crates/apub/src/inbox/community_inbox.rs index cb697184..080d55f3 100644 --- a/crates/apub/src/inbox/community_inbox.rs +++ b/crates/apub/src/inbox/community_inbox.rs @@ -28,9 +28,12 @@ use actix_web::{web, HttpRequest, HttpResponse}; use anyhow::{anyhow, Context}; use lemmy_api_structs::blocking; use lemmy_db_queries::{source::community::Community_, ApubObject, DbPool, Followable}; -use lemmy_db_schema::source::{ - community::{Community, CommunityFollower, CommunityFollowerForm}, - person::Person, +use lemmy_db_schema::{ + source::{ + community::{Community, CommunityFollower, CommunityFollowerForm}, + person::Person, + }, + CommunityId, }; use lemmy_db_views_actor::community_person_ban_view::CommunityPersonBanView; use lemmy_utils::{location_info, LemmyError}; @@ -261,7 +264,7 @@ async fn handle_undo_follow( pub(crate) async fn check_community_or_site_ban( person: &Person, - community_id: i32, + community_id: CommunityId, pool: &DbPool, ) -> Result<(), LemmyError> { if person.banned { diff --git a/crates/apub/src/objects/comment.rs b/crates/apub/src/objects/comment.rs index 0d9aab16..cc1d9f03 100644 --- a/crates/apub/src/objects/comment.rs +++ b/crates/apub/src/objects/comment.rs @@ -23,10 +23,13 @@ use activitystreams::{ use anyhow::{anyhow, Context}; use lemmy_api_structs::blocking; use lemmy_db_queries::{Crud, DbPool}; -use lemmy_db_schema::source::{ - comment::{Comment, CommentForm}, - person::Person, - post::Post, +use lemmy_db_schema::{ + source::{ + comment::{Comment, CommentForm}, + person::Person, + post::Post, + }, + CommentId, }; use lemmy_utils::{ location_info, @@ -153,7 +156,7 @@ impl FromApubToForm<NoteExt> for CommentForm { // The 2nd item, if it exists, is the parent comment apub_id // For deeply nested comments, FromApub automatically gets called recursively - let parent_id: Option<i32> = match in_reply_tos.next() { + let parent_id: Option<CommentId> = match in_reply_tos.next() { Some(parent_comment_uri) => { let parent_comment_ap_id = &parent_comment_uri?; let parent_comment = diff --git a/crates/apub/src/objects/mod.rs b/crates/apub/src/objects/mod.rs index b21a3a21..a2b527f8 100644 --- a/crates/apub/src/objects/mod.rs +++ b/crates/apub/src/objects/mod.rs @@ -14,7 +14,7 @@ use chrono::NaiveDateTime; use diesel::result::Error::NotFound; use lemmy_api_structs::blocking; use lemmy_db_queries::{ApubObject, Crud, DbPool}; -use lemmy_db_schema::{source::community::Community, DbUrl}; +use lemmy_db_schema::{source::community::Community, CommunityId, DbUrl}; use lemmy_utils::{ location_info, settings::structs::Settings, @@ -172,7 +172,7 @@ pub(in crate::objects) fn check_is_markdown(mime: Option<&Mime>) -> Result<(), L /// Converts an ActivityPub object (eg `Note`) to a database object (eg `Comment`). If an object /// with the same ActivityPub ID already exists in the database, it is returned directly. Otherwise /// the apub object is parsed, inserted and returned. -pub(in crate::objects) async fn get_object_from_apub<From, Kind, To, ToForm>( +pub(in crate::objects) async fn get_object_from_apub<From, Kind, To, ToForm, IdType>( from: &From, context: &LemmyContext, expected_domain: Url, @@ -180,7 +180,7 @@ pub(in crate::objects) async fn get_object_from_apub<From, Kind, To, ToForm>( ) -> Result<To, LemmyError> where From: BaseExt<Kind>, - To: ApubObject<ToForm> + Crud<ToForm> + Send + 'static, + To: ApubObject<ToForm> + Crud<ToForm, IdType> + Send + 'static, ToForm: FromApubToForm<From> + Send + 'static, { let object_id = from.id_unchecked().context(location_info!())?.to_owned(); @@ -205,7 +205,7 @@ where pub(in crate::objects) async fn check_object_for_community_or_site_ban<T, Kind>( object: &T, - community_id: i32, + community_id: CommunityId, context: &LemmyContext, request_counter: &mut i32, ) -> Result<(), LemmyError> diff --git a/crates/db_queries/src/aggregates/comment_aggregates.rs b/crates/db_queries/src/aggregates/comment_aggregates.rs index 72bdd024..c55fef0c 100644 --- a/crates/db_queries/src/aggregates/comment_aggregates.rs +++ b/crates/db_queries/src/aggregates/comment_aggregates.rs @@ -1,12 +1,12 @@ use diesel::{result::Error, *}; -use lemmy_db_schema::schema::comment_aggregates; +use lemmy_db_schema::{schema::comment_aggregates, CommentId}; use serde::Serialize; #[derive(Queryable, Associations, Identifiable, PartialEq, Debug, Serialize, Clone)] #[table_name = "comment_aggregates"] pub struct CommentAggregates { pub id: i32, - pub comment_id: i32, + pub comment_id: CommentId, pub score: i64, pub upvotes: i64, pub downvotes: i64, @@ -14,7 +14,7 @@ pub struct CommentAggregates { } impl CommentAggregates { - pub fn read(conn: &PgConnection, comment_id: i32) -> Result<Self, Error> { + pub fn read(conn: &PgConnection, comment_id: CommentId) -> Result<Self, Error> { comment_aggregates::table .filter(comment_aggregates::comment_id.eq(comment_id)) .first::<Self>(conn) diff --git a/crates/db_queries/src/aggregates/community_aggregates.rs b/crates/db_queries/src/aggregates/community_aggregates.rs index 4bf52459..bbe751ae 100644 --- a/crates/db_queries/src/aggregates/community_aggregates.rs +++ b/crates/db_queries/src/aggregates/community_aggregates.rs @@ -1,12 +1,12 @@ use diesel::{result::Error, *}; -use lemmy_db_schema::schema::community_aggregates; +use lemmy_db_schema::{schema::community_aggregates, CommunityId}; use serde::Serialize; #[derive(Queryable, Associations, Identifiable, PartialEq, Debug, Serialize, Clone)] #[table_name = "community_aggregates"] pub struct CommunityAggregates { pub id: i32, - pub community_id: i32, + pub community_id: CommunityId, pub subscribers: i64, pub posts: i64, pub comments: i64, @@ -18,7 +18,7 @@ pub struct CommunityAggregates { } impl CommunityAggregates { - pub fn read(conn: &PgConnection, community_id: i32) -> Result<Self, Error> { + pub fn read(conn: &PgConnection, community_id: CommunityId) -> Result<Self, Error> { community_aggregates::table .filter(community_aggregates::community_id.eq(community_id)) .first::<Self>(conn) diff --git a/crates/db_queries/src/aggregates/person_aggregates.rs b/crates/db_queries/src/aggregates/person_aggregates.rs index 473dac32..c1082c4b 100644 --- a/crates/db_queries/src/aggregates/person_aggregates.rs +++ b/crates/db_queries/src/aggregates/person_aggregates.rs @@ -1,12 +1,12 @@ use diesel::{result::Error, *}; -use lemmy_db_schema::schema::person_aggregates; +use lemmy_db_schema::{schema::person_aggregates, PersonId}; use serde::Serialize; #[derive(Queryable, Associations, Identifiable, PartialEq, Debug, Serialize, Clone)] #[table_name = "person_aggregates"] pub struct PersonAggregates { pub id: i32, - pub person_id: i32, + pub person_id: PersonId, pub post_count: i64, pub post_score: i64, pub comment_count: i64, @@ -14,7 +14,7 @@ pub struct PersonAggregates { } impl PersonAggregates { - pub fn read(conn: &PgConnection, person_id: i32) -> Result<Self, Error> { + pub fn read(conn: &PgConnection, person_id: PersonId) -> Result<Self, Error> { person_aggregates::table .filter(person_aggregates::person_id.eq(person_id)) .first::<Self>(conn) diff --git a/crates/db_queries/src/aggregates/post_aggregates.rs b/crates/db_queries/src/aggregates/post_aggregates.rs index a88918ae..aa5e774e 100644 --- a/crates/db_queries/src/aggregates/post_aggregates.rs +++ b/crates/db_queries/src/aggregates/post_aggregates.rs @@ -1,12 +1,12 @@ use diesel::{result::Error, *}; -use lemmy_db_schema::schema::post_aggregates; +use lemmy_db_schema::{schema::post_aggregates, PostId}; use serde::Serialize; #[derive(Queryable, Associations, Identifiable, PartialEq, Debug, Serialize, Clone)] #[table_name = "post_aggregates"] pub struct PostAggregates { pub id: i32, - pub post_id: i32, + pub post_id: PostId, pub comments: i64, pub score: i64, pub upvotes: i64, @@ -18,7 +18,7 @@ pub struct PostAggregates { } impl PostAggregates { - pub fn read(conn: &PgConnection, post_id: i32) -> Result<Self, Error> { + pub fn read(conn: &PgConnection, post_id: PostId) -> Result<Self, Error> { post_aggregates::table .filter(post_aggregates::post_id.eq(post_id)) .first::<Self>(conn) diff --git a/crates/db_queries/src/lib.rs b/crates/db_queries/src/lib.rs index e027cfc9..285ba332 100644 --- a/crates/db_queries/src/lib.rs +++ b/crates/db_queries/src/lib.rs @@ -13,7 +13,7 @@ extern crate diesel_migrations; extern crate serial_test; use diesel::{result::Error, *}; -use lemmy_db_schema::DbUrl; +use lemmy_db_schema::{CommunityId, DbUrl, PersonId}; use lemmy_utils::ApiError; use regex::Regex; use serde::{Deserialize, Serialize}; @@ -25,17 +25,17 @@ pub mod source; pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>; -pub trait Crud<T> { - fn create(conn: &PgConnection, form: &T) -> Result<Self, Error> +pub trait Crud<Form, IdType> { + fn create(conn: &PgConnection, form: &Form) -> Result<Self, Error> where Self: Sized; - fn read(conn: &PgConnection, id: i32) -> Result<Self, Error> + fn read(conn: &PgConnection, id: IdType) -> Result<Self, Error> where Self: Sized; - fn update(conn: &PgConnection, id: i32, form: &T) -> Result<Self, Error> + fn update(conn: &PgConnection, id: IdType, form: &Form) -> Result<Self, Error> where Self: Sized; - fn delete(_conn: &PgConnection, _id: i32) -> Result<usize, Error> + fn delete(_conn: &PgConnection, _id: IdType) -> Result<usize, Error> where Self: Sized, { @@ -43,81 +43,85 @@ pub trait Crud<T> { } } -pub trait Followable<T> { - fn follow(conn: &PgConnection, form: &T) -> Result<Self, Error> +pub trait Followable<Form> { + fn follow(conn: &PgConnection, form: &Form) -> Result<Self, Error> where Self: Sized; - fn follow_accepted(conn: &PgConnection, community_id: i32, person_id: i32) -> Result<Self, Error> + fn follow_accepted( + conn: &PgConnection, + community_id: CommunityId, + person_id: PersonId, + ) -> Result<Self, Error> where Self: Sized; - fn unfollow(conn: &PgConnection, form: &T) -> Result<usize, Error> + fn unfollow(conn: &PgConnection, form: &Form) -> Result<usize, Error> where Self: Sized; - fn has_local_followers(conn: &PgConnection, community_id: i32) -> Result<bool, Error>; + fn has_local_followers(conn: &PgConnection, community_id: CommunityId) -> Result<bool, Error>; } -pub trait Joinable<T> { - fn join(conn: &PgConnection, form: &T) -> Result<Self, Error> +pub trait Joinable<Form> { + fn join(conn: &PgConnection, form: &Form) -> Result<Self, Error> where Self: Sized; - fn leave(conn: &PgConnection, form: &T) -> Result<usize, Error> + fn leave(conn: &PgConnection, form: &Form) -> Result<usize, Error> where Self: Sized; } -pub trait Likeable<T> { - fn like(conn: &PgConnection, form: &T) -> Result<Self, Error> +pub trait Likeable<Form, IdType> { + fn like(conn: &PgConnection, form: &Form) -> Result<Self, Error> where Self: Sized; - fn remove(conn: &PgConnection, person_id: i32, item_id: i32) -> Result<usize, Error> + fn remove(conn: &PgConnection, person_id: PersonId, item_id: IdType) -> Result<usize, Error> where Self: Sized; } -pub trait Bannable<T> { - fn ban(conn: &PgConnection, form: &T) -> Result<Self, Error> +pub trait Bannable<Form> { + fn ban(conn: &PgConnection, form: &Form) -> Result<Self, Error> where Self: Sized; - fn unban(conn: &PgConnection, form: &T) -> Result<usize, Error> + fn unban(conn: &PgConnection, form: &Form) -> Result<usize, Error> where Self: Sized; } -pub trait Saveable<T> { - fn save(conn: &PgConnection, form: &T) -> Result<Self, Error> +pub trait Saveable<Form> { + fn save(conn: &PgConnection, form: &Form) -> Result<Self, Error> where Self: Sized; - fn unsave(conn: &PgConnection, form: &T) -> Result<usize, Error> + fn unsave(conn: &PgConnection, form: &Form) -> Result<usize, Error> where Self: Sized; } -pub trait Readable<T> { - fn mark_as_read(conn: &PgConnection, form: &T) -> Result<Self, Error> +pub trait Readable<Form> { + fn mark_as_read(conn: &PgConnection, form: &Form) -> Result<Self, Error> where Self: Sized; - fn mark_as_unread(conn: &PgConnection, form: &T) -> Result<usize, Error> + fn mark_as_unread(conn: &PgConnection, form: &Form) -> Result<usize, Error> where Self: Sized; } -pub trait Reportable<T> { - fn report(conn: &PgConnection, form: &T) -> Result<Self, Error> +pub trait Reportable<Form> { + fn report(conn: &PgConnection, form: &Form) -> Result<Self, Error> where Self: Sized; - fn resolve(conn: &PgConnection, report_id: i32, resolver_id: i32) -> Result<usize, Error> + fn resolve(conn: &PgConnection, report_id: i32, resolver_id: PersonId) -> Result<usize, Error> where Self: Sized; - fn unresolve(conn: &PgConnection, report_id: i32, resolver_id: i32) -> Result<usize, Error> + fn unresolve(conn: &PgConnection, report_id: i32, resolver_id: PersonId) -> Result<usize, Error> where Self: Sized; } -pub trait ApubObject<T> { +pub trait ApubObject<Form> { fn read_from_apub_id(conn: &PgConnection, object_id: &DbUrl) -> Result<Self, Error> where Self: Sized; - fn upsert(conn: &PgConnection, user_form: &T) -> Result<Self, Error> + fn upsert(conn: &PgConnection, user_form: &Form) -> Result<Self, Error> where Self: Sized; } diff --git a/crates/db_queries/src/source/activity.rs b/crates/db_queries/src/source/activity.rs index bd1bf451..1ec9b8d1 100644 --- a/crates/db_queries/src/source/activity.rs +++ b/crates/db_queries/src/source/activity.rs @@ -9,7 +9,7 @@ use std::{ io::{Error as IoError, ErrorKind}, }; -impl Crud<ActivityForm> for Activity { +impl Crud<ActivityForm, i32> for Activity { fn read(conn: &PgConnection, activity_id: i32) -> Result<Self, Error> { use lemmy_db_schema::schema::activity::dsl::*; activity.find(activity_id).first::<Self>(conn) diff --git a/crates/db_queries/src/source/comment.rs b/crates/db_queries/src/source/comment.rs index 67488898..69ac4c08 100644 --- a/crates/db_queries/src/source/comment.rs +++ b/crates/db_queries/src/source/comment.rs @@ -10,40 +10,54 @@ use lemmy_db_schema::{ CommentSaved, CommentSavedForm, }, + CommentId, DbUrl, + PersonId, }; pub trait Comment_ { - fn update_ap_id(conn: &PgConnection, comment_id: i32, apub_id: DbUrl) -> Result<Comment, Error>; + fn update_ap_id( + conn: &PgConnection, + comment_id: CommentId, + apub_id: DbUrl, + ) -> Result<Comment, Error>; fn permadelete_for_creator( conn: &PgConnection, - for_creator_id: i32, + for_creator_id: PersonId, ) -> Result<Vec<Comment>, Error>; fn update_deleted( conn: &PgConnection, - comment_id: i32, + comment_id: CommentId, new_deleted: bool, ) -> Result<Comment, Error>; fn update_removed( conn: &PgConnection, - comment_id: i32, + comment_id: CommentId, new_removed: bool, ) -> Result<Comment, Error>; fn update_removed_for_creator( conn: &PgConnection, - for_creator_id: i32, + for_creator_id: PersonId, new_removed: bool, ) -> Result<Vec<Comment>, Error>; - fn update_read(conn: &PgConnection, comment_id: i32, new_read: bool) -> Result<Comment, Error>; + fn update_read( + conn: &PgConnection, + comment_id: CommentId, + new_read: bool, + ) -> Result<Comment, Error>; fn update_content( conn: &PgConnection, - comment_id: i32, + comment_id: CommentId, new_content: &str, ) -> Result<Comment, Error>; } impl Comment_ for Comment { - fn update_ap_id(conn: &PgConnection, comment_id: i32, apub_id: DbUrl) -> Result<Self, Error> { + fn update_ap_id( + conn: &PgConnection, + comment_id: CommentId, + apub_id: DbUrl, + ) -> Result<Self, Error> { use lemmy_db_schema::schema::comment::dsl::*; diesel::update(comment.find(comment_id)) @@ -51,7 +65,10 @@ impl Comment_ for Comment { .get_result::<Self>(conn) } - fn permadelete_for_creator(conn: &PgConnection, for_creator_id: i32) -> Result<Vec<Self>, Error> { + fn permadelete_for_creator( + conn: &PgConnection, + for_creator_id: PersonId, + ) -> Result<Vec<Self>, Error> { use lemmy_db_schema::schema::comment::dsl::*; diesel::update(comment.filter(creator_id.eq(for_creator_id))) .set(( @@ -64,7 +81,7 @@ impl Comment_ for Comment { fn update_deleted( conn: &PgConnection, - comment_id: i32, + comment_id: CommentId, new_deleted: bool, ) -> Result<Self, Error> { use lemmy_db_schema::schema::comment::dsl::*; @@ -75,7 +92,7 @@ impl Comment_ for Comment { fn update_removed( conn: &PgConnection, - comment_id: i32, + comment_id: CommentId, new_removed: bool, ) -> Result<Self, Error> { use lemmy_db_schema::schema::comment::dsl::*; @@ -86,7 +103,7 @@ impl Comment_ for Comment { fn update_removed_for_creator( conn: &PgConnection, - for_creator_id: i32, + for_creator_id: PersonId, new_removed: bool, ) -> Result<Vec<Self>, Error> { use lemmy_db_schema::schema::comment::dsl::*; @@ -95,7 +112,11 @@ impl Comment_ for Comment { .get_results::<Self>(conn) } - fn update_read(conn: &PgConnection, comment_id: i32, new_read: bool) -> Result<Self, Error> { + fn update_read( + conn: &PgConnection, + comment_id: CommentId, + new_read: bool, + ) -> Result<Self, Error> { use lemmy_db_schema::schema::comment::dsl::*; diesel::update(comment.find(comment_id)) .set(read.eq(new_read)) @@ -104,7 +125,7 @@ impl Comment_ for Comment { fn update_content( conn: &PgConnection, - comment_id: i32, + comment_id: CommentId, new_content: &str, ) -> Result<Self, Error> { use lemmy_db_schema::schema::comment::dsl::*; @@ -114,13 +135,13 @@ impl Comment_ for Comment { } } -impl Crud<CommentForm> for Comment { - fn read(conn: &PgConnection, comment_id: i32) -> Result<Self, Error> { +impl Crud<CommentForm, CommentId> for Comment { + fn read(conn: &PgConnection, comment_id: CommentId) -> Result<Self, Error> { use lemmy_db_schema::schema::comment::dsl::*; comment.find(comment_id).first::<Self>(conn) } - fn delete(conn: &PgConnection, comment_id: i32) -> Result<usize, Error> { + fn delete(conn: &PgConnection, comment_id: CommentId) -> Result<usize, Error> { use lemmy_db_schema::schema::comment::dsl::*; diesel::delete(comment.find(comment_id)).execute(conn) } @@ -134,7 +155,7 @@ impl Crud<CommentForm> for Comment { fn update( conn: &PgConnection, - comment_id: i32, + comment_id: CommentId, comment_form: &CommentForm, ) -> Result<Self, Error> { use lemmy_db_schema::schema::comment::dsl::*; @@ -161,7 +182,7 @@ impl ApubObject<CommentForm> for Comment { } } -impl Likeable<CommentLikeForm> for CommentLike { +impl Likeable<CommentLikeForm, CommentId> for CommentLike { fn like(conn: &PgConnection, comment_like_form: &CommentLikeForm) -> Result<Self, Error> { use lemmy_db_schema::schema::comment_like::dsl::*; insert_into(comment_like) @@ -171,7 +192,11 @@ impl Likeable<CommentLikeForm> for CommentLike { .set(comment_like_form) .get_result::<Self>(conn) } - fn remove(conn: &PgConnection, person_id: i32, comment_id: i32) -> Result<usize, Error> { + fn remove( + conn: &PgConnection, + person_id: PersonId, + comment_id: CommentId, + ) -> Result<usize, Error> { use lemmy_db_schema::schema::comment_like::dsl; diesel::delete( dsl::comment_like diff --git a/crates/db_queries/src/source/comment_report.rs b/crates/db_queries/src/source/comment_report.rs index bf42704e..87b93606 100644 --- a/crates/db_queries/src/source/comment_report.rs +++ b/crates/db_queries/src/source/comment_report.rs @@ -3,6 +3,7 @@ use diesel::{dsl::*, result::Error, *}; use lemmy_db_schema::{ naive_now, source::comment_report::{CommentReport, CommentReportForm}, + PersonId, }; impl Reportable<CommentReportForm> for CommentReport { @@ -22,7 +23,11 @@ impl Reportable<CommentReportForm> for CommentReport { /// * `conn` - the postgres connection /// * `report_id` - the id of the report to resolve /// * `by_resolver_id` - the id of the user resolving the report - fn resolve(conn: &PgConnection, report_id: i32, by_resolver_id: i32) -> Result<usize, Error> { + fn resolve( + conn: &PgConnection, + report_id: i32, + by_resolver_id: PersonId, + ) -> Result<usize, Error> { use lemmy_db_schema::schema::comment_report::dsl::*; update(comment_report.find(report_id)) .set(( @@ -38,7 +43,11 @@ impl Reportable<CommentReportForm> for CommentReport { /// * `conn` - the postgres connection /// * `report_id` - the id of the report to unresolve /// * `by_resolver_id` - the id of the user unresolving the report - fn unresolve(conn: &PgConnection, report_id: i32, by_resolver_id: i32) -> Result<usize, Error> { + fn unresolve( + conn: &PgConnection, + report_id: i32, + by_resolver_id: PersonId, + ) -> Result<usize, Error> { use lemmy_db_schema::schema::comment_report::dsl::*; update(comment_report.find(report_id)) .set(( diff --git a/crates/db_queries/src/source/community.rs b/crates/db_queries/src/source/community.rs index 2981f230..5b7fc92c 100644 --- a/crates/db_queries/src/source/community.rs +++ b/crates/db_queries/src/source/community.rs @@ -12,7 +12,9 @@ use lemmy_db_schema::{ CommunityPersonBan, CommunityPersonBanForm, }, + CommunityId, DbUrl, + PersonId, }; mod safe_type { @@ -59,13 +61,13 @@ mod safe_type { } } -impl Crud<CommunityForm> for Community { - fn read(conn: &PgConnection, community_id: i32) -> Result<Self, Error> { +impl Crud<CommunityForm, CommunityId> for Community { + fn read(conn: &PgConnection, community_id: CommunityId) -> Result<Self, Error> { use lemmy_db_schema::schema::community::dsl::*; community.find(community_id).first::<Self>(conn) } - fn delete(conn: &PgConnection, community_id: i32) -> Result<usize, Error> { + fn delete(conn: &PgConnection, community_id: CommunityId) -> Result<usize, Error> { use lemmy_db_schema::schema::community::dsl::*; diesel::delete(community.find(community_id)).execute(conn) } @@ -79,7 +81,7 @@ impl Crud<CommunityForm> for Community { fn update( conn: &PgConnection, - community_id: i32, + community_id: CommunityId, new_community: &CommunityForm, ) -> Result<Self, Error> { use lemmy_db_schema::schema::community::dsl::*; @@ -112,23 +114,23 @@ pub trait Community_ { fn read_from_name(conn: &PgConnection, community_name: &str) -> Result<Community, Error>; fn update_deleted( conn: &PgConnection, - community_id: i32, + community_id: CommunityId, new_deleted: bool, ) -> Result<Community, Error>; fn update_removed( conn: &PgConnection, - community_id: i32, + community_id: CommunityId, new_removed: bool, ) -> Result<Community, Error>; fn update_removed_for_creator( conn: &PgConnection, - for_creator_id: i32, + for_creator_id: PersonId, new_removed: bool, ) -> Result<Vec<Community>, Error>; fn update_creator( conn: &PgConnection, - community_id: i32, - new_creator_id: i32, + community_id: CommunityId, + new_creator_id: PersonId, ) -> Result<Community, Error>; fn distinct_federated_communities(conn: &PgConnection) -> Result<Vec<String>, Error>; fn read_from_followers_url( @@ -148,7 +150,7 @@ impl Community_ for Community { fn update_deleted( conn: &PgConnection, - community_id: i32, + community_id: CommunityId, new_deleted: bool, ) -> Result<Community, Error> { use lemmy_db_schema::schema::community::dsl::*; @@ -159,7 +161,7 @@ impl Community_ for Community { fn update_removed( conn: &PgConnection, - community_id: i32, + community_id: CommunityId, new_removed: bool, ) -> Result<Community, Error> { use lemmy_db_schema::schema::community::dsl::*; @@ -170,7 +172,7 @@ impl Community_ for Community { fn update_removed_for_creator( conn: &PgConnection, - for_creator_id: i32, + for_creator_id: PersonId, new_removed: bool, ) -> Result<Vec<Community>, Error> { use lemmy_db_schema::schema::community::dsl::*; @@ -181,8 +183,8 @@ impl Community_ for Community { fn update_creator( conn: &PgConnection, - community_id: i32, - new_creator_id: i32, + community_id: CommunityId, + new_creator_id: PersonId, ) -> Result<Community, Error> { use lemmy_db_schema::schema::community::dsl::*; diesel::update(community.find(community_id)) @@ -232,28 +234,34 @@ impl Joinable<CommunityModeratorForm> for CommunityModerator { } pub trait CommunityModerator_ { - fn delete_for_community(conn: &PgConnection, for_community_id: i32) -> Result<usize, Error>; + fn delete_for_community( + conn: &PgConnection, + for_community_id: CommunityId, + ) -> Result<usize, Error>; fn get_person_moderated_communities( conn: &PgConnection, - for_person_id: i32, - ) -> Result<Vec<i32>, Error>; + for_person_id: PersonId, + ) -> Result<Vec<CommunityId>, Error>; } impl CommunityModerator_ for CommunityModerator { - fn delete_for_community(conn: &PgConnection, for_community_id: i32) -> Result<usize, Error> { + fn delete_for_community( + conn: &PgConnection, + for_community_id: CommunityId, + ) -> Result<usize, Error> { use lemmy_db_schema::schema::community_moderator::dsl::*; diesel::delete(community_moderator.filter(community_id.eq(for_community_id))).execute(conn) } fn get_person_moderated_communities( conn: &PgConnection, - for_person_id: i32, - ) -> Result<Vec<i32>, Error> { + for_person_id: PersonId, + ) -> Result<Vec<CommunityId>, Error> { use lemmy_db_schema::schema::community_moderator::dsl::*; community_moderator .filter(person_id.eq(for_person_id)) .select(community_id) - .load::<i32>(conn) + .load::<CommunityId>(conn) } } @@ -297,8 +305,8 @@ impl Followable<CommunityFollowerForm> for CommunityFollower { } fn follow_accepted( conn: &PgConnection, - community_id_: i32, - person_id_: i32, + community_id_: CommunityId, + person_id_: PersonId, ) -> Result<Self, Error> where Self: Sized, @@ -326,7 +334,7 @@ impl Followable<CommunityFollowerForm> for CommunityFollower { } // TODO: this function name only makes sense if you call it with a remote community. for a local // community, it will also return true if only remote followers exist - fn has_local_followers(conn: &PgConnection, community_id_: i32) -> Result<bool, Error> { + fn has_local_followers(conn: &PgConnection, community_id_: CommunityId) -> Result<bool, Error> { use lemmy_db_schema::schema::community_follower::dsl::*; diesel::select(exists( community_follower.filter(community_id.eq(community_id_)), diff --git a/crates/db_queries/src/source/local_user.rs b/crates/db_queries/src/source/local_user.rs index a3d2b85b..cd93d3fb 100644 --- a/crates/db_queries/src/source/local_user.rs +++ b/crates/db_queries/src/source/local_user.rs @@ -4,6 +4,8 @@ use diesel::{dsl::*, result::Error, *}; use lemmy_db_schema::{ schema::local_user::dsl::*, source::local_user::{LocalUser, LocalUserForm}, + LocalUserId, + PersonId, }; mod safe_type { @@ -66,10 +68,10 @@ pub trait LocalUser_ { fn register(conn: &PgConnection, form: &LocalUserForm) -> Result<LocalUser, Error>; fn update_password( conn: &PgConnection, - local_user_id: i32, + local_user_id: LocalUserId, new_password: &str, ) -> Result<LocalUser, Error>; - fn add_admin(conn: &PgConnection, person_id: i32, added: bool) -> Result<LocalUser, Error>; + fn add_admin(conn: &PgConnection, person_id: PersonId, added: bool) -> Result<LocalUser, Error>; } impl LocalUser_ for LocalUser { @@ -84,7 +86,7 @@ impl LocalUser_ for LocalUser { fn update_password( conn: &PgConnection, - local_user_id: i32, + local_user_id: LocalUserId, new_password: &str, ) -> Result<Self, Error> { let password_hash = hash(new_password, DEFAULT_COST).expect("Couldn't hash password"); @@ -94,18 +96,18 @@ impl LocalUser_ for LocalUser { .get_result::<Self>(conn) } - fn add_admin(conn: &PgConnection, for_person_id: i32, added: bool) -> Result<Self, Error> { + fn add_admin(conn: &PgConnection, for_person_id: PersonId, added: bool) -> Result<Self, Error> { diesel::update(local_user.filter(person_id.eq(for_person_id))) .set(admin.eq(added)) .get_result::<Self>(conn) } } -impl Crud<LocalUserForm> for LocalUser { - fn read(conn: &PgConnection, local_user_id: i32) -> Result<Self, Error> { +impl Crud<LocalUserForm, LocalUserId> for LocalUser { + fn read(conn: &PgConnection, local_user_id: LocalUserId) -> Result<Self, Error> { local_user.find(local_user_id).first::<Self>(conn) } - fn delete(conn: &PgConnection, local_user_id: i32) -> Result<usize, Error> { + fn delete(conn: &PgConnection, local_user_id: LocalUserId) -> Result<usize, Error> { diesel::delete(local_user.find(local_user_id)).execute(conn) } fn create(conn: &PgConnection, form: &LocalUserForm) -> Result<Self, Error> { @@ -113,7 +115,11 @@ impl Crud<LocalUserForm> for LocalUser { .values(form) .get_result::<Self>(conn) } - fn update(conn: &PgConnection, local_user_id: i32, form: &LocalUserForm) -> Result<Self, Error> { + fn update( + conn: &PgConnection, + local_user_id: LocalUserId, + form: &LocalUserForm, + ) -> Result<Self, Error> { diesel::update(local_user.find(local_user_id)) .set(form) .get_result::<Self>(conn) diff --git a/crates/db_queries/src/source/moderator.rs b/crates/db_queries/src/source/moderator.rs index 0a3fd7ef..526fc2bd 100644 --- a/crates/db_queries/src/source/moderator.rs +++ b/crates/db_queries/src/source/moderator.rs @@ -2,7 +2,7 @@ use crate::Crud; use diesel::{dsl::*, result::Error, *}; use lemmy_db_schema::source::moderator::*; -impl Crud<ModRemovePostForm> for ModRemovePost { +impl Crud<ModRemovePostForm, i32> for ModRemovePost { fn read(conn: &PgConnection, from_id: i32) -> Result<Self, Error> { use lemmy_db_schema::schema::mod_remove_post::dsl::*; mod_remove_post.find(from_id).first::<Self>(conn) @@ -23,7 +23,7 @@ impl Crud<ModRemovePostForm> for ModRemovePost { } } -impl Crud<ModLockPostForm> for ModLockPost { +impl Crud<ModLockPostForm, i32> for ModLockPost { fn read(conn: &PgConnection, from_id: i32) -> Result<Self, Error> { use lemmy_db_schema::schema::mod_lock_post::dsl::*; mod_lock_post.find(from_id).first::<Self>(conn) @@ -44,7 +44,7 @@ impl Crud<ModLockPostForm> for ModLockPost { } } -impl Crud<ModStickyPostForm> for ModStickyPost { +impl Crud<ModStickyPostForm, i32> for ModStickyPost { fn read(conn: &PgConnection, from_id: i32) -> Result<Self, Error> { use lemmy_db_schema::schema::mod_sticky_post::dsl::*; mod_sticky_post.find(from_id).first::<Self>(conn) @@ -65,7 +65,7 @@ impl Crud<ModStickyPostForm> for ModStickyPost { } } -impl Crud<ModRemoveCommentForm> for ModRemoveComment { +impl Crud<ModRemoveCommentForm, i32> for ModRemoveComment { fn read(conn: &PgConnection, from_id: i32) -> Result<Self, Error> { use lemmy_db_schema::schema::mod_remove_comment::dsl::*; mod_remove_comment.find(from_id).first::<Self>(conn) @@ -86,7 +86,7 @@ impl Crud<ModRemoveCommentForm> for ModRemoveComment { } } -impl Crud<ModRemoveCommunityForm> for ModRemoveCommunity { +impl Crud<ModRemoveCommunityForm, i32> for ModRemoveCommunity { fn read(conn: &PgConnection, from_id: i32) -> Result<Self, Error> { use lemmy_db_schema::schema::mod_remove_community::dsl::*; mod_remove_community.find(from_id).first::<Self>(conn) @@ -111,7 +111,7 @@ impl Crud<ModRemoveCommunityForm> for ModRemoveCommunity { } } -impl Crud<ModBanFromCommunityForm> for ModBanFromCommunity { +impl Crud<ModBanFromCommunityForm, i32> for ModBanFromCommunity { fn read(conn: &PgConnection, from_id: i32) -> Result<Self, Error> { use lemmy_db_schema::schema::mod_ban_from_community::dsl::*; mod_ban_from_community.find(from_id).first::<Self>(conn) @@ -136,7 +136,7 @@ impl Crud<ModBanFromCommunityForm> for ModBanFromCommunity { } } -impl Crud<ModBanForm> for ModBan { +impl Crud<ModBanForm, i32> for ModBan { fn read(conn: &PgConnection, from_id: i32) -> Result<Self, Error> { use lemmy_db_schema::schema::mod_ban::dsl::*; mod_ban.find(from_id).first::<Self>(conn) @@ -155,7 +155,7 @@ impl Crud<ModBanForm> for ModBan { } } -impl Crud<ModAddCommunityForm> for ModAddCommunity { +impl Crud<ModAddCommunityForm, i32> for ModAddCommunity { fn read(conn: &PgConnection, from_id: i32) -> Result<Self, Error> { use lemmy_db_schema::schema::mod_add_community::dsl::*; mod_add_community.find(from_id).first::<Self>(conn) @@ -176,7 +176,7 @@ impl Crud<ModAddCommunityForm> for ModAddCommunity { } } -impl Crud<ModAddForm> for ModAdd { +impl Crud<ModAddForm, i32> for ModAdd { fn read(conn: &PgConnection, from_id: i32) -> Result<Self, Error> { use lemmy_db_schema::schema::mod_add::dsl::*; mod_add.find(from_id).first::<Self>(conn) diff --git a/crates/db_queries/src/source/password_reset_request.rs b/crates/db_queries/src/source/password_reset_request.rs index dd00e6ff..89c37505 100644 --- a/crates/db_queries/src/source/password_reset_request.rs +++ b/crates/db_queries/src/source/password_reset_request.rs @@ -1,9 +1,13 @@ use crate::Crud; use diesel::{dsl::*, result::Error, PgConnection, *}; -use lemmy_db_schema::{schema::password_reset_request::dsl::*, source::password_reset_request::*}; +use lemmy_db_schema::{ + schema::password_reset_request::dsl::*, + source::password_reset_request::*, + LocalUserId, +}; use sha2::{Digest, Sha256}; -impl Crud<PasswordResetRequestForm> for PasswordResetRequest { +impl Crud<PasswordResetRequestForm, i32> for PasswordResetRequest { fn read(conn: &PgConnection, password_reset_request_id: i32) -> Result<Self, Error> { password_reset_request .find(password_reset_request_id) @@ -28,7 +32,7 @@ impl Crud<PasswordResetRequestForm> for PasswordResetRequest { pub trait PasswordResetRequest_ { fn create_token( conn: &PgConnection, - from_local_user_id: i32, + from_local_user_id: LocalUserId, token: &str, ) -> Result<PasswordResetRequest, Error>; fn read_from_token(conn: &PgConnection, token: &str) -> Result<PasswordResetRequest, Error>; @@ -37,7 +41,7 @@ pub trait PasswordResetRequest_ { impl PasswordResetRequest_ for PasswordResetRequest { fn create_token( conn: &PgConnection, - from_local_user_id: i32, + from_local_user_id: LocalUserId, token: &str, ) -> Result<PasswordResetRequest, Error> { let mut hasher = Sha256::new(); diff --git a/crates/db_queries/src/source/person.rs b/crates/db_queries/src/source/person.rs index 81df7b71..f9979c97 100644 --- a/crates/db_queries/src/source/person.rs +++ b/crates/db_queries/src/source/person.rs @@ -5,6 +5,7 @@ use lemmy_db_schema::{ schema::person::dsl::*, source::person::{Person, PersonForm}, DbUrl, + PersonId, }; mod safe_type { @@ -139,20 +140,20 @@ mod safe_type_alias_2 { } } -impl Crud<PersonForm> for Person { - fn read(conn: &PgConnection, person_id: i32) -> Result<Self, Error> { +impl Crud<PersonForm, PersonId> for Person { + fn read(conn: &PgConnection, person_id: PersonId) -> Result<Self, Error> { person .filter(deleted.eq(false)) .find(person_id) .first::<Self>(conn) } - fn delete(conn: &PgConnection, person_id: i32) -> Result<usize, Error> { + fn delete(conn: &PgConnection, person_id: PersonId) -> Result<usize, Error> { diesel::delete(person.find(person_id)).execute(conn) } fn create(conn: &PgConnection, form: &PersonForm) -> Result<Self, Error> { insert_into(person).values(form).get_result::<Self>(conn) } - fn update(conn: &PgConnection, person_id: i32, form: &PersonForm) -> Result<Self, Error> { + fn update(conn: &PgConnection, person_id: PersonId, form: &PersonForm) -> Result<Self, Error> { diesel::update(person.find(person_id)) .set(form) .get_result::<Self>(conn) @@ -179,14 +180,14 @@ impl ApubObject<PersonForm> for Person { } pub trait Person_ { - fn ban_person(conn: &PgConnection, person_id: i32, ban: bool) -> Result<Person, Error>; + fn ban_person(conn: &PgConnection, person_id: PersonId, ban: bool) -> Result<Person, Error>; fn find_by_name(conn: &PgConnection, name: &str) -> Result<Person, Error>; - fn mark_as_updated(conn: &PgConnection, person_id: i32) -> Result<Person, Error>; - fn delete_account(conn: &PgConnection, person_id: i32) -> Result<Person, Error>; + fn mark_as_updated(conn: &PgConnection, person_id: PersonId) -> Result<Person, Error>; + fn delete_account(conn: &PgConnection, person_id: PersonId) -> Result<Person, Error>; } impl Person_ for Person { - fn ban_person(conn: &PgConnection, person_id: i32, ban: bool) -> Result<Self, Error> { + fn ban_person(conn: &PgConnection, person_id: PersonId, ban: bool) -> Result<Self, Error> { diesel::update(person.find(person_id)) .set(banned.eq(ban)) .get_result::<Self>(conn) @@ -200,13 +201,13 @@ impl Person_ for Person { .first::<Person>(conn) } - fn mark_as_updated(conn: &PgConnection, person_id: i32) -> Result<Person, Error> { + fn mark_as_updated(conn: &PgConnection, person_id: PersonId) -> Result<Person, Error> { diesel::update(person.find(person_id)) .set((last_refreshed_at.eq(naive_now()),)) .get_result::<Self>(conn) } - fn delete_account(conn: &PgConnection, person_id: i32) -> Result<Person, Error> { + fn delete_account(conn: &PgConnection, person_id: PersonId) -> Result<Person, Error> { use lemmy_db_schema::schema::local_user; // Set the local user info to none diff --git a/crates/db_queries/src/source/person_mention.rs b/crates/db_queries/src/source/person_mention.rs index 7a568ba9..dfd626cb 100644 --- a/crates/db_queries/src/source/person_mention.rs +++ b/crates/db_queries/src/source/person_mention.rs @@ -1,9 +1,9 @@ use crate::Crud; use diesel::{dsl::*, result::Error, *}; -use lemmy_db_schema::source::person_mention::*; +use lemmy_db_schema::{source::person_mention::*, PersonId, PersonMentionId}; -impl Crud<PersonMentionForm> for PersonMention { - fn read(conn: &PgConnection, person_mention_id: i32) -> Result<Self, Error> { +impl Crud<PersonMentionForm, PersonMentionId> for PersonMention { + fn read(conn: &PgConnection, person_mention_id: PersonMentionId) -> Result<Self, Error> { use lemmy_db_schema::schema::person_mention::dsl::*; person_mention.find(person_mention_id).first::<Self>(conn) } @@ -22,7 +22,7 @@ impl Crud<PersonMentionForm> for PersonMention { fn update( conn: &PgConnection, - person_mention_id: i32, + person_mention_id: PersonMentionId, person_mention_form: &PersonMentionForm, ) -> Result<Self, Error> { use lemmy_db_schema::schema::person_mention::dsl::*; @@ -35,19 +35,19 @@ impl Crud<PersonMentionForm> for PersonMention { pub trait PersonMention_ { fn update_read( conn: &PgConnection, - person_mention_id: i32, + person_mention_id: PersonMentionId, new_read: bool, ) -> Result<PersonMention, Error>; fn mark_all_as_read( conn: &PgConnection, - for_recipient_id: i32, + for_recipient_id: PersonId, ) -> Result<Vec<PersonMention>, Error>; } impl PersonMention_ for PersonMention { fn update_read( conn: &PgConnection, - person_mention_id: i32, + person_mention_id: PersonMentionId, new_read: bool, ) -> Result<PersonMention, Error> { use lemmy_db_schema::schema::person_mention::dsl::*; @@ -58,7 +58,7 @@ impl PersonMention_ for PersonMention { fn mark_all_as_read( conn: &PgConnection, - for_recipient_id: i32, + for_recipient_id: PersonId, ) -> Result<Vec<PersonMention>, Error> { use lemmy_db_schema::schema::person_mention::dsl::*; diesel::update( diff --git a/crates/db_queries/src/source/post.rs b/crates/db_queries/src/source/post.rs index 6ac5039e..d6492e13 100644 --- a/crates/db_queries/src/source/post.rs +++ b/crates/db_queries/src/source/post.rs @@ -12,16 +12,19 @@ use lemmy_db_schema::{ PostSaved, PostSavedForm, }, + CommunityId, DbUrl, + PersonId, + PostId, }; -impl Crud<PostForm> for Post { - fn read(conn: &PgConnection, post_id: i32) -> Result<Self, Error> { +impl Crud<PostForm, PostId> for Post { + fn read(conn: &PgConnection, post_id: PostId) -> Result<Self, Error> { use lemmy_db_schema::schema::post::dsl::*; post.find(post_id).first::<Self>(conn) } - fn delete(conn: &PgConnection, post_id: i32) -> Result<usize, Error> { + fn delete(conn: &PgConnection, post_id: PostId) -> Result<usize, Error> { use lemmy_db_schema::schema::post::dsl::*; diesel::delete(post.find(post_id)).execute(conn) } @@ -31,7 +34,7 @@ impl Crud<PostForm> for Post { insert_into(post).values(new_post).get_result::<Self>(conn) } - fn update(conn: &PgConnection, post_id: i32, new_post: &PostForm) -> Result<Self, Error> { + fn update(conn: &PgConnection, post_id: PostId, new_post: &PostForm) -> Result<Self, Error> { use lemmy_db_schema::schema::post::dsl::*; diesel::update(post.find(post_id)) .set(new_post) @@ -41,24 +44,39 @@ impl Crud<PostForm> for Post { pub trait Post_ { //fn read(conn: &PgConnection, post_id: i32) -> Result<Post, Error>; - fn list_for_community(conn: &PgConnection, the_community_id: i32) -> Result<Vec<Post>, Error>; - fn update_ap_id(conn: &PgConnection, post_id: i32, apub_id: DbUrl) -> Result<Post, Error>; - fn permadelete_for_creator(conn: &PgConnection, for_creator_id: i32) -> Result<Vec<Post>, Error>; - fn update_deleted(conn: &PgConnection, post_id: i32, new_deleted: bool) -> Result<Post, Error>; - fn update_removed(conn: &PgConnection, post_id: i32, new_removed: bool) -> Result<Post, Error>; + fn list_for_community( + conn: &PgConnection, + the_community_id: CommunityId, + ) -> Result<Vec<Post>, Error>; + fn update_ap_id(conn: &PgConnection, post_id: PostId, apub_id: DbUrl) -> Result<Post, Error>; + fn permadelete_for_creator( + conn: &PgConnection, + for_creator_id: PersonId, + ) -> Result<Vec<Post>, Error>; + fn update_deleted(conn: &PgConnection, post_id: PostId, new_deleted: bool) + -> Result<Post, Error>; + fn update_removed(conn: &PgConnection, post_id: PostId, new_removed: bool) + -> Result<Post, Error>; fn update_removed_for_creator( conn: &PgConnection, - for_creator_id: i32, - for_community_id: Option<i32>, + for_creator_id: PersonId, + for_community_id: Option<CommunityId>, new_removed: bool, ) -> Result<Vec<Post>, Error>; - fn update_locked(conn: &PgConnection, post_id: i32, new_locked: bool) -> Result<Post, Error>; - fn update_stickied(conn: &PgConnection, post_id: i32, new_stickied: bool) -> Result<Post, Error>; - fn is_post_creator(person_id: i32, post_creator_id: i32) -> bool; + fn update_locked(conn: &PgConnection, post_id: PostId, new_locked: bool) -> Result<Post, Error>; + fn update_stickied( + conn: &PgConnection, + post_id: PostId, + new_stickied: bool, + ) -> Result<Post, Error>; + fn is_post_creator(person_id: PersonId, post_creator_id: PersonId) -> bool; } impl Post_ for Post { - fn list_for_community(conn: &PgConnection, the_community_id: i32) -> Result<Vec<Self>, Error> { + fn list_for_community( + conn: &PgConnection, + the_community_id: CommunityId, + ) -> Result<Vec<Self>, Error> { use lemmy_db_schema::schema::post::dsl::*; post .filter(community_id.eq(the_community_id)) @@ -68,7 +86,7 @@ impl Post_ for Post { .load::<Self>(conn) } - fn update_ap_id(conn: &PgConnection, post_id: i32, apub_id: DbUrl) -> Result<Self, Error> { + fn update_ap_id(conn: &PgConnection, post_id: PostId, apub_id: DbUrl) -> Result<Self, Error> { use lemmy_db_schema::schema::post::dsl::*; diesel::update(post.find(post_id)) @@ -76,7 +94,10 @@ impl Post_ for Post { .get_result::<Self>(conn) } - fn permadelete_for_creator(conn: &PgConnection, for_creator_id: i32) -> Result<Vec<Self>, Error> { + fn permadelete_for_creator( + conn: &PgConnection, + for_creator_id: PersonId, + ) -> Result<Vec<Self>, Error> { use lemmy_db_schema::schema::post::dsl::*; let perma_deleted = "*Permananently Deleted*"; @@ -93,14 +114,22 @@ impl Post_ for Post { .get_results::<Self>(conn) } - fn update_deleted(conn: &PgConnection, post_id: i32, new_deleted: bool) -> Result<Self, Error> { + fn update_deleted( + conn: &PgConnection, + post_id: PostId, + new_deleted: bool, + ) -> Result<Self, Error> { use lemmy_db_schema::schema::post::dsl::*; diesel::update(post.find(post_id)) .set((deleted.eq(new_deleted), updated.eq(naive_now()))) .get_result::<Self>(conn) } - fn update_removed(conn: &PgConnection, post_id: i32, new_removed: bool) -> Result<Self, Error> { + fn update_removed( + conn: &PgConnection, + post_id: PostId, + new_removed: bool, + ) -> Result<Self, Error> { use lemmy_db_schema::schema::post::dsl::*; diesel::update(post.find(post_id)) .set((removed.eq(new_removed), updated.eq(naive_now()))) @@ -109,8 +138,8 @@ impl Post_ for Post { fn update_removed_for_creator( conn: &PgConnection, - for_creator_id: i32, - for_community_id: Option<i32>, + for_creator_id: PersonId, + for_community_id: Option<CommunityId>, new_removed: bool, ) -> Result<Vec<Self>, Error> { use lemmy_db_schema::schema::post::dsl::*; @@ -127,21 +156,25 @@ impl Post_ for Post { .get_results::<Self>(conn) } - fn update_locked(conn: &PgConnection, post_id: i32, new_locked: bool) -> Result<Self, Error> { + fn update_locked(conn: &PgConnection, post_id: PostId, new_locked: bool) -> Result<Self, Error> { use lemmy_db_schema::schema::post::dsl::*; diesel::update(post.find(post_id)) .set(locked.eq(new_locked)) .get_result::<Self>(conn) } - fn update_stickied(conn: &PgConnection, post_id: i32, new_stickied: bool) -> Result<Self, Error> { + fn update_stickied( + conn: &PgConnection, + post_id: PostId, + new_stickied: bool, + ) -> Result<Self, Error> { use lemmy_db_schema::schema::post::dsl::*; diesel::update(post.find(post_id)) .set(stickied.eq(new_stickied)) .get_result::<Self>(conn) } - fn is_post_creator(person_id: i32, post_creator_id: i32) -> bool { + fn is_post_creator(person_id: PersonId, post_creator_id: PersonId) -> bool { person_id == post_creator_id } } @@ -163,7 +196,7 @@ impl ApubObject<PostForm> for Post { } } -impl Likeable<PostLikeForm> for PostLike { +impl Likeable<PostLikeForm, PostId> for PostLike { fn like(conn: &PgConnection, post_like_form: &PostLikeForm) -> Result<Self, Error> { use lemmy_db_schema::schema::post_like::dsl::*; insert_into(post_like) @@ -173,7 +206,7 @@ impl Likeable<PostLikeForm> for PostLike { .set(post_like_form) .get_result::<Self>(conn) } - fn remove(conn: &PgConnection, person_id: i32, post_id: i32) -> Result<usize, Error> { + fn remove(conn: &PgConnection, person_id: PersonId, post_id: PostId) -> Result<usize, Error> { use lemmy_db_schema::schema::post_like::dsl; diesel::delete( dsl::post_like diff --git a/crates/db_queries/src/source/post_report.rs b/crates/db_queries/src/source/post_report.rs index e81dc7c0..b4e85573 100644 --- a/crates/db_queries/src/source/post_report.rs +++ b/crates/db_queries/src/source/post_report.rs @@ -1,6 +1,6 @@ use crate::Reportable; use diesel::{dsl::*, result::Error, *}; -use lemmy_db_schema::{naive_now, source::post_report::*}; +use lemmy_db_schema::{naive_now, source::post_report::*, PersonId}; impl Reportable<PostReportForm> for PostReport { /// creates a post report and returns it @@ -19,7 +19,11 @@ impl Reportable<PostReportForm> for PostReport { /// * `conn` - the postgres connection /// * `report_id` - the id of the report to resolve /// * `by_resolver_id` - the id of the user resolving the report - fn resolve(conn: &PgConnection, report_id: i32, by_resolver_id: i32) -> Result<usize, Error> { + fn resolve( + conn: &PgConnection, + report_id: i32, + by_resolver_id: PersonId, + ) -> Result<usize, Error> { use lemmy_db_schema::schema::post_report::dsl::*; update(post_report.find(report_id)) .set(( @@ -35,7 +39,11 @@ impl Reportable<PostReportForm> for PostReport { /// * `conn` - the postgres connection /// * `report_id` - the id of the report to unresolve /// * `by_resolver_id` - the id of the user unresolving the report - fn unresolve(conn: &PgConnection, report_id: i32, by_resolver_id: i32) -> Result<usize, Error> { + fn unresolve( + conn: &PgConnection, + report_id: i32, + by_resolver_id: PersonId, + ) -> Result<usize, Error> { use lemmy_db_schema::schema::post_report::dsl::*; update(post_report.find(report_id)) .set(( diff --git a/crates/db_queries/src/source/private_message.rs b/crates/db_queries/src/source/private_message.rs index 936471f1..fe245689 100644 --- a/crates/db_queries/src/source/private_message.rs +++ b/crates/db_queries/src/source/private_message.rs @@ -1,9 +1,9 @@ use crate::{ApubObject, Crud}; use diesel::{dsl::*, result::Error, *}; -use lemmy_db_schema::{naive_now, source::private_message::*, DbUrl}; +use lemmy_db_schema::{naive_now, source::private_message::*, DbUrl, PersonId, PrivateMessageId}; -impl Crud<PrivateMessageForm> for PrivateMessage { - fn read(conn: &PgConnection, private_message_id: i32) -> Result<Self, Error> { +impl Crud<PrivateMessageForm, PrivateMessageId> for PrivateMessage { + fn read(conn: &PgConnection, private_message_id: PrivateMessageId) -> Result<Self, Error> { use lemmy_db_schema::schema::private_message::dsl::*; private_message.find(private_message_id).first::<Self>(conn) } @@ -17,7 +17,7 @@ impl Crud<PrivateMessageForm> for PrivateMessage { fn update( conn: &PgConnection, - private_message_id: i32, + private_message_id: PrivateMessageId, private_message_form: &PrivateMessageForm, ) -> Result<Self, Error> { use lemmy_db_schema::schema::private_message::dsl::*; @@ -52,34 +52,34 @@ impl ApubObject<PrivateMessageForm> for PrivateMessage { pub trait PrivateMessage_ { fn update_ap_id( conn: &PgConnection, - private_message_id: i32, + private_message_id: PrivateMessageId, apub_id: DbUrl, ) -> Result<PrivateMessage, Error>; fn update_content( conn: &PgConnection, - private_message_id: i32, + private_message_id: PrivateMessageId, new_content: &str, ) -> Result<PrivateMessage, Error>; fn update_deleted( conn: &PgConnection, - private_message_id: i32, + private_message_id: PrivateMessageId, new_deleted: bool, ) -> Result<PrivateMessage, Error>; fn update_read( conn: &PgConnection, - private_message_id: i32, + private_message_id: PrivateMessageId, new_read: bool, ) -> Result<PrivateMessage, Error>; fn mark_all_as_read( conn: &PgConnection, - for_recipient_id: i32, + for_recipient_id: PersonId, ) -> Result<Vec<PrivateMessage>, Error>; } impl PrivateMessage_ for PrivateMessage { fn update_ap_id( conn: &PgConnection, - private_message_id: i32, + private_message_id: PrivateMessageId, apub_id: DbUrl, ) -> Result<PrivateMessage, Error> { use lemmy_db_schema::schema::private_message::dsl::*; @@ -91,7 +91,7 @@ impl PrivateMessage_ for PrivateMessage { fn update_content( conn: &PgConnection, - private_message_id: i32, + private_message_id: PrivateMessageId, new_content: &str, ) -> Result<PrivateMessage, Error> { use lemmy_db_schema::schema::private_message::dsl::*; @@ -102,7 +102,7 @@ impl PrivateMessage_ for PrivateMessage { fn update_deleted( conn: &PgConnection, - private_message_id: i32, + private_message_id: PrivateMessageId, new_deleted: bool, ) -> Result<PrivateMessage, Error> { use lemmy_db_schema::schema::private_message::dsl::*; @@ -113,7 +113,7 @@ impl PrivateMessage_ for PrivateMessage { fn update_read( conn: &PgConnection, - private_message_id: i32, + private_message_id: PrivateMessageId, new_read: bool, ) -> Result<PrivateMessage, Error> { use lemmy_db_schema::schema::private_message::dsl::*; @@ -124,7 +124,7 @@ impl PrivateMessage_ for PrivateMessage { fn mark_all_as_read( conn: &PgConnection, - for_recipient_id: i32, + for_recipient_id: PersonId, ) -> Result<Vec<PrivateMessage>, Error> { use lemmy_db_schema::schema::private_message::dsl::*; diesel::update( diff --git a/crates/db_queries/src/source/site.rs b/crates/db_queries/src/source/site.rs index 2510f46c..d688546f 100644 --- a/crates/db_queries/src/source/site.rs +++ b/crates/db_queries/src/source/site.rs @@ -1,8 +1,8 @@ use crate::Crud; use diesel::{dsl::*, result::Error, *}; -use lemmy_db_schema::{naive_now, source::site::*}; +use lemmy_db_schema::{naive_now, source::site::*, PersonId}; -impl Crud<SiteForm> for Site { +impl Crud<SiteForm, i32> for Site { fn read(conn: &PgConnection, _site_id: i32) -> Result<Self, Error> { use lemmy_db_schema::schema::site::dsl::*; site.first::<Self>(conn) @@ -26,12 +26,12 @@ impl Crud<SiteForm> for Site { } pub trait Site_ { - fn transfer(conn: &PgConnection, new_creator_id: i32) -> Result<Site, Error>; + fn transfer(conn: &PgConnection, new_creator_id: PersonId) -> Result<Site, Error>; fn read_simple(conn: &PgConnection) -> Result<Site, Error>; } impl Site_ for Site { - fn transfer(conn: &PgConnection, new_creator_id: i32) -> Result<Site, Error> { + fn transfer(conn: &PgConnection, new_creator_id: PersonId) -> Result<Site, Error> { use lemmy_db_schema::schema::site::dsl::*; diesel::update(site.find(1)) .set((creator_id.eq(new_creator_id), updated.eq(naive_now()))) diff --git a/crates/db_schema/Cargo.toml b/crates/db_schema/Cargo.toml index 1da8b68f..70f3364e 100644 --- a/crates/db_schema/Cargo.toml +++ b/crates/db_schema/Cargo.toml @@ -13,3 +13,4 @@ serde = { version = "1.0.123", features = ["derive"] } serde_json = { version = "1.0.61", features = ["preserve_order"] } log = "0.4.14" url = { version = "2.2.1", features = ["serde"] } +diesel-derive-newtype = "0.1" diff --git a/crates/db_schema/src/lib.rs b/crates/db_schema/src/lib.rs index f44567b9..6b07e5ce 100644 --- a/crates/db_schema/src/lib.rs +++ b/crates/db_schema/src/lib.rs @@ -1,6 +1,9 @@ #[macro_use] extern crate diesel; +#[macro_use] +extern crate diesel_derive_newtype; + use chrono::NaiveDateTime; use diesel::{ backend::Backend, @@ -10,6 +13,7 @@ use diesel::{ }; use serde::{Deserialize, Serialize}; use std::{ + fmt, fmt::{Display, Formatter}, io::Write, }; @@ -18,6 +22,45 @@ use url::Url; pub mod schema; pub mod source; +#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, DieselNewType)] +pub struct PostId(pub i32); + +impl fmt::Display for PostId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} + +#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, DieselNewType)] +pub struct PersonId(pub i32); + +#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, DieselNewType)] +pub struct CommentId(pub i32); + +impl fmt::Display for CommentId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} + +#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, DieselNewType)] +pub struct CommunityId(pub i32); + +#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, DieselNewType)] +pub struct LocalUserId(pub i32); + +#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, DieselNewType)] +pub struct PrivateMessageId(i32); + +impl fmt::Display for PrivateMessageId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} + +#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, DieselNewType)] +pub struct PersonMentionId(i32); + #[repr(transparent)] #[derive(Clone, PartialEq, Serialize, Deserialize, Debug, AsExpression, FromSqlRow)] #[sql_type = "Text"] diff --git a/crates/db_schema/src/source/comment.rs b/crates/db_schema/src/source/comment.rs index e323a9ad..8a91f601 100644 --- a/crates/db_schema/src/source/comment.rs +++ b/crates/db_schema/src/source/comment.rs @@ -1,7 +1,10 @@ use crate::{ schema::{comment, comment_alias_1, comment_like, comment_saved}, source::post::Post, + CommentId, DbUrl, + PersonId, + PostId, }; use serde::Serialize; @@ -16,10 +19,10 @@ use serde::Serialize; #[belongs_to(Post)] #[table_name = "comment"] pub struct Comment { - pub id: i32, - pub creator_id: i32, - pub post_id: i32, - pub parent_id: Option<i32>, + pub id: CommentId, + pub creator_id: PersonId, + pub post_id: PostId, + pub parent_id: Option<CommentId>, pub content: String, pub removed: bool, pub read: bool, // Whether the recipient has read the comment or not @@ -34,10 +37,10 @@ pub struct Comment { #[belongs_to(Post)] #[table_name = "comment_alias_1"] pub struct CommentAlias1 { - pub id: i32, - pub creator_id: i32, - pub post_id: i32, - pub parent_id: Option<i32>, + pub id: CommentId, + pub creator_id: PersonId, + pub post_id: PostId, + pub parent_id: Option<CommentId>, pub content: String, pub removed: bool, pub read: bool, // Whether the recipient has read the comment or not @@ -51,9 +54,9 @@ pub struct CommentAlias1 { #[derive(Insertable, AsChangeset, Clone)] #[table_name = "comment"] pub struct CommentForm { - pub creator_id: i32, - pub post_id: i32, - pub parent_id: Option<i32>, + pub creator_id: PersonId, + pub post_id: PostId, + pub parent_id: Option<CommentId>, pub content: String, pub removed: Option<bool>, pub read: Option<bool>, @@ -69,9 +72,9 @@ pub struct CommentForm { #[table_name = "comment_like"] pub struct CommentLike { pub id: i32, - pub person_id: i32, - pub comment_id: i32, - pub post_id: i32, // TODO this is redundant + pub person_id: PersonId, + pub comment_id: CommentId, + pub post_id: PostId, // TODO this is redundant pub score: i16, pub published: chrono::NaiveDateTime, } @@ -79,9 +82,9 @@ pub struct CommentLike { #[derive(Insertable, AsChangeset, Clone)] #[table_name = "comment_like"] pub struct CommentLikeForm { - pub person_id: i32, - pub comment_id: i32, - pub post_id: i32, // TODO this is redundant + pub person_id: PersonId, + pub comment_id: CommentId, + pub post_id: PostId, // TODO this is redundant pub score: i16, } @@ -90,14 +93,14 @@ pub struct CommentLikeForm { #[table_name = "comment_saved"] pub struct CommentSaved { pub id: i32, - pub comment_id: i32, - pub person_id: i32, + pub comment_id: CommentId, + pub person_id: PersonId, pub published: chrono::NaiveDateTime, } #[derive(Insertable, AsChangeset)] #[table_name = "comment_saved"] pub struct CommentSavedForm { - pub comment_id: i32, - pub person_id: i32, + pub comment_id: CommentId, + pub person_id: PersonId, } diff --git a/crates/db_schema/src/source/comment_report.rs b/crates/db_schema/src/source/comment_report.rs index ec53408d..7b47bef2 100644 --- a/crates/db_schema/src/source/comment_report.rs +++ b/crates/db_schema/src/source/comment_report.rs @@ -1,4 +1,4 @@ -use crate::{schema::comment_report, source::comment::Comment}; +use crate::{schema::comment_report, source::comment::Comment, CommentId, PersonId}; use serde::{Deserialize, Serialize}; #[derive( @@ -8,12 +8,12 @@ use serde::{Deserialize, Serialize}; #[table_name = "comment_report"] pub struct CommentReport { pub id: i32, - pub creator_id: i32, - pub comment_id: i32, + pub creator_id: PersonId, + pub comment_id: CommentId, pub original_comment_text: String, pub reason: String, pub resolved: bool, - pub resolver_id: Option<i32>, + pub resolver_id: Option<PersonId>, pub published: chrono::NaiveDateTime, pub updated: Option<chrono::NaiveDateTime>, } @@ -21,8 +21,8 @@ pub struct CommentReport { #[derive(Insertable, AsChangeset, Clone)] #[table_name = "comment_report"] pub struct CommentReportForm { - pub creator_id: i32, - pub comment_id: i32, + pub creator_id: PersonId, + pub comment_id: CommentId, pub original_comment_text: String, pub reason: String, } diff --git a/crates/db_schema/src/source/community.rs b/crates/db_schema/src/source/community.rs index 98c302dc..81789ecd 100644 --- a/crates/db_schema/src/source/community.rs +++ b/crates/db_schema/src/source/community.rs @@ -1,17 +1,19 @@ use crate::{ schema::{community, community_follower, community_moderator, community_person_ban}, + CommunityId, DbUrl, + PersonId, }; use serde::Serialize; #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "community"] pub struct Community { - pub id: i32, + pub id: CommunityId, pub name: String, pub title: String, pub description: Option<String>, - pub creator_id: i32, + pub creator_id: PersonId, pub removed: bool, pub published: chrono::NaiveDateTime, pub updated: Option<chrono::NaiveDateTime>, @@ -33,11 +35,11 @@ pub struct Community { #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "community"] pub struct CommunitySafe { - pub id: i32, + pub id: CommunityId, pub name: String, pub title: String, pub description: Option<String>, - pub creator_id: i32, + pub creator_id: PersonId, pub removed: bool, pub published: chrono::NaiveDateTime, pub updated: Option<chrono::NaiveDateTime>, @@ -55,7 +57,7 @@ pub struct CommunityForm { pub name: String, pub title: String, pub description: Option<String>, - pub creator_id: i32, + pub creator_id: PersonId, pub removed: Option<bool>, pub published: Option<chrono::NaiveDateTime>, pub updated: Option<chrono::NaiveDateTime>, @@ -78,16 +80,16 @@ pub struct CommunityForm { #[table_name = "community_moderator"] pub struct CommunityModerator { pub id: i32, - pub community_id: i32, - pub person_id: i32, + pub community_id: CommunityId, + pub person_id: PersonId, pub published: chrono::NaiveDateTime, } #[derive(Insertable, AsChangeset, Clone)] #[table_name = "community_moderator"] pub struct CommunityModeratorForm { - pub community_id: i32, - pub person_id: i32, + pub community_id: CommunityId, + pub person_id: PersonId, } #[derive(Identifiable, Queryable, Associations, PartialEq, Debug)] @@ -95,16 +97,16 @@ pub struct CommunityModeratorForm { #[table_name = "community_person_ban"] pub struct CommunityPersonBan { pub id: i32, - pub community_id: i32, - pub person_id: i32, + pub community_id: CommunityId, + pub person_id: PersonId, pub published: chrono::NaiveDateTime, } #[derive(Insertable, AsChangeset, Clone)] #[table_name = "community_person_ban"] pub struct CommunityPersonBanForm { - pub community_id: i32, - pub person_id: i32, + pub community_id: CommunityId, + pub person_id: PersonId, } #[derive(Identifiable, Queryable, Associations, PartialEq, Debug)] @@ -112,8 +114,8 @@ pub struct CommunityPersonBanForm { #[table_name = "community_follower"] pub struct CommunityFollower { pub id: i32, - pub community_id: i32, - pub person_id: i32, + pub community_id: CommunityId, + pub person_id: PersonId, pub published: chrono::NaiveDateTime, pub pending: Option<bool>, } @@ -121,7 +123,7 @@ pub struct CommunityFollower { #[derive(Insertable, AsChangeset, Clone)] #[table_name = "community_follower"] pub struct CommunityFollowerForm { - pub community_id: i32, - pub person_id: i32, + pub community_id: CommunityId, + pub person_id: PersonId, pub pending: bool, } diff --git a/crates/db_schema/src/source/local_user.rs b/crates/db_schema/src/source/local_user.rs index 69201797..750a2255 100644 --- a/crates/db_schema/src/source/local_user.rs +++ b/crates/db_schema/src/source/local_user.rs @@ -1,11 +1,11 @@ -use crate::schema::local_user; +use crate::{schema::local_user, LocalUserId, PersonId}; 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 id: LocalUserId, + pub person_id: PersonId, pub password_encrypted: String, pub email: Option<String>, pub admin: bool, @@ -23,7 +23,7 @@ pub struct LocalUser { #[derive(Insertable, AsChangeset, Clone)] #[table_name = "local_user"] pub struct LocalUserForm { - pub person_id: i32, + pub person_id: PersonId, pub password_encrypted: String, pub email: Option<Option<String>>, pub admin: Option<bool>, @@ -41,8 +41,8 @@ pub struct LocalUserForm { #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "local_user"] pub struct LocalUserSettings { - pub id: i32, - pub person_id: i32, + pub id: LocalUserId, + pub person_id: PersonId, pub email: Option<String>, pub admin: bool, pub show_nsfw: bool, diff --git a/crates/db_schema/src/source/moderator.rs b/crates/db_schema/src/source/moderator.rs index dc890f16..19580fb9 100644 --- a/crates/db_schema/src/source/moderator.rs +++ b/crates/db_schema/src/source/moderator.rs @@ -1,13 +1,19 @@ -use crate::schema::{ - mod_add, - mod_add_community, - mod_ban, - mod_ban_from_community, - mod_lock_post, - mod_remove_comment, - mod_remove_community, - mod_remove_post, - mod_sticky_post, +use crate::{ + schema::{ + mod_add, + mod_add_community, + mod_ban, + mod_ban_from_community, + mod_lock_post, + mod_remove_comment, + mod_remove_community, + mod_remove_post, + mod_sticky_post, + }, + CommentId, + CommunityId, + PersonId, + PostId, }; use serde::Serialize; @@ -15,8 +21,8 @@ use serde::Serialize; #[table_name = "mod_remove_post"] pub struct ModRemovePost { pub id: i32, - pub mod_person_id: i32, - pub post_id: i32, + pub mod_person_id: PersonId, + pub post_id: PostId, pub reason: Option<String>, pub removed: Option<bool>, pub when_: chrono::NaiveDateTime, @@ -25,8 +31,8 @@ pub struct ModRemovePost { #[derive(Insertable, AsChangeset)] #[table_name = "mod_remove_post"] pub struct ModRemovePostForm { - pub mod_person_id: i32, - pub post_id: i32, + pub mod_person_id: PersonId, + pub post_id: PostId, pub reason: Option<String>, pub removed: Option<bool>, } @@ -35,8 +41,8 @@ pub struct ModRemovePostForm { #[table_name = "mod_lock_post"] pub struct ModLockPost { pub id: i32, - pub mod_person_id: i32, - pub post_id: i32, + pub mod_person_id: PersonId, + pub post_id: PostId, pub locked: Option<bool>, pub when_: chrono::NaiveDateTime, } @@ -44,8 +50,8 @@ pub struct ModLockPost { #[derive(Insertable, AsChangeset)] #[table_name = "mod_lock_post"] pub struct ModLockPostForm { - pub mod_person_id: i32, - pub post_id: i32, + pub mod_person_id: PersonId, + pub post_id: PostId, pub locked: Option<bool>, } @@ -53,8 +59,8 @@ pub struct ModLockPostForm { #[table_name = "mod_sticky_post"] pub struct ModStickyPost { pub id: i32, - pub mod_person_id: i32, - pub post_id: i32, + pub mod_person_id: PersonId, + pub post_id: PostId, pub stickied: Option<bool>, pub when_: chrono::NaiveDateTime, } @@ -62,8 +68,8 @@ pub struct ModStickyPost { #[derive(Insertable, AsChangeset)] #[table_name = "mod_sticky_post"] pub struct ModStickyPostForm { - pub mod_person_id: i32, - pub post_id: i32, + pub mod_person_id: PersonId, + pub post_id: PostId, pub stickied: Option<bool>, } @@ -71,8 +77,8 @@ pub struct ModStickyPostForm { #[table_name = "mod_remove_comment"] pub struct ModRemoveComment { pub id: i32, - pub mod_person_id: i32, - pub comment_id: i32, + pub mod_person_id: PersonId, + pub comment_id: CommentId, pub reason: Option<String>, pub removed: Option<bool>, pub when_: chrono::NaiveDateTime, @@ -81,8 +87,8 @@ pub struct ModRemoveComment { #[derive(Insertable, AsChangeset)] #[table_name = "mod_remove_comment"] pub struct ModRemoveCommentForm { - pub mod_person_id: i32, - pub comment_id: i32, + pub mod_person_id: PersonId, + pub comment_id: CommentId, pub reason: Option<String>, pub removed: Option<bool>, } @@ -91,8 +97,8 @@ pub struct ModRemoveCommentForm { #[table_name = "mod_remove_community"] pub struct ModRemoveCommunity { pub id: i32, - pub mod_person_id: i32, - pub community_id: i32, + pub mod_person_id: PersonId, + pub community_id: CommunityId, pub reason: Option<String>, pub removed: Option<bool>, pub expires: Option<chrono::NaiveDateTime>, @@ -102,8 +108,8 @@ pub struct ModRemoveCommunity { #[derive(Insertable, AsChangeset)] #[table_name = "mod_remove_community"] pub struct ModRemoveCommunityForm { - pub mod_person_id: i32, - pub community_id: i32, + pub mod_person_id: PersonId, + pub community_id: CommunityId, pub reason: Option<String>, pub removed: Option<bool>, pub expires: Option<chrono::NaiveDateTime>, @@ -113,9 +119,9 @@ pub struct ModRemoveCommunityForm { #[table_name = "mod_ban_from_community"] pub struct ModBanFromCommunity { pub id: i32, - pub mod_person_id: i32, - pub other_person_id: i32, - pub community_id: i32, + pub mod_person_id: PersonId, + pub other_person_id: PersonId, + pub community_id: CommunityId, pub reason: Option<String>, pub banned: Option<bool>, pub expires: Option<chrono::NaiveDateTime>, @@ -125,9 +131,9 @@ pub struct ModBanFromCommunity { #[derive(Insertable, AsChangeset)] #[table_name = "mod_ban_from_community"] pub struct ModBanFromCommunityForm { - pub mod_person_id: i32, - pub other_person_id: i32, - pub community_id: i32, + pub mod_person_id: PersonId, + pub other_person_id: PersonId, + pub community_id: CommunityId, pub reason: Option<String>, pub banned: Option<bool>, pub expires: Option<chrono::NaiveDateTime>, @@ -137,8 +143,8 @@ pub struct ModBanFromCommunityForm { #[table_name = "mod_ban"] pub struct ModBan { pub id: i32, - pub mod_person_id: i32, - pub other_person_id: i32, + pub mod_person_id: PersonId, + pub other_person_id: PersonId, pub reason: Option<String>, pub banned: Option<bool>, pub expires: Option<chrono::NaiveDateTime>, @@ -148,8 +154,8 @@ pub struct ModBan { #[derive(Insertable, AsChangeset)] #[table_name = "mod_ban"] pub struct ModBanForm { - pub mod_person_id: i32, - pub other_person_id: i32, + pub mod_person_id: PersonId, + pub other_person_id: PersonId, pub reason: Option<String>, pub banned: Option<bool>, pub expires: Option<chrono::NaiveDateTime>, @@ -159,9 +165,9 @@ pub struct ModBanForm { #[table_name = "mod_add_community"] pub struct ModAddCommunity { pub id: i32, - pub mod_person_id: i32, - pub other_person_id: i32, - pub community_id: i32, + pub mod_person_id: PersonId, + pub other_person_id: PersonId, + pub community_id: CommunityId, pub removed: Option<bool>, pub when_: chrono::NaiveDateTime, } @@ -169,9 +175,9 @@ pub struct ModAddCommunity { #[derive(Insertable, AsChangeset)] #[table_name = "mod_add_community"] pub struct ModAddCommunityForm { - pub mod_person_id: i32, - pub other_person_id: i32, - pub community_id: i32, + pub mod_person_id: PersonId, + pub other_person_id: PersonId, + pub community_id: CommunityId, pub removed: Option<bool>, } @@ -179,8 +185,8 @@ pub struct ModAddCommunityForm { #[table_name = "mod_add"] pub struct ModAdd { pub id: i32, - pub mod_person_id: i32, - pub other_person_id: i32, + pub mod_person_id: PersonId, + pub other_person_id: PersonId, pub removed: Option<bool>, pub when_: chrono::NaiveDateTime, } @@ -188,7 +194,7 @@ pub struct ModAdd { #[derive(Insertable, AsChangeset)] #[table_name = "mod_add"] pub struct ModAddForm { - pub mod_person_id: i32, - pub other_person_id: i32, + pub mod_person_id: PersonId, + pub other_person_id: PersonId, pub removed: Option<bool>, } diff --git a/crates/db_schema/src/source/password_reset_request.rs b/crates/db_schema/src/source/password_reset_request.rs index f03bcb03..0af2d024 100644 --- a/crates/db_schema/src/source/password_reset_request.rs +++ b/crates/db_schema/src/source/password_reset_request.rs @@ -1,4 +1,4 @@ -use crate::schema::password_reset_request; +use crate::{schema::password_reset_request, LocalUserId}; #[derive(Queryable, Identifiable, PartialEq, Debug)] #[table_name = "password_reset_request"] @@ -6,12 +6,12 @@ pub struct PasswordResetRequest { pub id: i32, pub token_encrypted: String, pub published: chrono::NaiveDateTime, - pub local_user_id: i32, + pub local_user_id: LocalUserId, } #[derive(Insertable, AsChangeset)] #[table_name = "password_reset_request"] pub struct PasswordResetRequestForm { - pub local_user_id: i32, + pub local_user_id: LocalUserId, pub token_encrypted: String, } diff --git a/crates/db_schema/src/source/person.rs b/crates/db_schema/src/source/person.rs index b3af21c3..f669f0c5 100644 --- a/crates/db_schema/src/source/person.rs +++ b/crates/db_schema/src/source/person.rs @@ -1,13 +1,14 @@ use crate::{ schema::{person, person_alias_1, person_alias_2}, DbUrl, + PersonId, }; use serde::Serialize; #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person"] pub struct Person { - pub id: i32, + pub id: PersonId, pub name: String, pub preferred_username: Option<String>, pub avatar: Option<DbUrl>, @@ -30,7 +31,7 @@ pub struct Person { #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person"] pub struct PersonSafe { - pub id: i32, + pub id: PersonId, pub name: String, pub preferred_username: Option<String>, pub avatar: Option<DbUrl>, @@ -49,7 +50,7 @@ pub struct PersonSafe { #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person_alias_1"] pub struct PersonAlias1 { - pub id: i32, + pub id: PersonId, pub name: String, pub preferred_username: Option<String>, pub avatar: Option<DbUrl>, @@ -71,7 +72,7 @@ pub struct PersonAlias1 { #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person_alias_1"] pub struct PersonSafeAlias1 { - pub id: i32, + pub id: PersonId, pub name: String, pub preferred_username: Option<String>, pub avatar: Option<DbUrl>, @@ -90,7 +91,7 @@ pub struct PersonSafeAlias1 { #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person_alias_2"] pub struct PersonAlias2 { - pub id: i32, + pub id: PersonId, pub name: String, pub preferred_username: Option<String>, pub avatar: Option<DbUrl>, @@ -112,7 +113,7 @@ pub struct PersonAlias2 { #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "person_alias_1"] pub struct PersonSafeAlias2 { - pub id: i32, + pub id: PersonId, pub name: String, pub preferred_username: Option<String>, pub avatar: Option<DbUrl>, diff --git a/crates/db_schema/src/source/person_mention.rs b/crates/db_schema/src/source/person_mention.rs index 6ad9c078..61ed32b0 100644 --- a/crates/db_schema/src/source/person_mention.rs +++ b/crates/db_schema/src/source/person_mention.rs @@ -1,13 +1,19 @@ -use crate::{schema::person_mention, source::comment::Comment}; +use crate::{ + schema::person_mention, + source::comment::Comment, + CommentId, + PersonId, + PersonMentionId, +}; use serde::Serialize; #[derive(Clone, Queryable, Associations, Identifiable, PartialEq, Debug, Serialize)] #[belongs_to(Comment)] #[table_name = "person_mention"] pub struct PersonMention { - pub id: i32, - pub recipient_id: i32, - pub comment_id: i32, + pub id: PersonMentionId, + pub recipient_id: PersonId, + pub comment_id: CommentId, pub read: bool, pub published: chrono::NaiveDateTime, } @@ -15,7 +21,7 @@ pub struct PersonMention { #[derive(Insertable, AsChangeset)] #[table_name = "person_mention"] pub struct PersonMentionForm { - pub recipient_id: i32, - pub comment_id: i32, + pub recipient_id: PersonId, + pub comment_id: CommentId, pub read: Option<bool>, } diff --git a/crates/db_schema/src/source/post.rs b/crates/db_schema/src/source/post.rs index 38616f12..34b889d4 100644 --- a/crates/db_schema/src/source/post.rs +++ b/crates/db_schema/src/source/post.rs @@ -1,18 +1,21 @@ use crate::{ schema::{post, post_like, post_read, post_saved}, + CommunityId, DbUrl, + PersonId, + PostId, }; use serde::Serialize; #[derive(Clone, Queryable, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "post"] pub struct Post { - pub id: i32, + pub id: PostId, pub name: String, pub url: Option<DbUrl>, pub body: Option<String>, - pub creator_id: i32, - pub community_id: i32, + pub creator_id: PersonId, + pub community_id: CommunityId, pub removed: bool, pub locked: bool, pub published: chrono::NaiveDateTime, @@ -34,8 +37,8 @@ pub struct PostForm { pub name: String, pub url: Option<DbUrl>, pub body: Option<String>, - pub creator_id: i32, - pub community_id: i32, + pub creator_id: PersonId, + pub community_id: CommunityId, pub removed: Option<bool>, pub locked: Option<bool>, pub published: Option<chrono::NaiveDateTime>, @@ -56,8 +59,8 @@ pub struct PostForm { #[table_name = "post_like"] pub struct PostLike { pub id: i32, - pub post_id: i32, - pub person_id: i32, + pub post_id: PostId, + pub person_id: PersonId, pub score: i16, pub published: chrono::NaiveDateTime, } @@ -65,8 +68,8 @@ pub struct PostLike { #[derive(Insertable, AsChangeset, Clone)] #[table_name = "post_like"] pub struct PostLikeForm { - pub post_id: i32, - pub person_id: i32, + pub post_id: PostId, + pub person_id: PersonId, pub score: i16, } @@ -75,16 +78,16 @@ pub struct PostLikeForm { #[table_name = "post_saved"] pub struct PostSaved { pub id: i32, - pub post_id: i32, - pub person_id: i32, + pub post_id: PostId, + pub person_id: PersonId, pub published: chrono::NaiveDateTime, } #[derive(Insertable, AsChangeset)] #[table_name = "post_saved"] pub struct PostSavedForm { - pub post_id: i32, - pub person_id: i32, + pub post_id: PostId, + pub person_id: PersonId, } #[derive(Identifiable, Queryable, Associations, PartialEq, Debug)] @@ -92,14 +95,14 @@ pub struct PostSavedForm { #[table_name = "post_read"] pub struct PostRead { pub id: i32, - pub post_id: i32, - pub person_id: i32, + pub post_id: PostId, + pub person_id: PersonId, pub published: chrono::NaiveDateTime, } #[derive(Insertable, AsChangeset)] #[table_name = "post_read"] pub struct PostReadForm { - pub post_id: i32, - pub person_id: i32, + pub post_id: PostId, + pub person_id: PersonId, } diff --git a/crates/db_schema/src/source/post_report.rs b/crates/db_schema/src/source/post_report.rs index 62ef31cd..d32d7e1e 100644 --- a/crates/db_schema/src/source/post_report.rs +++ b/crates/db_schema/src/source/post_report.rs @@ -1,4 +1,4 @@ -use crate::{schema::post_report, source::post::Post, DbUrl}; +use crate::{schema::post_report, source::post::Post, DbUrl, PersonId, PostId}; use serde::{Deserialize, Serialize}; #[derive( @@ -8,14 +8,14 @@ use serde::{Deserialize, Serialize}; #[table_name = "post_report"] pub struct PostReport { pub id: i32, - pub creator_id: i32, - pub post_id: i32, + pub creator_id: PersonId, + pub post_id: PostId, pub original_post_name: String, pub original_post_url: Option<DbUrl>, pub original_post_body: Option<String>, pub reason: String, pub resolved: bool, - pub resolver_id: Option<i32>, + pub resolver_id: Option<PersonId>, pub published: chrono::NaiveDateTime, pub updated: Option<chrono::NaiveDateTime>, } @@ -23,8 +23,8 @@ pub struct PostReport { #[derive(Insertable, AsChangeset, Clone)] #[table_name = "post_report"] pub struct PostReportForm { - pub creator_id: i32, - pub post_id: i32, + pub creator_id: PersonId, + pub post_id: PostId, pub original_post_name: String, pub original_post_url: Option<DbUrl>, pub original_post_body: Option<String>, diff --git a/crates/db_schema/src/source/private_message.rs b/crates/db_schema/src/source/private_message.rs index 949c9770..6d46c012 100644 --- a/crates/db_schema/src/source/private_message.rs +++ b/crates/db_schema/src/source/private_message.rs @@ -1,12 +1,12 @@ -use crate::{schema::private_message, DbUrl}; +use crate::{schema::private_message, DbUrl, PersonId, PrivateMessageId}; use serde::Serialize; #[derive(Clone, Queryable, Associations, Identifiable, PartialEq, Debug, Serialize)] #[table_name = "private_message"] pub struct PrivateMessage { - pub id: i32, - pub creator_id: i32, - pub recipient_id: i32, + pub id: PrivateMessageId, + pub creator_id: PersonId, + pub recipient_id: PersonId, pub content: String, pub deleted: bool, pub read: bool, @@ -19,8 +19,8 @@ pub struct PrivateMessage { #[derive(Insertable, AsChangeset)] #[table_name = "private_message"] pub struct PrivateMessageForm { - pub creator_id: i32, - pub recipient_id: i32, + pub creator_id: PersonId, + pub recipient_id: PersonId, pub content: String, pub deleted: Option<bool>, pub read: Option<bool>, diff --git a/crates/db_schema/src/source/site.rs b/crates/db_schema/src/source/site.rs index 998e9f9d..0723772e 100644 --- a/crates/db_schema/src/source/site.rs +++ b/crates/db_schema/src/source/site.rs @@ -1,4 +1,4 @@ -use crate::{schema::site, DbUrl}; +use crate::{schema::site, DbUrl, PersonId}; use serde::Serialize; #[derive(Queryable, Identifiable, PartialEq, Debug, Clone, Serialize)] @@ -7,7 +7,7 @@ pub struct Site { pub id: i32, pub name: String, pub description: Option<String>, - pub creator_id: i32, + pub creator_id: PersonId, pub published: chrono::NaiveDateTime, pub updated: Option<chrono::NaiveDateTime>, pub enable_downvotes: bool, @@ -22,7 +22,7 @@ pub struct Site { pub struct SiteForm { pub name: String, pub description: Option<String>, - pub creator_id: i32, + pub creator_id: PersonId, pub updated: Option<chrono::NaiveDateTime>, pub enable_downvotes: bool, pub open_registration: bool, diff --git a/crates/db_views/src/comment_report_view.rs b/crates/db_views/src/comment_report_view.rs index d06d17fb..2aa4bdfc 100644 --- a/crates/db_views/src/comment_report_view.rs +++ b/crates/db_views/src/comment_report_view.rs @@ -9,6 +9,7 @@ use lemmy_db_schema::{ person::{Person, PersonAlias1, PersonAlias2, PersonSafe, PersonSafeAlias1, PersonSafeAlias2}, post::Post, }, + CommunityId, }; use serde::Serialize; @@ -76,7 +77,10 @@ impl CommentReportView { /// * `community_ids` - a Vec<i32> of community_ids to get a count for /// TODO this eq_any is a bad way to do this, would be better to join to communitymoderator /// for a person id - pub fn get_report_count(conn: &PgConnection, community_ids: &[i32]) -> Result<i64, Error> { + pub fn get_report_count( + conn: &PgConnection, + community_ids: &[CommunityId], + ) -> Result<i64, Error> { use diesel::dsl::*; comment_report::table .inner_join(comment::table) @@ -93,7 +97,7 @@ impl CommentReportView { pub struct CommentReportQueryBuilder<'a> { conn: &'a PgConnection, - community_ids: Option<Vec<i32>>, // TODO bad way to do this + community_ids: Option<Vec<CommunityId>>, // TODO bad way to do this page: Option<i64>, limit: Option<i64>, resolved: Option<bool>, @@ -110,7 +114,7 @@ impl<'a> CommentReportQueryBuilder<'a> { } } - pub fn community_ids<T: MaybeOptional<Vec<i32>>>(mut self, community_ids: T) -> Self { + pub fn community_ids<T: MaybeOptional<Vec<CommunityId>>>(mut self, community_ids: T) -> Self { self.community_ids = community_ids.get_optional(); self } diff --git a/crates/db_views/src/comment_view.rs b/crates/db_views/src/comment_view.rs index d3e97c64..6c5850ad 100644 --- a/crates/db_views/src/comment_view.rs +++ b/crates/db_views/src/comment_view.rs @@ -30,6 +30,10 @@ use lemmy_db_schema::{ person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, post::Post, }, + CommentId, + CommunityId, + PersonId, + PostId, }; use serde::Serialize; @@ -64,11 +68,11 @@ type CommentViewTuple = ( impl CommentView { pub fn read( conn: &PgConnection, - comment_id: i32, - my_person_id: Option<i32>, + comment_id: CommentId, + my_person_id: Option<PersonId>, ) -> Result<Self, Error> { // The left join below will return None in this case - let person_id_join = my_person_id.unwrap_or(-1); + let person_id_join = my_person_id.unwrap_or(PersonId(-1)); let ( comment, @@ -158,7 +162,7 @@ impl CommentView { /// Gets the recipient person id. /// If there is no parent comment, its the post creator - pub fn get_recipient_id(&self) -> i32 { + pub fn get_recipient_id(&self) -> PersonId { match &self.recipient { Some(parent_commenter) => parent_commenter.id, None => self.post.creator_id, @@ -170,12 +174,12 @@ pub struct CommentQueryBuilder<'a> { conn: &'a PgConnection, listing_type: ListingType, sort: &'a SortType, - community_id: Option<i32>, + community_id: Option<CommunityId>, community_name: Option<String>, - post_id: Option<i32>, - creator_id: Option<i32>, - recipient_id: Option<i32>, - my_person_id: Option<i32>, + post_id: Option<PostId>, + creator_id: Option<PersonId>, + recipient_id: Option<PersonId>, + my_person_id: Option<PersonId>, search_term: Option<String>, saved_only: bool, unread_only: bool, @@ -213,27 +217,27 @@ impl<'a> CommentQueryBuilder<'a> { self } - pub fn post_id<T: MaybeOptional<i32>>(mut self, post_id: T) -> Self { + pub fn post_id<T: MaybeOptional<PostId>>(mut self, post_id: T) -> Self { self.post_id = post_id.get_optional(); self } - pub fn creator_id<T: MaybeOptional<i32>>(mut self, creator_id: T) -> Self { + pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self { self.creator_id = creator_id.get_optional(); self } - pub fn recipient_id<T: MaybeOptional<i32>>(mut self, recipient_id: T) -> Self { + pub fn recipient_id<T: MaybeOptional<PersonId>>(mut self, recipient_id: T) -> Self { self.recipient_id = recipient_id.get_optional(); self } - pub fn community_id<T: MaybeOptional<i32>>(mut self, community_id: T) -> Self { + pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self { self.community_id = community_id.get_optional(); self } - pub fn my_person_id<T: MaybeOptional<i32>>(mut self, my_person_id: T) -> Self { + pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self { self.my_person_id = my_person_id.get_optional(); self } @@ -272,7 +276,7 @@ impl<'a> CommentQueryBuilder<'a> { use diesel::dsl::*; // The left join below will return None in this case - let person_id_join = self.my_person_id.unwrap_or(-1); + let person_id_join = self.my_person_id.unwrap_or(PersonId(-1)); let mut query = comment::table .inner_join(person::table) diff --git a/crates/db_views/src/local_user_view.rs b/crates/db_views/src/local_user_view.rs index ee4811b6..85a83e15 100644 --- a/crates/db_views/src/local_user_view.rs +++ b/crates/db_views/src/local_user_view.rs @@ -6,6 +6,8 @@ use lemmy_db_schema::{ local_user::{LocalUser, LocalUserSettings}, person::{Person, PersonSafe}, }, + LocalUserId, + PersonId, }; use serde::Serialize; @@ -19,7 +21,7 @@ pub struct LocalUserView { type LocalUserViewTuple = (LocalUser, Person, PersonAggregates); impl LocalUserView { - pub fn read(conn: &PgConnection, local_user_id: i32) -> Result<Self, Error> { + pub fn read(conn: &PgConnection, local_user_id: LocalUserId) -> Result<Self, Error> { let (local_user, person, counts) = local_user::table .find(local_user_id) .inner_join(person::table) @@ -37,7 +39,7 @@ impl LocalUserView { }) } - pub fn read_person(conn: &PgConnection, person_id: i32) -> Result<Self, Error> { + pub fn read_person(conn: &PgConnection, person_id: PersonId) -> Result<Self, Error> { let (local_user, person, counts) = local_user::table .filter(person::id.eq(person_id)) .inner_join(person::table) @@ -125,7 +127,7 @@ pub struct LocalUserSettingsView { type LocalUserSettingsViewTuple = (LocalUserSettings, PersonSafe, PersonAggregates); impl LocalUserSettingsView { - pub fn read(conn: &PgConnection, local_user_id: i32) -> Result<Self, Error> { + pub fn read(conn: &PgConnection, local_user_id: LocalUserId) -> Result<Self, Error> { let (local_user, person, counts) = local_user::table .find(local_user_id) .inner_join(person::table) diff --git a/crates/db_views/src/post_report_view.rs b/crates/db_views/src/post_report_view.rs index e8221c72..a3dc49e2 100644 --- a/crates/db_views/src/post_report_view.rs +++ b/crates/db_views/src/post_report_view.rs @@ -8,6 +8,7 @@ use lemmy_db_schema::{ post::Post, post_report::PostReport, }, + CommunityId, }; use serde::Serialize; @@ -69,7 +70,10 @@ impl PostReportView { /// * `community_ids` - a Vec<i32> of community_ids to get a count for /// TODO this eq_any is a bad way to do this, would be better to join to communitymoderator /// for a person id - pub fn get_report_count(conn: &PgConnection, community_ids: &[i32]) -> Result<i64, Error> { + pub fn get_report_count( + conn: &PgConnection, + community_ids: &[CommunityId], + ) -> Result<i64, Error> { use diesel::dsl::*; post_report::table .inner_join(post::table) @@ -85,7 +89,7 @@ impl PostReportView { pub struct PostReportQueryBuilder<'a> { conn: &'a PgConnection, - community_ids: Option<Vec<i32>>, // TODO bad way to do this + community_ids: Option<Vec<CommunityId>>, // TODO bad way to do this page: Option<i64>, limit: Option<i64>, resolved: Option<bool>, @@ -102,7 +106,7 @@ impl<'a> PostReportQueryBuilder<'a> { } } - pub fn community_ids<T: MaybeOptional<Vec<i32>>>(mut self, community_ids: T) -> Self { + pub fn community_ids<T: MaybeOptional<Vec<CommunityId>>>(mut self, community_ids: T) -> Self { self.community_ids = community_ids.get_optional(); self } diff --git a/crates/db_views/src/post_view.rs b/crates/db_views/src/post_view.rs index 2db35fff..fe852e37 100644 --- a/crates/db_views/src/post_view.rs +++ b/crates/db_views/src/post_view.rs @@ -27,6 +27,9 @@ use lemmy_db_schema::{ person::{Person, PersonSafe}, post::{Post, PostRead, PostSaved}, }, + CommunityId, + PersonId, + PostId, }; use log::debug; use serde::Serialize; @@ -57,9 +60,13 @@ type PostViewTuple = ( ); impl PostView { - pub fn read(conn: &PgConnection, post_id: i32, my_person_id: Option<i32>) -> Result<Self, Error> { + pub fn read( + conn: &PgConnection, + post_id: PostId, + my_person_id: Option<PersonId>, + ) -> Result<Self, Error> { // The left join below will return None in this case - let person_id_join = my_person_id.unwrap_or(-1); + let person_id_join = my_person_id.unwrap_or(PersonId(-1)); let ( post, @@ -150,10 +157,10 @@ pub struct PostQueryBuilder<'a> { conn: &'a PgConnection, listing_type: &'a ListingType, sort: &'a SortType, - creator_id: Option<i32>, - community_id: Option<i32>, + creator_id: Option<PersonId>, + community_id: Option<CommunityId>, community_name: Option<String>, - my_person_id: Option<i32>, + my_person_id: Option<PersonId>, search_term: Option<String>, url_search: Option<String>, show_nsfw: bool, @@ -193,12 +200,12 @@ impl<'a> PostQueryBuilder<'a> { self } - pub fn community_id<T: MaybeOptional<i32>>(mut self, community_id: T) -> Self { + pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self { self.community_id = community_id.get_optional(); self } - pub fn my_person_id<T: MaybeOptional<i32>>(mut self, my_person_id: T) -> Self { + pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self { self.my_person_id = my_person_id.get_optional(); self } @@ -208,7 +215,7 @@ impl<'a> PostQueryBuilder<'a> { self } - pub fn creator_id<T: MaybeOptional<i32>>(mut self, creator_id: T) -> Self { + pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self { self.creator_id = creator_id.get_optional(); self } @@ -247,7 +254,7 @@ impl<'a> PostQueryBuilder<'a> { use diesel::dsl::*; // The left join below will return None in this case - let person_id_join = self.my_person_id.unwrap_or(-1); + let person_id_join = self.my_person_id.unwrap_or(PersonId(-1)); let mut query = post::table .inner_join(person::table) diff --git a/crates/db_views/src/private_message_view.rs b/crates/db_views/src/private_message_view.rs index e4dd3d3f..5cef7364 100644 --- a/crates/db_views/src/private_message_view.rs +++ b/crates/db_views/src/private_message_view.rs @@ -6,6 +6,8 @@ use lemmy_db_schema::{ person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, private_message::PrivateMessage, }, + PersonId, + PrivateMessageId, }; use log::debug; use serde::Serialize; @@ -20,7 +22,7 @@ pub struct PrivateMessageView { type PrivateMessageViewTuple = (PrivateMessage, PersonSafe, PersonSafeAlias1); impl PrivateMessageView { - pub fn read(conn: &PgConnection, private_message_id: i32) -> Result<Self, Error> { + pub fn read(conn: &PgConnection, private_message_id: PrivateMessageId) -> Result<Self, Error> { let (private_message, creator, recipient) = private_message::table .find(private_message_id) .inner_join(person::table.on(private_message::creator_id.eq(person::id))) @@ -43,14 +45,14 @@ impl PrivateMessageView { pub struct PrivateMessageQueryBuilder<'a> { conn: &'a PgConnection, - recipient_id: i32, + recipient_id: PersonId, unread_only: bool, page: Option<i64>, limit: Option<i64>, } impl<'a> PrivateMessageQueryBuilder<'a> { - pub fn create(conn: &'a PgConnection, recipient_id: i32) -> Self { + pub fn create(conn: &'a PgConnection, recipient_id: PersonId) -> Self { PrivateMessageQueryBuilder { conn, recipient_id, diff --git a/crates/db_views_actor/src/community_follower_view.rs b/crates/db_views_actor/src/community_follower_view.rs index 337c28cd..73082419 100644 --- a/crates/db_views_actor/src/community_follower_view.rs +++ b/crates/db_views_actor/src/community_follower_view.rs @@ -6,6 +6,8 @@ use lemmy_db_schema::{ community::{Community, CommunitySafe}, person::{Person, PersonSafe}, }, + CommunityId, + PersonId, }; use serde::Serialize; @@ -18,7 +20,7 @@ pub struct CommunityFollowerView { type CommunityFollowerViewTuple = (CommunitySafe, PersonSafe); impl CommunityFollowerView { - pub fn for_community(conn: &PgConnection, community_id: i32) -> Result<Vec<Self>, Error> { + pub fn for_community(conn: &PgConnection, community_id: CommunityId) -> Result<Vec<Self>, Error> { let res = community_follower::table .inner_join(community::table) .inner_join(person::table) @@ -33,7 +35,7 @@ impl CommunityFollowerView { Ok(Self::from_tuple_to_vec(res)) } - pub fn for_person(conn: &PgConnection, person_id: i32) -> Result<Vec<Self>, Error> { + pub fn for_person(conn: &PgConnection, person_id: PersonId) -> Result<Vec<Self>, Error> { let res = community_follower::table .inner_join(community::table) .inner_join(person::table) diff --git a/crates/db_views_actor/src/community_moderator_view.rs b/crates/db_views_actor/src/community_moderator_view.rs index bdddf917..274f6824 100644 --- a/crates/db_views_actor/src/community_moderator_view.rs +++ b/crates/db_views_actor/src/community_moderator_view.rs @@ -6,6 +6,8 @@ use lemmy_db_schema::{ community::{Community, CommunitySafe}, person::{Person, PersonSafe}, }, + CommunityId, + PersonId, }; use serde::Serialize; @@ -18,7 +20,7 @@ pub struct CommunityModeratorView { type CommunityModeratorViewTuple = (CommunitySafe, PersonSafe); impl CommunityModeratorView { - pub fn for_community(conn: &PgConnection, community_id: i32) -> Result<Vec<Self>, Error> { + pub fn for_community(conn: &PgConnection, community_id: CommunityId) -> Result<Vec<Self>, Error> { let res = community_moderator::table .inner_join(community::table) .inner_join(person::table) @@ -33,7 +35,7 @@ impl CommunityModeratorView { Ok(Self::from_tuple_to_vec(res)) } - pub fn for_person(conn: &PgConnection, person_id: i32) -> Result<Vec<Self>, Error> { + pub fn for_person(conn: &PgConnection, person_id: PersonId) -> Result<Vec<Self>, Error> { let res = community_moderator::table .inner_join(community::table) .inner_join(person::table) 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 c63d15a0..4db96723 100644 --- a/crates/db_views_actor/src/community_person_ban_view.rs +++ b/crates/db_views_actor/src/community_person_ban_view.rs @@ -6,6 +6,8 @@ use lemmy_db_schema::{ community::{Community, CommunitySafe}, person::{Person, PersonSafe}, }, + CommunityId, + PersonId, }; use serde::Serialize; @@ -18,8 +20,8 @@ pub struct CommunityPersonBanView { impl CommunityPersonBanView { pub fn get( conn: &PgConnection, - from_person_id: i32, - from_community_id: i32, + from_person_id: PersonId, + from_community_id: CommunityId, ) -> Result<Self, Error> { let (community, person) = community_person_ban::table .inner_join(community::table) diff --git a/crates/db_views_actor/src/community_view.rs b/crates/db_views_actor/src/community_view.rs index 2e7f1746..fe3a80bb 100644 --- a/crates/db_views_actor/src/community_view.rs +++ b/crates/db_views_actor/src/community_view.rs @@ -17,6 +17,8 @@ use lemmy_db_schema::{ community::{Community, CommunityFollower, CommunitySafe}, person::{Person, PersonSafe}, }, + CommunityId, + PersonId, }; use serde::Serialize; @@ -38,11 +40,11 @@ type CommunityViewTuple = ( impl CommunityView { pub fn read( conn: &PgConnection, - community_id: i32, - my_person_id: Option<i32>, + community_id: CommunityId, + my_person_id: Option<PersonId>, ) -> Result<Self, Error> { // The left join below will return None in this case - let person_id_join = my_person_id.unwrap_or(-1); + let person_id_join = my_person_id.unwrap_or(PersonId(-1)); let (community, creator, counts, follower) = community::table .find(community_id) @@ -72,8 +74,11 @@ impl CommunityView { } // TODO: this function is only used by is_mod_or_admin() below, can probably be merged - fn community_mods_and_admins(conn: &PgConnection, community_id: i32) -> Result<Vec<i32>, Error> { - let mut mods_and_admins: Vec<i32> = Vec::new(); + fn community_mods_and_admins( + conn: &PgConnection, + community_id: CommunityId, + ) -> Result<Vec<PersonId>, Error> { + let mut mods_and_admins: Vec<PersonId> = Vec::new(); mods_and_admins.append( &mut CommunityModeratorView::for_community(conn, community_id) .map(|v| v.into_iter().map(|m| m.moderator.id).collect())?, @@ -84,7 +89,11 @@ impl CommunityView { Ok(mods_and_admins) } - pub fn is_mod_or_admin(conn: &PgConnection, person_id: i32, community_id: i32) -> bool { + pub fn is_mod_or_admin( + conn: &PgConnection, + person_id: PersonId, + community_id: CommunityId, + ) -> bool { Self::community_mods_and_admins(conn, community_id) .unwrap_or_default() .contains(&person_id) @@ -95,7 +104,7 @@ pub struct CommunityQueryBuilder<'a> { conn: &'a PgConnection, listing_type: &'a ListingType, sort: &'a SortType, - my_person_id: Option<i32>, + my_person_id: Option<PersonId>, show_nsfw: bool, search_term: Option<String>, page: Option<i64>, @@ -136,7 +145,7 @@ impl<'a> CommunityQueryBuilder<'a> { self } - pub fn my_person_id<T: MaybeOptional<i32>>(mut self, my_person_id: T) -> Self { + pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self { self.my_person_id = my_person_id.get_optional(); self } @@ -153,7 +162,7 @@ impl<'a> CommunityQueryBuilder<'a> { pub fn list(self) -> Result<Vec<CommunityView>, Error> { // The left join below will return None in this case - let person_id_join = self.my_person_id.unwrap_or(-1); + let person_id_join = self.my_person_id.unwrap_or(PersonId(-1)); let mut query = community::table .inner_join(person::table) diff --git a/crates/db_views_actor/src/person_mention_view.rs b/crates/db_views_actor/src/person_mention_view.rs index daa6599b..958d084b 100644 --- a/crates/db_views_actor/src/person_mention_view.rs +++ b/crates/db_views_actor/src/person_mention_view.rs @@ -29,6 +29,8 @@ use lemmy_db_schema::{ person_mention::PersonMention, post::Post, }, + PersonId, + PersonMentionId, }; use serde::Serialize; @@ -64,11 +66,11 @@ type PersonMentionViewTuple = ( impl PersonMentionView { pub fn read( conn: &PgConnection, - person_mention_id: i32, - my_person_id: Option<i32>, + person_mention_id: PersonMentionId, + my_person_id: Option<PersonId>, ) -> Result<Self, Error> { // The left join below will return None in this case - let person_id_join = my_person_id.unwrap_or(-1); + let person_id_join = my_person_id.unwrap_or(PersonId(-1)); let ( person_mention, @@ -151,8 +153,8 @@ impl PersonMentionView { pub struct PersonMentionQueryBuilder<'a> { conn: &'a PgConnection, - my_person_id: Option<i32>, - recipient_id: Option<i32>, + my_person_id: Option<PersonId>, + recipient_id: Option<PersonId>, sort: &'a SortType, unread_only: bool, page: Option<i64>, @@ -182,12 +184,12 @@ impl<'a> PersonMentionQueryBuilder<'a> { self } - pub fn recipient_id<T: MaybeOptional<i32>>(mut self, recipient_id: T) -> Self { + pub fn recipient_id<T: MaybeOptional<PersonId>>(mut self, recipient_id: T) -> Self { self.recipient_id = recipient_id.get_optional(); self } - pub fn my_person_id<T: MaybeOptional<i32>>(mut self, my_person_id: T) -> Self { + pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self { self.my_person_id = my_person_id.get_optional(); self } @@ -206,7 +208,7 @@ impl<'a> PersonMentionQueryBuilder<'a> { use diesel::dsl::*; // The left join below will return None in this case - let person_id_join = self.my_person_id.unwrap_or(-1); + let person_id_join = self.my_person_id.unwrap_or(PersonId(-1)); let mut query = person_mention::table .inner_join(comment::table) diff --git a/crates/db_views_actor/src/person_view.rs b/crates/db_views_actor/src/person_view.rs index 920e5900..a44a468c 100644 --- a/crates/db_views_actor/src/person_view.rs +++ b/crates/db_views_actor/src/person_view.rs @@ -11,6 +11,7 @@ use lemmy_db_queries::{ use lemmy_db_schema::{ schema::{local_user, person, person_aggregates}, source::person::{Person, PersonSafe}, + PersonId, }; use serde::Serialize; @@ -23,9 +24,9 @@ pub struct PersonViewSafe { type PersonViewSafeTuple = (PersonSafe, PersonAggregates); impl PersonViewSafe { - pub fn read(conn: &PgConnection, id: i32) -> Result<Self, Error> { + pub fn read(conn: &PgConnection, person_id: PersonId) -> Result<Self, Error> { let (person, counts) = person::table - .find(id) + .find(person_id) .inner_join(person_aggregates::table) .select((Person::safe_columns_tuple(), person_aggregates::all_columns)) .first::<PersonViewSafeTuple>(conn)?; 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 8fabe740..df56d8cb 100644 --- a/crates/db_views_moderator/src/mod_add_community_view.rs +++ b/crates/db_views_moderator/src/mod_add_community_view.rs @@ -7,6 +7,8 @@ use lemmy_db_schema::{ moderator::ModAddCommunity, person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, }, + CommunityId, + PersonId, }; use serde::Serialize; @@ -23,8 +25,8 @@ type ModAddCommunityViewTuple = (ModAddCommunity, PersonSafe, CommunitySafe, Per impl ModAddCommunityView { pub fn list( conn: &PgConnection, - community_id: Option<i32>, - mod_person_id: Option<i32>, + community_id: Option<CommunityId>, + mod_person_id: Option<PersonId>, page: Option<i64>, limit: Option<i64>, ) -> Result<Vec<Self>, Error> { diff --git a/crates/db_views_moderator/src/mod_add_view.rs b/crates/db_views_moderator/src/mod_add_view.rs index a6ce4472..d4b5746b 100644 --- a/crates/db_views_moderator/src/mod_add_view.rs +++ b/crates/db_views_moderator/src/mod_add_view.rs @@ -6,6 +6,7 @@ use lemmy_db_schema::{ moderator::ModAdd, person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, }, + PersonId, }; use serde::Serialize; @@ -21,7 +22,7 @@ type ModAddViewTuple = (ModAdd, PersonSafe, PersonSafeAlias1); impl ModAddView { pub fn list( conn: &PgConnection, - mod_person_id: Option<i32>, + mod_person_id: Option<PersonId>, page: Option<i64>, limit: Option<i64>, ) -> Result<Vec<Self>, Error> { 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 2d16edb0..82d336f1 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 @@ -7,6 +7,8 @@ use lemmy_db_schema::{ moderator::ModBanFromCommunity, person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, }, + CommunityId, + PersonId, }; use serde::Serialize; @@ -28,8 +30,8 @@ type ModBanFromCommunityViewTuple = ( impl ModBanFromCommunityView { pub fn list( conn: &PgConnection, - community_id: Option<i32>, - mod_person_id: Option<i32>, + community_id: Option<CommunityId>, + mod_person_id: Option<PersonId>, page: Option<i64>, limit: Option<i64>, ) -> Result<Vec<Self>, Error> { diff --git a/crates/db_views_moderator/src/mod_ban_view.rs b/crates/db_views_moderator/src/mod_ban_view.rs index 2a3c1864..ff962977 100644 --- a/crates/db_views_moderator/src/mod_ban_view.rs +++ b/crates/db_views_moderator/src/mod_ban_view.rs @@ -6,6 +6,7 @@ use lemmy_db_schema::{ moderator::ModBan, person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, }, + PersonId, }; use serde::Serialize; @@ -21,7 +22,7 @@ type ModBanViewTuple = (ModBan, PersonSafe, PersonSafeAlias1); impl ModBanView { pub fn list( conn: &PgConnection, - mod_person_id: Option<i32>, + mod_person_id: Option<PersonId>, page: Option<i64>, limit: Option<i64>, ) -> Result<Vec<Self>, Error> { 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 5f5e7346..2ce303ec 100644 --- a/crates/db_views_moderator/src/mod_lock_post_view.rs +++ b/crates/db_views_moderator/src/mod_lock_post_view.rs @@ -8,6 +8,8 @@ use lemmy_db_schema::{ person::{Person, PersonSafe}, post::Post, }, + CommunityId, + PersonId, }; use serde::Serialize; @@ -24,8 +26,8 @@ type ModLockPostViewTuple = (ModLockPost, PersonSafe, Post, CommunitySafe); impl ModLockPostView { pub fn list( conn: &PgConnection, - community_id: Option<i32>, - mod_person_id: Option<i32>, + community_id: Option<CommunityId>, + mod_person_id: Option<PersonId>, page: Option<i64>, limit: Option<i64>, ) -> Result<Vec<Self>, Error> { 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 2e8dfccc..33b167b8 100644 --- a/crates/db_views_moderator/src/mod_remove_comment_view.rs +++ b/crates/db_views_moderator/src/mod_remove_comment_view.rs @@ -9,6 +9,8 @@ use lemmy_db_schema::{ person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1}, post::Post, }, + CommunityId, + PersonId, }; use serde::Serialize; @@ -34,8 +36,8 @@ type ModRemoveCommentViewTuple = ( impl ModRemoveCommentView { pub fn list( conn: &PgConnection, - community_id: Option<i32>, - mod_person_id: Option<i32>, + community_id: Option<CommunityId>, + mod_person_id: Option<PersonId>, page: Option<i64>, limit: Option<i64>, ) -> Result<Vec<Self>, Error> { 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 767bcdc4..34fd0982 100644 --- a/crates/db_views_moderator/src/mod_remove_community_view.rs +++ b/crates/db_views_moderator/src/mod_remove_community_view.rs @@ -7,6 +7,7 @@ use lemmy_db_schema::{ moderator::ModRemoveCommunity, person::{Person, PersonSafe}, }, + PersonId, }; use serde::Serialize; @@ -22,7 +23,7 @@ type ModRemoveCommunityTuple = (ModRemoveCommunity, PersonSafe, CommunitySafe); impl ModRemoveCommunityView { pub fn list( conn: &PgConnection, - mod_person_id: Option<i32>, + mod_person_id: Option<PersonId>, page: Option<i64>, limit: Option<i64>, ) -> Result<Vec<Self>, Error> { 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 7456ff8a..ac34ff5e 100644 --- a/crates/db_views_moderator/src/mod_remove_post_view.rs +++ b/crates/db_views_moderator/src/mod_remove_post_view.rs @@ -8,6 +8,8 @@ use lemmy_db_schema::{ person::{Person, PersonSafe}, post::Post, }, + CommunityId, + PersonId, }; use serde::Serialize; @@ -24,8 +26,8 @@ type ModRemovePostViewTuple = (ModRemovePost, PersonSafe, Post, CommunitySafe); impl ModRemovePostView { pub fn list( conn: &PgConnection, - community_id: Option<i32>, - mod_person_id: Option<i32>, + community_id: Option<CommunityId>, + mod_person_id: Option<PersonId>, page: Option<i64>, limit: Option<i64>, ) -> Result<Vec<Self>, Error> { 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 c0629a4e..411cb57a 100644 --- a/crates/db_views_moderator/src/mod_sticky_post_view.rs +++ b/crates/db_views_moderator/src/mod_sticky_post_view.rs @@ -8,6 +8,8 @@ use lemmy_db_schema::{ person::{Person, PersonSafe}, post::Post, }, + CommunityId, + PersonId, }; use serde::Serialize; @@ -24,8 +26,8 @@ type ModStickyPostViewTuple = (ModStickyPost, PersonSafe, Post, CommunitySafe); impl ModStickyPostView { pub fn list( conn: &PgConnection, - community_id: Option<i32>, - mod_person_id: Option<i32>, + community_id: Option<CommunityId>, + mod_person_id: Option<PersonId>, page: Option<i64>, limit: Option<i64>, ) -> Result<Vec<Self>, Error> { diff --git a/crates/routes/src/feeds.rs b/crates/routes/src/feeds.rs index 30f5f963..47aca46f 100644 --- a/crates/routes/src/feeds.rs +++ b/crates/routes/src/feeds.rs @@ -9,7 +9,10 @@ use lemmy_db_queries::{ ListingType, SortType, }; -use lemmy_db_schema::source::{community::Community, local_user::LocalUser, person::Person}; +use lemmy_db_schema::{ + source::{community::Community, local_user::LocalUser, person::Person}, + LocalUserId, +}; use lemmy_db_views::{ comment_view::{CommentQueryBuilder, CommentView}, post_view::{PostQueryBuilder, PostView}, @@ -224,7 +227,7 @@ fn get_feed_front( jwt: String, ) -> Result<ChannelBuilder, LemmyError> { let site_view = SiteView::read(&conn)?; - let local_user_id = Claims::decode(&jwt)?.claims.local_user_id; + let local_user_id = LocalUserId(Claims::decode(&jwt)?.claims.local_user_id); let person_id = LocalUser::read(&conn, local_user_id)?.person_id; let posts = PostQueryBuilder::create(&conn) @@ -251,7 +254,7 @@ fn get_feed_front( fn get_feed_inbox(conn: &PgConnection, jwt: String) -> Result<ChannelBuilder, LemmyError> { let site_view = SiteView::read(&conn)?; - let local_user_id = Claims::decode(&jwt)?.claims.local_user_id; + let local_user_id = LocalUserId(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/lib.rs b/crates/utils/src/lib.rs index 373cacab..f917d938 100644 --- a/crates/utils/src/lib.rs +++ b/crates/utils/src/lib.rs @@ -18,13 +18,19 @@ pub mod version; use crate::settings::structs::Settings; use http::StatusCode; use regex::Regex; +use std::fmt; use thiserror::Error; pub type ConnectionId = usize; -pub type PostId = i32; -pub type CommunityId = i32; -pub type LocalUserId = i32; -pub type IpAddr = String; + +#[derive(PartialEq, Eq, Hash, Debug, Clone)] +pub struct IpAddr(pub String); + +impl fmt::Display for IpAddr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} #[macro_export] macro_rules! location_info { diff --git a/crates/utils/src/rate_limit/mod.rs b/crates/utils/src/rate_limit/mod.rs index d3e74ed5..578384c6 100644 --- a/crates/utils/src/rate_limit/mod.rs +++ b/crates/utils/src/rate_limit/mod.rs @@ -1,6 +1,7 @@ use crate::{ settings::structs::{RateLimitConfig, Settings}, utils::get_ip, + IpAddr, LemmyError, }; use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform}; @@ -62,7 +63,7 @@ impl RateLimit { impl RateLimited { pub async fn wrap<T, E>( self, - ip_addr: String, + ip_addr: IpAddr, fut: impl Future<Output = Result<T, E>>, ) -> Result<T, E> where diff --git a/crates/utils/src/rate_limit/rate_limiter.rs b/crates/utils/src/rate_limit/rate_limiter.rs index 701d608b..a965c79b 100644 --- a/crates/utils/src/rate_limit/rate_limiter.rs +++ b/crates/utils/src/rate_limit/rate_limiter.rs @@ -32,7 +32,7 @@ impl Default for RateLimiter { } impl RateLimiter { - fn insert_ip(&mut self, ip: &str) { + fn insert_ip(&mut self, ip: &IpAddr) { for rate_limit_type in RateLimitType::iter() { if self.buckets.get(&rate_limit_type).is_none() { self.buckets.insert(rate_limit_type, HashMap::new()); @@ -41,7 +41,7 @@ impl RateLimiter { if let Some(bucket) = self.buckets.get_mut(&rate_limit_type) { if bucket.get(ip).is_none() { bucket.insert( - ip.to_string(), + ip.clone(), RateLimitBucket { last_checked: SystemTime::now(), allowance: -2f64, @@ -56,7 +56,7 @@ impl RateLimiter { pub(super) fn check_rate_limit_full( &mut self, type_: RateLimitType, - ip: &str, + ip: &IpAddr, rate: i32, per: i32, check_only: bool, diff --git a/crates/utils/src/utils.rs b/crates/utils/src/utils.rs index 33ea833d..c53d6c7c 100644 --- a/crates/utils/src/utils.rs +++ b/crates/utils/src/utils.rs @@ -1,4 +1,4 @@ -use crate::{settings::structs::Settings, ApiError}; +use crate::{settings::structs::Settings, ApiError, IpAddr}; use actix_web::dev::ConnectionInfo; use chrono::{DateTime, FixedOffset, NaiveDateTime}; use itertools::Itertools; @@ -122,12 +122,14 @@ pub fn is_valid_post_title(title: &str) -> bool { VALID_POST_TITLE_REGEX.is_match(title) } -pub fn get_ip(conn_info: &ConnectionInfo) -> String { - conn_info - .realip_remote_addr() - .unwrap_or("127.0.0.1:12345") - .split(':') - .next() - .unwrap_or("127.0.0.1") - .to_string() +pub fn get_ip(conn_info: &ConnectionInfo) -> IpAddr { + IpAddr( + conn_info + .realip_remote_addr() + .unwrap_or("127.0.0.1:12345") + .split(':') + .next() + .unwrap_or("127.0.0.1") + .to_string(), + ) } diff --git a/crates/websocket/src/chat_server.rs b/crates/websocket/src/chat_server.rs index ea4a651a..c9016a25 100644 --- a/crates/websocket/src/chat_server.rs +++ b/crates/websocket/src/chat_server.rs @@ -7,16 +7,14 @@ use diesel::{ PgConnection, }; use lemmy_api_structs::{comment::*, post::*}; +use lemmy_db_schema::{CommunityId, LocalUserId, PostId}; use lemmy_utils::{ location_info, rate_limit::RateLimit, ApiError, - CommunityId, ConnectionId, IpAddr, LemmyError, - LocalUserId, - PostId, }; use rand::rngs::ThreadRng; use reqwest::Client; @@ -349,7 +347,12 @@ impl ChatServer { )?; // Send it to the community too - self.send_community_room_message(user_operation, &comment_post_sent, 0, websocket_id)?; + self.send_community_room_message( + user_operation, + &comment_post_sent, + CommunityId(0), + websocket_id, + )?; self.send_community_room_message( user_operation, &comment_post_sent, @@ -383,7 +386,7 @@ impl ChatServer { post_sent.post_view.my_vote = None; // Send it to /c/all and that community - self.send_community_room_message(user_operation, &post_sent, 0, websocket_id)?; + self.send_community_room_message(user_operation, &post_sent, CommunityId(0), websocket_id)?; self.send_community_room_message(user_operation, &post_sent, community_id, websocket_id)?; // Send it to the post room @@ -412,7 +415,7 @@ impl ChatServer { let ip: IpAddr = match self.sessions.get(&msg.id) { Some(info) => info.ip.to_owned(), - None => "blank_ip".to_string(), + None => IpAddr("blank_ip".to_string()), }; let context = LemmyContext { diff --git a/crates/websocket/src/handlers.rs b/crates/websocket/src/handlers.rs index ccc2d099..30cd9639 100644 --- a/crates/websocket/src/handlers.rs +++ b/crates/websocket/src/handlers.rs @@ -4,6 +4,7 @@ use crate::{ }; use actix::{Actor, Context, Handler, ResponseFuture}; use lemmy_db_schema::naive_now; +use lemmy_utils::ConnectionId; use log::{error, info}; use rand::Rng; use serde::Serialize; @@ -19,7 +20,7 @@ impl Actor for ChatServer { /// /// Register new session and assign unique id to this session impl Handler<Connect> for ChatServer { - type Result = usize; + type Result = ConnectionId; fn handle(&mut self, msg: Connect, _ctx: &mut Context<Self>) -> Self::Result { // register session with random id diff --git a/crates/websocket/src/messages.rs b/crates/websocket/src/messages.rs index 675563f3..a1d4396b 100644 --- a/crates/websocket/src/messages.rs +++ b/crates/websocket/src/messages.rs @@ -1,7 +1,8 @@ use crate::UserOperation; use actix::{prelude::*, Recipient}; use lemmy_api_structs::{comment::CommentResponse, post::PostResponse}; -use lemmy_utils::{CommunityId, ConnectionId, IpAddr, LocalUserId, PostId}; +use lemmy_db_schema::{CommunityId, LocalUserId, PostId}; +use lemmy_utils::{ConnectionId, IpAddr}; use serde::{Deserialize, Serialize}; /// Chat server sends this messages to session diff --git a/crates/websocket/src/routes.rs b/crates/websocket/src/routes.rs index 71ff36b1..8a487813 100644 --- a/crates/websocket/src/routes.rs +++ b/crates/websocket/src/routes.rs @@ -6,7 +6,7 @@ use crate::{ use actix::prelude::*; use actix_web::*; use actix_web_actors::ws; -use lemmy_utils::utils::get_ip; +use lemmy_utils::{utils::get_ip, ConnectionId, IpAddr}; use log::{debug, error, info}; use std::time::{Duration, Instant}; @@ -36,8 +36,8 @@ pub async fn chat_route( struct WsSession { cs_addr: Addr<ChatServer>, /// unique session id - id: usize, - ip: String, + id: ConnectionId, + ip: IpAddr, /// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT), /// otherwise we drop connection. hb: Instant, -- 2.44.1