| 1 | use serde_json::{Value, json}; |
| 2 | use session::{ApiResponse, Method, Request, Session}; |
| 3 | |
| 4 | use crate::cards::{CardTransport, DEFAULT_MT_REGION, SessionCardTransport, spaces_scope}; |
| 5 | use crate::error::{Error, Result}; |
| 6 | |
| 7 | const FORBIDDEN_STATUS: u16 = 403; |
| 8 | const RESULT_LIMIT: &str = "27"; |
| 9 | const RATING: &str = "g"; |
| 10 | const LANGUAGE: &str = "de-de"; |
| 11 | |
| 12 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 13 | pub struct Gif { |
| 14 | pub url: String, |
| 15 | pub preview_url: String, |
| 16 | pub title: String, |
| 17 | pub width: u32, |
| 18 | pub height: u32, |
| 19 | pub preview_width: u32, |
| 20 | pub preview_height: u32, |
| 21 | } |
| 22 | |
| 23 | pub struct Gifs<T: CardTransport = SessionCardTransport> { |
| 24 | transport: T, |
| 25 | url: String, |
| 26 | } |
| 27 | |
| 28 | impl Gifs<SessionCardTransport> { |
| 29 | pub fn new(session: &Session) -> Self { |
| 30 | Gifs::with_transport(SessionCardTransport::new(session), DEFAULT_MT_REGION) |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | impl<T: CardTransport> Gifs<T> { |
| 35 | pub fn with_transport(transport: T, mt_region: &str) -> Self { |
| 36 | Gifs { |
| 37 | transport, |
| 38 | url: format!( |
| 39 | "https://teams.cloud.microsoft/api/mt/{mt_region}/beta/commands/com.microsoft.teamspace.inputextension.giphy/execute?version=1.0" |
| 40 | ), |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | /// An empty query returns the trending GIFs. |
| 45 | pub async fn search(&self, query: &str) -> Result<Vec<Gif>> { |
| 46 | let mut request = Request::with_body(Method::Post, &self.url, search_body(query)); |
| 47 | request.headers = vec![( |
| 48 | "content-type".to_owned(), |
| 49 | "application/json;charset=UTF-8".to_owned(), |
| 50 | )]; |
| 51 | let answer = self.transport.send(request, spaces_scope()).await?; |
| 52 | parse_answer(answer, &self.url) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | fn search_body(query: &str) -> Value { |
| 57 | json!([ |
| 58 | {"name": "query", "value": query}, |
| 59 | {"name": "rating", "value": RATING}, |
| 60 | {"name": "limit", "value": RESULT_LIMIT}, |
| 61 | {"name": "lang", "value": LANGUAGE}, |
| 62 | ]) |
| 63 | } |
| 64 | |
| 65 | fn parse_answer(answer: ApiResponse, url: &str) -> Result<Vec<Gif>> { |
| 66 | if answer.status == FORBIDDEN_STATUS { |
| 67 | return Err(Error::GifsDisabled); |
| 68 | } |
| 69 | if !answer.is_success() { |
| 70 | return Err(Error::Session(session::Error::api( |
| 71 | answer.status, |
| 72 | url, |
| 73 | answer.body, |
| 74 | ))); |
| 75 | } |
| 76 | Ok(parse_gifs(&answer.body)) |
| 77 | } |
| 78 | |
| 79 | pub fn parse_gifs(body: &Value) -> Vec<Gif> { |
| 80 | body.pointer("/result/0/result") |
| 81 | .and_then(Value::as_array) |
| 82 | .into_iter() |
| 83 | .flatten() |
| 84 | .filter_map(parse_gif) |
| 85 | .collect() |
| 86 | } |
| 87 | |
| 88 | fn parse_gif(entry: &Value) -> Option<Gif> { |
| 89 | let field = |name: &str| { |
| 90 | entry |
| 91 | .get("fieldValues")? |
| 92 | .as_array()? |
| 93 | .iter() |
| 94 | .find(|field| field.get("fieldName").and_then(Value::as_str) == Some(name))? |
| 95 | .get("fieldValue")? |
| 96 | .as_str() |
| 97 | }; |
| 98 | let number = |name: &str| field(name)?.parse::<u32>().ok().filter(|size| *size > 0); |
| 99 | let url = entry.get("composeValue")?.as_str()?.to_owned(); |
| 100 | Some(Gif { |
| 101 | preview_url: field("previewImageFW") |
| 102 | .or_else(|| field("previewImage")) |
| 103 | .map_or_else(|| url.clone(), str::to_owned), |
| 104 | title: field("title").unwrap_or_default().to_owned(), |
| 105 | width: number("width")?, |
| 106 | height: number("height")?, |
| 107 | preview_width: number("previewImageFWWidth").unwrap_or(1), |
| 108 | preview_height: number("previewImageFWHeight").unwrap_or(1), |
| 109 | url, |
| 110 | }) |
| 111 | } |
| 112 | |
| 113 | #[cfg(test)] |
| 114 | mod tests { |
| 115 | use std::sync::Mutex; |
| 116 | |
| 117 | use session::Scope; |
| 118 | |
| 119 | use super::*; |
| 120 | |
| 121 | struct Canned { |
| 122 | status: u16, |
| 123 | body: Value, |
| 124 | sent: Mutex<Vec<(Request, Scope)>>, |
| 125 | } |
| 126 | |
| 127 | impl CardTransport for Canned { |
| 128 | async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> { |
| 129 | self.sent.lock().unwrap().push((request, scope)); |
| 130 | Ok(ApiResponse { |
| 131 | status: self.status, |
| 132 | body: self.body.clone(), |
| 133 | retry_after: None, |
| 134 | }) |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | fn gifs(status: u16, body: Value) -> Gifs<Canned> { |
| 139 | Gifs::with_transport( |
| 140 | Canned { |
| 141 | status, |
| 142 | body, |
| 143 | sent: Mutex::new(Vec::new()), |
| 144 | }, |
| 145 | "emea", |
| 146 | ) |
| 147 | } |
| 148 | |
| 149 | fn fixture() -> Value { |
| 150 | serde_json::from_str(include_str!("../tests/fixtures/giphy_search.json")).unwrap() |
| 151 | } |
| 152 | |
| 153 | #[tokio::test] |
| 154 | async fn search_posts_the_query_to_the_giphy_command() { |
| 155 | let gifs = gifs(200, fixture()); |
| 156 | gifs.search("thumbs up").await.unwrap(); |
| 157 | let sent = gifs.transport.sent.lock().unwrap(); |
| 158 | let (request, scope) = &sent[0]; |
| 159 | assert_eq!(request.method, Method::Post); |
| 160 | assert_eq!( |
| 161 | request.url, |
| 162 | "https://teams.cloud.microsoft/api/mt/emea/beta/commands/com.microsoft.teamspace.inputextension.giphy/execute?version=1.0" |
| 163 | ); |
| 164 | assert_eq!(request.body.as_ref().unwrap()[0]["value"], "thumbs up"); |
| 165 | assert_eq!(request.body.as_ref().unwrap()[2]["value"], "27"); |
| 166 | assert_eq!(*scope, spaces_scope()); |
| 167 | } |
| 168 | |
| 169 | #[tokio::test] |
| 170 | async fn results_carry_urls_titles_and_sizes() { |
| 171 | let found = gifs(200, fixture()).search("x").await.unwrap(); |
| 172 | assert_eq!(found.len(), 2); |
| 173 | assert_eq!(found[0].title, "Baby Thank You GIF"); |
| 174 | assert!(found[0].url.ends_with("/giphy.gif")); |
| 175 | assert!(found[0].preview_url.ends_with("/200w.gif")); |
| 176 | assert_eq!((found[0].width, found[0].height), (358, 360)); |
| 177 | assert_eq!( |
| 178 | (found[0].preview_width, found[0].preview_height), |
| 179 | (200, 202) |
| 180 | ); |
| 181 | } |
| 182 | |
| 183 | #[tokio::test] |
| 184 | async fn forbidden_means_disabled() { |
| 185 | let outcome = gifs(403, json!({"errorCode": "Forbidden"})) |
| 186 | .search("") |
| 187 | .await; |
| 188 | assert!(matches!(outcome, Err(Error::GifsDisabled))); |
| 189 | } |
| 190 | |
| 191 | #[tokio::test] |
| 192 | async fn other_failures_are_api_errors() { |
| 193 | let outcome = gifs(500, Value::Null).search("").await; |
| 194 | assert!(matches!( |
| 195 | outcome, |
| 196 | Err(Error::Session(session::Error::Api { status: 500, .. })) |
| 197 | )); |
| 198 | } |
| 199 | |
| 200 | #[test] |
| 201 | fn entries_without_a_size_are_skipped() { |
| 202 | let body = json!({"result": [{"result": [{"composeValue": "https://media0.giphy.com/a.gif", "fieldValues": []}]}]}); |
| 203 | assert!(parse_gifs(&body).is_empty()); |
| 204 | } |
| 205 | } |