zulip.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. use crate::db::notifications::add_metadata;
  2. use crate::db::notifications::{self, delete_ping, move_indices, record_ping, Identifier};
  3. use crate::github::{self, GithubClient};
  4. use crate::handlers::Context;
  5. use anyhow::Context as _;
  6. use std::convert::TryInto;
  7. use std::env;
  8. #[derive(Debug, serde::Deserialize)]
  9. pub struct Request {
  10. /// Markdown body of the sent message.
  11. data: String,
  12. /// Metadata about this request.
  13. message: Message,
  14. /// Authentication token. The same for all Zulip messages.
  15. token: String,
  16. }
  17. #[derive(Debug, serde::Deserialize)]
  18. struct Message {
  19. sender_id: usize,
  20. sender_short_name: String,
  21. sender_full_name: String,
  22. }
  23. #[derive(serde::Serialize, serde::Deserialize)]
  24. struct Response<'a> {
  25. content: &'a str,
  26. }
  27. pub async fn to_github_id(client: &GithubClient, zulip_id: usize) -> anyhow::Result<Option<i64>> {
  28. let url = format!("{}/zulip-map.json", rust_team_data::v1::BASE_URL);
  29. let map: rust_team_data::v1::ZulipMapping = client
  30. .json(client.raw().get(&url))
  31. .await
  32. .context("could not get team data")?;
  33. Ok(map.users.get(&zulip_id).map(|v| *v as i64))
  34. }
  35. pub async fn to_zulip_id(client: &GithubClient, github_id: i64) -> anyhow::Result<Option<usize>> {
  36. let url = format!("{}/zulip-map.json", rust_team_data::v1::BASE_URL);
  37. let map: rust_team_data::v1::ZulipMapping = client
  38. .json(client.raw().get(&url))
  39. .await
  40. .context("could not get team data")?;
  41. Ok(map
  42. .users
  43. .iter()
  44. .find(|(_, github)| **github == github_id as usize)
  45. .map(|v| *v.0))
  46. }
  47. pub async fn respond(ctx: &Context, req: Request) -> String {
  48. let expected_token = std::env::var("ZULIP_TOKEN").expect("`ZULIP_TOKEN` set for authorization");
  49. if !openssl::memcmp::eq(req.token.as_bytes(), expected_token.as_bytes()) {
  50. return serde_json::to_string(&Response {
  51. content: "Invalid authorization.",
  52. })
  53. .unwrap();
  54. }
  55. log::trace!("zulip hook: {:?}", req);
  56. let gh_id = match to_github_id(&ctx.github, req.message.sender_id).await {
  57. Ok(Some(gh_id)) => gh_id,
  58. Ok(None) => {
  59. return serde_json::to_string(&Response {
  60. content: &format!(
  61. "Unknown Zulip user. Please add `zulip-id = {}` to your file in rust-lang/team.",
  62. req.message.sender_id),
  63. })
  64. .unwrap();
  65. }
  66. Err(e) => {
  67. return serde_json::to_string(&Response {
  68. content: &format!("Failed to query team API: {:?}", e),
  69. })
  70. .unwrap();
  71. }
  72. };
  73. handle_command(ctx, gh_id, &req.data, &req.message).await
  74. }
  75. fn handle_command<'a>(
  76. ctx: &'a Context,
  77. gh_id: i64,
  78. words: &'a str,
  79. message_data: &'a Message,
  80. ) -> std::pin::Pin<Box<dyn std::future::Future<Output = String> + Send + 'a>> {
  81. Box::pin(async move {
  82. let mut words = words.split_whitespace();
  83. match words.next() {
  84. Some("as") => match execute_for_other_user(&ctx, gh_id, words, message_data).await {
  85. Ok(r) => r,
  86. Err(e) => serde_json::to_string(&Response {
  87. content: &format!(
  88. "Failed to parse; expected `as <username> <command...>`: {:?}.",
  89. e
  90. ),
  91. })
  92. .unwrap(),
  93. },
  94. Some("acknowledge") => match acknowledge(&ctx, gh_id, words).await {
  95. Ok(r) => r,
  96. Err(e) => serde_json::to_string(&Response {
  97. content: &format!(
  98. "Failed to parse acknowledgement, expected `acknowledge <identifier>`: {:?}.",
  99. e
  100. ),
  101. })
  102. .unwrap(),
  103. },
  104. Some("add") => match add_notification(&ctx, gh_id, words).await {
  105. Ok(r) => r,
  106. Err(e) => serde_json::to_string(&Response {
  107. content: &format!(
  108. "Failed to parse description addition, expected `add <url> <description (multiple words)>`: {:?}.",
  109. e
  110. ),
  111. })
  112. .unwrap(),
  113. },
  114. Some("move") => match move_notification(&ctx, gh_id, words).await {
  115. Ok(r) => r,
  116. Err(e) => serde_json::to_string(&Response {
  117. content: &format!(
  118. "Failed to parse movement, expected `move <from> <to>`: {:?}.",
  119. e
  120. ),
  121. })
  122. .unwrap(),
  123. },
  124. Some("meta") => match add_meta_notification(&ctx, gh_id, words).await {
  125. Ok(r) => r,
  126. Err(e) => serde_json::to_string(&Response {
  127. content: &format!(
  128. "Failed to parse movement, expected `move <idx> <meta...>`: {:?}.",
  129. e
  130. ),
  131. })
  132. .unwrap(),
  133. },
  134. _ => serde_json::to_string(&Response {
  135. content: "Unknown command.",
  136. })
  137. .unwrap(),
  138. }
  139. })
  140. }
  141. // This does two things:
  142. // * execute the command for the other user
  143. // * tell the user executed for that a command was run as them by the user
  144. // given.
  145. async fn execute_for_other_user(
  146. ctx: &Context,
  147. _original_gh_id: i64,
  148. mut words: impl Iterator<Item = &str>,
  149. message_data: &Message,
  150. ) -> anyhow::Result<String> {
  151. // username is a GitHub username, not a Zulip username
  152. let username = match words.next() {
  153. Some(username) => username,
  154. None => anyhow::bail!("no username provided"),
  155. };
  156. let user_id = match (github::User {
  157. login: username.to_owned(),
  158. id: None,
  159. })
  160. .get_id(&ctx.github)
  161. .await
  162. .context("getting ID of github user")?
  163. {
  164. Some(id) => id.try_into().unwrap(),
  165. None => {
  166. return Ok(serde_json::to_string(&Response {
  167. content: "Can only authorize for other GitHub users.",
  168. })
  169. .unwrap());
  170. }
  171. };
  172. let mut command = words.fold(String::new(), |mut acc, piece| {
  173. acc.push_str(piece);
  174. acc.push(' ');
  175. acc
  176. });
  177. let command = if command.is_empty() {
  178. anyhow::bail!("no command provided")
  179. } else {
  180. assert_eq!(command.pop(), Some(' ')); // pop trailing space
  181. command
  182. };
  183. let bot_email = "triage-rust-lang-bot@zulipchat.com"; // FIXME: don't hardcode
  184. let bot_api_token = env::var("ZULIP_API_TOKEN").expect("ZULIP_API_TOKEN");
  185. let members = ctx
  186. .github
  187. .raw()
  188. .get("https://rust-lang.zulipchat.com/api/v1/users")
  189. .basic_auth(bot_email, Some(&bot_api_token))
  190. .send()
  191. .await;
  192. let members = match members {
  193. Ok(members) => members,
  194. Err(e) => {
  195. return Ok(serde_json::to_string(&Response {
  196. content: &format!("Failed to get list of zulip users: {:?}.", e),
  197. })
  198. .unwrap());
  199. }
  200. };
  201. let members = members.json::<Vec<Member>>().await;
  202. let members = match members {
  203. Ok(members) => members,
  204. Err(e) => {
  205. return Ok(serde_json::to_string(&Response {
  206. content: &format!("Failed to get list of zulip users: {:?}.", e),
  207. })
  208. .unwrap());
  209. }
  210. };
  211. // Map GitHub `user_id` to `zulip_user_id`.
  212. let zulip_user_id = match to_github_id(&ctx.github, user_id).await {
  213. Ok(Some(id)) => id,
  214. Ok(None) => {
  215. return Ok(serde_json::to_string(&Response {
  216. content: &format!("Could not find GitHub ID for Zulip ID: {}", user_id),
  217. })
  218. .unwrap());
  219. }
  220. Err(e) => {
  221. return Ok(serde_json::to_string(&Response {
  222. content: &format!("Could not find Zulip ID for github id {}: {:?}", user_id, e),
  223. })
  224. .unwrap());
  225. }
  226. };
  227. let user_email = match members.iter().find(|m| m.user_id == zulip_user_id) {
  228. Some(m) => &m.email,
  229. None => {
  230. return Ok(serde_json::to_string(&Response {
  231. content: &format!("Could not find Zulip user email."),
  232. })
  233. .unwrap());
  234. }
  235. };
  236. let output = handle_command(ctx, user_id as i64, &command, message_data).await;
  237. let output_msg: Response = serde_json::from_str(&output).expect("result should always be JSON");
  238. let output_msg = output_msg.content;
  239. // At this point, the command has been run (FIXME: though it may have
  240. // errored, it's hard to determine that currently, so we'll just give the
  241. // output fromt he command as well as the command itself).
  242. let message = format!(
  243. "{} ({}) ran `{}` with output `{}` as you.",
  244. message_data.sender_full_name, message_data.sender_short_name, command, output_msg
  245. );
  246. let res = ctx
  247. .github
  248. .raw()
  249. .post("https://rust-lang.zulipchat.com/api/v1/messages")
  250. .basic_auth(bot_email, Some(&bot_api_token))
  251. .form(&MessageApiRequest {
  252. type_: "private",
  253. to: &user_email,
  254. content: &message,
  255. })
  256. .send()
  257. .await;
  258. match res {
  259. Ok(resp) => {
  260. if !resp.status().is_success() {
  261. log::error!(
  262. "Failed to notify real user about command: response: {:?}",
  263. resp
  264. );
  265. }
  266. }
  267. Err(err) => {
  268. log::error!("Failed to notify real user about command: {:?}", err);
  269. }
  270. }
  271. Ok(output)
  272. }
  273. #[derive(serde::Deserialize)]
  274. struct Member {
  275. email: String,
  276. user_id: i64,
  277. }
  278. #[derive(serde::Serialize)]
  279. struct MessageApiRequest<'a> {
  280. #[serde(rename = "type")]
  281. type_: &'a str,
  282. to: &'a str,
  283. content: &'a str,
  284. }
  285. async fn acknowledge(
  286. ctx: &Context,
  287. gh_id: i64,
  288. mut words: impl Iterator<Item = &str>,
  289. ) -> anyhow::Result<String> {
  290. let url = match words.next() {
  291. Some(url) => {
  292. if words.next().is_some() {
  293. anyhow::bail!("too many words");
  294. }
  295. url
  296. }
  297. None => anyhow::bail!("not enough words"),
  298. };
  299. let ident = if let Ok(number) = url.parse::<usize>() {
  300. Identifier::Index(
  301. std::num::NonZeroUsize::new(number)
  302. .ok_or_else(|| anyhow::anyhow!("index must be at least 1"))?,
  303. )
  304. } else {
  305. Identifier::Url(url)
  306. };
  307. match delete_ping(
  308. &mut Context::make_db_client(&ctx.github.raw()).await?,
  309. gh_id,
  310. ident,
  311. )
  312. .await
  313. {
  314. Ok(()) => Ok(serde_json::to_string(&Response {
  315. content: &format!("Acknowledged {}.", url),
  316. })
  317. .unwrap()),
  318. Err(e) => Ok(serde_json::to_string(&Response {
  319. content: &format!("Failed to acknowledge {}: {:?}.", url, e),
  320. })
  321. .unwrap()),
  322. }
  323. }
  324. async fn add_notification(
  325. ctx: &Context,
  326. gh_id: i64,
  327. mut words: impl Iterator<Item = &str>,
  328. ) -> anyhow::Result<String> {
  329. let url = match words.next() {
  330. Some(idx) => idx,
  331. None => anyhow::bail!("url not present"),
  332. };
  333. let mut description = words.fold(String::new(), |mut acc, piece| {
  334. acc.push_str(piece);
  335. acc.push(' ');
  336. acc
  337. });
  338. let description = if description.is_empty() {
  339. None
  340. } else {
  341. assert_eq!(description.pop(), Some(' ')); // pop trailing space
  342. Some(description)
  343. };
  344. match record_ping(
  345. &ctx.db,
  346. &notifications::Notification {
  347. user_id: gh_id,
  348. origin_url: url.to_owned(),
  349. origin_html: String::new(),
  350. short_description: description,
  351. time: chrono::Utc::now().into(),
  352. team_name: None,
  353. },
  354. )
  355. .await
  356. {
  357. Ok(()) => Ok(serde_json::to_string(&Response {
  358. content: "Created!",
  359. })
  360. .unwrap()),
  361. Err(e) => Ok(serde_json::to_string(&Response {
  362. content: &format!("Failed to create: {:?}", e),
  363. })
  364. .unwrap()),
  365. }
  366. }
  367. async fn add_meta_notification(
  368. ctx: &Context,
  369. gh_id: i64,
  370. mut words: impl Iterator<Item = &str>,
  371. ) -> anyhow::Result<String> {
  372. let idx = match words.next() {
  373. Some(idx) => idx,
  374. None => anyhow::bail!("idx not present"),
  375. };
  376. let idx = idx
  377. .parse::<usize>()
  378. .context("index")?
  379. .checked_sub(1)
  380. .ok_or_else(|| anyhow::anyhow!("1-based indexes"))?;
  381. let mut description = words.fold(String::new(), |mut acc, piece| {
  382. acc.push_str(piece);
  383. acc.push(' ');
  384. acc
  385. });
  386. let description = if description.is_empty() {
  387. None
  388. } else {
  389. assert_eq!(description.pop(), Some(' ')); // pop trailing space
  390. Some(description)
  391. };
  392. match add_metadata(
  393. &mut Context::make_db_client(&ctx.github.raw()).await?,
  394. gh_id,
  395. idx,
  396. description.as_deref(),
  397. )
  398. .await
  399. {
  400. Ok(()) => Ok(serde_json::to_string(&Response {
  401. content: "Added metadata!",
  402. })
  403. .unwrap()),
  404. Err(e) => Ok(serde_json::to_string(&Response {
  405. content: &format!("Failed to add: {:?}", e),
  406. })
  407. .unwrap()),
  408. }
  409. }
  410. async fn move_notification(
  411. ctx: &Context,
  412. gh_id: i64,
  413. mut words: impl Iterator<Item = &str>,
  414. ) -> anyhow::Result<String> {
  415. let from = match words.next() {
  416. Some(idx) => idx,
  417. None => anyhow::bail!("from idx not present"),
  418. };
  419. let to = match words.next() {
  420. Some(idx) => idx,
  421. None => anyhow::bail!("from idx not present"),
  422. };
  423. let from = from
  424. .parse::<usize>()
  425. .context("from index")?
  426. .checked_sub(1)
  427. .ok_or_else(|| anyhow::anyhow!("1-based indexes"))?;
  428. let to = to
  429. .parse::<usize>()
  430. .context("to index")?
  431. .checked_sub(1)
  432. .ok_or_else(|| anyhow::anyhow!("1-based indexes"))?;
  433. match move_indices(
  434. &mut Context::make_db_client(&ctx.github.raw()).await?,
  435. gh_id,
  436. from,
  437. to,
  438. )
  439. .await
  440. {
  441. Ok(()) => Ok(serde_json::to_string(&Response {
  442. // to 1-base indices
  443. content: &format!("Moved {} to {}.", from + 1, to + 1),
  444. })
  445. .unwrap()),
  446. Err(e) => Ok(serde_json::to_string(&Response {
  447. content: &format!("Failed to move: {:?}.", e),
  448. })
  449. .unwrap()),
  450. }
  451. }