use std::path::PathBuf;
use crate::{EventPayload, NodeId, PayloadValue};
pub const MAX_TEXT_BYTES: usize = 1024 * 1024;
pub const MAX_URL_BYTES: usize = 16 * 1024;
pub const MAX_FILES: usize = 100;
pub(crate) const NOT_GRANTED: &str =
"share: the share sheet is not granted: add `\"share\": true` to capabilities in nsh.json";
const REFUSED_SCHEMES: &[&str] = &[
"javascript",
"vbscript",
"data",
"blob",
"file",
"about",
"asset",
];
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ShareRequest {
pub title: Option<String>,
pub text: Option<String>,
pub url: Option<String>,
pub files: Vec<PathBuf>,
pub anchor: Option<NodeId>,
}
impl ShareRequest {
pub fn new() -> Self {
Self::default()
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn text(mut self, text: impl Into<String>) -> Self {
self.text = Some(text.into());
self
}
pub fn url(mut self, url: impl Into<String>) -> Self {
self.url = Some(url.into());
self
}
pub fn file(mut self, path: impl Into<PathBuf>) -> Self {
self.files.push(path.into());
self
}
pub fn anchor(mut self, anchor: &crate::element::ElementRef) -> Self {
self.anchor = anchor.node();
self
}
pub fn check(&self) -> Result<(), String> {
let text = self.text.as_deref().filter(|text| !text.is_empty());
if text.is_none() && self.url.is_none() && self.files.is_empty() {
return Err("share: give `text`, `url` or `files`".into());
}
for (name, value) in [("title", &self.title), ("text", &self.text)] {
if value.as_ref().is_some_and(|v| v.len() > MAX_TEXT_BYTES) {
return Err(format!(
"share: `{name}` has at most {MAX_TEXT_BYTES} bytes"
));
}
}
if let Some(url) = &self.url {
check_url(url)?;
}
if self.files.len() > MAX_FILES {
return Err(format!("share: at most {MAX_FILES} files"));
}
if let Some(path) = self
.files
.iter()
.find(|path| !crate::access::absolute(path))
{
return Err(format!(
"share: `{}` is not an absolute path",
path.display()
));
}
Ok(())
}
}
fn check_url(url: &str) -> Result<(), String> {
if url.len() > MAX_URL_BYTES {
return Err(format!("share: a URL has at most {MAX_URL_BYTES} bytes"));
}
if url.chars().any(|c| c.is_whitespace() || c.is_control()) {
return Err("share: a URL has no whitespace or control characters".into());
}
let parsed = url::Url::parse(url).map_err(|e| format!("share: not a URL: {e} ({url})"))?;
let scheme = parsed.scheme();
if REFUSED_SCHEMES.contains(&scheme) {
return Err(format!(
"share: `{scheme}:` URLs are not shared (share local files as `files`)"
));
}
Ok(())
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct ShareSheet {
pub title: Option<String>,
pub text: Option<String>,
pub url: Option<String>,
pub files: Vec<String>,
pub anchor: Option<NodeId>,
}
impl ShareSheet {
pub(crate) fn new(request: ShareRequest, anchor: Option<NodeId>) -> Self {
let present = |value: Option<String>| value.filter(|value| !value.is_empty());
Self {
title: present(request.title),
text: present(request.text),
url: request.url,
files: request
.files
.into_iter()
.map(|path| path.to_string_lossy().into_owned())
.collect(),
anchor,
}
}
pub fn combined_text(&self) -> Option<String> {
match (&self.text, &self.url) {
(Some(text), Some(url)) if !text.is_empty() => Some(format!("{text}\n{url}")),
(Some(text), None) => Some(text.clone()),
(_, Some(url)) => Some(url.clone()),
(None, None) => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum ShareAction {
Shared,
#[default]
Dismissed,
}
impl ShareAction {
pub fn as_str(self) -> &'static str {
match self {
ShareAction::Shared => "shared",
ShareAction::Dismissed => "dismissed",
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ShareOutcome {
pub action: ShareAction,
pub target: Option<String>,
}
impl ShareOutcome {
pub fn shared(target: Option<String>) -> Self {
Self {
action: ShareAction::Shared,
target,
}
}
pub fn dismissed() -> Self {
Self {
action: ShareAction::Dismissed,
target: None,
}
}
pub fn payload(&self, id: u32) -> EventPayload {
let mut fields = vec![
("id", PayloadValue::Number(id as f64)),
("action", PayloadValue::Str(self.action.as_str().into())),
];
if let Some(target) = &self.target {
fields.push(("target", PayloadValue::Str(target.clone())));
}
EventPayload::Map(fields)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ShareError {
pub code: Option<String>,
pub message: String,
}
impl ShareError {
pub fn failed(message: impl Into<String>) -> Self {
Self {
code: None,
message: message.into(),
}
}
pub fn unavailable(message: impl Into<String>) -> Self {
Self {
code: Some(crate::element::codes::UNAVAILABLE.into()),
message: message.into(),
}
}
pub fn payload(&self, id: u32) -> EventPayload {
let mut fields = vec![
("id", PayloadValue::Number(id as f64)),
("error", PayloadValue::Str(self.message.clone())),
];
if let Some(code) = &self.code {
fields.push(("code", PayloadValue::Str(code.clone())));
}
EventPayload::Map(fields)
}
}
impl std::fmt::Display for ShareError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ShareError {}
pub(crate) fn answer_from_payload(
payload: &EventPayload,
) -> Option<(u32, Result<ShareOutcome, ShareError>)> {
let EventPayload::Map(fields) = payload else {
return None;
};
let text = |key: &str| {
fields.iter().find_map(|(k, v)| match v {
PayloadValue::Str(s) if *k == key => Some(s.clone()),
_ => None,
})
};
let id = fields.iter().find_map(|(k, v)| match v {
PayloadValue::Number(n) if *k == "id" => Some(*n as u32),
_ => None,
})?;
if let Some(message) = text("error") {
return Some((
id,
Err(ShareError {
code: text("code"),
message,
}),
));
}
let outcome = match text("action").as_deref() {
Some("shared") => ShareOutcome::shared(text("target")),
_ => ShareOutcome::dismissed(),
};
Some((id, Ok(outcome)))
}
#[cfg(test)]
mod tests {
use super::*;
fn absolute(name: &str) -> PathBuf {
if cfg!(windows) {
PathBuf::from(format!("C:\\data\\{name}"))
} else {
PathBuf::from(format!("/data/{name}"))
}
}
#[test]
fn a_request_needs_something_to_share() {
assert!(ShareRequest::new().title("Only a title").check().is_err());
assert!(ShareRequest::new().text("Hello").check().is_ok());
assert!(
ShareRequest::new()
.url("https://example.com/a")
.check()
.is_ok()
);
assert!(ShareRequest::new().file(absolute("a.pdf")).check().is_ok());
}
#[test]
fn urls_that_run_code_or_name_local_files_are_refused() {
for url in [
"javascript:alert(1)",
"data:text/plain,hi",
"file:///etc/hosts",
"asset:/a.png",
"relative/path",
"https://example.com/a b",
] {
assert!(ShareRequest::new().url(url).check().is_err(), "{url}");
}
for url in [
"https://example.com",
"mailto:a@example.com",
"myapp://open/1",
] {
assert!(ShareRequest::new().url(url).check().is_ok(), "{url}");
}
}
#[test]
fn files_are_absolute_and_bounded() {
assert!(ShareRequest::new().file("a.pdf").check().is_err());
let mut many = ShareRequest::new();
for i in 0..=MAX_FILES {
many = many.file(absolute(&format!("{i}.txt")));
}
assert!(many.check().is_err());
let long = "x".repeat(MAX_TEXT_BYTES + 1);
assert!(ShareRequest::new().text(long).check().is_err());
}
#[test]
fn payloads_round_trip() {
let shared = ShareOutcome::shared(Some("com.apple.UIKit.activity.Mail".into()));
assert_eq!(
answer_from_payload(&shared.payload(7)),
Some((7, Ok(shared)))
);
let dismissed = ShareOutcome::dismissed();
assert_eq!(
answer_from_payload(&dismissed.payload(8)),
Some((8, Ok(dismissed)))
);
let error = ShareError::unavailable("no share sheet");
assert_eq!(
answer_from_payload(&error.payload(9)),
Some((9, Err(error)))
);
assert_eq!(answer_from_payload(&EventPayload::None), None);
}
#[test]
fn one_string_carries_the_text_and_the_url() {
let sheet = ShareSheet::new(
ShareRequest::new().text("Look").url("https://example.com"),
None,
);
assert_eq!(
sheet.combined_text().as_deref(),
Some("Look\nhttps://example.com")
);
let only_url = ShareSheet::new(ShareRequest::new().url("https://example.com"), None);
assert_eq!(
only_url.combined_text().as_deref(),
Some("https://example.com")
);
}
}