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