pkpass 1.1.0

Rust library for generate Apple Wallet Passes for iOS, WatchOS, MacOS.
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
use chrono::{DateTime, Utc};
use is_empty::IsEmpty;
use serde::{Deserialize, Serialize};

use super::semantic_tags::SemanticTags;

/// Represents the groups of fields that display information on the front and back of a pass.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Fields {
    /// Represents the fields that display additional information on the front of a pass.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auxiliary_fields: Option<Vec<Content>>,

    /// Represents the fields that display information on the back of a pass.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub back_fields: Option<Vec<Content>>,

    /// Represents the fields that display information at the top of a pass.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub header_fields: Option<Vec<Content>>,

    /// Represents the fields that display the most important information on a pass.
    pub primary_fields: Vec<Content>,

    /// Represents the fields that display supporting information on the front of a pass.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub secondary_fields: Option<Vec<Content>>,
}

impl Default for Fields {
    /// Creates an empty `Fields`.
    fn default() -> Self {
        Self {
            auxiliary_fields: None,
            back_fields: None,
            header_fields: None,
            primary_fields: Vec::new(),
            secondary_fields: None,
        }
    }
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum ContentValue {
    String(String),
    Date(DateTime<Utc>),
    Int(i64),
    Float(f64),
}

impl From<String> for ContentValue {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

impl From<&str> for ContentValue {
    fn from(value: &str) -> Self {
        Self::String(value.to_string())
    }
}

impl From<DateTime<Utc>> for ContentValue {
    fn from(value: DateTime<Utc>) -> Self {
        Self::Date(value)
    }
}

impl From<i64> for ContentValue {
    fn from(value: i64) -> Self {
        Self::Int(value)
    }
}

impl From<f64> for ContentValue {
    fn from(value: f64) -> Self {
        Self::Float(value)
    }
}

/// Represents the information to display in a field on a pass.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Content {
    /// (Required) A unique key that identifies a field in the pass; for example, “departure-gate”.
    pub key: String,

    /// (Required) The value to use for the field; for example, 42. A date or time value must include a time zone.
    pub value: ContentValue,

    /// All optionals
    #[serde(flatten)]
    pub options: ContentOptions,
}

impl Content {
    /// Creates `FieldContent`.
    #[must_use]
    pub fn new(key: &str, value: &str, options: ContentOptions) -> Self {
        Self {
            key: String::from(key),
            value: ContentValue::from(value),
            options,
        }
    }
}

/// Represents options for `FieldContent`
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ContentOptions {
    /// The value of the field, including HTML markup for links.
    ///
    /// The only supported tag is the `<a>` tag and its href attribute.
    ///
    /// The value of this key overrides that of the value key.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attributed_value: Option<String>,

    /// A format string for the alert text to display when the pass is updated.
    ///
    /// The format string must contain the escape %@, which is replaced with the field’s new value.
    /// For example, “Gate changed to %@”.
    ///
    /// You must provide a value for the system to show a change notification.
    ///
    /// This field isn’t used for watchOS.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub change_message: Option<String>,

    /// The currency code to use for the value of the field.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency_code: Option<String>,

    /// The data detectors to apply to the value of a field on the back of the pass.
    ///
    /// The default is to apply all data detectors. To use no data detectors, specify an empty array.
    ///
    /// You don’t use data detectors for fields on the front of the pass.
    ///
    /// This field isn’t used for watchOS.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_detector_types: Option<DetectorType>,

    /// The style of the date to display in the field.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date_style: Option<DateStyle>,

    /// A Boolean value that controls the time zone for the time and date to display in the field.
    ///
    /// The default value is false, which displays the time and date using the current device’s time zone.
    /// Otherwise, the time and date appear in the time zone associated with the date and time of value.
    ///
    /// This key doesn’t affect the pass relevance calculation.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ignores_time_zone: Option<bool>,

    /// A Boolean value that controls whether the date appears as a relative date.\
    ///
    /// The default value is false, which displays the date as an absolute date.
    ///
    /// This key doesn’t affect the pass relevance calculation.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_relative: Option<bool>,

    /// The text for a field label.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,

    /// The style of the number to display in the field.
    ///
    /// Formatter styles have the same meaning as the formats with corresponding names in NumberFormatter.Style.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub number_style: Option<NumberStyle>,

    /// The alignment for the content of a field. The default is natural alignment, which aligns the text based on its script direction.
    ///
    /// This key is invalid for primary and back fields.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_alignment: Option<TextAlignment>,

    /// The style of the time displayed in the field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_style: Option<DateStyle>,

    /// Semantic tags
    ///
    /// Metadata the system uses to offer a pass and suggest related actions.
    #[serde(default)]
    #[serde(skip_serializing_if = "SemanticTags::is_empty")]
    pub semantics: SemanticTags,
}

impl Default for ContentOptions {
    /// Creates an empty `FieldContentOptions`.
    fn default() -> Self {
        Self {
            attributed_value: None,
            change_message: None,
            currency_code: None,
            data_detector_types: None,
            date_style: None,
            ignores_time_zone: None,
            is_relative: None,
            label: None,
            number_style: None,
            text_alignment: None,
            time_style: None,
            semantics: SemanticTags::default(),
        }
    }
}

/// The data detectors to apply to the value of a field on the back of the pass.
#[derive(Serialize, Deserialize, Debug)]
pub enum DetectorType {
    #[serde(rename = "PKDataDetectorTypePhoneNumber")]
    PhoneNumber,
    #[serde(rename = "PKDataDetectorTypeLink")]
    Link,
    #[serde(rename = "PKDataDetectorTypeAddress")]
    Address,
    #[serde(rename = "PKDataDetectorTypeCalendarEvent")]
    CalendarEvent,
}

/// The style of the date to display in the field.
#[derive(Serialize, Deserialize, Debug)]
pub enum DateStyle {
    #[serde(rename = "PKDateStyleNone")]
    None,
    #[serde(rename = "PKDateStyleShort")]
    Short,
    #[serde(rename = "PKDateStyleMedium")]
    Medium,
    #[serde(rename = "PKDateStyleLong")]
    Long,
    #[serde(rename = "PKDateStyleFull")]
    Full,
}

/// The style of the number to display in the field.
#[derive(Serialize, Deserialize, Debug)]
pub enum NumberStyle {
    #[serde(rename = "PKNumberStyleDecimal")]
    Decimal,
    #[serde(rename = "PKNumberStylePercent")]
    Percent,
    #[serde(rename = "PKNumberStyleScientific")]
    Scientific,
    #[serde(rename = "PKNumberStyleSpellOut")]
    SpellOut,
}

/// The alignment for the content of a field.
#[derive(Serialize, Deserialize, Debug)]
pub enum TextAlignment {
    #[serde(rename = "PKTextAlignmentLeft")]
    Left,
    #[serde(rename = "PKTextAlignmentCenter")]
    Center,
    #[serde(rename = "PKTextAlignmentRight")]
    Right,
    #[serde(rename = "PKTextAlignmentNatural")]
    Natural,
}

/// Groups of fields that display information on the front and back of a pass.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub enum Type {
    /// Represents the groups of fields that display the information for a boarding pass.
    BoardingPass {
        /// Groups of fields that display information on the front and back of a pass.
        #[serde(flatten)]
        pass_fields: Fields,

        /// (Required) The type of transit for a boarding pass. This key is invalid for other types of passes.
        #[serde(rename = "transitType")]
        transit_type: TransitType,
    },
    /// Represents the groups of fields that display the information for a coupon.
    Coupon {
        /// Groups of fields that display information on the front and back of a pass.
        #[serde(flatten)]
        pass_fields: Fields,
    },
    /// Represents the groups of fields that display the information for an event ticket.
    EventTicket {
        /// Groups of fields that display information on the front and back of a pass.
        #[serde(flatten)]
        pass_fields: Fields,
    },
    /// Represents the groups of fields that display the information for an event ticket.
    StoreCard {
        /// Groups of fields that display information on the front and back of a pass.
        #[serde(flatten)]
        pass_fields: Fields,
    },
    /// Represents the groups of fields that display the information for a generic pass.
    Generic {
        /// Groups of fields that display information on the front and back of a pass.
        #[serde(flatten)]
        pass_fields: Fields,
    },
}

/// The type of transit for a boarding pass.
#[derive(Serialize, Deserialize, Debug)]
pub enum TransitType {
    #[serde(rename = "PKTransitTypeAir")]
    Air,
    #[serde(rename = "PKTransitTypeBoat")]
    Boat,
    #[serde(rename = "PKTransitTypeBus")]
    Bus,
    #[serde(rename = "PKTransitTypeGeneric")]
    Generic,
    #[serde(rename = "PKTransitTypeTrain")]
    Train,
}

impl Type {
    /// Add field that display additional information on the front of a pass.
    #[must_use]
    pub fn add_auxiliary_field(mut self, field: Content) -> Self {
        match self {
            Self::BoardingPass {
                ref mut pass_fields,
                transit_type: _,
            }
            | Self::Coupon {
                ref mut pass_fields,
            }
            | Self::EventTicket {
                ref mut pass_fields,
            }
            | Self::StoreCard {
                ref mut pass_fields,
            }
            | Self::Generic {
                ref mut pass_fields,
            } => pass_fields
                .auxiliary_fields
                .get_or_insert_default()
                .push(field),
        }
        self
    }

    /// Add field that display information on the back of a pass.
    #[must_use]
    pub fn add_back_field(mut self, field: Content) -> Self {
        match self {
            Self::BoardingPass {
                ref mut pass_fields,
                transit_type: _,
            }
            | Self::Coupon {
                ref mut pass_fields,
            }
            | Self::EventTicket {
                ref mut pass_fields,
            }
            | Self::StoreCard {
                ref mut pass_fields,
            }
            | Self::Generic {
                ref mut pass_fields,
            } => pass_fields.back_fields.get_or_insert_default().push(field),
        }
        self
    }

    /// Add field that display information at the top of a pass.
    #[must_use]
    pub fn add_header_field(mut self, field: Content) -> Self {
        match self {
            Self::BoardingPass {
                ref mut pass_fields,
                transit_type: _,
            }
            | Self::Coupon {
                ref mut pass_fields,
            }
            | Self::EventTicket {
                ref mut pass_fields,
            }
            | Self::StoreCard {
                ref mut pass_fields,
            }
            | Self::Generic {
                ref mut pass_fields,
            } => pass_fields
                .header_fields
                .get_or_insert_default()
                .push(field),
        }
        self
    }

    /// Add field that display the most important information on a pass.
    #[must_use]
    pub fn add_primary_field(mut self, field: Content) -> Self {
        match self {
            Self::BoardingPass {
                ref mut pass_fields,
                transit_type: _,
            }
            | Self::Coupon {
                ref mut pass_fields,
            }
            | Self::EventTicket {
                ref mut pass_fields,
            }
            | Self::StoreCard {
                ref mut pass_fields,
            }
            | Self::Generic {
                ref mut pass_fields,
            } => pass_fields.primary_fields.push(field),
        }
        self
    }

    /// Add field that display supporting information on the front of a pass.
    #[must_use]
    pub fn add_secondary_field(mut self, field: Content) -> Self {
        match self {
            Self::BoardingPass {
                ref mut pass_fields,
                transit_type: _,
            }
            | Self::Coupon {
                ref mut pass_fields,
            }
            | Self::EventTicket {
                ref mut pass_fields,
            }
            | Self::StoreCard {
                ref mut pass_fields,
            }
            | Self::Generic {
                ref mut pass_fields,
            } => pass_fields
                .secondary_fields
                .get_or_insert_default()
                .push(field),
        }
        self
    }
}

#[cfg(test)]
mod tests {
    use crate::pass::semantic_tags::SemanticTagSeat;

    use super::*;

    #[test]
    fn make_pass() {
        // Serialization test
        let pass = Type::Generic {
            pass_fields: Fields {
                ..Default::default()
            },
        };

        let json = serde_json::to_string_pretty(&pass).unwrap();

        println!("{json}");

        let json_expected = r#"{
  "generic": {
    "primaryFields": []
  }
}"#;
        assert_eq!(json_expected, json);

        // Deserialization test
        let pass: Type = serde_json::from_str(json_expected).unwrap();
        let json = serde_json::to_string_pretty(&pass).unwrap();
        assert_eq!(json_expected, json);
    }

    #[test]
    fn make_boarding_pass() {
        // Serialization test
        let boarding_pass = Type::BoardingPass {
            pass_fields: Fields {
                ..Default::default()
            },
            transit_type: TransitType::Air,
        }
        .add_primary_field(Content::new(
            "title",
            "Airplane Ticket",
            ContentOptions::default(),
        ))
        .add_primary_field(Content::new(
            "seat",
            "12",
            ContentOptions {
                semantics: SemanticTags {
                    seats: vec![SemanticTagSeat {
                        seat_number: String::from("12").into(),
                        seat_row: String::from("5A").into(),
                        seat_section: String::from("A").into(),
                        ..Default::default()
                    }],
                    ..Default::default()
                },
                label: String::from("Seat").into(),
                ..Default::default()
            },
        ))
        .add_header_field(Content::new("company", "DAL", ContentOptions::default()))
        .add_header_field(Content::new(
            "company_sub",
            "Dodo Air Lines",
            ContentOptions::default(),
        ))
        .add_secondary_field(Content::new(
            "description",
            "Some information here",
            ContentOptions::default(),
        ));

        let json = serde_json::to_string_pretty(&boarding_pass).unwrap();

        println!("{json}");

        let json_expected = r#"{
  "boardingPass": {
    "headerFields": [
      {
        "key": "company",
        "value": "DAL"
      },
      {
        "key": "company_sub",
        "value": "Dodo Air Lines"
      }
    ],
    "primaryFields": [
      {
        "key": "title",
        "value": "Airplane Ticket"
      },
      {
        "key": "seat",
        "value": "12",
        "label": "Seat",
        "semantics": {
          "seats": [
            {
              "seatNumber": "12",
              "seatRow": "5A",
              "seatSection": "A"
            }
          ]
        }
      }
    ],
    "secondaryFields": [
      {
        "key": "description",
        "value": "Some information here"
      }
    ],
    "transitType": "PKTransitTypeAir"
  }
}"#;
        assert_eq!(json_expected, json);

        // Deserialization test
        let boarding_pass: Type = serde_json::from_str(json_expected).unwrap();
        let json = serde_json::to_string_pretty(&boarding_pass).unwrap();
        assert_eq!(json_expected, json);
    }

    #[test]
    fn make_event_ticket() {
        // Serialization test
        let event_ticket = Type::EventTicket {
            pass_fields: Fields {
                ..Default::default()
            },
        }
        .add_primary_field(Content::new(
            "title",
            "Super Ticket",
            ContentOptions {
                label: String::from("NAME").into(),
                ..Default::default()
            },
        ))
        .add_primary_field(Content::new("seat", "12", ContentOptions::default()))
        .add_header_field(Content::new(
            "event_title",
            "KKK",
            ContentOptions::default(),
        ))
        .add_header_field(Content::new("some", "123", ContentOptions::default()))
        .add_secondary_field(Content::new(
            "description",
            "Some information here",
            ContentOptions::default(),
        ));

        let json = serde_json::to_string_pretty(&event_ticket).unwrap();

        println!("{json}");

        let json_expected = r#"{
  "eventTicket": {
    "headerFields": [
      {
        "key": "event_title",
        "value": "KKK"
      },
      {
        "key": "some",
        "value": "123"
      }
    ],
    "primaryFields": [
      {
        "key": "title",
        "value": "Super Ticket",
        "label": "NAME"
      },
      {
        "key": "seat",
        "value": "12"
      }
    ],
    "secondaryFields": [
      {
        "key": "description",
        "value": "Some information here"
      }
    ]
  }
}"#;
        assert_eq!(json_expected, json);

        // Deserialization test
        let event_ticket: Type = serde_json::from_str(json_expected).unwrap();
        let json = serde_json::to_string_pretty(&event_ticket).unwrap();
        assert_eq!(json_expected, json);
    }
}