1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*
 * This file is part of ActivityStreams.
 *
 * Copyright © 2020 Riley Trautman
 *
 * ActivityStreams is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ActivityStreams is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ActivityStreams.  If not, see <http://www.gnu.org/licenses/>.
 */

//! Defining extensibility in the ActivityStreams spec
//!
//! In ActivityStreams, there are many times you may want to use an extension. For example, to
//! interact with Mastodon, you need to at least understand the `publicKey` field on their actor
//! type. If not, you won't be able to use HTTP Signatures, and will have your messages rejected.
//!
//! But this library doesn't provide any of the security extensions to ActivityStreams. In order to
//! support it, you could implment your own extensions to this library. Let's cover a basic
//! example.
//!
//! ```rust
//! // For this example, we'll use the Extensible trait, the Extension trait, the Actor trait, and
//! // the Person type
//! use activitystreams::{
//!     actor::{Actor, Person},
//!     ext::{Extensible, Extension},
//! };
//!
//! /// Let's define the PublicKey type. The three fields in this PublicKey struct are how Mastodon
//! /// represents Public Keys on actors. We'll need to derive Serialize and Deserialize for these
//! /// in order for them to be useful.
//! #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
//! #[serde(rename_all = "camelCase")]
//! pub struct PublicKey {
//!     /// The ID of the key.
//!     ///
//!     /// In mastodon, this is the same as the actor's URL with a #main-key on
//!     /// the end.
//!     pub id: String,
//!
//!     /// The ID of the actor who owns this key.
//!     pub owner: String,
//!
//!     /// This is a PEM file with PKCS#8 encoded data.
//!     pub public_key_pem: String,
//! }
//!
//! /// Now, we'll need more than just a PublicKey struct to make this work. We'll need to define a
//! /// second struct that declares the correct key to house this information inside of
//! ///
//! /// The information is represented as the following json:
//! /// ```json
//! /// {
//! ///     "publicKey": {
//! ///         "id": "key id",
//! ///         "owner": "actor id",
//! ///         "publicKeyPem": "pem string"
//! ///     }
//! /// }
//! /// ```
//! ///
//! /// This means we'll need to define the 'publicKey' key
//! #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
//! #[serde(rename_all = "camelCase")]
//! pub struct PublicKeyExtension {
//!     /// The public key's information
//!     pub public_key: PublicKey
//! }
//!
//! impl PublicKey {
//!     /// Let's add a convenience method to turn a PublicKey into a PublicKeyExtension
//!     pub fn to_ext(self) -> PublicKeyExtension {
//!         PublicKeyExtension { public_key: self }
//!     }
//! }
//!
//! // And finally, we'll implement the Extension trait for PublicKeyExtension
//! //
//! // We'll bound this extension by the Actor trait, since we don't care about non-actors having
//! // keys. This means that you can put a key on a `Person`, but not on a `Video`.
//! impl<T> Extension<T> for PublicKeyExtension where T: Actor {}
//!
//! // Now that these types are defined, we can put them to use!
//! let person = Person::new();
//!
//! // let's just create a dummy key for this example
//! let public_key = PublicKey {
//!     id: "My ID".to_owned(),
//!     owner: "Owner ID".to_owned(),
//!     public_key_pem: "My Public Key".to_owned(),
//! };
//!
//! // We're doing it! The person is being extended with a public key
//! //
//! // Note that calling `extend` on person here is possible because the Extensible trait is in
//! // scope
//! let person_with_key = person.extend(public_key.to_ext());
//! ```

use crate::{
    activity::{Activity, ActivityBox, IntransitiveActivity, IntransitiveActivityBox},
    actor::{Actor, ActorBox},
    collection::{Collection, CollectionBox, CollectionPage, CollectionPageBox},
    link::{Link, LinkBox},
    object::{Object, ObjectBox},
    Base, BaseBox,
};
use std::{convert::TryFrom, fmt::Debug};

/// Defines an extension to an activitystreams object or link
///
/// This type provides two fields, the first field, `base`, should always the be base
/// ActivityStreams type. As long as `base` implements an ActivityStreams trait, Ext will also.
///
/// For example, the type `Ext<Video, HashMap<String, String>>` will implement the `Object` trait,
/// because `Video` implements that trait.
///
/// Additionally, AsRef and AsMut have been implemented for Ext. If type type
/// `Ext<Ext<Follow, SomeTime>, AnotherType>` exists, that will implement
/// `AsRef<ActivityProperties>` just like the innermost `Follow`.
///
/// Usage:
/// ```rust
/// use activitystreams::object::Video;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let mut video = Video::full();
///
///     // AsMut works even though this is an Ext<Video, ApObjectProperties>
///     video
///         .as_mut()
///         .set_id("https://example.com")?;
///
///     // set information on the extension
///     video
///         .extension
///         .set_source_xsd_any_uri("https://example.com")?;
///
///     Ok(())
/// }
/// ```
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "derive", derive(serde::Deserialize, serde::Serialize))]
pub struct Ext<T, U> {
    /// The ActivityStreams base type, or another extension containing one
    #[cfg_attr(feature = "derive", serde(flatten))]
    pub base: T,

    /// The extension being applied to the type
    #[cfg_attr(feature = "derive", serde(flatten))]
    pub extension: U,
}

/// A trait implemented by extensions to the ActivityStreams specification
///
/// This is implemented for a couple types by default, such as
/// ApObjectProperties, and ApActorProperties.
///
/// Extensions are not intended to be used as trait objects
pub trait Extension<T>
where
    T: Base,
{
    /// A default implementation that simply returns the Ext type with Self and the base type
    /// inside of it.
    fn extends(self, base: T) -> Ext<T, Self>
    where
        Self: Sized,
    {
        Ext {
            base,
            extension: self,
        }
    }
}

/// A trait implemented (automatically) by objects and links in the ActivityStreams specification
///
/// This is used to easily extend objects.
///
/// ```rust
/// # use activitystreams::object::{Video, properties::ApObjectProperties};
/// use activitystreams::ext::Extensible;
/// let vid = Video::new();
/// let ap_props = ApObjectProperties::default();
///
/// let extended_vid = vid.extend(ap_props);
/// ```
pub trait Extensible<U> {
    fn extend(self, extension: U) -> Ext<Self, U>
    where
        Self: Sized;
}

impl<T, U, V> AsRef<V> for Ext<T, U>
where
    T: Base + AsRef<V>,
    U: Extension<T> + Debug,
{
    fn as_ref(&self) -> &V {
        self.base.as_ref()
    }
}

impl<T, U, V> AsMut<V> for Ext<T, U>
where
    T: Base + AsMut<V>,
    U: Extension<T> + Debug,
{
    fn as_mut(&mut self) -> &mut V {
        self.base.as_mut()
    }
}

impl<T, U> TryFrom<Ext<T, U>> for BaseBox
where
    T: Base + serde::ser::Serialize,
    U: Extension<T> + serde::ser::Serialize + Debug,
{
    type Error = std::io::Error;

    fn try_from(e: Ext<T, U>) -> Result<Self, Self::Error> {
        BaseBox::from_concrete(e)
    }
}

impl<T, U> TryFrom<Ext<T, U>> for ObjectBox
where
    T: Object + serde::ser::Serialize,
    U: Extension<T> + serde::ser::Serialize + Debug,
{
    type Error = std::io::Error;

    fn try_from(e: Ext<T, U>) -> Result<Self, Self::Error> {
        ObjectBox::from_concrete(e)
    }
}

impl<T, U> TryFrom<Ext<T, U>> for LinkBox
where
    T: Link + serde::ser::Serialize,
    U: Extension<T> + serde::ser::Serialize + Debug,
{
    type Error = std::io::Error;

    fn try_from(e: Ext<T, U>) -> Result<Self, Self::Error> {
        LinkBox::from_concrete(e)
    }
}

impl<T, U> TryFrom<Ext<T, U>> for CollectionBox
where
    T: Collection + serde::ser::Serialize,
    U: Extension<T> + serde::ser::Serialize + Debug,
{
    type Error = std::io::Error;

    fn try_from(e: Ext<T, U>) -> Result<Self, Self::Error> {
        CollectionBox::from_concrete(e)
    }
}

impl<T, U> TryFrom<Ext<T, U>> for CollectionPageBox
where
    T: CollectionPage + serde::ser::Serialize,
    U: Extension<T> + serde::ser::Serialize + Debug,
{
    type Error = std::io::Error;

    fn try_from(e: Ext<T, U>) -> Result<Self, Self::Error> {
        CollectionPageBox::from_concrete(e)
    }
}

impl<T, U> TryFrom<Ext<T, U>> for ActivityBox
where
    T: Activity + serde::ser::Serialize,
    U: Extension<T> + serde::ser::Serialize + Debug,
{
    type Error = std::io::Error;

    fn try_from(e: Ext<T, U>) -> Result<Self, Self::Error> {
        ActivityBox::from_concrete(e)
    }
}

impl<T, U> TryFrom<Ext<T, U>> for IntransitiveActivityBox
where
    T: IntransitiveActivity + serde::ser::Serialize,
    U: Extension<T> + serde::ser::Serialize + Debug,
{
    type Error = std::io::Error;

    fn try_from(e: Ext<T, U>) -> Result<Self, Self::Error> {
        IntransitiveActivityBox::from_concrete(e)
    }
}

impl<T, U> TryFrom<Ext<T, U>> for ActorBox
where
    T: Actor + serde::ser::Serialize,
    U: Extension<T> + serde::ser::Serialize + Debug,
{
    type Error = std::io::Error;

    fn try_from(e: Ext<T, U>) -> Result<Self, Self::Error> {
        ActorBox::from_concrete(e)
    }
}

impl<T, U> Extensible<U> for T
where
    T: crate::Base,
    U: Extension<T>,
{
    fn extend(self, item: U) -> Ext<Self, U> {
        item.extends(self)
    }
}

impl<T, U> Base for Ext<T, U>
where
    T: Base,
    U: Debug,
{
}

impl<T, U> Object for Ext<T, U>
where
    T: Object,
    U: Debug,
{
}

impl<T, U> Link for Ext<T, U>
where
    T: Link,
    U: Debug,
{
}

impl<T, U> Actor for Ext<T, U>
where
    T: Actor,
    U: Debug,
{
}

impl<T, U> Collection for Ext<T, U>
where
    T: Collection,
    U: Debug,
{
}

impl<T, U> CollectionPage for Ext<T, U>
where
    T: CollectionPage,
    U: Debug,
{
}

impl<T, U> Activity for Ext<T, U>
where
    T: Activity,
    U: Debug,
{
}

impl<T, U> IntransitiveActivity for Ext<T, U>
where
    T: IntransitiveActivity,
    U: Debug,
{
}