contributors.rs

  1use std::sync::{Arc, OnceLock};
  2
  3use axum::{
  4    Extension, Json, Router,
  5    extract::{self, Query},
  6    routing::get,
  7};
  8use chrono::{NaiveDateTime, SecondsFormat};
  9use serde::{Deserialize, Serialize};
 10
 11use crate::db::ContributorSelector;
 12use crate::{AppState, Result};
 13
 14pub fn router() -> Router {
 15    Router::new()
 16        .route("/contributors", get(get_contributors).post(add_contributor))
 17        .route("/contributor", get(check_is_contributor))
 18}
 19
 20async fn get_contributors(Extension(app): Extension<Arc<AppState>>) -> Result<Json<Vec<String>>> {
 21    Ok(Json(app.db.get_contributors().await?))
 22}
 23
 24#[derive(Debug, Deserialize)]
 25struct CheckIsContributorParams {
 26    github_user_id: Option<i32>,
 27    github_login: Option<String>,
 28}
 29
 30impl CheckIsContributorParams {
 31    fn into_contributor_selector(self) -> Result<ContributorSelector> {
 32        if let Some(github_user_id) = self.github_user_id {
 33            return Ok(ContributorSelector::GitHubUserId { github_user_id });
 34        }
 35
 36        if let Some(github_login) = self.github_login {
 37            return Ok(ContributorSelector::GitHubLogin { github_login });
 38        }
 39
 40        Err(anyhow::anyhow!(
 41            "must be one of `github_user_id` or `github_login`."
 42        ))?
 43    }
 44}
 45
 46#[derive(Debug, Serialize)]
 47struct CheckIsContributorResponse {
 48    signed_at: Option<String>,
 49}
 50
 51async fn check_is_contributor(
 52    Extension(app): Extension<Arc<AppState>>,
 53    Query(params): Query<CheckIsContributorParams>,
 54) -> Result<Json<CheckIsContributorResponse>> {
 55    let params = params.into_contributor_selector()?;
 56
 57    if RenovateBot::is_renovate_bot(&params) {
 58        return Ok(Json(CheckIsContributorResponse {
 59            signed_at: Some(
 60                RenovateBot::created_at()
 61                    .and_utc()
 62                    .to_rfc3339_opts(SecondsFormat::Millis, true),
 63            ),
 64        }));
 65    }
 66
 67    if ZedZippyBot::is_zed_zippy_bot(&params) {
 68        return Ok(Json(CheckIsContributorResponse {
 69            signed_at: Some(
 70                ZedZippyBot::created_at()
 71                    .and_utc()
 72                    .to_rfc3339_opts(SecondsFormat::Millis, true),
 73            ),
 74        }));
 75    }
 76
 77    Ok(Json(CheckIsContributorResponse {
 78        signed_at: app
 79            .db
 80            .get_contributor_sign_timestamp(&params)
 81            .await?
 82            .map(|ts| ts.and_utc().to_rfc3339_opts(SecondsFormat::Millis, true)),
 83    }))
 84}
 85
 86/// The Renovate bot GitHub user (`renovate[bot]`).
 87///
 88/// https://api.github.com/users/renovate[bot]
 89struct RenovateBot;
 90
 91impl RenovateBot {
 92    const LOGIN: &'static str = "renovate[bot]";
 93    const USER_ID: i32 = 29139614;
 94
 95    /// Returns the `created_at` timestamp for the Renovate bot user.
 96    fn created_at() -> &'static NaiveDateTime {
 97        static CREATED_AT: OnceLock<NaiveDateTime> = OnceLock::new();
 98        CREATED_AT.get_or_init(|| {
 99            chrono::DateTime::parse_from_rfc3339("2017-06-02T07:04:12Z")
100                .expect("failed to parse 'created_at' for 'renovate[bot]'")
101                .naive_utc()
102        })
103    }
104
105    /// Returns whether the given contributor selector corresponds to the Renovate bot user.
106    fn is_renovate_bot(contributor: &ContributorSelector) -> bool {
107        match contributor {
108            ContributorSelector::GitHubLogin { github_login } => github_login == Self::LOGIN,
109            ContributorSelector::GitHubUserId { github_user_id } => {
110                github_user_id == &Self::USER_ID
111            }
112        }
113    }
114}
115
116/// The Zed Zippy bot GitHub user (`zed-zippy[bot]`).
117///
118/// https://api.github.com/users/zed-zippy[bot]
119struct ZedZippyBot;
120
121impl ZedZippyBot {
122    const LOGIN: &'static str = "zed-zippy[bot]";
123    const USER_ID: i32 = 234243425;
124
125    /// Returns the `created_at` timestamp for the Zed Zippy bot user.
126    fn created_at() -> &'static NaiveDateTime {
127        static CREATED_AT: OnceLock<NaiveDateTime> = OnceLock::new();
128        CREATED_AT.get_or_init(|| {
129            chrono::DateTime::parse_from_rfc3339("2025-09-24T17:00:11Z")
130                .expect("failed to parse 'created_at' for 'zed-zippy[bot]'")
131                .naive_utc()
132        })
133    }
134
135    /// Returns whether the given contributor selector corresponds to the Zed Zippy bot user.
136    fn is_zed_zippy_bot(contributor: &ContributorSelector) -> bool {
137        match contributor {
138            ContributorSelector::GitHubLogin { github_login } => github_login == Self::LOGIN,
139            ContributorSelector::GitHubUserId { github_user_id } => {
140                github_user_id == &Self::USER_ID
141            }
142        }
143    }
144}
145
146#[derive(Debug, Deserialize)]
147struct AddContributorBody {
148    github_user_id: i32,
149    github_login: String,
150    github_email: Option<String>,
151    github_name: Option<String>,
152    github_user_created_at: chrono::DateTime<chrono::Utc>,
153}
154
155async fn add_contributor(
156    Extension(app): Extension<Arc<AppState>>,
157    extract::Json(params): extract::Json<AddContributorBody>,
158) -> Result<()> {
159    let initial_channel_id = app.config.auto_join_channel_id;
160    app.db
161        .add_contributor(
162            &params.github_login,
163            params.github_user_id,
164            params.github_email.as_deref(),
165            params.github_name.as_deref(),
166            params.github_user_created_at,
167            initial_channel_id,
168        )
169        .await
170}