caio.co/de/cantine


Only output image url(s) if we have any by Caio 5 years ago (log)

Blob cantine/src/model.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use std::{convert::TryInto, mem::size_of};

use base64::{self, URL_SAFE_NO_PAD};
use serde::{
    de::{Deserializer, Error, Visitor},
    Deserialize, Serialize, Serializer,
};
use uuid::{self, Uuid};

use crate::database::DatabaseRecord;
use tique::FilterAndAggregation;

#[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
pub struct Recipe {
    pub uuid: Uuid,

    pub recipe_id: RecipeId,
    pub name: String,
    pub crawl_url: String,

    pub ingredients: Vec<String>,
    pub instructions: Vec<String>,
    pub images: Vec<String>,

    pub similar_recipe_ids: Vec<u64>,

    pub features: Features,
}

pub type RecipeId = u64;

impl DatabaseRecord for Recipe {
    fn get_id(&self) -> u64 {
        self.recipe_id
    }
    fn get_uuid(&self) -> uuid::Bytes {
        *self.uuid.as_bytes()
    }
}

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct RecipeCard {
    pub name: String,
    pub uuid: Uuid,
    pub crawl_url: String,
    pub num_ingredients: u8,
    pub instructions_length: u32,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_time: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub calories: Option<u32>,
}

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct RecipeInfo {
    pub uuid: Uuid,
    pub name: String,
    pub crawl_url: String,

    pub num_ingredients: u8,
    pub ingredients: Vec<String>,

    pub instructions: Vec<String>,

    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub images: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_time: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub calories: Option<u32>,
}

impl From<Recipe> for RecipeInfo {
    fn from(src: Recipe) -> Self {
        Self {
            uuid: src.uuid,
            name: src.name,
            crawl_url: src.crawl_url,
            images: src.images,

            ingredients: src.ingredients,
            instructions: src.instructions,

            num_ingredients: src.features.num_ingredients,
            total_time: src.features.total_time,
            calories: src.features.calories,
        }
    }
}

impl From<Recipe> for RecipeCard {
    fn from(src: Recipe) -> Self {
        Self {
            name: src.name,
            uuid: src.uuid,
            crawl_url: src.crawl_url,
            image: src.images.into_iter().next(),
            num_ingredients: src.features.num_ingredients,
            instructions_length: src.features.instructions_length,
            total_time: src.features.total_time,
            calories: src.features.calories,
        }
    }
}

#[derive(FilterAndAggregation, Serialize, Deserialize, Debug, Default, PartialEq, Clone)]
pub struct Features {
    pub num_ingredients: u8,
    pub instructions_length: u32,

    pub prep_time: Option<u32>,
    pub total_time: Option<u32>,
    pub cook_time: Option<u32>,

    pub calories: Option<u32>,
    pub fat_content: Option<f32>,
    pub carb_content: Option<f32>,
    pub protein_content: Option<f32>,

    pub diet_lowcarb: Option<f32>,
    pub diet_vegetarian: Option<f32>,
    pub diet_vegan: Option<f32>,
    pub diet_keto: Option<f32>,
    pub diet_paleo: Option<f32>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum Sort {
    Relevance,
    NumIngredients,
    InstructionsLength,
    TotalTime,
    CookTime,
    PrepTime,
    Calories,
    FatContent,
    CarbContent,
    ProteinContent,
}

#[derive(Serialize, Deserialize, Debug, Default)]
#[serde(deny_unknown_fields)]
pub struct SearchQuery {
    pub fulltext: Option<String>,
    pub sort: Option<Sort>,
    pub num_items: Option<u8>,
    pub filter: Option<FeaturesFilterQuery>,
    pub agg: Option<FeaturesAggregationQuery>,
    pub after: Option<SearchCursor>,
}

#[derive(Serialize, Debug, Default)]
pub struct SearchResult {
    pub items: Vec<RecipeCard>,
    pub total_found: usize,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub agg: Option<FeaturesAggregationResult>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub next: Option<SearchCursor>,
}

#[derive(Debug, Default, PartialEq)]
pub struct SearchCursor(pub u64, pub uuid::Bytes);

impl SearchCursor {
    pub const SIZE: usize = size_of::<SearchCursor>();

    pub fn new(score_bits: u64, uuid: &Uuid) -> Self {
        Self(score_bits, *uuid.as_bytes())
    }

    pub fn from_bytes(src: &[u8; Self::SIZE]) -> Self {
        let score_bits =
            u64::from_be_bytes(src[0..8].try_into().expect("Slice has correct length"));
        Self(
            score_bits,
            src[8..].try_into().expect("Slice has correct length"),
        )
    }

    pub fn write_bytes(&self, buf: &mut [u8; Self::SIZE]) {
        buf[0..8].copy_from_slice(&self.0.to_be_bytes());
        buf[8..].copy_from_slice(&self.1[..]);
    }
}

const ENCODED_SEARCH_CURSOR_LEN: usize = 32;

impl Serialize for SearchCursor {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut buf = [0u8; SearchCursor::SIZE];

        self.write_bytes(&mut buf);

        let mut encode_buf = [0u8; ENCODED_SEARCH_CURSOR_LEN];
        base64::encode_config_slice(&buf, URL_SAFE_NO_PAD, &mut encode_buf[..]);

        let encoded = std::str::from_utf8(&encode_buf[..]).unwrap();
        serializer.serialize_str(encoded)
    }
}

struct SearchCursorVisitor;

impl<'de> Visitor<'de> for SearchCursorVisitor {
    type Value = SearchCursor;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("Base64-encoded SearchCursor")
    }

    fn visit_bytes<E: Error>(self, input: &[u8]) -> Result<Self::Value, E> {
        if input.len() != ENCODED_SEARCH_CURSOR_LEN {
            return Err(Error::invalid_length(ENCODED_SEARCH_CURSOR_LEN, &self));
        }

        let mut decode_buf = [0u8; SearchCursor::SIZE];
        base64::decode_config_slice(input, URL_SAFE_NO_PAD, &mut decode_buf[..])
            .map_err(|_| Error::custom("base64_decode failed"))?;

        Ok(SearchCursor::from_bytes(
            &decode_buf.try_into().expect("Slice has correct length"),
        ))
    }
}

impl<'de> Deserialize<'de> for SearchCursor {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_bytes(SearchCursorVisitor)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    use serde_json;

    #[test]
    fn search_cursor_json_round_trip() {
        for i in 0..100 {
            let cursor = SearchCursor::new(i, &Uuid::new_v4());

            let serialized = serde_json::to_string(&cursor).unwrap();
            let deserialized = serde_json::from_str(&serialized).unwrap();

            assert_eq!(cursor, deserialized);
        }
    }

    proptest! {
        #[test]
        #[allow(unused_must_use)]
        fn no_crash_json_any_input_size(input in "\\PC*") {
            serde_json::from_str::<SearchCursor>(input.as_str());
        }

        #[test]
        #[allow(unused_must_use)]
        fn no_crash_with_properly_sized_junk(buf in prop::array::uniform32(0u8..)) {
            let visitor = SearchCursorVisitor;
            visitor.visit_bytes::<serde_json::Error>(&buf);
        }
    }
}