use super::{
convert as android_liveupdate,
layout::{self as android_layout, Environment},
};
use crate::{
ActionEvent, Backend, EndPolicy, Error, Event, HandledEvent, LayoutActivityRecord,
LayoutEndInput, LayoutSnapshot, LayoutStartInput, LayoutUpdateInput, OpenedEvent, Result,
UnknownEvent, Visibility,
layout::{Alert, AndroidOptions, AndroidPlacement, AndroidVisibility},
};
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
fs,
io::Read,
path::PathBuf,
sync::{Mutex, MutexGuard, PoisonError},
};
const MAX_ICON_SIDE: u32 = 1024;
const MAX_ICON_BYTES: u64 = 1_048_576;
const PENDING: &str = "pending:";
const ALERT: &str = "alert";
const ALERT_SOUND: &str = "alert.sound";
const PUBLIC_VERSION: &str = "publicVersion";
const ACTIONS_KEPT: usize = 32;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Entry {
pub(crate) origin: LayoutStartInput,
pub(crate) snapshot: LayoutSnapshot,
pub(crate) degraded: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) actions: Vec<String>,
}
pub(crate) type Entries = BTreeMap<String, Entry>;
pub(crate) trait Store: Send + Sync {
fn load(&self) -> Result<Entries>;
fn save(&self, entries: &Entries) -> Result<()>;
}
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())
}
}
pub(crate) struct Settings {
pub(crate) app_name: String,
pub(crate) samsung_now_bar: bool,
pub(crate) files: Option<PathBuf>,
pub(crate) image_folder: String,
}
pub(crate) struct Layouts<D: liveupdate::Driver, S: Store> {
settings: Settings,
store: S,
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,
}
}
fn guard(&self) -> MutexGuard<'_, ()> {
self.lock.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn start(
&self,
updates: &liveupdate::LiveUpdate<D>,
input: LayoutStartInput,
) -> Result<LayoutActivityRecord> {
let input = LayoutStartInput {
push: None,
ios: None,
snapshot: for_android(input.snapshot),
android: input.android.map(by_default),
..input
};
let _guard = self.guard();
let (mut entries, records) = self.reconciled(updates)?;
let under_the_key = records
.iter()
.filter(|record| running(record))
.find_map(|record| {
let entry = entries.get(&record.id)?;
(entry.origin.activity_key == input.activity_key).then_some((record, entry))
});
if under_the_key.is_some_and(|(_, entry)| !same_start(&entry.origin, &input)) {
return Err(Error::new(
"CONFLICT",
"a running activity of this key started with another request",
));
}
let input = match under_the_key {
Some((record, entry)) if record.state == liveupdate::ActivityState::Scheduled => {
return waiting(updates, record, entry);
}
Some((record, entry)) if record.state != liveupdate::ActivityState::Unknown => {
return Ok(layout_record(record, entry));
}
Some((_, entry)) => LayoutStartInput {
scheduled: entry.origin.scheduled.clone(),
..input
},
None => input,
};
let mut offered = Offered::of(updates);
let begins = input.scheduled.as_ref();
let alert = begins.map(|scheduled| &scheduled.alert);
if begins.is_some() && placement(&input) == liveupdate::Placement::Foreground {
return Err(Error::unsupported_feature(
"A service holds a notification that is there: a scheduled start takes no foreground placement",
));
}
let pending = format!("{PENDING}{}", input.activity_key);
let mut links = true;
let (record, entry) = loop {
let projection = self.sent(&mut offered, &input, &input.snapshot, alert, links)?;
let retry = links && unlinked(&input.snapshot, &projection.snapshot);
let template = projection
.snapshot
.template()
.map_err(android_liveupdate::error)?;
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,
placement: placement(&input),
start_at: begins.map(|scheduled| scheduled.at),
};
let entry = Entry {
origin: input.clone(),
snapshot: input.snapshot.clone(),
degraded: projection.degraded,
actions: with_actions(Vec::new(), &input.snapshot),
};
entries.insert(pending.clone(), entry.clone());
self.store.save(&entries)?;
match updates.start(request) {
Ok(record) => break (record, entry),
Err(error) if retry && refuses_links(&error) => links = false,
Err(error) => return Err(android_liveupdate::error(error)),
}
};
entries.remove(&pending);
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.guard();
let (mut entries, records) = self.reconciled(updates)?;
let alert = input.alert.as_ref();
let snapshot = for_android(input.snapshot);
let record = self.replace(updates, &mut entries, &records, &input.id, snapshot, alert)?;
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.guard();
let (mut entries, records) = self.reconciled(updates)?;
let entry = entries.get(&input.id).ok_or_else(not_found)?;
let state = records
.iter()
.find(|record| record.id == input.id && running(record))
.map(|record| record.state);
let waits = state == Some(liveupdate::ActivityState::Scheduled);
let live = state.is_some() && !waits;
let last = input.snapshot.filter(|_| state.is_some()).map(for_android);
if let Some(snapshot) = &last {
fits(entry, &input.id, snapshot)?;
}
let last = last.filter(|_| live);
let delayed = matches!(input.policy, EndPolicy::After { .. });
if delayed && live && !Offered::of(updates).get()?.delayed_end {
return Err(Error::unsupported_feature(
"This device removes an ended activity at once",
));
}
if let Some(snapshot) = last {
self.replace(updates, &mut entries, &records, &input.id, snapshot, None)?;
}
let policy = if waits {
EndPolicy::Default {}
} else {
input.policy
};
let record = updates
.end(&input.id, android_liveupdate::end_policy(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.guard();
let (entries, records) = self.reconciled(updates)?;
Ok(records
.iter()
.filter_map(|record| {
entries
.get(&record.id)
.map(|entry| layout_record(record, entry))
})
.collect())
}
pub(crate) fn events(&self, updates: &liveupdate::LiveUpdate<D>) -> Result<Vec<Event>> {
let _guard = self.guard();
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| {
let entry = entries.get(&event.activity_id);
let activity_key = entry.map(|entry| entry.origin.activity_key.clone());
match event.kind {
liveupdate::EventKind::Action { action_id } => {
if entry.is_some_and(|entry| !declares(entry, &action_id)) {
return None;
}
let on = entry.and_then(|entry| asked_for(entry, &action_id));
Some(Event::Action(ActionEvent {
activity_key,
on,
tap: stored_tap(event.sequence, event.occurred_at),
..ActionEvent::new(action_id, event.activity_id)
}))
}
liveupdate::EventKind::Opened { action_id } => {
Some(Event::Opened(OpenedEvent {
activity_id: event.activity_id,
activity_key,
action_id,
}))
}
liveupdate::EventKind::Handled { action_id } => {
Some(Event::Handled(HandledEvent {
activity_id: event.activity_id,
activity_key,
action_id,
tap: stored_tap(event.sequence, event.occurred_at),
}))
}
liveupdate::EventKind::Dismissed => None,
liveupdate::EventKind::Pushed {
command,
activity_key,
revision,
code,
} => Some(android_liveupdate::pushed(
event.activity_id,
&command,
activity_key,
revision,
code,
)),
_ => Some(Event::Unknown(UnknownEvent {
activity_id: event.activity_id,
activity_key,
})),
}
})
.collect())
}
fn replace(
&self,
updates: &liveupdate::LiveUpdate<D>,
entries: &mut Entries,
records: &[liveupdate::ActivityRecord],
id: &str,
snapshot: LayoutSnapshot,
alert: Option<&Alert>,
) -> Result<liveupdate::ActivityRecord> {
let entry = entries.get(id).ok_or_else(not_found)?;
fits(entry, id, &snapshot)?;
let current = records
.iter()
.find(|record| record.id == id && running(record))
.ok_or_else(not_found)?;
if current.state == liveupdate::ActivityState::Scheduled {
return Err(Error::new(
"CONFLICT",
"a scheduled activity takes no update before it began",
));
}
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 mut offered = Offered::of(updates);
let mut links = true;
let (record, degraded) = loop {
let projection = self.sent(&mut offered, &entry.origin, &snapshot, alert, links)?;
let retry = links && unlinked(&snapshot, &projection.snapshot);
let style = projection.snapshot.template();
if style.map_err(android_liveupdate::error)? != current.template
&& !offered.get()?.style_change
{
return Err(Error::unsupported_feature(
"This device keeps the notification style an activity shows",
));
}
match updates.update(id, projection.snapshot) {
Ok(record) => break (record, projection.degraded),
Err(error) if retry && refuses_links(&error) => links = false,
Err(error) => return Err(android_liveupdate::error(error)),
}
};
let entry = Entry {
origin: entry.origin.clone(),
actions: with_actions(entry.actions.clone(), &snapshot),
snapshot,
degraded,
};
entries.insert(id.to_owned(), entry);
self.store.save(entries)?;
Ok(record)
}
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 sent(
&self,
offered: &mut Offered<'_, D>,
input: &LayoutStartInput,
snapshot: &LayoutSnapshot,
alert: Option<&Alert>,
links: bool,
) -> Result<android_layout::Projection> {
let shown = self.shown(offered, input, snapshot, links)?;
let presentation = shown.snapshot.presentation.as_ref();
let needed = presentation.map(extensions).unwrap_or_default();
if !needed.is_empty() {
let device = offered.get()?;
if let Some((name, _)) = needed.iter().find(|(_, offers)| !offers(&device)) {
return Err(Error::unsupported_feature(&format!(
"This device does not offer `{name}` of an Android content"
)));
}
}
let asked = alert.is_some() || presentation.is_some_and(|presentation| presentation.alert);
let alerts = asked && offered.get()?.alert;
let sound = alerts && alert.is_some_and(|alert| alert.sound.is_some());
let of_the_start = input
.android
.as_ref()
.and_then(|android| android.public_version.as_ref())
.filter(|_| presentation.is_some_and(|shown| shown.public_version.is_none()));
let public_version = match of_the_start {
Some(version) if offered.get()?.public_version => Some(version.clone()),
_ => None,
};
let unshown = of_the_start.is_some() && public_version.is_none();
let carried = input
.android
.as_ref()
.and_then(|android| android.wear_ongoing_activity)
.unwrap_or(true);
let local = input
.android
.as_ref()
.and_then(|android| android.local_only)
.unwrap_or(false);
Ok(android_layout::Projection {
snapshot: marked(shown.snapshot, alerts, public_version, carried, local),
degraded: shown
.degraded
.into_iter()
.chain((asked && !alerts).then(|| ALERT.to_owned()))
.chain(sound.then(|| ALERT_SOUND.to_owned()))
.chain(unshown.then(|| PUBLIC_VERSION.to_owned()))
.collect(),
})
}
fn shown(
&self,
offered: &mut Offered<'_, D>,
input: &LayoutStartInput,
snapshot: &LayoutSnapshot,
links: bool,
) -> Result<android_layout::Projection> {
match &snapshot.android {
Some(content) => Ok(android_layout::Projection {
snapshot: content.snapshot(snapshot.revision, snapshot.stale_at),
degraded: Vec::new(),
}),
None => {
let projection = self.project(offered, input, snapshot, links)?;
Ok(android_layout::Projection {
snapshot: targeted(projection.snapshot, input),
..projection
})
}
}
}
fn project(
&self,
offered: &mut Offered<'_, D>,
input: &LayoutStartInput,
snapshot: &LayoutSnapshot,
links: bool,
) -> Result<android_layout::Projection> {
let (linked, clocked) = android_layout::could_use(&input.layout);
let device = if (links && linked) || clocked {
offered.get()?
} else {
liveupdate::PresentationCapabilities::default()
};
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,
public: visibility(input) == liveupdate::Visibility::Public,
links: links && device.links,
chronometer: device.chronometer,
};
Ok(android_layout::project(
&input.layout,
input.styles.is_some(),
snapshot,
android_layout::template(&input.layout),
&environment,
))
}
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}"))
}
}
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))
}
type Offer = fn(&liveupdate::PresentationCapabilities) -> bool;
struct Offered<'a, D: liveupdate::Driver> {
updates: &'a liveupdate::LiveUpdate<D>,
known: Option<liveupdate::PresentationCapabilities>,
}
impl<'a, D: liveupdate::Driver> Offered<'a, D> {
fn of(updates: &'a liveupdate::LiveUpdate<D>) -> Self {
Self {
updates,
known: None,
}
}
fn get(&mut self) -> Result<liveupdate::PresentationCapabilities> {
if let Some(known) = self.known {
return Ok(known);
}
let asked = self
.updates
.capabilities()
.map_err(android_liveupdate::error)?
.presentation;
self.known = Some(asked);
Ok(asked)
}
}
fn extensions(presentation: &liveupdate::AndroidPresentation) -> Vec<(&'static str, Offer)> {
let links = presentation.open_url.is_some()
|| presentation
.actions
.iter()
.any(|action| action.open_url.is_some());
let branding = presentation.small_icon.is_some()
|| presentation.accent_color.is_some()
|| presentation.sub_text.is_some();
let used: [(bool, &'static str, Offer); 4] = [
(links, "links", |offered| offered.links),
(
presentation.chronometer.is_some(),
"chronometer",
|offered| offered.chronometer,
),
(
presentation.public_version.is_some(),
"publicVersion",
|offered| offered.public_version,
),
(branding, "branding", |offered| offered.branding),
];
used.into_iter()
.filter(|(used, ..)| *used)
.map(|(_, name, offer)| (name, offer))
.collect()
}
fn marked(
snapshot: liveupdate::Snapshot,
alerts: bool,
public_version: Option<liveupdate::PublicVersion>,
carried: bool,
local: bool,
) -> liveupdate::Snapshot {
liveupdate::Snapshot {
presentation: snapshot
.presentation
.map(|presentation| liveupdate::AndroidPresentation {
alert: alerts,
public_version: presentation.public_version.or(public_version),
wear_ongoing_activity: carried && presentation.wear_ongoing_activity,
local_only: local || presentation.local_only,
..presentation
}),
..snapshot
}
}
fn unlinked(snapshot: &LayoutSnapshot, sent: &liveupdate::Snapshot) -> bool {
snapshot.android.is_none()
&& sent.presentation.as_ref().is_some_and(|shown| {
shown.open_url.is_some() || shown.actions.iter().any(|action| action.open_url.is_some())
})
}
fn refuses_links(error: &liveupdate::Error) -> bool {
matches!(
error.code,
liveupdate::ErrorCode::InvalidInput | liveupdate::ErrorCode::Conflict
)
}
fn by_default(options: AndroidOptions) -> AndroidOptions {
AndroidOptions {
placement: options
.placement
.filter(|placement| *placement != AndroidPlacement::Tagged),
wear_ongoing_activity: options.wear_ongoing_activity.filter(|carried| !carried),
local_only: options.local_only.filter(|local| *local),
..options
}
}
fn placement(input: &LayoutStartInput) -> liveupdate::Placement {
match input.android.as_ref().and_then(|android| android.placement) {
Some(AndroidPlacement::Foreground) => liveupdate::Placement::Foreground,
_ => liveupdate::Placement::Tagged,
}
}
fn fits(entry: &Entry, id: &str, snapshot: &LayoutSnapshot) -> Result<()> {
entry
.origin
.validate_update(&LayoutUpdateInput::new(id, snapshot.clone()))?;
if entry.origin.takes_public_version_of(snapshot) {
Ok(())
} else {
Err(Error::invalid())
}
}
fn for_android(snapshot: LayoutSnapshot) -> LayoutSnapshot {
LayoutSnapshot {
relevance: None,
..snapshot
}
}
fn with_actions(kept: Vec<String>, snapshot: &LayoutSnapshot) -> Vec<String> {
let Some(content) = &snapshot.android else {
return kept;
};
let shown: Vec<&String> = content
.presentation
.actions
.iter()
.map(|action| &action.id)
.collect();
let earlier = kept.into_iter().filter(|id| !shown.contains(&id));
let all: Vec<String> = earlier
.chain(shown.iter().map(|id| (*id).clone()))
.collect();
let surplus = all.len().saturating_sub(ACTIONS_KEPT);
all.into_iter().skip(surplus).collect()
}
fn declares(entry: &Entry, action_id: &str) -> bool {
crate::layout::controls(&entry.origin.layout.lock_screen, action_id)
|| entry.actions.iter().any(|id| id == action_id)
}
fn asked_for(entry: &Entry, action_id: &str) -> Option<bool> {
if entry.snapshot.android.is_some() {
return None;
}
android_layout::asked_for(&entry.origin.layout, &entry.snapshot.values, action_id)
}
fn targeted(snapshot: liveupdate::Snapshot, input: &LayoutStartInput) -> liveupdate::Snapshot {
let Some(targets) = input
.android
.as_ref()
.map(|android| &android.targets)
.filter(|targets| !targets.is_empty())
else {
return snapshot;
};
liveupdate::Snapshot {
presentation: snapshot
.presentation
.map(|presentation| liveupdate::AndroidPresentation {
actions: presentation
.actions
.into_iter()
.map(|action| liveupdate::NotificationAction {
target: action
.open_url
.is_none()
.then(|| targets.get(&action.id).cloned())
.flatten(),
..action
})
.collect(),
..presentation
}),
..snapshot
}
}
fn same_start(kept: &LayoutStartInput, asked: &LayoutStartInput) -> bool {
let asked = LayoutStartInput {
scheduled: kept.scheduled.clone(),
..asked.clone()
};
*kept == asked
}
fn waiting<D: liveupdate::Driver>(
updates: &liveupdate::LiveUpdate<D>,
record: &liveupdate::ActivityRecord,
entry: &Entry,
) -> Result<LayoutActivityRecord> {
let kept = liveupdate::StartRequest {
activity_key: record.activity_key.clone(),
schema_version: 2,
template: record.template,
fallback: android_liveupdate::fallback(entry.origin.fallback),
visibility: visibility(&entry.origin),
snapshot: record.snapshot.clone(),
placement: placement(&entry.origin),
start_at: record.start_at,
};
let record = updates.start(kept).map_err(android_liveupdate::error)?;
Ok(layout_record(&record, entry))
}
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;
pub(crate) fn stored_tap(sequence: u64, occurred_at: u64) -> crate::Tap {
crate::Tap {
id: Some(sequence.to_string()),
at: Some(occurred_at),
..crate::Tap::default()
}
}