Skip to main content

max / makenotwork

7.3 KB · 191 lines History Blame Raw
1 //! Follow/unfollow API endpoints.
2
3 use axum::{
4 extract::{Path, State},
5 response::{IntoResponse, Response},
6 };
7 use uuid::Uuid;
8
9 use crate::{
10 auth::AuthUser,
11 db::{self, FollowTargetType, UserId},
12 error::{AppError, Result},
13 helpers::spawn_email,
14 templates::{FollowButtonTemplate, TagFollowToggleTemplate},
15 AppState,
16 };
17
18 /// POST /api/follow/{target_type}/{target_id}: follow a user or project.
19 #[tracing::instrument(skip_all, name = "follows::follow_target")]
20 pub(super) async fn follow_target(
21 State(state): State<AppState>,
22 AuthUser(user): AuthUser,
23 Path((target_type_str, target_id)): Path<(String, Uuid)>,
24 ) -> Result<Response> {
25 user.check_not_suspended()?;
26 user.check_not_sandbox()?;
27 let target_type: FollowTargetType = target_type_str.parse()
28 .map_err(|_| AppError::BadRequest("Invalid target type".to_string()))?;
29
30 validate_target(&state, target_type, target_id, user.id).await?;
31
32 db::follows::follow(&state.db, user.id, target_type, target_id).await?;
33
34 // Subscribe to project content mailing list (non-critical)
35 if target_type == FollowTargetType::Project
36 && let Err(e) = db::mailing_lists::subscribe_to_content_list(
37 &state.db, db::ProjectId::from(target_id), user.id,
38 ).await
39 {
40 tracing::warn!(project_id = %target_id, error = ?e, "failed to subscribe to content mailing list");
41 }
42
43 // Send follower notification (fire-and-forget, non-critical)
44 match target_type {
45 FollowTargetType::Tag => {} // no notification for tag follows
46 FollowTargetType::User => {
47 if let Ok(Some(target_user)) = db::users::get_user_by_id(&state.db, UserId::from(target_id)).await
48 && target_user.notify_follower
49 {
50 let follower_user = db::users::get_user_by_id(&state.db, user.id).await.ok().flatten();
51 let follower_username = follower_user.as_ref()
52 .map(|u| u.username.to_string())
53 .unwrap_or_else(|| "Someone".to_string());
54 let target_email = target_user.email.clone();
55 let target_name = target_user.display_name.clone();
56 let unsub_url = crate::email::generate_unsubscribe_url(
57 &state.config.host_url, target_user.id, crate::email::UnsubscribeAction::Follower, &target_user.id.to_string(), &state.config.signing_secret,
58 );
59 spawn_email!(state, "follower notification", |email| {
60 email.send_follower_notification(
61 &target_email,
62 target_name.as_deref(),
63 &follower_username,
64 "you",
65 Some(&unsub_url),
66 )
67 });
68 }
69 }
70 FollowTargetType::Project => {
71 if let Ok(Some(project)) = db::projects::get_project_by_id(&state.db, db::ProjectId::from(target_id)).await
72 && let Ok(Some(owner)) = db::users::get_user_by_id(&state.db, project.user_id).await
73 && owner.notify_follower
74 {
75 let follower_user = db::users::get_user_by_id(&state.db, user.id).await.ok().flatten();
76 let follower_username = follower_user.as_ref()
77 .map(|u| u.username.to_string())
78 .unwrap_or_else(|| "Someone".to_string());
79 let context = format!("your project {}", project.title);
80 let owner_email = owner.email.clone();
81 let owner_name = owner.display_name.clone();
82 let unsub_url = crate::email::generate_unsubscribe_url(
83 &state.config.host_url, owner.id, crate::email::UnsubscribeAction::Follower, &owner.id.to_string(), &state.config.signing_secret,
84 );
85 spawn_email!(state, "follower notification", |email| {
86 email.send_follower_notification(
87 &owner_email,
88 owner_name.as_deref(),
89 &follower_username,
90 &context,
91 Some(&unsub_url),
92 )
93 });
94 }
95 }
96 }
97
98 if target_type == FollowTargetType::Tag {
99 return Ok(TagFollowToggleTemplate {
100 tag_id: target_id.to_string(),
101 is_following: true,
102 }
103 .into_response());
104 }
105
106 let count = db::follows::get_follower_count(&state.db, target_type, target_id).await?;
107
108 Ok(FollowButtonTemplate {
109 target_type: target_type.to_string(),
110 target_id: target_id.to_string(),
111 is_following: true,
112 follower_count: count,
113 }
114 .into_response())
115 }
116
117 /// DELETE /api/follow/{target_type}/{target_id}: unfollow a user or project.
118 #[tracing::instrument(skip_all, name = "follows::unfollow_target")]
119 pub(super) async fn unfollow_target(
120 State(state): State<AppState>,
121 AuthUser(user): AuthUser,
122 Path((target_type_str, target_id)): Path<(String, Uuid)>,
123 ) -> Result<Response> {
124 user.check_not_suspended()?;
125 let target_type: FollowTargetType = target_type_str.parse()
126 .map_err(|_| AppError::BadRequest("Invalid target type".to_string()))?;
127
128 validate_target(&state, target_type, target_id, user.id).await?;
129
130 db::follows::unfollow(&state.db, user.id, target_type, target_id).await?;
131
132 // Unsubscribe from all project mailing lists (non-critical)
133 if target_type == FollowTargetType::Project
134 && let Err(e) = db::mailing_lists::unsubscribe_from_project(
135 &state.db, db::ProjectId::from(target_id), user.id,
136 ).await
137 {
138 tracing::warn!(project_id = %target_id, error = ?e, "failed to unsubscribe from project mailing lists");
139 }
140
141 if target_type == FollowTargetType::Tag {
142 return Ok(TagFollowToggleTemplate {
143 tag_id: target_id.to_string(),
144 is_following: false,
145 }
146 .into_response());
147 }
148
149 let count = db::follows::get_follower_count(&state.db, target_type, target_id).await?;
150
151 Ok(FollowButtonTemplate {
152 target_type: target_type.to_string(),
153 target_id: target_id.to_string(),
154 is_following: false,
155 follower_count: count,
156 }
157 .into_response())
158 }
159
160 /// Validate that the target exists and prevent self-following for user targets.
161 /// Project self-following is allowed (creators may want to follow their own project feed).
162 async fn validate_target(
163 state: &AppState,
164 target_type: FollowTargetType,
165 target_id: Uuid,
166 follower_id: UserId,
167 ) -> Result<()> {
168 match target_type {
169 FollowTargetType::User => {
170 if *follower_id == target_id {
171 return Err(AppError::BadRequest("Cannot follow yourself".to_string()));
172 }
173 db::users::get_user_by_id(&state.db, UserId::from(target_id))
174 .await?
175 .ok_or(AppError::NotFound)?;
176 }
177 FollowTargetType::Project => {
178 db::projects::get_project_by_id(&state.db, db::ProjectId::from(target_id))
179 .await?
180 .ok_or(AppError::NotFound)?;
181 }
182 FollowTargetType::Tag => {
183 db::tags::get_tag_by_id(&state.db, db::TagId::from(target_id))
184 .await?
185 .ok_or(AppError::NotFound)?;
186 }
187 }
188
189 Ok(())
190 }
191