contributors.rs

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