xapi-data 1.0.0-rc.1

Rust bindings for the Experience API (xAPI) data structures
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
// SPDX-License-Identifier: GPL-3.0-or-later

use crate::{
    Canonical, DataError, Extensions, InteractionComponent, InteractionType, LanguageMap,
    MyLanguageTag, Validate, ValidationError, add_language, emit_error, merge_maps,
    validate::validate_irl,
};
use core::fmt;
use iri_string::types::{IriStr, IriString};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::skip_serializing_none;

/// Structure that provides additional information (metadata) related to an
/// [Activity][crate::Activity].
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ActivityDefinition {
    name: Option<LanguageMap>,
    description: Option<LanguageMap>,
    #[serde(rename = "type")]
    type_: Option<IriString>,
    more_info: Option<IriString>,
    // IMPORTANT (20240925) - 'interactionType' property must be present if any
    // of the 'correctResponsesPattern', 'choices', 'scale', 'source', 'target',
    // or 'steps' are.
    interaction_type: Option<InteractionType>,
    correct_responses_pattern: Option<Vec<String>>,
    choices: Option<Vec<InteractionComponent>>,
    scale: Option<Vec<InteractionComponent>>,
    source: Option<Vec<InteractionComponent>>,
    target: Option<Vec<InteractionComponent>>,
    steps: Option<Vec<InteractionComponent>>,
    extensions: Option<Extensions>,
}

impl ActivityDefinition {
    /// Return an [ActivityDefinition] _Builder_.
    pub fn builder() -> ActivityDefinitionBuilder<'static> {
        ActivityDefinitionBuilder::default()
    }

    /// Return the `name` for the given language `tag` if it exists; `None`
    /// otherwise.
    pub fn name(&self, tag: &MyLanguageTag) -> Option<&str> {
        match &self.name {
            Some(lm) => lm.get(tag),
            None => None,
        }
    }

    /// Return the `description` for the given language `tag` if it exists;
    /// `None` otherwise.
    pub fn description(&self, tag: &MyLanguageTag) -> Option<&str> {
        match &self.description {
            Some(lm) => lm.get(tag),
            None => None,
        }
    }

    /// Return the `type_` field if set; `None` otherwise.
    pub fn type_(&self) -> Option<&IriStr> {
        self.type_.as_deref()
    }

    /// Return the `more_info` field if set; `None` otherwise.
    ///
    /// When set, it's an IRL that points to information about the associated
    /// [Activity][crate::Activity] possibly incl. a way to launch it.
    pub fn more_info(&self) -> Option<&IriStr> {
        self.more_info.as_deref()
    }

    /// Return the `interaction_type` field if set; `None` otherwise.
    ///
    /// Possible values are: [`true-false`][InteractionType#variant.TrueFalse],
    /// [`choice`][InteractionType#variant.Choice],
    /// [`fill-in`][InteractionType#variant.FillIn],
    /// [`long-fill-in`][InteractionType#variant.LongFillIn],
    /// [`matching`][InteractionType#variant.Matching],
    /// [`performance`][InteractionType#variant.Performance],
    /// [`sequencing`][InteractionType#variant.Sequencing],
    /// [`likert`][InteractionType#variant.Likert],
    /// [`numeric`][InteractionType#variant.Numeric], and
    /// [`other`][InteractionType#variant.Other],
    pub fn interaction_type(&self) -> Option<&InteractionType> {
        self.interaction_type.as_ref()
    }

    /// Return the `correct_responses_pattern` field if set; `None` otherwise.
    ///
    /// When set, it's a Vector of patterns representing the correct response
    /// to the interaction.
    ///
    /// The structure of the patterns vary depending on the `interaction_type`.
    pub fn correct_responses_pattern(&self) -> Option<&Vec<String>> {
        self.correct_responses_pattern.as_ref()
    }

    /// Return the `choices` field if set; `None` otherwise.
    ///
    /// When set, it's a vector of of [InteractionComponent]s representing the
    /// correct response to the interaction.
    ///
    /// The contents of item(s) in the vector are specific to the given
    /// `interaction_type`.
    pub fn choices(&self) -> Option<&Vec<InteractionComponent>> {
        self.choices.as_ref()
    }

    /// Return the `scale` field if set; `None` otherwise.
    ///
    /// When set, it's a vector of of [InteractionComponent]s representing the
    /// correct response to the interaction.
    ///
    /// The contents of item(s) in the vector are specific to the given
    /// `interaction_type`.
    pub fn scale(&self) -> Option<&Vec<InteractionComponent>> {
        self.scale.as_ref()
    }

    /// Return the `source` field if set; `None` otherwise.
    ///
    /// When set, it's a vector of of [InteractionComponent]s representing the
    /// correct response to the interaction.
    ///
    /// The contents of item(s) in the vector are specific to the given
    /// `interaction_type`.
    pub fn source(&self) -> Option<&Vec<InteractionComponent>> {
        self.source.as_ref()
    }

    /// Return the `target` field if set; `None` otherwise.
    ///
    /// When set, it's a vector of of [InteractionComponent]s representing the
    /// correct response to the interaction.
    ///
    /// The contents of item(s) in the vector are specific to the given
    /// `interaction_type`.
    pub fn target(&self) -> Option<&Vec<InteractionComponent>> {
        self.target.as_ref()
    }

    /// Return the `steps` field if set; `None` otherwise.
    ///
    /// When set, it's a vector of of [InteractionComponent]s representing the
    /// correct response to the interaction.
    ///
    /// The contents of item(s) in the vector are specific to the given
    /// `interaction_type`.
    pub fn steps(&self) -> Option<&Vec<InteractionComponent>> {
        self.steps.as_ref()
    }

    /// Return the [`extensions`][Extensions] field if set; `None` otherwise.
    pub fn extensions(&self) -> Option<&Extensions> {
        self.extensions.as_ref()
    }

    /// Return the _extension_ keyed by `key` if it exists; `None` otherwise.
    pub fn extension(&self, key: &IriStr) -> Option<&Value> {
        if let Some(z_extensions) = self.extensions.as_ref() {
            z_extensions.get(key)
        } else {
            None
        }
    }

    /// Consume `that` merging it into this instance.
    pub fn merge(&mut self, that: Self) {
        // merge two Option<Vec<InteractionComponents>>...
        fn merge_opt_collections(
            dst: &mut Option<Vec<InteractionComponent>>,
            src: Option<Vec<InteractionComponent>>,
        ) {
            match dst {
                Some(lhs) => {
                    if let Some(rhs) = src {
                        InteractionComponent::merge_collections(lhs, rhs)
                    }
                }
                None => *dst = src,
            }
        }

        // extend b-tree maps...
        merge_maps!(&mut self.name, that.name);
        merge_maps!(&mut self.description, that.description);
        merge_maps!(&mut self.extensions, that.extensions);
        // overwrite if none...
        if self.type_.is_none() {
            self.type_ = that.type_
        }
        if self.more_info.is_none() {
            self.more_info = that.more_info
        }
        if self.interaction_type.is_none() {
            self.interaction_type = that.interaction_type
        }
        // combine string collections...
        match &mut self.correct_responses_pattern {
            Some(this_field) => {
                if let Some(that_field) = that.correct_responses_pattern {
                    this_field.extend(that_field);
                    // NOTE (rsn) 20250412 - ensure no dups...
                    this_field.sort();
                    this_field.dedup();
                }
            }
            None => self.correct_responses_pattern = that.correct_responses_pattern,
        }
        // merge optional collections of InteractionComponents...
        merge_opt_collections(&mut self.choices, that.choices);
        merge_opt_collections(&mut self.scale, that.scale);
        merge_opt_collections(&mut self.source, that.source);
        merge_opt_collections(&mut self.target, that.target);
        merge_opt_collections(&mut self.steps, that.steps);
    }
}

impl fmt::Display for ActivityDefinition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut vec = vec![];
        if let Some(z_name) = self.name.as_ref() {
            vec.push(format!("name: {}", z_name));
        }
        if let Some(z_description) = self.description.as_ref() {
            vec.push(format!("description: {}", z_description));
        }
        if let Some(z_type) = self.type_.as_ref() {
            vec.push(format!("type: \"{}\"", z_type));
        }
        if let Some(z_more_info) = self.more_info.as_ref() {
            vec.push(format!("moreInfo: \"{}\"", z_more_info));
        }
        if let Some(z_interaction_type) = self.interaction_type.as_ref() {
            vec.push(format!("interactionType: {}", z_interaction_type));
        }
        if let Some(z_correct_responses_pattern) = self.correct_responses_pattern.as_ref() {
            vec.push(format!(
                "correctResponsesPattern: {}",
                array_to_display_str(z_correct_responses_pattern)
            ));
        }
        if let Some(z_choices) = self.choices.as_ref() {
            vec.push(format!("choices: {}", vec_to_display_str(z_choices)));
        }
        if let Some(z_scale) = self.scale.as_ref() {
            vec.push(format!("scale: {}", vec_to_display_str(z_scale)));
        }
        if let Some(z_source) = self.source.as_ref() {
            vec.push(format!("source: {}", vec_to_display_str(z_source)));
        }
        if let Some(z_target) = self.target.as_ref() {
            vec.push(format!("target: {}", vec_to_display_str(z_target)));
        }
        if let Some(z_steps) = self.steps.as_ref() {
            vec.push(format!("steps: {}", vec_to_display_str(z_steps)));
        }
        if let Some(z_extensions) = self.extensions.as_ref() {
            vec.push(format!("extensions: {}", z_extensions))
        }
        let res = vec
            .iter()
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
            .join(", ");
        write!(f, "ActivityDefinition{{ {res} }}")
    }
}

impl Validate for ActivityDefinition {
    fn validate(&self) -> Vec<ValidationError> {
        let mut vec: Vec<ValidationError> = vec![];

        // validate type
        if self.type_.is_some() && self.type_.as_ref().unwrap().is_empty() {
            vec.push(ValidationError::InvalidIRI("type".into()))
        }
        // validate more_info
        if let Some(z_more_info) = self.more_info.as_ref() {
            validate_irl(z_more_info).unwrap_or_else(|x| vec.push(x));
        }
        // interaction type is guaranteed to be valid when present; is it missing?
        if (self.correct_responses_pattern.is_some()
            || self.choices.is_some()
            || self.scale.is_some()
            || self.source.is_some()
            || self.target.is_some()
            || self.steps.is_some())
            && self.interaction_type.is_none()
        {
            vec.push(ValidationError::ConstraintViolation(
                "Activity definition interaction-type must be present when any Interaction Activities properties is too".into(),
            ))
        }
        // validate correct response pattern
        if let Some(z_correct_responses_pattern) = self.correct_responses_pattern.as_ref() {
            for it in z_correct_responses_pattern.iter() {
                if it.is_empty() {
                    vec.push(ValidationError::Empty("correctResponsePattern".into()))
                }
            }
        }
        // validate choices
        if let Some(z_choices) = self.choices.as_ref() {
            z_choices.iter().for_each(|x| vec.extend(x.validate()));
        }
        // validate scale
        if let Some(z_scale) = self.scale.as_ref() {
            z_scale.iter().for_each(|x| vec.extend(x.validate()));
        }
        // validate source
        if let Some(z_source) = self.source.as_ref() {
            z_source.iter().for_each(|x| vec.extend(x.validate()));
        }
        // validate target
        if let Some(z_target) = self.target.as_ref() {
            z_target.iter().for_each(|x| vec.extend(x.validate()));
        }
        // validate steps
        if let Some(z_steps) = self.steps.as_ref() {
            z_steps.iter().for_each(|x| vec.extend(x.validate()));
        }

        vec
    }
}

impl Canonical for ActivityDefinition {
    fn canonicalize(&mut self, language_tags: &[MyLanguageTag]) {
        if let Some(z_name) = self.name.as_mut() {
            z_name.canonicalize(language_tags)
        }
        if let Some(z_description) = self.description.as_mut() {
            z_description.canonicalize(language_tags)
        }
        if let Some(z_choices) = self.choices.as_mut() {
            for it in z_choices {
                it.canonicalize(language_tags)
            }
        }
        if let Some(z_scale) = self.scale.as_mut() {
            for it in z_scale {
                it.canonicalize(language_tags)
            }
        }
        if let Some(z_source) = self.source.as_mut() {
            for it in z_source {
                it.canonicalize(language_tags)
            }
        }
        if let Some(z_target) = self.target.as_mut() {
            for it in z_target {
                it.canonicalize(language_tags)
            }
        }
        if let Some(z_steps) = self.steps.as_mut() {
            for it in z_steps {
                it.canonicalize(language_tags)
            }
        }
    }
}

/// A Type that knows how to construct an [ActivityDefinition]
#[derive(Debug, Default)]
pub struct ActivityDefinitionBuilder<'a> {
    _name: Option<LanguageMap>,
    _description: Option<LanguageMap>,
    _type_: Option<&'a IriStr>,
    _more_info: Option<&'a IriStr>,
    _interaction_type: Option<InteractionType>,
    _correct_responses_pattern: Option<Vec<String>>,
    _choices: Option<Vec<InteractionComponent>>,
    _scale: Option<Vec<InteractionComponent>>,
    _source: Option<Vec<InteractionComponent>>,
    _target: Option<Vec<InteractionComponent>>,
    _steps: Option<Vec<InteractionComponent>>,
    _extensions: Option<Extensions>,
}

impl<'a> ActivityDefinitionBuilder<'a> {
    /// Add the given `label` to the `name` dictionary keyed by the given `tag`.
    ///
    /// Raise [DataError] if `tag` is not a valid Language Tag.
    pub fn name(mut self, tag: &MyLanguageTag, label: &str) -> Result<Self, DataError> {
        add_language!(self._name, tag, label);
        Ok(self)
    }

    /// Add the given `label` to the `description` dictionary keyed by the given
    /// `tag`.
    ///
    /// Raise [DataError] if `tag` is not a valid Language Tag.
    pub fn description(mut self, tag: &MyLanguageTag, label: &str) -> Result<Self, DataError> {
        add_language!(self._description, tag, label);
        Ok(self)
    }

    /// Set the `type_` field.
    pub fn type_(mut self, val: &'a str) -> Result<Self, DataError> {
        let val = val.trim();
        if val.is_empty() {
            emit_error!(DataError::Validation(ValidationError::Empty("type".into())))
        } else {
            let iri = IriStr::new(val)?;
            self._type_ = Some(iri);
            Ok(self)
        }
    }

    /// Set the `more_info` field.
    pub fn more_info(mut self, val: &'a str) -> Result<Self, DataError> {
        let val = val.trim();
        if val.is_empty() {
            emit_error!(DataError::Validation(ValidationError::Empty(
                "more_info".into()
            )))
        } else {
            let val = IriStr::new(val)?;
            validate_irl(val)?;
            self._more_info = Some(val);
            Ok(self)
        }
    }

    /// Set the `interaction_type` field.
    pub fn interaction_type(mut self, val: InteractionType) -> Self {
        self._interaction_type = Some(val);
        self
    }

    /// Add `val` to correct responses pattern.
    pub fn correct_responses_pattern(mut self, val: &str) -> Result<Self, DataError> {
        let val = val.trim();
        if val.is_empty() {
            emit_error!(DataError::Validation(ValidationError::Empty(
                "correct_responses_pattern".into()
            )))
        }
        if self._correct_responses_pattern.is_none() {
            self._correct_responses_pattern = Some(vec![])
        }
        self._correct_responses_pattern
            .as_mut()
            .unwrap()
            .push(val.to_string());
        Ok(self)
    }

    /// Add `val` to `choices`.
    pub fn choices(mut self, val: InteractionComponent) -> Result<Self, DataError> {
        val.check_validity()?;
        if self._choices.is_none() {
            self._choices = Some(vec![])
        }
        self._choices.as_mut().unwrap().push(val);
        Ok(self)
    }

    /// Add `val` to `scale`.
    pub fn scale(mut self, val: InteractionComponent) -> Result<Self, DataError> {
        val.check_validity()?;
        if self._scale.is_none() {
            self._scale = Some(vec![])
        }
        self._scale.as_mut().unwrap().push(val);
        Ok(self)
    }

    /// Add `val` to `source`.
    pub fn source(mut self, val: InteractionComponent) -> Result<Self, DataError> {
        val.check_validity()?;
        if self._source.is_none() {
            self._source = Some(vec![])
        }
        self._source.as_mut().unwrap().push(val);
        Ok(self)
    }

    /// Add `val` to `target`.
    pub fn target(mut self, val: InteractionComponent) -> Result<Self, DataError> {
        val.check_validity()?;
        if self._target.is_none() {
            self._target = Some(vec![])
        }
        self._target.as_mut().unwrap().push(val);
        Ok(self)
    }

    /// Add `val` to `steps`.
    pub fn steps(mut self, val: InteractionComponent) -> Result<Self, DataError> {
        val.check_validity()?;
        if self._steps.is_none() {
            self._steps = Some(vec![])
        }
        self._steps.as_mut().unwrap().push(val);
        Ok(self)
    }

    /// Add an extension's `key` and `value` pair.
    pub fn extension(mut self, key: &str, value: &Value) -> Result<Self, DataError> {
        if self._extensions.is_none() {
            self._extensions = Some(Extensions::new());
        }
        let _ = self._extensions.as_mut().unwrap().add(key, value);
        Ok(self)
    }

    /// Create an [ActivityDefinition] from set field values.
    ///
    /// Raise [DataError] if no field was set.
    pub fn build(self) -> Result<ActivityDefinition, DataError> {
        if self._name.is_none()
            && self._description.is_none()
            && self._type_.is_none()
            && self._more_info.is_none()
            && self._interaction_type.is_none()
            && self._correct_responses_pattern.is_none()
            && self._choices.is_none()
            && self._scale.is_none()
            && self._source.is_none()
            && self._target.is_none()
            && self._steps.is_none()
            && self._extensions.is_none()
        {
            emit_error!(DataError::Validation(ValidationError::ConstraintViolation(
                "At least 1 field must be set".into()
            )))
        }

        if self._interaction_type.is_none()
            && (self._correct_responses_pattern.is_some()
                || self._choices.is_some()
                || self._scale.is_some()
                || self._source.is_some()
                || self._target.is_some()
                || self._steps.is_some())
        {
            emit_error!(DataError::Validation(ValidationError::MissingField(
                "interaction_type".into()
            )))
        }

        Ok(ActivityDefinition {
            name: self._name,
            description: self._description,
            type_: self._type_.map(|x| x.into()),
            more_info: self._more_info.map(|x| x.into()),
            interaction_type: self._interaction_type,
            correct_responses_pattern: self._correct_responses_pattern,
            choices: self._choices,
            scale: self._scale,
            source: self._source,
            target: self._target,
            steps: self._steps,

            extensions: self._extensions,
        })
    }
}

fn array_to_display_str(val: &[String]) -> String {
    let mut vec = vec![];
    for v in val.iter() {
        vec.push(format!("\"{v}\""))
    }
    vec.iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(", ")
}

fn vec_to_display_str(val: &Vec<InteractionComponent>) -> String {
    let mut vec = vec![];
    for ic in val {
        vec.push(format!("{ic}"))
    }
    vec.iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(", ")
}

#[cfg(test)]
mod tests {
    use super::*;
    use tracing_test::traced_test;

    #[traced_test]
    #[test]
    fn test_display() {
        const DISPLAY: &str = r#"ActivityDefinition{ description: {"en-US":"Does the xAPI include the concept of statements?"}, type: "http://adlnet.gov/expapi/activities/cmi.interaction", interactionType: true-false, correctResponsesPattern: "true" }"#;

        let json = r#"{
            "description": {
                "en-US": "Does the xAPI include the concept of statements?"
            },
            "type": "http://adlnet.gov/expapi/activities/cmi.interaction",
            "interactionType": "true-false",
            "correctResponsesPattern": [
                "true"
            ]
        }"#;

        let de_result = serde_json::from_str::<ActivityDefinition>(json);
        assert!(de_result.is_ok());
        let ad = de_result.unwrap();
        let display = format!("{}", ad);
        assert_eq!(display, DISPLAY);
    }

    #[traced_test]
    #[test]
    fn test_missing_interaction_type() {
        const BAD: &str = r#"{
"name":{"en": "Fill-In"},
"description":{"en": "Ben is often heard saying:"},
"type":"http://adlnet.gov/expapi/activities/cmi.interaction",
"moreInfo":"http://virtualmeeting.example.com/345256",
"correctResponsesPattern":["Bob's your uncle"],
"extensions":{
 "http://example.com/profiles/meetings/extension/location":"X:\\\\meetings\\\\minutes\\\\examplemeeting.one",
 "http://example.com/profiles/meetings/extension/reporter":{"name":"Thomas","id":"http://openid.com/342"}
}}"#;

        let de_result = serde_json::from_str::<ActivityDefinition>(BAD);
        assert!(de_result.is_ok());
        let ad = de_result.unwrap();
        // should not be valid b/c missing interaction_type!
        assert!(!ad.is_valid());
    }
}