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(¶ms) {
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 Ok(Json(CheckIsContributorResponse {
68 signed_at: app
69 .db
70 .get_contributor_sign_timestamp(¶ms)
71 .await?
72 .map(|ts| ts.and_utc().to_rfc3339_opts(SecondsFormat::Millis, true)),
73 }))
74}
75
76/// The Renovate bot GitHub user (`renovate[bot]`).
77///
78/// https://api.github.com/users/renovate[bot]
79struct RenovateBot;
80
81impl RenovateBot {
82 const LOGIN: &'static str = "renovate[bot]";
83 const USER_ID: i32 = 29139614;
84
85 /// Returns the `created_at` timestamp for the Renovate bot user.
86 fn created_at() -> &'static NaiveDateTime {
87 static CREATED_AT: OnceLock<NaiveDateTime> = OnceLock::new();
88 CREATED_AT.get_or_init(|| {
89 chrono::DateTime::parse_from_rfc3339("2017-06-02T07:04:12Z")
90 .expect("failed to parse 'created_at' for 'renovate[bot]'")
91 .naive_utc()
92 })
93 }
94
95 /// Returns whether the given contributor selector corresponds to the Renovate bot user.
96 fn is_renovate_bot(contributor: &ContributorSelector) -> bool {
97 match contributor {
98 ContributorSelector::GitHubLogin { github_login } => github_login == Self::LOGIN,
99 ContributorSelector::GitHubUserId { github_user_id } => {
100 github_user_id == &Self::USER_ID
101 }
102 }
103 }
104}
105
106#[derive(Debug, Deserialize)]
107struct AddContributorBody {
108 github_user_id: i32,
109 github_login: String,
110 github_email: Option<String>,
111 github_name: Option<String>,
112 github_user_created_at: chrono::DateTime<chrono::Utc>,
113}
114
115async fn add_contributor(
116 Extension(app): Extension<Arc<AppState>>,
117 extract::Json(params): extract::Json<AddContributorBody>,
118) -> Result<()> {
119 let initial_channel_id = app.config.auto_join_channel_id;
120 app.db
121 .add_contributor(
122 ¶ms.github_login,
123 params.github_user_id,
124 params.github_email.as_deref(),
125 params.github_name.as_deref(),
126 params.github_user_created_at,
127 initial_channel_id,
128 )
129 .await
130}