use crate::api::ActionAddress;
use super::{
APPLICATION_OPEN_ACTION, APPLICATION_RESOURCE_PREFIX, InvokeArgument, RemoteActionTarget,
workspace_provider,
};
pub const CONTENT_HASH_ARGUMENT: &str = "content_hash";
pub const NAME_ARGUMENT: &str = "name";
#[must_use]
pub fn valid_file_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 255
&& name != "."
&& name != ".."
&& !name
.chars()
.any(|c| c.is_control() || c == '/' || c == '\\')
}
#[must_use]
pub fn application_open_target(workspace: &str, app_id: &str) -> RemoteActionTarget {
RemoteActionTarget {
provider: workspace_provider(workspace),
address: ActionAddress::new(
format!("{APPLICATION_RESOURCE_PREFIX}{app_id}"),
APPLICATION_OPEN_ACTION,
),
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ApplicationLaunch {
pub app_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_hash: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action: Option<crate::ActionAddress>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
impl ApplicationLaunch {
pub const TYPE: &'static str = "tilo.application.launch";
#[must_use]
pub fn app(app_id: impl Into<String>) -> Self {
Self {
app_id: app_id.into(),
content_hash: None,
action: None,
name: None,
}
}
#[must_use]
pub fn with_action(
app_id: impl Into<String>,
resource: impl Into<String>,
action: impl Into<String>,
) -> Self {
Self {
app_id: app_id.into(),
content_hash: None,
action: Some(crate::ActionAddress::new(resource, action)),
name: None,
}
}
#[must_use]
pub fn target(&self, workspace: &str) -> RemoteActionTarget {
self.action.as_ref().map_or_else(
|| application_open_target(workspace, &self.app_id),
|action| {
application_action_target(workspace, &self.app_id, &action.resource, &action.action)
},
)
}
#[must_use]
pub fn with_content(app_id: impl Into<String>, content_hash: impl Into<String>) -> Self {
Self {
app_id: app_id.into(),
content_hash: Some(content_hash.into()),
action: None,
name: None,
}
}
#[must_use]
pub fn named(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub fn valid(&self) -> bool {
self.action.as_ref().is_none_or(|action| {
self.content_hash.is_none()
&& !action.resource.is_empty()
&& action.resource.len() <= 1024
&& !action.action.is_empty()
&& action.action.len() <= 128
}) && !self.app_id.is_empty()
&& self.app_id.len() <= 128
&& self
.app_id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-'))
&& self.content_hash.as_ref().is_none_or(|hash| {
hash.len() == 64
&& hash
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
})
&& self
.name
.as_ref()
.is_none_or(|name| self.content_hash.is_some() && valid_file_name(name))
}
#[must_use]
pub fn argument(&self) -> InvokeArgument {
match (&self.content_hash, &self.name) {
(Some(hash), Some(name)) => InvokeArgument::Json(serde_json::Map::from_iter([
(
CONTENT_HASH_ARGUMENT.to_owned(),
serde_json::Value::String(hash.clone()),
),
(
NAME_ARGUMENT.to_owned(),
serde_json::Value::String(name.clone()),
),
])),
(Some(hash), None) => InvokeArgument::Text(hash.clone()),
(None, _) => InvokeArgument::None,
}
}
#[must_use]
pub fn opened_content(argument: &InvokeArgument) -> Option<(&str, Option<&str>)> {
match argument {
InvokeArgument::Text(hash) => Some((hash, None)),
InvokeArgument::Json(map) => {
let hash = map.get(CONTENT_HASH_ARGUMENT)?.as_str()?;
let name = map
.get(NAME_ARGUMENT)
.and_then(serde_json::Value::as_str)
.filter(|name| valid_file_name(name));
Some((hash, name))
}
InvokeArgument::None => None,
}
}
#[must_use]
pub fn content_spec(
app_id: &str,
id: &str,
label: &str,
description: &str,
) -> crate::ActionSpec {
let app_id = app_id.to_owned();
let spec = crate::ActionSpec::typed_operation(
id,
label,
description,
crate::OperationKind::Effect,
Self::TYPE,
vec![
crate::ActionParam::required(
CONTENT_HASH_ARGUMENT,
crate::ParamType::Text,
"Content address hash of what the app opens",
),
crate::ActionParam::optional(
NAME_ARGUMENT,
crate::ParamType::Text,
"The name of the file it is",
),
],
move |args| {
let launch = Self::with_content(
app_id.clone(),
args.text(CONTENT_HASH_ARGUMENT).unwrap_or_default(),
);
let launch = match args.text(NAME_ARGUMENT).filter(|name| !name.is_empty()) {
Some(name) => launch.named(name),
None => launch,
};
crate::EncodedAction::encode_operation(Self::TYPE, &launch).unwrap_or_else(|_| {
crate::EncodedAction {
type_id: Self::TYPE.to_owned(),
payload: Vec::new(),
}
})
},
);
Self::launched_here(spec)
}
fn launched_here(mut spec: crate::ActionSpec) -> crate::ActionSpec {
spec.type_mut()
.contract
.tags
.push(crate::OWN_DEVICE_SCOPE.to_owned());
spec
}
#[must_use]
pub fn spec(&self, id: &str, label: &str, description: &str) -> crate::ActionSpec {
let encoded =
crate::EncodedAction::encode_operation(Self::TYPE, self).unwrap_or_else(|_| {
crate::EncodedAction {
type_id: Self::TYPE.to_owned(),
payload: Vec::new(),
}
});
Self::launched_here(crate::ActionSpec::typed_operation(
id,
label,
description,
crate::OperationKind::Effect,
Self::TYPE,
Vec::new(),
move |_| encoded.clone(),
))
}
}
pub const APPLICATION_PROVIDER: &str = "application";
#[must_use]
pub fn application_provider_token(workspace: &str, app_id: &str) -> String {
format!("{APPLICATION_PROVIDER}:{workspace}:{app_id}")
}
#[must_use]
pub fn application_action_target(
workspace: &str,
app_id: &str,
resource: impl Into<String>,
action: impl Into<String>,
) -> RemoteActionTarget {
RemoteActionTarget {
provider: application_provider_token(workspace, app_id),
address: ActionAddress::new(resource, action),
}
}
#[must_use]
pub fn application_resource_target(
workspace: &str,
app_id: &str,
record: &str,
resource: impl Into<String>,
action: impl Into<String>,
) -> RemoteActionTarget {
let mut target = application_action_target(workspace, app_id, resource, action);
target.provider = format!("{}:{record}", target.provider);
target
}
#[must_use]
pub fn application_provider(provider: &str) -> Option<(&str, &str)> {
application_parts(provider).map(|(workspace, app_id, _)| (workspace, app_id))
}
#[must_use]
pub fn application_provider_resource(provider: &str) -> Option<&str> {
application_parts(provider).and_then(|(_, _, record)| record)
}
fn application_parts(provider: &str) -> Option<(&str, &str, Option<&str>)> {
let (workspace, rest) = provider
.strip_prefix(APPLICATION_PROVIDER)?
.strip_prefix(':')?
.split_once(':')?;
let (app_id, record) = match rest.split_once(':') {
Some((app_id, record)) => (app_id, Some(record)),
None => (rest, None),
};
(!workspace.is_empty() && !app_id.is_empty() && record.is_none_or(|record| !record.is_empty()))
.then_some((workspace, app_id, record))
}
#[cfg(test)]
mod named_content_tests {
use super::*;
#[test]
fn a_launch_carries_the_name_of_the_file_it_opens() {
let hash = "ab".repeat(32);
let plain = ApplicationLaunch::with_content("so.tilo.notes", hash.clone());
assert_eq!(plain.argument(), InvokeArgument::Text(hash.clone()));
assert_eq!(
ApplicationLaunch::opened_content(&plain.argument()),
Some((hash.as_str(), None))
);
let named = plain.named("plan.txt");
assert!(named.valid());
assert_eq!(
ApplicationLaunch::opened_content(&named.argument()),
Some((hash.as_str(), Some("plan.txt")))
);
for name in ["", "..", "a/b", "a\\b", "line\nbreak"] {
assert!(
!ApplicationLaunch::with_content("so.tilo.notes", hash.clone())
.named(name)
.valid()
);
}
assert!(
!ApplicationLaunch::app("so.tilo.notes")
.named("plan.txt")
.valid()
);
}
}