-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendpoints.rs
More file actions
361 lines (334 loc) · 10.5 KB
/
endpoints.rs
File metadata and controls
361 lines (334 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
use std::{
collections::{BTreeMap, BTreeSet},
ops::AddAssign,
};
use ::octocrab::models::teams::RequestedTeam;
use anyhow::Context;
use axum::{
Json,
extract::{OriginalUri, Path, State},
response::IntoResponse,
};
use chrono::Utc;
use futures::future::join_all;
use http::HeaderMap;
use indexmap::IndexMap;
use serde::Serialize;
use tower_sessions::Session;
use crate::{
Error, ServerState,
course::{BatchMembers, get_batch_members},
github_accounts::get_trainees,
newtypes::GithubLogin,
octocrab::{all_pages, octocrab, octocrab_for_maybe_token},
prs::{PrWithReviews, fill_in_reviewers, get_prs},
register::{Attendance, get_register},
sheets::sheets_client,
};
pub async fn health_check() -> impl IntoResponse {
"ok"
}
pub async fn whoami_github(
session: Session,
State(server_state): State<ServerState>,
OriginalUri(original_uri): OriginalUri,
) -> Result<String, Error> {
let user = octocrab(&session, &server_state, original_uri)
.await?
.current()
.user()
.await
.context("Failed to get current user")?;
Ok(format!("You are authenticated as {}", user.login))
}
#[derive(Serialize)]
pub struct GroupMetadata {
name: String,
slug: String,
}
#[derive(Serialize)]
pub struct Subgroups {
groups: Vec<GroupMetadata>,
}
#[derive(Serialize)]
pub struct Courses {
courses: IndexMap<String, Vec<String>>,
}
pub async fn courses(State(server_state): State<ServerState>) -> Json<Courses> {
let courses = server_state
.config
.courses
.into_iter()
.filter_map(|(course_name, course_info)| {
course_info
.batches
.get_index(0)
.map(|(_batch_name, course_schedule)| {
(
course_name,
course_schedule.sprints.keys().cloned().collect::<Vec<_>>(),
)
})
})
.collect();
Json(Courses { courses })
}
pub async fn trainee_batches(
session: Session,
State(server_state): State<ServerState>,
OriginalUri(original_uri): OriginalUri,
Path(course): Path<String>,
) -> Result<Json<Subgroups>, Error> {
let octocrab = octocrab(&session, &server_state, original_uri).await?;
let results = all_pages("child teams", &octocrab, async || {
octocrab
.teams(server_state.config.github_org)
.list_children(format!("{course}-trainees"))
.send()
.await
})
.await?;
Ok(Json(Subgroups {
groups: results
.into_iter()
.map(|RequestedTeam { name, slug, .. }| GroupMetadata { name, slug })
.collect(),
}))
}
pub async fn trainee_batch(
session: Session,
headers: HeaderMap,
State(server_state): State<ServerState>,
OriginalUri(original_uri): OriginalUri,
Path((_course, batch)): Path<(String, String)>,
) -> Result<Json<BatchMembers>, Error> {
let octocrab = octocrab(&session, &server_state, original_uri.clone()).await?;
let sheets_client =
sheets_client(&session, server_state.clone(), headers, original_uri).await?;
let batch_members = get_batch_members(
&octocrab,
sheets_client,
&server_state.config.github_email_mapping_sheet_id,
&server_state.config.github_org,
&batch,
)
.await?;
Ok(Json(batch_members))
}
pub async fn teams(
session: Session,
State(server_state): State<ServerState>,
OriginalUri(original_uri): OriginalUri,
) -> Result<String, Error> {
let octocrab = octocrab(&session, &server_state, original_uri).await?;
let results = all_pages("team members", &octocrab, async || {
octocrab
.teams("CodeYourFuture")
.members("itp-mentors")
.send()
.await
})
.await?;
let mut ret = String::new();
for result in results {
ret += &result.login;
ret += "\n";
}
Ok(ret)
}
#[derive(Serialize)]
pub struct PrList {
prs: Vec<PrWithReviews>,
}
pub async fn course_prs(
session: Session,
State(server_state): State<ServerState>,
OriginalUri(original_uri): OriginalUri,
Path(course): Path<String>,
) -> Result<Json<PrList>, Error> {
let octocrab = octocrab(&session, &server_state, original_uri).await?;
let mut futures = Vec::new();
let course = server_state
.config
.courses
.get(&course)
.ok_or_else(|| Error::Fatal(anyhow::anyhow!("Course not found: {course}")))?;
for module in course
.batches
.get_index(0)
.iter()
.flat_map(|(_batch_name, course_schedule)| course_schedule.sprints.keys().cloned())
{
let octocrab = octocrab.clone();
let github_org = &server_state.config.github_org;
futures.push(async move {
let prs = get_prs(&octocrab, github_org, &module, true).await?;
fill_in_reviewers(octocrab.clone(), github_org.to_owned(), prs).await
});
}
let mut prs = Vec::new();
for future in join_all(futures).await {
prs.extend(future?)
}
Ok(Json(PrList { prs }))
}
#[derive(Serialize)]
pub struct Region {
region: Option<crate::newtypes::Region>,
}
pub async fn get_region(
session: Session,
headers: HeaderMap,
State(server_state): State<ServerState>,
OriginalUri(original_uri): OriginalUri,
Path(github_login): Path<String>,
) -> Result<Json<Region>, Error> {
let sheets_client = sheets_client(
&session,
server_state.clone(),
headers,
original_uri.clone(),
)
.await?;
let trainees = get_trainees(
sheets_client,
&server_state.config.github_email_mapping_sheet_id,
)
.await?;
Ok(Json(Region {
region: trainees
.get(&GithubLogin::from(github_login))
.map(|trainee| trainee.region.clone()),
}))
}
#[derive(Serialize)]
pub struct AttendanceResponse {
#[serde(flatten)]
attendance: Attendance,
sprint: String,
module: String,
batch: String,
}
pub async fn fetch_attendance(
session: Session,
headers: HeaderMap,
State(server_state): State<ServerState>,
OriginalUri(original_uri): OriginalUri,
) -> Result<Json<Vec<AttendanceResponse>>, Error> {
let all_courses = &server_state.config.courses;
let sheets_client = sheets_client(
&session,
server_state.clone(),
headers,
original_uri.clone(),
)
.await?;
let mut register_futures = Vec::new();
for (course_name, course_info) in all_courses {
for batch_name in course_info.batches.keys() {
let course_schedule = server_state
.config
.get_course_schedule_with_register_sheet_id(course_name.clone(), batch_name)
.ok_or_else(|| Error::Fatal(anyhow::anyhow!("Course not found: {course_name}")))?;
let register_future = get_register(
sheets_client.clone(),
course_schedule.register_sheet_id.clone(),
course_schedule.course_schedule.start,
course_schedule.course_schedule.end,
);
register_futures.push(async move {
(
course_name.clone(),
batch_name.clone(),
register_future.await,
)
});
}
}
let register_info = join_all(register_futures).await;
let mut registered_attendance = Vec::new();
for (_course_name, batch_name, register_result) in register_info {
let register = register_result?;
for (module_name, sprint_info) in register.modules {
for (sprint_number, attendance_info) in sprint_info.attendance.iter().enumerate() {
let sprint_name = format!("Sprint-{}", sprint_number + 1);
for attendance in attendance_info.values() {
registered_attendance.push(AttendanceResponse {
attendance: attendance.clone(),
sprint: sprint_name.clone(),
module: module_name.clone(),
batch: batch_name.clone(),
});
}
}
}
}
Ok(Json(registered_attendance))
}
#[derive(Serialize)]
pub struct ExpectedAttendance {
course: String,
cohort: String,
region: crate::newtypes::Region,
expected_classes: usize,
}
pub async fn expected_attendance(
State(server_state): State<ServerState>,
) -> Json<Vec<ExpectedAttendance>> {
let now = Utc::now();
let mut expected_attendance = Vec::new();
for (course, course_info) in server_state.config.courses {
for (cohort, schedule) in course_info.batches {
let mut region_to_expected_classes: BTreeMap<crate::newtypes::Region, usize> =
BTreeMap::new();
for (_module_name, sprints) in schedule.sprints {
for sprint in sprints {
for (region, date) in sprint {
let start_time = region.class_start_time(&date);
if start_time < now {
region_to_expected_classes
.entry(region)
.or_default()
.add_assign(1);
}
}
}
}
for (region, expected_classes) in region_to_expected_classes {
expected_attendance.push(ExpectedAttendance {
course: course.clone(),
cohort: cohort.clone(),
region,
expected_classes,
})
}
}
}
Json(expected_attendance)
}
pub async fn started_itp(
session: Session,
State(server_state): State<ServerState>,
OriginalUri(original_uri): OriginalUri,
) -> Result<Json<BTreeSet<GithubLogin>>, Error> {
let octocrab = octocrab(&session, &server_state, original_uri).await;
// Allow un-authenticated requests to this endpoint.
let octocrab = if let Ok(octocrab) = octocrab {
octocrab
} else {
octocrab_for_maybe_token(None)?
};
let prs = all_pages("pull requests", &octocrab, async || {
octocrab
.pulls(server_state.config.github_org, "Module-Onboarding")
.list()
.send()
.await
})
.await?;
let usernames: BTreeSet<_> = prs
.into_iter()
.filter_map(|pr| Some(GithubLogin::from(pr.user.login)))
.collect();
Ok(Json(usernames))
}