liveactivity 0.12.0

Framework-neutral Live Activities: one interface over ActivityKit, Android Live Updates and other backends
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
//! activitykit's `ActivityKit` and `Activity` as the [`Kit`] and [`Handle`] that the backend's logic runs on. Only
//! a device with Live Activities runs these calls; the logic itself is tested on a fake kit.

use super::{
    Acknowledge, Authorization, EndSpec, Handle, Kit, KitEvent, StartSpec, UpdateSpec, action_event,
};
use crate::{
    layout::{Alert, LayoutPush},
    models::EndPolicy,
};
use activitykit::{
    Acknowledgement, Activity, ActivityKit, ChannelId, End, Event, Push, Start, State, Update,
    Values,
};
use std::{
    future::Future,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

/// 9999-12-31T23:59:59.999Z in epoch milliseconds: a cap every platform's `SystemTime` holds.
pub(crate) const LATEST_MILLIS: u64 = 253_402_300_799_999;

/// The time of `millis` epoch milliseconds, clamped to [`LATEST_MILLIS`].
pub(crate) fn time(millis: u64) -> SystemTime {
    UNIX_EPOCH + Duration::from_millis(millis.min(LATEST_MILLIS))
}

/// `at` in epoch milliseconds, when it is after the epoch and fits.
pub(crate) fn millis(at: SystemTime) -> Option<u64> {
    u64::try_from(at.duration_since(UNIX_EPOCH).ok()?.as_millis()).ok()
}

/// activitykit's start, or `INVALID_INPUT` for a channel that is no id, which the check of the request keeps out, and
/// for a kind of push that a later activitykit adds and this version cannot start.
pub(crate) fn start_of(spec: StartSpec) -> activitykit::Result<Start> {
    let start = Start::new(spec.layout, spec.values)
        .key(spec.key)
        .revision(spec.revision);
    let start = match spec.stale_at {
        Some(at) => start.stale_at(time(at)),
        None => start,
    };
    let start = match spec.timestamp {
        Some(at) => start.timestamp(time(at)),
        None => start,
    };
    let start = match spec.relevance {
        Some(score) => start.relevance(score),
        None => start,
    };
    let start = if spec.transient {
        start.transient()
    } else {
        start
    };
    let start = match spec.scheduled {
        Some(scheduled) => start.scheduled(time(scheduled.at), alert_of(scheduled.alert)),
        None => start,
    };
    match spec.push {
        Some(LayoutPush::Token) => Ok(start.push(Push::Token)),
        Some(LayoutPush::Channel(id)) => Ok(start.push(Push::Channel(ChannelId::new(id)?))),
        None => Ok(start),
        // A start without the push it asked for would be one the application did not ask for.
        Some(_) => Err(activitykit::Error::InvalidInput(
            "A push of a kind this version cannot start".into(),
        )),
    }
}

pub(crate) fn update_of(spec: UpdateSpec) -> Update {
    let update = Update::new(spec.values).revision(spec.revision);
    let update = match spec.stale_at {
        Some(at) => update.stale_at(time(at)),
        None => update,
    };
    let update = match spec.timestamp {
        Some(at) => update.timestamp(time(at)),
        None => update,
    };
    let update = match spec.relevance {
        Some(score) => update.relevance(score),
        None => update,
    };
    match spec.alert {
        Some(alert) => update.alert(alert_of(alert)),
        None => update,
    }
}

/// activitykit's alert, with its sound when it names one.
fn alert_of(alert: Alert) -> activitykit::Alert {
    let shown = activitykit::Alert::new(alert.title, alert.body);
    match alert.sound {
        Some(name) => shown.sound(name),
        None => shown,
    }
}

pub(crate) fn end_of(spec: EndSpec) -> End {
    let end = match spec.policy {
        EndPolicy::Immediate {} => End::immediately(),
        EndPolicy::Default {} => End::default(),
        EndPolicy::After { at } => End::after(time(at)),
    };
    let end = match spec.values {
        Some(values) => end.values(values),
        None => end,
    };
    let end = match spec.revision {
        Some(revision) => end.revision(revision),
        None => end,
    };
    let end = match spec.stale_at {
        Some(at) => end.stale_at(time(at)),
        None => end,
    };
    let end = match spec.timestamp {
        Some(at) => end.timestamp(time(at)),
        None => end,
    };
    match spec.relevance {
        Some(score) => end.relevance(score),
        None => end,
    }
}

impl Acknowledge for Acknowledgement {
    fn acknowledge(&self) {
        Acknowledgement::acknowledge(self);
    }
}

fn authorization_of(authorization: activitykit::Authorization) -> Authorization {
    Authorization {
        supported: authorization.supported,
        enabled: authorization.enabled,
        buttons: authorization.buttons,
        frequent_pushes: authorization.frequent_pushes,
        later: crate::IosCapabilities {
            push_to_start: authorization.push_to_start,
            push_channels: authorization.push_channels,
            transient: authorization.transient,
            scheduled_start: authorization.scheduled_start,
            small_family: authorization.small_family,
        },
    }
}

/// What activitykit says of a tap, its time in epoch milliseconds.
fn tap_of(tap: &activitykit::Tap) -> crate::Tap {
    crate::Tap {
        id: tap.id.clone(),
        at: tap
            .at
            .and_then(|at| at.duration_since(std::time::UNIX_EPOCH).ok())
            .and_then(|since| u64::try_from(since.as_millis()).ok()),
        revision: tap.revision,
        late: tap.late,
    }
}

/// What the backend takes of one of activitykit's events; the others pass.
fn kit_event(event: Event) -> Option<KitEvent<Activity, Acknowledgement>> {
    match event {
        Event::Action {
            activity,
            action,
            on,
            acknowledgement,
            tap,
            ..
        } => Some(KitEvent::Tap(
            action_event(&activity, action, on, tap_of(&tap)),
            acknowledgement,
        )),
        Event::PushToken {
            activity, token, ..
        } => Some(KitEvent::PushToken {
            activity,
            token: token.to_string(),
        }),
        Event::PushToStartToken { token, .. } => Some(KitEvent::PushToStartToken {
            token: token.to_string(),
        }),
        Event::Updated { activity, .. } => Some(KitEvent::Updated(activity)),
        Event::Started { activity, .. } => Some(KitEvent::Started(activity)),
        Event::State {
            activity, state, ..
        } => Some(KitEvent::State(activity, state)),
        Event::Authorization(authorization) => {
            Some(KitEvent::Authorization(authorization_of(authorization)))
        }
        _ => None,
    }
}

impl Kit for ActivityKit {
    type Handle = Activity;
    type Ack = Acknowledgement;

    fn events(&self) -> Box<dyn Iterator<Item = KitEvent<Activity, Acknowledgement>> + Send> {
        let events = self.events();
        Box::new(std::iter::from_fn(move || {
            loop {
                if let Some(found) = kit_event(events.recv_blocking().ok()?) {
                    return Some(found);
                }
            }
        }))
    }

    fn authorization(&self) -> Authorization {
        authorization_of(ActivityKit::authorization(self))
    }

    async fn start(&self, spec: StartSpec) -> activitykit::Result<Activity> {
        self.start_with(start_of(spec)?).await
    }

    fn activity(
        &self,
        id: &str,
    ) -> impl Future<Output = activitykit::Result<Option<Activity>>> + Send {
        ActivityKit::activity(self, id)
    }

    fn activities(&self) -> impl Future<Output = activitykit::Result<Vec<Activity>>> + Send {
        ActivityKit::activities(self)
    }

    fn write_image(&self, name: &str, png: &[u8]) -> activitykit::Result<()> {
        ActivityKit::write_image(self, name, png)
    }
}

impl Handle for Activity {
    fn id(&self) -> &str {
        Activity::id(self)
    }

    fn key(&self) -> &str {
        Activity::key(self)
    }

    fn state(&self) -> State {
        Activity::state(self)
    }

    fn values(&self) -> Values {
        Activity::values(self)
    }

    fn revision(&self) -> Option<u64> {
        Activity::revision(self)
    }

    fn stale_at(&self) -> Option<u64> {
        Activity::stale_at(self).and_then(millis)
    }

    fn timestamp(&self) -> Option<u64> {
        Activity::timestamp(self).and_then(millis)
    }

    fn relevance(&self) -> f64 {
        Activity::relevance(self)
    }

    fn degraded_features(&self) -> Vec<String> {
        Activity::degraded_features(self)
    }

    fn update(&self, spec: UpdateSpec) -> impl Future<Output = activitykit::Result<()>> + Send {
        self.update_with(update_of(spec))
    }

    fn end(&self, spec: EndSpec) -> impl Future<Output = activitykit::Result<()>> + Send {
        Activity::end(self, end_of(spec))
    }
}

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

    #[test]
    fn req_e_009_a_tap_of_activitykit_says_which_tap_it_is() {
        // REQ-E-009
        let mut tap = activitykit::Tap::default();
        assert_eq!(tap_of(&tap), crate::Tap::default());
        tap.id = Some("tap-7".into());
        tap.at = Some(std::time::UNIX_EPOCH + std::time::Duration::from_millis(1_800_000_000_123));
        tap.revision = Some(3);
        tap.late = true;
        assert_eq!(
            tap_of(&tap),
            crate::Tap {
                id: Some("tap-7".into()),
                at: Some(1_800_000_000_123),
                revision: Some(3),
                late: true,
            }
        );
        // A time before 1970 is no time of a tap.
        tap.at = Some(std::time::UNIX_EPOCH - std::time::Duration::from_secs(1));
        assert_eq!(tap_of(&tap).at, None);
    }

    #[test]
    fn req_i_014_activitykits_authorization_says_the_later_features() {
        // REQ-I-014
        let mut authorization = activitykit::Authorization::default();
        assert_eq!(
            authorization_of(authorization).later,
            crate::IosCapabilities::default()
        );
        authorization.supported = true;
        authorization.push_to_start = true;
        authorization.push_channels = true;
        authorization.transient = true;
        authorization.scheduled_start = true;
        authorization.small_family = true;
        assert_eq!(
            authorization_of(authorization).later,
            crate::IosCapabilities {
                push_to_start: true,
                push_channels: true,
                transient: true,
                scheduled_start: true,
                small_family: true,
            }
        );
    }

    fn debug(value: impl std::fmt::Debug) -> String {
        format!("{value:?}")
    }

    #[test]
    fn specs_reach_activitykit_with_their_revision_times_and_push() {
        let layout = activitykit::Layout::new(activitykit::layout::text("Recording"));
        let values = || Values::from([("level", 0.2)]);
        let spec = |push| StartSpec {
            key: "rec".into(),
            layout: layout.clone(),
            values: values(),
            revision: 5,
            stale_at: Some(1_000),
            timestamp: Some(2_000),
            relevance: Some(80.0),
            push,
            transient: false,
            scheduled: None,
        };
        let expected = Start::new(layout.clone(), values())
            .key("rec")
            .revision(5)
            .stale_at(time(1_000))
            .timestamp(time(2_000))
            .relevance(80.0);
        assert_eq!(
            debug(start_of(spec(None)).unwrap()),
            debug(expected.clone())
        );
        assert_eq!(
            debug(start_of(spec(Some(LayoutPush::Token))).unwrap()),
            debug(expected.push(Push::Token))
        );
        // A channel that is no id never reaches ActivityKit.
        let refused = start_of(spec(Some(LayoutPush::Channel("no id".into())))).unwrap_err();
        assert_eq!(refused.code(), "INVALID_INPUT");
        // REQ-I-006, REQ-I-007: a transient style, and a later time with the alert shown then and its sound.
        let alert = crate::Alert::new("Recording", "It starts now").with_sound("chime.aiff");
        let later = StartSpec {
            transient: true,
            scheduled: Some(crate::ScheduledStart::new(9_000, alert)),
            ..spec(None)
        };
        let shown = activitykit::Alert::new("Recording", "It starts now").sound("chime.aiff");
        let expected = Start::new(layout.clone(), values())
            .key("rec")
            .revision(5)
            .stale_at(time(1_000))
            .timestamp(time(2_000))
            .relevance(80.0)
            .transient()
            .scheduled(time(9_000), shown);
        assert_eq!(debug(start_of(later).unwrap()), debug(expected));

        let update = UpdateSpec {
            values: values(),
            revision: 6,
            stale_at: None,
            timestamp: Some(u64::MAX),
            relevance: Some(20.0),
            alert: Some(crate::Alert::new("Stopped", "Tap to resume")),
        };
        // REQ-I-001, REQ-I-002
        let expected = Update::new(values())
            .revision(6)
            .timestamp(time(LATEST_MILLIS))
            .relevance(20.0)
            .alert(activitykit::Alert::new("Stopped", "Tap to resume"));
        assert_eq!(debug(update_of(update)), debug(expected));
        let silent = UpdateSpec {
            values: values(),
            revision: 7,
            stale_at: None,
            timestamp: None,
            relevance: None,
            alert: None,
        };
        assert_eq!(
            debug(update_of(silent)),
            debug(Update::new(values()).revision(7))
        );
        // REQ-I-007
        let loud = UpdateSpec {
            values: values(),
            revision: 8,
            stale_at: None,
            timestamp: None,
            relevance: None,
            alert: Some(crate::Alert::new("Stopped", "Tap to resume").with_sound("stop.caf")),
        };
        let shown = activitykit::Alert::new("Stopped", "Tap to resume").sound("stop.caf");
        assert_eq!(
            debug(update_of(loud)),
            debug(Update::new(values()).revision(8).alert(shown))
        );

        let end = |policy, values: Option<Values>| EndSpec {
            policy,
            revision: values.as_ref().map(|_| 7),
            values,
            stale_at: None,
            timestamp: None,
            relevance: None,
        };
        assert_eq!(
            end_of(end(EndPolicy::Immediate {}, None)),
            End::immediately()
        );
        assert_eq!(end_of(end(EndPolicy::Default {}, None)), End::default());
        assert_eq!(
            end_of(end(EndPolicy::After { at: 9_000 }, Some(values()))),
            End::after(time(9_000)).values(values()).revision(7)
        );
        let relevant = EndSpec {
            relevance: Some(5.0),
            ..end(EndPolicy::Default {}, None)
        };
        assert_eq!(end_of(relevant), End::default().relevance(5.0));
        assert_eq!(millis(time(1_800_000_000_000)), Some(1_800_000_000_000));
        assert_eq!(millis(UNIX_EPOCH - Duration::from_secs(1)), None);
    }
}