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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
use std::sync::Arc;
use std::sync::atomic::{AtomicI64, AtomicUsize, Ordering};
use chrono::Utc;
use serde_json::Value;
use crate::core::voiceflow::dialog_blocks::traits::FromValue;
use crate::core::voiceflow::dialog_blocks::VoiceflowCard;
use crate::errors::{VoiceflousionError, VoiceflousionResult};
/// Represents a carousel in a Voiceflow dialog.
///
/// `VoiceflowCarousel` contains a list of `VoiceflowCard` instances and a flag indicating whether the carousel has images.
/// The carousel allows for easy navigation between cards and keeps track of the selected card's index and the timestamp when it was selected.
#[derive(Debug, Clone)]
pub struct VoiceflowCarousel {
/// The list of cards in the carousel.
cards: Vec<VoiceflowCard>,
/// A flag indicating whether the carousel has images.
///
/// - `true`: All cards in the carousel have images.
/// - `false`: All cards in the carousel are text-only (no images).
/// Mixed carousels (some cards with images and others without) are not allowed and will trigger an error during initialization.
has_images: bool,
/// The index of the currently selected card in the carousel.
///
/// This value is updated as the user navigates through the carousel.
selected_index: Arc<AtomicUsize>,
/// The timestamp of when the currently selected card was accessed.
///
/// This value helps track when the user last interacted with a specific card.
selected_mark: Arc<AtomicI64>,
}
impl VoiceflowCarousel {
/// Creates a new `VoiceflowCarousel` instance.
///
/// # Parameters
///
/// * `cards` - A list of `VoiceflowCard` instances.
/// * `has_images` - A flag indicating whether the carousel has images.
///
/// # Returns
///
/// A new instance of `VoiceflowCarousel` with the current timestamp and initial selected index set to 0.
///
/// # Example
///
/// ```
/// use voiceflousion::core::voiceflow::dialog_blocks::{VoiceflowCard, VoiceflowCarousel};
///
/// let card = VoiceflowCard::new(Some("https://example.com/image.jpg".to_string()), Some("Title".to_string()), Some("Description".to_string()), None);
/// let cards = vec![card];
/// let carousel = VoiceflowCarousel::new(cards, true);
/// ```
pub fn new(cards: Vec<VoiceflowCard>, has_images: bool) -> Self {
let timestamp = Utc::now().timestamp();
Self {
cards,
has_images,
selected_mark: Arc::new(AtomicI64::new(timestamp)),
selected_index: Arc::new(AtomicUsize::new(0usize)),
}
}
/// Returns whether the carousel has images.
///
/// # Returns
///
/// `true` if the carousel has images, `false` otherwise.
///
/// # Example
///
/// ```
/// use voiceflousion::core::voiceflow::dialog_blocks::{VoiceflowCard, VoiceflowCarousel};
///
/// let card = VoiceflowCard::new(Some("https://example.com/image.jpg".to_string()), Some("Title".to_string()), Some("Description".to_string()), None);
/// let cards = vec![card];
/// let carousel = VoiceflowCarousel::new(cards, true);
/// let has_images = carousel.has_images();
/// ```
pub fn has_images(&self) -> bool {
self.has_images
}
/// Returns the number of cards in the carousel.
///
/// # Returns
///
/// A `usize` representing the number of cards in the carousel.
///
/// # Example
///
/// ```
/// use voiceflousion::core::voiceflow::dialog_blocks::{VoiceflowCard, VoiceflowCarousel};
///
/// let card = VoiceflowCard::new(Some("https://example.com/image.jpg".to_string()), Some("Title".to_string()), Some("Description".to_string()), None);
/// let cards = vec![card];
/// let carousel = VoiceflowCarousel::new(cards, true);
/// let length = carousel.len();
/// ```
pub fn len(&self) -> usize {
self.cards.len()
}
/// Returns whether the carousel contains any cards.
///
/// # Returns
///
/// A boolean indicating if the carousel is empty.
///
/// # Example
///
/// ```
/// use voiceflousion::core::voiceflow::dialog_blocks::{VoiceflowCard, VoiceflowCarousel};
///
/// let card = VoiceflowCard::new(Some("https://example.com/image.jpg".to_string()), Some("Title".to_string()), Some("Description".to_string()), None);
/// let cards = vec![card];
/// let carousel = VoiceflowCarousel::new(cards, true);
/// let is_empty = carousel.is_empty();
/// ```
pub fn is_empty(&self) -> bool {
self.cards.is_empty()
}
/// Returns the currently selected card and its index.
///
/// # Returns
///
/// A `VoiceflousionResult` containing a tuple with a reference to the selected `VoiceflowCard` and its index.
///
/// # Example
///
/// ```
/// use voiceflousion::core::voiceflow::dialog_blocks::{VoiceflowCard, VoiceflowCarousel};
///
/// let card = VoiceflowCard::new(Some("https://example.com/image.jpg".to_string()), Some("Title".to_string()), Some("Description".to_string()), None);
/// let cards = vec![card];
/// let carousel = VoiceflowCarousel::new(cards, true);
/// let (selected_card, index) = carousel.get_selected_card().unwrap();
/// ```
pub fn get_selected_card(&self) -> VoiceflousionResult<(&VoiceflowCard, usize)> {
let index = self.get_selected_index();
let card = self.cards.get(index).ok_or_else(|| {
VoiceflousionError::ValidationError(
"VoiceflousionCarousel".to_string(),
format!("Index {} out of bounds", index),
)
})?;
Ok((card, index))
}
/// Returns the timestamp of when the current card was selected.
///
/// # Returns
///
/// An `i64` representing the timestamp of the selected card.
///
/// # Example
///
/// ```
/// use voiceflousion::core::voiceflow::dialog_blocks::{VoiceflowCard, VoiceflowCarousel};
///
/// let card = VoiceflowCard::new(Some("https://example.com/image.jpg".to_string()), Some("Title".to_string()), Some("Description".to_string()), None);
/// let cards = vec![card];
/// let carousel = VoiceflowCarousel::new(cards, true);
/// let timestamp = carousel.get_selected_mark();
/// ```
pub fn get_selected_mark(&self) -> i64 {
self.selected_mark.load(Ordering::SeqCst)
}
/// Returns the index of the currently selected card.
///
/// # Returns
///
/// A `usize` representing the index of the selected card.
///
/// # Example
///
/// ```
/// use voiceflousion::core::voiceflow::dialog_blocks::{VoiceflowCard, VoiceflowCarousel};
///
/// let card = VoiceflowCard::new(Some("https://example.com/image.jpg".to_string()), Some("Title".to_string()), Some("Description".to_string()), None);
/// let cards = vec![card];
/// let carousel = VoiceflowCarousel::new(cards, true);
/// let selected_index = carousel.get_selected_index();
/// ```
pub fn get_selected_index(&self) -> usize {
self.selected_index.load(Ordering::SeqCst)
}
/// Retrieves the next card in the carousel based on the provided direction.
///
/// # Parameters
///
/// * `direction` - A boolean indicating the direction of navigation. `true` for forward, `false` for backward.
///
/// # Returns
///
/// A `VoiceflousionResult` containing a tuple with a reference to the next `VoiceflowCard` and its index.
///
/// # Example
///
/// ```
/// use voiceflousion::core::voiceflow::dialog_blocks::{VoiceflowCard, VoiceflowCarousel};
///
/// let card1 = VoiceflowCard::new(Some("https://example.com/image1.jpg".to_string()), Some("Title1".to_string()), Some("Description1".to_string()), None);
/// let card2 = VoiceflowCard::new(Some("https://example.com/image2.jpg".to_string()), Some("Title2".to_string()), Some("Description2".to_string()), None);
/// let cards = vec![card1, card2];
/// let carousel = VoiceflowCarousel::new(cards, true);
/// let (next_card, index) = carousel.get_next_card(true).unwrap(); // Navigate forward
/// ```
pub fn get_next_card(&self, direction: bool) -> VoiceflousionResult<(&VoiceflowCard, usize)> {
let current_index = self.get_selected_index();
let new_index = if direction {
if current_index < self.cards.len() - 1 {
current_index + 1
} else {
return Err(VoiceflousionError::ValidationError(
"VoiceflousionCarousel".to_string(),
format!("Index {} can't be bigger", current_index),
));
}
} else {
if current_index > 0 {
current_index - 1
} else {
return Err(VoiceflousionError::ValidationError(
"VoiceflousionCarousel".to_string(),
format!("Index {} can't be lesser", current_index),
));
}
};
let card = self.cards.get(new_index).ok_or_else(|| {
VoiceflousionError::ValidationError(
"VoiceflousionCarousel".to_string(),
format!("Index {} out of bounds", new_index),
)
})?;
Ok((card, new_index))
}
/// Sets the selected card index and updates the timestamp of selection.
///
/// # Parameters
///
/// * `selected_index` - The index of the card to set as selected.
/// * `timestamp` - The timestamp to associate with the selection.
///
/// # Panics
///
/// This method will panic if `selected_index` is out of bounds.
///
/// # Example
///
/// ```
/// use chrono::Utc;
/// use voiceflousion::core::voiceflow::dialog_blocks::{VoiceflowCard, VoiceflowCarousel};
///
/// let card1 = VoiceflowCard::new(Some("https://example.com/image1.jpg".to_string()), Some("Title1".to_string()), Some("Description1".to_string()), None);
/// let card2 = VoiceflowCard::new(Some("https://example.com/image2.jpg".to_string()), Some("Title2".to_string()), Some("Description2".to_string()), None);
/// let cards = vec![card1, card2];
/// let carousel = VoiceflowCarousel::new(cards, true);
/// carousel.set_selected_card(1, Utc::now().timestamp());
/// ```
pub fn set_selected_card(&self, selected_index: usize, timestamp: i64) {
if selected_index >= self.cards.len() {
panic!("Index {} is out of bounds", selected_index);
}
self.selected_index.store(selected_index, Ordering::SeqCst);
self.selected_mark.store(timestamp, Ordering::SeqCst);
}
}
impl FromValue for VoiceflowCarousel {
/// Attempts to convert a JSON `Value` into a `VoiceflowCarousel` instance.
///
/// This method extracts the list of cards from the JSON value and determines
/// whether the carousel contains only images or only text. Mixed carousels
/// are not allowed and will return an error.
///
/// # Parameters
///
/// * `value` - A reference to the JSON `Value` to convert from.
///
/// # Returns
///
/// A `VoiceflousionResult` containing an `Option` with the `VoiceflowCarousel` instance if the conversion
/// succeeds, or a `VoiceflousionError` if the conversion fails. If the conversion
/// succeeds but there is no meaningful value, `None` can be returned.
fn from_value(value: &Value) -> VoiceflousionResult<Option<Self>> {
// Extract the "payload" field from the "trace" object in the JSON value.
let payload = value["trace"].get("payload").ok_or_else(|| {
VoiceflousionError::VoiceflowBlockConvertationError(
"VoiceflowCarousel carousel payload".to_string(),
value.clone(),
)
})?;
// Extract the "cards" array from the payload.
let cards_value = payload
.get("cards")
.and_then(|cards| cards.as_array())
.ok_or_else(|| {
VoiceflousionError::VoiceflowBlockConvertationError(
"VoiceflowCarousel cards value".to_string(),
value.clone(),
)
})?;
// Convert each card in the array into a VoiceflowCard.
let cards_option: Result<Vec<Option<VoiceflowCard>>, VoiceflousionError> = cards_value
.into_iter()
.map(|card| VoiceflowCard::from_value(card))
.collect();
let cards: Vec<VoiceflowCard> = cards_option?.into_iter().filter_map(|card| card).collect();
// Return None if the carousel has no cards.
if cards.is_empty() {
return Ok(None);
}
// Determine if all cards have images or if all are text-only.
let has_images = cards.iter().all(|card| card.image_url().is_some());
let no_images = cards.iter().all(|card| card.image_url().is_none());
// Check for mixed types: some cards with images, some without.
if !has_images && !no_images {
return Err(VoiceflousionError::VoiceflowBlockConvertationError(
"VoiceflowCarousel cards value".to_string(),
value.clone(),
));
}
// Return the constructed VoiceflowCarousel.
Ok(Some(Self::new(cards, has_images)))
}
}