Skip to main content

paprika_api/
api.rs

1use flate2::write::GzEncoder;
2use flate2::Compression;
3use hex;
4#[cfg(test)]
5use mockito;
6use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
7use reqwest::multipart;
8use serde::{Deserialize, Serialize};
9use sha2::{Digest, Sha256};
10use std::io::prelude::*;
11use std::str;
12use uuid::Uuid;
13
14#[cfg(not(test))]
15lazy_static! {
16    static ref URL: String = String::from("https://www.paprikaapp.com/api/v2");
17}
18
19#[cfg(test)]
20lazy_static! {
21    static ref URL: String = mockito::server_url();
22}
23
24pub enum QueryType {
25    GET,
26    POST,
27}
28
29#[derive(Debug, Serialize, Deserialize)]
30pub struct ApiResponse {
31    pub result: ApiResult,
32}
33
34#[derive(Debug, Serialize, Deserialize)]
35#[serde(untagged)] // this is what lets serde guess at how to deserialize ApiResponse properly
36pub enum ApiResult {
37    Token(Token),
38    Bool(bool),
39    Recipes(Vec<RecipeEntry>),
40    Categories(Vec<Category>),
41    Recipe(Recipe),
42}
43
44#[derive(Debug, Serialize, Deserialize)]
45pub struct Token {
46    pub token: String,
47}
48
49#[derive(Debug, Serialize, Deserialize)]
50pub struct RecipeEntry {
51    pub uid: String,
52    pub hash: String,
53}
54
55#[derive(Debug, Serialize, Deserialize)]
56pub struct Category {
57    pub uid: String,
58    pub order_flag: i32,
59    pub name: String,
60    pub parent_uid: Option<String>,
61}
62
63#[derive(Debug, Serialize, Deserialize, Hash, Default, Clone)]
64pub struct Recipe {
65    pub uid: String,
66    pub name: String,
67    pub ingredients: String,
68    pub directions: String,
69    pub description: String,
70    pub notes: String,
71    pub nutritional_info: String,
72    pub servings: String,
73    pub difficulty: String,
74    pub prep_time: String,
75    pub cook_time: String,
76    pub total_time: String,
77    pub source: String,
78    pub source_url: Option<String>,
79    pub image_url: Option<String>,
80    pub photo: Option<String>,
81    pub photo_hash: Option<String>,
82    pub photo_large: Option<String>,
83    pub scale: Option<String>,
84    pub hash: String,
85    pub categories: Vec<String>,
86    pub rating: i32,
87    pub in_trash: bool,
88    pub is_pinned: bool,
89    pub on_favorites: bool,
90    pub on_grocery_list: bool,
91    pub created: String,
92    pub photo_url: Option<String>,
93}
94
95impl Recipe {
96    fn update_hash(&mut self) {
97        let mut hasher = Sha256::new();
98
99        let serialized = serde_json::to_string(&self).unwrap();
100        hasher.update(serialized);
101
102        self.hash = hex::encode(hasher.finalize());
103    }
104
105    fn generate_uuid(&mut self) {
106        self.uid = Uuid::new_v4().to_string();
107    }
108}
109
110fn get_headers(token: &str) -> HeaderMap {
111    let mut headers = HeaderMap::new();
112
113    headers.append(
114        AUTHORIZATION,
115        HeaderValue::from_str(&(String::from("Bearer ") + token)).unwrap(),
116    );
117
118    headers
119}
120
121pub async fn simple_query(
122    token: &str,
123    endpoint: &str,
124    query_type: QueryType,
125    form_args: Option<Box<[(&str, &str)]>>,
126//) -> Result<ApiResult, serde_json::Error> {
127) -> Result<ApiResult, Box<dyn std::error::Error>> {
128    let client = reqwest::Client::new();
129    let mut builder: reqwest::RequestBuilder;
130
131    match query_type {
132        QueryType::GET => builder = client.get(format!("{}/{}/", &**URL, endpoint)),
133        QueryType::POST => builder = client.post(format!("{}/{}/", &**URL, endpoint)),
134    }
135
136    if let Some(t) = form_args {
137        builder = builder.form(&*t);
138    }
139
140    let resp_text = builder
141        .headers(get_headers(token))
142        .send()
143        .await?
144        //.expect("Request failed")
145        .text()
146        .await?;
147        //.expect("Failed to decode response as text");
148
149    let response: Result<ApiResponse, serde_json::Error> = serde_json::from_str(&resp_text);
150
151    match response {
152        Ok(r) => Ok(r.result),
153        Err(e) => Err(e.into()),
154    }
155}
156
157pub async fn login(email: &str, password: &str) -> Result<Token, Box<dyn std::error::Error>> {
158    let params = [("email", email), ("password", password)];
159
160    let token = simple_query("", "account/login", QueryType::POST, Some(Box::new(params))).await;
161
162    match token {
163        Ok(r) => match r {
164            ApiResult::Token(r) => Ok(r),
165            _ => Err("Invalid API response".into()),
166        },
167        Err(e) => Err(e),
168    }
169}
170
171pub async fn get_recipes(token: &str) -> Result<Vec<RecipeEntry>, Box<dyn std::error::Error>> {
172    let recipes = simple_query(token, "sync/recipes", QueryType::GET, None).await;
173
174    match recipes {
175        Ok(r) => match r {
176            ApiResult::Recipes(r) => Ok(r),
177            _ => Err("Invalid API response".into()),
178        },
179        Err(e) => Err(e),
180    }
181}
182
183pub async fn get_categories(token: &str) -> Result<Vec<Category>, Box<dyn std::error::Error>> {
184    let categories = simple_query(token, "sync/categories", QueryType::GET, None).await;
185
186    match categories {
187        Ok(r) => match r {
188            ApiResult::Categories(r) => Ok(r),
189            _ => Err("Invalid API response".into()),
190        },
191        Err(e) => Err(e),
192    }
193}
194
195pub async fn get_recipe_by_id(token: &str, id: &str) -> Result<Recipe, Box<dyn std::error::Error>> {
196    let endpoint = format!("{}/{}", "sync/recipe", &id);
197    let recipe = simple_query(token, &&endpoint, QueryType::GET, None).await;
198
199    match recipe {
200        Ok(r) => match r {
201            ApiResult::Recipe(r) => Ok(r),
202            _ => Err("Invalid API response".into()),
203        },
204        Err(e) => Err(e),
205    }
206}
207
208/// Uploads a new recipe (when uid == "") or updates an existing one (when uid exists in database already)
209/// #arguments
210/// * `token` a login token from `login()`
211/// * `recipe` a populated Recipe, with or without a `uid` (for updating or creating a new recipe)
212pub async fn upload_recipe(
213    token: &str,
214    recipe: &mut Recipe,
215) -> Result<bool, Box<dyn std::error::Error>> {
216    let client = reqwest::Client::new();
217
218    // new recipes won't have UID
219    if recipe.uid.is_empty() {
220        recipe.generate_uuid();
221    }
222
223    recipe.update_hash();
224
225    // updating/creating recipes seems to have very weird HTTP requirements
226    // first, convert to JSON
227    let body_json = serde_json::to_vec(&recipe).unwrap();
228
229    // then, GZip-encode that json with no compression
230    let mut encoder = GzEncoder::new(Vec::new(), Compression::none());
231    encoder.write_all(body_json.as_slice()).unwrap();
232    let gzip_body = encoder.finish().unwrap();
233
234    // send that GZip-encoded data as a multi-part file field named "data"
235    let part = reqwest::multipart::Part::bytes(gzip_body).file_name("data");
236    let form = multipart::Form::new().part("data", part);
237
238    let resp_text = client
239        .post(format!("{}/sync/recipe/{}/", &**URL, &recipe.uid))
240        .multipart(form)
241        .header("accept", "*/*")
242        .header("accept-encoding", "utf-8")
243        .header("authorization", "Bearer ".to_string() + token)
244        .send()
245        .await?
246        .text()
247        .await?;
248
249    let recipe_post_resp: Result<ApiResponse, serde_json::Error> = serde_json::from_str(&resp_text);
250
251    match recipe_post_resp {
252        Ok(r) => match r.result {
253            ApiResult::Bool(b) => Ok(b),
254            _ => Err("Recipe POST failed".into()),
255        },
256        Err(e) => Err(Box::new(e)),
257    }
258}