use crate::{
Error, Result,
models::{ActivityState, Backend, EndPolicy, Fallback, PromotionState, Visibility},
validation::{Validate, require, text},
};
use activitykit::contract as wire;
use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
use std::collections::BTreeMap;
pub use activitykit::Value;
pub use activitykit::contract::PushWire as LayoutPush;
pub use activitykit::contract::{Island, IslandExpanded, weight};
pub use activitykit::layout::{
Accessibility, Alignment, Bindable, Bound, ButtonStyle, Color, ColorName, ContentMode,
ContentTransition, Dimension, Element, ExpandedRegion, Font, FontDesign, FontWeight, Frame,
HorizontalAlignment, ImageSource, IndicatorKind, IslandMargins, Node, Padding, Privacy,
RegionPriorities, Style, SymbolRendering, Transition, VerticalAlignment,
};
pub use liveupdate::{
AndroidPresentation, BigTextStyle, IconSource, Metric, MetricStyle, MetricValue,
NotificationAction, PresentationCapabilities, PresentationStyle, ProgressPoint,
ProgressSegment, ProgressStyle, PublicVersion, SamsungNowBar, SemanticStyle, TimerStyle,
};
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AndroidVisibility {
Public,
Private,
Secret,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AndroidPlacement {
Tagged,
Foreground,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AndroidOptions {
pub visibility: AndroidVisibility,
#[serde(default, deserialize_with = "non_null", skip_serializing_if = "none")]
pub public_version: Option<PublicVersion>,
#[serde(default, deserialize_with = "non_null", skip_serializing_if = "none")]
pub placement: Option<AndroidPlacement>,
}
impl AndroidOptions {
pub fn new(visibility: AndroidVisibility) -> Self {
Self {
visibility,
public_version: None,
placement: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AndroidContent {
pub title: String,
pub status: String,
pub presentation: AndroidPresentation,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Alert {
pub title: String,
pub body: String,
}
impl Alert {
pub fn new(title: impl Into<String>, body: impl Into<String>) -> Self {
Self {
title: title.into(),
body: body.into(),
}
}
}
pub type Layout = wire::LayoutRegions;
fn non_null<'de, D: Deserializer<'de>, T: Deserialize<'de>>(
deserializer: D,
) -> std::result::Result<Option<T>, D::Error> {
T::deserialize(deserializer).map(Some)
}
fn none<T>(member: &Option<T>) -> bool {
member.is_none()
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LayoutSnapshot {
pub revision: u64,
pub values: BTreeMap<String, Value>,
#[serde(default, deserialize_with = "non_null", skip_serializing_if = "none")]
pub stale_at: Option<u64>,
#[serde(default, deserialize_with = "non_null", skip_serializing_if = "none")]
pub timestamp: Option<u64>,
#[serde(default, deserialize_with = "non_null", skip_serializing_if = "none")]
pub relevance: Option<f64>,
#[serde(default, deserialize_with = "non_null", skip_serializing_if = "none")]
pub android: Option<AndroidContent>,
}
impl LayoutSnapshot {
pub fn new(revision: u64, values: BTreeMap<String, Value>) -> Self {
Self {
revision,
values,
stale_at: None,
timestamp: None,
relevance: None,
android: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LayoutStartInput {
pub activity_key: String,
pub schema_version: u8,
pub fallback: Fallback,
pub layout: Layout,
#[serde(default, deserialize_with = "non_null", skip_serializing_if = "none")]
pub styles: Option<BTreeMap<String, Style>>,
pub snapshot: LayoutSnapshot,
#[serde(default, deserialize_with = "non_null", skip_serializing_if = "none")]
pub android: Option<AndroidOptions>,
#[serde(default, deserialize_with = "non_null", skip_serializing_if = "none")]
pub push: Option<LayoutPush>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LayoutUpdateInput {
pub id: String,
pub snapshot: LayoutSnapshot,
#[serde(default, deserialize_with = "non_null", skip_serializing_if = "none")]
pub alert: Option<Alert>,
}
impl LayoutStartInput {
pub fn new(activity_key: impl Into<String>, layout: Layout, snapshot: LayoutSnapshot) -> Self {
Self {
activity_key: activity_key.into(),
schema_version: 2,
fallback: Fallback::Notification,
layout,
styles: None,
snapshot,
android: None,
push: None,
}
}
}
impl LayoutEndInput {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
policy: EndPolicy::Default {},
snapshot: None,
}
}
pub fn immediate(id: impl Into<String>) -> Self {
Self {
policy: EndPolicy::Immediate {},
..Self::new(id)
}
}
}
impl LayoutUpdateInput {
pub fn new(id: impl Into<String>, snapshot: LayoutSnapshot) -> Self {
Self {
id: id.into(),
snapshot,
alert: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LayoutEndInput {
pub id: String,
pub policy: EndPolicy,
#[serde(default, deserialize_with = "non_null", skip_serializing_if = "none")]
pub snapshot: Option<LayoutSnapshot>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LayoutActivityRecord {
pub id: String,
pub activity_key: String,
pub schema_version: u8,
pub snapshot: LayoutSnapshot,
pub backend: Backend,
pub state: ActivityState,
pub visibility: Visibility,
pub degraded_features: Vec<String>,
pub promotion_requested: bool,
pub promotion_state: PromotionState,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionEvent {
pub action_id: String,
pub activity_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub activity_key: Option<String>,
}
impl LayoutSnapshot {
fn wire(&self) -> wire::LayoutSnapshot {
wire::LayoutSnapshot {
revision: self.revision,
values: self.values.clone().into(),
stale_at: self.stale_at,
timestamp: self.timestamp,
}
}
}
impl LayoutStartInput {
pub(crate) fn wire(&self) -> wire::LayoutStartInput {
wire::LayoutStartInput {
activity_key: self.activity_key.clone(),
schema_version: self.schema_version,
fallback: match self.fallback {
Fallback::None => wire::Fallback::None,
Fallback::Notification => wire::Fallback::Notification,
},
layout: self.layout.clone(),
styles: self.styles.clone(),
snapshot: self.snapshot.wire(),
android: None,
push: self.push.clone(),
}
}
pub fn validate_update(&self, update: &LayoutUpdateInput) -> Result<()> {
Ok(self.wire().validate_update(&update.wire())?)
}
pub fn validate_end(&self, end: &LayoutEndInput) -> Result<()> {
Ok(self.wire().validate_end(&end.wire())?)
}
}
impl LayoutUpdateInput {
fn wire(&self) -> wire::LayoutUpdateInput {
wire::LayoutUpdateInput {
id: self.id.clone(),
snapshot: self.snapshot.wire(),
}
}
}
impl LayoutEndInput {
fn wire(&self) -> wire::EndInput {
wire::EndInput {
id: self.id.clone(),
policy: match self.policy {
EndPolicy::Immediate {} => wire::EndPolicy::Immediate {},
EndPolicy::Default {} => wire::EndPolicy::Default {},
EndPolicy::After { at } => wire::EndPolicy::After { at },
},
snapshot: self.snapshot.as_ref().map(LayoutSnapshot::wire),
}
}
}
impl AndroidContent {
pub(crate) fn snapshot(&self, revision: u64, stale_at: Option<u64>) -> liveupdate::Snapshot {
liveupdate::Snapshot {
revision,
title: self.title.clone(),
status: self.status.clone(),
progress: None,
timer: None,
stale_at,
presentation: Some(self.presentation.clone()),
}
}
}
impl LayoutSnapshot {
fn beside_the_layout(&self) -> Result<()> {
require(self.relevance.is_none_or(f64::is_finite))?;
match &self.android {
Some(content) => content
.snapshot(self.revision, self.stale_at)
.validate()
.map_err(|_| Error::invalid()),
None => Ok(()),
}
}
}
impl Validate for Alert {
fn validate(&self) -> Result<()> {
require(text(&self.title, 120) && text(&self.body, 240))
}
}
impl Validate for LayoutSnapshot {
fn validate(&self) -> Result<()> {
wire::Validate::validate(&self.wire())?;
self.beside_the_layout()
}
}
pub(crate) const TEMPLATE_MARKER: &str = "liveActivityTemplate";
fn unmarked(snapshot: &LayoutSnapshot) -> Result<()> {
if snapshot.values.contains_key(TEMPLATE_MARKER) {
Err(Error::invalid())
} else {
Ok(())
}
}
impl LayoutStartInput {
pub(crate) fn validate_contract(&self) -> Result<()> {
Ok(wire::Validate::validate(&self.wire())?)
}
}
impl LayoutStartInput {
pub(crate) fn takes_public_version_of(&self, snapshot: &LayoutSnapshot) -> bool {
let private = self
.android
.as_ref()
.is_none_or(|android| android.visibility == AndroidVisibility::Private);
let public_version = snapshot
.android
.as_ref()
.and_then(|content| content.presentation.public_version.as_ref());
private || public_version.is_none()
}
}
impl LayoutStartInput {
fn public_version_of_the_start_fits(&self) -> bool {
let Some(android) = &self.android else {
return true;
};
let Some(public_version) = &android.public_version else {
return true;
};
let bounded = AndroidPresentation {
public_version: Some(public_version.clone()),
..AndroidPresentation::new(PresentationStyle::Standard)
};
android.visibility == AndroidVisibility::Private && bounded.validate().is_ok()
}
}
impl Validate for LayoutStartInput {
fn validate(&self) -> Result<()> {
self.validate_contract()?;
self.snapshot.beside_the_layout()?;
require(self.takes_public_version_of(&self.snapshot))?;
require(self.public_version_of_the_start_fits())?;
unmarked(&self.snapshot)
}
}
impl Validate for LayoutUpdateInput {
fn validate(&self) -> Result<()> {
wire::Validate::validate(&self.wire())?;
self.snapshot.beside_the_layout()?;
self.alert.as_ref().map_or(Ok(()), Validate::validate)?;
unmarked(&self.snapshot)
}
}
impl Validate for LayoutEndInput {
fn validate(&self) -> Result<()> {
wire::Validate::validate(&self.wire())?;
let Some(snapshot) = &self.snapshot else {
return Ok(());
};
snapshot.beside_the_layout()?;
unmarked(snapshot)
}
}
const MAX_NESTING: usize = 32;
fn shallow(value: &serde_json::Value, room: usize) -> bool {
match value {
serde_json::Value::Array(items) => {
room > 0 && items.iter().all(|item| shallow(item, room - 1))
}
serde_json::Value::Object(members) => {
room > 0 && members.values().all(|member| shallow(member, room - 1))
}
_ => true,
}
}
fn same(left: &serde_json::Value, right: &serde_json::Value) -> bool {
use serde_json::Value::{Array, Number, Object};
match (left, right) {
(Number(left), Number(right)) => left.as_f64() == right.as_f64(),
(Array(left), Array(right)) => {
left.len() == right.len()
&& left
.iter()
.zip(right)
.all(|(left, right)| same(left, right))
}
(Object(left), Object(right)) => {
left.len() == right.len()
&& left
.iter()
.all(|(key, left)| right.get(key).is_some_and(|right| same(left, right)))
}
_ => left == right,
}
}
const PRESENTATION: &str = "/snapshot/android/presentation";
fn beside_the_presentation(request: &serde_json::Value) -> serde_json::Value {
let mut request = request.clone();
if let Some(content) = request
.pointer_mut("/snapshot/android")
.and_then(serde_json::Value::as_object_mut)
{
content.remove("presentation");
}
request
}
fn same_but_defaults(encoded: &serde_json::Value, sent: &serde_json::Value) -> bool {
use serde_json::Value::{Array, Bool, Object};
match (encoded, sent) {
(Array(encoded), Array(sent)) => {
encoded.len() == sent.len()
&& encoded
.iter()
.zip(sent)
.all(|(encoded, sent)| same_but_defaults(encoded, sent))
}
(Object(encoded), Object(sent)) => {
let written = sent.iter().all(|(key, sent)| match encoded.get(key) {
Some(encoded) => same_but_defaults(encoded, sent),
None => matches!(sent, Bool(false)) || sent.as_array().is_some_and(Vec::is_empty),
});
written && encoded.keys().all(|key| sent.contains_key(key))
}
_ => same(encoded, sent),
}
}
fn strict<T: DeserializeOwned + Serialize + Validate>(input: &serde_json::Value) -> Result<T> {
require(shallow(input, MAX_NESTING))?;
let typed: T = serde_json::from_value(input.clone()).map_err(|_| Error::invalid())?;
let encoded = serde_json::to_value(&typed).map_err(|_| Error::invalid())?;
require(same(
&beside_the_presentation(&encoded),
&beside_the_presentation(input),
))?;
require(
match (encoded.pointer(PRESENTATION), input.pointer(PRESENTATION)) {
(Some(encoded), Some(sent)) => same_but_defaults(encoded, sent),
(None, None) => true,
_ => false,
},
)?;
typed.validate()?;
Ok(typed)
}
pub(crate) fn parse<T: DeserializeOwned + Validate>(
command: &str,
input: serde_json::Value,
) -> Result<T> {
match command {
"start_layout" => strict::<LayoutStartInput>(&input).map(|_| ())?,
"update_layout" => strict::<LayoutUpdateInput>(&input).map(|_| ())?,
"end_layout" => strict::<LayoutEndInput>(&input).map(|_| ())?,
_ => return Err(Error::invalid()),
}
let typed: T = serde_json::from_value(input).map_err(|_| Error::invalid())?;
typed.validate()?;
Ok(typed)
}
#[cfg(test)]
#[path = "layout_tests.rs"]
mod tests;