liveactivity 0.1.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
//! Layout activities on Android, on liveupdate: liveupdate keeps the lifecycle, the receipts and the notification
//! of each schema-v2 request that `android_layout` projects, and a store of the backend keeps what liveupdate does
//! not, the layout request and its latest snapshot, under liveupdate's id. Taps come from liveupdate's events.

use super::{
    convert as android_liveupdate,
    layout::{self as android_layout, Environment},
};
use crate::{
    ActionEvent, Backend, EndPolicy, Error, LayoutActivityRecord, LayoutEndInput, LayoutSnapshot,
    LayoutStartInput, LayoutUpdateInput, Result, Visibility,
    layout::{AndroidVisibility, Element, Node},
};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fs, io::Read, path::PathBuf, sync::Mutex};

/// liveupdate draws app files of at most this many pixels a side and bytes.
const MAX_ICON_SIDE: u32 = 1024;
const MAX_ICON_BYTES: u64 = 1_048_576;
/// The store's entry of a start before liveupdate has answered, under the activity key.
const PENDING: &str = "pending:";

/// What the backend keeps of a layout activity.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Entry {
    pub(crate) origin: LayoutStartInput,
    pub(crate) snapshot: LayoutSnapshot,
    /// The projection's `degradedFeatures`.
    pub(crate) degraded: Vec<String>,
}

/// The entries by liveupdate id, and by `pending:<key>` while a start is under way.
pub(crate) type Entries = BTreeMap<String, Entry>;

/// Durable storage of the entries.
pub(crate) trait Store: Send + Sync {
    fn load(&self) -> Result<Entries>;
    fn save(&self, entries: &Entries) -> Result<()>;
}

/// The entries as one JSON file, replaced whole.
pub(crate) struct FileStore {
    pub(crate) path: PathBuf,
}

impl Store for FileStore {
    fn load(&self) -> Result<Entries> {
        match fs::read(&self.path) {
            Ok(bytes) => serde_json::from_slice(&bytes).map_err(|_| Error::native()),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Entries::new()),
            Err(_) => Err(Error::native()),
        }
    }

    fn save(&self, entries: &Entries) -> Result<()> {
        let bytes = serde_json::to_vec(entries).map_err(|_| Error::native())?;
        let written = self.path.with_extension("json.new");
        if let Some(folder) = self.path.parent() {
            fs::create_dir_all(folder).map_err(|_| Error::native())?;
        }
        fs::write(&written, bytes)
            .and_then(|()| fs::rename(&written, &self.path))
            .map_err(|_| Error::native())
    }
}

/// The app around the projection: its name, the Now Bar option and the app's files folder.
pub(crate) struct Settings {
    pub(crate) app_name: String,
    pub(crate) samsung_now_bar: bool,
    pub(crate) files: Option<PathBuf>,
    /// Where `write_image` puts pictures, under the app's files.
    pub(crate) image_folder: String,
}

pub(crate) struct Layouts<D: liveupdate::Driver, S: Store> {
    settings: Settings,
    store: S,
    /// The store's entries change only under this lock, around the liveupdate call they follow.
    lock: Mutex<()>,
    _driver: std::marker::PhantomData<D>,
}

impl<D: liveupdate::Driver, S: Store> Layouts<D, S> {
    pub(crate) fn new(settings: Settings, store: S) -> Self {
        Self {
            settings,
            store,
            lock: Mutex::new(()),
            _driver: std::marker::PhantomData,
        }
    }

    pub(crate) fn start(
        &self,
        updates: &liveupdate::LiveUpdate<D>,
        input: LayoutStartInput,
    ) -> Result<LayoutActivityRecord> {
        // Android has no pushes: what the start asks of them is dropped here, so that it is no part of the request
        // the activity keeps and a repeated start is compared without it.
        let input = LayoutStartInput {
            push: None,
            ..input
        };
        let _guard = self.lock.lock().map_err(|_| Error::native())?;
        let (mut entries, records) = self.reconciled(updates)?;
        // liveupdate compares the projections; two starts that project the same may still differ.
        let conflicting = records
            .iter()
            .filter(|record| running(record))
            .any(|record| {
                entries.get(&record.id).is_some_and(|entry| {
                    entry.origin.activity_key == input.activity_key && entry.origin != input
                })
            });
        if conflicting {
            return Err(Error::new(
                "CONFLICT",
                "a running activity of this key started with another request",
            ));
        }
        let template = android_layout::template(&input.layout);
        let projection = self.project(&input, &input.snapshot, template);
        let request = liveupdate::StartRequest {
            activity_key: input.activity_key.clone(),
            schema_version: 2,
            template,
            fallback: android_liveupdate::fallback(input.fallback),
            visibility: visibility(&input),
            snapshot: projection.snapshot,
        };
        let pending = format!("{PENDING}{}", input.activity_key);
        let entry = Entry {
            origin: input.clone(),
            snapshot: input.snapshot.clone(),
            degraded: projection.degraded,
        };
        entries.insert(pending.clone(), entry.clone());
        self.store.save(&entries)?;
        // A refusal leaves the pending entry: the next reconciliation adopts it when liveupdate posted the activity
        // after all (an answer lost on the way back), and drops it otherwise.
        let record = updates.start(request).map_err(android_liveupdate::error)?;
        entries.remove(&pending);
        // The same start again answers the running activity, whose entry has the latest values.
        let entry = entries.entry(record.id.clone()).or_insert(entry).clone();
        self.store.save(&entries)?;
        Ok(layout_record(&record, &entry))
    }

    pub(crate) fn update(
        &self,
        updates: &liveupdate::LiveUpdate<D>,
        input: LayoutUpdateInput,
    ) -> Result<LayoutActivityRecord> {
        let _guard = self.lock.lock().map_err(|_| Error::native())?;
        let (mut entries, records) = self.reconciled(updates)?;
        let record = self.replace(updates, &mut entries, &records, &input.id, input.snapshot)?;
        let entry = entries.get(&input.id).ok_or_else(not_found)?;
        Ok(layout_record(&record, entry))
    }

    pub(crate) fn end(
        &self,
        updates: &liveupdate::LiveUpdate<D>,
        input: LayoutEndInput,
    ) -> Result<LayoutActivityRecord> {
        let _guard = self.lock.lock().map_err(|_| Error::native())?;
        let (mut entries, records) = self.reconciled(updates)?;
        if !entries.contains_key(&input.id) {
            return Err(not_found());
        }
        if let EndPolicy::After { .. } = input.policy {
            return Err(Error::new(
                "UNSUPPORTED_FEATURE",
                "Android does not support delayed activity dismissal",
            ));
        }
        if let Some(snapshot) = input.snapshot {
            self.replace(updates, &mut entries, &records, &input.id, snapshot)?;
        }
        let record = updates
            .end(&input.id, android_liveupdate::end_policy(input.policy))
            .map_err(android_liveupdate::error)?;
        let entry = entries.get(&input.id).ok_or_else(not_found)?;
        Ok(layout_record(&record, entry))
    }

    pub(crate) fn list(
        &self,
        updates: &liveupdate::LiveUpdate<D>,
    ) -> Result<Vec<LayoutActivityRecord>> {
        let _guard = self.lock.lock().map_err(|_| Error::native())?;
        let (entries, records) = self.reconciled(updates)?;
        Ok(records
            .iter()
            .filter_map(|record| {
                entries
                    .get(&record.id)
                    .map(|entry| layout_record(record, entry))
            })
            .collect())
    }

    /// The taps in liveupdate's queue, as the backend passes them on: with the activity's key, and without the taps
    /// on action ids that the activity's layout never declared. Dismissals need nothing: the list reconciles.
    pub(crate) fn taps(&self, updates: &liveupdate::LiveUpdate<D>) -> Result<Vec<ActionEvent>> {
        // The entries are read before the queue is drained, under the lock, so that a start settles first and a
        // tap on its activity finds the entry; a store that cannot be read loses no tap, only the keys.
        let _guard = self.lock.lock().map_err(|_| Error::native())?;
        let entries = self.store.load().unwrap_or_default();
        let batch = updates.events().map_err(android_liveupdate::error)?;
        Ok(batch
            .events
            .into_iter()
            .filter_map(|event| match event.kind {
                liveupdate::EventKind::Action { action_id } => {
                    let entry = entries.get(&event.activity_id);
                    if entry.is_some_and(|entry| {
                        !declares(&entry.origin.layout.lock_screen, &action_id)
                    }) {
                        return None;
                    }
                    Some(ActionEvent {
                        action_id,
                        activity_key: entry.map(|entry| entry.origin.activity_key.clone()),
                        activity_id: event.activity_id,
                    })
                }
                _ => None,
            })
            .collect())
    }

    /// Checks `snapshot` as an update of the activity `id` and sends it, keeping it in the store.
    fn replace(
        &self,
        updates: &liveupdate::LiveUpdate<D>,
        entries: &mut Entries,
        records: &[liveupdate::ActivityRecord],
        id: &str,
        snapshot: LayoutSnapshot,
    ) -> Result<liveupdate::ActivityRecord> {
        let entry = entries.get(id).ok_or_else(not_found)?;
        entry.origin.validate_update(&LayoutUpdateInput {
            id: id.to_owned(),
            snapshot: snapshot.clone(),
        })?;
        let current = records
            .iter()
            .find(|record| record.id == id && running(record))
            .ok_or_else(not_found)?;
        if snapshot.revision < entry.snapshot.revision {
            return Err(Error::new(
                "STALE_REVISION",
                "the revision is below the accepted one",
            ));
        }
        if snapshot.revision == entry.snapshot.revision {
            return if snapshot == entry.snapshot {
                Ok(current.clone())
            } else {
                Err(Error::new(
                    "CONFLICT",
                    "the accepted revision has other values",
                ))
            };
        }
        let projection = self.project(&entry.origin, &snapshot, current.template);
        let record = updates
            .update(id, projection.snapshot)
            .map_err(android_liveupdate::error)?;
        let entry = Entry {
            origin: entry.origin.clone(),
            snapshot,
            degraded: projection.degraded,
        };
        entries.insert(id.to_owned(), entry);
        self.store.save(entries)?;
        Ok(record)
    }

    /// liveupdate's schema-v2 records and the entries of the activities it keeps; the store forgets the others. A
    /// pending entry whose start liveupdate took before the backend could note it is adopted under its id; any other
    /// pending entry is from a start that never got an answer.
    fn reconciled(
        &self,
        updates: &liveupdate::LiveUpdate<D>,
    ) -> Result<(Entries, Vec<liveupdate::ActivityRecord>)> {
        let records: Vec<_> = updates
            .list()
            .map_err(android_liveupdate::error)?
            .into_iter()
            .filter(|record| record.schema_version == 2)
            .collect();
        let stored = self.store.load()?;
        let entries: Entries = records
            .iter()
            .filter_map(|record| {
                let pending = || {
                    running(record)
                        .then(|| stored.get(&format!("{PENDING}{}", record.activity_key)))
                        .flatten()
                };
                stored
                    .get(&record.id)
                    .or_else(pending)
                    .map(|entry| (record.id.clone(), entry.clone()))
            })
            .collect();
        if entries != stored {
            self.store.save(&entries)?;
        }
        Ok((entries, records))
    }

    fn project(
        &self,
        input: &LayoutStartInput,
        snapshot: &LayoutSnapshot,
        template: liveupdate::Template,
    ) -> android_layout::Projection {
        let image = |name: &str| self.image(name);
        let environment = Environment {
            app_name: &self.settings.app_name,
            samsung_now_bar: self.settings.samsung_now_bar,
            image: &image,
        };
        android_layout::project(
            &input.layout,
            input.styles.is_some(),
            snapshot,
            template,
            &environment,
        )
    }

    /// The app-file path of a picture `write_image` wrote, when liveupdate can draw it.
    fn image(&self, name: &str) -> Option<String> {
        let folder = &self.settings.image_folder;
        let path = self.settings.files.as_ref()?.join(folder).join(name);
        let metadata = fs::metadata(&path).ok()?;
        if !metadata.is_file() || metadata.len() > MAX_ICON_BYTES {
            return None;
        }
        let (width, height) = png_size(&path)?;
        (1..=MAX_ICON_SIDE).contains(&width).then_some(())?;
        (1..=MAX_ICON_SIDE).contains(&height).then_some(())?;
        Some(format!("{folder}/{name}"))
    }
}

/// The width and height of a PNG, from its IHDR chunk.
fn png_size(path: &std::path::Path) -> Option<(u32, u32)> {
    let mut header = [0_u8; 24];
    fs::File::open(path).ok()?.read_exact(&mut header).ok()?;
    if header[..8] != *b"\x89PNG\r\n\x1a\n" || header[12..16] != *b"IHDR" {
        return None;
    }
    let width = u32::from_be_bytes(header[16..20].try_into().ok()?);
    let height = u32::from_be_bytes(header[20..24].try_into().ok()?);
    Some((width, height))
}

/// Whether a button of the tree has `action_id`.
fn declares(node: &Node, action_id: &str) -> bool {
    match &node.element {
        Element::Button {
            action_id: id,
            child,
        } => id == action_id || declares(child, action_id),
        Element::Vstack { children, .. }
        | Element::Hstack { children, .. }
        | Element::Zstack { children, .. } => {
            children.iter().any(|child| declares(child, action_id))
        }
        _ => false,
    }
}

fn running(record: &liveupdate::ActivityRecord) -> bool {
    !matches!(
        record.state,
        liveupdate::ActivityState::Ended | liveupdate::ActivityState::Dismissed
    )
}

fn visibility(input: &LayoutStartInput) -> liveupdate::Visibility {
    match input.android.as_ref().map(|android| android.visibility) {
        Some(AndroidVisibility::Public) => liveupdate::Visibility::Public,
        Some(AndroidVisibility::Secret) => liveupdate::Visibility::Secret,
        _ => liveupdate::Visibility::Private,
    }
}

fn layout_record(record: &liveupdate::ActivityRecord, entry: &Entry) -> LayoutActivityRecord {
    LayoutActivityRecord {
        id: record.id.clone(),
        activity_key: record.activity_key.clone(),
        schema_version: 2,
        snapshot: entry.snapshot.clone(),
        backend: Backend::AndroidNotification,
        state: android_liveupdate::activity_state(record.state),
        visibility: Visibility::Unknown,
        degraded_features: record
            .degraded_features
            .iter()
            .chain(&entry.degraded)
            .cloned()
            .collect(),
        promotion_requested: record.promotion_requested,
        promotion_state: android_liveupdate::promotion_state(record.promotion_state),
    }
}

fn not_found() -> Error {
    Error::new("NOT_FOUND", "no layout activity has this id")
}

#[cfg(test)]
#[path = "layouts_tests.rs"]
mod tests;