Merge pull request #27 from Plume-org/activitystreams

Use the Activitystreams crate
This commit is contained in:
Baptiste Gelez
2018-05-18 23:14:55 +01:00
committed by GitHub
18 changed files with 551 additions and 179 deletions
+114 -68
View File
@@ -1,100 +1,146 @@
use activitystreams_traits::Actor;
use activitystreams_types::{
actor::Person,
activity::{Accept, Create, Follow, Like, Undo},
object::{Article, Note}
};
use diesel::PgConnection;
use failure::Error;
use serde_json;
use activity_pub::activity;
use activity_pub::actor::Actor;
use activity_pub::outbox::broadcast;
use activity_pub::{broadcast, Id, IntoId};
use activity_pub::actor::Actor as APActor;
use activity_pub::sign::*;
use models::blogs::Blog;
use models::comments::*;
use models::follows::*;
use models::likes::*;
use models::follows;
use models::likes;
use models::posts::*;
use models::users::User;
#[derive(Fail, Debug)]
enum InboxError {
#[fail(display = "The `type` property is required, but was not present")]
NoType,
#[fail(display = "Invalid activity type")]
InvalidType,
#[fail(display = "Couldn't undo activity")]
CantUndo
}
pub trait Inbox {
fn received(&self, conn: &PgConnection, act: serde_json::Value);
fn save(&self, conn: &PgConnection, act: serde_json::Value) {
match act["type"].as_str().unwrap() {
"Create" => {
match act["object"]["type"].as_str().unwrap() {
"Article" => {
Post::insert(conn, NewPost {
blog_id: 0, // TODO
slug: String::from(""), // TODO
title: String::from(""), // TODO
content: act["object"]["content"].as_str().unwrap().to_string(),
published: true,
license: String::from("CC-0"),
ap_url: act["object"]["url"].as_str().unwrap().to_string()
});
},
"Note" => {
let previous_comment = Comment::find_by_ap_url(conn, act["object"]["inReplyTo"].as_str().unwrap().to_string());
Comment::insert(conn, NewComment {
content: act["object"]["content"].as_str().unwrap().to_string(),
spoiler_text: act["object"]["summary"].as_str().unwrap_or("").to_string(),
ap_url: Some(act["object"]["id"].as_str().unwrap().to_string()),
in_response_to_id: previous_comment.clone().map(|c| c.id),
post_id: previous_comment
.map(|c| c.post_id)
.unwrap_or_else(|| Post::find_by_ap_url(conn, act["object"]["inReplyTo"].as_str().unwrap().to_string()).unwrap().id),
author_id: User::from_url(conn, act["actor"].as_str().unwrap().to_string()).unwrap().id,
sensitive: act["object"]["sensitive"].as_bool().unwrap_or(false)
});
}
x => println!("Received a new {}, but didn't saved it", x)
}
},
"Follow" => {
let follow_act = activity::Follow::deserialize(act.clone());
let from = User::from_url(conn, act["actor"].as_str().unwrap().to_string()).unwrap();
match User::from_url(conn, act["object"].as_str().unwrap().to_string()) {
Some(u) => self.accept_follow(conn, &from, &u, &follow_act, from.id, u.id),
None => {
let blog = Blog::from_url(conn, follow_act.get_target_id()).unwrap();
self.accept_follow(conn, &from, &blog, &follow_act, from.id, blog.id)
}
};
fn new_article(&self, conn: &PgConnection, article: Article) -> Result<(), Error> {
Post::insert(conn, NewPost {
blog_id: 0, // TODO
slug: String::from(""), // TODO
title: article.object_props.name_string().unwrap(),
content: article.object_props.content_string().unwrap(),
published: true,
license: String::from("CC-0"),
ap_url: article.object_props.url_string()?
});
Ok(())
}
fn new_comment(&self, conn: &PgConnection, note: Note, actor_id: String) -> Result<(), Error> {
let previous_url = note.object_props.in_reply_to.clone().unwrap().as_str().unwrap().to_string();
let previous_comment = Comment::find_by_ap_url(conn, previous_url.clone());
Comment::insert(conn, NewComment {
content: note.object_props.content_string().unwrap(),
spoiler_text: note.object_props.summary_string().unwrap(),
ap_url: note.object_props.id_string().ok(),
in_response_to_id: previous_comment.clone().map(|c| c.id),
post_id: previous_comment
.map(|c| c.post_id)
.unwrap_or_else(|| Post::find_by_ap_url(conn, previous_url).unwrap().id),
author_id: User::from_url(conn, actor_id).unwrap().id,
sensitive: false // "sensitive" is not a standard property, we need to think about how to support it with the activitystreams crate
});
Ok(())
}
fn follow(&self, conn: &PgConnection, follow: Follow) -> Result<(), Error> {
let from = User::from_url(conn, follow.actor.as_str().unwrap().to_string()).unwrap();
match User::from_url(conn, follow.object.as_str().unwrap().to_string()) {
Some(u) => self.accept_follow(conn, &from, &u, follow, from.id, u.id),
None => {
let blog = Blog::from_url(conn, follow.object.as_str().unwrap().to_string()).unwrap();
self.accept_follow(conn, &from, &blog, follow, from.id, blog.id)
}
"Like" => {
let liker = User::from_url(conn, act["actor"].as_str().unwrap().to_string());
let post = Post::find_by_ap_url(conn, act["object"].as_str().unwrap().to_string());
Like::insert(conn, NewLike {
post_id: post.unwrap().id,
user_id: liker.unwrap().id,
ap_url: act["id"].as_str().unwrap().to_string()
});
},
"Undo" => {
match act["object"]["type"].as_str().unwrap() {
"Like" => {
let like = Like::find_by_ap_url(conn, act["object"]["id"].as_str().unwrap().to_string()).unwrap();
like.delete(conn);
};
Ok(())
}
fn like(&self, conn: &PgConnection, like: Like) -> Result<(), Error> {
let liker = User::from_url(conn, like.actor.as_str().unwrap().to_string());
let post = Post::find_by_ap_url(conn, like.object.as_str().unwrap().to_string());
likes::Like::insert(conn, likes::NewLike {
post_id: post.unwrap().id,
user_id: liker.unwrap().id,
ap_url: like.object_props.id_string()?
});
Ok(())
}
fn unlike(&self, conn: &PgConnection, undo: Undo) -> Result<(), Error> {
let like = likes::Like::find_by_ap_url(conn, undo.object_object::<Like>()?.object_props.id_string()?).unwrap();
like.delete(conn);
Ok(())
}
fn save(&self, conn: &PgConnection, act: serde_json::Value) -> Result<(), Error> {
match act["type"].as_str() {
Some(t) => {
match t {
"Create" => {
let act: Create = serde_json::from_value(act.clone())?;
match act.object["type"].as_str().unwrap() {
"Article" => self.new_article(conn, act.object_object().unwrap()),
"Note" => self.new_comment(conn, act.object_object().unwrap(), act.actor_object::<Person>()?.object_props.id_string()?),
_ => Err(InboxError::InvalidType)?
}
},
"Follow" => self.follow(conn, serde_json::from_value(act.clone())?),
"Like" => self.like(conn, serde_json::from_value(act.clone())?),
"Undo" => {
let act: Undo = serde_json::from_value(act.clone())?;
match act.object["type"].as_str().unwrap() {
"Like" => self.unlike(conn, act),
_ => Err(InboxError::CantUndo)?
}
}
x => println!("Wanted to Undo a {}, but it is not supported yet", x)
_ => Err(InboxError::InvalidType)?
}
},
x => println!("Received unknow activity type: {}", x)
None => Err(InboxError::NoType)?
}
}
fn accept_follow<A: Actor + Signer, B: Actor + Clone, T: activity::Activity>(
fn accept_follow<A: Signer + IntoId + Clone, B: Clone + WithInbox + Actor>(
&self,
conn: &PgConnection,
from: &A,
target: &B,
follow: &T,
follow: Follow,
from_id: i32,
target_id: i32
) {
Follow::insert(conn, NewFollow {
follows::Follow::insert(conn, follows::NewFollow {
follower_id: from_id,
following_id: target_id
});
let accept = activity::Accept::new(target, follow, conn);
broadcast(conn, from, accept, vec![target.clone()]);
let mut accept = Accept::default();
accept.set_actor_link::<Id>(from.clone().into_id()).unwrap();
accept.set_object_object(follow).unwrap();
broadcast(conn, &*from, accept, vec![target.clone()]);
}
}
pub trait WithInbox {
fn get_inbox_url(&self) -> String;
fn get_shared_inbox_url(&self) -> Option<String>;
}
+71 -4
View File
@@ -1,13 +1,20 @@
use rocket::http::ContentType;
use rocket::response::Content;
use activitystreams_traits::{Activity, Actor, Object, Link};
use array_tool::vec::Uniq;
use diesel::PgConnection;
use reqwest::Client;
use rocket::http::{ContentType, Status};
use rocket::response::{Response, Responder, Content};
use rocket::request::Request;
use rocket_contrib::Json;
use serde_json;
pub mod activity;
use self::sign::Signable;
// pub mod activity;
pub mod actor;
pub mod inbox;
pub mod object;
pub mod outbox;
// pub mod outbox;
pub mod request;
pub mod sign;
pub mod webfinger;
@@ -54,3 +61,63 @@ pub fn context() -> serde_json::Value {
pub fn activity_pub(json: serde_json::Value) -> ActivityPub {
Content(ContentType::new("application", "activity+json"), Json(json))
}
pub struct ActivityStream<T> (T);
impl<T> ActivityStream<T> {
pub fn new(t: T) -> ActivityStream<T> {
ActivityStream(t)
}
}
impl<'r, O: Object> Responder<'r> for ActivityStream<O> {
fn respond_to(self, request: &Request) -> Result<Response<'r>, Status> {
serde_json::to_string(&self.0).respond_to(request)
}
}
pub fn broadcast<A: Activity + Clone, S: sign::Signer, T: inbox::WithInbox + Actor>(conn: &PgConnection, sender: &S, act: A, to: Vec<T>) {
let boxes = to.into_iter()
.map(|u| u.get_shared_inbox_url().unwrap_or(u.get_inbox_url()))
.collect::<Vec<String>>()
.unique();
for inbox in boxes {
// TODO: run it in Sidekiq or something like that
let mut act = serde_json::to_value(act.clone()).unwrap();
act["@context"] = context();
let signed = act.sign(sender, conn);
let res = Client::new()
.post(&inbox[..])
.headers(request::headers())
.header(request::signature(sender, request::headers(), conn))
.header(request::digest(signed.to_string()))
.body(signed.to_string())
.send();
match res {
Ok(mut r) => println!("Successfully sent activity to inbox ({})\n\n{:?}", inbox, r.text().unwrap()),
Err(e) => println!("Error while sending to inbox ({:?})", e)
}
}
}
#[derive(Clone, Serialize, Deserialize)]
pub struct Id {
#[serde(flatten)]
id: String
}
impl Id {
pub fn new<T: Into<String>>(id: T) -> Id {
Id {
id: id.into()
}
}
}
pub trait IntoId {
fn into_id(self) -> Id;
}
impl Link for Id {}
+1 -57
View File
@@ -1,3 +1,4 @@
use activitystreams_traits::{Activity, Object};
use array_tool::vec::Uniq;
use diesel::PgConnection;
use reqwest::Client;
@@ -8,64 +9,7 @@ use serde_json;
use std::sync::Arc;
use activity_pub::{activity_pub, ActivityPub, context};
use activity_pub::activity::Activity;
use activity_pub::actor::Actor;
use activity_pub::request;
use activity_pub::sign::*;
pub struct Outbox {
id: String,
items: Vec<Arc<Activity>>
}
impl Outbox {
pub fn new(id: String, items: Vec<Arc<Activity>>) -> Outbox {
Outbox {
id: id,
items: items
}
}
fn serialize(&self) -> ActivityPub {
let items = self.items.clone().into_iter().map(|i| i.serialize()).collect::<Vec<serde_json::Value>>();
activity_pub(json!({
"@context": context(),
"type": "OrderedCollection",
"id": self.id,
"totalItems": items.len(),
"orderedItems": items
}))
}
}
impl<'r> Responder<'r> for Outbox {
fn respond_to(self, request: &Request) -> Result<Response<'r>, Status> {
self.serialize().respond_to(request)
}
}
pub fn broadcast<A: Activity + Clone, S: Actor + Signer, T: Actor>(conn: &PgConnection, sender: &S, act: A, to: Vec<T>) {
let boxes = to.into_iter()
.map(|u| u.get_shared_inbox_url().unwrap_or(u.get_inbox_url()))
.collect::<Vec<String>>()
.unique();
for inbox in boxes {
// TODO: run it in Sidekiq or something like that
let mut act = act.serialize();
act["@context"] = context();
let signed = act.sign(sender, conn);
let res = Client::new()
.post(&inbox[..])
.headers(request::headers())
.header(request::signature(sender, request::headers(), conn))
.header(request::digest(signed.to_string()))
.body(signed.to_string())
.send();
match res {
Ok(mut r) => println!("Successfully sent activity to inbox ({})\n\n{:?}", inbox, r.text().unwrap()),
Err(e) => println!("Error while sending to inbox ({:?})", e)
}
}
}
+8
View File
@@ -1,10 +1,18 @@
#![feature(plugin, custom_derive, iterator_find_map)]
#![plugin(rocket_codegen)]
extern crate activitystreams;
#[macro_use]
extern crate activitystreams_derive;
extern crate activitystreams_traits;
extern crate activitystreams_types;
extern crate array_tool;
extern crate base64;
extern crate bcrypt;
extern crate chrono;
extern crate failure;
#[macro_use]
extern crate failure_derive;
extern crate heck;
extern crate hex;
#[macro_use]
+32 -9
View File
@@ -1,3 +1,5 @@
use activitystreams_traits::{Actor, Object};
use activitystreams_types::collection::OrderedCollection;
use reqwest::Client;
use reqwest::header::{Accept, qitem};
use reqwest::mime::Mime;
@@ -9,18 +11,17 @@ use openssl::hash::MessageDigest;
use openssl::pkey::{PKey, Private};
use openssl::rsa::Rsa;
use openssl::sign::Signer;
use std::sync::Arc;
use activity_pub::activity::Activity;
use activity_pub::actor::{Actor, ActorType};
use activity_pub::outbox::Outbox;
use activity_pub::{ActivityStream, Id, IntoId};
use activity_pub::actor::{Actor as APActor, ActorType};
use activity_pub::inbox::WithInbox;
use activity_pub::sign;
use activity_pub::webfinger::*;
use models::instance::Instance;
use schema::blogs;
#[derive(Queryable, Identifiable, Serialize, Clone)]
#[derive(Queryable, Identifiable, Serialize, Deserialize, Clone)]
pub struct Blog {
pub id: i32,
pub actor_id: String,
@@ -158,11 +159,14 @@ impl Blog {
}
}
pub fn outbox(&self, conn: &PgConnection) -> Outbox {
Outbox::new(self.compute_outbox(conn), self.get_activities(conn))
pub fn outbox(&self, conn: &PgConnection) -> ActivityStream<OrderedCollection> {
let mut coll = OrderedCollection::default();
coll.collection_props.items = serde_json::to_value(self.get_activities(conn)).unwrap();
coll.collection_props.set_total_items_u64(self.get_activities(conn).len() as u64).unwrap();
ActivityStream::new(coll)
}
fn get_activities(&self, _conn: &PgConnection) -> Vec<Arc<Activity>> {
fn get_activities(&self, _conn: &PgConnection) -> Vec<serde_json::Value> {
vec![]
}
@@ -171,7 +175,26 @@ impl Blog {
}
}
impl Actor for Blog {
impl IntoId for Blog {
fn into_id(self) -> Id {
Id::new(self.ap_url)
}
}
impl Object for Blog {}
impl Actor for Blog {}
impl WithInbox for Blog {
fn get_inbox_url(&self) -> String {
self.inbox_url.clone()
}
fn get_shared_inbox_url(&self) -> Option<String> {
None
}
}
impl APActor for Blog {
fn get_box_prefix() -> &'static str {
"~"
}
+36 -1
View File
@@ -1,8 +1,12 @@
use activitystreams_types::{
activity::Create,
object::{Note, properties::ObjectProperties}
};
use chrono;
use diesel::{self, PgConnection, RunQueryDsl, QueryDsl, ExpressionMethods};
use serde_json;
use activity_pub::{ap_url, PUBLIC_VISIBILTY};
use activity_pub::{ap_url, IntoId, PUBLIC_VISIBILTY};
use activity_pub::actor::Actor;
use activity_pub::object::Object;
use models::posts::Post;
@@ -71,6 +75,37 @@ impl Comment {
pub fn get_post(&self, conn: &PgConnection) -> Post {
Post::get(conn, self.post_id).unwrap()
}
pub fn into_activity(&self, conn: &PgConnection) -> Note {
let mut to = self.get_author(conn).get_followers(conn).into_iter().map(|f| f.ap_url).collect::<Vec<String>>();
to.append(&mut self.get_post(conn).get_receivers_urls(conn));
to.push(PUBLIC_VISIBILTY.to_string());
let mut comment = Note::default();
comment.object_props = ObjectProperties {
id: Some(serde_json::to_value(self.ap_url.clone()).unwrap()),
summary: Some(serde_json::to_value(self.spoiler_text.clone()).unwrap()),
content: Some(serde_json::to_value(self.content.clone()).unwrap()),
in_reply_to: Some(serde_json::to_value(self.in_response_to_id.map_or_else(|| self.get_post(conn).ap_url, |id| {
let comm = Comment::get(conn, id).unwrap();
comm.ap_url.clone().unwrap_or(comm.compute_id(conn))
})).unwrap()),
published: Some(serde_json::to_value(self.creation_date).unwrap()),
attributed_to: Some(serde_json::to_value(self.get_author(conn).compute_id(conn)).unwrap()),
to: Some(serde_json::to_value(to).unwrap()),
cc: Some(serde_json::to_value(Vec::<serde_json::Value>::new()).unwrap()),
..ObjectProperties::default()
};
comment
}
pub fn create_activity(&self, conn: &PgConnection) -> Create {
let mut act = Create::default();
act.set_actor_link(self.get_author(conn).into_id()).unwrap();
act.set_object_object(self.into_activity(conn)).unwrap();
act.object_props.set_id_string(format!("{}/activity", self.ap_url.clone().unwrap())).unwrap();
act
}
}
impl Object for Comment {
+1 -1
View File
@@ -86,7 +86,7 @@ impl Instance {
impl Inbox for Instance {
fn received(&self, conn: &PgConnection, act: serde_json::Value) {
self.save(conn, act.clone());
self.save(conn, act.clone()).unwrap();
// TODO: add to stream, or whatever needs to be done
}
+20 -1
View File
@@ -1,7 +1,9 @@
use activitystreams_types::activity;
use chrono;
use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
use serde_json;
use activity_pub::IntoId;
use activity_pub::actor::Actor;
use activity_pub::object::Object;
use models::posts::Post;
@@ -66,8 +68,25 @@ impl Like {
.into_iter().nth(0)
}
pub fn delete(&self, conn: &PgConnection) {
pub fn delete(&self, conn: &PgConnection) -> activity::Undo {
diesel::delete(self).execute(conn).unwrap();
let mut act = activity::Undo::default();
act.set_actor_link(User::get(conn, self.user_id).unwrap().into_id()).unwrap();
act.set_object_object(self.into_activity(conn)).unwrap();
act
}
pub fn into_activity(&self, conn: &PgConnection) -> activity::Like {
let mut act = activity::Like::default();
act.set_actor_link(User::get(conn, self.user_id).unwrap().into_id()).unwrap();
act.set_object_link(Post::get(conn, self.post_id).unwrap().into_id()).unwrap();
act.object_props.set_id_string(format!("{}/like/{}",
User::get(conn, self.user_id).unwrap().ap_url,
Post::get(conn, self.post_id).unwrap().ap_url
)).unwrap();
act
}
}
+39 -1
View File
@@ -1,10 +1,14 @@
use activitystreams_types::{
activity::Create,
object::{Article, properties::ObjectProperties}
};
use chrono::NaiveDateTime;
use diesel::{self, PgConnection, RunQueryDsl, QueryDsl, ExpressionMethods, BelongingToDsl};
use diesel::dsl::any;
use serde_json;
use BASE_URL;
use activity_pub::{PUBLIC_VISIBILTY, ap_url};
use activity_pub::{PUBLIC_VISIBILTY, ap_url, Id, IntoId};
use activity_pub::actor::Actor;
use activity_pub::object::Object;
use models::blogs::Blog;
@@ -137,6 +141,40 @@ impl Post {
});
to
}
pub fn into_activity(&self, conn: &PgConnection) -> Article {
let mut to = self.get_receivers_urls(conn);
to.push(PUBLIC_VISIBILTY.to_string());
let mut article = Article::default();
article.object_props = ObjectProperties {
name: Some(serde_json::to_value(self.title.clone()).unwrap()),
id: Some(serde_json::to_value(self.ap_url.clone()).unwrap()),
attributed_to: Some(serde_json::to_value(self.get_authors(conn).into_iter().map(|x| x.ap_url).collect::<Vec<String>>()).unwrap()),
content: Some(serde_json::to_value(self.content.clone()).unwrap()),
published: Some(serde_json::to_value(self.creation_date).unwrap()),
tag: Some(serde_json::to_value(Vec::<serde_json::Value>::new()).unwrap()),
url: Some(serde_json::to_value(self.compute_id(conn)).unwrap()),
to: Some(serde_json::to_value(to).unwrap()),
cc: Some(serde_json::to_value(Vec::<serde_json::Value>::new()).unwrap()),
..ObjectProperties::default()
};
article
}
pub fn create_activity(&self, conn: &PgConnection) -> Create {
let mut act = Create::default();
act.object_props.set_id_string(format!("{}/activity", self.ap_url)).unwrap();
act.set_actor_link(Id::new(self.get_authors(conn)[0].clone().ap_url)).unwrap();
act.set_object_object(self.into_activity(conn)).unwrap();
act
}
}
impl IntoId for Post {
fn into_id(self) -> Id {
Id::new(self.ap_url.clone())
}
}
impl Object for Post {
+79 -13
View File
@@ -1,3 +1,10 @@
use activitystreams_traits::{Actor, Object, Link};
use activitystreams_types::{
actor::Person,
collection::OrderedCollection,
object::properties::ObjectProperties,
CustomObject
};
use bcrypt;
use chrono::NaiveDateTime;
use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods, BelongingToDsl, PgConnection};
@@ -12,15 +19,12 @@ use reqwest::mime::Mime;
use rocket::request::{self, FromRequest, Request};
use rocket::outcome::IntoOutcome;
use serde_json;
use std::sync::Arc;
use url::Url;
use BASE_URL;
use activity_pub::ap_url;
use activity_pub::activity::{Create, Activity};
use activity_pub::actor::{ActorType, Actor};
use activity_pub::inbox::Inbox;
use activity_pub::outbox::Outbox;
use activity_pub::{ap_url, ActivityStream, Id, IntoId};
use activity_pub::actor::{ActorType, Actor as APActor};
use activity_pub::inbox::{Inbox, WithInbox};
use activity_pub::sign::{Signer, gen_keypair};
use activity_pub::webfinger::{Webfinger, resolve};
use db_conn::DbConn;
@@ -34,7 +38,7 @@ use schema::users;
pub const AUTH_COOKIE: &'static str = "user_id";
#[derive(Queryable, Identifiable, Serialize, Clone)]
#[derive(Queryable, Identifiable, Serialize, Deserialize, Clone)]
pub struct User {
pub id: i32,
pub username: String,
@@ -224,16 +228,23 @@ impl User {
}
}
pub fn outbox(&self, conn: &PgConnection) -> Outbox {
Outbox::new(self.compute_outbox(conn), self.get_activities(conn))
pub fn outbox(&self, conn: &PgConnection) -> ActivityStream<OrderedCollection> {
let acts = self.get_activities(conn);
let n_acts = acts.len();
let mut coll = OrderedCollection::default();
coll.collection_props.items = serde_json::to_value(acts).unwrap();
coll.collection_props.set_total_items_u64(n_acts as u64).unwrap();
ActivityStream::new(coll)
}
fn get_activities(&self, conn: &PgConnection) -> Vec<Arc<Activity>> {
fn get_activities(&self, conn: &PgConnection) -> Vec<serde_json::Value> {
use schema::posts;
use schema::post_authors;
let posts_by_self = PostAuthor::belonging_to(self).select(post_authors::post_id);
let posts = posts::table.filter(posts::id.eq(any(posts_by_self))).load::<Post>(conn).unwrap();
posts.into_iter().map(|p| Arc::new(Create::new(self, &p, conn)) as Arc<Activity>).collect::<Vec<Arc<Activity>>>()
posts.into_iter().map(|p| {
serde_json::to_value(p.create_activity(conn)).unwrap()
}).collect::<Vec<serde_json::Value>>()
}
pub fn get_fqn(&self, conn: &PgConnection) -> String {
@@ -270,6 +281,42 @@ impl User {
pub fn get_keypair(&self) -> PKey<Private> {
PKey::from_rsa(Rsa::private_key_from_pem(self.private_key.clone().unwrap().as_ref()).unwrap()).unwrap()
}
pub fn into_activity(&self, conn: &PgConnection) -> CustomObject<ApProps, Person> {
let mut actor = Person::default();
actor.object_props = ObjectProperties {
id: Some(serde_json::to_value(self.compute_id(conn)).unwrap()),
name: Some(serde_json::to_value(self.get_display_name()).unwrap()),
summary: Some(serde_json::to_value(self.get_summary()).unwrap()),
url: Some(serde_json::to_value(self.compute_id(conn)).unwrap()),
..ObjectProperties::default()
};
CustomObject::new(actor, ApProps {
inbox: Some(serde_json::to_value(self.compute_inbox(conn)).unwrap()),
outbox: Some(serde_json::to_value(self.compute_outbox(conn)).unwrap()),
preferred_username: Some(serde_json::to_value(self.get_actor_id()).unwrap()),
endpoints: Some(json!({
"sharedInbox": ap_url(format!("{}/inbox", BASE_URL.as_str()))
}))
})
}
}
#[derive(Serialize, Deserialize, Default, Properties)]
#[serde(rename_all = "camelCase")]
pub struct ApProps {
#[activitystreams(ab(Object, Link))]
inbox: Option<serde_json::Value>,
#[activitystreams(ab(Object, Link))]
outbox: Option<serde_json::Value>,
#[activitystreams(ab(Object, Link))]
preferred_username: Option<serde_json::Value>,
#[activitystreams(ab(Object))]
endpoints: Option<serde_json::Value>
}
impl<'a, 'r> FromRequest<'a, 'r> for User {
@@ -285,7 +332,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for User {
}
}
impl Actor for User {
impl APActor for User {
fn get_box_prefix() -> &'static str {
"@"
}
@@ -350,9 +397,28 @@ impl Actor for User {
}
}
impl IntoId for User {
fn into_id(self) -> Id {
Id::new(self.ap_url.clone())
}
}
impl Object for User {}
impl Actor for User {}
impl WithInbox for User {
fn get_inbox_url(&self) -> String {
self.inbox_url.clone()
}
fn get_shared_inbox_url(&self) -> Option<String> {
self.shared_inbox_url.clone()
}
}
impl Inbox for User {
fn received(&self, conn: &PgConnection, act: serde_json::Value) {
self.save(conn, act.clone());
self.save(conn, act.clone()).unwrap();
// Notifications
match act["type"].as_str().unwrap() {
+3 -3
View File
@@ -1,11 +1,11 @@
use activitystreams_types::collection::OrderedCollection;
use rocket::request::Form;
use rocket::response::Redirect;
use rocket_contrib::Template;
use serde_json;
use activity_pub::ActivityPub;
use activity_pub::{ActivityStream, ActivityPub};
use activity_pub::actor::Actor;
use activity_pub::outbox::Outbox;
use db_conn::DbConn;
use models::blog_authors::*;
use models::blogs::*;
@@ -78,7 +78,7 @@ fn create(conn: DbConn, data: Form<NewBlogForm>, user: User) -> Redirect {
}
#[get("/~/<name>/outbox")]
fn outbox(name: String, conn: DbConn) -> Outbox {
fn outbox(name: String, conn: DbConn) -> ActivityStream<OrderedCollection> {
let blog = Blog::find_local(&*conn, name).unwrap();
blog.outbox(&*conn)
}
+3 -4
View File
@@ -2,8 +2,7 @@ use rocket::request::Form;
use rocket::response::Redirect;
use rocket_contrib::Template;
use activity_pub::activity::Create;
use activity_pub::outbox::broadcast;
use activity_pub::broadcast;
use db_conn::DbConn;
use models::comments::*;
use models::posts::Post;
@@ -41,8 +40,8 @@ fn create(blog: String, slug: String, query: CommentQuery, data: Form<NewComment
sensitive: false,
spoiler_text: "".to_string()
});
let act = Create::new(&user, &comment, &*conn);
broadcast(&*conn, &user, act, user.get_followers(&*conn));
broadcast(&*conn, &user, comment.create_activity(&*conn), user.get_followers(&*conn));
Redirect::to(format!("/~/{}/{}/#comment-{}", blog, slug, comment.id).as_ref())
}
+5 -6
View File
@@ -1,7 +1,6 @@
use rocket::response::Redirect;
use activity_pub::activity::{Like, Undo};
use activity_pub::outbox::broadcast;
use activity_pub::broadcast;
use db_conn::DbConn;
use models::likes;
use models::posts::Post;
@@ -18,12 +17,12 @@ fn create(blog: String, slug: String, user: User, conn: DbConn) -> Redirect {
ap_url: "".to_string()
});
like.update_ap_url(&*conn);
let act = Like::new(&user, &post, &*conn);
broadcast(&*conn, &user, act, user.get_followers(&*conn));
broadcast(&*conn, &user, like.into_activity(&*conn), user.get_followers(&*conn));
} else {
let like = likes::Like::find_by_user_on_post(&*conn, &user, &post).unwrap();
like.delete(&*conn);
broadcast(&*conn, &user, Undo::new(&user, &like, &*conn), user.get_followers(&*conn));
let delete_act = like.delete(&*conn);
broadcast(&*conn, &user, delete_act, user.get_followers(&*conn));
}
Redirect::to(format!("/~/{}/{}/", blog, slug).as_ref())
+3 -5
View File
@@ -4,10 +4,8 @@ use rocket::response::Redirect;
use rocket_contrib::Template;
use serde_json;
use activity_pub::{context, activity_pub, ActivityPub};
use activity_pub::activity::Create;
use activity_pub::{broadcast, context, activity_pub, ActivityPub};
use activity_pub::object::Object;
use activity_pub::outbox::broadcast;
use db_conn::DbConn;
use models::blogs::*;
use models::comments::Comment;
@@ -39,7 +37,7 @@ fn details(blog: String, slug: String, conn: DbConn, user: Option<User>) -> Temp
#[get("/~/<_blog>/<slug>", rank = 3, format = "application/activity+json")]
fn activity_details(_blog: String, slug: String, conn: DbConn) -> ActivityPub {
// TODO: posts in different blogs may have the same slug
// FIXME: posts in different blogs may have the same slug
let post = Post::find_by_slug(&*conn, slug).unwrap();
let mut act = post.serialize(&*conn);
@@ -86,7 +84,7 @@ fn create(blog_name: String, data: Form<NewPostForm>, user: User, conn: DbConn)
author_id: user.id
});
let act = Create::new(&user, &post, &*conn);
let act = post.create_activity(&*conn);
broadcast(&*conn, &user, act, user.get_followers(&*conn));
Redirect::to(format!("/~/{}/{}", blog_name, slug).as_str())
+13 -6
View File
@@ -1,14 +1,17 @@
use activitystreams_types::{
activity::Follow,
collection::OrderedCollection
};
use rocket::request::Form;
use rocket::response::Redirect;
use rocket_contrib::Template;
use serde_json;
use activity_pub::{activity, activity_pub, ActivityPub, context};
use activity_pub::{activity_pub, ActivityPub, ActivityStream, context, broadcast, Id, IntoId};
use activity_pub::actor::Actor;
use activity_pub::inbox::Inbox;
use activity_pub::outbox::{broadcast, Outbox};
use db_conn::DbConn;
use models::follows::*;
use models::follows;
use models::instance::Instance;
use models::posts::Post;
use models::users::*;
@@ -49,11 +52,15 @@ fn details(name: String, conn: DbConn, account: Option<User>) -> Template {
#[get("/@/<name>/follow")]
fn follow(name: String, conn: DbConn, user: User) -> Redirect {
let target = User::find_by_fqn(&*conn, name.clone()).unwrap();
Follow::insert(&*conn, NewFollow {
follows::Follow::insert(&*conn, follows::NewFollow {
follower_id: user.id,
following_id: target.id
});
broadcast(&*conn, &user, activity::Follow::new(&user, &target, &*conn), vec![target]);
let mut act = Follow::default();
act.set_actor_link::<Id>(user.clone().into_id()).unwrap();
act.set_object_object(user.into_activity(&*conn)).unwrap();
act.object_props.set_id_string(format!("{}/follow/{}", user.ap_url, target.ap_url)).unwrap();
broadcast(&*conn, &user, act, vec![target]);
Redirect::to(format!("/@/{}", name).as_ref())
}
@@ -152,7 +159,7 @@ fn create(conn: DbConn, data: Form<NewUserForm>) -> Result<Redirect, String> {
}
#[get("/@/<name>/outbox")]
fn outbox(name: String, conn: DbConn) -> Outbox {
fn outbox(name: String, conn: DbConn) -> ActivityStream<OrderedCollection> {
let user = User::find_local(&*conn, name).unwrap();
user.outbox(&*conn)
}