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 Dependabot::is_dependabot(&params) {
 58        return Ok(Json(CheckIsContributorResponse {
 59            signed_at: Some(
 60                Dependabot::created_at()
 61                    .and_utc()
 62                    .to_rfc3339_opts(SecondsFormat::Millis, true),
 63            ),
 64        }));
 65    }
 66
 67    if RenovateBot::is_renovate_bot(&params) {
 68        return Ok(Json(CheckIsContributorResponse {
 69            signed_at: Some(
 70                RenovateBot::created_at()
 71                    .and_utc()
 72                    .to_rfc3339_opts(SecondsFormat::Millis, true),
 73            ),
 74        }));
 75    }
 76
 77    if ZedZippyBot::is_zed_zippy_bot(&params) {
 78        return Ok(Json(CheckIsContributorResponse {
 79            signed_at: Some(
 80                ZedZippyBot::created_at()
 81                    .and_utc()
 82                    .to_rfc3339_opts(SecondsFormat::Millis, true),
 83            ),
 84        }));
 85    }
 86
 87    Ok(Json(CheckIsContributorResponse {
 88        signed_at: app
 89            .db
 90            .get_contributor_sign_timestamp(&params)
 91            .await?
 92            .map(|ts| ts.and_utc().to_rfc3339_opts(SecondsFormat::Millis, true)),
 93    }))
 94}
 95
 96/// The Dependabot bot GitHub user (`dependabot[bot]`).
 97///
 98/// https://api.github.com/users/dependabot[bot]
 99struct Dependabot;
100
101impl Dependabot {
102    const LOGIN: &'static str = "dependabot[bot]";
103    const USER_ID: i32 = 49699333;
104
105    /// Returns the `created_at` timestamp for the Dependabot bot user.
106    fn created_at() -> &'static NaiveDateTime {
107        static CREATED_AT: OnceLock<NaiveDateTime> = OnceLock::new();
108        CREATED_AT.get_or_init(|| {
109            chrono::DateTime::parse_from_rfc3339("2019-04-16T22:34:25Z")
110                .expect("failed to parse 'created_at' for 'dependabot[bot]'")
111                .naive_utc()
112        })
113    }
114
115    /// Returns whether the given contributor selector corresponds to the Dependabot bot user.
116    fn is_dependabot(contributor: &ContributorSelector) -> bool {
117        match contributor {
118            ContributorSelector::GitHubLogin { github_login } => github_login == Self::LOGIN,
119            ContributorSelector::GitHubUserId { github_user_id } => {
120                github_user_id == &Self::USER_ID
121            }
122        }
123    }
124}
125
126/// The Renovate bot GitHub user (`renovate[bot]`).
127///
128/// https://api.github.com/users/renovate[bot]
129struct RenovateBot;
130
131impl RenovateBot {
132    const LOGIN: &'static str = "renovate[bot]";
133    const USER_ID: i32 = 29139614;
134
135    /// Returns the `created_at` timestamp for the Renovate bot user.
136    fn created_at() -> &'static NaiveDateTime {
137        static CREATED_AT: OnceLock<NaiveDateTime> = OnceLock::new();
138        CREATED_AT.get_or_init(|| {
139            chrono::DateTime::parse_from_rfc3339("2017-06-02T07:04:12Z")
140                .expect("failed to parse 'created_at' for 'renovate[bot]'")
141                .naive_utc()
142        })
143    }
144
145    /// Returns whether the given contributor selector corresponds to the Renovate bot user.
146    fn is_renovate_bot(contributor: &ContributorSelector) -> bool {
147        match contributor {
148            ContributorSelector::GitHubLogin { github_login } => github_login == Self::LOGIN,
149            ContributorSelector::GitHubUserId { github_user_id } => {
150                github_user_id == &Self::USER_ID
151            }
152        }
153    }
154}
155
156/// The Zed Zippy bot GitHub user (`zed-zippy[bot]`).
157///
158/// https://api.github.com/users/zed-zippy[bot]
159struct ZedZippyBot;
160
161impl ZedZippyBot {
162    const LOGIN: &'static str = "zed-zippy[bot]";
163    const USER_ID: i32 = 234243425;
164
165    /// Returns the `created_at` timestamp for the Zed Zippy bot user.
166    fn created_at() -> &'static NaiveDateTime {
167        static CREATED_AT: OnceLock<NaiveDateTime> = OnceLock::new();
168        CREATED_AT.get_or_init(|| {
169            chrono::DateTime::parse_from_rfc3339("2025-09-24T17:00:11Z")
170                .expect("failed to parse 'created_at' for 'zed-zippy[bot]'")
171                .naive_utc()
172        })
173    }
174
175    /// Returns whether the given contributor selector corresponds to the Zed Zippy bot user.
176    fn is_zed_zippy_bot(contributor: &ContributorSelector) -> bool {
177        match contributor {
178            ContributorSelector::GitHubLogin { github_login } => github_login == Self::LOGIN,
179            ContributorSelector::GitHubUserId { github_user_id } => {
180                github_user_id == &Self::USER_ID
181            }
182        }
183    }
184}
185
186#[derive(Debug, Deserialize)]
187struct AddContributorBody {
188    github_user_id: i32,
189    github_login: String,
190    github_email: Option<String>,
191    github_name: Option<String>,
192    github_user_created_at: chrono::DateTime<chrono::Utc>,
193}
194
195async fn add_contributor(
196    Extension(app): Extension<Arc<AppState>>,
197    extract::Json(params): extract::Json<AddContributorBody>,
198) -> Result<()> {
199    let initial_channel_id = app.config.auto_join_channel_id;
200    app.db
201        .add_contributor(
202            &params.github_login,
203            params.github_user_id,
204            params.github_email.as_deref(),
205            params.github_name.as_deref(),
206            params.github_user_created_at,
207            initial_channel_id,
208        )
209        .await
210}