| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | use std::collections::HashMap; |
| 16 | |
| 17 | use forge_core::issues::{ |
| 18 | Comment, IssueFilter, IssueListItem, IssueSort, IssueState, Label, Milestone, |
| 19 | }; |
| 20 | use forge_core::pulls::PullRequest; |
| 21 | use forge_core::reactions::ReactionTarget; |
| 22 | use forge_core::reviews::{Review, ReviewComment, ReviewState, Side}; |
| 23 | use forge_core::token::hash_token; |
| 24 | use forge_core::{Action, Repo as CoreRepo, User, Visibility}; |
| 25 | use http::HeaderMap; |
| 26 | use http::header::{AUTHORIZATION, HeaderName, HeaderValue}; |
| 27 | use serde_json::{Value, json}; |
| 28 | use topcoat::context::{Cx, context}; |
| 29 | use topcoat::router::request::{headers, uri}; |
| 30 | use topcoat::router::response::Response; |
| 31 | use topcoat::router::{StatusCode, path_param, route}; |
| 32 | |
| 33 | use crate::api::{self, Refusal}; |
| 34 | use crate::client_ip::client_ip; |
| 35 | use crate::state::AppState; |
| 36 | |
| 37 | path_param!(owner); |
| 38 | path_param!(repo); |
| 39 | path_param!(index); |
| 40 | path_param!(id); |
| 41 | path_param!(review_id); |
| 42 | |
| 43 | |
| 44 | |
| 45 | pub const GITEA_VERSION: &str = "1.22.0"; |
| 46 | |
| 47 | pub const MAX_PAGE: usize = 50; |
| 48 | |
| 49 | const DEFAULT_PAGE: usize = 30; |
| 50 | |
| 51 | |
| 52 | pub fn numeric_id(id: &str) -> i64 { |
| 53 | let digest = hash_token(id); |
| 54 | i64::from_str_radix(&digest[..12], 16).unwrap_or(0) + 1 |
| 55 | } |
| 56 | |
| 57 | |
| 58 | pub fn is_numeric(raw: &str) -> bool { |
| 59 | !raw.is_empty() && raw.len() <= 15 && raw.bytes().all(|b| b.is_ascii_digit()) |
| 60 | } |
| 61 | |
| 62 | |
| 63 | fn comment_id(number: i64, position: usize) -> i64 { |
| 64 | (number << 20) | (position as i64 + 1) |
| 65 | } |
| 66 | |
| 67 | fn split_comment_id(id: i64) -> Option<(i64, usize)> { |
| 68 | let position = (id & 0xF_FFFF) as usize; |
| 69 | let number = id >> 20; |
| 70 | (number > 0 && position > 0).then_some((number, position - 1)) |
| 71 | } |
| 72 | |
| 73 | |
| 74 | pub fn user_json(base: &str, id: &str, name: &str) -> Value { |
| 75 | json!({ |
| 76 | "id": numeric_id(id), |
| 77 | "login": name, |
| 78 | "username": name, |
| 79 | "login_name": "", |
| 80 | "full_name": "", |
| 81 | "email": "", |
| 82 | "avatar_url": "", |
| 83 | "html_url": format!("{}/{}", base.trim_end_matches('/'), name), |
| 84 | "is_admin": false, |
| 85 | }) |
| 86 | } |
| 87 | |
| 88 | |
| 89 | fn query_value(cx: &Cx, key: &str) -> Option<String> { |
| 90 | let query = uri(cx).query()?; |
| 91 | form_urlencoded::parse(query.as_bytes()) |
| 92 | .find(|(k, _)| k == key) |
| 93 | .map(|(_, v)| v.into_owned()) |
| 94 | } |
| 95 | |
| 96 | |
| 97 | |
| 98 | fn effective_headers(cx: &Cx) -> HeaderMap { |
| 99 | let mut map = headers(cx).clone(); |
| 100 | if !map.contains_key(AUTHORIZATION) |
| 101 | && let Some(token) = query_value(cx, "access_token").or_else(|| query_value(cx, "token")) |
| 102 | && let Ok(value) = HeaderValue::from_str(&format!("token {token}")) |
| 103 | { |
| 104 | map.insert(AUTHORIZATION, value); |
| 105 | } |
| 106 | map |
| 107 | } |
| 108 | |
| 109 | |
| 110 | async fn caller(cx: &Cx) -> Result<(Option<User>, Option<String>), Refusal> { |
| 111 | let state = context::<AppState>(cx); |
| 112 | let map = effective_headers(cx); |
| 113 | let actor = api::authenticate(state, client_ip(cx), &map).await?; |
| 114 | let token = api::presented_token(&map).flatten(); |
| 115 | Ok((actor, token)) |
| 116 | } |
| 117 | |
| 118 | struct Ctx { |
| 119 | repo: CoreRepo, |
| 120 | token: Option<String>, |
| 121 | base: String, |
| 122 | } |
| 123 | |
| 124 | async fn read_ctx(cx: &Cx) -> Result<Ctx, Refusal> { |
| 125 | let state = context::<AppState>(cx); |
| 126 | let (actor, token) = caller(cx).await?; |
| 127 | let repo = api::load_repo(state, actor.as_ref(), owner(cx), repo(cx), Action::Read).await?; |
| 128 | Ok(Ctx { |
| 129 | repo, |
| 130 | token: actor.and(token), |
| 131 | base: state.config.base_url.trim_end_matches('/').to_owned(), |
| 132 | }) |
| 133 | } |
| 134 | |
| 135 | fn bad(message: &str) -> Refusal { |
| 136 | Box::new(api::error(StatusCode::BAD_REQUEST, message)) |
| 137 | } |
| 138 | |
| 139 | fn not_found(what: &str) -> Refusal { |
| 140 | Box::new(api::error(StatusCode::NOT_FOUND, what)) |
| 141 | } |
| 142 | |
| 143 | |
| 144 | |
| 145 | pub struct Paging { |
| 146 | pub page: usize, |
| 147 | pub limit: usize, |
| 148 | } |
| 149 | |
| 150 | pub fn paging(cx: &Cx, default_limit: usize) -> Paging { |
| 151 | let number = |key: &str| query_value(cx, key).and_then(|v| v.parse::<usize>().ok()); |
| 152 | Paging { |
| 153 | page: number("page").filter(|p| *p > 0).unwrap_or(1), |
| 154 | limit: number("limit") |
| 155 | .filter(|l| *l > 0) |
| 156 | .map_or(default_limit, |l| l.min(MAX_PAGE)), |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | |
| 161 | pub fn slice<T>(items: Vec<T>, pg: &Paging) -> (Vec<T>, usize) { |
| 162 | let total = items.len(); |
| 163 | let start = pg.page.saturating_sub(1).saturating_mul(pg.limit); |
| 164 | ( |
| 165 | items.into_iter().skip(start).take(pg.limit).collect(), |
| 166 | total, |
| 167 | ) |
| 168 | } |
| 169 | |
| 170 | |
| 171 | pub fn page_response(cx: &Cx, items: Vec<Value>, total: usize, pg: &Paging) -> Response { |
| 172 | let mut res = api::json(StatusCode::OK, &Value::Array(items)); |
| 173 | let last = total.div_ceil(pg.limit.max(1)).max(1); |
| 174 | let state = context::<AppState>(cx); |
| 175 | let base = state.config.base_url.trim_end_matches('/'); |
| 176 | let mut rest = String::new(); |
| 177 | if let Some(query) = uri(cx).query() { |
| 178 | for (k, v) in form_urlencoded::parse(query.as_bytes()) { |
| 179 | if k != "page" && k != "limit" { |
| 180 | rest.push_str(&format!( |
| 181 | "{}={}&", |
| 182 | form_urlencoded::byte_serialize(k.as_bytes()).collect::<String>(), |
| 183 | form_urlencoded::byte_serialize(v.as_bytes()).collect::<String>() |
| 184 | )); |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | let link = |page: usize, rel: &str| { |
| 189 | format!( |
| 190 | "<{base}{}?{rest}page={page}&limit={}>; rel=\"{rel}\"", |
| 191 | uri(cx).path(), |
| 192 | pg.limit |
| 193 | ) |
| 194 | }; |
| 195 | let mut links = Vec::new(); |
| 196 | if pg.page < last { |
| 197 | links.push(link(pg.page + 1, "next")); |
| 198 | links.push(link(last, "last")); |
| 199 | } |
| 200 | if pg.page > 1 { |
| 201 | links.push(link(pg.page - 1, "prev")); |
| 202 | links.push(link(1, "first")); |
| 203 | } |
| 204 | let map = res.headers_mut(); |
| 205 | map.insert( |
| 206 | HeaderName::from_static("x-total-count"), |
| 207 | HeaderValue::from(total), |
| 208 | ); |
| 209 | if !links.is_empty() |
| 210 | && let Ok(value) = HeaderValue::from_str(&links.join(", ")) |
| 211 | { |
| 212 | map.insert(HeaderName::from_static("link"), value); |
| 213 | } |
| 214 | map.insert( |
| 215 | HeaderName::from_static("access-control-expose-headers"), |
| 216 | HeaderValue::from_static("Link, X-Total-Count"), |
| 217 | ); |
| 218 | res |
| 219 | } |
| 220 | |
| 221 | fn internal(e: impl std::fmt::Display) -> Refusal { |
| 222 | api::internal(e) |
| 223 | } |
| 224 | |
| 225 | #[route(GET "/api/v1/version")] |
| 226 | async fn version_route(cx: &Cx) -> topcoat::Result<Response> { |
| 227 | Ok(api::json( |
| 228 | StatusCode::OK, |
| 229 | &json!({ "version": GITEA_VERSION }), |
| 230 | )) |
| 231 | } |
| 232 | |
| 233 | #[route(GET "/api/v1/settings/api")] |
| 234 | async fn settings_api(cx: &Cx) -> topcoat::Result<Response> { |
| 235 | Ok(api::json( |
| 236 | StatusCode::OK, |
| 237 | &json!({ |
| 238 | "max_response_items": MAX_PAGE, |
| 239 | "default_paging_num": DEFAULT_PAGE, |
| 240 | "default_git_trees_per_page": 1000, |
| 241 | "default_max_blob_size": 10_485_760, |
| 242 | }), |
| 243 | )) |
| 244 | } |
| 245 | |
| 246 | |
| 247 | |
| 248 | fn clone_url(base: &str, repo: &CoreRepo, token: Option<&str>) -> String { |
| 249 | let plain = format!("{base}/{}/{}.git", repo.owner_name, repo.name); |
| 250 | match (repo.visibility, token) { |
| 251 | (Visibility::Private, Some(token)) => match plain.split_once("://") { |
| 252 | Some((scheme, rest)) => format!("{scheme}://oauth2:{token}@{rest}"), |
| 253 | None => plain, |
| 254 | }, |
| 255 | _ => plain, |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | |
| 260 | pub async fn repo_json( |
| 261 | state: &AppState, |
| 262 | base: &str, |
| 263 | repo: &CoreRepo, |
| 264 | token: Option<&str>, |
| 265 | ) -> Result<Value, Refusal> { |
| 266 | let empty = repo.default_branch.is_empty(); |
| 267 | let ssh_host = &state.config.ssh_public_host; |
| 268 | Ok(json!({ |
| 269 | "id": numeric_id(&repo.id), |
| 270 | "owner": user_json(base, &repo.owner_id, &repo.owner_name), |
| 271 | "name": repo.name, |
| 272 | "full_name": format!("{}/{}", repo.owner_name, repo.name), |
| 273 | "description": repo.description, |
| 274 | "empty": empty, |
| 275 | "private": repo.visibility == Visibility::Private, |
| 276 | "fork": repo.fork_of.is_some(), |
| 277 | "template": false, |
| 278 | "mirror": false, |
| 279 | "archived": repo.archived, |
| 280 | "website": "", |
| 281 | "html_url": format!("{base}/{}/{}", repo.owner_name, repo.name), |
| 282 | "clone_url": clone_url(base, repo, token), |
| 283 | "ssh_url": format!("git@{ssh_host}:{}/{}.git", repo.owner_name, repo.name), |
| 284 | "original_url": "", |
| 285 | "default_branch": repo.default_branch, |
| 286 | "avatar_url": "", |
| 287 | "has_issues": true, |
| 288 | "has_pull_requests": true, |
| 289 | "has_wiki": true, |
| 290 | "has_releases": true, |
| 291 | "created_at": repo.created_at, |
| 292 | "updated_at": repo.created_at, |
| 293 | })) |
| 294 | } |
| 295 | |
| 296 | #[route(GET "/api/v1/repos/{owner}/{repo}")] |
| 297 | async fn get_repo(cx: &Cx) -> topcoat::Result<Response> { |
| 298 | let state = context::<AppState>(cx); |
| 299 | let ctx = match read_ctx(cx).await { |
| 300 | Ok(ctx) => ctx, |
| 301 | Err(res) => return Ok(*res), |
| 302 | }; |
| 303 | match repo_json(state, &ctx.base, &ctx.repo, ctx.token.as_deref()).await { |
| 304 | Ok(value) => Ok(api::json(StatusCode::OK, &value)), |
| 305 | Err(res) => Ok(*res), |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | |
| 310 | #[route(GET "/api/v1/repos/{owner}/{repo}/topics")] |
| 311 | async fn topics_route(cx: &Cx) -> topcoat::Result<Response> { |
| 312 | match read_ctx(cx).await { |
| 313 | Ok(_) => Ok(api::json(StatusCode::OK, &json!({ "topics": [] }))), |
| 314 | Err(res) => Ok(*res), |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | fn label_json(base: &str, repo: &CoreRepo, label: &Label) -> Value { |
| 319 | json!({ |
| 320 | "id": numeric_id(&label.id), |
| 321 | "name": label.name, |
| 322 | "exclusive": false, |
| 323 | "is_archived": false, |
| 324 | "color": label.color.trim_start_matches('#'), |
| 325 | "description": label.description, |
| 326 | "url": format!("{base}/api/v1/repos/{}/{}/labels/{}", repo.owner_name, repo.name, numeric_id(&label.id)), |
| 327 | }) |
| 328 | } |
| 329 | |
| 330 | #[route(GET "/api/v1/repos/{owner}/{repo}/labels")] |
| 331 | async fn list_labels_route(cx: &Cx) -> topcoat::Result<Response> { |
| 332 | let state = context::<AppState>(cx); |
| 333 | let ctx = match read_ctx(cx).await { |
| 334 | Ok(ctx) => ctx, |
| 335 | Err(res) => return Ok(*res), |
| 336 | }; |
| 337 | let all = match state.store.list_labels(&ctx.repo.id).await { |
| 338 | Ok(all) => all, |
| 339 | Err(e) => return Ok(*internal(e)), |
| 340 | }; |
| 341 | let pg = paging(cx, DEFAULT_PAGE); |
| 342 | let (page, total) = slice(all, &pg); |
| 343 | let items = page |
| 344 | .iter() |
| 345 | .map(|l| label_json(&ctx.base, &ctx.repo, l)) |
| 346 | .collect(); |
| 347 | Ok(page_response(cx, items, total, &pg)) |
| 348 | } |
| 349 | |
| 350 | fn date_time(date: &str) -> String { |
| 351 | if date.len() == 10 { |
| 352 | format!("{date}T00:00:00Z") |
| 353 | } else { |
| 354 | date.to_owned() |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | fn milestone_json(m: &Milestone) -> Value { |
| 359 | json!({ |
| 360 | "id": numeric_id(&m.id), |
| 361 | "title": m.title, |
| 362 | "description": m.description, |
| 363 | "state": m.state.as_str(), |
| 364 | "open_issues": m.open_issues, |
| 365 | "closed_issues": m.closed_issues, |
| 366 | "created_at": m.created_at, |
| 367 | "updated_at": m.closed_at.clone().unwrap_or_else(|| m.created_at.clone()), |
| 368 | "closed_at": m.closed_at, |
| 369 | "due_on": m.due_on.as_deref().map(date_time), |
| 370 | }) |
| 371 | } |
| 372 | |
| 373 | |
| 374 | fn state_filter(cx: &Cx) -> Result<Option<IssueState>, Refusal> { |
| 375 | match query_value(cx, "state").as_deref() { |
| 376 | None | Some("") | Some("open") => Ok(Some(IssueState::Open)), |
| 377 | Some("closed") => Ok(Some(IssueState::Closed)), |
| 378 | Some("all") => Ok(None), |
| 379 | Some(other) => Err(bad(&format!("unknown state {other:?}"))), |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | #[route(GET "/api/v1/repos/{owner}/{repo}/milestones")] |
| 384 | async fn list_milestones_route(cx: &Cx) -> topcoat::Result<Response> { |
| 385 | let state = context::<AppState>(cx); |
| 386 | let ctx = match read_ctx(cx).await { |
| 387 | Ok(ctx) => ctx, |
| 388 | Err(res) => return Ok(*res), |
| 389 | }; |
| 390 | let wanted = match state_filter(cx) { |
| 391 | Ok(wanted) => wanted, |
| 392 | Err(res) => return Ok(*res), |
| 393 | }; |
| 394 | let all = match state.store.list_milestones(&ctx.repo.id, wanted).await { |
| 395 | Ok(all) => all, |
| 396 | Err(e) => return Ok(*internal(e)), |
| 397 | }; |
| 398 | let pg = paging(cx, DEFAULT_PAGE); |
| 399 | let (page, total) = slice(all, &pg); |
| 400 | let items = page.iter().map(milestone_json).collect(); |
| 401 | Ok(page_response(cx, items, total, &pg)) |
| 402 | } |
| 403 | |
| 404 | |
| 405 | async fn names(state: &AppState, ids: Vec<String>) -> Result<HashMap<String, String>, Refusal> { |
| 406 | let found = state.store.usernames_by_ids(&ids).await.map_err(internal)?; |
| 407 | Ok(found |
| 408 | .into_iter() |
| 409 | .map(|(id, (name, _))| (id, name)) |
| 410 | .collect()) |
| 411 | } |
| 412 | |
| 413 | fn user_of(base: &str, names: &HashMap<String, String>, id: &str) -> Value { |
| 414 | let name = names.get(id).map_or("ghost", String::as_str); |
| 415 | user_json(base, id, name) |
| 416 | } |
| 417 | |
| 418 | |
| 419 | async fn issue_core( |
| 420 | state: &AppState, |
| 421 | ctx: &Ctx, |
| 422 | item: &IssueListItem, |
| 423 | milestones: &HashMap<String, Milestone>, |
| 424 | pull: bool, |
| 425 | ) -> Result<Value, Refusal> { |
| 426 | let issue = &item.issue; |
| 427 | let assignees = state |
| 428 | .store |
| 429 | .issue_assignees(&issue.id) |
| 430 | .await |
| 431 | .map_err(internal)?; |
| 432 | let assignees: Vec<Value> = assignees |
| 433 | .iter() |
| 434 | .map(|(id, name)| user_json(&ctx.base, id, name)) |
| 435 | .collect(); |
| 436 | let url = format!( |
| 437 | "{}/{}/{}/{}/{}", |
| 438 | ctx.base, |
| 439 | ctx.repo.owner_name, |
| 440 | ctx.repo.name, |
| 441 | if pull { "pulls" } else { "issues" }, |
| 442 | issue.number |
| 443 | ); |
| 444 | Ok(json!({ |
| 445 | "id": numeric_id(&issue.id), |
| 446 | "number": issue.number, |
| 447 | "user": user_json(&ctx.base, &issue.author_id, &item.author), |
| 448 | "title": issue.title, |
| 449 | "body": issue.body, |
| 450 | "labels": item.labels.iter().map(|l| label_json(&ctx.base, &ctx.repo, l)).collect::<Vec<_>>(), |
| 451 | "milestone": issue.milestone_id.as_ref().and_then(|m| milestones.get(m)).map(milestone_json), |
| 452 | "assignee": assignees.first(), |
| 453 | "assignees": assignees, |
| 454 | "state": issue.state.as_str(), |
| 455 | "is_locked": issue.locked, |
| 456 | "comments": issue.comment_count, |
| 457 | "created_at": issue.created_at, |
| 458 | "updated_at": issue.updated_at, |
| 459 | "closed_at": issue.closed_at, |
| 460 | "due_date": null, |
| 461 | "html_url": url, |
| 462 | "url": format!("{}/api/v1/repos/{}/{}/issues/{}", ctx.base, ctx.repo.owner_name, ctx.repo.name, issue.number), |
| 463 | "pull_request": if pull { json!({"merged": false, "merged_at": null, "html_url": url}) } else { Value::Null }, |
| 464 | })) |
| 465 | } |
| 466 | |
| 467 | async fn milestone_map( |
| 468 | state: &AppState, |
| 469 | repo: &CoreRepo, |
| 470 | ) -> Result<HashMap<String, Milestone>, Refusal> { |
| 471 | let all = state |
| 472 | .store |
| 473 | .list_milestones(&repo.id, None) |
| 474 | .await |
| 475 | .map_err(internal)?; |
| 476 | Ok(all.into_iter().map(|m| (m.id.clone(), m)).collect()) |
| 477 | } |
| 478 | |
| 479 | fn filter_of(cx: &Cx, pg: &Paging) -> Result<IssueFilter, Refusal> { |
| 480 | Ok(IssueFilter { |
| 481 | state: state_filter(cx)?, |
| 482 | sort: IssueSort::Oldest, |
| 483 | page: pg.page as u32, |
| 484 | per_page: pg.limit as u32, |
| 485 | ..IssueFilter::default() |
| 486 | }) |
| 487 | } |
| 488 | |
| 489 | #[route(GET "/api/v1/repos/{owner}/{repo}/issues")] |
| 490 | async fn list_issues_route(cx: &Cx) -> topcoat::Result<Response> { |
| 491 | let state = context::<AppState>(cx); |
| 492 | let ctx = match read_ctx(cx).await { |
| 493 | Ok(ctx) => ctx, |
| 494 | Err(res) => return Ok(*res), |
| 495 | }; |
| 496 | match issues_inner(cx, state, &ctx).await { |
| 497 | Ok(res) => Ok(res), |
| 498 | Err(res) => Ok(*res), |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | async fn issues_inner(cx: &Cx, state: &AppState, ctx: &Ctx) -> Result<Response, Refusal> { |
| 503 | let pg = paging(cx, DEFAULT_PAGE); |
| 504 | let filter = filter_of(cx, &pg)?; |
| 505 | let pulls = query_value(cx, "type").as_deref() == Some("pulls"); |
| 506 | let (rows, total) = if pulls { |
| 507 | state.store.list_pulls(&ctx.repo.id, &filter).await |
| 508 | } else { |
| 509 | state.store.list_issues(&ctx.repo.id, &filter).await |
| 510 | } |
| 511 | .map_err(internal)?; |
| 512 | let milestones = milestone_map(state, &ctx.repo).await?; |
| 513 | let mut out = Vec::with_capacity(rows.len()); |
| 514 | for item in &rows { |
| 515 | out.push(issue_core(state, ctx, item, &milestones, pulls).await?); |
| 516 | } |
| 517 | Ok(page_response(cx, out, total as usize, &pg)) |
| 518 | } |
| 519 | |
| 520 | |
| 521 | |
| 522 | async fn issue_row( |
| 523 | state: &AppState, |
| 524 | repo: &CoreRepo, |
| 525 | raw: &str, |
| 526 | ) -> Result<forge_core::issues::Issue, Refusal> { |
| 527 | let number: i64 = raw.parse().map_err(|_| bad("invalid issue index"))?; |
| 528 | match state.store.issue_by_number(&repo.id, number).await { |
| 529 | Ok(Some(issue)) => return Ok(issue), |
| 530 | Ok(None) => {} |
| 531 | Err(e) => return Err(internal(e)), |
| 532 | } |
| 533 | match state.store.pull_by_number(&repo.id, number).await { |
| 534 | Ok(Some(pull)) => Ok(pull.issue), |
| 535 | Ok(None) => Err(not_found("issue not found")), |
| 536 | Err(e) => Err(internal(e)), |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | fn comment_json( |
| 541 | ctx: &Ctx, |
| 542 | issue_number: i64, |
| 543 | position: usize, |
| 544 | comment: &Comment, |
| 545 | names: &HashMap<String, String>, |
| 546 | ) -> Value { |
| 547 | let id = comment_id(issue_number, position); |
| 548 | let issue_url = format!( |
| 549 | "{}/{}/{}/issues/{issue_number}", |
| 550 | ctx.base, ctx.repo.owner_name, ctx.repo.name |
| 551 | ); |
| 552 | json!({ |
| 553 | "id": id, |
| 554 | "html_url": format!("{issue_url}#comment-{id}"), |
| 555 | "issue_url": issue_url, |
| 556 | "pull_request_url": "", |
| 557 | "user": user_of(&ctx.base, names, &comment.author_id), |
| 558 | "original_author": "", |
| 559 | "original_author_id": 0, |
| 560 | "body": comment.body, |
| 561 | "created_at": comment.created_at, |
| 562 | "updated_at": comment.updated_at, |
| 563 | }) |
| 564 | } |
| 565 | |
| 566 | #[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/comments")] |
| 567 | async fn issue_comments(cx: &Cx) -> topcoat::Result<Response> { |
| 568 | let state = context::<AppState>(cx); |
| 569 | let ctx = match read_ctx(cx).await { |
| 570 | Ok(ctx) => ctx, |
| 571 | Err(res) => return Ok(*res), |
| 572 | }; |
| 573 | let result: Result<Response, Refusal> = async { |
| 574 | let issue = issue_row(state, &ctx.repo, index(cx)).await?; |
| 575 | let all = state |
| 576 | .store |
| 577 | .list_comments(&issue.id) |
| 578 | .await |
| 579 | .map_err(internal)?; |
| 580 | let numbered: Vec<(usize, Comment)> = all.into_iter().enumerate().collect(); |
| 581 | let pg = paging(cx, DEFAULT_PAGE); |
| 582 | let (page, total) = slice(numbered, &pg); |
| 583 | let authors = names( |
| 584 | state, |
| 585 | page.iter().map(|(_, c)| c.author_id.clone()).collect(), |
| 586 | ) |
| 587 | .await?; |
| 588 | let items = page |
| 589 | .iter() |
| 590 | .map(|(pos, c)| comment_json(&ctx, issue.number, *pos, c, &authors)) |
| 591 | .collect(); |
| 592 | Ok(page_response(cx, items, total, &pg)) |
| 593 | } |
| 594 | .await; |
| 595 | Ok(result.unwrap_or_else(|res| *res)) |
| 596 | } |
| 597 | |
| 598 | |
| 599 | async fn reactions_json( |
| 600 | state: &AppState, |
| 601 | ctx: &Ctx, |
| 602 | kind: ReactionTarget, |
| 603 | target_id: &str, |
| 604 | created_at: &str, |
| 605 | ) -> Result<Vec<Value>, Refusal> { |
| 606 | let map = state |
| 607 | .store |
| 608 | .reactions_for(kind, &[target_id.to_owned()], None) |
| 609 | .await |
| 610 | .map_err(internal)?; |
| 611 | let mut out = Vec::new(); |
| 612 | for summary in map.get(target_id).into_iter().flatten() { |
| 613 | for username in &summary.users { |
| 614 | let id = match state.store.user_by_username(username).await { |
| 615 | Ok(Some(user)) => user.id, |
| 616 | _ => continue, |
| 617 | }; |
| 618 | out.push(json!({ |
| 619 | "user": user_json(&ctx.base, &id, username), |
| 620 | "reaction": summary.reaction.name(), |
| 621 | "created_at": created_at, |
| 622 | })); |
| 623 | } |
| 624 | } |
| 625 | Ok(out) |
| 626 | } |
| 627 | |
| 628 | #[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/reactions")] |
| 629 | async fn issue_reactions(cx: &Cx) -> topcoat::Result<Response> { |
| 630 | let state = context::<AppState>(cx); |
| 631 | let ctx = match read_ctx(cx).await { |
| 632 | Ok(ctx) => ctx, |
| 633 | Err(res) => return Ok(*res), |
| 634 | }; |
| 635 | let result: Result<Response, Refusal> = async { |
| 636 | let issue = issue_row(state, &ctx.repo, index(cx)).await?; |
| 637 | let all = reactions_json( |
| 638 | state, |
| 639 | &ctx, |
| 640 | ReactionTarget::Issue, |
| 641 | &issue.id, |
| 642 | &issue.created_at, |
| 643 | ) |
| 644 | .await?; |
| 645 | let pg = paging(cx, 1000); |
| 646 | let (page, total) = slice(all, &pg); |
| 647 | Ok(page_response(cx, page, total, &pg)) |
| 648 | } |
| 649 | .await; |
| 650 | Ok(result.unwrap_or_else(|res| *res)) |
| 651 | } |
| 652 | |
| 653 | #[route(GET "/api/v1/repos/{owner}/{repo}/issues/comments/{id}/reactions")] |
| 654 | async fn comment_reactions(cx: &Cx) -> topcoat::Result<Response> { |
| 655 | let state = context::<AppState>(cx); |
| 656 | let ctx = match read_ctx(cx).await { |
| 657 | Ok(ctx) => ctx, |
| 658 | Err(res) => return Ok(*res), |
| 659 | }; |
| 660 | let result: Result<Response, Refusal> = async { |
| 661 | let id: i64 = id(cx).parse().map_err(|_| bad("invalid comment id"))?; |
| 662 | let (number, position) = |
| 663 | split_comment_id(id).ok_or_else(|| not_found("comment not found"))?; |
| 664 | let issue = issue_row(state, &ctx.repo, &number.to_string()).await?; |
| 665 | let all = state |
| 666 | .store |
| 667 | .list_comments(&issue.id) |
| 668 | .await |
| 669 | .map_err(internal)?; |
| 670 | let comment = all |
| 671 | .get(position) |
| 672 | .ok_or_else(|| not_found("comment not found"))?; |
| 673 | let items = reactions_json( |
| 674 | state, |
| 675 | &ctx, |
| 676 | ReactionTarget::Comment, |
| 677 | &comment.id, |
| 678 | &comment.created_at, |
| 679 | ) |
| 680 | .await?; |
| 681 | let pg = paging(cx, 1000); |
| 682 | let (page, total) = slice(items, &pg); |
| 683 | Ok(page_response(cx, page, total, &pg)) |
| 684 | } |
| 685 | .await; |
| 686 | Ok(result.unwrap_or_else(|res| *res)) |
| 687 | } |
| 688 | |
| 689 | fn pr_branch( |
| 690 | ctx: &Ctx, |
| 691 | label_owner: &str, |
| 692 | repo: Option<&CoreRepo>, |
| 693 | branch: &str, |
| 694 | sha: &str, |
| 695 | ) -> Value { |
| 696 | json!({ |
| 697 | "label": format!("{label_owner}:{branch}"), |
| 698 | "ref": branch, |
| 699 | "sha": sha, |
| 700 | "repo_id": repo.map(|r| numeric_id(&r.id)), |
| 701 | "repo": repo.map(|r| json!({ |
| 702 | "id": numeric_id(&r.id), |
| 703 | "owner": user_json(&ctx.base, &r.owner_id, &r.owner_name), |
| 704 | "name": r.name, |
| 705 | "full_name": format!("{}/{}", r.owner_name, r.name), |
| 706 | "private": r.visibility == Visibility::Private, |
| 707 | "html_url": format!("{}/{}/{}", ctx.base, r.owner_name, r.name), |
| 708 | "clone_url": format!("{}/{}/{}.git", ctx.base, r.owner_name, r.name), |
| 709 | "default_branch": r.default_branch, |
| 710 | })), |
| 711 | }) |
| 712 | } |
| 713 | |
| 714 | async fn pull_json( |
| 715 | state: &AppState, |
| 716 | ctx: &Ctx, |
| 717 | item: &IssueListItem, |
| 718 | pull: &PullRequest, |
| 719 | milestones: &HashMap<String, Milestone>, |
| 720 | ) -> Result<Value, Refusal> { |
| 721 | let mut value = issue_core(state, ctx, item, milestones, true).await?; |
| 722 | let head_repo = match &pull.head_repo_id { |
| 723 | Some(id) if *id == ctx.repo.id => Some(ctx.repo.clone()), |
| 724 | Some(id) => state.store.repo_by_id(id).await.map_err(internal)?, |
| 725 | None => None, |
| 726 | }; |
| 727 | |
| 728 | let head_repo = match head_repo { |
| 729 | Some(r) if r.id == ctx.repo.id || r.visibility == Visibility::Public => Some(r), |
| 730 | _ => None, |
| 731 | }; |
| 732 | let head_owner = head_repo |
| 733 | .as_ref() |
| 734 | .map_or(ctx.repo.owner_name.as_str(), |r| r.owner_name.as_str()); |
| 735 | let merged_by = match &pull.merged_by { |
| 736 | Some(id) => state |
| 737 | .store |
| 738 | .usernames_by_ids(std::slice::from_ref(id)) |
| 739 | .await |
| 740 | .map_err(internal)? |
| 741 | .get(id) |
| 742 | .map(|(name, _)| user_json(&ctx.base, id, name)), |
| 743 | None => None, |
| 744 | }; |
| 745 | let html = format!( |
| 746 | "{}/{}/{}/pulls/{}", |
| 747 | ctx.base, ctx.repo.owner_name, ctx.repo.name, pull.issue.number |
| 748 | ); |
| 749 | let obj = value.as_object_mut().expect("object"); |
| 750 | obj.insert("merged".into(), json!(pull.merged_at.is_some())); |
| 751 | obj.insert("merged_at".into(), json!(pull.merged_at)); |
| 752 | obj.insert("merged_by".into(), json!(merged_by)); |
| 753 | obj.insert("merge_commit_sha".into(), json!(pull.merge_commit)); |
| 754 | obj.insert("merged_commit_id".into(), json!(pull.merge_commit)); |
| 755 | obj.insert("merge_base".into(), json!(pull.merge_base)); |
| 756 | obj.insert( |
| 757 | "mergeable".into(), |
| 758 | json!(matches!( |
| 759 | pull.mergeable, |
| 760 | forge_core::pulls::Mergeable::Clean |
| 761 | )), |
| 762 | ); |
| 763 | obj.insert("draft".into(), json!(pull.draft)); |
| 764 | obj.insert("allow_maintainer_edit".into(), json!(false)); |
| 765 | obj.insert("diff_url".into(), json!(format!("{html}.diff"))); |
| 766 | obj.insert("patch_url".into(), json!(format!("{html}.patch"))); |
| 767 | obj.insert("flow".into(), json!(0)); |
| 768 | obj.insert( |
| 769 | "base".into(), |
| 770 | pr_branch( |
| 771 | ctx, |
| 772 | &ctx.repo.owner_name, |
| 773 | Some(&ctx.repo), |
| 774 | &pull.base_branch, |
| 775 | &pull.base_oid, |
| 776 | ), |
| 777 | ); |
| 778 | obj.insert( |
| 779 | "head".into(), |
| 780 | pr_branch( |
| 781 | ctx, |
| 782 | head_owner, |
| 783 | head_repo.as_ref(), |
| 784 | &pull.head_branch, |
| 785 | &pull.head_oid, |
| 786 | ), |
| 787 | ); |
| 788 | obj.insert( |
| 789 | "pull_request".into(), |
| 790 | json!({"merged": pull.merged_at.is_some(), "merged_at": pull.merged_at, "html_url": html}), |
| 791 | ); |
| 792 | Ok(value) |
| 793 | } |
| 794 | |
| 795 | #[route(GET "/api/v1/repos/{owner}/{repo}/pulls")] |
| 796 | async fn list_pulls_route(cx: &Cx) -> topcoat::Result<Response> { |
| 797 | let state = context::<AppState>(cx); |
| 798 | let ctx = match read_ctx(cx).await { |
| 799 | Ok(ctx) => ctx, |
| 800 | Err(res) => return Ok(*res), |
| 801 | }; |
| 802 | let result: Result<Response, Refusal> = async { |
| 803 | let pg = paging(cx, DEFAULT_PAGE); |
| 804 | let filter = filter_of(cx, &pg)?; |
| 805 | let (rows, total) = state |
| 806 | .store |
| 807 | .list_pulls(&ctx.repo.id, &filter) |
| 808 | .await |
| 809 | .map_err(internal)?; |
| 810 | let milestones = milestone_map(state, &ctx.repo).await?; |
| 811 | let mut out = Vec::with_capacity(rows.len()); |
| 812 | for item in &rows { |
| 813 | let Some(pull) = state |
| 814 | .store |
| 815 | .pull_by_number(&ctx.repo.id, item.issue.number) |
| 816 | .await |
| 817 | .map_err(internal)? |
| 818 | else { |
| 819 | continue; |
| 820 | }; |
| 821 | out.push(pull_json(state, &ctx, item, &pull, &milestones).await?); |
| 822 | } |
| 823 | Ok(page_response(cx, out, total as usize, &pg)) |
| 824 | } |
| 825 | .await; |
| 826 | Ok(result.unwrap_or_else(|res| *res)) |
| 827 | } |
| 828 | |
| 829 | |
| 830 | |
| 831 | |
| 832 | fn review_state(review: &Review) -> &'static str { |
| 833 | let effective = if review.state == ReviewState::Dismissed { |
| 834 | review.dismissed_from.unwrap_or(ReviewState::Commented) |
| 835 | } else { |
| 836 | review.state |
| 837 | }; |
| 838 | match effective { |
| 839 | ReviewState::Approved => "APPROVED", |
| 840 | ReviewState::ChangesRequested => "CHANGES_REQUESTED", |
| 841 | ReviewState::Pending => "PENDING", |
| 842 | ReviewState::Commented | ReviewState::Dismissed => "COMMENTED", |
| 843 | } |
| 844 | } |
| 845 | |
| 846 | fn review_json(ctx: &Ctx, number: i64, review: &Review, comment_count: usize) -> Value { |
| 847 | let html = format!( |
| 848 | "{}/{}/{}/pulls/{number}", |
| 849 | ctx.base, ctx.repo.owner_name, ctx.repo.name |
| 850 | ); |
| 851 | json!({ |
| 852 | "id": numeric_id(&review.id), |
| 853 | "user": user_json(&ctx.base, &review.author_id, &review.author_name), |
| 854 | "team": null, |
| 855 | "state": review_state(review), |
| 856 | "body": review.body, |
| 857 | "commit_id": review.commit_oid, |
| 858 | "stale": false, |
| 859 | "official": matches!(review_state(review), "APPROVED" | "CHANGES_REQUESTED"), |
| 860 | "dismissed": review.state == ReviewState::Dismissed, |
| 861 | "comments_count": comment_count, |
| 862 | "submitted_at": review.submitted_at.clone().unwrap_or_else(|| review.created_at.clone()), |
| 863 | "updated_at": review.submitted_at.clone().unwrap_or_else(|| review.created_at.clone()), |
| 864 | "html_url": format!("{html}#{}", numeric_id(&review.id)), |
| 865 | "pull_request_url": html, |
| 866 | }) |
| 867 | } |
| 868 | |
| 869 | |
| 870 | async fn review_comments(state: &AppState, issue_id: &str) -> Result<Vec<ReviewComment>, Refusal> { |
| 871 | let threads = state |
| 872 | .store |
| 873 | .review_threads(issue_id, None) |
| 874 | .await |
| 875 | .map_err(internal)?; |
| 876 | let mut all: Vec<ReviewComment> = threads |
| 877 | .into_iter() |
| 878 | .flat_map(|t| std::iter::once(t.root).chain(t.replies)) |
| 879 | .filter(|c| !c.pending) |
| 880 | .collect(); |
| 881 | all.sort_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id))); |
| 882 | Ok(all) |
| 883 | } |
| 884 | |
| 885 | #[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews")] |
| 886 | async fn pull_reviews(cx: &Cx) -> topcoat::Result<Response> { |
| 887 | let state = context::<AppState>(cx); |
| 888 | let ctx = match read_ctx(cx).await { |
| 889 | Ok(ctx) => ctx, |
| 890 | Err(res) => return Ok(*res), |
| 891 | }; |
| 892 | let result: Result<Response, Refusal> = async { |
| 893 | let issue = pull_issue(state, &ctx.repo, index(cx)).await?; |
| 894 | let reviews = state |
| 895 | .store |
| 896 | .list_reviews(&issue.id) |
| 897 | .await |
| 898 | .map_err(internal)?; |
| 899 | let comments = review_comments(state, &issue.id).await?; |
| 900 | let pg = paging(cx, DEFAULT_PAGE); |
| 901 | let (page, total) = slice(reviews, &pg); |
| 902 | let items = page |
| 903 | .iter() |
| 904 | .map(|r| { |
| 905 | let count = comments.iter().filter(|c| c.review_id == r.id).count(); |
| 906 | review_json(&ctx, issue.number, r, count) |
| 907 | }) |
| 908 | .collect(); |
| 909 | Ok(page_response(cx, items, total, &pg)) |
| 910 | } |
| 911 | .await; |
| 912 | Ok(result.unwrap_or_else(|res| *res)) |
| 913 | } |
| 914 | |
| 915 | |
| 916 | async fn pull_issue( |
| 917 | state: &AppState, |
| 918 | repo: &CoreRepo, |
| 919 | raw: &str, |
| 920 | ) -> Result<forge_core::issues::Issue, Refusal> { |
| 921 | let number: i64 = raw.parse().map_err(|_| bad("invalid pull request index"))?; |
| 922 | match state.store.pull_by_number(&repo.id, number).await { |
| 923 | Ok(Some(pull)) => Ok(pull.issue), |
| 924 | Ok(None) => Err(not_found("pull request not found")), |
| 925 | Err(e) => Err(internal(e)), |
| 926 | } |
| 927 | } |
| 928 | |
| 929 | fn review_comment_json(ctx: &Ctx, number: i64, c: &ReviewComment) -> Value { |
| 930 | let html = format!( |
| 931 | "{}/{}/{}/pulls/{number}", |
| 932 | ctx.base, ctx.repo.owner_name, ctx.repo.name |
| 933 | ); |
| 934 | let (line, old_line) = match c.side { |
| 935 | Side::New => (c.line, 0), |
| 936 | Side::Old => (0, c.line), |
| 937 | }; |
| 938 | json!({ |
| 939 | "id": numeric_id(&c.id), |
| 940 | "body": c.body, |
| 941 | "user": user_json(&ctx.base, &c.author_id, &c.author_name), |
| 942 | "resolver": null, |
| 943 | "pull_request_review_id": numeric_id(&c.review_id), |
| 944 | "created_at": c.created_at, |
| 945 | "updated_at": c.updated_at, |
| 946 | "path": c.path, |
| 947 | "commit_id": c.commit_oid, |
| 948 | "original_commit_id": c.commit_oid, |
| 949 | "diff_hunk": c.diff_hunk, |
| 950 | "position": line, |
| 951 | "original_position": line, |
| 952 | "line_num": line, |
| 953 | "old_line_num": old_line, |
| 954 | "html_url": format!("{html}#{}", numeric_id(&c.id)), |
| 955 | "pull_request_url": html, |
| 956 | }) |
| 957 | } |
| 958 | |
| 959 | #[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews/{review_id}/comments")] |
| 960 | async fn pull_review_comments(cx: &Cx) -> topcoat::Result<Response> { |
| 961 | let state = context::<AppState>(cx); |
| 962 | let ctx = match read_ctx(cx).await { |
| 963 | Ok(ctx) => ctx, |
| 964 | Err(res) => return Ok(*res), |
| 965 | }; |
| 966 | let result: Result<Response, Refusal> = async { |
| 967 | let issue = pull_issue(state, &ctx.repo, index(cx)).await?; |
| 968 | let raw = review_id(cx); |
| 969 | let reviews = state |
| 970 | .store |
| 971 | .list_reviews(&issue.id) |
| 972 | .await |
| 973 | .map_err(internal)?; |
| 974 | let review = reviews |
| 975 | .iter() |
| 976 | .find(|r| r.id == raw || (is_numeric(raw) && raw.parse() == Ok(numeric_id(&r.id)))) |
| 977 | .ok_or_else(|| not_found("review not found"))?; |
| 978 | let own: Vec<ReviewComment> = review_comments(state, &issue.id) |
| 979 | .await? |
| 980 | .into_iter() |
| 981 | .filter(|c| c.review_id == review.id) |
| 982 | .collect(); |
| 983 | let items = own |
| 984 | .iter() |
| 985 | .map(|c| review_comment_json(&ctx, issue.number, c)) |
| 986 | .collect::<Vec<_>>(); |
| 987 | let total = items.len(); |
| 988 | |
| 989 | let pg = Paging { |
| 990 | page: 1, |
| 991 | limit: total.max(1), |
| 992 | }; |
| 993 | Ok(page_response(cx, items, total, &pg)) |
| 994 | } |
| 995 | .await; |
| 996 | Ok(result.unwrap_or_else(|res| *res)) |
| 997 | } |