use crate::deep_links::DeepLink;
use crate::runtime::current_runtime;
use crate::{Error, Operation, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ActivityId(String);
impl ActivityId {
pub fn parse(value: impl Into<String>) -> Result<Self> {
let value = value.into();
if value.trim().is_empty() {
return Err(Error::invalid("activity id", "must not be empty"));
}
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for ActivityId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(formatter)
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct LiveActivitySnapshot {
pub title: Option<String>,
pub status: Option<String>,
pub progress: Option<f32>,
pub leading_text: Option<String>,
pub trailing_text: Option<String>,
pub deep_link: Option<DeepLink>,
}
impl LiveActivitySnapshot {
pub const fn new() -> Self {
Self {
title: None,
status: None,
progress: None,
leading_text: None,
trailing_text: None,
deep_link: None,
}
}
pub fn title(mut self, value: impl Into<String>) -> Self {
self.title = Some(value.into());
self
}
pub fn status(mut self, value: impl Into<String>) -> Self {
self.status = Some(value.into());
self
}
pub const fn progress(mut self, value: f32) -> Self {
self.progress = Some(value);
self
}
pub fn leading_text(mut self, value: impl Into<String>) -> Self {
self.leading_text = Some(value.into());
self
}
pub fn trailing_text(mut self, value: impl Into<String>) -> Self {
self.trailing_text = Some(value.into());
self
}
pub fn deep_link(mut self, value: DeepLink) -> Self {
self.deep_link = Some(value);
self
}
fn validate(&self) -> Result<()> {
if self
.progress
.is_some_and(|progress| !progress.is_finite() || !(0.0..=1.0).contains(&progress))
{
return Err(Error::invalid(
"live activity progress",
"must be finite and between 0 and 1",
));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StartRequest {
pub attributes: Value,
pub state: Value,
pub snapshot: Option<LiveActivitySnapshot>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StateRequest {
pub id: ActivityId,
pub state: Value,
pub snapshot: Option<LiveActivitySnapshot>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActiveActivity {
pub id: ActivityId,
pub attributes: Value,
pub state: Value,
pub snapshot: Option<LiveActivitySnapshot>,
}
pub fn is_supported() -> bool {
current_runtime().supports(Operation::LiveActivityStart)
}
pub fn start<A: Serialize, S: Serialize>(attributes: &A, state: &S) -> Result<ActivityId> {
start_with_snapshot(attributes, state, None)
}
pub fn start_with_snapshot<A: Serialize, S: Serialize>(
attributes: &A,
state: &S,
snapshot: impl Into<Option<LiveActivitySnapshot>>,
) -> Result<ActivityId> {
let snapshot = snapshot.into();
if let Some(snapshot) = &snapshot {
snapshot.validate()?;
}
let request = StartRequest {
attributes: serialize("live activity attributes", attributes)?,
state: serialize("live activity state", state)?,
snapshot,
};
let runtime = current_runtime();
runtime.ensure_supported(Operation::LiveActivityStart)?;
runtime.backend().live_activity_start(request)
}
pub fn update<S: Serialize>(id: &ActivityId, state: &S) -> Result<()> {
update_with_snapshot(id, state, None)
}
pub fn update_with_snapshot<S: Serialize>(
id: &ActivityId,
state: &S,
snapshot: impl Into<Option<LiveActivitySnapshot>>,
) -> Result<()> {
let snapshot = snapshot.into();
if let Some(snapshot) = &snapshot {
snapshot.validate()?;
}
let request = StateRequest {
id: id.clone(),
state: serialize("live activity state", state)?,
snapshot,
};
let runtime = current_runtime();
runtime.ensure_supported(Operation::LiveActivityUpdate)?;
runtime.backend().live_activity_update(request)
}
pub fn end<S: Serialize>(id: &ActivityId, final_state: &S) -> Result<()> {
end_with_snapshot(id, final_state, None)
}
pub fn end_with_snapshot<S: Serialize>(
id: &ActivityId,
final_state: &S,
snapshot: impl Into<Option<LiveActivitySnapshot>>,
) -> Result<()> {
let snapshot = snapshot.into();
if let Some(snapshot) = &snapshot {
snapshot.validate()?;
}
let request = StateRequest {
id: id.clone(),
state: serialize("live activity final state", final_state)?,
snapshot,
};
let runtime = current_runtime();
runtime.ensure_supported(Operation::LiveActivityEnd)?;
runtime.backend().live_activity_end(request)
}
pub fn list_active() -> Result<Vec<ActiveActivity>> {
let runtime = current_runtime();
runtime.ensure_supported(Operation::LiveActivityList)?;
runtime.backend().live_activity_list()
}
fn serialize(label: &'static str, value: impl Serialize) -> Result<Value> {
serde_json::to_value(value).map_err(|error| Error::invalid(label, error.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::TestRuntime;
#[test]
fn activity_lifecycle_is_inspectable() {
let runtime = TestRuntime::new();
let _guard = runtime.enter();
let id = start_with_snapshot(
&serde_json::json!({"match": "final"}),
&serde_json::json!({"home": 0}),
LiveActivitySnapshot::new().title("Score").progress(0.0),
)
.unwrap();
update(&id, &serde_json::json!({"home": 1})).unwrap();
assert_eq!(list_active().unwrap()[0].state["home"], 1);
end(&id, &serde_json::json!({"home": 2})).unwrap();
assert!(list_active().unwrap().is_empty());
}
}