mod backend;
mod kit;
pub(crate) mod template;
#[cfg(test)]
mod fake;
#[cfg(test)]
mod tests;
use crate::{
Error, Result,
layout::{
ActionEvent, LayoutActivityRecord, LayoutEndInput, LayoutPush, LayoutSnapshot,
LayoutStartInput, LayoutUpdateInput,
},
models::*,
pushes::{PushTokenEvent, UpdatedEvent},
validation::Validate,
};
use activitykit::{State, Values};
use std::{
collections::VecDeque,
future::Future,
pin::pin,
sync::{Arc, Mutex, PoisonError},
task::{Context, Poll, Wake, Waker},
thread,
};
pub(crate) trait Acknowledge: Send + 'static {
fn acknowledge(&self);
}
pub(crate) enum KitEvent<H, A> {
Tap(ActionEvent, A),
PushToken {
activity: H,
token: String,
},
PushToStartToken {
token: String,
},
Updated(H),
}
pub(crate) trait Kit: Send + Sync + 'static {
type Handle: Handle;
type Ack: Acknowledge;
fn events(&self) -> Box<dyn Iterator<Item = KitEvent<Self::Handle, Self::Ack>> + Send>;
fn authorization(&self) -> Authorization;
fn start(
&self,
start: StartSpec,
) -> impl Future<Output = activitykit::Result<Self::Handle>> + Send;
fn activity(
&self,
id: &str,
) -> impl Future<Output = activitykit::Result<Option<Self::Handle>>> + Send;
fn activities(&self) -> impl Future<Output = activitykit::Result<Vec<Self::Handle>>> + Send;
fn write_image(&self, name: &str, png: &[u8]) -> activitykit::Result<()>;
}
pub(crate) trait Handle: Clone + Send + Sync + 'static {
fn id(&self) -> &str;
fn key(&self) -> &str;
fn state(&self) -> State;
fn values(&self) -> Values;
fn revision(&self) -> Option<u64>;
fn stale_at(&self) -> Option<u64>;
fn timestamp(&self) -> Option<u64>;
fn degraded_features(&self) -> Vec<String>;
fn update(&self, update: UpdateSpec) -> impl Future<Output = activitykit::Result<()>> + Send;
fn end(&self, end: EndSpec) -> impl Future<Output = activitykit::Result<()>> + Send;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Authorization {
pub(crate) supported: bool,
pub(crate) enabled: bool,
pub(crate) buttons: bool,
pub(crate) frequent_pushes: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct StartSpec {
pub(crate) key: String,
pub(crate) layout: activitykit::Layout,
pub(crate) values: Values,
pub(crate) revision: u64,
pub(crate) stale_at: Option<u64>,
pub(crate) timestamp: Option<u64>,
pub(crate) push: Option<LayoutPush>,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct UpdateSpec {
pub(crate) values: Values,
pub(crate) revision: u64,
pub(crate) stale_at: Option<u64>,
pub(crate) timestamp: Option<u64>,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct EndSpec {
pub(crate) policy: EndPolicy,
pub(crate) values: Option<Values>,
pub(crate) revision: Option<u64>,
pub(crate) stale_at: Option<u64>,
pub(crate) timestamp: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Layout,
Template(Template),
}
impl Kind {
fn is_layout(self) -> bool {
self == Self::Layout
}
fn is_template(self) -> bool {
matches!(self, Self::Template(_))
}
}
const ENDED_KEPT: usize = 64;
pub(crate) struct Apple<K: Kit> {
kit: K,
ended: Mutex<VecDeque<K::Handle>>,
}
fn not_found() -> Error {
Error::new("NOT_FOUND", "No active activity has this handle.")
}
fn state(state: State) -> ActivityState {
match state {
State::Pending => ActivityState::Pending,
State::Active => ActivityState::Active,
State::Stale => ActivityState::Stale,
State::Ended => ActivityState::Ended,
State::Dismissed => ActivityState::Dismissed,
_ => ActivityState::Unknown,
}
}
fn kind<H: Handle>(handle: &H) -> Kind {
template::of(&handle.values()).map_or(Kind::Layout, Kind::Template)
}
pub(crate) fn action_event<H: Handle>(handle: &H, action: String) -> ActionEvent {
let key = handle.key();
ActionEvent {
action_id: action,
activity_id: handle.id().to_owned(),
activity_key: (!key.is_empty()).then(|| key.to_owned()),
}
}
pub(crate) fn push_token_event<H: Handle>(handle: &H, token: String) -> PushTokenEvent {
let key = handle.key();
PushTokenEvent {
activity_id: handle.id().to_owned(),
activity_key: (!key.is_empty()).then(|| key.to_owned()),
token,
}
}
pub(crate) fn updated_event<H: Handle>(handle: &H) -> Option<UpdatedEvent> {
kind(handle).is_layout().then(|| UpdatedEvent {
record: layout_record(handle),
})
}
fn layout_record<H: Handle>(handle: &H) -> LayoutActivityRecord {
LayoutActivityRecord {
id: handle.id().to_owned(),
activity_key: handle.key().to_owned(),
schema_version: 2,
snapshot: LayoutSnapshot {
revision: handle.revision().unwrap_or(0),
values: handle.values().into_inner(),
stale_at: handle.stale_at(),
timestamp: handle.timestamp(),
},
backend: Backend::ActivityKit,
state: state(handle.state()),
visibility: Visibility::Unknown,
degraded_features: handle.degraded_features(),
promotion_requested: false,
promotion_state: PromotionState::NotApplicable,
}
}
fn template_record<H: Handle>(handle: &H) -> Option<ActivityRecord> {
let revision = handle.revision().unwrap_or(0);
let (template, snapshot) = template::snapshot(revision, &handle.values(), handle.stale_at())?;
Some(ActivityRecord {
id: handle.id().to_owned(),
activity_key: handle.key().to_owned(),
schema_version: 1,
template,
snapshot,
backend: Backend::ActivityKit,
state: state(handle.state()),
visibility: Visibility::Unknown,
degraded_features: handle.degraded_features(),
promotion_requested: false,
promotion_state: PromotionState::NotApplicable,
})
}
pub(crate) fn start_spec(request: LayoutStartInput) -> StartSpec {
let layout = activitykit::Layout {
lock_screen: request.layout.lock_screen,
island: request.layout.island,
background: request.layout.background,
keyline: request.layout.keyline,
styles: request.styles.unwrap_or_default(),
};
StartSpec {
key: request.activity_key,
layout,
values: request.snapshot.values.into(),
revision: request.snapshot.revision,
stale_at: request.snapshot.stale_at,
timestamp: request.snapshot.timestamp,
push: request.push,
}
}
fn update_spec(snapshot: LayoutSnapshot) -> UpdateSpec {
UpdateSpec {
values: snapshot.values.into(),
revision: snapshot.revision,
stale_at: snapshot.stale_at,
timestamp: snapshot.timestamp,
}
}
fn end_spec(policy: EndPolicy, snapshot: Option<LayoutSnapshot>) -> EndSpec {
match snapshot {
Some(snapshot) => EndSpec {
policy,
values: Some(snapshot.values.into()),
revision: Some(snapshot.revision),
stale_at: snapshot.stale_at,
timestamp: snapshot.timestamp,
},
None => EndSpec {
policy,
values: None,
revision: None,
stale_at: None,
timestamp: None,
},
}
}
impl<K: Kit> Apple<K> {
pub(crate) fn new(kit: K) -> Self {
Self {
kit,
ended: Mutex::default(),
}
}
pub(crate) fn capabilities(&self) -> Capabilities {
let authorization = self.kit.authorization();
let support = |yes: bool| {
if yes {
FeatureSupport::Supported
} else {
FeatureSupport::Unsupported
}
};
let supported = support(authorization.supported);
Capabilities {
platform: "ios".into(),
backend: if authorization.supported {
Backend::ActivityKit
} else {
Backend::Unsupported
},
start: supported,
update: supported,
end: supported,
progress: supported,
timer: supported,
actions: support(authorization.supported && authorization.buttons),
state_observation: supported,
silent_update: supported,
native_live_activity: supported,
max_payload_bytes: 4096,
layout: supported,
push: supported,
}
}
pub(crate) fn permissions(&self, request: bool) -> Permissions {
let authorization = self.kit.authorization();
let live_activities = match (authorization.supported, authorization.enabled, request) {
(false, _, _) => PermissionState::NotApplicable,
(true, true, _) => PermissionState::Granted,
(true, false, true) => PermissionState::SettingsRequired,
(true, false, false) => PermissionState::Denied,
};
let frequent_pushes = match (authorization.supported, authorization.frequent_pushes) {
(false, _) => PermissionState::NotApplicable,
(true, true) => PermissionState::Granted,
(true, false) => PermissionState::Denied,
};
Permissions {
notifications: PermissionState::NotApplicable,
live_activities,
promotion: PermissionState::NotApplicable,
frequent_pushes,
}
}
pub(crate) fn request_permissions(&self, kind: PermissionKind) -> Result<Permissions> {
match kind {
PermissionKind::LiveActivities => Ok(self.permissions(true)),
_ => Err(Error::new(
"UNSUPPORTED_FEATURE",
"This backend only exposes Live Activity settings.",
)),
}
}
pub(crate) fn write_image(&self, name: &str, png: &[u8]) -> Result<()> {
crate::image::check_image(name, png)?;
Ok(self.kit.write_image(name, png)?)
}
pub(crate) async fn start_layout(
&self,
input: LayoutStartInput,
) -> Result<LayoutActivityRecord> {
input.validate()?;
Ok(layout_record(&self.start(input).await?))
}
pub(crate) async fn update_layout(
&self,
input: LayoutUpdateInput,
) -> Result<LayoutActivityRecord> {
input.validate()?;
let handle = self.find(&input.id, Kind::is_layout).await?;
handle.update(update_spec(input.snapshot)).await?;
Ok(layout_record(&handle))
}
pub(crate) async fn end_layout(&self, input: LayoutEndInput) -> Result<LayoutActivityRecord> {
input.validate()?;
let handle = self.find(&input.id, Kind::is_layout).await?;
handle.end(end_spec(input.policy, input.snapshot)).await?;
self.keep_ended(&handle);
Ok(layout_record(&handle))
}
pub(crate) async fn list_layout(&self) -> Result<Vec<LayoutActivityRecord>> {
let handles = self.kit.activities().await?;
Ok(handles
.iter()
.filter(|handle| kind(*handle).is_layout())
.map(layout_record)
.collect())
}
pub(crate) async fn start_template(&self, input: StartInput) -> Result<ActivityRecord> {
input.validate()?;
let request = template::start(&input);
request.validate_contract()?;
let handle = self.start(request).await?;
template_record(&handle).ok_or_else(Error::native)
}
pub(crate) async fn update_template(&self, input: UpdateInput) -> Result<ActivityRecord> {
input.validate()?;
let (template, snapshot) = template::layout_snapshot(&input.snapshot);
let handle = self.find(&input.id, Kind::is_template).await?;
if kind(&handle) != Kind::Template(template) {
return Err(Error::invalid());
}
handle.update(update_spec(snapshot)).await?;
template_record(&handle).ok_or_else(Error::native)
}
pub(crate) async fn end_template(&self, input: EndInput) -> Result<ActivityRecord> {
input.validate()?;
let handle = self.find(&input.id, Kind::is_template).await?;
handle.end(end_spec(input.policy, None)).await?;
self.keep_ended(&handle);
template_record(&handle).ok_or_else(Error::native)
}
pub(crate) async fn list_templates(&self) -> Result<Vec<ActivityRecord>> {
let handles = self.kit.activities().await?;
Ok(handles.iter().filter_map(template_record).collect())
}
async fn start(&self, request: LayoutStartInput) -> Result<K::Handle> {
Ok(self.kit.start(start_spec(request)).await?)
}
fn keep_ended(&self, handle: &K::Handle) {
let mut ended = self.ended.lock().unwrap_or_else(PoisonError::into_inner);
if ended.iter().any(|kept| kept.id() == handle.id()) {
return;
}
if ended.len() == ENDED_KEPT {
ended.pop_front();
}
ended.push_back(handle.clone());
}
async fn find(&self, id: &str, wanted: fn(Kind) -> bool) -> Result<K::Handle> {
match self.kit.activity(id).await? {
Some(handle) if wanted(kind(&handle)) => Ok(handle),
_ => Err(not_found()),
}
}
}
#[cfg(target_os = "ios")]
#[allow(unsafe_code)]
fn on_main_thread() -> bool {
unsafe extern "C" {
fn pthread_main_np() -> std::ffi::c_int;
}
unsafe { pthread_main_np() != 0 }
}
#[cfg(not(target_os = "ios"))]
fn on_main_thread() -> bool {
false
}
pub fn wait<T>(future: impl Future<Output = Result<T>>) -> Result<T> {
wait_on(on_main_thread(), future)
}
fn wait_on<T>(main: bool, future: impl Future<Output = Result<T>>) -> Result<T> {
if main {
return Err(Error::new(
"NATIVE_ERROR",
"A blocking call on the main thread, where activitykit answers, would never end: call it on another \
thread, or await it.",
));
}
block_on(future)
}
pub fn block_on<F: Future>(future: F) -> F::Output {
struct Unpark(thread::Thread);
impl Wake for Unpark {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
let waker = Waker::from(Arc::new(Unpark(thread::current())));
let mut context = Context::from_waker(&waker);
let mut future = pin!(future);
loop {
if let Poll::Ready(output) = future.as_mut().poll(&mut context) {
return output;
}
thread::park();
}
}
pub use backend::ActivityKitBackend;
pub(crate) use backend::already_connected;