You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

358 lines
10 KiB
Rust

use serde::de::{MapAccess, SeqAccess};
use serde::ser::{SerializeMap, SerializeSeq};
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
use std::fmt;
use crate::core::*;
/// The `@context` field in an ActivityPub document.
#[cfg_attr(test, derive(PartialEq))]
#[derive(Debug)]
pub struct Context {
entries: Vec<Entry>,
}
pub mod uri {
pub static ACTIVITY_STREAMS: &'static str = "https://www.w3.org/ns/activitystreams";
pub static ACTIVITY_STREAMS_ALT: &'static str = "http://www.w3.org/ns/activitystreams";
pub static NYANO: &'static str = "https://nyanoblog.org/ns/activitystreams";
pub static TOOT: &'static str = "http://joinmastodon.org/ns#";
}
#[derive(Debug, Clone)]
pub enum Entry {
Anon(AnonEntry),
Named(NamedEntry),
}
#[derive(Debug, Clone, PartialEq)]
pub struct AnonEntry(String);
#[derive(Debug, Clone, PartialEq)]
pub struct NamedEntry(String, String);
impl Entry {
pub fn anon(uri: &str) -> Entry {
Entry::Anon(AnonEntry(String::from(uri)))
}
pub fn named(name: &str, uri: &str) -> Entry {
Entry::Named(NamedEntry(String::from(name), String::from(uri)))
}
pub fn name(&self) -> Option<&str> {
match self {
Entry::Anon(_) => None,
Entry::Named(named) => Some(&named.0),
}
}
pub fn uri(&self) -> &str {
match self {
Entry::Anon(anon) => &anon.0,
Entry::Named(named) => &named.1,
}
}
}
impl PartialEq for Entry {
fn eq(&self, other: &Self) -> bool {
match self {
Entry::Anon(self_anon) => self_anon.0.eq(other.uri()),
Entry::Named(self_named) => match other {
Entry::Anon(other_anon) => self_named.1.eq(&other_anon.0),
Entry::Named(other_named) => self_named.eq(other_named),
},
}
}
}
impl Context {
pub fn new() -> Context {
Context {
entries: Vec::new(),
}
}
pub fn has_entry(&self, uri: &str) -> bool {
self.entries.iter().any(|e| e.uri().eq(uri))
}
pub fn add_entry(&mut self, mut entry: Entry) {
// As per <https://www.w3.org/TR/activitystreams-core/#jsonld>:
//
// > Implementations producing ActivityStreams 2.0. documents SHOULD include a
// > @context property with a value that includes a reference to the normative
// > Activity Streams 2.0 JSON-LD @context definition using the URL
// > "https://www.w3.org/ns/activitystreams". Implementations MAY use the
// > alternative URL "http://www.w3.org/ns/activitystreams" instead.
// > This can be done using a string, object, or array.
//
// We're just gonna silently rewrite the http:// to https:// and call it a day.
if entry.uri().eq(uri::ACTIVITY_STREAMS_ALT) {
entry = match entry {
Entry::Anon(_) => Entry::anon(uri::ACTIVITY_STREAMS),
Entry::Named(named) => Entry::named(&named.0, uri::ACTIVITY_STREAMS),
};
}
if !self.has_entry(entry.uri()) {
self.entries.push(entry);
}
}
/// Merge with a contained object's context, consuming that child's context.
///
/// To be used as:
///
/// ```
/// if let Some(other_context) = other_object.context.take() {
/// context.merge(other_context);
/// }
/// ```
pub fn merge(&mut self, other: Context) {
for e in other.entries {
self.add_entry(e);
}
}
}
impl Default for Context {
fn default() -> Self {
let mut ctx = Context::new();
ctx.add_entry(Entry::anon(uri::ACTIVITY_STREAMS));
ctx
}
}
impl Serialize for Context {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
// FIXME: omg this is just horrible
if self.entries.len() == 1 {
serializer.serialize_str(self.entries[0].uri())
} else {
let mut anons = Vec::new();
let mut nameds = Vec::new();
for e in &self.entries {
match e {
Entry::Anon(anon) => anons.push(anon),
Entry::Named(named) => nameds.push(named),
}
}
let (anons, nameds) = (anons, nameds);
let seq_len = anons.len() + if nameds.len() > 0 { 1 } else { 0 };
let mut seq = serializer.serialize_seq(Some(seq_len))?;
for a in anons {
seq.serialize_element(&a.0)?;
}
if nameds.len() > 0 {
seq.serialize_element(&NamedEntriesWrapper(nameds))?;
}
seq.end()
}
}
}
impl<'de> de::Deserialize<'de> for Context {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(ContextVisitor)
}
}
struct ContextVisitor;
impl<'de> de::Visitor<'de> for ContextVisitor {
type Value = Context;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a valid JSON-LD context specification")
}
fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
where
E: de::Error,
{
Ok(Context {
entries: vec![Entry::anon(value)],
})
}
fn visit_none<E>(self) -> std::result::Result<Self::Value, E>
where
E: de::Error,
{
Ok(Context::new())
}
fn visit_seq<S>(self, mut seq: S) -> std::result::Result<Self::Value, S::Error>
where
S: SeqAccess<'de>,
{
let mut context = Context::new();
while let Some(wrapper) = seq.next_element::<StupidEntryWrapper>()? {
match wrapper {
StupidEntryWrapper::Single(entry) => context.add_entry(entry),
StupidEntryWrapper::Multi(entries) => {
for e in entries {
context.add_entry(e);
}
}
}
}
// As per <https://www.w3.org/TR/activitystreams-core/#jsonld>:
//
// "When a JSON-LD enabled Activity Streams 2.0 implementation encounters
// a JSON document identified using the "application/activity+json" MIME
// media type, and that document does not contain a @context property whose
// value includes a reference to the normative Activity Streams 2.0 JSON-LD
// @context definition, the implementation MUST assume that the normative
// @context definition still applies."
if !context.has_entry(uri::ACTIVITY_STREAMS) {
warn!(target: "ap", "@context does not have canonical ActivityStreams URI");
context.add_entry(Entry::anon(uri::ACTIVITY_STREAMS));
}
if context.entries.len() == 0 {
warn!(target: "ap", "Malformed @context: Arrays must always have elements, or be null");
context.add_entry(Entry::anon(uri::ACTIVITY_STREAMS));
}
Ok(context)
}
fn visit_map<A>(self, mut map: A) -> std::result::Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut entries = Vec::new();
while let Some((k, v)) = map.next_entry::<&str, &str>()? {
entries.push(Entry::named(k, v));
}
Ok(Context { entries })
}
}
/// Stupid wrapper because if @context is an array, its elements are strings and/or maps.
enum StupidEntryWrapper {
/// Single (anonymous) URI
Single(Entry),
/// Map of (named) URIs
Multi(Vec<Entry>),
}
impl<'de> Deserialize<'de> for StupidEntryWrapper {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(StupidEntryWrapperVisitor)
}
}
struct StupidEntryWrapperVisitor;
impl<'de> de::Visitor<'de> for StupidEntryWrapperVisitor {
type Value = StupidEntryWrapper;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a context URI or map of named URIs")
}
fn visit_str<E>(self, s: &str) -> std::result::Result<Self::Value, E>
where
E: de::Error,
{
Ok(StupidEntryWrapper::Single(Entry::anon(s)))
}
fn visit_map<A>(self, mut map: A) -> std::result::Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut entries = Vec::new();
while let Some((k, v)) = map.next_entry()? {
entries.push(Entry::Named(NamedEntry(k, v)));
}
Ok(StupidEntryWrapper::Multi(entries))
}
}
/// We can't use a HashMap to serialize named entries because that doesn't
/// produce deterministic results, so we have to use our own serializer
struct NamedEntriesWrapper<'a>(Vec<&'a NamedEntry>);
impl<'a> Serialize for NamedEntriesWrapper<'a> {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(self.0.len()))?;
for entry in &self.0 {
//let entry = *entry;
map.serialize_entry(&entry.0, &entry.1)?;
}
map.end()
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_test::{assert_tokens, Token};
#[test]
fn default() {
let ctx = Context::default();
assert_tokens(&ctx, &[Token::String(uri::ACTIVITY_STREAMS)]);
}
#[test]
fn multi_anon() {
let mut ctx = Context::default();
ctx.add_entry(Entry::anon(uri::NYANO));
assert_tokens(
&ctx,
&[
Token::Seq { len: Some(2) },
Token::String(uri::ACTIVITY_STREAMS),
Token::String(uri::NYANO),
Token::SeqEnd,
],
);
}
#[test]
fn multi_named() {
let mut ctx = Context::default();
ctx.add_entry(Entry::named("nyano", uri::NYANO));
ctx.add_entry(Entry::named("toot", uri::TOOT));
assert_tokens(
&ctx,
&[
Token::Seq { len: Some(2) },
Token::String(uri::ACTIVITY_STREAMS),
Token::Map { len: Some(2) },
Token::String("nyano"),
Token::String(uri::NYANO),
Token::String("toot"),
Token::String(uri::TOOT),
Token::MapEnd,
Token::SeqEnd,
],
)
}
}