//! Follow/unfollow API endpoints. use axum::{ extract::{Path, State}, response::{IntoResponse, Response}, }; use uuid::Uuid; use crate::{ auth::AuthUser, db::{self, FollowTargetType, UserId}, error::{AppError, Result}, helpers::spawn_email, templates::{FollowButtonTemplate, TagFollowToggleTemplate}, AppState, }; /// POST /api/follow/{target_type}/{target_id}: follow a user or project. #[tracing::instrument(skip_all, name = "follows::follow_target")] pub(super) async fn follow_target( State(state): State, AuthUser(user): AuthUser, Path((target_type_str, target_id)): Path<(String, Uuid)>, ) -> Result { user.check_not_suspended()?; user.check_not_sandbox()?; let target_type: FollowTargetType = target_type_str.parse() .map_err(|_| AppError::BadRequest("Invalid target type".to_string()))?; validate_target(&state, target_type, target_id, user.id).await?; db::follows::follow(&state.db, user.id, target_type, target_id).await?; // Subscribe to project content mailing list (non-critical) if target_type == FollowTargetType::Project && let Err(e) = db::mailing_lists::subscribe_to_content_list( &state.db, db::ProjectId::from(target_id), user.id, ).await { tracing::warn!(project_id = %target_id, error = ?e, "failed to subscribe to content mailing list"); } // Send follower notification (fire-and-forget, non-critical) match target_type { FollowTargetType::Tag => {} // no notification for tag follows FollowTargetType::User => { if let Ok(Some(target_user)) = db::users::get_user_by_id(&state.db, UserId::from(target_id)).await && target_user.notify_follower { let follower_user = db::users::get_user_by_id(&state.db, user.id).await.ok().flatten(); let follower_username = follower_user.as_ref() .map(|u| u.username.to_string()) .unwrap_or_else(|| "Someone".to_string()); let target_email = target_user.email.clone(); let target_name = target_user.display_name.clone(); let unsub_url = crate::email::generate_unsubscribe_url( &state.config.host_url, target_user.id, crate::email::UnsubscribeAction::Follower, &target_user.id.to_string(), &state.config.signing_secret, ); spawn_email!(state, "follower notification", |email| { email.send_follower_notification( &target_email, target_name.as_deref(), &follower_username, "you", Some(&unsub_url), ) }); } } FollowTargetType::Project => { if let Ok(Some(project)) = db::projects::get_project_by_id(&state.db, db::ProjectId::from(target_id)).await && let Ok(Some(owner)) = db::users::get_user_by_id(&state.db, project.user_id).await && owner.notify_follower { let follower_user = db::users::get_user_by_id(&state.db, user.id).await.ok().flatten(); let follower_username = follower_user.as_ref() .map(|u| u.username.to_string()) .unwrap_or_else(|| "Someone".to_string()); let context = format!("your project {}", project.title); let owner_email = owner.email.clone(); let owner_name = owner.display_name.clone(); let unsub_url = crate::email::generate_unsubscribe_url( &state.config.host_url, owner.id, crate::email::UnsubscribeAction::Follower, &owner.id.to_string(), &state.config.signing_secret, ); spawn_email!(state, "follower notification", |email| { email.send_follower_notification( &owner_email, owner_name.as_deref(), &follower_username, &context, Some(&unsub_url), ) }); } } } if target_type == FollowTargetType::Tag { return Ok(TagFollowToggleTemplate { tag_id: target_id.to_string(), is_following: true, } .into_response()); } let count = db::follows::get_follower_count(&state.db, target_type, target_id).await?; Ok(FollowButtonTemplate { target_type: target_type.to_string(), target_id: target_id.to_string(), is_following: true, follower_count: count, } .into_response()) } /// DELETE /api/follow/{target_type}/{target_id}: unfollow a user or project. #[tracing::instrument(skip_all, name = "follows::unfollow_target")] pub(super) async fn unfollow_target( State(state): State, AuthUser(user): AuthUser, Path((target_type_str, target_id)): Path<(String, Uuid)>, ) -> Result { user.check_not_suspended()?; let target_type: FollowTargetType = target_type_str.parse() .map_err(|_| AppError::BadRequest("Invalid target type".to_string()))?; validate_target(&state, target_type, target_id, user.id).await?; db::follows::unfollow(&state.db, user.id, target_type, target_id).await?; // Unsubscribe from all project mailing lists (non-critical) if target_type == FollowTargetType::Project && let Err(e) = db::mailing_lists::unsubscribe_from_project( &state.db, db::ProjectId::from(target_id), user.id, ).await { tracing::warn!(project_id = %target_id, error = ?e, "failed to unsubscribe from project mailing lists"); } if target_type == FollowTargetType::Tag { return Ok(TagFollowToggleTemplate { tag_id: target_id.to_string(), is_following: false, } .into_response()); } let count = db::follows::get_follower_count(&state.db, target_type, target_id).await?; Ok(FollowButtonTemplate { target_type: target_type.to_string(), target_id: target_id.to_string(), is_following: false, follower_count: count, } .into_response()) } /// Validate that the target exists and prevent self-following for user targets. /// Project self-following is allowed (creators may want to follow their own project feed). async fn validate_target( state: &AppState, target_type: FollowTargetType, target_id: Uuid, follower_id: UserId, ) -> Result<()> { match target_type { FollowTargetType::User => { if *follower_id == target_id { return Err(AppError::BadRequest("Cannot follow yourself".to_string())); } db::users::get_user_by_id(&state.db, UserId::from(target_id)) .await? .ok_or(AppError::NotFound)?; } FollowTargetType::Project => { db::projects::get_project_by_id(&state.db, db::ProjectId::from(target_id)) .await? .ok_or(AppError::NotFound)?; } FollowTargetType::Tag => { db::tags::get_tag_by_id(&state.db, db::TagId::from(target_id)) .await? .ok_or(AppError::NotFound)?; } } Ok(()) }