zulip.rs 15 KB

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