Files
Pictor-public/crates/qr/src/payload.rs
T

228 lines
7.3 KiB
Rust

//! What goes inside the code: plain text, a web address, a Wi-Fi login, or a contact card.
use serde::{Deserialize, Serialize};
use crate::{Level, QrError};
/// Wi-Fi security, as the `T:` field of the Wi-Fi payload names it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WifiSecurity {
/// WPA, WPA2 or WPA3 personal (phones read `T:WPA` for all of them).
#[default]
Wpa,
/// The old WEP.
Wep,
/// No password.
Open,
}
/// The content of a code, before it is turned into the string that is encoded.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Payload {
/// Any text, kept exactly as given.
Text(String),
/// A web address; `https://` is added when it has no scheme.
Url(String),
/// A Wi-Fi login. The password is ignored for [`WifiSecurity::Open`].
Wifi {
ssid: String,
#[serde(default)]
password: String,
#[serde(default)]
security: WifiSecurity,
#[serde(default)]
hidden: bool,
},
/// A contact card (vCard 3.0). Empty optional fields are left out.
Contact {
name: String,
#[serde(default)]
phone: Option<String>,
#[serde(default)]
email: Option<String>,
#[serde(default)]
organisation: Option<String>,
#[serde(default)]
url: Option<String>,
#[serde(default)]
address: Option<String>,
#[serde(default)]
note: Option<String>,
},
}
/// The string to encode for `payload`. Fails on empty required fields and on content that no QR code can hold
/// (even at level L); whether it fits at a higher level is checked when it is rendered.
pub fn payload_string(payload: &Payload) -> Result<String, QrError> {
let s = match payload {
Payload::Text(t) => {
if t.trim().is_empty() {
return Err(QrError::Empty);
}
t.clone()
}
Payload::Url(u) => url(u)?,
Payload::Wifi { ssid, password, security, hidden } => wifi(ssid, password, *security, *hidden)?,
Payload::Contact { name, phone, email, organisation, url, address, note } => {
let field = |f: &Option<String>| f.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
vcard(&Contact {
name: name.trim(),
phone: field(phone),
email: field(email),
organisation: field(organisation),
url: field(url),
address: field(address),
note: field(note),
})?
}
};
crate::encode::encode(&s, Level::L, false)?;
Ok(s)
}
fn url(u: &str) -> Result<String, QrError> {
let u = u.trim();
if u.is_empty() {
return Err(QrError::EmptyField { field: "web address" });
}
Ok(if has_scheme(u) { u.to_string() } else { format!("https://{u}") })
}
/// RFC 3986 `scheme ":"`, where the colon is not followed by a digit (so `localhost:8080` is a host and a port).
fn has_scheme(u: &str) -> bool {
let Some((scheme, rest)) = u.split_once(':') else { return false };
let mut chars = scheme.chars();
let first_ok = chars.next().is_some_and(|c| c.is_ascii_alphabetic());
first_ok
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
&& !rest.starts_with(|c: char| c.is_ascii_digit())
}
/// The de-facto Wi-Fi format (`WIFI:T:WPA;S:<ssid>;P:<password>;H:true;;`), with `\ ; , : "` backslash-escaped.
fn wifi(ssid: &str, password: &str, security: WifiSecurity, hidden: bool) -> Result<String, QrError> {
fn esc(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if matches!(c, '\\' | ';' | ',' | ':' | '"') {
out.push('\\');
}
out.push(c);
}
out
}
if ssid.is_empty() {
return Err(QrError::EmptyField { field: "Wi-Fi network name" });
}
let t = match security {
WifiSecurity::Wpa => "WPA",
WifiSecurity::Wep => "WEP",
WifiSecurity::Open => "nopass",
};
let mut s = format!("WIFI:T:{t};S:{};", esc(ssid));
if security != WifiSecurity::Open {
if password.is_empty() {
return Err(QrError::EmptyField { field: "Wi-Fi password (choose \"Open\" for a network without one)" });
}
s.push_str(&format!("P:{};", esc(password)));
}
if hidden {
s.push_str("H:true;");
}
s.push(';');
Ok(s)
}
struct Contact<'a> {
name: &'a str,
phone: Option<String>,
email: Option<String>,
organisation: Option<String>,
url: Option<String>,
address: Option<String>,
note: Option<String>,
}
/// vCard text value escaping (RFC 2426 / 6350): `\` `,` `;` get a backslash, every line break becomes `\n`.
fn esc_text(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
match c {
'\\' | ',' | ';' => {
out.push('\\');
out.push(c);
}
'\r' => {
chars.next_if_eq(&'\n');
out.push_str("\\n");
}
'\n' => out.push_str("\\n"),
_ => out.push(c),
}
}
out
}
/// A value that is not text (telephone, e-mail, URI): kept as given, but on one line.
fn one_line(s: &str) -> String {
s.split(['\r', '\n']).filter(|p| !p.is_empty()).collect::<Vec<_>>().join(" ")
}
/// vCard 3.0 with CRLF line endings. `N` is split at the last space into given and family name. Lines are not
/// folded at 75 octets: every scanner reads long lines, and some do not unfold.
fn vcard(c: &Contact) -> Result<String, QrError> {
if c.name.is_empty() {
return Err(QrError::EmptyField { field: "contact name" });
}
let (given, family) = match c.name.rsplit_once(char::is_whitespace) {
Some((g, f)) => (g.trim_end(), f),
None => ("", c.name),
};
let mut lines = vec![
"BEGIN:VCARD".to_string(),
"VERSION:3.0".to_string(),
format!("N:{};{};;;", esc_text(family), esc_text(given)),
format!("FN:{}", esc_text(c.name)),
];
if let Some(v) = &c.organisation {
lines.push(format!("ORG:{}", esc_text(v)));
}
if let Some(v) = &c.phone {
lines.push(format!("TEL:{}", one_line(v)));
}
if let Some(v) = &c.email {
lines.push(format!("EMAIL:{}", one_line(v)));
}
if let Some(v) = &c.url {
lines.push(format!("URL:{}", one_line(v)));
}
if let Some(v) = &c.address {
lines.push(format!("ADR:;;{};;;;", esc_text(v)));
}
if let Some(v) = &c.note {
lines.push(format!("NOTE:{}", esc_text(v)));
}
lines.push("END:VCARD".to_string());
let mut s = lines.join("\r\n");
s.push_str("\r\n");
Ok(s)
}
#[cfg(test)]
mod tests {
use super::has_scheme;
#[test]
fn scheme_detection() {
assert!(has_scheme("https://a"));
assert!(has_scheme("mailto:x@y"));
assert!(has_scheme("tel:+420"));
assert!(!has_scheme("example.com"));
assert!(!has_scheme("example.com:8080/x"));
assert!(!has_scheme("1http://x"));
assert!(!has_scheme("ex ample:x"));
}
}